|
| 1 | +/** |
| 2 | + * THE ONCE-PER-CALL RULE for the tools that start or send something |
| 3 | + * (decision page workflows-future: "A delegate, handoff or page call carries |
| 4 | + * a key, so a turn retried after a cut finds the item it already started"). |
| 5 | + * A `delegate`, `handoff` or `artifact_create` call that carries its |
| 6 | + * harness's key for the call runs once per calling session and key: a call |
| 7 | + * that comes again under the same key while the first runs is answered that |
| 8 | + * call's answer as it comes, and once answered, the same answer, with no |
| 9 | + * second item, message or page made. The workflow engine replayed a step the |
| 10 | + * same way (20d367743); here it is the three calls. |
| 11 | + * |
| 12 | + * The key is what each harness sends again when it retries a call: |
| 13 | + * - Claude Code names every MCP `tools/call` by its tool_use id in `_meta` |
| 14 | + * (`"claudecode/toolUseId"`), and after a connection lost mid-call takes |
| 15 | + * it again and retries the call once, under the same tool use |
| 16 | + * (`callMCPToolWithUrlElicitationRetry`, src/services/mcp/client.ts, read |
| 17 | + * at https://cc.windliang.wang/10-mcp-and-dynamic-tool-discovery.html: |
| 18 | + * "连接在执行期间失效时 … 会重新取得连接并最多重试一次"). |
| 19 | + * - OpenCode names no call: its `_meta` carries the session alone |
| 20 | + * (`"ai.opencode/sessionID"`, https://opencode.ai/v2/docs/mcp-servers), |
| 21 | + * and its retry after an expired session replays the same `tools/call` |
| 22 | + * once (anomalyco/opencode#25137, fixed by #32088: "rebuilds the |
| 23 | + * transport and replays the call once"). What it sends again is that |
| 24 | + * session and the same arguments, so they are its key. |
| 25 | + * - pi names each call by its `toolCallId`, which CawCo's pi runtime sends |
| 26 | + * with the call to the hub's tool door (agent delegation.ts |
| 27 | + * `callDelegationTool`). |
| 28 | + * |
| 29 | + * Kept with the relayed calls' keys (`tool_call_keys`, tool-call-keys.ts), |
| 30 | + * which prunes them {@link TOOL_CALL_KEY_KEPT_MS} after their answer and |
| 31 | + * marks those a stopped hub was running as interrupted. |
| 32 | + */ |
| 33 | +import { createHash } from "node:crypto"; |
| 34 | +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; |
| 35 | +import type { ToolCallKeysDb } from "./db/tool-call-keys"; |
| 36 | +import { INTERRUPTED_CALL } from "./tool-call-keys"; |
| 37 | + |
| 38 | +/** The tools a key makes run once: each starts work or sends words that a second run would double. */ |
| 39 | +export const KEYED_TOOLS: ReadonlySet<string> = new Set([ |
| 40 | + "delegate", |
| 41 | + "handoff", |
| 42 | + "artifact_create", |
| 43 | +]); |
| 44 | + |
| 45 | +/** Where Claude Code names a call's tool use in `tools/call`'s `_meta`. */ |
| 46 | +export const CLAUDE_CALL_META = "claudecode/toolUseId"; |
| 47 | +/** Where OpenCode names the calling session in `tools/call`'s `_meta`. */ |
| 48 | +export const OPENCODE_SESSION_META = "ai.opencode/sessionID"; |
| 49 | + |
| 50 | +/** |
| 51 | + * The key a `tools/call`'s `_meta` gives the call: Claude Code's tool use, |
| 52 | + * else OpenCode's session with the call's own name and arguments. None |
| 53 | + * when the harness named neither. |
| 54 | + */ |
| 55 | +export const mcpCallKey = ( |
| 56 | + meta: Record<string, unknown> | undefined, |
| 57 | + name: string, |
| 58 | + args: Record<string, unknown> |
| 59 | +): string | undefined => { |
| 60 | + const toolUse = meta?.[CLAUDE_CALL_META]; |
| 61 | + if (typeof toolUse === "string" && toolUse) { |
| 62 | + return `claude:${toolUse}`; |
| 63 | + } |
| 64 | + const session = meta?.[OPENCODE_SESSION_META]; |
| 65 | + if (typeof session === "string" && session) { |
| 66 | + const asked = createHash("sha256") |
| 67 | + .update(JSON.stringify([name, args])) |
| 68 | + .digest("hex"); |
| 69 | + return `opencode:${session}:${asked}`; |
| 70 | + } |
| 71 | + return undefined; |
| 72 | +}; |
| 73 | + |
| 74 | +const encoder = new TextEncoder(); |
| 75 | +const decoder = new TextDecoder(); |
| 76 | + |
| 77 | +export const createCallKeys = ({ db }: { db: ToolCallKeysDb }) => { |
| 78 | + /** Each keyed call this process runs now, by its stored id. */ |
| 79 | + const live = new Map<string, Promise<CallToolResult>>(); |
| 80 | + |
| 81 | + return { |
| 82 | + /** |
| 83 | + * `run`'s answer, run once per `instanceId`, `name` and `key`; a tool |
| 84 | + * outside {@link KEYED_TOOLS}, or a call with no key, is simply run. |
| 85 | + */ |
| 86 | + async once( |
| 87 | + instanceId: string | null, |
| 88 | + name: string, |
| 89 | + key: string | undefined, |
| 90 | + run: () => Promise<CallToolResult> |
| 91 | + ): Promise<CallToolResult> { |
| 92 | + if (!(instanceId && key && KEYED_TOOLS.has(name))) { |
| 93 | + return await run(); |
| 94 | + } |
| 95 | + const id = createHash("sha256") |
| 96 | + .update(["session-call", instanceId, name, key].join("\n")) |
| 97 | + .digest("hex"); |
| 98 | + const running = live.get(id); |
| 99 | + if (running !== undefined) { |
| 100 | + console.info( |
| 101 | + `[call-keys] ${name} from ${instanceId} sent again while it runs: answered as it answers` |
| 102 | + ); |
| 103 | + return await running; |
| 104 | + } |
| 105 | + if (!db.take(id, Date.now())) { |
| 106 | + const row = db.get(id); |
| 107 | + if (row?.state === "answered" && row.body) { |
| 108 | + console.info( |
| 109 | + `[call-keys] ${name} from ${instanceId} sent again once answered: its first answer, not run again` |
| 110 | + ); |
| 111 | + return JSON.parse(decoder.decode(row.body)) as CallToolResult; |
| 112 | + } |
| 113 | + return { |
| 114 | + isError: true, |
| 115 | + content: [{ type: "text", text: INTERRUPTED_CALL }], |
| 116 | + }; |
| 117 | + } |
| 118 | + const answered = run().catch((error: unknown): CallToolResult => ({ |
| 119 | + isError: true, |
| 120 | + content: [ |
| 121 | + { |
| 122 | + type: "text", |
| 123 | + text: error instanceof Error ? error.message : String(error), |
| 124 | + }, |
| 125 | + ], |
| 126 | + })); |
| 127 | + live.set(id, answered); |
| 128 | + try { |
| 129 | + const result = await answered; |
| 130 | + db.answer( |
| 131 | + id, |
| 132 | + { |
| 133 | + status: 200, |
| 134 | + headers: [], |
| 135 | + body: encoder.encode(JSON.stringify(result)), |
| 136 | + }, |
| 137 | + Date.now() |
| 138 | + ); |
| 139 | + return result; |
| 140 | + } finally { |
| 141 | + live.delete(id); |
| 142 | + } |
| 143 | + }, |
| 144 | + }; |
| 145 | +}; |
| 146 | + |
| 147 | +export type CallKeys = ReturnType<typeof createCallKeys>; |
0 commit comments