fix(orchestration): route subagent-attributed Claude text to the child thread
The Claude Agent SDK forwards subagent assistant messages into the parent query stream tagged with parent_tool_use_id. The adapter already honored that attribution for tool uses (ensureToolCallStarted) but the assistant-text path ignored it, so every streamed subagent narration and final answer projected as parent-thread assistant prose — interleaved across concurrent subagents and duplicating the summary the child thread receives via task_notification. Assistant text now resolves the same subagentsByToolUseId registry and lands in the subagent's child thread. The child-thread result message becomes a fallback for streams that were never forwarded: once a subagent has streamed text since (re)open, the task_notification summary no longer re-emits as a duplicate child message (the parent subagent card still carries task.result). Attributed text whose registry lookup misses is dropped with a warning instead of leaking into the parent transcript. Subagent text dedupes against a per-subagent set rather than the parent turn's emittedNativeItemIds, which gates the parent fallback-text emission and must not be suppressed by subagent traffic. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
378615bb51
commit
c65da86a0f
2 files changed
+220
-1
No files matched your search
@@ -2380,6 +2380,135 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("routes subagent-attributed assistant text to the child thread", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const SUBAGENT_TASK_ID = "task-subagent-text-routing";
|
||||
const SUBAGENT_TOOL_USE_ID = "toolu-subagent-text-routing";
|
||||
const SUBAGENT_TEXT = "All done. Summary of changes.";
|
||||
const harness = yield* makeWakeHarness;
|
||||
const now = yield* DateTime.now;
|
||||
const subagentEvents = () =>
|
||||
harness.events.filter(
|
||||
(event): event is Extract<ProviderAdapterV2Event, { type: "subagent.updated" }> =>
|
||||
event.type === "subagent.updated",
|
||||
);
|
||||
const assistantItems = () =>
|
||||
harness.events.filter(
|
||||
(event): event is Extract<ProviderAdapterV2Event, { type: "turn_item.updated" }> =>
|
||||
event.type === "turn_item.updated" && event.turnItem.type === "assistant_message",
|
||||
);
|
||||
|
||||
yield* harness.runtime.startTurn(
|
||||
makeClaudeTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-claude-subagent-text-routing"),
|
||||
text: "Delegate this task.",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "system",
|
||||
subtype: "task_started",
|
||||
task_id: SUBAGENT_TASK_ID,
|
||||
tool_use_id: SUBAGENT_TOOL_USE_ID,
|
||||
description: "Fix environments tests",
|
||||
subagent_type: "general-purpose",
|
||||
task_type: "local_agent",
|
||||
prompt: "Fix the tests.",
|
||||
uuid: "00000000-0000-4000-8000-000000000226",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => subagentEvents().length >= 1, "subagent node created");
|
||||
const childThreadId = subagentEvents()[0]?.subagent.childThreadId;
|
||||
assert.ok(childThreadId);
|
||||
|
||||
// The SDK forwards the subagent's assistant message into the parent
|
||||
// query stream, attributed via parent_tool_use_id.
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "assistant",
|
||||
message: {
|
||||
model: "claude-sonnet-4-6",
|
||||
id: "msg_subagent-text-routing",
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
content: [{ type: "text", text: SUBAGENT_TEXT }],
|
||||
stop_reason: null,
|
||||
stop_sequence: null,
|
||||
usage: {
|
||||
input_tokens: 1,
|
||||
output_tokens: 1,
|
||||
cache_creation_input_tokens: 0,
|
||||
cache_read_input_tokens: 0,
|
||||
},
|
||||
},
|
||||
parent_tool_use_id: SUBAGENT_TOOL_USE_ID,
|
||||
uuid: "00000000-0000-4000-8000-000000000227",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(
|
||||
() => assistantItems().some((event) => event.turnItem.threadId === childThreadId),
|
||||
"child thread assistant text",
|
||||
);
|
||||
assert.equal(
|
||||
assistantItems().filter((event) => event.turnItem.threadId === harness.threadId).length,
|
||||
0,
|
||||
);
|
||||
|
||||
// The completion notification's summary duplicates the streamed final
|
||||
// message, so no separate result message may land in the child thread.
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: SUBAGENT_TASK_ID,
|
||||
tool_use_id: SUBAGENT_TOOL_USE_ID,
|
||||
status: "completed",
|
||||
output_file: "/tmp/task-subagent-text-routing.output",
|
||||
summary: SUBAGENT_TEXT,
|
||||
uuid: "00000000-0000-4000-8000-000000000228",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(
|
||||
() => subagentEvents().at(-1)?.subagent.status === "completed",
|
||||
"subagent terminal",
|
||||
);
|
||||
assert.equal(subagentEvents().at(-1)?.subagent.result, SUBAGENT_TEXT);
|
||||
assert.equal(
|
||||
assistantItems().filter((event) => event.turnItem.threadId === childThreadId).length,
|
||||
1,
|
||||
);
|
||||
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000229",
|
||||
result: "Delegation completed.",
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
|
||||
// The parent turn emitted no assistant text of its own, so its result
|
||||
// fallback must still materialize — subagent text must not count
|
||||
// against the fallback gate.
|
||||
const parentAssistantItems = assistantItems().filter(
|
||||
(event) => event.turnItem.threadId === harness.threadId,
|
||||
);
|
||||
assert.equal(parentAssistantItems.length, 1);
|
||||
assert.equal(parentAssistantItems[0]?.turnItem.text, "Delegation completed.");
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("releases the idle pin when a post-settle subagent stops without completing", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1937,6 +1937,11 @@ interface ActiveClaudeSubagent {
|
||||
progressItemOrdinal: number | null;
|
||||
progressStartedAt: DateTime.Utc | null;
|
||||
resultItemOrdinal: number | null;
|
||||
// Deliberately separate from the parent turn's emittedNativeItemIds: that
|
||||
// set gates the parent fallback-text emission, which subagent-attributed
|
||||
// text must not suppress.
|
||||
readonly emittedTextNativeItemIds: Set<string>;
|
||||
hasStreamedText: boolean;
|
||||
}
|
||||
|
||||
interface ClaudeLiveQueryContext {
|
||||
@@ -2381,6 +2386,10 @@ export function makeClaudeAdapterV2(
|
||||
progressItemOrdinal: existingSubagent?.progressItemOrdinal ?? null,
|
||||
progressStartedAt: existingSubagent?.progressStartedAt ?? null,
|
||||
resultItemOrdinal: existingSubagent?.resultItemOrdinal ?? null,
|
||||
emittedTextNativeItemIds: existingSubagent?.emittedTextNativeItemIds ?? new Set(),
|
||||
// A resumed run's result suppression starts fresh: text streamed
|
||||
// before the resume no longer represents the new outcome.
|
||||
hasStreamedText: isReopen ? false : (existingSubagent?.hasStreamedText ?? false),
|
||||
} satisfies ActiveClaudeSubagent;
|
||||
input.context.subagentsByTaskId.set(input.taskId, subagent);
|
||||
if (input.toolUseId !== undefined) {
|
||||
@@ -2597,10 +2606,16 @@ export function makeClaudeAdapterV2(
|
||||
});
|
||||
}
|
||||
|
||||
// The child-thread result message is a fallback for subagents whose
|
||||
// stream was never forwarded (background tasks settling across
|
||||
// turns): when the live stream already delivered the subagent's
|
||||
// assistant text into the child thread, its last message IS the
|
||||
// final answer and the task_notification summary would duplicate it.
|
||||
if (
|
||||
input.result !== undefined &&
|
||||
input.result.trim().length > 0 &&
|
||||
input.status !== "running"
|
||||
input.status !== "running" &&
|
||||
!subagent.hasStreamedText
|
||||
) {
|
||||
const resultNativeItemId = `${nativeItemId}:result`;
|
||||
const resultItemOrdinal = subagent.resultItemOrdinal ?? ++subagent.nextChildItemOrdinal;
|
||||
@@ -3014,6 +3029,54 @@ export function makeClaudeAdapterV2(
|
||||
);
|
||||
});
|
||||
|
||||
const emitSubagentAssistantTextArtifacts = Effect.fnUntraced(function* (input: {
|
||||
readonly context: ActiveClaudeTurnContext;
|
||||
readonly subagent: ActiveClaudeSubagent;
|
||||
readonly nativeItemId: string;
|
||||
readonly text: string;
|
||||
}) {
|
||||
if (input.subagent.emittedTextNativeItemIds.has(input.nativeItemId)) {
|
||||
return;
|
||||
}
|
||||
input.subagent.emittedTextNativeItemIds.add(input.nativeItemId);
|
||||
const now = yield* DateTime.now;
|
||||
const ordinal = ++input.subagent.nextChildItemOrdinal;
|
||||
input.subagent.hasStreamedText = true;
|
||||
const artifacts = makeSubagentConversationArtifacts({
|
||||
messageId: idAllocator.derive.messageFromProviderItem({
|
||||
driver: CLAUDE_PROVIDER,
|
||||
nativeItemId: input.nativeItemId,
|
||||
}),
|
||||
turnItemId: idAllocator.derive.turnItemFromProviderItem({
|
||||
driver: CLAUDE_PROVIDER,
|
||||
nativeItemId: input.nativeItemId,
|
||||
}),
|
||||
threadId: input.subagent.childThreadId,
|
||||
rootNodeId: input.subagent.childRootNodeId,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: {
|
||||
driver: CLAUDE_PROVIDER,
|
||||
nativeId: input.nativeItemId,
|
||||
strength: "strong",
|
||||
},
|
||||
role: "assistant",
|
||||
text: input.text,
|
||||
ordinal,
|
||||
now,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "message.updated",
|
||||
driver: CLAUDE_PROVIDER,
|
||||
message: artifacts.message,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver: CLAUDE_PROVIDER,
|
||||
turnItem: artifacts.turnItem,
|
||||
});
|
||||
});
|
||||
|
||||
const finalizeActiveTurnAfterQueryExit = Effect.fnUntraced(function* (
|
||||
cause?: Cause.Cause<ClaudeAgentSdkQueryRunnerError>,
|
||||
) {
|
||||
@@ -3377,6 +3440,33 @@ export function makeClaudeAdapterV2(
|
||||
|
||||
const assistantText = assistantTextFromSdkMessage(message);
|
||||
if (assistantText !== null && assistantText.text.length > 0) {
|
||||
// The SDK forwards subagent assistant messages into the parent
|
||||
// query stream tagged with parent_tool_use_id; they belong to the
|
||||
// subagent's child thread, never to the parent transcript. Tool
|
||||
// uses on the same messages already route via
|
||||
// ensureToolCallStarted, so text must follow the same attribution.
|
||||
const textParentToolUseId = parentToolUseIdFromSdkMessage(message);
|
||||
if (textParentToolUseId !== null) {
|
||||
const subagent = context.subagentsByToolUseId.get(textParentToolUseId);
|
||||
if (subagent === undefined) {
|
||||
// Dropped rather than surfaced in the parent thread: the
|
||||
// child thread still receives the final answer via the
|
||||
// task_notification result fallback.
|
||||
yield* Effect.logWarning("orchestration-v2.claude-subagent-text-unrouted", {
|
||||
providerTurnId: context.providerTurnId,
|
||||
parentToolUseId: textParentToolUseId,
|
||||
nativeItemId: assistantText.nativeItemId,
|
||||
});
|
||||
} else {
|
||||
yield* emitSubagentAssistantTextArtifacts({
|
||||
context,
|
||||
subagent,
|
||||
nativeItemId: assistantText.nativeItemId,
|
||||
text: assistantText.text,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* emitAssistantTextArtifacts({
|
||||
context,
|
||||
nativeItemId: assistantText.nativeItemId,
|
||||
|
||||
Reference in new issue
Block a user