AGENT SKILL

twirp-rpc-patterns

暂无简介

License 许可
Apache-2.0
最近更新
2026-11-11
Stars
★ 13
Forks
1

03 SKILL.md 正文

/twirp-rpc-patterns

When to Use

  • gRPC is overkill: no HTTP/2 infrastructure, no streaming required
  • Simple request-response RPC with Protobuf encoding over plain HTTP
  • Behind standard reverse proxies (nginx, Caddy) without grpc_pass config
  • JSON fallback: same service works with both Protobuf and JSON clients

Do NOT use for

  • Bidirectional streaming (use [[grpc-streaming-rpc]])
  • Browser clients without CORS concerns (Twirp JSON works, but REST is simpler)

Twirp URL convention

POST /twirp/<package>.<Service>/<Method>
Content-Type: application/protobuf   (binary)
           or application/json       (human-readable fallback)

Node.js Twirp server (twirp-ts)

import { createServer }   from 'http'
import { TwirpServer, chainHooks } from 'twirp-ts'
import { AgentBus }       from './generated/agent_bus_twirp'  // generated from proto

const server = new TwirpServer({
  service: AgentBus,
  implementation: {
    async DispatchTask(ctx, req) {
      const taskId = `task-${Date.now()}`
      return { taskId, accepted: true }
    },

    async GetTaskStatus(ctx, req) {
      const status = await taskRegistry.get(req.taskId)
      if (!status) throw new TwirpError(TwirpErrorCode.NotFound, `task ${req.taskId} not found`)
      return { taskId: req.taskId, status }
    },
  },
  hooks: chainHooks(
    {
      requestReceived: async (ctx) => {
        ctx.agentId = ctx.req.headers['x-agent-id'] as string
        if (!ctx.agentId) throw new TwirpError(TwirpErrorCode.Unauthenticated, 'missing x-agent-id')
      },
    }
  ),
})

createServer((req, res) => server.httpHandler(req, res)).listen(8080)

Twirp client (JSON transport)

import fetch from 'node-fetch'

async function twirpCall<Req, Res>(
  baseUrl:  string,
  service:  string,
  method:   string,
  body:     Req,
  agentId:  string
): Promise<Res> {
  const url = `${baseUrl}/twirp/${service}/${method}`
  const res = await fetch(url, {
    method:  'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Agent-Id':   agentId,
    },
    body: JSON.stringify(body),
  })

  if (!res.ok) {
    const err = await res.json()
    throw new Error(`[twirp] ${err.code}: ${err.msg}`)
  }
  return res.json()
}

const ack = await twirpCall(
  'http://localhost:8080',
  'yamtam.AgentBus',
  'DispatchTask',
  { tool: 'bash', paramsJson: '{"cmd":"ls"}' },
  'did:yamtam:0xabc123'
)

Twirp error codes

import { TwirpError, TwirpErrorCode } from 'twirp-ts'

// Standard error codes (map to HTTP status):
// Canceled           → 408
// Unknown            → 500
// InvalidArgument    → 400
// NotFound           → 404
// AlreadyExists      → 409
// PermissionDenied   → 403
// Unauthenticated    → 401
// ResourceExhausted  → 429  ← rate limit
// Internal           → 500

throw new TwirpError(TwirpErrorCode.ResourceExhausted, 'rate limit exceeded')

Anti-Fake-Pass Checklist

❌ Missing Content-Type: application/json → Twirp returns 415 Unsupported Media Type
❌ URL path case mismatch — Twirp routing is case-sensitive: /DispatchTask ≠ /dispatchtask
❌ Throwing plain Error in handler → becomes TwirpErrorCode.Internal with no details
❌ No authentication hook → any caller can invoke any method
❌ Protobuf and JSON clients mixed without content-type check → binary parsed as JSON
❌ TwirpErrorCode.ResourceExhausted not mapped to retry logic on client → no backoff

04 同仓库更多 Skills

Horonomos-laps
Horonomos-laps/Yana-AI

openai--sentry--sentry

Use when the user asks to inspect Sentry issues or events, summarize recent production errors, or pull basic Sentry health data via the Sentry API; perform read-only queries with the bundled script and require `SENTRY_AUTH_TOKEN`.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

ito-basket-compare

Compare Itô prediction-market baskets against a user's knowledge base, portfolio notes, financial context, watchlist, or research thesis. Use for read-only basket comparison and gap analysis without investment advice or live trading.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

implementing-network-traffic-baselining

Build network traffic baselines from NetFlow/IPFIX data using Python pandas for statistical analysis, z-score anomaly detection, and hourly/daily traffic pattern profiling

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

detecting-evasion-techniques-in-endpoint-logs

Detects defense evasion techniques used by adversaries in endpoint logs including log tampering, timestomping, process injection, and security tool disabling. Use when investigating suspicious endpoint behavior, building detection rules for evasion tactics, or conducting threat hunting for stealthy adversary activity. Activates for requests involving evasion detection, defense evasion analysis, log tampering detection, or MITRE ATT&CK TA0005.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

implementing-microsegmentation-with-guardicore

Implementing microsegmentation using Akamai Guardicore Segmentation to map application dependencies, create granular network policies, visualize east-west traffic flows, and enforce least-privilege communication between workloads across data centers and cloud.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

ramdisk-tmpfs-patterns

暂无简介

★ 13