Skip to content

Commit 82a221e

Browse files
committed
fix(claude): isolate subagent tool streams
1 parent 0d34579 commit 82a221e

2 files changed

Lines changed: 162 additions & 10 deletions

File tree

‎apps/server/src/provider/Layers/ClaudeAdapter.test.ts‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1467,6 +1467,157 @@ describe("ClaudeAdapterLive", () => {
14671467
);
14681468
});
14691469

1470+
for (const ending of ["results", "turn-completed", "stream-failed"] as const) {
1471+
it.effect(`isolates parent and sibling tool streams through ${ending}`, () => {
1472+
const harness = makeHarness();
1473+
return Effect.gen(function* () {
1474+
const adapter = yield* ClaudeAdapter;
1475+
const eventsFiber = yield* adapter.streamEvents.pipe(
1476+
Stream.takeUntil((event) => event.type === "turn.completed"),
1477+
Stream.runCollect,
1478+
Effect.forkChild,
1479+
);
1480+
yield* adapter.startSession({
1481+
threadId: THREAD_ID,
1482+
provider: ProviderDriverKind.make("claudeAgent"),
1483+
runtimeMode: "full-access",
1484+
});
1485+
yield* adapter.sendTurn({ threadId: THREAD_ID, input: "Delegate work", attachments: [] });
1486+
const stream = (owner: string | null, event: unknown) =>
1487+
harness.query.emit({
1488+
type: "stream_event",
1489+
session_id: "sdk-isolated",
1490+
uuid: "stream-isolated",
1491+
parent_tool_use_id: owner,
1492+
event,
1493+
} as unknown as SDKMessage);
1494+
const owners = [null, "task-a", "task-b"] as const;
1495+
stream(null, {
1496+
type: "content_block_start",
1497+
index: 1,
1498+
content_block: { type: "text", text: "" },
1499+
});
1500+
stream(null, {
1501+
type: "content_block_delta",
1502+
index: 1,
1503+
delta: { type: "text_delta", text: "Parent " },
1504+
});
1505+
for (const owner of owners) {
1506+
stream(owner, {
1507+
type: "content_block_start",
1508+
index: 0,
1509+
content_block: {
1510+
type: "tool_use",
1511+
id: `tool-${owner ?? "parent"}`,
1512+
name: "Read",
1513+
input: {},
1514+
},
1515+
});
1516+
}
1517+
for (const owner of owners) {
1518+
stream(owner, {
1519+
type: "content_block_delta",
1520+
index: 0,
1521+
delta: { type: "input_json_delta", partial_json: '{"file_path":"' },
1522+
});
1523+
}
1524+
for (const owner of owners.toReversed()) {
1525+
stream(owner, {
1526+
type: "content_block_delta",
1527+
index: 0,
1528+
delta: { type: "input_json_delta", partial_json: `${owner ?? "parent"}.ts"}` },
1529+
});
1530+
stream(owner, { type: "content_block_stop", index: 0 });
1531+
}
1532+
// A suppressed child text block must not close the parent's block at the same index.
1533+
stream("task-a", {
1534+
type: "content_block_start",
1535+
index: 1,
1536+
content_block: { type: "text", text: "" },
1537+
});
1538+
stream("task-a", { type: "content_block_stop", index: 1 });
1539+
stream(null, {
1540+
type: "content_block_delta",
1541+
index: 1,
1542+
delta: { type: "text_delta", text: "answer" },
1543+
});
1544+
stream(null, { type: "content_block_stop", index: 1 });
1545+
if (ending === "results") {
1546+
for (const owner of owners.toReversed()) {
1547+
harness.query.emit({
1548+
type: "user",
1549+
session_id: "sdk-isolated",
1550+
uuid: "result-isolated",
1551+
parent_tool_use_id: owner,
1552+
message: {
1553+
role: "user",
1554+
content: [
1555+
{
1556+
type: "tool_result",
1557+
tool_use_id: `tool-${owner ?? "parent"}`,
1558+
content: `result-${owner ?? "parent"}`,
1559+
is_error: owner === "task-b",
1560+
},
1561+
],
1562+
},
1563+
} as unknown as SDKMessage);
1564+
}
1565+
}
1566+
if (ending === "stream-failed") harness.query.fail(new Error("SDK stream failed"));
1567+
else
1568+
harness.query.emit({
1569+
type: "result",
1570+
subtype: "success",
1571+
is_error: false,
1572+
errors: [],
1573+
session_id: "sdk-isolated",
1574+
uuid: "result-isolated",
1575+
} as unknown as SDKMessage);
1576+
const events = Array.from(yield* Fiber.join(eventsFiber));
1577+
const textDeltas = events.filter(
1578+
(event) =>
1579+
event.type === "content.delta" && event.payload.streamKind === "assistant_text",
1580+
);
1581+
assert.equal(textDeltas.length, 2);
1582+
assert.equal(textDeltas[0]?.itemId, textDeltas[1]?.itemId);
1583+
for (const owner of owners) {
1584+
const completed = events.filter(
1585+
(event) =>
1586+
event.type === "item.completed" && event.itemId === `tool-${owner ?? "parent"}`,
1587+
);
1588+
assert.equal(completed.length, 1);
1589+
const event = completed[0];
1590+
assert.equal(event?.type, "item.completed");
1591+
if (event?.type !== "item.completed") return;
1592+
assert.equal(event.payload.parentToolUseId, owner ?? undefined);
1593+
assert.equal(
1594+
event.payload.status,
1595+
ending === "stream-failed" || (ending === "results" && owner === "task-b")
1596+
? "failed"
1597+
: "completed",
1598+
);
1599+
assert.deepEqual(event.payload.data, {
1600+
toolName: "Read",
1601+
input: { file_path: `${owner ?? "parent"}.ts` },
1602+
...(ending === "results"
1603+
? {
1604+
result: {
1605+
type: "tool_result",
1606+
tool_use_id: `tool-${owner ?? "parent"}`,
1607+
content: `result-${owner ?? "parent"}`,
1608+
is_error: owner === "task-b",
1609+
},
1610+
}
1611+
: {}),
1612+
});
1613+
}
1614+
}).pipe(
1615+
Effect.provideService(Random.Random, makeDeterministicRandomService()),
1616+
Effect.provide(harness.layer),
1617+
);
1618+
});
1619+
}
1620+
14701621
it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => {
14711622
const harness = makeHarness();
14721623
return Effect.gen(function* () {

‎apps/server/src/provider/Layers/ClaudeAdapter.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ interface ClaudeSessionContext {
305305
id: TurnId;
306306
items: Array<unknown>;
307307
}>;
308-
readonly inFlightTools: Map<number, ToolInFlight>;
308+
readonly inFlightTools: Map<string, ToolInFlight>;
309309
readonly claudeTasks: Map<string, ClaudeTaskState>;
310310
readonly taskAgents: Map<string, ClaudeTaskAgentState>;
311311
/**
@@ -2565,6 +2565,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
25652565
status: status === "completed" ? "completed" : "failed",
25662566
title: tool.title,
25672567
...(tool.detail ? { detail: tool.detail } : {}),
2568+
...(tool.agentId ? { agentId: tool.agentId } : {}),
2569+
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
25682570
data: {
25692571
toolName: tool.toolName,
25702572
input: tool.input,
@@ -2746,7 +2748,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
27462748
}
27472749

27482750
if (event.delta.type === "input_json_delta") {
2749-
const tool = context.inFlightTools.get(event.index);
2751+
// Every parent and subagent message numbers its own content blocks from zero.
2752+
const toolKey = `${streamParentToolUseId ?? ""}:${event.index}`;
2753+
const tool = context.inFlightTools.get(toolKey);
27502754
if (!tool || typeof event.delta.partial_json !== "string") {
27512755
return;
27522756
}
@@ -2770,7 +2774,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
27702774
parsedInput && Object.keys(parsedInput).length > 0
27712775
? toolInputFingerprint(parsedInput)
27722776
: undefined;
2773-
context.inFlightTools.set(event.index, nextTool);
2777+
context.inFlightTools.set(toolKey, nextTool);
27742778

27752779
if (
27762780
!parsedInput ||
@@ -2784,7 +2788,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
27842788
...nextTool,
27852789
lastEmittedInputFingerprint: nextFingerprint,
27862790
};
2787-
context.inFlightTools.set(event.index, nextTool);
2791+
context.inFlightTools.set(toolKey, nextTool);
27882792

27892793
const stamp = yield* makeEventStamp();
27902794
yield* offerRuntimeEvent({
@@ -2895,7 +2899,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
28952899
...(owningAgentId ? { agentId: owningAgentId } : {}),
28962900
...(parentToolUseId ? { parentToolUseId } : {}),
28972901
};
2898-
context.inFlightTools.set(index, tool);
2902+
context.inFlightTools.set(`${parentToolUseId ?? ""}:${index}`, tool);
28992903

29002904
const stamp = yield* makeEventStamp();
29012905
yield* offerRuntimeEvent({
@@ -2931,6 +2935,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
29312935
}
29322936

29332937
if (event.type === "content_block_stop") {
2938+
if (streamParentToolUseId !== null && streamParentToolUseId !== undefined) return;
29342939
const { index } = event;
29352940
const assistantBlock = context.turnState?.assistantTextBlocks.get(index);
29362941
if (assistantBlock) {
@@ -2941,10 +2946,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
29412946
});
29422947
return;
29432948
}
2944-
const tool = context.inFlightTools.get(index);
2945-
if (!tool) {
2946-
return;
2947-
}
29482949
}
29492950
});
29502951

@@ -4209,7 +4210,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
42094210

42104211
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
42114212
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
4212-
const inFlightTools = new Map<number, ToolInFlight>();
4213+
const inFlightTools = new Map<string, ToolInFlight>();
42134214
const claudeTasks = new Map<string, ClaudeTaskState>();
42144215
const taskAgents = new Map<string, ClaudeTaskAgentState>();
42154216
const pendingTaskModels = new Map<string, string>();

0 commit comments

Comments
 (0)