The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 23:15 UTC
fix(acp-registry): enable Claude native background lifecycle (#21618)
Co-authored-by: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Julius Marminge committed
Oct 19, 2026 at 21:21 UTC
b1167b6ca20c19790694ca3552429b8868865285
4 files changed
+1399
-1
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+1242
@@ -1,13 +1,22 @@
1
import * as NodeServices from "@effect/platform-node/NodeServices";
2
import { assert, describe, it } from "@effect/vitest";
3
import {
4
+ MessageId,
5
+ NodeId,
6
+ ProjectId,
7
+ RunAttemptId,
8
+ RunId,
9
type ModelSelection,
10
ProviderInstanceId,
11
ProviderSessionId,
12
ThreadId,
13
} from "@t3tools/contracts";
14
+import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
15
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
16
+import * as Exit from "effect/Exit";
17
+import * as Fiber from "effect/Fiber";
18
import * as DateTime from "effect/DateTime";
19
+import * as Queue from "effect/Queue";
20
import * as Stream from "effect/Stream";
21
import * as Deferred from "effect/Deferred";
22
import * as Effect from "effect/Effect";
@@ -24,6 +33,11 @@ import * as EffectAcpErrors from "effect-acp/errors";
33
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
34
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
35
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
36
+import {
37
+ makeProviderReplayGate,
38
+ type ProviderReplayGate,
39
+} from "@t3tools/provider-testing/replayGate";
40
+import type { ProviderContinuationRequest } from "@t3tools/provider-core/server/ProviderContinuationRequests";
41
import * as ServerSettings from "../../serverSettings.ts";
42
import type {
43
AcpRegistryAvailableCommands,
@@ -106,6 +120,305 @@ const layerTest = Layer.mergeAll(
120
ServerSettings.layerTest(),
121
);
122
123
+const CLAUDE_ROOT_SESSION = "claude-session";
124
+
125
+/** Replay frames of Claude Agent (claude-agent-acp 0.90.0) on ACP v2. */
126
+const claudeFrames = {
127
+ open: [
128
+ { type: "expect_outbound", frame: { kind: "request", method: "initialize", params: "<any>" } },
129
+ {
130
+ type: "emit_inbound",
131
+ frame: {
132
+ kind: "response",
133
+ method: "initialize",
134
+ result: {
135
+ protocolVersion: 2,
136
+ info: { name: "@agentclientprotocol/claude-agent-acp", version: "0.90.0" },
137
+ capabilities: { session: {} },
138
+ authMethods: [],
139
+ },
140
+ },
141
+ },
142
+ { type: "expect_outbound", frame: { kind: "request", method: "session/new", params: "<any>" } },
143
+ {
144
+ type: "emit_inbound",
145
+ frame: {
146
+ kind: "response",
147
+ method: "session/new",
148
+ result: { sessionId: CLAUDE_ROOT_SESSION },
149
+ },
150
+ },
151
+ ],
152
+ update: (sessionId: string, sessionUpdate: Record<string, unknown>) => ({
153
+ type: "emit_inbound",
154
+ frame: {
155
+ kind: "notification",
156
+ method: "session/update",
157
+ params: { sessionId, update: sessionUpdate },
158
+ },
159
+ }),
160
+ childState: (parent: string, child: string, state: string) =>
161
+ claudeFrames.update(parent, {
162
+ sessionUpdate: "subagent_update",
163
+ sessionId: child,
164
+ state: { state },
165
+ }),
166
+ /** A prompt Claude takes in and works on. */
167
+ prompt: (ordinal: number) => [
168
+ {
169
+ type: "expect_outbound",
170
+ frame: { kind: "request", method: "session/prompt", params: "<any>" },
171
+ },
172
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
173
+ sessionUpdate: "user_message",
174
+ messageId: `user-${ordinal}`,
175
+ content: [{ type: "text", text: "test prompt" }],
176
+ }),
177
+ {
178
+ type: "emit_inbound",
179
+ frame: {
180
+ kind: "response",
181
+ method: "session/prompt",
182
+ result: { messageId: `user-${ordinal}` },
183
+ },
184
+ },
185
+ claudeFrames.update(CLAUDE_ROOT_SESSION, { sessionUpdate: "state_update", state: "running" }),
186
+ ],
187
+ idle: (stopReason: string) =>
188
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
189
+ sessionUpdate: "state_update",
190
+ state: "idle",
191
+ stopReason,
192
+ }),
193
+ closeRequest: {
194
+ type: "expect_outbound",
195
+ frame: {
196
+ kind: "request",
197
+ method: "session/close",
198
+ params: { sessionId: CLAUDE_ROOT_SESSION },
199
+ },
200
+ },
201
+ closed: {
202
+ type: "emit_inbound",
203
+ frame: { kind: "response", method: "session/close", result: {} },
204
+ },
205
+};
206
+
207
+const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
208
+ entries: ReadonlyArray<unknown>,
209
+ replayGate?: ProviderReplayGate,
210
+ continuationEnabled = true,
211
+) {
212
+ const fileSystem = yield* FileSystem.FileSystem;
213
+ const path = yield* Path.Path;
214
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
215
+ const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-lifecycle-" });
216
+ const transcript = yield* decodeAcpReplayTranscript(
217
+ {
218
+ provider: ACP_REGISTRY_PROVIDER,
219
+ protocol: "acp.ndjson-jsonrpc",
220
+ version: "1",
221
+ scenario: "claude-lifecycle",
222
+ entries: entries as never,
223
+ },
224
+ ACP_REGISTRY_PROVIDER,
225
+ );
226
+ const offers: Array<ProviderContinuationRequest> = [];
227
+ const offered = yield* Queue.unbounded<void>();
228
+ const continuationRequests = {
229
+ offer: (request: ProviderContinuationRequest) =>
230
+ Effect.sync(() => {
231
+ offers.push(request);
232
+ }).pipe(Effect.andThen(Queue.offer(offered, undefined)), Effect.asVoid),
233
+ };
234
+ const instanceId = ProviderInstanceId.make("claude-lifecycle");
235
+ let onTermination: NonNullable<
236
+ AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"]
237
+ > = () => Effect.die("Runtime has not started");
238
+ const replayRuntime = makeAcpReplayRuntime({
239
+ transcript,
240
+ statusPath: path.join(replayDir, "status.json"),
241
+ scriptPath: yield* path.fromFileUrl(
242
+ new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
243
+ ),
244
+ childProcessSpawner,
245
+ fileSystem,
246
+ ...(replayGate === undefined ? {} : { replayGate }),
247
+ });
248
+ const adapterOptions = {
249
+ selfInvocation: yield* resolveSelfInvocation(),
250
+ instanceId,
251
+ settings: yield* decodeAcpRegistryAdapterSettings({ agentId: "claude-acp" }),
252
+ environment: {},
253
+ ...(continuationEnabled ? { continuationRequests } : {}),
254
+ makeRuntime: (runtimeInput: Parameters<typeof replayRuntime>[0]) => {
255
+ onTermination = runtimeInput.onTermination;
256
+ return replayRuntime(runtimeInput);
257
+ },
258
+ };
259
+ const adapter = yield* makeAcpRegistryAdapterV2(adapterOptions).pipe(
260
+ Effect.provide(layerInjectedRuntimeCatalog),
261
+ );
262
+ const threadId = ThreadId.make("thread-claude-lifecycle");
263
+ const modelSelection = { instanceId, model: "default" } as const;
264
+ const runtimeMode = "approval-required";
265
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
266
+ runtimeMode,
267
+ interactionMode: "default",
268
+ cwd: replayDir,
269
+ });
270
+ const runtime = yield* adapter.openSession({
271
+ threadId,
272
+ providerSessionId: ProviderSessionId.make("session-claude-lifecycle"),
273
+ modelSelection,
274
+ runtimePolicy,
275
+ });
276
+ yield* Effect.addFinalizer(() => Effect.sync(() => replayGate?.releaseAll()));
277
+ if (continuationEnabled) {
278
+ assert.isDefined(
279
+ runtime.hasPendingBackgroundWork,
280
+ "Claude ACP v2 must report background work after foreground idle",
281
+ );
282
+ }
283
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
284
+ yield* runtime.events.pipe(
285
+ Stream.runForEach((event) => Queue.offer(events, event)),
286
+ Effect.forkScoped,
287
+ );
288
+ const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
289
+ const now = yield* DateTime.now;
290
+ const turnInput = (
291
+ ordinal: number,
292
+ options: { readonly continuation?: boolean } = {},
293
+ ): ProviderAdapter.ProviderAdapterV2TurnInput => ({
294
+ appThread: {
295
+ createdBy: "user",
296
+ creationSource: "web",
297
+ id: threadId,
298
+ projectId: ProjectId.make(`project-claude-lifecycle`),
299
+ title: "Claude Agent",
300
+ providerInstanceId: instanceId,
301
+ modelSelection,
302
+ runtimeMode,
303
+ interactionMode: "default",
304
+ branch: null,
305
+ worktreePath: null,
306
+ activeProviderThreadId: providerThread.id,
307
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
308
+ forkedFrom: null,
309
+ createdAt: now,
310
+ updatedAt: now,
311
+ archivedAt: null,
312
+ settledOverride: null,
313
+ settledAt: null,
314
+ lastVisitedAt: null,
315
+ deletedAt: null,
316
+ },
317
+ threadId,
318
+ runId: RunId.make(`run-claude-lifecycle-${ordinal}`),
319
+ runOrdinal: ordinal,
320
+ providerTurnOrdinal: ordinal,
321
+ attemptId: RunAttemptId.make(`attempt-claude-lifecycle-${ordinal}`),
322
+ rootNodeId: NodeId.make(`node-claude-lifecycle-${ordinal}`),
323
+ providerThread,
324
+ message: {
325
+ ...(options.continuation === true
326
+ ? { createdBy: "agent" as const, creationSource: "provider" as const }
327
+ : { createdBy: "user" as const, creationSource: "web" as const }),
328
+ messageId: MessageId.make(`message-claude-lifecycle-${ordinal}`),
329
+ text: "test prompt",
330
+ attachments: [],
331
+ },
332
+ modelSelection,
333
+ runtimePolicy,
334
+ });
335
+ const until = (predicate: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) =>
336
+ Effect.gen(function* () {
337
+ const seen: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
338
+ while (true) {
339
+ const event = yield* Queue.take(events);
340
+ seen.push(event);
341
+ if (predicate(event)) return seen;
342
+ }
343
+ });
344
+ const throughMarker = (title: string) =>
345
+ until(
346
+ (event) =>
347
+ event.type === "provider_thread.updated" &&
348
+ event.providerThread.nativeMetadata?.title === title,
349
+ );
350
+ const terminal = until((event) => event.type === "turn.terminal").pipe(
351
+ Effect.map((seen) => {
352
+ const event = seen.at(-1)!;
353
+ if (event.type !== "turn.terminal") throw new Error("Missing terminal");
354
+ return event;
355
+ }),
356
+ );
357
+ return {
358
+ runtime,
359
+ providerThread,
360
+ turnInput,
361
+ until,
362
+ throughMarker,
363
+ terminal,
364
+ offers,
365
+ offered,
366
+ terminate: () =>
367
+ onTermination(
368
+ new EffectAcpErrors.AcpTransportError({
369
+ detail: "Injected fixture process exit",
370
+ cause: "test",
371
+ }),
372
+ ),
373
+ };
374
+});
375
+
376
+const claudeMarker = (title: string) =>
377
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
378
+ sessionUpdate: "session_info_update",
379
+ title,
380
+ });
381
+const claudeChild = [
382
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
383
+ sessionUpdate: "tool_call_update",
384
+ toolCallId: "agent-1",
385
+ name: "Agent",
386
+ title: "Review",
387
+ kind: "think",
388
+ status: "in_progress",
389
+ rawInput: { prompt: "Review the code", description: "Review", run_in_background: true },
390
+ }),
391
+ claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "running"),
392
+ claudeFrames.update("child-1", {
393
+ sessionUpdate: "session_message",
394
+ messageId: "agent-1",
395
+ senderSessionId: CLAUDE_ROOT_SESSION,
396
+ recipientSessionId: "child-1",
397
+ content: [{ type: "text", text: "Review the code" }],
398
+ }),
399
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
400
+ sessionUpdate: "tool_call_update",
401
+ toolCallId: "agent-1",
402
+ status: "completed",
403
+ _meta: { claudeCode: { toolResponse: { isAsync: true } } },
404
+ }),
405
+];
406
+
407
+const claudeUnrelatedChildren = [
408
+ claudeFrames.childState("unknown-parent", "unrelated-child", "running"),
409
+ claudeFrames.update("unrelated-child", {
410
+ sessionUpdate: "session_message",
411
+ messageId: "agent-1",
412
+ senderSessionId: "unknown-parent",
413
+ content: [{ type: "text", text: "Unrelated delegation" }],
414
+ }),
415
+ claudeFrames.update("unlinked-child", {
416
+ sessionUpdate: "agent_message_chunk",
417
+ messageId: "unlinked-reply",
418
+ content: { type: "text", text: "Unlinked output" },
419
+ }),
420
+];
421
+
422
describe("AcpRegistryAdapterV2", () => {
423
it("preserves and sanitizes structured ACP errors without exposing arbitrary defects", () => {
424
const limit = new EffectAcpErrors.AcpRequestError({
@@ -685,6 +998,935 @@ describe("AcpRegistryAdapterV2", () => {
998
}).pipe(Effect.provide(layerTest), Effect.scoped),
999
);
1000
1001
+ it.effect("launches Claude Agent on ACP v2 unless its instance environment decides", () =>
1002
+ Effect.gen(function* () {
1003
+ const launchSwitch = Effect.fn("launchSwitch")(function* (
1004
+ config: Record<string, unknown>,
1005
+ environment: NodeJS.ProcessEnv = {},
1006
+ ) {
1007
+ let launched: NodeJS.ProcessEnv | undefined;
1008
+ const instanceId = ProviderInstanceId.make("acp-registry-launch-environment");
1009
+ const adapter = yield* makeAcpRegistryAdapterV2({
1010
+ selfInvocation: yield* resolveSelfInvocation(),
1011
+ instanceId,
1012
+ settings: yield* decodeAcpRegistryAdapterSettings(config),
1013
+ environment,
1014
+ }).pipe(
1015
+ Effect.provide(
1016
+ Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({
1017
+ resolve: (_settings, _cwd, launchEnvironment) => {
1018
+ launched = launchEnvironment;
1019
+ return Effect.fail(
1020
+ new AcpRegistrySupport.AcpRegistryError({
1021
+ reason: "runner_unavailable",
1022
+ detail: "Recorded the launch environment.",
1023
+ }),
1024
+ );
1025
+ },
1026
+ }),
1027
+ ),
1028
+ );
1029
+ yield* adapter
1030
+ .openSession({
1031
+ threadId: ThreadId.make("thread-acp-registry-launch-environment"),
1032
+ providerSessionId: ProviderSessionId.make("provider-session-launch-environment"),
1033
+ modelSelection: { instanceId, model: "default" },
1034
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1035
+ runtimeMode: "full-access",
1036
+ interactionMode: "default",
1037
+ cwd: process.cwd(),
1038
+ }),
1039
+ })
1040
+ .pipe(Effect.flip);
1041
+ return launched?.CLAUDE_AGENT_ACP_EXPERIMENTAL_V2;
1042
+ });
1043
+
1044
+ assert.equal(yield* launchSwitch({ agentId: "claude-acp" }), "1");
1045
+ assert.equal(
1046
+ yield* launchSwitch(
1047
+ { source: "local", commandPath: "/opt/bin/claude-agent-acp" },
1048
+ { PATH: "/opt/bin" },
1049
+ ),
1050
+ "1",
1051
+ );
1052
+ assert.equal(
1053
+ yield* launchSwitch({ agentId: "claude-acp" }, { CLAUDE_AGENT_ACP_EXPERIMENTAL_V2: "0" }),
1054
+ "0",
1055
+ );
1056
+ assert.isUndefined(yield* launchSwitch({ agentId: "gemini" }));
1057
+ const fallback = yield* openClaudeReplaySession(
1058
+ [
1059
+ ...claudeFrames.open,
1060
+ claudeFrames.prompt(1)[0],
1061
+ claudeChild[0],
1062
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
1063
+ sessionUpdate: "tool_call_update",
1064
+ toolCallId: "agent-1",
1065
+ status: "completed",
1066
+ }),
1067
+ ...claudeFrames.prompt(1).slice(1),
1068
+ claudeFrames.idle("end_turn"),
1069
+ claudeFrames.closeRequest,
1070
+ claudeFrames.closed,
1071
+ ],
1072
+ undefined,
1073
+ false,
1074
+ );
1075
+ assert.isUndefined(
1076
+ fallback.runtime.hasPendingBackgroundWork,
1077
+ "an adapter without a continuation dispatcher must use ordinary prompt completion",
1078
+ );
1079
+ yield* fallback.runtime.startTurn(fallback.turnInput(1));
1080
+ const completed = yield* fallback.until((event) => event.type === "turn.terminal");
1081
+ assert.isTrue(
1082
+ completed.some(
1083
+ (event) =>
1084
+ event.type === "turn_item.updated" &&
1085
+ event.turnItem.type === "dynamic_tool" &&
1086
+ event.turnItem.nativeItemRef?.nativeId === "agent-1",
1087
+ ),
1088
+ );
1089
+ const terminal = completed.at(-1)!;
1090
+ if (terminal.type !== "turn.terminal") throw new Error("Missing fallback terminal");
1091
+ assert.equal(terminal.status, "completed");
1092
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
1093
+ );
1094
+
1095
+ it.effect("settles Claude's accepted foreground reply while retaining child output", () =>
1096
+ Effect.gen(function* () {
1097
+ const gate = makeProviderReplayGate(["accepted", "child-output", "wake"]);
1098
+ const { update, idle, prompt } = claudeFrames;
1099
+ const session = yield* openClaudeReplaySession(
1100
+ [
1101
+ ...claudeFrames.open,
1102
+ prompt(1)[0],
1103
+ idle("end_turn"),
1104
+ claudeMarker("before acceptance"),
1105
+ { ...prompt(1)[1], label: "accepted" },
1106
+ ...prompt(1).slice(2),
1107
+ update(CLAUDE_ROOT_SESSION, {
1108
+ sessionUpdate: "tool_call_update",
1109
+ toolCallId: "agent-1",
1110
+ name: "Agent",
1111
+ title: "Review",
1112
+ kind: "think",
1113
+ status: "pending",
1114
+ rawInput: { description: "Review" },
1115
+ }),
1116
+ update(CLAUDE_ROOT_SESSION, {
1117
+ sessionUpdate: "tool_call_update",
1118
+ toolCallId: "malformed-agent",
1119
+ name: "Agent",
1120
+ title: "Incomplete agent",
1121
+ kind: "think",
1122
+ status: "pending",
1123
+ rawInput: { description: "Never receives a prompt" },
1124
+ }),
1125
+ update(CLAUDE_ROOT_SESSION, {
1126
+ sessionUpdate: "tool_call_update",
1127
+ toolCallId: "failed-task",
1128
+ name: "Task",
1129
+ title: "Malformed task",
1130
+ kind: "think",
1131
+ status: "failed",
1132
+ rawInput: { description: "Missing prompt" },
1133
+ }),
1134
+ ...claudeChild.slice(0, 2),
1135
+ update("child-1", {
1136
+ sessionUpdate: "agent_message_chunk",
1137
+ messageId: "early-reply",
1138
+ content: { type: "text", text: "First review result." },
1139
+ }),
1140
+ claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
1141
+ ...claudeChild.slice(2),
1142
+ update("child-1", { sessionUpdate: "state_update", state: "running" }),
1143
+ ...claudeUnrelatedChildren,
1144
+ update(CLAUDE_ROOT_SESSION, {
1145
+ sessionUpdate: "agent_message_chunk",
1146
+ messageId: "reply",
1147
+ content: { type: "text", text: "The review is running." },
1148
+ }),
1149
+ idle("end_turn"),
1150
+ {
1151
+ ...update("child-1", {
1152
+ sessionUpdate: "agent_message_chunk",
1153
+ messageId: "child-reply",
1154
+ content: { type: "text", text: "Found the regression." },
1155
+ }),
1156
+ label: "child-output",
1157
+ },
1158
+ update("child-1", {
1159
+ sessionUpdate: "usage_update",
1160
+ used: 2_500,
1161
+ size: 10_000,
1162
+ cost: { amount: 0.42, currency: "USD" },
1163
+ }),
1164
+ update("child-1", {
1165
+ sessionUpdate: "session_info_update",
1166
+ title: "Child review",
1167
+ updatedAt: "2026-10-19T00:00:00Z",
1168
+ }),
1169
+ update("child-1", {
1170
+ sessionUpdate: "state_update",
1171
+ state: "idle",
1172
+ stopReason: "end_turn",
1173
+ usage: { totalTokens: 3_000, inputTokens: 2_500, outputTokens: 500, thoughtTokens: 0 },
1174
+ }),
1175
+ claudeMarker("child output"),
1176
+ {
1177
+ ...update(CLAUDE_ROOT_SESSION, {
1178
+ sessionUpdate: "user_message",
1179
+ messageId: "wake-user",
1180
+ content: [{ type: "text", text: "Continue the review." }],
1181
+ }),
1182
+ label: "wake",
1183
+ },
1184
+ idle("end_turn"),
1185
+ claudeMarker("continuation idle"),
1186
+ claudeFrames.closeRequest,
1187
+ claudeFrames.closed,
1188
+ ],
1189
+ gate,
1190
+ );
1191
+ yield* session.runtime.startTurn(session.turnInput(1));
1192
+ const beforeAcceptance = yield* session.throughMarker("before acceptance");
1193
+ assert.isFalse(beforeAcceptance.some((event) => event.type === "turn.terminal"));
1194
+ gate.release("accepted");
1195
+ const foreground = yield* session.until((event) => event.type === "turn.terminal");
1196
+ const foregroundTerminal = foreground.at(-1)!;
1197
+ if (foregroundTerminal.type !== "turn.terminal")
1198
+ throw new Error("Missing foreground terminal");
1199
+ assert.equal(foregroundTerminal.status, "completed");
1200
+ const earlyResult = foreground.findLast(
1201
+ (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
1202
+ );
1203
+ assert.isDefined(earlyResult, "a child can finish before its spawn acknowledgement");
1204
+ if (earlyResult?.type !== "subagent.updated") throw new Error("Missing early result");
1205
+ assert.equal(earlyResult.subagent.result, "First review result.");
1206
+ const earlyItem = foreground.findLast(
1207
+ (event) =>
1208
+ event.type === "turn_item.updated" &&
1209
+ event.turnItem.type === "subagent" &&
1210
+ event.turnItem.status === "completed",
1211
+ );
1212
+ if (earlyItem?.type !== "turn_item.updated" || earlyItem.turnItem.type !== "subagent")
1213
+ throw new Error("Missing early parent item");
1214
+ assert.equal(earlyItem.turnItem.result, "First review result.");
1215
+ assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
1216
+ gate.release("child-output");
1217
+ const childOutput = yield* session.throughMarker("child output");
1218
+ const message = childOutput.find(
1219
+ (event) =>
1220
+ event.type === "message.updated" && event.message.text === "Found the regression.",
1221
+ );
1222
+ assert.isDefined(message, "child output survives foreground completion");
1223
+ if (message?.type !== "message.updated") throw new Error("Missing child output");
1224
+ assert.notEqual(message.message.threadId, session.turnInput(1).threadId);
1225
+ const childThreads = childOutput.flatMap((event) =>
1226
+ event.type === "provider_thread.updated" &&
1227
+ event.providerThread.appThreadId === message.message.threadId
1228
+ ? [event.providerThread]
1229
+ : [],
1230
+ );
1231
+ assert.deepEqual(
1232
+ childThreads.map((thread) => thread.contextUsage),
1233
+ [
1234
+ { usedTokens: 2_500, maxTokens: 10_000, cost: { amount: 0.42, currency: "USD" } },
1235
+ { usedTokens: 2_500, maxTokens: 10_000, cost: { amount: 0.42, currency: "USD" } },
1236
+ { usedTokens: 3_000 },
1237
+ ],
1238
+ );
1239
+ assert.deepEqual(childThreads.at(-1)?.nativeMetadata, {
1240
+ title: "Child review",
1241
+ updatedAt: "2026-10-19T00:00:00Z",
1242
+ });
1243
+ assert.isFalse(childOutput.some((event) => event.type === "turn.terminal"));
1244
+ assert.isTrue(
1245
+ childOutput.some(
1246
+ (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
1247
+ ),
1248
+ );
1249
+ const latestChild = childOutput.findLast((event) => event.type === "subagent.updated");
1250
+ if (latestChild?.type !== "subagent.updated") throw new Error("Missing current child result");
1251
+ assert.equal(latestChild.subagent.result, "Found the regression.");
1252
+ const rootItems = new Map(
1253
+ [...foreground, ...childOutput].flatMap((event) =>
1254
+ event.type === "turn_item.updated" &&
1255
+ event.turnItem.threadId === session.turnInput(1).threadId
1256
+ ? [[event.turnItem.id, event.turnItem] as const]
1257
+ : [],
1258
+ ),
1259
+ );
1260
+ const generic = [...rootItems.values()].filter((item) => item.type === "dynamic_tool");
1261
+ assert.isFalse(
1262
+ generic.some((item) => item.nativeItemRef?.nativeId === "agent-1"),
1263
+ "native subagents never project a duplicate generic tool",
1264
+ );
1265
+ const malformed = generic.find((item) => item.nativeItemRef?.nativeId === "malformed-agent");
1266
+ assert.isDefined(malformed, "unclassified tools still project on foreground completion");
1267
+ assert.equal(malformed?.status, "completed");
1268
+ const failed = generic.find((item) => item.nativeItemRef?.nativeId === "failed-task");
1269
+ assert.isDefined(failed, "unclassified terminal tools retain ordinary failures");
1270
+ assert.equal(failed?.status, "failed");
1271
+ assert.isFalse(
1272
+ [...rootItems.values()].some((item) => item.type === "user_message"),
1273
+ "the submitted root prompt is already owned by the app",
1274
+ );
1275
+ assert.deepEqual(pendingBackgroundTurnItems({ turnItems: [...rootItems.values()] }), []);
1276
+ assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
1277
+ gate.release("wake");
1278
+ yield* Queue.take(session.offered);
1279
+ yield* session.throughMarker("continuation idle");
1280
+ const offer = session.offers[0]!;
1281
+ yield* offer.dispatchIfCurrent!(Effect.void);
1282
+ yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
1283
+ const continuation = yield* session.until((event) => event.type === "turn.terminal");
1284
+ const terminal = continuation.at(-1)!;
1285
+ if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal");
1286
+ assert.equal(
1287
+ terminal.status,
1288
+ "completed",
1289
+ "buffered acceptance preserves the latest live idle",
1290
+ );
1291
+ assert.isFalse(
1292
+ continuation.some(
1293
+ (event) => event.type === "turn_item.updated" && event.turnItem.type === "user_message",
1294
+ ),
1295
+ "autonomous root echoes only signal acceptance",
1296
+ );
1297
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
1298
+ );
1299
+
1300
+ it.effect.each([
1301
+ { kind: "approval", stopReason: "end_turn", status: "completed" },
1302
+ { kind: "question", stopReason: "error", status: "failed" },
1303
+ ] as const)("continues Claude's background $kind and preserves $status idle", (testCase) =>
1304
+ Effect.gen(function* () {
1305
+ const gate = makeProviderReplayGate(["wake", "stop-request", "refused-response"]);
1306
+ const method =
1307
+ testCase.kind === "approval" ? "session/request_permission" : "elicitation/create";
1308
+ const params =
1309
+ testCase.kind === "approval"
1310
+ ? {
1311
+ sessionId: "child-1",
1312
+ title: "Run tests?",
1313
+ subject: {
1314
+ type: "tool_call",
1315
+ toolCall: {
1316
+ toolCallId: "test-command",
1317
+ name: "Bash",
1318
+ title: "Run tests",
1319
+ kind: "execute",
1320
+ status: "pending",
1321
+ rawInput: { command: "vp test run" },
1322
+ },
1323
+ },
1324
+ options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
1325
+ }
1326
+ : {
1327
+ sessionId: "child-1",
1328
+ mode: "form",
1329
+ message: "Which file?",
1330
+ requestedSchema: {
1331
+ type: "object",
1332
+ properties: { file: { type: "string", title: "File", enum: ["a.ts", "b.ts"] } },
1333
+ required: ["file"],
1334
+ },
1335
+ };
1336
+ const session = yield* openClaudeReplaySession(
1337
+ [
1338
+ ...claudeFrames.open,
1339
+ ...claudeFrames.prompt(1),
1340
+ ...claudeChild,
1341
+ claudeFrames.idle("end_turn"),
1342
+ {
1343
+ ...claudeFrames.update(CLAUDE_ROOT_SESSION, {
1344
+ sessionUpdate: "state_update",
1345
+ state: "running",
1346
+ }),
1347
+ label: "wake",
1348
+ },
1349
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
1350
+ sessionUpdate: "user_message",
1351
+ messageId: "wake-user",
1352
+ content: [{ type: "text", text: "Continue the review." }],
1353
+ }),
1354
+ claudeFrames.closeRequest,
1355
+ { type: "emit_inbound", frame: { kind: "request", method, params } },
1356
+ {
1357
+ type: "emit_inbound",
1358
+ label: "refused-response",
1359
+ frame: {
1360
+ kind: "response",
1361
+ method: "session/close",
1362
+ error: { code: -32603, message: "Close refused" },
1363
+ },
1364
+ },
1365
+ {
1366
+ type: "expect_outbound",
1367
+ frame: {
1368
+ kind: "response",
1369
+ method,
1370
+ result:
1371
+ testCase.kind === "approval"
1372
+ ? { outcome: { outcome: "selected", optionId: "allow" } }
1373
+ : { action: "accept", content: { file: "a.ts" } },
1374
+ },
1375
+ },
1376
+ claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
1377
+ ...claudeUnrelatedChildren,
1378
+ claudeFrames.update(CLAUDE_ROOT_SESSION, {
1379
+ sessionUpdate: "state_update",
1380
+ state: "idle",
1381
+ stopReason: testCase.stopReason,
1382
+ ...(testCase.status === "failed"
1383
+ ? { error: { code: -32603, message: "API Error: 529 overloaded" } }
1384
+ : {}),
1385
+ }),
1386
+ {
1387
+ type: "emit_inbound",
1388
+ label: "stop-request",
1389
+ frame: { kind: "request", method, params },
1390
+ },
1391
+ claudeFrames.closeRequest,
1392
+ claudeFrames.closed,
1393
+ {
1394
+ type: "expect_outbound",
1395
+ frame: {
1396
+ kind: "response",
1397
+ method,
1398
+ result:
1399
+ testCase.kind === "approval"
1400
+ ? { outcome: { outcome: "cancelled" } }
1401
+ : { action: "cancel" },
1402
+ },
1403
+ },
1404
+ claudeMarker("detached request cancelled"),
1405
+ ],
1406
+ gate,
1407
+ );
1408
+ yield* session.runtime.startTurn(session.turnInput(1));
1409
+ assert.equal((yield* session.terminal).status, "completed");
1410
+ assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
1411
+ gate.release("wake");
1412
+ yield* Queue.take(session.offered);
1413
+ const offer = session.offers[0]!;
1414
+ assert.isDefined(offer.dispatchIfCurrent);
1415
+ yield* offer.dispatchIfCurrent!(Effect.void);
1416
+ yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
1417
+ const started = yield* session.until(
1418
+ (event) =>
1419
+ event.type === "provider_turn.updated" && event.providerTurn.status === "running",
1420
+ );
1421
+ const running = started.at(-1)!;
1422
+ if (running.type !== "provider_turn.updated") throw new Error("Missing active continuation");
1423
+ const closing = yield* session.runtime
1424
+ .interruptTurn({
1425
+ providerThread: session.providerThread,
1426
+ providerTurnId: running.providerTurn.id,
1427
+ requestRuntimeRestart: true,
1428
+ })
1429
+ .pipe(Effect.exit, Effect.forkScoped);
1430
+ yield* Effect.addFinalizer(() => Effect.sync(() => gate.releaseAll()));
1431
+ const seen = yield* session.until(
1432
+ (event) =>
1433
+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
1434
+ );
1435
+ assert.isFalse(
1436
+ seen.some(
1437
+ (event) => event.type === "turn_item.updated" && event.turnItem.type === "user_message",
1438
+ ),
1439
+ );
1440
+ const request = seen.at(-1)!;
1441
+ if (request.type !== "runtime_request.updated") throw new Error("Missing request");
1442
+ assert.isTrue(
1443
+ seen.some(
1444
+ (event) =>
1445
+ event.type === "node.updated" &&
1446
+ event.node.id === request.runtimeRequest.nodeId &&
1447
+ event.node.runId === session.turnInput(2).runId,
1448
+ ),
1449
+ );
1450
+ yield* Effect.promise(() => gate.waitForReached("refused-response"));
1451
+ gate.release("refused-response");
1452
+ assert.isTrue(Exit.isFailure(yield* Fiber.join(closing)));
1453
+ assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
1454
+ yield* session.runtime.respondToRuntimeRequest({
1455
+ requestId: request.runtimeRequest.id,
1456
+ ...(testCase.kind === "approval"
1457
+ ? { decision: "accept" as const }
1458
+ : { answers: { file: "a.ts" } }),
1459
+ });
1460
+ const terminal = yield* session.terminal;
1461
+ assert.equal(terminal.status, testCase.status);
1462
+ if (terminal.status === "failed") {
1463
+ assert.include(terminal.failure?.message ?? "", "529 overloaded");
1464
+ assert.isUndefined(terminal.childTurnsContinue);
1465
+ assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
1466
+ }
1467
+ gate.release("stop-request");
1468
+ yield* Queue.take(session.offered);
1469
+ yield* session.runtime.interruptTurn({
1470
+ providerThread: session.providerThread,
1471
+ providerTurnId: terminal.providerTurnId,
1472
+ requestRuntimeRestart: true,
1473
+ });
1474
+ const cancelled = yield* session.throughMarker("detached request cancelled");
1475
+ assert.isFalse(
1476
+ cancelled.some(
1477
+ (event) =>
1478
+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
1479
+ ),
1480
+ "detached requests are cancelled before turn admission",
1481
+ );
1482
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
1483
+ );
1484
+
1485
+ it.effect.each(["error", "end_turn"])(
1486
+ "hands live Claude child tools to the next run after %s and keeps nested output in the child",
1487
+ (stopReason) =>
1488
+ Effect.gen(function* () {
1489
+ const { update, childState, idle, prompt } = claudeFrames;
1490
+ const gate = makeProviderReplayGate(["nested-output", "nested-idle"]);
1491
+ const session = yield* openClaudeReplaySession(
1492
+ [
1493
+ ...claudeFrames.open,
1494
+ ...prompt(1),
1495
+ update(CLAUDE_ROOT_SESSION, {
1496
+ sessionUpdate: "tool_call_update",
1497
+ toolCallId: "agent-1",
1498
+ name: "Agent",
1499
+ title: "Review",
1500
+ kind: "think",
1501
+ status: "in_progress",
1502
+ rawInput: { prompt: "Review the code", description: "Review" },
1503
+ }),
1504
+ ...claudeChild.slice(1, -1),
1505
+ update("child-1", {
1506
+ sessionUpdate: "tool_call_update",
1507
+ toolCallId: "child-tool",
1508
+ name: "Bash",
1509
+ title: "Read package",
1510
+ kind: "execute",
1511
+ status: "in_progress",
1512
+ rawInput: { command: "cat package.json" },
1513
+ }),
1514
+ update("child-1", {
1515
+ sessionUpdate: "agent_message_chunk",
1516
+ messageId: "progress",
1517
+ content: { type: "text", text: "Review in progress." },
1518
+ }),
1519
+ idle(stopReason),
1520
+ ...prompt(2),
1521
+ childState(CLAUDE_ROOT_SESSION, "child-1", "running"),
1522
+ update("child-1", {
1523
+ sessionUpdate: "session_message",
1524
+ messageId: "resume-child",
1525
+ senderSessionId: CLAUDE_ROOT_SESSION,
1526
+ recipientSessionId: "child-1",
1527
+ content: [{ type: "text", text: "Continue the review." }],
1528
+ }),
1529
+ claudeMarker("resumed"),
1530
+ childState("child-1", "grandchild", "running"),
1531
+ childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
1532
+ update(CLAUDE_ROOT_SESSION, {
1533
+ sessionUpdate: "tool_call_update",
1534
+ toolCallId: "agent-1",
1535
+ name: "Agent",
1536
+ status: "completed",
1537
+ rawInput: { prompt: "Review the code", description: "Review" },
1538
+ }),
1539
+ idle("end_turn"),
1540
+ {
1541
+ ...update("grandchild", {
1542
+ sessionUpdate: "terminal_update",
1543
+ terminalId: "nested-terminal",
1544
+ command: "/usr/bin/node /srv/t3/bin.ts acp-mcp-call orchestrator_capabilities {}",
1545
+ }),
1546
+ label: "nested-output",
1547
+ },
1548
+ update("grandchild", {
1549
+ sessionUpdate: "terminal_output_chunk",
1550
+ terminalId: "nested-terminal",
1551
+ data: Buffer.from("{}\n").toString("base64"),
1552
+ }),
1553
+ update("grandchild", {
1554
+ sessionUpdate: "terminal_update",
1555
+ terminalId: "nested-terminal",
1556
+ exitStatus: { exitCode: 0 },
1557
+ }),
1558
+ update("grandchild", {
1559
+ sessionUpdate: "tool_call_update",
1560
+ toolCallId: "terminal-tool",
1561
+ name: "Bash",
1562
+ title: "Run nested command",
1563
+ kind: "execute",
1564
+ status: "in_progress",
1565
+ content: [{ type: "terminal", terminalId: "nested-terminal" }],
1566
+ }),
1567
+ update("grandchild", {
1568
+ sessionUpdate: "tool_call_update",
1569
+ toolCallId: "nested-tool",
1570
+ name: "Bash",
1571
+ title: "Read nested package",
1572
+ kind: "execute",
1573
+ status: "in_progress",
1574
+ rawInput: { command: "cat nested/package.json" },
1575
+ }),
1576
+ update("grandchild", {
1577
+ sessionUpdate: "agent_message_chunk",
1578
+ messageId: "nested-reply",
1579
+ content: { type: "text", text: "Nested output" },
1580
+ }),
1581
+ update(CLAUDE_ROOT_SESSION, {
1582
+ sessionUpdate: "user_message",
1583
+ messageId: "nested-wake",
1584
+ content: [{ type: "text", text: "Continue the review." }],
1585
+ }),
1586
+ idle("end_turn"),
1587
+ claudeMarker("nested"),
1588
+ {
1589
+ ...childState("child-1", "grandchild", "idle"),
1590
+ label: "nested-idle",
1591
+ },
1592
+ claudeMarker("nested idle"),
1593
+ ...prompt(4),
1594
+ update("child-1", {
1595
+ sessionUpdate: "session_message",
1596
+ messageId: "second-review",
1597
+ senderSessionId: CLAUDE_ROOT_SESSION,
1598
+ recipientSessionId: "child-1",
1599
+ content: [{ type: "text", text: "Review the fix." }],
1600
+ }),
1601
+ childState(CLAUDE_ROOT_SESSION, "child-1", "running"),
1602
+ update("child-1", {
1603
+ sessionUpdate: "agent_message_chunk",
1604
+ messageId: "nested-reply",
1605
+ content: { type: "text", text: "The fix is correct." },
1606
+ }),
1607
+ childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
1608
+ idle("end_turn"),
1609
+ claudeFrames.closeRequest,
1610
+ claudeFrames.closed,
1611
+ ],
1612
+ gate,
1613
+ );
1614
+ yield* session.runtime.startTurn(session.turnInput(1));
1615
+ const settled = yield* session.terminal;
1616
+ assert.equal(settled.status, stopReason === "error" ? "failed" : "completed");
1617
+ if (settled.status === "failed") assert.isTrue(settled.childTurnsContinue);
1618
+ yield* session.runtime.startTurn(session.turnInput(2));
1619
+ const resumed = yield* session.throughMarker("resumed");
1620
+ const row = resumed.find((event) => event.type === "subagent.updated");
1621
+ assert.isDefined(row);
1622
+ if (row?.type !== "subagent.updated") throw new Error("Missing resumed child");
1623
+ assert.equal(row.subagent.runId, session.turnInput(2).runId);
1624
+ assert.equal(
1625
+ row.subagent.result,
1626
+ "Review in progress.",
1627
+ "live handoff retains current execution progress",
1628
+ );
1629
+ assert.lengthOf(
1630
+ resumed.filter(
1631
+ (event) =>
1632
+ event.type === "message.updated" &&
1633
+ event.message.threadId === row.subagent.childThreadId &&
1634
+ event.message.role === "user" &&
1635
+ event.message.text === "Continue the review.",
1636
+ ),
1637
+ 1,
1638
+ "child resume prompts remain visible once",
1639
+ );
1640
+ const openTools = resumed.filter(
1641
+ (event) =>
1642
+ event.type === "turn_item.updated" &&
1643
+ event.turnItem.type === "dynamic_tool" &&
1644
+ event.turnItem.status === "running",
1645
+ );
1646
+ assert.lengthOf(openTools, 1, "handoff announces each open child tool once");
1647
+ const foreground = yield* session.until((event) => event.type === "turn.terminal");
1648
+ assert.isTrue(
1649
+ foreground.some(
1650
+ (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
1651
+ ),
1652
+ "the foreground Agent tool terminalizes its visible owner",
1653
+ );
1654
+ assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
1655
+ gate.release("nested-output");
1656
+ const childOutput = yield* session.throughMarker("nested");
1657
+ yield* Queue.take(session.offered);
1658
+ assert.lengthOf(session.offers, 1);
1659
+ yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
1660
+ yield* session.runtime.startTurn(session.turnInput(3, { continuation: true }));
1661
+ const continued = yield* session.until((event) => event.type === "turn.terminal");
1662
+ const terminal = continued.at(-1)!;
1663
+ if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal");
1664
+ assert.equal(terminal.status, "completed");
1665
+ const nested = [...childOutput, ...continued];
1666
+ const messages = nested.filter(
1667
+ (event) => event.type === "message.updated" && event.message.text === "Nested output",
1668
+ );
1669
+ assert.lengthOf(messages, 1);
1670
+ if (messages[0]?.type === "message.updated") {
1671
+ assert.equal(messages[0].message.threadId, row.subagent.childThreadId);
1672
+ }
1673
+ const nestedTool = nested.find(
1674
+ (event) =>
1675
+ event.type === "turn_item.updated" &&
1676
+ event.turnItem.type === "dynamic_tool" &&
1677
+ event.turnItem.nativeItemRef?.nativeId ===
1678
+ "agent-1:session:grandchild:tool:nested-tool",
1679
+ );
1680
+ assert.isDefined(nestedTool);
1681
+ if (nestedTool?.type === "turn_item.updated") {
1682
+ assert.equal(nestedTool.turnItem.threadId, row.subagent.childThreadId);
1683
+ if (nestedTool.turnItem.type === "dynamic_tool")
1684
+ assert.deepEqual(nestedTool.turnItem.input, { command: "cat nested/package.json" });
1685
+ }
1686
+ assert.isTrue(
1687
+ nested.some(
1688
+ (event) =>
1689
+ event.type === "turn_item.updated" &&
1690
+ event.turnItem.type === "dynamic_tool" &&
1691
+ event.turnItem.nativeItemRef?.nativeId ===
1692
+ "agent-1:session:grandchild:tool:terminal-tool" &&
1693
+ event.turnItem.threadId === row.subagent.childThreadId &&
1694
+ event.turnItem.toolName === "t3-code.orchestrator_capabilities",
1695
+ ),
1696
+ "embedded agent-terminal commands preserve nested MCP identity",
1697
+ );
1698
+ assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
1699
+ gate.release("nested-idle");
1700
+ const finished = yield* session.throughMarker("nested idle");
1701
+ assert.isTrue(
1702
+ finished.some(
1703
+ (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
1704
+ ),
1705
+ );
1706
+ assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
1707
+ assert.lengthOf(session.offers, 1, "nested frames make progress in one continuation");
1708
+ const firstResult = finished.findLast((event) => event.type === "subagent.updated");
1709
+ if (firstResult?.type !== "subagent.updated")
1710
+ throw new Error("Missing first review result");
1711
+ assert.equal(
1712
+ firstResult.subagent.result,
1713
+ "Review in progress.",
1714
+ "reopening the visible owner for a running descendant keeps its execution result",
1715
+ );
1716
+ yield* session.runtime.startTurn(session.turnInput(4));
1717
+ const reviewed = yield* session.until((event) => event.type === "turn.terminal");
1718
+ const currentResult = reviewed.findLast((event) => event.type === "subagent.updated");
1719
+ if (currentResult?.type !== "subagent.updated")
1720
+ throw new Error("Missing second review result");
1721
+ assert.equal(currentResult.subagent.id, row.subagent.id);
1722
+ assert.equal(currentResult.subagent.childThreadId, row.subagent.childThreadId);
1723
+ assert.equal(currentResult.subagent.result, "The fix is correct.");
1724
+ const currentItem = reviewed.findLast(
1725
+ (event) => event.type === "turn_item.updated" && event.turnItem.type === "subagent",
1726
+ );
1727
+ if (currentItem?.type !== "turn_item.updated" || currentItem.turnItem.type !== "subagent")
1728
+ throw new Error("Missing current parent item");
1729
+ assert.equal(currentItem.turnItem.result, "The fix is correct.");
1730
+ assert.lengthOf(
1731
+ reviewed.filter(
1732
+ (event) =>
1733
+ event.type === "message.updated" && event.message.text === "The fix is correct.",
1734
+ ),
1735
+ 1,
1736
+ "a new execution does not append the previous execution's text",
1737
+ );
1738
+ assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
1739
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
1740
+ );
1741
+
1742
+ it.effect("fails active Claude work and releases its children when the process exits", () =>
1743
+ Effect.gen(function* () {
1744
+ const session = yield* openClaudeReplaySession([
1745
+ ...claudeFrames.open,
1746
+ ...claudeFrames.prompt(1),
1747
+ ...claudeChild,
1748
+ claudeMarker("child ready"),
1749
+ ]);
1750
+ yield* session.runtime.startTurn(session.turnInput(1));
1751
+ yield* session.throughMarker("child ready");
1752
+ yield* session.terminate();
1753
+ const terminal = yield* session.terminal;
1754
+ assert.equal(terminal.status, "failed");
1755
+ assert.equal(terminal.failure?.class, "transport_error");
1756
+ assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
1757
+ const settled = yield* openClaudeReplaySession([
1758
+ ...claudeFrames.open,
1759
+ ...claudeFrames.prompt(1),
1760
+ ...claudeChild,
1761
+ claudeFrames.childState("child-1", "grandchild", "running"),
1762
+ claudeFrames.update("grandchild", {
1763
+ sessionUpdate: "tool_call_update",
1764
+ toolCallId: "nested-tool",
1765
+ name: "Bash",
1766
+ kind: "execute",
1767
+ status: "in_progress",
1768
+ rawInput: { command: "cat package.json" },
1769
+ }),
1770
+ claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
1771
+ claudeFrames.idle("end_turn"),
1772
+ ]);
1773
+ yield* settled.runtime.startTurn(settled.turnInput(1));
1774
+ const foreground = yield* settled.until((event) => event.type === "turn.terminal");
1775
+ const completed = foreground.at(-1)!;
1776
+ if (completed.type !== "turn.terminal") throw new Error("Missing settled root terminal");
1777
+ assert.equal(completed.status, "completed");
1778
+ assert.isTrue(yield* settled.runtime.hasPendingBackgroundWork!);
1779
+ yield* settled.terminate();
1780
+ assert.isFalse(
1781
+ yield* settled.runtime.hasPendingBackgroundWork!,
1782
+ "exit releases visible owners held open by nested work",
1783
+ );
1784
+ const exited = yield* settled.until(
1785
+ (event) =>
1786
+ event.type === "turn_item.updated" &&
1787
+ event.turnItem.type === "subagent" &&
1788
+ event.turnItem.status === "failed",
1789
+ );
1790
+ assert.isTrue(
1791
+ exited.some(
1792
+ (event) => event.type === "subagent.updated" && event.subagent.status === "failed",
1793
+ ),
1794
+ );
1795
+ const items = new Map(
1796
+ [...foreground, ...exited].flatMap((event) =>
1797
+ event.type === "turn_item.updated" ? [[event.turnItem.id, event.turnItem] as const] : [],
1798
+ ),
1799
+ );
1800
+ assert.deepEqual(pendingBackgroundTurnItems({ turnItems: [...items.values()] }), []);
1801
+ assert.isTrue(
1802
+ exited.some(
1803
+ (event) =>
1804
+ event.type === "turn_item.updated" &&
1805
+ event.turnItem.type === "dynamic_tool" &&
1806
+ event.turnItem.status === "interrupted",
1807
+ ),
1808
+ );
1809
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
1810
+ );
1811
+
1812
+ it.effect("keeps Claude activity after a refused Stop and closes it on retry", () =>
1813
+ Effect.gen(function* () {
1814
+ const gate = makeProviderReplayGate(["close-response", "queued-close-response"]);
1815
+ const session = yield* openClaudeReplaySession(
1816
+ [
1817
+ ...claudeFrames.open,
1818
+ ...claudeFrames.prompt(1),
1819
+ ...claudeChild,
1820
+ claudeMarker("before Stop"),
1821
+ claudeFrames.closeRequest,
1822
+ claudeFrames.update("child-1", {
1823
+ sessionUpdate: "agent_message_chunk",
1824
+ messageId: "closing-reply",
1825
+ content: { type: "text", text: "Finished during close." },
1826
+ }),
1827
+ claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
1828
+ claudeFrames.idle("end_turn"),
1829
+ claudeMarker("idle during close"),
1830
+ {
1831
+ type: "emit_inbound",
1832
+ label: "close-response",
1833
+ frame: {
1834
+ kind: "response",
1835
+ method: "session/close",
1836
+ error: { code: -32603, message: "Close refused" },
1837
+ },
1838
+ },
1839
+ ...claudeFrames.prompt(2),
1840
+ claudeMarker("before retry"),
1841
+ claudeFrames.closeRequest,
1842
+ claudeFrames.idle("cancelled"),
1843
+ claudeFrames.closed,
1844
+ ],
1845
+ gate,
1846
+ );
1847
+ yield* session.runtime.startTurn(session.turnInput(1));
1848
+ const started = yield* session.throughMarker("before Stop");
1849
+ const running = started.findLast((event) => event.type === "provider_turn.updated");
1850
+ if (running?.type !== "provider_turn.updated") throw new Error("Missing active turn");
1851
+ const stop = {
1852
+ providerThread: session.providerThread,
1853
+ providerTurnId: running.providerTurn.id,
1854
+ requestRuntimeRestart: true,
1855
+ };
1856
+ const closing = yield* session.runtime
1857
+ .interruptTurn(stop)
1858
+ .pipe(Effect.exit, Effect.forkScoped);
1859
+ yield* Effect.addFinalizer(() => Effect.sync(() => gate.releaseAll()));
1860
+ const idle = yield* session.throughMarker("idle during close");
1861
+ gate.release("close-response");
1862
+ const refused = yield* Fiber.join(closing);
1863
+ assert.isTrue(Exit.isFailure(refused), "a refused close must not report a successful Stop");
1864
+ const terminal = idle.findLast((event) => event.type === "turn.terminal");
1865
+ assert.equal(
1866
+ terminal?.type === "turn.terminal" ? terminal.status : null,
1867
+ "completed",
1868
+ "idle during a refused close must settle the foreground turn",
1869
+ );
1870
+ const result = idle.findLast((event) => event.type === "subagent.updated");
1871
+ if (result?.type !== "subagent.updated") throw new Error("Missing child close-time result");
1872
+ assert.equal(result.subagent.status, "completed");
1873
+ assert.equal(result.subagent.result, "Finished during close.");
1874
+ assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
1875
+ yield* session.runtime.startTurn(session.turnInput(2));
1876
+ const retry = yield* session.throughMarker("before retry");
1877
+ const retryRunning = retry.findLast((event) => event.type === "provider_turn.updated");
1878
+ if (retryRunning?.type !== "provider_turn.updated")
1879
+ throw new Error("Missing active retry turn");
1880
+ yield* session.runtime.interruptTurn({
1881
+ ...stop,
1882
+ providerTurnId: retryRunning.providerTurn.id,
1883
+ });
1884
+ assert.equal((yield* session.terminal).status, "interrupted");
1885
+ assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
1886
+
1887
+ const queued = yield* openClaudeReplaySession(
1888
+ [
1889
+ ...claudeFrames.open,
1890
+ {
1891
+ type: "expect_outbound",
1892
+ frame: { kind: "request", method: "session/prompt", params: "<any>" },
1893
+ },
1894
+ claudeMarker("before queued Stop"),
1895
+ claudeFrames.closeRequest,
1896
+ {
1897
+ type: "emit_inbound",
1898
+ frame: {
1899
+ kind: "response",
1900
+ method: "session/prompt",
1901
+ error: { code: -32800, message: "Request cancelled" },
1902
+ },
1903
+ },
1904
+ { ...claudeFrames.closed, label: "queued-close-response" },
1905
+ ],
1906
+ gate,
1907
+ );
1908
+ yield* queued.runtime.startTurn(queued.turnInput(3));
1909
+ const pending = yield* queued.throughMarker("before queued Stop");
1910
+ const queuedRunning = pending.findLast((event) => event.type === "provider_turn.updated");
1911
+ if (queuedRunning?.type !== "provider_turn.updated")
1912
+ throw new Error("Missing queued provider turn");
1913
+ const queuedClosing = yield* queued.runtime
1914
+ .interruptTurn({
1915
+ providerThread: queued.providerThread,
1916
+ providerTurnId: queuedRunning.providerTurn.id,
1917
+ requestRuntimeRestart: true,
1918
+ })
1919
+ .pipe(Effect.forkScoped);
1920
+ const queuedTerminal = yield* queued.terminal;
1921
+ gate.release("queued-close-response");
1922
+ yield* Fiber.join(queuedClosing);
1923
+ assert.equal(queuedTerminal.providerTurnId, queuedRunning.providerTurn.id);
1924
+ assert.equal(queuedTerminal.status, "interrupted");
1925
+ assert.isNull(queuedTerminal.failure);
1926
+ assert.isFalse(yield* queued.runtime.hasPendingBackgroundWork!);
1927
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
1928
+ );
1929
+
1930
it.effect("opens a real ACP child process resolved from registry configuration", () =>
1931
Effect.gen(function* () {
1932
const path = yield* Path.Path;
docs/user/providers-acp.md
+4
@@ -13,6 +13,10 @@ configuration, compaction, and agent-terminal updates when the agent supports th
13
negotiates ACP v1 for Registry agents that have not migrated yet, so agents such as Pi continue to
14
work through the same generic integration.
15
16
+Claude Agent uses the ACP v2 preview by default for Registry and local `claude-agent-acp`
17
+commands. If you encounter preview issues, set `CLAUDE_AGENT_ACP_EXPERIMENTAL_V2=0` in the
18
+provider instance's environment overrides to use ACP v1.
19
+
20
## Add an agent
21
22
1. Open **Settings → Providers**.
packages/provider-acp-registry/src/server/adapter.ts
+36
-1
@@ -1,3 +1,8 @@
1
+import {
2
+ extractClaudeSubagentUpdate,
3
+ extractClaudeSubagentSessionEvent,
4
+ isClaudeProvisionalSubagentTool,
5
+} from "./claudeAcp.ts";
6
import {
7
normalizeDevinSessionUpdate,
8
normalizeDevinToolCall,
@@ -25,6 +30,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
30
import * as EffectAcpErrors from "effect-acp/errors";
31
32
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
33
+import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
34
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
35
import {
36
normalizeAcpRegistryCommands,
@@ -71,6 +77,7 @@ export interface AcpRegistryAdapterV2Options {
77
EffectAcpErrors.AcpError,
78
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
79
>;
80
+ readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
81
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
82
}
83
@@ -183,6 +190,22 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
190
registryAgentId === "github-copilot-cli" ||
191
(options.settings.source === "local" &&
192
/^copilot(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
193
+ const isClaude =
194
+ registryAgentId === "claude-acp" ||
195
+ (options.settings.source === "local" &&
196
+ /^claude-agent-acp(\.exe|\.cmd)?$/i.test(
197
+ options.settings.commandPath.split(/[\\/]/).pop() ?? "",
198
+ ));
199
+ const runtimeOptions = isClaude
200
+ ? {
201
+ ...options,
202
+ environment: {
203
+ ...options.environment,
204
+ CLAUDE_AGENT_ACP_EXPERIMENTAL_V2:
205
+ options.environment.CLAUDE_AGENT_ACP_EXPERIMENTAL_V2 ?? "1",
206
+ },
207
+ }
208
+ : options;
209
const copilotRouting = isCopilot ? makeCopilotSubagentRouting() : undefined;
210
const flavor: AcpAdapterV2Flavor = {
211
driver: ACP_REGISTRY_PROVIDER,
@@ -192,6 +215,14 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
215
...(registryAgentId === "mistral-vibe"
216
? { registerExtensions: registerMistralVibeAcpExtensions }
217
: {}),
218
+ ...(isClaude
219
+ ? {
220
+ followAgentWorkState: true,
221
+ extractSubagentUpdate: extractClaudeSubagentUpdate,
222
+ isProvisionalSubagentTool: isClaudeProvisionalSubagentTool,
223
+ extractSubagentSessionEvent: extractClaudeSubagentSessionEvent,
224
+ }
225
+ : {}),
226
...(isDevin
227
? {
228
clientCapabilitiesMeta: {
@@ -211,7 +242,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
242
normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate,
243
extractSubagentUpdate: extractCopilotSubagentUpdate,
244
}),
214
- makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options, catalog),
245
+ makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog),
246
...(runtimeCoordinator === undefined
247
? {}
248
: {
@@ -245,6 +276,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
276
instanceId: options.instanceId,
277
flavor,
278
selfInvocation: options.selfInvocation,
279
+ ...(options.continuationRequests === undefined
280
+ ? {}
281
+ : { continuationRequests: options.continuationRequests }),
282
// Devin runs commands through client terminals and has no ask mode over ACP to fall back on.
283
...(isDevin
284
? {
@@ -287,6 +321,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
321
settings: { ...input.config, enabled: input.enabled },
322
environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
323
selfInvocation,
324
+ continuationRequests: yield* ProviderContinuationRequests.ProviderContinuationRequests,
325
nativeLogging: (threadId) =>
326
makeNativeLogger({
327
nativeEventLogger: providerEventLoggers.native,
packages/provider-acp-registry/src/server/claudeAcp.ts
new
+117
@@ -0,0 +1,117 @@
1
+import * as Option from "effect/Option";
2
+import * as Schema from "effect/Schema";
3
+import type * as AcpSchema from "effect-acp/compat";
4
+import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
5
+import type {
6
+ AcpAdapterV2SubagentUpdate,
7
+ AcpSubagentSessionEvent,
8
+} from "@t3tools/provider-acp/server/adapter";
9
+
10
+const decodeAgentInput = Schema.decodeUnknownOption(
11
+ Schema.Struct({
12
+ prompt: Schema.String,
13
+ description: Schema.optionalKey(Schema.String),
14
+ model: Schema.optionalKey(Schema.String),
15
+ run_in_background: Schema.optionalKey(Schema.Boolean),
16
+ }),
17
+);
18
+const decodeAsyncResponse = Schema.decodeUnknownOption(
19
+ Schema.Struct({
20
+ claudeCode: Schema.Struct({ toolResponse: Schema.Struct({ isAsync: Schema.Boolean }) }),
21
+ }),
22
+);
23
+
24
+export function isClaudeProvisionalSubagentTool(tool: AcpToolCallState): boolean {
25
+ return (
26
+ (tool.data.name === "Agent" || tool.data.name === "Task") &&
27
+ tool.status !== "failed" &&
28
+ tool.status !== "completed" &&
29
+ Option.isNone(decodeAgentInput(tool.data.rawInput))
30
+ );
31
+}
32
+
33
+export function extractClaudeSubagentUpdate(
34
+ tool: AcpToolCallState,
35
+): AcpAdapterV2SubagentUpdate | undefined {
36
+ if (tool.data.name !== "Agent" && tool.data.name !== "Task") return;
37
+ const input = decodeAgentInput(tool.data.rawInput);
38
+ if (Option.isNone(input)) return;
39
+ const response = decodeAsyncResponse(tool.data.meta);
40
+ const background =
41
+ input.value.run_in_background === true ||
42
+ (Option.isSome(response) && response.value.claudeCode.toolResponse.isAsync);
43
+ return {
44
+ nativeTaskId: tool.toolCallId,
45
+ childSessionId: null,
46
+ prompt: input.value.prompt,
47
+ title: input.value.description ?? null,
48
+ model: input.value.model ?? null,
49
+ status:
50
+ tool.status === "failed"
51
+ ? "failed"
52
+ : tool.status === "completed" && !background
53
+ ? "completed"
54
+ : "running",
55
+ result: null,
56
+ };
57
+}
58
+
59
+const decodeChildState = Schema.decodeUnknownOption(
60
+ Schema.Struct({
61
+ sessionId: Schema.String,
62
+ state: Schema.Struct({
63
+ state: Schema.String,
64
+ stopReason: Schema.optionalKey(Schema.NullOr(Schema.String)),
65
+ error: Schema.optionalKey(Schema.NullOr(Schema.Struct({ message: Schema.String }))),
66
+ }),
67
+ }),
68
+);
69
+const decodeDelegation = Schema.decodeUnknownOption(
70
+ Schema.Struct({
71
+ messageId: Schema.String,
72
+ senderSessionId: Schema.optionalKey(Schema.String),
73
+ content: Schema.Array(
74
+ Schema.Struct({ type: Schema.String, text: Schema.optionalKey(Schema.String) }),
75
+ ),
76
+ }),
77
+);
78
+
79
+// Claude's session_message id is the Agent/Task or SendMessage tool-use id.
80
+export function extractClaudeSubagentSessionEvent(
81
+ notification: AcpSchema.SessionNotification,
82
+): AcpSubagentSessionEvent | undefined {
83
+ const update = notification.update;
84
+ if (update.sessionUpdate !== "_t3_unknown") return;
85
+ if (update.originalSessionUpdate === "subagent_update") {
86
+ const child = decodeChildState(update.raw);
87
+ if (Option.isNone(child)) return;
88
+ const { sessionId, state } = child.value;
89
+ return {
90
+ type: "state",
91
+ childSessionId: sessionId,
92
+ parentSessionId: notification.sessionId,
93
+ status:
94
+ state.state === "running" || state.state === "requires_action"
95
+ ? "running"
96
+ : state.stopReason === "error"
97
+ ? "failed"
98
+ : state.stopReason === "cancelled" || state.state === "unknown"
99
+ ? "cancelled"
100
+ : "completed",
101
+ result: state.error?.message ?? null,
102
+ };
103
+ }
104
+ if (update.originalSessionUpdate === "session_message") {
105
+ const delegation = decodeDelegation(update.raw);
106
+ if (Option.isNone(delegation)) return;
107
+ return {
108
+ type: "delegation",
109
+ childSessionId: notification.sessionId,
110
+ parentSessionId: delegation.value.senderSessionId ?? null,
111
+ delegationId: delegation.value.messageId,
112
+ prompt: delegation.value.content
113
+ .flatMap((block) => (block.type === "text" && block.text !== undefined ? [block.text] : []))
114
+ .join("\n"),
115
+ };
116
+ }
117
+}