Skip to content

Commit d2beb39

Browse files
Bewinxedclaude
andcommitted
A delegate, handoff or page call runs once per its harness's key: a retried call finds what it already started
delegate, handoff and artifact_create carry the calling harness's key for the call (call-keys.ts), and run once per calling session and key: a call sent again while the first runs is answered that call's answer, and once answered, the same answer, with no second item, message or page. The keys are what each harness sends again on a retry: - Claude Code: `_meta["claudecode/toolUseId"]`, which its MCP client resends when it retakes a connection lost mid-call and retries the call once. - OpenCode: no call id; `_meta["ai.opencode/sessionID"]` and the same arguments, which its replay after an expired session sends again (anomalyco/opencode#25137, #32088). - pi: its toolCallId, sent by CawCo's pi runtime with the call to the tool door as `callKey`. Kept with the relayed calls' keys (tool_call_keys), pruned ten minutes after their answer; one a stopped hub was running answers that it was not run again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4cda7db commit d2beb39

6 files changed

Lines changed: 184 additions & 10 deletions

File tree

‎packages/agent/src/delegation.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,9 @@ export async function callDelegationTool(
8383
instanceId: string,
8484
name: string,
8585
args: unknown,
86-
credential?: string
86+
credential?: string,
87+
/** The harness's own id for this call (pi's `toolCallId`): the hub runs a keyed tool once per id (hub call-keys.ts). */
88+
callId?: string
8789
) {
8890
const url = harnessMcpUrl(
8991
`/api/delegation/call/${encodeURIComponent(instanceId)}`
@@ -94,7 +96,11 @@ export async function callDelegationTool(
9496
"Content-Type": "application/json",
9597
...(credential ? { Authorization: `Bearer ${credential}` } : {}),
9698
},
97-
body: JSON.stringify({ name, arguments: args }),
99+
body: JSON.stringify({
100+
name,
101+
arguments: args,
102+
...(callId ? { callKey: `pi:${callId}` } : {}),
103+
}),
98104
};
99105
const take = async (response: Response) => {
100106
if (!response.ok) {

‎packages/agent/src/harnesses/pi-runtime.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -331,8 +331,10 @@ const piHandoffTools = async (
331331
label: tool.name,
332332
description: tool.description,
333333
parameters: tool.inputSchema as never,
334-
execute: async (_id, params) =>
335-
callDelegationTool(instanceId, tool.name, params, credential.value),
334+
// pi's own id for the call: the key the hub runs a delegate, a
335+
// handoff or a page under once (hub call-keys.ts).
336+
execute: async (id, params) =>
337+
callDelegationTool(instanceId, tool.name, params, credential.value, id),
336338
})
337339
);
338340

‎packages/hub/src/call-keys.ts‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
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>;

‎packages/hub/src/delegation-mcp.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
import { ACTION_TOOLS, type Actions } from "./actions";
1919
import { adminTools, answeredWithoutAsking, isAdminWrite } from "./admin-tools";
2020
import { BROWSER_TOOLS, type BrowserAsks } from "./browser-tools";
21+
import { type CallKeys, CLAUDE_CALL_META, mcpCallKey } from "./call-keys";
2122
import type { Caw } from "./caw";
2223
import type { Connections } from "./connections";
2324
import type {
@@ -113,7 +114,7 @@ const CREDENTIAL_TOKEN =
113114
* (`"_meta": {"claudecode/toolUseId": "toolu_…", "progressToken": 14}`,
114115
* github.com/modelcontextprotocol/python-sdk/issues/2579).
115116
*/
116-
const TOOL_USE_META = "claudecode/toolUseId";
117+
const TOOL_USE_META = CLAUDE_CALL_META;
117118

118119
/** What an admin write's progress heartbeat says while the person decides. */
119120
const ASKING = "Waiting for the person to approve this fleet-settings change";
@@ -318,6 +319,8 @@ export function createDelegationMcp(options: {
318319
input: Record<string, unknown>,
319320
toolUseId?: string
320321
) => Promise<void>;
322+
/** The once-per-key rule of the calls that start or send (call-keys.ts). */
323+
callKeys: Pick<CallKeys, "once">;
321324
/** `send_to_user`'s push to the person's paired devices (push.ts `userMessage`); its transcript row is the call itself. */
322325
sendToUser: (actor: InstanceRow, message: string) => void;
323326
/** Why `actor` may not show the person one of `paths` (shown-files.ts `shownRefusal`). */
@@ -693,7 +696,9 @@ export function createDelegationMcp(options: {
693696
name: string,
694697
args: Record<string, unknown>,
695698
authorization?: string,
696-
toolUseId?: string
699+
toolUseId?: string,
700+
/** The harness's key for the call (call-keys.ts): a delegate, handoff or page call runs once per key. */
701+
callKey?: string
697702
): Promise<CallToolResult> => {
698703
const admitted = admitToolCall(name, binding ?? "unbound");
699704
if ("refused" in admitted) {
@@ -703,7 +708,9 @@ export function createDelegationMcp(options: {
703708
};
704709
}
705710
try {
706-
return await answer(binding, name, args, authorization, toolUseId);
711+
return await options.callKeys.once(binding, name, callKey, () =>
712+
answer(binding, name, args, authorization, toolUseId)
713+
);
707714
} finally {
708715
admitted.release();
709716
}
@@ -1104,15 +1111,17 @@ export function createDelegationMcp(options: {
11041111
// The tool call this request is, as Claude Code names it in `_meta`
11051112
// (`claudecode/toolUseId`): an ask it parks is drawn at that call.
11061113
const toolUseId = message.params._meta?.[TOOL_USE_META];
1114+
const args = message.params.arguments ?? {};
11071115
try {
11081116
return await call(
11091117
binding,
11101118
message.params.name,
1111-
message.params.arguments ?? {},
1119+
args,
11121120
typeof extra.requestInfo?.headers.authorization === "string"
11131121
? extra.requestInfo.headers.authorization
11141122
: undefined,
1115-
typeof toolUseId === "string" ? toolUseId : undefined
1123+
typeof toolUseId === "string" ? toolUseId : undefined,
1124+
mcpCallKey(message.params._meta, message.params.name, args)
11161125
);
11171126
} finally {
11181127
options.lifetime.cancel(heartbeat);

‎packages/hub/src/role-budgets.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ export const listRoleTools = (): RoleTools[] => {
410410
fleet: { instances: () => rows, machines: () => [] },
411411
formerIds: () => ({}),
412412
forward: () => Promise.resolve(),
413+
callKeys: { once: (_actor, _name, _key, run) => run() },
413414
spawn: () => Promise.reject(new Error("A budget read starts nothing")),
414415
deliver: () => Promise.reject(new Error("measuring")),
415416
credentialActor: () => undefined,

‎packages/hub/src/server.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,7 @@ import {
534534
browserRoutes,
535535
createBrowsers,
536536
} from "./browsers";
537+
import { createCallKeys } from "./call-keys";
537538
import {
538539
attemptTry,
539540
type Caw,
@@ -24500,6 +24501,8 @@ export const createServer = (
2450024501
const toolCallKeys = createToolCallKeys({ db: db.toolCallKeys, lifetime });
2450124502
const delegationMcp = createDelegationMcp({
2450224503
lifetime,
24504+
// Kept with the relayed calls' keys, whose table tool-call-keys prunes.
24505+
callKeys: createCallKeys({ db: db.toolCallKeys }),
2450324506
tasks,
2450424507
connections,
2450524508
hubTools,
@@ -27584,6 +27587,8 @@ export const createServer = (
2758427587
const input = body as {
2758527588
name: string;
2758627589
arguments?: Record<string, unknown>;
27590+
/** The harness's own key for the call (pi's toolCallId, call-keys.ts). */
27591+
callKey?: unknown;
2758727592
};
2758827593
if (
2758927594
input.name === "generate_image" ||
@@ -27603,7 +27608,11 @@ export const createServer = (
2760327608
params.instanceId,
2760427609
input.name,
2760527610
input.arguments ?? {},
27606-
authorization ?? undefined
27611+
authorization ?? undefined,
27612+
undefined,
27613+
typeof input.callKey === "string" && input.callKey
27614+
? input.callKey
27615+
: undefined
2760727616
)
2760827617
),
2760927618
toolResultRefused

0 commit comments

Comments
 (0)