Skip to content

Commit 77b6a16

Browse files
jakeleventhalclaude
andcommitted
feat(fx): sub-agent threads show the child's steps and its full reply
fx clips every ACP tool result to a 200-byte preview and streams no sub-agent frames, so an fx sub-agent's thread held only its task and a cut-off reply. T3 now opts into fx's libfx hooks on session/new, load and resume, and uses them only when fx confirms hooksVersion 1. Older fx keeps the ACP-only view. A dispatched child's tool calls and its narration between them become steps in its existing child thread, and its reply comes whole from the root call's tool.end or tool.result. Delegation phases drive the child's status. Unused events, including model.start request content, are dropped at decode and nothing retains them. Child events are followed only while their call runs, so a reload, which replays finished calls without their steps, leaves projected threads alone. The new fx_subagent_hooks fixture is a live fx 0.0.15 recording, and an adapter test plays fx's recorded load replay. Existing fx fixtures now expect the opt-in and cover fx not confirming it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 20497e4 commit 77b6a16

25 files changed

Lines changed: 1239 additions & 97 deletions

File tree

‎apps/server/scripts/record-fx-acp-replay-fixture.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,8 +223,23 @@ function normalizeOutboundFrame(frame: Record<string, unknown>, runtimeInstructi
223223
}
224224
}
225225

