Skip to content
5 changes: 5 additions & 0 deletions .changeset/claude-code-nests-in-container.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@flow-state-dev/claude-code": patch
---

A Claude Code run inside a container now shows its top-level steps, including its sub-agent boxes, inside that container, as Codex and Cursor runs already do; steps inside a sub-agent still show inside the sub-agent (FIX-1701).
88 changes: 45 additions & 43 deletions packages/claude-code/src/sdk/emit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* the message's `parent_tool_use_id`); tools surface as `tool_output` items
* correlated by SDK tool-use id.
*/
import type { BlockContext } from "@flow-state-dev/core/types";
import { itemScope, type BlockContext } from "@flow-state-dev/core/types";
import type { TranslatedEvent } from "./types";

/** Provenance shape derived once per run and stamped on every emitted item. */
Expand All @@ -34,10 +34,10 @@ interface EmitProvenance {
*/
export interface EmitState {
/** Item id + accumulated text of the in-progress streamed message, if any.
* `ownedBy` (when set) nests the item under a sub-agent container. */
* `ownedBy` (when set) is the owner the open carried; the close keeps it. */
message: { id: string; contentIndex: number; text: string; ownedBy?: string } | null;
/** Item id + accumulated text of the in-progress streamed reasoning, if any.
* `ownedBy` (when set) nests the item under a sub-agent container. */
* `ownedBy` (when set) is the owner the open carried; the close keeps it. */
reasoning: { id: string; contentIndex: number; text: string; ownedBy?: string } | null;
/** Open tool_output items keyed by SDK tool-use callId. */
readonly openTools: Map<
Expand Down Expand Up @@ -103,37 +103,48 @@ function mintId(kind: string): string {

/**
* Fields every item carries besides its id. A close reuses the id from
* `item.added`, so it cannot go through {@link buildBase}. The task id is
* stamped here once and omitted outside a task scope.
* `item.added`, so it cannot go through {@link buildBase}. Task and runtime
* owner come from {@link itemScope}. `ownedBy`, when passed, replaces the
* runtime owner (a sub-agent's id, or the owner the open stored).
*/
function itemFields(ctx: BlockContext, provenance: EmitProvenance) {
const taskId = (ctx as { _blockIdentity?: { taskId?: string } })._blockIdentity?.taskId;
function itemFields(ctx: BlockContext, provenance: EmitProvenance, ownedBy?: string) {
const scope = itemScope(ctx);
const owner = ownedBy ?? scope.ownedBy;
return {
requestId: ctx.request.identity.id,
itemIndex: ctx.response.getItemCount(),
provenance,
ts: Date.now(),
...(taskId === undefined ? {} : { taskId }),
...(scope.taskId !== undefined ? { taskId: scope.taskId } : {}),
...(owner !== undefined ? { ownedBy: owner } : {}),
};
}

/** Per-item base for a newly opened item: a fresh id plus {@link itemFields}. */
function buildBase(ctx: BlockContext, provenance: EmitProvenance, kind: string) {
return { id: mintId(kind), ...itemFields(ctx, provenance) };
function buildBase(ctx: BlockContext, provenance: EmitProvenance, kind: string, ownedBy?: string) {
return { id: mintId(kind), ...itemFields(ctx, provenance, ownedBy) };
}

const CONVERSATIONAL_VISIBILITY = { client: true, history: true } as const;

/**
* Resolve the `ownedBy` value for an item produced inside a sub-agent.
* `parentCallId` is the sub-agent's tool-use id (from the SDK message's
* `parent_tool_use_id`); when a container is open for it, the item nests under
* that container by carrying its `provenance.blockInstanceId` (the framework's
* container-ownership key). Returns `undefined` for top-level items.
* Resolve the `ownedBy` value for an item. `parentCallId` is the sub-agent's
* tool-use id (from the SDK message's `parent_tool_use_id`); when a container
* is open for it, the item nests under that container by carrying its
* `provenance.blockInstanceId` (the framework's container-ownership key). The
* sub-agent's owner wins inside it; every other item takes the owner of the
* container this run sits in, as the runtime describes it, so a run inside a
* container shows its steps inside that container
* (`docs/architecture/streaming.md` → "Container Ownership").
*/
function resolveOwnedBy(state: EmitState, parentCallId: string | undefined): string | undefined {
if (parentCallId === undefined) return undefined;
return state.openSubagents.get(parentCallId)?.instanceId;
function resolveOwnedBy(
ctx: BlockContext,
state: EmitState,
parentCallId: string | undefined,
): string | undefined {
const subAgentOwner =
parentCallId === undefined ? undefined : state.openSubagents.get(parentCallId)?.instanceId;
return subAgentOwner ?? itemScope(ctx).ownedBy;
}

/**
Expand Down Expand Up @@ -196,15 +207,14 @@ async function emitMessageDelta(
if (state.message === null) {
// A reasoning item streaming before the first text closes here.
await closeStreamingReasoning(ctx, state, provenance.blockName);
const ownedBy = resolveOwnedBy(state, parentCallId);
const base = buildBase(ctx, provenance, "msg");
const ownedBy = resolveOwnedBy(ctx, state, parentCallId);
const base = buildBase(ctx, provenance, "msg", ownedBy);
const item = {
...base,
type: "message" as const,
role: "assistant" as const,
status: "in_progress" as const,
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
content: [{ type: "output_text" as const, text: "" }],
};
await ctx.response.emit({ type: "item.added", item });
Expand Down Expand Up @@ -262,9 +272,8 @@ async function closeStreamingMessage(
type: "message",
role: "assistant",
status: "completed",
...itemFields(ctx, deriveProvenance(ctx, blockName)),
...itemFields(ctx, deriveProvenance(ctx, blockName), ownedBy),
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
content: [{ type: "output_text", text }],
},
});
Expand All @@ -283,15 +292,14 @@ async function emitMessageComplete(
provenance: EmitProvenance,
parentCallId: string | undefined,
): Promise<void> {
const ownedBy = resolveOwnedBy(state, parentCallId);
const base = buildBase(ctx, provenance, "msg");
const ownedBy = resolveOwnedBy(ctx, state, parentCallId);
const base = buildBase(ctx, provenance, "msg", ownedBy);
const inProgress = {
...base,
type: "message" as const,
role: "assistant" as const,
status: "in_progress" as const,
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
content: [{ type: "output_text" as const, text: "" }],
};
await ctx.response.emit({ type: "item.added", item: inProgress });
Expand Down Expand Up @@ -323,14 +331,13 @@ async function emitReasoningDelta(
parentCallId: string | undefined,
): Promise<void> {
if (state.reasoning === null) {
const ownedBy = resolveOwnedBy(state, parentCallId);
const base = buildBase(ctx, provenance, "reasoning");
const ownedBy = resolveOwnedBy(ctx, state, parentCallId);
const base = buildBase(ctx, provenance, "reasoning", ownedBy);
const item = {
...base,
type: "reasoning" as const,
status: "in_progress" as const,
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
summary: [{ type: "reasoning_text" as const, text: "" }],
};
await ctx.response.emit({ type: "item.added", item });
Expand Down Expand Up @@ -371,9 +378,8 @@ async function closeStreamingReasoning(
id,
type: "reasoning",
status: "completed",
...itemFields(ctx, deriveProvenance(ctx, blockName)),
...itemFields(ctx, deriveProvenance(ctx, blockName), ownedBy),
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
summary: [{ type: "reasoning_text", text }],
},
});
Expand All @@ -388,14 +394,13 @@ async function emitReasoningComplete(
provenance: EmitProvenance,
parentCallId: string | undefined,
): Promise<void> {
const ownedBy = resolveOwnedBy(state, parentCallId);
const base = buildBase(ctx, provenance, "reasoning");
const ownedBy = resolveOwnedBy(ctx, state, parentCallId);
const base = buildBase(ctx, provenance, "reasoning", ownedBy);
const inProgress = {
...base,
type: "reasoning" as const,
status: "in_progress" as const,
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
summary: [{ type: "reasoning_text" as const, text: "" }],
};
await ctx.response.emit({ type: "item.added", item: inProgress });
Expand Down Expand Up @@ -429,8 +434,8 @@ async function emitToolCall(
await closeStreamingMessage(ctx, state, provenance.blockName);
await closeStreamingReasoning(ctx, state, provenance.blockName);
if (!state.toolsObserved.includes(event.name)) state.toolsObserved.push(event.name);
const ownedBy = resolveOwnedBy(state, event.parentCallId);
const base = buildBase(ctx, provenance, "tool");
const ownedBy = resolveOwnedBy(ctx, state, event.parentCallId);
const base = buildBase(ctx, provenance, "tool", ownedBy);
const item = {
...base,
type: "tool_output" as const,
Expand All @@ -444,14 +449,13 @@ async function emitToolCall(
generatorBlock: blockName,
},
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
};
await ctx.response.emit({ type: "item.added", item });
state.openTools.set(event.callId, {
id: base.id,
name: event.name,
arguments: event.arguments,
...(ownedBy ? { ownedBy } : {}),
ownedBy,
});
}

Expand All @@ -473,12 +477,12 @@ async function emitToolResult(
const id = open?.id ?? mintId("tool");
const toolName = open?.name ?? blockName;
const toolArgs = open?.arguments ?? "{}";
const ownedBy = open?.ownedBy ?? resolveOwnedBy(state, event.parentCallId);
const ownedBy = open?.ownedBy ?? resolveOwnedBy(ctx, state, event.parentCallId);
const item = {
id,
type: "tool_output" as const,
status: event.isError ? ("failed" as const) : ("completed" as const),
...itemFields(ctx, provenance),
...itemFields(ctx, provenance, ownedBy),
blockName: toolName,
output: event.output,
toolCall: {
Expand All @@ -488,7 +492,6 @@ async function emitToolResult(
generatorBlock: blockName,
},
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(ownedBy ? { ownedBy } : {}),
...(event.isError ? { error: { message: String(event.output) } } : {}),
};
if (isOrphan) {
Expand Down Expand Up @@ -592,7 +595,7 @@ export async function finalizeOpenItems(
id: open.id,
type: "tool_output",
status: "incomplete",
...itemFields(ctx, deriveProvenance(ctx, blockName)),
...itemFields(ctx, deriveProvenance(ctx, blockName), open.ownedBy),
blockName: open.name,
output: null,
toolCall: {
Expand All @@ -602,7 +605,6 @@ export async function finalizeOpenItems(
generatorBlock: blockName,
},
itemVisibility: CONVERSATIONAL_VISIBILITY,
...(open.ownedBy ? { ownedBy: open.ownedBy } : {}),
},
});
}
Expand Down
80 changes: 80 additions & 0 deletions packages/claude-code/test/sdk/agent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1125,6 +1125,86 @@ describe("claudeCodeAgent — task attribution", () => {
});
});

describe("claudeCodeAgent — inside an owned container", () => {
// The Container Ownership contract (`docs/architecture/streaming.md`): every
// item emitted inside a container carries that container's `ownedBy`, and a
// nested container's own item carries the outer owner. A Claude Code run
// placed inside a container must show its steps inside it, as Codex and
// Cursor runs do; a sub-agent's own steps still show inside the sub-agent.
// Driven through the real block inside a real sequencer that declares a
// container, so the owner comes from the runtime, not a hand-built identity.
it("stamps the container's owner on every top-level item and sub-agent box, and the sub-agent's on its own items", async () => {
const messages: SdkMessageLike[] = [
{ type: "system", subtype: "init", session_id: "sess_owned" },
{
type: "assistant",
message: {
content: [
{ type: "thinking", thinking: "plan" },
{ type: "text", text: "working" },
{ type: "tool_use", id: "toolu_1", name: "Bash", input: { command: "ls" } },
],
},
},
{ type: "user", message: { content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "ok" }] } },
{
type: "assistant",
message: { content: [{ type: "tool_use", id: "toolu_agent", name: "Agent", input: { task: "sub" } }] },
},
{
type: "assistant",
parent_tool_use_id: "toolu_agent",
message: { content: [{ type: "tool_use", id: "toolu_inner", name: "Read", input: { path: "a" } }] },
},
{
type: "user",
parent_tool_use_id: "toolu_agent",
message: { content: [{ type: "tool_result", tool_use_id: "toolu_inner", content: "ok" }] },
},
{ type: "user", message: { content: [{ type: "tool_result", tool_use_id: "toolu_agent", content: "child done" }] } },
{ type: "result", subtype: "error_max_turns", result: "too many turns", session_id: "sess_owned" },
];
const owned = sequencer({
name: "owned-run",
inputSchema: z.object({ prompt: z.string() }),
container: { component: "harness-run" },
}).step(claudeCodeAgent({ resolveClaudeAgent: scriptedQuery(messages), includePartialMessages: false }));

const { items, error } = await testBlock(owned, { input: { prompt: "do the thing" } });

expect(error).toBeNull();
const outer = items.find((i) => i.type === "container" && i.blockName === "owned-run") as
| { provenance: { blockInstanceId: string } }
| undefined;
expect(outer).toBeDefined();
const outerOwner = outer!.provenance.blockInstanceId;
const subagent = items.find((i) => i.type === "container" && i.blockName === "Agent") as
| { provenance: { blockInstanceId: string } }
| undefined;
expect(subagent).toBeDefined();
const subagentOwner = subagent!.provenance.blockInstanceId;

const RUN_TYPES = new Set(["message", "reasoning", "tool_output", "container", "error"]);
const runItems = items.filter((i) => RUN_TYPES.has(i.type) && i !== outer);
expect(new Set(runItems.map((i) => i.type))).toEqual(
new Set(["message", "reasoning", "tool_output", "container", "error"]),
);
const innerCallIds = new Set(["toolu_inner"]);
const ownership = runItems.map((i) => {
const callId = (i as { toolCall?: { callId?: string } }).toolCall?.callId;
return { type: i.type, callId, ownedBy: (i as { ownedBy?: string }).ownedBy };
});
expect(ownership).toEqual(
ownership.map(({ type, callId }) => ({
type,
callId,
ownedBy: callId !== undefined && innerCallIds.has(callId) ? subagentOwner : outerOwner,
})),
);
expect(ownership.some((o) => o.ownedBy === subagentOwner)).toBe(true);
});
});

describe("claudeCodeAgent — detached", () => {
/** The read the board's refusal performs, spelled the same way. */
function authoredSessionStateSchema(block: unknown): unknown {
Expand Down
Loading
Loading