226+
/** A model call's request content: up to 64 KiB per hook that T3 never reads. */
227+
const HOOK_MODEL_REQUEST_FIELDS = new Set(["messages", "instructions", "tools", "toolsJson"]);
228+
226229
function normalizeInboundFrame(frame: Record<string, unknown>): Record<string, unknown> {
227230
const params = isRecord(frame.params) ? frame.params : undefined;
231+
if (frame.method === "libfx/hook" && params?.type === "model.start" && isRecord(params.data)) {
232+
const data = params.data;
233+
return {
234+
...frame,
235+
params: {
236+
...params,
237+
data: Object.fromEntries(
238+
Object.entries(data).filter(([key]) => !HOOK_MODEL_REQUEST_FIELDS.has(key)),
239+
),
240+
},
241+
};
242+
}
228243
const update = isRecord(params?.update) ? params.update : undefined;
229244
if (
230245
update?.sessionUpdate === "available_commands_update" &&
@@ -461,7 +476,7 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str
461476
generatedBy: "live-fx-recorder",
462477
fxVersion: initializeAgent.version ?? "unknown",
463478
normalization:
464-
"Session ids are fx-session-NN, the workspace is <workspace>, HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are <any>. User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.",
479+
"Session ids are fx-session-NN, the workspace is <workspace>, HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are <any>. User skill names, emails and token-shaped strings are removed. libfx/hook model.start events keep their ids and purpose but not their request content. Timestamps are kept as recorded.",
465480
droppedFrames,
466481
},
467482
entries: [

‎apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ export function makeAcpReplayRuntime(input: {
196196
readonly cancelMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelMeta"];
197197
readonly cancelBehavior?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelBehavior"];
198198
readonly initializeMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["initializeMeta"];
199+
readonly sessionMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["sessionMeta"];
199200
readonly replayGate?: ProviderReplayGate;
200201
}): (
201202
runtimeInput: AcpAdapterV2RuntimeInput,
@@ -238,6 +239,7 @@ export function makeAcpReplayRuntime(input: {
238239
...(input.cancelMeta === undefined ? {} : { cancelMeta: input.cancelMeta }),
239240
...(input.cancelBehavior === undefined ? {} : { cancelBehavior: input.cancelBehavior }),
240241
...(input.initializeMeta === undefined ? {} : { initializeMeta: input.initializeMeta }),
242+
...(input.sessionMeta === undefined ? {} : { sessionMeta: input.sessionMeta }),
241243
...(input.replayGate === undefined
242244
? {}
243245
: { transformStdout: holdGatedReplayLines(input.transcript, input.replayGate) }),

‎apps/server/src/orchestration-v2/Adapters/FxAdapterV2.test.ts‎

Lines changed: 189 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
2-
import { describe, it } from "@effect/vitest";
2+
import { assert, describe, it } from "@effect/vitest";
33
import {
44
MessageId,
55
NodeId,
@@ -13,7 +13,11 @@ import {
1313
} from "@t3tools/contracts";
1414
import { ACP_PROTOCOL } from "@t3tools/provider-acp/server/adapter";
1515
import { FxSettings } from "@t3tools/provider-fx/settings";
16-
import { FX_DRIVER_KIND, makeFxAdapterV2 } from "@t3tools/provider-fx/testing";
16+
import {
17+
FX_DRIVER_KIND,
18+
FX_HOOKS_SESSION_META,
19+
makeFxAdapterV2,
20+
} from "@t3tools/provider-fx/testing";
1721
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
1822
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
1923
import { ProviderAdapterV2RuntimePolicy } from "@t3tools/provider-core/server/ProviderAdapter";
@@ -115,6 +119,64 @@ const fxSession = (input: {
115119
modes: { currentModeId: "ask", availableModes: input.modes.map((id) => ({ id, name: id })) },
116120
});
117121

122+
const update = (sessionId: string, sessionUpdate: Record<string, unknown>): Frame => ({
123+
type: "emit_inbound",
124+
label: `session/update:${String(sessionUpdate.sessionUpdate)}`,
125+
frame: {
126+
kind: "notification",
127+
method: "session/update",
128+
params: { sessionId, update: sessionUpdate },
129+
},
130+
});
131+
/** A `libfx/hook` event as fx 0.0.15 sends it once a session opts in. */
132+
const hook = (sessionId: string, type: string, data: Record<string, unknown>): Frame => ({
133+
type: "emit_inbound",
134+
label: `libfx/hook:${type}`,
135+
frame: {
136+
kind: "notification",
137+
method: "libfx/hook",
138+
params: {
139+
version: 1,
140+
sessionId,
141+
rootSessionId: SESSION_ID,
142+
parentSessionId: sessionId === SESSION_ID ? null : SESSION_ID,
143+
sourceSessionId: null,
144+
workId: null,
145+
turnId: "turn-1",
146+
executionId: `execution-${sessionId}`,
147+
stepIndex: 1,
148+
timestamp: 1_793_283_383_907,
149+
type,
150+
data,
151+
contentCaptured: true,
152+
contentTruncated: false,
153+
},
154+
},
155+
});
156+
const subagentReply = (reply: string) =>
157+
JSON.stringify({ ok: true, result: reply, error_code: null });
158+
const subagentCall = (callId: string, task: string) =>
159+
update(SESSION_ID, {
160+
sessionUpdate: "tool_call",
161+
toolCallId: callId,
162+
name: "subagent",
163+
title: `Subagent · ${task}`,
164+
kind: "other",
165+
status: "pending",
166+
rawInput: { action: "run", task },
167+
_meta: { fx: { toolCall: { internal: false } } },
168+
});
169+
/** fx's 200-byte ACP preview of a finished `subagent` call. */
170+
const subagentPreview = (callId: string, reply: string) =>
171+
update(SESSION_ID, {
172+
sessionUpdate: "tool_call_update",
173+
toolCallId: callId,
174+
status: "completed",
175+
content: [
176+
{ type: "content", content: { type: "text", text: subagentReply(reply).slice(0, 199) } },
177+
],
178+
});
179+
118180
const initialize: ReadonlyArray<Frame> = [
119181
outbound("initialize"),
120182
answer("initialize", {
@@ -184,6 +246,7 @@ const openFxSession = Effect.fn("openFxSession")(function* (input: {
184246
),
185247
childProcessSpawner,
186248
fileSystem,
249+
sessionMeta: FX_HOOKS_SESSION_META,
187250
}),
188251
});
189252
const threadId = ThreadId.make(`thread-fx-${input.scenario}`);
@@ -199,15 +262,15 @@ const openFxSession = Effect.fn("openFxSession")(function* (input: {
199262
interactionMode: "default",
200263
cwd: replayDir,
201264
});
202-
yield* Effect.gen(function* () {
265+
const events = yield* Effect.gen(function* () {
203266
const session = yield* adapter.openSession({
204267
threadId,
205268
providerSessionId: ProviderSessionId.make(`provider-session-fx-${input.scenario}`),
206269
modelSelection,
207270
runtimePolicy,
208271
...(input.loadSessionId === undefined ? {} : { initialNativeThreadId: input.loadSessionId }),
209272
});
210-
if (input.turnModel === undefined) return;
273+
if (input.turnModel === undefined) return [];
211274
const providerThread = yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
212275
const now = yield* DateTime.now;
213276
const turnSelection = selectionOn(input.turnModel);
@@ -252,12 +315,13 @@ const openFxSession = Effect.fn("openFxSession")(function* (input: {
252315
modelSelection: turnSelection,
253316
runtimePolicy,
254317
});
255-
yield* session.events.pipe(
318+
return yield* session.events.pipe(
256319
Stream.takeUntil((event) => event.type === "turn.terminal"),
257-
Stream.runDrain,
320+
Stream.runCollect,
258321
);
259322
}).pipe(Effect.scoped);
260323
yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
324+
return events;
261325
});
262326

263327
describe("FxAdapterV2", () => {
@@ -273,7 +337,11 @@ describe("FxAdapterV2", () => {
273337
runtimeMode: "auto",
274338
frames: [
275339
...initialize,
276-
outbound("session/new", { cwd: "<workspace>", mcpServers: "<any>" }),
340+
outbound("session/new", {
341+
cwd: "<workspace>",
342+
mcpServers: "<any>",
343+
_meta: FX_HOOKS_SESSION_META,
344+
}),
277345
answer("session/new", fxSession({ model: FX_DEFAULT_MODEL, modes })),
278346
...setConfig(
279347
"mode",
@@ -365,4 +433,118 @@ describe("FxAdapterV2", () => {
365433
],
366434
}).pipe(Effect.provide(testLayer), Effect.scoped),
367435
);
436+
// A restart reloads the session: fx replays the finished call from history
437+
// with its 200-byte preview and none of the child's steps, which T3 already
438+
// holds. The reload confirms hooks, so the next sub-agent shows its steps.
439+
it.effect("leaves a reloaded sub-agent's thread alone and follows the next one", () =>
440+
Effect.gen(function* () {
441+
const earlierReply = `package.json names fx-hooks-fixture. ${"It has five scripts. ".repeat(12)}`;
442+
const reply = `tsconfig.json targets ES2023. ${"Strict mode is on. ".repeat(12)}`;
443+
const childSessionId = "fx-session-04";
444+
const events = yield* openFxSession({
445+
scenario: "reload-subagent",
446+
runtimeMode: "approval-required",
447+
loadSessionId: SESSION_ID,
448+
turnModel: "default",
449+
frames: [
450+
...initialize,
451+
outbound("session/load", {
452+
sessionId: SESSION_ID,
453+
cwd: "<workspace>",
454+
mcpServers: "<any>",
455+
_meta: FX_HOOKS_SESSION_META,
456+
}),
457+
update(SESSION_ID, {
458+
sessionUpdate: "user_message_chunk",
459+
content: { type: "text", text: "Spawn a subagent to read package.json" },
460+
}),
461+
subagentCall("call_earlier", "Read package.json"),
462+
subagentPreview("call_earlier", earlierReply),
463+
update(SESSION_ID, {
464+
sessionUpdate: "agent_message_chunk",
465+
content: { type: "text", text: "The subagent read package.json." },
466+
}),
467+
answer("session/load", {
468+
...fxSession({ model: FX_DEFAULT_MODEL, modes: FX_MAIN_MODES }),
469+
_meta: { fx: { hooksVersion: 1 } },
470+
}),
471+
...setConfig("mode", "ask", fxConfig({ model: FX_DEFAULT_MODEL, modes: FX_MAIN_MODES })),
472+
outbound("session/prompt"),
473+
subagentCall("call_next", "Read tsconfig.json"),
474+
hook(SESSION_ID, "delegation", {
475+
callId: "call_next",
476+
childSessionId,
477+
workId: "work-1",
478+
operationId: null,
479+
phase: "dispatched",
480+
}),
481+
hook(childSessionId, "tool.start", {
482+
call: {
483+
callId: "call_read",
484+
name: "read_file",
485+
provenance: "fx_local",
486+
argumentsJson: '{"path":"tsconfig.json"}',
487+
},
488+
rerun: false,
489+
}),
490+
hook(childSessionId, "tool.end", {
491+
call: {
492+
callId: "call_read",
493+
name: "read_file",
494+
provenance: "fx_local",
495+
argumentsJson: '{"path":"tsconfig.json"}',
496+
},
497+
output: '{"compilerOptions":{"target":"ES2023"}}',
498+
status: "success",
499+
error: null,
500+
}),
501+
hook(SESSION_ID, "delegation", {
502+
callId: "call_next",
503+
childSessionId,
504+
workId: "work-1",
505+
operationId: null,
506+
phase: "completed",
507+
}),
508+
subagentPreview("call_next", reply),
509+
hook(SESSION_ID, "tool.end", {
510+
call: { callId: "call_next", name: "subagent", provenance: "model" },
511+
output: subagentReply(reply),
512+
status: "success",
513+
error: null,
514+
}),
515+
answer("session/prompt", { stopReason: "end_turn" }),
516+
],
517+
});
518+
519+
const subagents = events.flatMap((event) =>
520+
event.type === "subagent.updated" ? [event.subagent] : [],
521+
);
522+
assert.deepEqual(
523+
[...new Set(subagents.map((subagent) => subagent.nativeTaskRef?.nativeId))],
524+
["call_next"],
525+
"the reload projects nothing for the earlier sub-agent",
526+
);
527+
assert.lengthOf(
528+
events.filter((event) => event.type === "app_thread.created"),
529+
1,
530+
);
531+
const settled = subagents.at(-1);
532+
assert.equal(settled?.status, "completed");
533+
assert.equal(settled?.result, reply);
534+
const childItems = events.flatMap((event) =>
535+
event.type === "turn_item.updated" && event.turnItem.threadId === settled?.childThreadId
536+
? [event.turnItem]
537+
: [],
538+
);
539+
assert.deepInclude(childItems.at(-1), { type: "assistant_message", text: reply });
540+
assert.isTrue(
541+
childItems.some(
542+
(item) =>
543+
item.type === "dynamic_tool" &&
544+
item.status === "completed" &&
545+
item.title === "Read tsconfig.json",
546+
),
547+
);
548+
}).pipe(Effect.provide(testLayer), Effect.scoped),
549+
);
368550
});

‎apps/server/src/orchestration-v2/Adapters/FxAdapterV2.testkit.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { FxSettings } from "@t3tools/provider-fx/settings";
33
import {
44
FX_ACP_CANCEL_BEHAVIOR,
55
FX_DRIVER_KIND,
6+
FX_HOOKS_SESSION_META,
67
makeFxAdapterV2,
78
} from "@t3tools/provider-fx/testing";
89
import { ProviderInstanceId } from "@t3tools/contracts";
@@ -64,6 +65,7 @@ function layerFxProviderAdapterRegistryReplay(
6465
childProcessSpawner,
6566
fileSystem,
6667
cancelBehavior: FX_ACP_CANCEL_BEHAVIOR,
68+
sessionMeta: FX_HOOKS_SESSION_META,
6769
...(replayGate === undefined ? {} : { replayGate }),
6870
})(runtimeInput),
6971
assertComplete: makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript),

0 commit comments

Comments
 (0)