@devries-cameron20 / t3code Mirror · read-only
Fork 0

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 21, 04:45 UTC

main
ts 3,947 lines 152 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, describe, it } from "@effect/vitest";
4 import {
5 EnvironmentId,
6 MessageId,
7 NodeId,
8 ProjectId,
9 RunAttemptId,
10 RunId,
11 type ModelSelection,
12 ProviderInstanceId,
13 ProviderSessionId,
14 ThreadId,
15 } from "@t3tools/contracts";
16 import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
17 import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
18 import * as Exit from "effect/Exit";
19 import * as Fiber from "effect/Fiber";
20 import * as DateTime from "effect/DateTime";
21 import * as Queue from "effect/Queue";
22 import * as Stream from "effect/Stream";
23 import * as TestClock from "effect/testing/TestClock";
24 import * as Effect from "effect/Effect";
25 import * as FileSystem from "effect/FileSystem";
26 import * as Layer from "effect/Layer";
27 import * as Option from "effect/Option";
28 import * as Path from "effect/Path";
29 import * as Schema from "effect/Schema";
30 import * as HttpClient from "effect/http/HttpClient";
31 import * as HttpClientResponse from "effect/http/HttpClientResponse";
32 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
33 import * as EffectAcpErrors from "effect-acp/errors";
34
35 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
36 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
37 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
38 import {
39 makeProviderReplayGate,
40 type ProviderReplayGate,
41 } from "@t3tools/provider-testing/replayGate";
42 import type { ProviderContinuationRequest } from "@t3tools/provider-core/server/ProviderContinuationRequests";
43 import * as ServerSettings from "../../serverSettings.ts";
44 import type { AcpRegistryLiveConfiguration } from "@t3tools/provider-acp-registry/testing";
45 import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
46 import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
47 import { ACP_SESSION_MODE_OPTION_ID } from "@t3tools/provider-acp/server/sessionConfig";
48 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
49 import { t3AcpPromptWithInstructions } from "@t3tools/provider-core/server/orchestrationInstructions";
50 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
51 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
52 import {
53 decodeAcpReplayTranscript,
54 makeAcpReplayCompletenessAssertion,
55 makeAcpReplayRuntime,
56 makeTurnInput,
57 } from "./AcpAdapterV2.testkit.ts";
58 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
59 import { AcpRegistryAdapterV2Driver } from "@t3tools/provider-acp-registry/server";
60 import {
61 ACP_REGISTRY_PROVIDER,
62 makeAcpRegistryAdapterV2,
63 acpRegistryPromptFailure,
64 acpRegistryProbeResult,
65 } from "@t3tools/provider-acp-registry/testing";
66
67 const decodeAcpRegistryAdapterSettings = Schema.decodeUnknownEffect(
68 AcpRegistryAdapterV2Driver.configSchema,
69 );
70
71 const layerHost = TestProviderHost.layer().pipe(
72 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
73 );
74
75 const layerRegistry = Layer.succeed(
76 HttpClient.HttpClient,
77 HttpClient.make((request) =>
78 Effect.succeed(
79 HttpClientResponse.fromWeb(
80 request,
81 Response.json({
82 version: "1.0.0",
83 agents: [
84 {
85 id: "fixture-agent",
86 name: "Fixture Agent",
87 version: "1.0.0",
88 description: "ACP V2 adapter fixture",
89 distribution: {
90 binary: {
91 "darwin-aarch64": {
92 archive: "https://registry.test/unused",
93 cmd: "fixture-agent",
94 args: [],
95 },
96 "linux-x86_64": {
97 archive: "https://registry.test/unused",
98 cmd: "fixture-agent",
99 args: [],
100 },
101 },
102 },
103 },
104 ],
105 }),
106 ),
107 ),
108 ),
109 );
110
111 const layerInjectedRuntimeCatalog = Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({
112 resolve: () => Effect.die("the runtime is injected"),
113 });
114
115 const layerTest = Layer.mergeAll(
116 NodeServices.layer,
117 NodeCrypto.layer,
118 IdAllocator.layer,
119 McpProviderSessions.layer,
120 layerHost,
121 layerRegistry,
122 ServerSettings.layerTest(),
123 );
124
125 const CLAUDE_ROOT_SESSION = "claude-session";
126
127 /** Replay frames of Claude Agent (claude-agent-acp 0.90.0) on ACP v2. */
128 const claudeFrames = {
129 open: [
130 { type: "expect_outbound", frame: { kind: "request", method: "initialize", params: "<any>" } },
131 {
132 type: "emit_inbound",
133 frame: {
134 kind: "response",
135 method: "initialize",
136 result: {
137 protocolVersion: 2,
138 info: { name: "@agentclientprotocol/claude-agent-acp", version: "0.90.0" },
139 capabilities: { session: {} },
140 authMethods: [],
141 },
142 },
143 },
144 { type: "expect_outbound", frame: { kind: "request", method: "session/new", params: "<any>" } },
145 {
146 type: "emit_inbound",
147 frame: {
148 kind: "response",
149 method: "session/new",
150 result: { sessionId: CLAUDE_ROOT_SESSION },
151 },
152 },
153 ],
154 update: (sessionId: string, sessionUpdate: Record<string, unknown>) => ({
155 type: "emit_inbound",
156 frame: {
157 kind: "notification",
158 method: "session/update",
159 params: { sessionId, update: sessionUpdate },
160 },
161 }),
162 childState: (parent: string, child: string, state: string) =>
163 claudeFrames.update(parent, {
164 sessionUpdate: "subagent_update",
165 sessionId: child,
166 state: { state },
167 }),
168 /** A prompt Claude takes in and works on. */
169 prompt: (ordinal: number) => [
170 {
171 type: "expect_outbound",
172 frame: { kind: "request", method: "session/prompt", params: "<any>" },
173 },
174 claudeFrames.update(CLAUDE_ROOT_SESSION, {
175 sessionUpdate: "user_message",
176 messageId: `user-${ordinal}`,
177 content: [{ type: "text", text: "test prompt" }],
178 }),
179 {
180 type: "emit_inbound",
181 frame: {
182 kind: "response",
183 method: "session/prompt",
184 result: { messageId: `user-${ordinal}` },
185 },
186 },
187 claudeFrames.update(CLAUDE_ROOT_SESSION, { sessionUpdate: "state_update", state: "running" }),
188 ],
189 idle: (stopReason: string) =>
190 claudeFrames.update(CLAUDE_ROOT_SESSION, {
191 sessionUpdate: "state_update",
192 state: "idle",
193 stopReason,
194 }),
195 closeRequest: {
196 type: "expect_outbound",
197 frame: {
198 kind: "request",
199 method: "session/close",
200 params: { sessionId: CLAUDE_ROOT_SESSION },
201 },
202 },
203 closed: {
204 type: "emit_inbound",
205 frame: { kind: "response", method: "session/close", result: {} },
206 },
207 };
208
209 const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* (
210 entries: ReadonlyArray<unknown>,
211 replayGate?: ProviderReplayGate,
212 continuationEnabled = true,
213 agentId: string | Record<string, unknown> = "claude-acp",
214 replacementEntries?: ReadonlyArray<unknown>,
215 runtimeMode: "approval-required" | "full-access" = "approval-required",
216 ) {
217 const fileSystem = yield* FileSystem.FileSystem;
218 const path = yield* Path.Path;
219 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
220 const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-lifecycle-" });
221 const scriptPath = yield* path.fromFileUrl(
222 new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
223 );
224 const makeReplay = Effect.fn("openClaudeReplaySession.makeReplay")(function* (
225 entries: ReadonlyArray<unknown>,
226 name: string,
227 ) {
228 const transcript = yield* decodeAcpReplayTranscript(
229 {
230 provider: ACP_REGISTRY_PROVIDER,
231 protocol: "acp.ndjson-jsonrpc",
232 version: "1",
233 scenario: name,
234 entries: entries as never,
235 },
236 ACP_REGISTRY_PROVIDER,
237 );
238 return makeAcpReplayRuntime({
239 transcript,
240 statusPath: path.join(replayDir, `${name}.json`),
241 scriptPath,
242 childProcessSpawner,
243 fileSystem,
244 ...(replayGate === undefined ? {} : { replayGate }),
245 });
246 });
247 const offers: Array<ProviderContinuationRequest> = [];
248 const offered = yield* Queue.unbounded<void>();
249 const continuationRequests = {
250 offer: (request: ProviderContinuationRequest) =>
251 Effect.sync(() => {
252 offers.push(request);
253 }).pipe(Effect.andThen(Queue.offer(offered, undefined)), Effect.asVoid),
254 };
255 const instanceId = ProviderInstanceId.make("claude-lifecycle");
256 const outgoing = yield* Queue.unbounded<unknown>();
257 let onTermination: NonNullable<
258 AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"]
259 > = () => Effect.die("Runtime has not started");
260 const replayRuntime = yield* makeReplay(entries, "claude-lifecycle");
261 const replacementRuntime =
262 replacementEntries === undefined
263 ? replayRuntime
264 : yield* makeReplay(replacementEntries, "replacement");
265 let started = false;
266 const adapterOptions = {
267 selfInvocation: yield* resolveSelfInvocation(),
268 instanceId,
269 settings: yield* decodeAcpRegistryAdapterSettings(
270 typeof agentId === "string" ? { agentId } : agentId,
271 ),
272 environment: {},
273 ...(continuationEnabled ? { continuationRequests } : {}),
274 makeRuntime: (runtimeInput: Parameters<typeof replayRuntime>[0]) => {
275 onTermination = runtimeInput.onTermination;
276 const replay = started ? replacementRuntime : replayRuntime;
277 started = true;
278 return replay({
279 ...runtimeInput,
280 protocolLogging: {
281 logIncoming: false,
282 logOutgoing: true,
283 logger: (event) =>
284 event.stage === "raw" && typeof event.payload === "string"
285 ? Queue.offer(outgoing, JSON.parse(event.payload)).pipe(Effect.asVoid)
286 : Effect.void,
287 },
288 });
289 },
290 };
291 const adapter = yield* makeAcpRegistryAdapterV2(adapterOptions).pipe(
292 Effect.provide(layerInjectedRuntimeCatalog),
293 );
294 const threadId = ThreadId.make("thread-claude-lifecycle");
295 const modelSelection = { instanceId, model: "default" } as const;
296 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
297 runtimeMode,
298 interactionMode: "default",
299 cwd: replayDir,
300 });
301 const runtime = yield* adapter.openSession({
302 threadId,
303 providerSessionId: ProviderSessionId.make("session-claude-lifecycle"),
304 modelSelection,
305 runtimePolicy,
306 });
307 yield* Effect.addFinalizer(() => Effect.sync(() => replayGate?.releaseAll()));
308 if (continuationEnabled && agentId === "claude-acp") {
309 assert.isDefined(
310 runtime.hasPendingBackgroundWork,
311 "Claude ACP v2 must report background work after foreground idle",
312 );
313 }
314 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
315 yield* runtime.events.pipe(
316 Stream.runForEach((event) => Queue.offer(events, event)),
317 Effect.forkScoped,
318 );
319 const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
320 const now = yield* DateTime.now;
321 const turnInput = (
322 ordinal: number,
323 options: { readonly continuation?: boolean } = {},
324 ): ProviderAdapter.ProviderAdapterV2TurnInput => ({
325 appThread: {
326 createdBy: "user",
327 creationSource: "web",
328 id: threadId,
329 projectId: ProjectId.make(`project-claude-lifecycle`),
330 title: "Claude Agent",
331 providerInstanceId: instanceId,
332 modelSelection,
333 runtimeMode,
334 interactionMode: "default",
335 branch: null,
336 worktreePath: null,
337 activeProviderThreadId: providerThread.id,
338 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
339 forkedFrom: null,
340 createdAt: now,
341 updatedAt: now,
342 archivedAt: null,
343 settledOverride: null,
344 settledAt: null,
345 lastVisitedAt: null,
346 deletedAt: null,
347 },
348 threadId,
349 runId: RunId.make(`run-claude-lifecycle-${ordinal}`),
350 runOrdinal: ordinal,
351 providerTurnOrdinal: ordinal,
352 attemptId: RunAttemptId.make(`attempt-claude-lifecycle-${ordinal}`),
353 rootNodeId: NodeId.make(`node-claude-lifecycle-${ordinal}`),
354 providerThread,
355 message: {
356 ...(options.continuation === true
357 ? { createdBy: "agent" as const, creationSource: "provider" as const }
358 : { createdBy: "user" as const, creationSource: "web" as const }),
359 messageId: MessageId.make(`message-claude-lifecycle-${ordinal}`),
360 text: "test prompt",
361 attachments: [],
362 },
363 modelSelection,
364 runtimePolicy,
365 });
366 const until = (predicate: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) =>
367 Effect.gen(function* () {
368 const seen: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
369 while (true) {
370 const event = yield* Queue.take(events);
371 seen.push(event);
372 if (predicate(event)) return seen;
373 }
374 });
375 const throughMarker = (title: string) =>
376 until(
377 (event) =>
378 event.type === "provider_thread.updated" &&
379 event.providerThread.nativeMetadata?.title === title,
380 );
381 const terminal = until((event) => event.type === "turn.terminal").pipe(
382 Effect.map((seen) => {
383 const event = seen.at(-1)!;
384 if (event.type !== "turn.terminal") throw new Error("Missing terminal");
385 return event;
386 }),
387 );
388 return {
389 runtime,
390 providerThread,
391 turnInput,
392 until,
393 throughMarker,
394 terminal,
395 offers,
396 offered,
397 outgoing,
398 terminate: () =>
399 onTermination(
400 new EffectAcpErrors.AcpTransportError({
401 detail: "Injected fixture process exit",
402 cause: "test",
403 }),
404 ),
405 };
406 });
407
408 const claudeMarker = (title: string) =>
409 claudeFrames.update(CLAUDE_ROOT_SESSION, {
410 sessionUpdate: "session_info_update",
411 title,
412 });
413 const claudeChild = [
414 claudeFrames.update(CLAUDE_ROOT_SESSION, {
415 sessionUpdate: "tool_call_update",
416 toolCallId: "agent-1",
417 name: "Agent",
418 title: "Review",
419 kind: "think",
420 status: "in_progress",
421 rawInput: { prompt: "Review the code", description: "Review", run_in_background: true },
422 }),
423 claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "running"),
424 claudeFrames.update("child-1", {
425 sessionUpdate: "session_message",
426 messageId: "agent-1",
427 senderSessionId: CLAUDE_ROOT_SESSION,
428 recipientSessionId: "child-1",
429 content: [{ type: "text", text: "Review the code" }],
430 }),
431 claudeFrames.update(CLAUDE_ROOT_SESSION, {
432 sessionUpdate: "tool_call_update",
433 toolCallId: "agent-1",
434 status: "completed",
435 _meta: { claudeCode: { toolResponse: { isAsync: true } } },
436 }),
437 ];
438
439 const claudeUnrelatedChildren = [
440 claudeFrames.childState("unknown-parent", "unrelated-child", "running"),
441 claudeFrames.update("unrelated-child", {
442 sessionUpdate: "session_message",
443 messageId: "agent-1",
444 senderSessionId: "unknown-parent",
445 content: [{ type: "text", text: "Unrelated delegation" }],
446 }),
447 claudeFrames.update("unlinked-child", {
448 sessionUpdate: "agent_message_chunk",
449 messageId: "unlinked-reply",
450 content: { type: "text", text: "Unlinked output" },
451 }),
452 ];
453
454 describe("AcpRegistryAdapterV2", () => {
455 it.effect.each([
456 { commandPath: "/root/.local/bin/agy", offers: 1 },
457 { commandPath: "C:\\tools\\agy.exe", offers: 1 },
458 { commandPath: "/opt/bin/other-agent", offers: 0 },
459 ])("continues late output only for agy ($commandPath)", ({ commandPath, offers }) =>
460 Effect.gen(function* () {
461 const gate = makeProviderReplayGate(["wake"]);
462 const update = (sessionUpdate: Record<string, unknown>) =>
463 claudeFrames.update(CLAUDE_ROOT_SESSION, sessionUpdate);
464 const session = yield* openClaudeReplaySession(
465 [
466 {
467 type: "expect_outbound",
468 frame: { kind: "request", method: "initialize", params: "<any>" },
469 },
470 {
471 type: "emit_inbound",
472 frame: {
473 kind: "response",
474 method: "initialize",
475 result: {
476 protocolVersion: 1,
477 agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" },
478 agentCapabilities: { loadSession: true },
479 authMethods: [],
480 },
481 },
482 },
483 claudeFrames.open[2],
484 claudeFrames.open[3],
485 claudeFrames.prompt(1)[0],
486 {
487 type: "emit_inbound",
488 frame: {
489 kind: "response",
490 method: "session/prompt",
491 result: { stopReason: "end_turn" },
492 },
493 },
494 {
495 ...update({
496 sessionUpdate: "agent_message_chunk",
497 content: { type: "text", text: "Background work finished." },
498 }),
499 label: "wake",
500 },
501 // agy ends each reply with usage_update; this one ends before the continuation run starts.
502 update({ sessionUpdate: "usage_update", used: 100, size: 1000 }),
503 claudeMarker("late output received"),
504 ],
505 gate,
506 true,
507 { source: "local", commandPath, commandArgs: ["acp"] },
508 );
509 yield* session.runtime.startTurn(session.turnInput(1));
510 assert.equal((yield* session.terminal).status, "completed");
511 gate.release("wake");
512 yield* session.throughMarker("late output received");
513 assert.lengthOf(session.offers, offers, "late output must only wake agy");
514 if (offers === 0) return;
515 yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
516 yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
517 yield* TestClock.adjust("3 seconds");
518 const continued = yield* session.until((event) => event.type === "turn.terminal");
519 assert.include(JSON.stringify(continued), "Background work finished.");
520 const terminal = continued.at(-1)!;
521 if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal");
522 assert.equal(terminal.status, "completed");
523 }).pipe(Effect.provide(layerTest)),
524 );
525
526 it.effect.each(["approval-required", "full-access"] as const)(
527 "continues an agy permission request after the prompt settles (%s)",
528 (runtimeMode) =>
529 Effect.gen(function* () {
530 const gate = makeProviderReplayGate(["wake", "reply"]);
531 const session = yield* openClaudeReplaySession(
532 [
533 {
534 type: "expect_outbound",
535 frame: { kind: "request", method: "initialize", params: "<any>" },
536 },
537 {
538 type: "emit_inbound",
539 frame: {
540 kind: "response",
541 method: "initialize",
542 result: {
543 protocolVersion: 1,
544 agentInfo: { name: "Antigravity ACP Server", version: "1.5.9" },
545 agentCapabilities: { loadSession: true },
546 authMethods: [],
547 },
548 },
549 },
550 claudeFrames.open[2],
551 claudeFrames.open[3],
552 claudeFrames.prompt(1)[0],
553 {
554 type: "emit_inbound",
555 frame: {
556 kind: "response",
557 method: "session/prompt",
558 result: { stopReason: "end_turn" },
559 },
560 },
561 {
562 type: "emit_inbound",
563 label: "wake",
564 frame: {
565 kind: "request",
566 method: "session/request_permission",
567 params: {
568 sessionId: CLAUDE_ROOT_SESSION,
569 toolCall: {
570 toolCallId: "late-command",
571 title: "Run command",
572 kind: "execute",
573 status: "pending",
574 },
575 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
576 },
577 },
578 },
579 claudeMarker("late permission received"),
580 {
581 type: "expect_outbound",
582 frame: {
583 kind: "response",
584 method: "session/request_permission",
585 result: { outcome: { outcome: "selected", optionId: "allow" } },
586 },
587 },
588 {
589 ...claudeFrames.update(CLAUDE_ROOT_SESSION, {
590 sessionUpdate: "agent_message_chunk",
591 content: { type: "text", text: "Command approved." },
592 }),
593 label: "reply",
594 },
595 claudeFrames.update(CLAUDE_ROOT_SESSION, {
596 sessionUpdate: "usage_update",
597 used: 100,
598 size: 1000,
599 }),
600 claudeMarker("reply ended"),
601 ],
602 gate,
603 true,
604 { source: "local", commandPath: "/root/.local/bin/agy", commandArgs: ["acp"] },
605 undefined,
606 runtimeMode,
607 );
608 yield* session.runtime.startTurn(session.turnInput(1));
609 assert.equal((yield* session.terminal).status, "completed");
610 gate.release("wake");
611 yield* session.throughMarker("late permission received");
612 assert.lengthOf(session.offers, 1, "a permission request must offer a continuation");
613 yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
614 yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
615 if (runtimeMode === "approval-required") {
616 const events = yield* session.until(
617 (event) =>
618 event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
619 );
620 const request = events.at(-1)!;
621 if (request.type !== "runtime_request.updated") throw new Error("Missing approval");
622 yield* TestClock.adjust("5 seconds");
623 yield* session.runtime.respondToRuntimeRequest({
624 requestId: request.runtimeRequest.id,
625 decision: "accept",
626 });
627 }
628 // The model can be silent longer than the finalize debounce before it goes on.
629 yield* TestClock.adjust("10 seconds");
630 gate.release("reply");
631 // The closing usage_update must be handled before the clock moves, or its debounce never fires.
632 const output = yield* session.throughMarker("reply ended");
633 assert.isTrue(
634 output.some(
635 (event) =>
636 event.type === "message.updated" && event.message.text === "Command approved.",
637 ),
638 );
639 assert.isFalse(output.some((event) => event.type === "turn.terminal"));
640 yield* TestClock.adjust("3 seconds");
641 assert.equal((yield* session.terminal).status, "completed");
642 }).pipe(Effect.provide(layerTest)),
643 );
644
645 it("preserves and sanitizes structured ACP errors without exposing arbitrary defects", () => {
646 const limit = new EffectAcpErrors.AcpRequestError({
647 code: -31001,
648 errorMessage: "Rate limit exceeded for mistral (model: mistral-vibe-cli-latest).",
649 });
650 assert.deepEqual(acpRegistryPromptFailure("mistral-vibe", limit), {
651 class: "usage_limit",
652 message: limit.errorMessage,
653 code: "-31001",
654 retryable: null,
655 });
656 assert.equal(acpRegistryPromptFailure("other-agent", limit).class, "provider_error");
657 assert.equal(
658 acpRegistryPromptFailure("mistral-vibe", new Error("private defect")).message,
659 "Provider turn failed.",
660 );
661 const rejected = acpRegistryPromptFailure(
662 "any-agent",
663 new EffectAcpErrors.AcpRequestError({
664 code: -32603,
665 errorMessage: "Request rejected. api_key=private-key https://example.test/?token=secret",
666 }),
667 );
668 assert.include(rejected.message, "Request rejected.");
669 assert.notInclude(rejected.message, "private-key");
670 assert.notInclude(rejected.message, "token=secret");
671 });
672
673 describe("the agent's own pickers", () => {
674 type Frame = Record<string, unknown>;
675 const outbound = (method: string, params: unknown = "<any>"): Frame => ({
676 type: "expect_outbound",
677 frame: { kind: "request", method, params },
678 });
679 const answer = (method: string, result: unknown): Frame => ({
680 type: "emit_inbound",
681 frame: { kind: "response", method, result },
682 });
683 const permissionModeOption = (currentValue: string) => ({
684 id: "permission-mode",
685 name: "Permission mode",
686 category: "mode",
687 type: "select",
688 currentValue,
689 options: ["ask", "auto"].map((value) => ({ value, name: value })),
690 });
691
692 const openWithStoredPicks = Effect.fn("openWithStoredPicks")(function* (input: {
693 readonly setup: unknown;
694 readonly pickFrames: ReadonlyArray<Frame>;
695 readonly agentId?: string;
696 readonly customModels?: ReadonlyArray<string>;
697 readonly storedModel?: string;
698 readonly storedModePick?: string;
699 readonly turnModels?: ReadonlyArray<string>;
700 readonly rejectedModel?: string;
701 readonly storedOptions?: ReadonlyArray<{ readonly id: string; readonly value: string }>;
702 readonly failsConfiguration?: boolean;
703 readonly liveConfiguration?: AcpRegistryLiveConfiguration;
704 }) {
705 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
706 // Scope release gives the replay agent at most a second to exit, so the status
707 // read below waits for the agent itself instead of racing its last write.
708 const agentExits: Array<Effect.Effect<void>> = [];
709 const childProcessSpawner = ChildProcessSpawner.make((command) =>
710 spawner
711 .spawn(command)
712 .pipe(
713 Effect.tap((handle) =>
714 Effect.sync(() => agentExits.push(Effect.ignore(handle.exitCode))),
715 ),
716 ),
717 );
718 const fileSystem = yield* FileSystem.FileSystem;
719 const path = yield* Path.Path;
720 const replayDir = yield* fileSystem.makeTempDirectoryScoped({
721 prefix: "t3-acp-registry-stored-picks-",
722 });
723 const statusPath = path.join(replayDir, "status.json");
724 const transcript = yield* decodeAcpReplayTranscript(
725 {
726 provider: ACP_REGISTRY_PROVIDER,
727 protocol: "acp.ndjson-jsonrpc",
728 version: "1",
729 scenario: "stored-picks",
730 entries: [
731 outbound("initialize"),
732 answer("initialize", {
733 protocolVersion: 1,
734 agentCapabilities: { loadSession: false },
735 authMethods: [{ id: "test", name: "Test" }],
736 }),
737 outbound("session/new"),
738 answer("session/new", { sessionId: "agent-session", ...(input.setup as object) }),
739 ...input.pickFrames,
740 ] as never,
741 },
742 ACP_REGISTRY_PROVIDER,
743 );
744 const instanceId = ProviderInstanceId.make("acp-registry-stored-picks");
745 let published: AcpRegistryLiveConfiguration | undefined;
746 const adapter = yield* makeAcpRegistryAdapterV2({
747 selfInvocation: yield* resolveSelfInvocation(),
748 instanceId,
749 settings: yield* decodeAcpRegistryAdapterSettings({
750 agentId: input.agentId ?? "fixture-agent",
751 authMethodId: "test",
752 customModels: input.customModels ?? [],
753 }),
754 environment: {},
755 makeRuntime: makeAcpReplayRuntime({
756 customModels: input.customModels,
757 transcript,
758 statusPath,
759 scriptPath: yield* path.fromFileUrl(
760 new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
761 ),
762 childProcessSpawner,
763 fileSystem,
764 }),
765 }).pipe(
766 Effect.provide(
767 Layer.mergeAll(
768 layerInjectedRuntimeCatalog,
769 Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({
770 withForegroundStartup: (_startupKey, effect) => effect,
771 getLiveConfiguration: () =>
772 Effect.sync(() => Option.fromUndefinedOr(published ?? input.liveConfiguration)),
773 publishLiveConfiguration: (_instanceId, configuration) =>
774 Effect.sync(() => {
775 published = configuration;
776 }),
777 }),
778 ),
779 ),
780 );
781 const threadId = ThreadId.make("thread-acp-registry-stored-picks");
782 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
783 runtimeMode: "approval-required",
784 interactionMode: "default",
785 cwd: replayDir,
786 });
787 const stored: ModelSelection = {
788 instanceId,
789 model: input.storedModel ?? "default",
790 ...(input.storedModePick === undefined
791 ? {}
792 : { options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }] }),
793 ...(input.storedOptions === undefined ? {} : { options: input.storedOptions }),
794 };
795 const configurations: Array<AcpRegistryLiveConfiguration | undefined> = [];
796 yield* Effect.gen(function* () {
797 const runtime = yield* adapter.openSession({
798 threadId,
799 providerSessionId: ProviderSessionId.make("provider-session-stored-picks"),
800 modelSelection: stored,
801 runtimePolicy,
802 });
803 configurations.push(published);
804 if (input.turnModels === undefined) return;
805 const providerThread = yield* runtime.ensureThread({
806 threadId,
807 modelSelection: stored,
808 runtimePolicy,
809 });
810 const now = yield* DateTime.now;
811 let current = stored;
812 for (const [index, model] of input.turnModels.entries()) {
813 const target: ModelSelection = { instanceId, model };
814 const plan = yield* adapter.planSelectionTransition({
815 current,
816 target,
817 sessionCapabilities: runtime.providerSession.capabilities,
818 });
819 assert.equal(plan.type, "apply_on_next_turn");
820 yield* runtime.startTurn(
821 makeTurnInput({
822 threadId,
823 providerThread,
824 instanceId,
825 runtimePolicy,
826 now,
827 ordinal: index + 1,
828 modelSelection: target,
829 }),
830 );
831 yield* runtime.events.pipe(
832 Stream.takeUntil((event) => event.type === "turn.terminal"),
833 Stream.runForEach((event) =>
834 Effect.sync(() => {
835 if (event.type === "turn.terminal") {
836 assert.equal(event.status, "completed", event.failure?.message);
837 }
838 }),
839 ),
840 );
841 configurations.push(published);
842 current = target;
843 }
844 }).pipe(
845 Effect.match({
846 onFailure: (error) => {
847 if (input.failsConfiguration === true) return;
848 assert.isDefined(input.rejectedModel);
849 assert.equal(
850 makeProviderFailure({ cause: error }).message,
851 `The agent did not accept the model "${input.rejectedModel}". Choose another model for this provider, then retry.`,
852 );
853 },
854 onSuccess: () => {
855 assert.isUndefined(input.rejectedModel);
856 assert.notEqual(input.failsConfiguration, true, "configuration should have failed");
857 },
858 }),
859 Effect.scoped,
860 );
861 yield* Effect.all(agentExits, { discard: true });
862 yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
863 return { configurations };
864 });
865
866 it.effect("switches an agent that only advertises modes with session/set_mode", () =>
867 openWithStoredPicks({
868 setup: {
869 modes: {
870 currentModeId: "default",
871 availableModes: ["default", "autoEdit"].map((id) => ({ id, name: id })),
872 },
873 },
874 pickFrames: [
875 outbound("session/set_mode", { sessionId: "agent-session", modeId: "autoEdit" }),
876 answer("session/set_mode", {}),
877 ],
878 storedModePick: "autoEdit",
879 }).pipe(Effect.provide(layerTest)),
880 );
881
882 it.effect("switches a mode config option under its own id", () =>
883 openWithStoredPicks({
884 setup: { configOptions: [permissionModeOption("ask")] },
885 pickFrames: [
886 outbound("session/set_config_option", {
887 sessionId: "agent-session",
888 configId: "permission-mode",
889 value: "auto",
890 }),
891 answer("session/set_config_option", { configOptions: [permissionModeOption("auto")] }),
892 ],
893 storedModePick: "auto",
894 }).pipe(Effect.provide(layerTest)),
895 );
896
897 const modelOption = (id: string, currentValue: string, grouped = false) => ({
898 id,
899 name: "Model",
900 category: "model",
901 type: "select",
902 currentValue,
903 options: grouped
904 ? [{ group: "models", name: "Models", options: [{ value: "default", name: "Default" }] }]
905 : [{ value: "auto", name: "Auto" }],
906 });
907 const configOptionUpdate = (configOptions: ReadonlyArray<unknown>): Frame => ({
908 type: "emit_inbound",
909 frame: {
910 kind: "notification",
911 method: "session/update",
912 params: {
913 sessionId: "agent-session",
914 update: { sessionUpdate: "config_option_update", configOptions },
915 },
916 },
917 });
918 const prompt = (...updates: ReadonlyArray<Frame>): ReadonlyArray<Frame> => [
919 outbound("session/prompt"),
920 ...updates,
921 answer("session/prompt", { stopReason: "end_turn" }),
922 ];
923 const setModel = (modelId: string): ReadonlyArray<Frame> => [
924 outbound("session/set_model", { sessionId: "agent-session", modelId }),
925 answer("session/set_model", {}),
926 ];
927
928 it.effect(
929 "discovers session models and switches through live model configuration changes",
930 () =>
931 Effect.gen(function* () {
932 const flatOption = (current: string) => modelOption("live-model", current);
933 const groupedOption = (current: string) =>
934 modelOption("replacement-model", current, true);
935 const { configurations } = yield* openWithStoredPicks({
936 setup: {
937 models: {
938 currentModelId: "hermes",
939 availableModels: ["hermes", "auto", "default"].map((modelId) => ({
940 modelId,
941 name: modelId,
942 })),
943 },
944 },
945 customModels: ["custom-model"],
946 storedModel: "default",
947 turnModels: [
948 "hermes",
949 "custom-model",
950 "auto",
951 "default",
952 "hermes",
953 "custom-model",
954 "auto",
955 "custom-model",
956 "default",
957 "hermes",
958 ],
959 pickFrames: [
960 ...setModel("default"),
961 ...setModel("hermes"),
962 ...prompt(),
963 ...setModel("custom-model"),
964 ...prompt(),
965 ...setModel("auto"),
966 ...prompt(),
967 ...setModel("default"),
968 ...prompt(),
969 ...setModel("hermes"),
970 ...prompt(configOptionUpdate([flatOption("hermes")])),
971 outbound("session/set_config_option", {
972 sessionId: "agent-session",
973 configId: "live-model",
974 value: "custom-model",
975 }),
976 answer("session/set_config_option", { configOptions: [flatOption("custom-model")] }),
977 ...prompt(),
978 outbound("session/set_config_option", {
979 sessionId: "agent-session",
980 configId: "live-model",
981 value: "auto",
982 }),
983 answer("session/set_config_option", { configOptions: [flatOption("auto")] }),
984 ...prompt(configOptionUpdate([groupedOption("auto")])),
985 outbound("session/set_config_option", {
986 sessionId: "agent-session",
987 configId: "replacement-model",
988 value: "custom-model",
989 }),
990 answer("session/set_config_option", {
991 configOptions: [groupedOption("custom-model")],
992 }),
993 ...prompt(),
994 outbound("session/set_config_option", {
995 sessionId: "agent-session",
996 configId: "replacement-model",
997 value: "default",
998 }),
999 answer("session/set_config_option", { configOptions: [groupedOption("default")] }),
1000 ...prompt(configOptionUpdate([])),
1001 ...setModel("hermes"),
1002 ...prompt(),
1003 ],
1004 });
1005 assert.deepEqual(
1006 configurations.map((configuration) => ({
1007 models: configuration?.models.map((model) => model.id),
1008 current: configuration?.currentModelId,
1009 })),
1010 [
1011 { models: ["hermes", "auto", "default"], current: "default" },
1012 { models: ["hermes", "auto", "default"], current: "hermes" },
1013 { models: ["hermes", "auto", "default"], current: null },
1014 { models: ["hermes", "auto", "default"], current: "auto" },
1015 { models: ["hermes", "auto", "default"], current: "default" },
1016 { models: ["auto"], current: null },
1017 { models: ["auto"], current: null },
1018 { models: ["default"], current: null },
1019 { models: ["default"], current: null },
1020 { models: ["hermes", "auto", "default"], current: "default" },
1021 { models: ["hermes", "auto", "default"], current: "hermes" },
1022 ],
1023 );
1024 }).pipe(Effect.provide(layerTest)),
1025 );
1026
1027 // Copilot's session/new reports its built-in default, not the model it will run
1028 // (github/copilot-cli#5363), so the selected model must be written even when it matches,
1029 // and an unset effort gets the value the composer shows.
1030 it.effect(
1031 "writes the selected Copilot model and the shown effort when session/new reports defaults",
1032 () => {
1033 const copilotModel = (currentValue: string) => ({
1034 ...modelOption("model", currentValue),
1035 options: ["claude-sonnet-5.5", "claude-haiku-4.5"].map((value) => ({
1036 value,
1037 name: value,
1038 })),
1039 });
1040 const effort = (currentValue: string) => ({
1041 id: "reasoning_effort",
1042 name: "Reasoning effort",
1043 category: "thought_level",
1044 type: "select",
1045 currentValue,
1046 options: ["medium", "xhigh"].map((value) => ({ value, name: value })),
1047 });
1048 return openWithStoredPicks({
1049 agentId: "github-copilot-cli",
1050 setup: { configOptions: [copilotModel("claude-sonnet-5.5"), effort("medium")] },
1051 storedModel: "claude-sonnet-5.5",
1052 liveConfiguration: {
1053 models: [],
1054 currentModelId: null,
1055 configOptions: [
1056 {
1057 id: "reasoning_effort",
1058 label: "Reasoning effort",
1059 type: "select",
1060 role: "reasoning",
1061 currentValue: "xhigh",
1062 options: [
1063 { id: "medium", label: "medium" },
1064 { id: "xhigh", label: "xhigh" },
1065 ],
1066 },
1067 ],
1068 },
1069 pickFrames: [
1070 // The new session's own update replaces the shared live configuration.
1071 {
1072 type: "emit_inbound",
1073 frame: {
1074 kind: "notification",
1075 method: "session/update",
1076 params: {
1077 sessionId: "agent-session",
1078 update: {
1079 sessionUpdate: "config_option_update",
1080 configOptions: [copilotModel("claude-sonnet-5.5"), effort("medium")],
1081 },
1082 },
1083 },
1084 },
1085 outbound("session/set_config_option", {
1086 sessionId: "agent-session",
1087 configId: "model",
1088 value: "claude-sonnet-5.5",
1089 }),
1090 answer("session/set_config_option", {
1091 configOptions: [copilotModel("claude-sonnet-5.5"), effort("medium")],
1092 }),
1093 outbound("session/set_config_option", {
1094 sessionId: "agent-session",
1095 configId: "reasoning_effort",
1096 value: "xhigh",
1097 }),
1098 answer("session/set_config_option", {
1099 configOptions: [copilotModel("claude-sonnet-5.5"), effort("xhigh")],
1100 }),
1101 ],
1102 }).pipe(Effect.provide(layerTest));
1103 },
1104 );
1105
1106 it.effect.each([
1107 "config",
1108 "legacy",
1109 "updated-config",
1110 "removed-config",
1111 "configuration-update",
1112 "unavailable-before-configuration",
1113 ] as const)(
1114 "rejects an unavailable explicit model in a %s catalog before inference",
1115 (catalog) => {
1116 const duringTurn = catalog === "updated-config" || catalog === "removed-config";
1117 const duringConfiguration = catalog === "configuration-update";
1118 const changesOptions =
1119 duringConfiguration || catalog === "unavailable-before-configuration";
1120 const model = duringTurn || duringConfiguration ? "hermes" : "missing";
1121 const restrictedOption = {
1122 ...modelOption("model", "other"),
1123 options: [{ value: "other", name: "Other" }],
1124 };
1125 return openWithStoredPicks({
1126 setup: {
1127 ...(catalog === "legacy" || catalog === "removed-config"
1128 ? {
1129 models: {
1130 currentModelId: "other",
1131 availableModels: [{ modelId: "other", name: "Other" }],
1132 },
1133 }
1134 : {}),
1135 configOptions:
1136 catalog === "legacy"
1137 ? []
1138 : [
1139 {
1140 ...modelOption("model", "hermes"),
1141 options: [{ value: "hermes", name: "Hermes" }],
1142 },
1143 ...(changesOptions ? [permissionModeOption("ask")] : []),
1144 ],
1145 },
1146 storedModel: model,
1147 ...(duringTurn ? { turnModels: [model, model] } : {}),
1148 ...(changesOptions ? { storedModePick: "auto" } : {}),
1149 rejectedModel: model,
1150 pickFrames: duringTurn
1151 ? prompt(configOptionUpdate(catalog === "removed-config" ? [] : [restrictedOption]))
1152 : duringConfiguration
1153 ? [
1154 outbound("session/set_config_option", {
1155 sessionId: "agent-session",
1156 configId: "permission-mode",
1157 value: "auto",
1158 }),
1159 answer("session/set_config_option", {
1160 configOptions: [restrictedOption, permissionModeOption("auto")],
1161 }),
1162 ]
1163 : [],
1164 }).pipe(Effect.provide(layerTest));
1165 },
1166 );
1167
1168 // regression: #19519 models come from session model state, not a hardcoded list
1169 it.effect("keeps unadvertised default and auto selections agent-controlled", () =>
1170 Effect.gen(function* () {
1171 const { configurations } = yield* openWithStoredPicks({
1172 setup: {
1173 models: {
1174 currentModelId: "hermes",
1175 availableModels: ["hermes", "other"].map((modelId) => ({ modelId, name: modelId })),
1176 },
1177 },
1178 storedModel: "default",
1179 turnModels: ["auto", "default", "other", "default", "auto", "default", "auto"],
1180 pickFrames: [
1181 ...prompt(),
1182 ...prompt(),
1183 ...setModel("other"),
1184 ...prompt(
1185 configOptionUpdate([
1186 {
1187 ...modelOption("live-model", "other"),
1188 options: [{ value: "other", name: "Other" }],
1189 },
1190 ]),
1191 ),
1192 ...prompt(),
1193 ...prompt(),
1194 ...prompt(
1195 configOptionUpdate([
1196 {
1197 ...modelOption("replacement-model", "other", true),
1198 options: [
1199 {
1200 group: "models",
1201 name: "Models",
1202 options: [{ value: "other", name: "Other" }],
1203 },
1204 ],
1205 },
1206 ]),
1207 ),
1208 ...prompt(),
1209 ],
1210 });
1211 assert.deepEqual(
1212 configurations.map((configuration) => configuration?.currentModelId),
1213 ["hermes", "hermes", "hermes", "other", "other", "other", "other", "other"],
1214 );
1215 }).pipe(Effect.provide(layerTest)),
1216 );
1217 it.effect(
1218 "fails configuration when an option write errors for a reason other than refusal",
1219 () => {
1220 const sessionModel = (currentValue: string) => ({
1221 ...modelOption("model", currentValue),
1222 options: ["default", "named"].map((value) => ({ value, name: value })),
1223 });
1224 const thinking = {
1225 id: "thinking",
1226 name: "Thinking",
1227 category: "thought_level",
1228 type: "select",
1229 currentValue: "low",
1230 options: ["low", "high"].map((value) => ({ value, name: value })),
1231 };
1232 return openWithStoredPicks({
1233 setup: { configOptions: [sessionModel("default")] },
1234 storedModel: "named",
1235 storedOptions: [
1236 { id: "thinking", value: "high" },
1237 { id: "unavailable", value: "x" },
1238 ],
1239 failsConfiguration: true,
1240 pickFrames: [
1241 outbound("session/set_config_option", {
1242 sessionId: "agent-session",
1243 configId: "model",
1244 value: "named",
1245 }),
1246 answer("session/set_config_option", {
1247 configOptions: [sessionModel("named"), thinking],
1248 }),
1249 outbound("session/set_config_option", {
1250 sessionId: "agent-session",
1251 configId: "thinking",
1252 value: "high",
1253 }),
1254 {
1255 type: "emit_inbound",
1256 frame: {
1257 kind: "response",
1258 method: "session/set_config_option",
1259 error: { code: -32603, message: "Internal error" },
1260 },
1261 },
1262 ],
1263 }).pipe(Effect.provide(layerTest));
1264 },
1265 );
1266 const modelOptions = [
1267 { id: "fast", name: "Fast", category: "model", type: "boolean", currentValue: false },
1268 {
1269 id: " ",
1270 name: "Unnamed",
1271 category: "model",
1272 type: "select",
1273 currentValue: "unaddressable",
1274 options: [{ value: "unaddressable", name: "Unaddressable" }],
1275 },
1276 {
1277 id: "provider",
1278 name: "Provider",
1279 category: "model",
1280 type: "select",
1281 currentValue: "gateway",
1282 options: [
1283 {
1284 group: "hosted",
1285 name: "Hosted",
1286 options: [
1287 { value: "gateway", name: "Gateway" },
1288 { value: "codex", name: "Codex" },
1289 ],
1290 },
1291 ],
1292 },
1293 {
1294 id: "model",
1295 name: "Model",
1296 category: "model",
1297 type: "select",
1298 currentValue: "later-model",
1299 options: [{ value: "later-model", name: "Later model" }],
1300 },
1301 ] as const;
1302
1303 it.effect("opens a model from the catalog by writing the first usable model select", () =>
1304 Effect.gen(function* () {
1305 const setup = { sessionId: "agent-session", configOptions: modelOptions };
1306 const catalog = acpRegistryProbeResult(ProviderInstanceId.make("acp-registry-mode-pick"), {
1307 sessionId: setup.sessionId,
1308 initializeResult: { protocolVersion: 1 },
1309 sessionSetupResult: {
1310 ...setup,
1311 // The catalog uses the normalized groupId; ACP v1 sends group on the wire.
1312 configOptions: modelOptions.map((option) =>
1313 option.id === "provider"
1314 ? {
1315 ...option,
1316 options: [{ ...option.options[0], groupId: option.options[0].group }],
1317 }
1318 : option,
1319 ),
1320 },
1321 modelConfigId: "provider",
1322 });
1323 assert.deepEqual(catalog.models, [
1324 { id: "gateway", name: "Gateway", description: null },
1325 { id: "codex", name: "Codex", description: null },
1326 ]);
1327 assert.equal(catalog.currentModelId, "gateway");
1328 const model = catalog.models[1]?.id;
1329 assert.isDefined(model);
1330 const opened = yield* openWithStoredPicks({
1331 setup,
1332 pickFrames: [
1333 outbound("session/set_config_option", {
1334 sessionId: "agent-session",
1335 configId: "provider",
1336 value: "codex",
1337 }),
1338 answer("session/set_config_option", {
1339 configOptions: modelOptions.map((option) =>
1340 option.id === "provider" ? { ...option, currentValue: "codex" } : option,
1341 ),
1342 }),
1343 ],
1344 storedModel: model,
1345 });
1346 assert.equal(opened.configurations.at(-1)?.currentModelId, "codex");
1347 }).pipe(Effect.provide(layerTest)),
1348 );
1349 });
1350
1351 // regression: #21618 Claude Agent needs ACP v2 for native background lifecycle
1352 it.effect("launches Claude Agent on ACP v2 unless its instance environment decides", () =>
1353 Effect.gen(function* () {
1354 const launchSwitch = Effect.fn("launchSwitch")(function* (
1355 config: Record<string, unknown>,
1356 environment: NodeJS.ProcessEnv = {},
1357 ) {
1358 let launched: NodeJS.ProcessEnv | undefined;
1359 const instanceId = ProviderInstanceId.make("acp-registry-launch-environment");
1360 const adapter = yield* makeAcpRegistryAdapterV2({
1361 selfInvocation: yield* resolveSelfInvocation(),
1362 instanceId,
1363 settings: yield* decodeAcpRegistryAdapterSettings(config),
1364 environment,
1365 }).pipe(
1366 Effect.provide(
1367 Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({
1368 resolve: (_settings, _cwd, launchEnvironment) => {
1369 launched = launchEnvironment;
1370 return Effect.fail(
1371 new AcpRegistrySupport.AcpRegistryError({
1372 reason: "runner_unavailable",
1373 detail: "Recorded the launch environment.",
1374 }),
1375 );
1376 },
1377 }),
1378 ),
1379 );
1380 yield* adapter
1381 .openSession({
1382 threadId: ThreadId.make("thread-acp-registry-launch-environment"),
1383 providerSessionId: ProviderSessionId.make("provider-session-launch-environment"),
1384 modelSelection: { instanceId, model: "default" },
1385 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1386 runtimeMode: "full-access",
1387 interactionMode: "default",
1388 cwd: process.cwd(),
1389 }),
1390 })
1391 .pipe(Effect.flip);
1392 return launched?.CLAUDE_AGENT_ACP_EXPERIMENTAL_V2;
1393 });
1394
1395 assert.equal(yield* launchSwitch({ agentId: "claude-acp" }), "1");
1396 assert.equal(
1397 yield* launchSwitch(
1398 { source: "local", commandPath: "/opt/bin/claude-agent-acp" },
1399 { PATH: "/opt/bin" },
1400 ),
1401 "1",
1402 );
1403 assert.equal(
1404 yield* launchSwitch({ agentId: "claude-acp" }, { CLAUDE_AGENT_ACP_EXPERIMENTAL_V2: "0" }),
1405 "0",
1406 );
1407 assert.isUndefined(yield* launchSwitch({ agentId: "gemini" }));
1408 const fallback = yield* openClaudeReplaySession(
1409 [
1410 ...claudeFrames.open,
1411 claudeFrames.prompt(1)[0],
1412 claudeChild[0],
1413 claudeFrames.update(CLAUDE_ROOT_SESSION, {
1414 sessionUpdate: "tool_call_update",
1415 toolCallId: "agent-1",
1416 status: "completed",
1417 }),
1418 ...claudeFrames.prompt(1).slice(1),
1419 claudeFrames.idle("end_turn"),
1420 claudeFrames.closeRequest,
1421 claudeFrames.closed,
1422 ],
1423 undefined,
1424 false,
1425 );
1426 assert.isUndefined(
1427 fallback.runtime.hasPendingBackgroundWork,
1428 "an adapter without a continuation dispatcher must use ordinary prompt completion",
1429 );
1430 yield* fallback.runtime.startTurn(fallback.turnInput(1));
1431 const completed = yield* fallback.until((event) => event.type === "turn.terminal");
1432 assert.isTrue(
1433 completed.some(
1434 (event) =>
1435 event.type === "turn_item.updated" &&
1436 event.turnItem.type === "dynamic_tool" &&
1437 event.turnItem.nativeItemRef?.nativeId === "agent-1",
1438 ),
1439 );
1440 const terminal = completed.at(-1)!;
1441 if (terminal.type !== "turn.terminal") throw new Error("Missing fallback terminal");
1442 assert.equal(terminal.status, "completed");
1443 }).pipe(Effect.provide(layerTest)),
1444 );
1445
1446 // regression: #26695 cancelling a Copilot prompt kills its background agents
1447 it.effect("never steers Copilot by cancelling its prompt", () =>
1448 Effect.gen(function* () {
1449 const steering = Effect.fn("steering")(function* (config: Record<string, unknown>) {
1450 const instanceId = ProviderInstanceId.make("acp-registry-steering");
1451 const adapter = yield* makeAcpRegistryAdapterV2({
1452 selfInvocation: yield* resolveSelfInvocation(),
1453 instanceId,
1454 settings: yield* decodeAcpRegistryAdapterSettings(config),
1455 environment: {},
1456 }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
1457 const { turns } = yield* adapter.getCapabilities();
1458 return {
1459 supportsInterrupt: turns.supportsInterrupt,
1460 supportsActiveSteering: turns.supportsActiveSteering,
1461 supportsSteeringByInterruptRestart: turns.supportsSteeringByInterruptRestart,
1462 };
1463 });
1464 const copilot = {
1465 supportsInterrupt: true,
1466 supportsActiveSteering: false,
1467 supportsSteeringByInterruptRestart: false,
1468 };
1469
1470 assert.deepEqual(yield* steering({ agentId: "github-copilot-cli" }), copilot);
1471 assert.deepEqual(
1472 yield* steering({ source: "local", commandPath: "C:\\tools\\copilot.cmd" }),
1473 copilot,
1474 );
1475 assert.deepEqual(yield* steering({ agentId: "gemini" }), {
1476 ...copilot,
1477 supportsSteeringByInterruptRestart: true,
1478 });
1479 }).pipe(Effect.provide(layerTest)),
1480 );
1481
1482 it.effect("gives HTTP-capable agents T3's MCP server over HTTP", () =>
1483 Effect.gen(function* () {
1484 const selfInvocation = yield* resolveSelfInvocation();
1485 const mockAgentPath = yield* (yield* Path.Path).fromFileUrl(
1486 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1487 );
1488 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
1489 const endpoint = "http://127.0.0.1:43123/mcp";
1490 const sessionMcpServers = Effect.fn("sessionMcpServers")(function* (
1491 config: Record<string, unknown>,
1492 agentEnvironment: Record<string, string> = {},
1493 ) {
1494 const requests: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
1495 const instanceId = ProviderInstanceId.make("acp-registry-mcp-transport");
1496 const threadId = ThreadId.make("thread-acp-registry-mcp-transport");
1497 const mcpSession = {
1498 environmentId: EnvironmentId.make("environment-acp-registry-mcp-transport"),
1499 threadId,
1500 providerSessionId: "mcp-session-acp-registry-mcp-transport",
1501 providerInstanceId: instanceId,
1502 endpoint,
1503 browserToolsAvailable: false,
1504 };
1505 yield* mcpSessions.set({ ...mcpSession, authorizationHeader: "Bearer opened-token" });
1506 const adapter = yield* makeAcpRegistryAdapterV2({
1507 selfInvocation,
1508 instanceId,
1509 settings: yield* decodeAcpRegistryAdapterSettings(config),
1510 environment: {},
1511 nativeLogging: () => ({
1512 requestLogger: (event) =>
1513 Effect.sync(() => {
1514 if (event.status === "started") requests.push(event);
1515 }),
1516 }),
1517 }).pipe(
1518 Effect.provide(
1519 Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({
1520 resolve: () =>
1521 Effect.succeed({
1522 distribution: "local" as const,
1523 spawn: {
1524 command: process.execPath,
1525 args: [mockAgentPath],
1526 env: { T3_ACP_SESSION_LIFECYCLE: "1", ...agentEnvironment },
1527 },
1528 }),
1529 }),
1530 ),
1531 );
1532 const modelSelection = { instanceId, model: "default" } as const;
1533 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1534 runtimeMode: "full-access",
1535 interactionMode: "default",
1536 cwd: process.cwd(),
1537 });
1538 const runtime = yield* adapter.openSession({
1539 threadId,
1540 providerSessionId: ProviderSessionId.make("provider-session-acp-registry-mcp-transport"),
1541 modelSelection,
1542 runtimePolicy,
1543 });
1544 const providerThread = yield* runtime.ensureThread({
1545 threadId,
1546 modelSelection,
1547 runtimePolicy,
1548 });
1549 yield* mcpSessions.set({ ...mcpSession, authorizationHeader: "Bearer rotated-token" });
1550 yield* runtime.resumeThread({
1551 providerThread: {
1552 ...providerThread,
1553 nativeThreadRef: {
1554 driver: ACP_REGISTRY_PROVIDER,
1555 nativeId: "mock-session-2",
1556 strength: "strong",
1557 },
1558 },
1559 });
1560 const sent = (method: string) => {
1561 const payload = requests.find((event) => event.method === method)?.payload;
1562 return typeof payload === "object" && payload !== null
1563 ? Reflect.get(payload, "mcpServers")
1564 : undefined;
1565 };
1566 return { new: sent("session/new"), load: sent("session/load") };
1567 });
1568 const plainHttp = (authorization: string) => [
1569 {
1570 type: "http",
1571 name: "t3-code",
1572 url: endpoint,
1573 headers: [{ name: "Authorization", value: authorization }],
1574 },
1575 ];
1576 const http = (authorization: string) => [
1577 {
1578 type: "http",
1579 name: "t3-code",
1580 url: endpoint,
1581 headers: [
1582 { name: "Authorization", value: authorization },
1583 { name: "t3-tool-exposure", value: "deferred" },
1584 ],
1585 },
1586 ];
1587 const stdio = (authorization: string) => [
1588 {
1589 name: "t3-code",
1590 command: selfInvocation.command,
1591 args: [...selfInvocationArgs(selfInvocation, ["acp-mcp-bridge"])],
1592 env: [
1593 { name: "ELECTRON_RUN_AS_NODE", value: "1" },
1594 { name: "T3_ACP_MCP_ENDPOINT", value: endpoint },
1595 { name: "T3_ACP_MCP_AUTHORIZATION", value: authorization },
1596 ],
1597 },
1598 ];
1599
1600 assert.deepEqual(
1601 yield* sessionMcpServers({ agentId: "github-copilot-cli" }, { T3_ACP_MCP_HTTP: "1" }),
1602 { new: http("Bearer opened-token"), load: http("Bearer rotated-token") },
1603 );
1604 const acp = [{ type: "acp", name: "t3-code", serverId: "t3-code" }];
1605 assert.deepEqual(
1606 yield* sessionMcpServers(
1607 { agentId: "github-copilot-cli" },
1608 { T3_ACP_MCP_HTTP: "1", T3_ACP_MCP_ACP: "1" },
1609 ),
1610 { new: acp, load: acp },
1611 );
1612 assert.deepEqual(yield* sessionMcpServers({ agentId: "github-copilot-cli" }), {
1613 new: stdio("Bearer opened-token"),
1614 load: stdio("Bearer rotated-token"),
1615 });
1616 assert.deepEqual(yield* sessionMcpServers({ agentId: "gemini" }, { T3_ACP_MCP_HTTP: "1" }), {
1617 new: stdio("Bearer opened-token"),
1618 load: stdio("Bearer rotated-token"),
1619 });
1620 // Command Code cannot start the stdio bridge on Windows: it spawns MCP commands through
1621 // cmd.exe, which splits the unquoted T3 executable path at the space.
1622 const commandCode = {
1623 source: "local",
1624 commandPath: "C:\\tools\\cmdc.exe",
1625 commandArgs: ["acp"],
1626 };
1627 // Command Code is not Copilot: no deferred tool-exposure header.
1628 assert.deepEqual(yield* sessionMcpServers(commandCode, { T3_ACP_MCP_HTTP: "1" }), {
1629 new: plainHttp("Bearer opened-token"),
1630 load: plainHttp("Bearer rotated-token"),
1631 });
1632 assert.deepEqual(yield* sessionMcpServers(commandCode), {
1633 new: stdio("Bearer opened-token"),
1634 load: stdio("Bearer rotated-token"),
1635 });
1636 // Any other local agent keeps the stdio bridge.
1637 assert.deepEqual(
1638 yield* sessionMcpServers(
1639 { source: "local", commandPath: "C:\\tools\\node.exe", commandArgs: ["agent.mjs"] },
1640 { T3_ACP_MCP_HTTP: "1" },
1641 ),
1642 { new: stdio("Bearer opened-token"), load: stdio("Bearer rotated-token") },
1643 );
1644 }).pipe(Effect.provide(layerTest)),
1645 );
1646
1647 it.effect("the agent process env names the thread it serves", () =>
1648 Effect.gen(function* () {
1649 const selfInvocation = yield* resolveSelfInvocation();
1650 const mockAgentPath = yield* (yield* Path.Path).fromFileUrl(
1651 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1652 );
1653 const endpoint = "http://127.0.0.1:43123/mcp";
1654 const instanceId = ProviderInstanceId.make("acp-registry-thread-env");
1655 const threadId = ThreadId.make("thread-acp-registry-thread-env");
1656 yield* (yield* McpProviderSessions.McpProviderSessions).set({
1657 environmentId: EnvironmentId.make("environment-acp-registry-thread-env"),
1658 threadId,
1659 providerSessionId: "mcp-session-acp-registry-thread-env",
1660 providerInstanceId: instanceId,
1661 endpoint,
1662 authorizationHeader: "Bearer thread-env-token",
1663 browserToolsAvailable: false,
1664 });
1665 // Several agents can run from one directory at once; the spawn env is how
1666 // a process the agent starts (an MCP server, a shell tool) finds its own
1667 // T3 thread, the same way Claude and Codex sessions do.
1668 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1669 const spawnEnvironments: Array<Record<string, unknown> | undefined> = [];
1670 const capturingSpawner = ChildProcessSpawner.make((command) =>
1671 Effect.sync(() => {
1672 if (command._tag === "StandardCommand") spawnEnvironments.push(command.options.env);
1673 }).pipe(Effect.andThen(spawner.spawn(command))),
1674 );
1675 const withCapturedSpawns = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1676 effect.pipe(
1677 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, capturingSpawner),
1678 );
1679 const adapter = yield* withCapturedSpawns(
1680 makeAcpRegistryAdapterV2({
1681 selfInvocation,
1682 instanceId,
1683 settings: yield* decodeAcpRegistryAdapterSettings({ agentId: "claude-acp" }),
1684 environment: {},
1685 }).pipe(
1686 Effect.provide(
1687 Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({
1688 resolve: () =>
1689 Effect.succeed({
1690 distribution: "local" as const,
1691 spawn: {
1692 command: process.execPath,
1693 args: [mockAgentPath],
1694 env: { T3_ACP_SESSION_LIFECYCLE: "1" },
1695 },
1696 }),
1697 }),
1698 ),
1699 ),
1700 );
1701 const modelSelection = { instanceId, model: "default" } as const;
1702 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1703 runtimeMode: "full-access",
1704 interactionMode: "default",
1705 cwd: process.cwd(),
1706 });
1707 const runtime = yield* withCapturedSpawns(
1708 adapter.openSession({
1709 threadId,
1710 providerSessionId: ProviderSessionId.make("provider-session-acp-registry-thread-env"),
1711 modelSelection,
1712 runtimePolicy,
1713 }),
1714 );
1715 yield* withCapturedSpawns(runtime.ensureThread({ threadId, modelSelection, runtimePolicy }));
1716 const agentEnvironment = spawnEnvironments.find(
1717 (environment) => environment?.T3_ACP_SESSION_LIFECYCLE === "1",
1718 );
1719 assert.isDefined(agentEnvironment, "the agent itself must have been spawned");
1720 assert.equal(agentEnvironment?.T3CODE_THREAD_ID, "thread-acp-registry-thread-env");
1721 assert.equal(agentEnvironment?.T3_ACP_MCP_ENDPOINT, endpoint);
1722 assert.equal(agentEnvironment?.T3_ACP_MCP_AUTHORIZATION, "Bearer thread-env-token");
1723 }).pipe(Effect.provide(layerTest)),
1724 );
1725
1726 it.effect.each(["before", "after"] as const)(
1727 "reconciles a full prompt echo %s acknowledgment",
1728 (ordering) =>
1729 Effect.gen(function* () {
1730 const runtimeInstructions = {
1731 type: "text",
1732 text: buildRuntimeInstructions({ harness: "acpRegistry", model: "default" }),
1733 };
1734 const promptBlocks = (ordinal: number) => [
1735 {
1736 type: "text",
1737 text:
1738 ordinal === 1
1739 ? t3AcpPromptWithInstructions({
1740 prompt: "test prompt",
1741 state: { interactionMode: "default", hasT3Mcp: false, hasDeviceTools: false },
1742 })
1743 : "test prompt",
1744 },
1745 ...(ordinal === 1 ? [runtimeInstructions] : []),
1746 ];
1747 const echo = (messageId: string, content: ReadonlyArray<unknown>) =>
1748 claudeFrames.update(CLAUDE_ROOT_SESSION, {
1749 sessionUpdate: "user_message",
1750 messageId,
1751 content,
1752 });
1753 const promptText = (ordinal: number) =>
1754 promptBlocks(ordinal)
1755 .map((block) => block.text)
1756 .join("\n");
1757 const frames = (ordinal: number) => {
1758 const [request, , acknowledgment] = claudeFrames.prompt(ordinal);
1759 const matching = echo(`echo-${ordinal}`, promptBlocks(ordinal));
1760 return [
1761 request,
1762 echo("different-blocks", [
1763 {
1764 type: "text",
1765 text: promptText(ordinal),
1766 annotations: { audience: ["user"] },
1767 },
1768 ]),
1769 ...(ordering === "before" ? [matching, acknowledgment] : [acknowledgment, matching]),
1770 claudeFrames.update(CLAUDE_ROOT_SESSION, {
1771 sessionUpdate: "user_message_chunk",
1772 messageId: `echo-${ordinal}`,
1773 content: { type: "text", text: "updated echo" },
1774 }),
1775 echo(`echo-${ordinal}`, [{ type: "text", text: "updated echo" }]),
1776 echo("second-id", promptBlocks(ordinal)),
1777 echo("unmatched", [{ type: "text", text: "Continue the review." }]),
1778 claudeFrames.idle("end_turn"),
1779 ];
1780 };
1781 const session = yield* openClaudeReplaySession(
1782 [
1783 ...claudeFrames.open,
1784 ...frames(1),
1785 ...frames(2),
1786 claudeFrames.closeRequest,
1787 claudeFrames.closed,
1788 ],
1789 undefined,
1790 false,
1791 );
1792 for (const ordinal of [1, 2]) {
1793 yield* session.runtime.startTurn(session.turnInput(ordinal));
1794 const events = yield* session.until((event) => event.type === "turn.terminal");
1795 const messages = events.flatMap((event) =>
1796 event.type === "message.updated" && event.message.role === "user"
1797 ? [event.message]
1798 : [],
1799 );
1800 const items = events.flatMap((event) =>
1801 event.type === "turn_item.updated" && event.turnItem.type === "user_message"
1802 ? [event.turnItem]
1803 : [],
1804 );
1805 const expected = new Set([promptText(ordinal), "Continue the review."]);
1806 assert.deepEqual(new Set(messages.map((message) => message.text)), expected);
1807 assert.equal(new Set(messages.map((message) => message.id)).size, 3);
1808 assert.equal(new Set(items.map((item) => item.id)).size, 3);
1809 for (const id of ["different-blocks", "second-id", "unmatched"]) {
1810 assert.isTrue(
1811 items.some((item) => item.nativeItemRef?.nativeId?.endsWith(`:user:message:${id}`)),
1812 `${id} remains visible`,
1813 );
1814 }
1815 }
1816 }).pipe(Effect.provide(layerTest)),
1817 );
1818
1819 it.effect("settles Claude's accepted foreground reply while retaining child output", () =>
1820 Effect.gen(function* () {
1821 const gate = makeProviderReplayGate(["accepted", "child-output", "wake"]);
1822 const { update, idle, prompt } = claudeFrames;
1823 const session = yield* openClaudeReplaySession(
1824 [
1825 ...claudeFrames.open,
1826 prompt(1)[0],
1827 idle("end_turn"),
1828 claudeMarker("before acceptance"),
1829 { ...prompt(1)[1], label: "accepted" },
1830 ...prompt(1).slice(2),
1831 update(CLAUDE_ROOT_SESSION, {
1832 sessionUpdate: "tool_call_update",
1833 toolCallId: "agent-1",
1834 name: "Agent",
1835 title: "Review",
1836 kind: "think",
1837 status: "pending",
1838 rawInput: { description: "Review" },
1839 }),
1840 update(CLAUDE_ROOT_SESSION, {
1841 sessionUpdate: "tool_call_update",
1842 toolCallId: "malformed-agent",
1843 name: "Agent",
1844 title: "Incomplete agent",
1845 kind: "think",
1846 status: "pending",
1847 rawInput: { description: "Never receives a prompt" },
1848 }),
1849 update(CLAUDE_ROOT_SESSION, {
1850 sessionUpdate: "tool_call_update",
1851 toolCallId: "failed-task",
1852 name: "Task",
1853 title: "Malformed task",
1854 kind: "think",
1855 status: "failed",
1856 rawInput: { description: "Missing prompt" },
1857 }),
1858 ...claudeChild.slice(0, 2),
1859 update("child-1", {
1860 sessionUpdate: "agent_message_chunk",
1861 messageId: "early-reply",
1862 content: { type: "text", text: "First review result." },
1863 }),
1864 claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
1865 ...claudeChild.slice(2),
1866 update("child-1", { sessionUpdate: "state_update", state: "running" }),
1867 ...claudeUnrelatedChildren,
1868 update(CLAUDE_ROOT_SESSION, {
1869 sessionUpdate: "agent_message_chunk",
1870 messageId: "reply",
1871 content: { type: "text", text: "The review is running." },
1872 }),
1873 idle("end_turn"),
1874 {
1875 ...update("child-1", {
1876 sessionUpdate: "agent_message_chunk",
1877 messageId: "child-reply",
1878 content: { type: "text", text: "Found the regression." },
1879 }),
1880 label: "child-output",
1881 },
1882 update("child-1", {
1883 sessionUpdate: "usage_update",
1884 used: 2_500,
1885 size: 10_000,
1886 cost: { amount: 0.42, currency: "USD" },
1887 }),
1888 update("child-1", {
1889 sessionUpdate: "session_info_update",
1890 title: "Child review",
1891 updatedAt: "2026-10-19T00:00:00Z",
1892 }),
1893 update("child-1", {
1894 sessionUpdate: "state_update",
1895 state: "idle",
1896 stopReason: "end_turn",
1897 usage: { totalTokens: 3_000, inputTokens: 2_500, outputTokens: 500, thoughtTokens: 0 },
1898 }),
1899 claudeMarker("child output"),
1900 {
1901 ...update(CLAUDE_ROOT_SESSION, {
1902 sessionUpdate: "user_message",
1903 messageId: "wake-user",
1904 content: [{ type: "text", text: "Continue the review." }],
1905 }),
1906 label: "wake",
1907 },
1908 idle("end_turn"),
1909 claudeMarker("continuation idle"),
1910 claudeFrames.closeRequest,
1911 claudeFrames.closed,
1912 ],
1913 gate,
1914 );
1915 yield* session.runtime.startTurn(session.turnInput(1));
1916 const beforeAcceptance = yield* session.throughMarker("before acceptance");
1917 assert.isFalse(beforeAcceptance.some((event) => event.type === "turn.terminal"));
1918 gate.release("accepted");
1919 const foreground = yield* session.until((event) => event.type === "turn.terminal");
1920 const foregroundTerminal = foreground.at(-1)!;
1921 if (foregroundTerminal.type !== "turn.terminal")
1922 throw new Error("Missing foreground terminal");
1923 assert.equal(foregroundTerminal.status, "completed");
1924 const earlyResult = foreground.findLast(
1925 (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
1926 );
1927 assert.isDefined(earlyResult, "a child can finish before its spawn acknowledgement");
1928 if (earlyResult?.type !== "subagent.updated") throw new Error("Missing early result");
1929 assert.equal(earlyResult.subagent.result, "First review result.");
1930 const earlyItem = foreground.findLast(
1931 (event) =>
1932 event.type === "turn_item.updated" &&
1933 event.turnItem.type === "subagent" &&
1934 event.turnItem.status === "completed",
1935 );
1936 if (earlyItem?.type !== "turn_item.updated" || earlyItem.turnItem.type !== "subagent")
1937 throw new Error("Missing early parent item");
1938 assert.equal(earlyItem.turnItem.result, "First review result.");
1939 assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
1940 gate.release("child-output");
1941 const childOutput = yield* session.throughMarker("child output");
1942 const message = childOutput.find(
1943 (event) =>
1944 event.type === "message.updated" && event.message.text === "Found the regression.",
1945 );
1946 assert.isDefined(message, "child output survives foreground completion");
1947 if (message?.type !== "message.updated") throw new Error("Missing child output");
1948 assert.notEqual(message.message.threadId, session.turnInput(1).threadId);
1949 const childThreads = childOutput.flatMap((event) =>
1950 event.type === "provider_thread.updated" &&
1951 event.providerThread.appThreadId === message.message.threadId
1952 ? [event.providerThread]
1953 : [],
1954 );
1955 assert.deepEqual(
1956 childThreads.map((thread) => thread.contextUsage),
1957 [
1958 { usedTokens: 2_500, maxTokens: 10_000, cost: { amount: 0.42, currency: "USD" } },
1959 { usedTokens: 2_500, maxTokens: 10_000, cost: { amount: 0.42, currency: "USD" } },
1960 ],
1961 );
1962 assert.deepEqual(childThreads.at(-1)?.nativeMetadata, {
1963 title: "Child review",
1964 updatedAt: "2026-10-19T00:00:00Z",
1965 });
1966 assert.isFalse(childOutput.some((event) => event.type === "turn.terminal"));
1967 assert.isTrue(
1968 childOutput.some(
1969 (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
1970 ),
1971 );
1972 const latestChild = childOutput.findLast((event) => event.type === "subagent.updated");
1973 if (latestChild?.type !== "subagent.updated") throw new Error("Missing current child result");
1974 assert.equal(latestChild.subagent.result, "Found the regression.");
1975 const rootItems = new Map(
1976 [...foreground, ...childOutput].flatMap((event) =>
1977 event.type === "turn_item.updated" &&
1978 event.turnItem.threadId === session.turnInput(1).threadId
1979 ? [[event.turnItem.id, event.turnItem] as const]
1980 : [],
1981 ),
1982 );
1983 const generic = [...rootItems.values()].filter((item) => item.type === "dynamic_tool");
1984 assert.isFalse(
1985 generic.some((item) => item.nativeItemRef?.nativeId === "agent-1"),
1986 "native subagents never project a duplicate generic tool",
1987 );
1988 const malformed = generic.find((item) => item.nativeItemRef?.nativeId === "malformed-agent");
1989 assert.isDefined(malformed, "unclassified tools still project on foreground completion");
1990 assert.equal(malformed?.status, "completed");
1991 const failed = generic.find((item) => item.nativeItemRef?.nativeId === "failed-task");
1992 assert.isDefined(failed, "unclassified terminal tools retain ordinary failures");
1993 assert.equal(failed?.status, "failed");
1994 assert.isFalse(
1995 [...rootItems.values()].some((item) => item.type === "user_message"),
1996 "the submitted root prompt is already owned by the app",
1997 );
1998 assert.deepEqual(pendingBackgroundTurnItems({ turnItems: [...rootItems.values()] }), []);
1999 assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
2000 gate.release("wake");
2001 yield* Queue.take(session.offered);
2002 yield* session.throughMarker("continuation idle");
2003 const offer = session.offers[0]!;
2004 yield* offer.dispatchIfCurrent!(Effect.void);
2005 yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
2006 const continuation = yield* session.until((event) => event.type === "turn.terminal");
2007 const terminal = continuation.at(-1)!;
2008 if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal");
2009 assert.equal(
2010 terminal.status,
2011 "completed",
2012 "buffered acceptance preserves the latest live idle",
2013 );
2014 assert.isFalse(
2015 continuation.some(
2016 (event) => event.type === "turn_item.updated" && event.turnItem.type === "user_message",
2017 ),
2018 "autonomous root echoes only signal acceptance",
2019 );
2020 }).pipe(Effect.provide(layerTest)),
2021 );
2022
2023 // Copilot holds session/prompt while an attached async shell runs (github/copilot-cli#5293);
2024 // its documented foreground-done signal is the opt-in assistant.idle session event.
2025 it.effect("settles Copilot's reply on assistant.idle while an async shell holds the prompt", () =>
2026 Effect.gen(function* () {
2027 const sessionId = "copilot-session";
2028 const sessionEvent = (type: string) => ({
2029 type: "emit_inbound",
2030 frame: {
2031 kind: "notification",
2032 method: "github.com/copilot/sessionEvent",
2033 params: { sessionId, type, data: {} },
2034 },
2035 });
2036 const update = (sessionUpdate: Record<string, unknown>) =>
2037 claudeFrames.update(sessionId, sessionUpdate);
2038 const session = yield* openClaudeReplaySession(
2039 [
2040 {
2041 type: "expect_outbound",
2042 frame: { kind: "request", method: "initialize", params: "<any>" },
2043 },
2044 {
2045 type: "emit_inbound",
2046 frame: {
2047 kind: "response",
2048 method: "initialize",
2049 result: {
2050 protocolVersion: 1,
2051 agentInfo: { name: "Copilot", version: "1.0.110" },
2052 agentCapabilities: { loadSession: true },
2053 authMethods: [],
2054 },
2055 },
2056 },
2057 {
2058 type: "expect_outbound",
2059 frame: { kind: "request", method: "session/new", params: "<any>" },
2060 },
2061 {
2062 type: "emit_inbound",
2063 frame: { kind: "response", method: "session/new", result: { sessionId } },
2064 },
2065 {
2066 type: "expect_outbound",
2067 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2068 },
2069 // A previous prompt's idle can land before this prompt's turn starts.
2070 sessionEvent("assistant.idle"),
2071 update({ sessionUpdate: "session_info_update", title: "after stale idle" }),
2072 sessionEvent("assistant.turn_start"),
2073 update({
2074 sessionUpdate: "tool_call",
2075 toolCallId: "shell-1",
2076 title: "sleep 120",
2077 kind: "execute",
2078 status: "completed",
2079 rawInput: { command: "sleep 120", mode: "async", detach: false },
2080 }),
2081 update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "ok" } }),
2082 sessionEvent("assistant.idle"),
2083 update({ sessionUpdate: "session_info_update", title: "after foreground idle" }),
2084 // The shell never exits, so the first session/prompt is never answered.
2085 {
2086 type: "expect_outbound",
2087 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2088 },
2089 sessionEvent("assistant.turn_start"),
2090 update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "two" } }),
2091 sessionEvent("assistant.idle"),
2092 update({ sessionUpdate: "session_info_update", title: "after second idle" }),
2093 ],
2094 undefined,
2095 false,
2096 "github-copilot-cli",
2097 );
2098 yield* session.runtime.startTurn(session.turnInput(1));
2099 const stale = yield* session.throughMarker("after stale idle");
2100 assert.isFalse(stale.some((event) => event.type === "turn.terminal"));
2101 const foreground = yield* session.throughMarker("after foreground idle");
2102 const terminal = foreground.find((event) => event.type === "turn.terminal");
2103 assert.isDefined(terminal, "the run settles once Copilot's foreground work is idle");
2104 assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed");
2105 yield* session.runtime.startTurn(session.turnInput(2));
2106 const second = yield* session.throughMarker("after second idle");
2107 const secondTerminal = second.find((event) => event.type === "turn.terminal");
2108 assert.equal(secondTerminal?.type === "turn.terminal" ? secondTerminal.runOrdinal : null, 2);
2109 }).pipe(Effect.provide(layerTest)),
2110 );
2111
2112 // Copilot wakes its root agent when a background subagent finishes, after the run settled.
2113 it.effect("does not drop Copilot's root reply when a finished background agent wakes it", () =>
2114 Effect.gen(function* () {
2115 const sessionId = "copilot-session";
2116 const sessionEvent = (type: string) => ({
2117 type: "emit_inbound",
2118 frame: {
2119 kind: "notification",
2120 method: "github.com/copilot/sessionEvent",
2121 params: { sessionId, type, data: {} },
2122 },
2123 });
2124 const update = (sessionUpdate: Record<string, unknown>) =>
2125 claudeFrames.update(sessionId, sessionUpdate);
2126 const session = yield* openClaudeReplaySession(
2127 [
2128 {
2129 type: "expect_outbound",
2130 frame: { kind: "request", method: "initialize", params: "<any>" },
2131 },
2132 {
2133 type: "emit_inbound",
2134 frame: {
2135 kind: "response",
2136 method: "initialize",
2137 result: {
2138 protocolVersion: 1,
2139 agentInfo: { name: "Copilot", version: "1.0.112" },
2140 agentCapabilities: { loadSession: true },
2141 authMethods: [],
2142 },
2143 },
2144 },
2145 {
2146 type: "expect_outbound",
2147 frame: { kind: "request", method: "session/new", params: "<any>" },
2148 },
2149 {
2150 type: "emit_inbound",
2151 frame: { kind: "response", method: "session/new", result: { sessionId } },
2152 },
2153 {
2154 type: "expect_outbound",
2155 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2156 },
2157 sessionEvent("assistant.turn_start"),
2158 update({
2159 sessionUpdate: "agent_message_chunk",
2160 content: { type: "text", text: "Agents are still working." },
2161 }),
2162 sessionEvent("assistant.idle"),
2163 update({ sessionUpdate: "session_info_update", title: "after foreground idle" }),
2164 // The background agent finishes; Copilot reads it and starts a new root turn.
2165 sessionEvent("assistant.turn_start"),
2166 update({
2167 sessionUpdate: "tool_call",
2168 toolCallId: "read-agent-1",
2169 title: "read_agent",
2170 kind: "other",
2171 status: "completed",
2172 rawInput: { agent_id: "agent-1" },
2173 }),
2174 update({
2175 sessionUpdate: "agent_message_chunk",
2176 content: { type: "text", text: "Agent 1 finished" },
2177 }),
2178 sessionEvent("assistant.idle"),
2179 {
2180 type: "emit_inbound",
2181 frame: {
2182 kind: "response",
2183 method: "session/prompt",
2184 result: { stopReason: "end_turn" },
2185 },
2186 },
2187 update({ sessionUpdate: "session_info_update", title: "after wake idle" }),
2188 ],
2189 undefined,
2190 true,
2191 "github-copilot-cli",
2192 );
2193 yield* session.runtime.startTurn(session.turnInput(1));
2194 const foreground = yield* session.throughMarker("after foreground idle");
2195 assert.isDefined(foreground.find((event) => event.type === "turn.terminal"));
2196 const wake = yield* session.throughMarker("after wake idle");
2197 assert.isTrue(
2198 session.offers.length > 0 || JSON.stringify(wake).includes("Agent 1 finished"),
2199 "the woken root reply is shown or opens a continuation run",
2200 );
2201 yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
2202 const continuation = yield* session.until((event) => event.type === "turn.terminal");
2203 assert.include(JSON.stringify(continuation), "Agent 1 finished");
2204 assert.include(JSON.stringify(continuation.at(-1)), '"status":"completed"');
2205 }).pipe(Effect.provide(layerTest)),
2206 );
2207
2208 // regression: #38599 Hermes replies on its own when a background process it started exits
2209 it.effect.each([
2210 { launch: "hermes acp", commandPath: "hermes", commandArgs: ["acp"] },
2211 { launch: "a wrapper", commandPath: "node", commandArgs: ["hermes-acp.mjs"] },
2212 ])("does not drop Hermes' reply after a background process finishes ($launch)", (launch) =>
2213 Effect.gen(function* () {
2214 const gate = makeProviderReplayGate(["process-exit"]);
2215 const sessionId = "hermes-session";
2216 const update = (sessionUpdate: Record<string, unknown>) =>
2217 claudeFrames.update(sessionId, sessionUpdate);
2218 const session = yield* openClaudeReplaySession(
2219 [
2220 {
2221 type: "expect_outbound",
2222 frame: { kind: "request", method: "initialize", params: "<any>" },
2223 },
2224 {
2225 type: "emit_inbound",
2226 frame: {
2227 kind: "response",
2228 method: "initialize",
2229 result: {
2230 protocolVersion: 1,
2231 agentInfo: { name: "hermes-agent", version: "0.23.1" },
2232 agentCapabilities: { loadSession: true },
2233 authMethods: [],
2234 },
2235 },
2236 },
2237 {
2238 type: "expect_outbound",
2239 frame: { kind: "request", method: "session/new", params: "<any>" },
2240 },
2241 {
2242 type: "emit_inbound",
2243 frame: { kind: "response", method: "session/new", result: { sessionId } },
2244 },
2245 {
2246 type: "expect_outbound",
2247 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2248 },
2249 update({
2250 sessionUpdate: "agent_message_chunk",
2251 content: { type: "text", text: "Started it in the background." },
2252 }),
2253 {
2254 type: "emit_inbound",
2255 frame: {
2256 kind: "response",
2257 method: "session/prompt",
2258 result: { stopReason: "end_turn" },
2259 },
2260 },
2261 {
2262 ...update({
2263 sessionUpdate: "agent_message_chunk",
2264 content: { type: "text", text: "The background command printed DONE" },
2265 }),
2266 label: "process-exit",
2267 },
2268 update({ sessionUpdate: "session_info_update", title: "after completion reply" }),
2269 ],
2270 gate,
2271 true,
2272 { source: "local", commandPath: launch.commandPath, commandArgs: launch.commandArgs },
2273 );
2274 yield* session.runtime.startTurn(session.turnInput(1));
2275 const foreground = yield* session.until((event) => event.type === "turn.terminal");
2276 assert.include(JSON.stringify(foreground.at(-1)), '"status":"completed"');
2277 gate.release("process-exit");
2278 yield* Queue.take(session.offered);
2279 yield* session.throughMarker("after completion reply");
2280 yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
2281 yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
2282 yield* TestClock.adjust("10 seconds");
2283 const continuation = yield* session.until((event) => event.type === "turn.terminal");
2284 assert.include(JSON.stringify(continuation), "printed DONE");
2285 assert.include(JSON.stringify(continuation.at(-1)), '"status":"completed"');
2286 }).pipe(Effect.provide(layerTest)),
2287 );
2288
2289 it.effect("protects Hermes background work when a wrapper launches it on replacement", () =>
2290 Effect.gen(function* () {
2291 const gate = makeProviderReplayGate(["process-exit"]);
2292 const request = (method: string) => ({
2293 type: "expect_outbound",
2294 frame: { kind: "request", method, params: "<any>" },
2295 });
2296 const respond = (method: string, result: object) => ({
2297 type: "emit_inbound",
2298 frame: { kind: "response", method, result },
2299 });
2300 const open = (sessionId: string, name: string) => [
2301 request("initialize"),
2302 respond("initialize", { protocolVersion: 1, agentInfo: { name, version: "1.0.0" } }),
2303 request("session/new"),
2304 respond("session/new", { sessionId }),
2305 ];
2306 const sessionId = "hermes-replacement";
2307 const session = yield* openClaudeReplaySession(
2308 open("initial-session", "generic-agent"),
2309 gate,
2310 true,
2311 { source: "local", commandPath: "node", commandArgs: ["agent-wrapper.mjs"] },
2312 [
2313 ...open(sessionId, "hermes-agent"),
2314 request("session/prompt"),
2315 respond("session/prompt", { stopReason: "end_turn" }),
2316 {
2317 ...claudeFrames.update(sessionId, {
2318 sessionUpdate: "agent_message_chunk",
2319 content: { type: "text", text: "Background command finished" },
2320 }),
2321 label: "process-exit",
2322 },
2323 ],
2324 );
2325 const { threadId, modelSelection, runtimePolicy } = session.turnInput(1);
2326 const replaceThread = {
2327 threadId,
2328 modelSelection,
2329 runtimePolicy,
2330 forceNewNativeThread: true,
2331 };
2332 const pendingWork = session.runtime.hasPendingBackgroundWork ?? Effect.succeed(false);
2333 assert.isFalse(yield* pendingWork);
2334 const providerThread = yield* session.runtime.ensureThread(replaceThread);
2335 yield* session.runtime.startTurn({ ...session.turnInput(1), providerThread });
2336 assert.equal((yield* session.terminal).status, "completed");
2337
2338 gate.release("process-exit");
2339 yield* Queue.take(session.offered);
2340 assert.isTrue(yield* pendingWork);
2341 const error = yield* session.runtime.ensureThread(replaceThread).pipe(Effect.flip);
2342 assert.include(String(error.cause), "background work is active");
2343 }).pipe(Effect.provide(layerTest)),
2344 );
2345
2346 // Copilot flattens MCP titles and reports kind "read" for MCP calls and glob ("other" for rg);
2347 // its native tool.execution_start event carries the real identity.
2348 it.effect.each(["glob", "rg"])("keeps Copilot's MCP and %s identity", (toolName) =>
2349 Effect.gen(function* () {
2350 const sessionId = "copilot-session";
2351 const executionStart = (data: Record<string, unknown>) => ({
2352 type: "emit_inbound",
2353 frame: {
2354 kind: "notification",
2355 method: "github.com/copilot/sessionEvent",
2356 params: { sessionId, type: "tool.execution_start", data },
2357 },
2358 });
2359 const update = (sessionUpdate: Record<string, unknown>) =>
2360 claudeFrames.update(sessionId, sessionUpdate);
2361 const session = yield* openClaudeReplaySession(
2362 [
2363 {
2364 type: "expect_outbound",
2365 frame: { kind: "request", method: "initialize", params: "<any>" },
2366 },
2367 {
2368 type: "emit_inbound",
2369 frame: {
2370 kind: "response",
2371 method: "initialize",
2372 result: {
2373 protocolVersion: 1,
2374 agentInfo: { name: "Copilot", version: "1.0.112" },
2375 agentCapabilities: { loadSession: true },
2376 authMethods: [],
2377 },
2378 },
2379 },
2380 {
2381 type: "expect_outbound",
2382 frame: { kind: "request", method: "session/new", params: "<any>" },
2383 },
2384 {
2385 type: "emit_inbound",
2386 frame: { kind: "response", method: "session/new", result: { sessionId } },
2387 },
2388 {
2389 type: "expect_outbound",
2390 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2391 },
2392 executionStart({
2393 toolCallId: "mcp-call",
2394 mcpServerName: "demo-library",
2395 mcpToolName: "search_books",
2396 }),
2397 update({
2398 sessionUpdate: "tool_call",
2399 toolCallId: "mcp-call",
2400 title: "demo-library-search_books",
2401 kind: "read",
2402 status: "completed",
2403 rawInput: { arguments: { query: "paper airplanes" }, limit: 2 },
2404 }),
2405 executionStart({
2406 toolCallId: "native-search",
2407 toolName,
2408 toolTitle: "Finding files",
2409 arguments: { pattern: "*.ts", paths: ["/workspace"] },
2410 }),
2411 update({
2412 sessionUpdate: "tool_call",
2413 toolCallId: "native-search",
2414 title: "Finding files matching *.ts",
2415 kind: toolName === "rg" ? "other" : "read",
2416 status: "completed",
2417 rawInput: { pattern: "*.ts", paths: ["/workspace"] },
2418 locations: [{ path: "/workspace" }],
2419 }),
2420 update({ sessionUpdate: "session_info_update", title: "after tools" }),
2421 ],
2422 undefined,
2423 false,
2424 "github-copilot-cli",
2425 );
2426 yield* session.runtime.startTurn(session.turnInput(1));
2427 const events = yield* session.throughMarker("after tools");
2428 const lastItem = (nativeId: string) =>
2429 events
2430 .flatMap((event) =>
2431 event.type === "turn_item.updated" &&
2432 event.turnItem.nativeItemRef?.nativeId === nativeId
2433 ? [event.turnItem]
2434 : [],
2435 )
2436 .at(-1);
2437 const mcp = lastItem("mcp-call");
2438 const search = lastItem("native-search");
2439 assert.deepEqual(
2440 {
2441 mcp: mcp?.type === "dynamic_tool" ? mcp.toolName : mcp?.type,
2442 search: search?.type === "dynamic_tool" ? search.toolName : search?.type,
2443 },
2444 { mcp: "demo-library.search_books", search: "file_search" },
2445 );
2446 }).pipe(Effect.provide(layerTest)),
2447 );
2448
2449 it.effect.each([
2450 { kind: "approval", stopReason: "end_turn", status: "completed" },
2451 { kind: "question", stopReason: "error", status: "failed" },
2452 ] as const)("continues Claude's background $kind and preserves $status idle", (testCase) =>
2453 Effect.gen(function* () {
2454 const gate = makeProviderReplayGate(["wake", "stop-request", "refused-response"]);
2455 const method =
2456 testCase.kind === "approval" ? "session/request_permission" : "elicitation/create";
2457 const params =
2458 testCase.kind === "approval"
2459 ? {
2460 sessionId: "child-1",
2461 title: "Run tests?",
2462 subject: {
2463 type: "tool_call",
2464 toolCall: {
2465 toolCallId: "test-command",
2466 name: "Bash",
2467 title: "Run tests",
2468 kind: "execute",
2469 status: "pending",
2470 rawInput: { command: "vp test run" },
2471 },
2472 },
2473 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
2474 }
2475 : {
2476 sessionId: "child-1",
2477 mode: "form",
2478 message: "Which file?",
2479 requestedSchema: {
2480 type: "object",
2481 properties: { file: { type: "string", title: "File", enum: ["a.ts", "b.ts"] } },
2482 required: ["file"],
2483 },
2484 };
2485 const session = yield* openClaudeReplaySession(
2486 [
2487 ...claudeFrames.open,
2488 ...claudeFrames.prompt(1),
2489 ...claudeChild,
2490 claudeFrames.idle("end_turn"),
2491 {
2492 ...claudeFrames.update(CLAUDE_ROOT_SESSION, {
2493 sessionUpdate: "state_update",
2494 state: "running",
2495 }),
2496 label: "wake",
2497 },
2498 claudeFrames.update(CLAUDE_ROOT_SESSION, {
2499 sessionUpdate: "user_message",
2500 messageId: "wake-user",
2501 content: [{ type: "text", text: "Continue the review." }],
2502 }),
2503 claudeFrames.closeRequest,
2504 { type: "emit_inbound", frame: { kind: "request", method, params } },
2505 {
2506 type: "emit_inbound",
2507 label: "refused-response",
2508 frame: {
2509 kind: "response",
2510 method: "session/close",
2511 error: { code: -32603, message: "Close refused" },
2512 },
2513 },
2514 {
2515 type: "expect_outbound",
2516 frame: {
2517 kind: "response",
2518 method,
2519 result:
2520 testCase.kind === "approval"
2521 ? { outcome: { outcome: "selected", optionId: "allow" } }
2522 : { action: "accept", content: { file: "a.ts" } },
2523 },
2524 },
2525 claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
2526 ...claudeUnrelatedChildren,
2527 claudeFrames.update(CLAUDE_ROOT_SESSION, {
2528 sessionUpdate: "state_update",
2529 state: "idle",
2530 stopReason: testCase.stopReason,
2531 ...(testCase.status === "failed"
2532 ? { error: { code: -32603, message: "API Error: 529 overloaded" } }
2533 : {}),
2534 }),
2535 {
2536 type: "emit_inbound",
2537 label: "stop-request",
2538 frame: { kind: "request", method, params },
2539 },
2540 claudeFrames.closeRequest,
2541 claudeFrames.closed,
2542 {
2543 type: "expect_outbound",
2544 frame: {
2545 kind: "response",
2546 method,
2547 result:
2548 testCase.kind === "approval"
2549 ? { outcome: { outcome: "cancelled" } }
2550 : { action: "cancel" },
2551 },
2552 },
2553 claudeMarker("detached request cancelled"),
2554 ],
2555 gate,
2556 );
2557 yield* session.runtime.startTurn(session.turnInput(1));
2558 assert.equal((yield* session.terminal).status, "completed");
2559 assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
2560 gate.release("wake");
2561 yield* Queue.take(session.offered);
2562 const offer = session.offers[0]!;
2563 assert.isDefined(offer.dispatchIfCurrent);
2564 yield* offer.dispatchIfCurrent!(Effect.void);
2565 yield* session.runtime.startTurn(session.turnInput(2, { continuation: true }));
2566 const started = yield* session.until(
2567 (event) =>
2568 event.type === "provider_turn.updated" && event.providerTurn.status === "running",
2569 );
2570 const running = started.at(-1)!;
2571 if (running.type !== "provider_turn.updated") throw new Error("Missing active continuation");
2572 const closing = yield* session.runtime
2573 .interruptTurn({
2574 providerThread: session.providerThread,
2575 providerTurnId: running.providerTurn.id,
2576 requestRuntimeRestart: true,
2577 })
2578 .pipe(Effect.exit, Effect.forkScoped);
2579 yield* Effect.addFinalizer(() => Effect.sync(() => gate.releaseAll()));
2580 const seen = yield* session.until(
2581 (event) =>
2582 event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
2583 );
2584 assert.isFalse(
2585 seen.some(
2586 (event) => event.type === "turn_item.updated" && event.turnItem.type === "user_message",
2587 ),
2588 );
2589 const request = seen.at(-1)!;
2590 if (request.type !== "runtime_request.updated") throw new Error("Missing request");
2591 assert.isTrue(
2592 seen.some(
2593 (event) =>
2594 event.type === "node.updated" &&
2595 event.node.id === request.runtimeRequest.nodeId &&
2596 event.node.runId === session.turnInput(2).runId,
2597 ),
2598 );
2599 yield* Effect.promise(() => gate.waitForReached("refused-response"));
2600 gate.release("refused-response");
2601 assert.isTrue(Exit.isFailure(yield* Fiber.join(closing)));
2602 assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
2603 yield* session.runtime.respondToRuntimeRequest({
2604 requestId: request.runtimeRequest.id,
2605 ...(testCase.kind === "approval"
2606 ? { decision: "accept" as const }
2607 : { answers: { file: "a.ts" } }),
2608 });
2609 const terminal = yield* session.terminal;
2610 assert.equal(terminal.status, testCase.status);
2611 if (terminal.status === "failed") {
2612 assert.include(terminal.failure?.message ?? "", "529 overloaded");
2613 assert.isUndefined(terminal.childTurnsContinue);
2614 assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
2615 }
2616 gate.release("stop-request");
2617 yield* Queue.take(session.offered);
2618 yield* session.runtime.interruptTurn({
2619 providerThread: session.providerThread,
2620 providerTurnId: terminal.providerTurnId,
2621 requestRuntimeRestart: true,
2622 });
2623 const cancelled = yield* session.throughMarker("detached request cancelled");
2624 assert.isFalse(
2625 cancelled.some(
2626 (event) =>
2627 event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
2628 ),
2629 "detached requests are cancelled before turn admission",
2630 );
2631 }).pipe(Effect.provide(layerTest)),
2632 );
2633
2634 it.effect("retains streamed child tool output through the generic Devin route", () =>
2635 Effect.gen(function* () {
2636 const { update } = claudeFrames;
2637 const session = yield* openClaudeReplaySession(
2638 [
2639 ...claudeFrames.open,
2640 ...claudeFrames.prompt(1),
2641 update("child-1", {
2642 sessionUpdate: "tool_call_update",
2643 toolCallId: "early-tool",
2644 status: "in_progress",
2645 rawInput: { command: "echo early" },
2646 }),
2647 update("child-1", {
2648 sessionUpdate: "tool_call_content_chunk",
2649 toolCallId: "early-tool",
2650 content: { type: "content", content: { type: "text", text: "early" } },
2651 }),
2652 update("child-1", {
2653 sessionUpdate: "tool_call_update",
2654 toolCallId: "early-tool",
2655 status: "completed",
2656 }),
2657 update(CLAUDE_ROOT_SESSION, {
2658 sessionUpdate: "tool_call_update",
2659 toolCallId: "spawn",
2660 status: "in_progress",
2661 _meta: { "cognition.ai/subagent_started": { agentId: "child-1", task: "Review" } },
2662 }),
2663 ...[CLAUDE_ROOT_SESSION, "child-1"].map((sessionId) =>
2664 update(sessionId, {
2665 sessionUpdate: "tool_call_update",
2666 toolCallId: "shared-tool",
2667 title: "Read package",
2668 kind: "execute",
2669 status: "in_progress",
2670 rawInput: { command: "cat package.json" },
2671 ...(sessionId === "child-1"
2672 ? { content: [{ type: "content", content: { type: "text", text: "one" } }] }
2673 : {}),
2674 }),
2675 ),
2676 update("child-1", {
2677 sessionUpdate: "tool_call_content_chunk",
2678 toolCallId: "shared-tool",
2679 content: { type: "content", content: { type: "text", text: "two" } },
2680 }),
2681 update("child-1", {
2682 sessionUpdate: "tool_call_update",
2683 toolCallId: "shared-tool",
2684 status: "completed",
2685 }),
2686 update("child-1", {
2687 sessionUpdate: "tool_call_update",
2688 toolCallId: "shared-tool",
2689 content: [{ type: "content", content: { type: "text", text: "replacement" } }],
2690 }),
2691 update("child-1", {
2692 sessionUpdate: "tool_call_update",
2693 toolCallId: "shared-tool",
2694 content: [],
2695 }),
2696 update("child-1", {
2697 sessionUpdate: "tool_call_update",
2698 toolCallId: "shared-tool",
2699 rawOutput: { stdout: "structured", stderr: "" },
2700 }),
2701 update("child-1", {
2702 sessionUpdate: "tool_call_update",
2703 toolCallId: "shared-tool",
2704 content: [{ type: "content", content: { type: "text", text: "display" } }],
2705 }),
2706 update("child-1", {
2707 sessionUpdate: "tool_call_update",
2708 toolCallId: "shared-tool",
2709 rawOutput: { type: "Text", text: "vendor" },
2710 }),
2711 update("child-1", {
2712 sessionUpdate: "tool_call_update",
2713 toolCallId: "shared-tool",
2714 content: [{ type: "content", content: { type: "text", text: "display" } }],
2715 }),
2716 claudeMarker("tools complete"),
2717 claudeFrames.idle("end_turn"),
2718 claudeFrames.closeRequest,
2719 claudeFrames.closed,
2720 ],
2721 undefined,
2722 false,
2723 "devin",
2724 );
2725 yield* session.runtime.startTurn(session.turnInput(1));
2726 const events = yield* session.throughMarker("tools complete");
2727 const child = events.find((event) => event.type === "subagent.updated");
2728 if (child?.type !== "subagent.updated") throw new Error("Missing child");
2729 const tools = events.flatMap((event) =>
2730 event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
2731 ? [event.turnItem]
2732 : [],
2733 );
2734 const childTools = tools.filter((item) => item.threadId === child.subagent.childThreadId);
2735 assert.deepEqual(
2736 childTools.map((item) => item.output),
2737 [
2738 [{ type: "content", content: { type: "text", text: "one" } }],
2739 [{ type: "content", content: { type: "text", text: "onetwo" } }],
2740 [{ type: "content", content: { type: "text", text: "onetwo" } }],
2741 [{ type: "content", content: { type: "text", text: "replacement" } }],
2742 [],
2743 { stdout: "structured", stderr: "" },
2744 { stdout: "structured", stderr: "" },
2745 { type: "Text", text: "vendor" },
2746 { type: "Text", text: "vendor" },
2747 ],
2748 );
2749 assert.equal(new Set(childTools.map((item) => item.id)).size, 1);
2750 assert.equal(childTools.at(-1)?.nativeItemRef?.nativeId, "child-1:tool:shared-tool");
2751 assert.equal(childTools.at(-1)?.status, "completed");
2752 assert.deepEqual(childTools.at(-1)?.input, { command: "cat package.json" });
2753 const parentTools = events.flatMap((event) =>
2754 event.type === "turn_item.updated" &&
2755 event.turnItem.type === "command_execution" &&
2756 event.turnItem.threadId === session.turnInput(1).threadId &&
2757 event.turnItem.nativeItemRef?.nativeId === "shared-tool"
2758 ? [event.turnItem]
2759 : [],
2760 );
2761 assert.lengthOf(parentTools, 1);
2762 assert.isUndefined(parentTools[0]?.output);
2763 assert.isFalse(
2764 events.some(
2765 (event) => event.type === "message.updated" && event.message.text.includes("onetwo"),
2766 ),
2767 );
2768 }).pipe(Effect.provide(layerTest)),
2769 );
2770
2771 it.effect("replaces streamed root tool output with a later content list", () =>
2772 Effect.gen(function* () {
2773 const { update } = claudeFrames;
2774 const text = (value: string) => [{ type: "content", content: { type: "text", text: value } }];
2775 const session = yield* openClaudeReplaySession([
2776 ...claudeFrames.open,
2777 ...claudeFrames.prompt(1),
2778 update(CLAUDE_ROOT_SESSION, {
2779 sessionUpdate: "tool_call_update",
2780 toolCallId: "root-tool",
2781 title: "Stream",
2782 status: "in_progress",
2783 content: text("one"),
2784 }),
2785 update(CLAUDE_ROOT_SESSION, {
2786 sessionUpdate: "tool_call_content_chunk",
2787 toolCallId: "root-tool",
2788 content: { type: "content", content: { type: "text", text: "two" } },
2789 }),
2790 update(CLAUDE_ROOT_SESSION, {
2791 sessionUpdate: "tool_call_update",
2792 toolCallId: "root-tool",
2793 status: "completed",
2794 content: text("replacement"),
2795 }),
2796 update(CLAUDE_ROOT_SESSION, {
2797 sessionUpdate: "tool_call_content_chunk",
2798 toolCallId: "root-tool",
2799 content: { type: "content", content: { type: "text", text: "-more" } },
2800 }),
2801 update(CLAUDE_ROOT_SESSION, {
2802 sessionUpdate: "tool_call_content_chunk",
2803 toolCallId: "root-tool",
2804 content: {
2805 type: "diff",
2806 changes: [{ operation: "add", path: "/a.txt" }],
2807 patch: { format: "git_patch", text: "PATCH" },
2808 },
2809 }),
2810 claudeMarker("tools complete"),
2811 claudeFrames.idle("end_turn"),
2812 claudeFrames.closeRequest,
2813 claudeFrames.closed,
2814 ]);
2815 yield* session.runtime.startTurn(session.turnInput(1));
2816 const events = yield* session.throughMarker("tools complete");
2817 const outputs = events.flatMap((event) =>
2818 event.type === "turn_item.updated" &&
2819 event.turnItem.nativeItemRef?.nativeId === "root-tool" &&
2820 "output" in event.turnItem
2821 ? [event.turnItem.output]
2822 : [],
2823 );
2824 assert.deepEqual(outputs, [
2825 text("one"),
2826 text("onetwo"),
2827 text("replacement"),
2828 text("replacement-more"),
2829 { type: "Text", text: "replacement-morePATCH" },
2830 ]);
2831 }).pipe(Effect.provide(layerTest)),
2832 );
2833
2834 it.effect("approves Devin's plan without choosing a bypass option it lists first", () =>
2835 Effect.gen(function* () {
2836 const session = yield* openClaudeReplaySession(
2837 [
2838 ...claudeFrames.open.map((entry) =>
2839 entry.frame.method === "initialize" && entry.type === "emit_inbound"
2840 ? {
2841 ...entry,
2842 frame: {
2843 ...entry.frame,
2844 result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] },
2845 },
2846 }
2847 : entry,
2848 ),
2849 {
2850 type: "expect_outbound",
2851 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2852 },
2853 claudeFrames.update(CLAUDE_ROOT_SESSION, {
2854 sessionUpdate: "tool_call",
2855 toolCallId: "exit-plan",
2856 title: "Exit plan mode",
2857 kind: "switch_mode",
2858 status: "pending",
2859 }),
2860 {
2861 type: "emit_inbound",
2862 frame: {
2863 kind: "request",
2864 method: "session/request_permission",
2865 params: {
2866 sessionId: CLAUDE_ROOT_SESSION,
2867 toolCall: { toolCallId: "exit-plan" },
2868 // Devin gives both plan approvals allow_once and does not promise their order.
2869 options: [
2870 {
2871 optionId: "plan_bypass",
2872 name: "Yes, implement plan and bypass permissions",
2873 kind: "allow_once",
2874 },
2875 {
2876 optionId: "plan_accept_edits",
2877 name: "Yes, implement plan and accept edits",
2878 kind: "allow_once",
2879 },
2880 { optionId: "reject_once", name: "No, plan needs changes", kind: "reject_once" },
2881 ],
2882 },
2883 },
2884 },
2885 {
2886 type: "expect_outbound",
2887 frame: {
2888 kind: "response",
2889 method: "session/request_permission",
2890 result: { outcome: { outcome: "selected", optionId: "<any>" } },
2891 },
2892 },
2893 {
2894 type: "emit_inbound",
2895 frame: {
2896 kind: "response",
2897 method: "session/prompt",
2898 result: { stopReason: "end_turn" },
2899 },
2900 },
2901 claudeFrames.closeRequest,
2902 claudeFrames.closed,
2903 ],
2904 undefined,
2905 false,
2906 "devin",
2907 );
2908 yield* session.runtime.startTurn(session.turnInput(1)).pipe(Effect.forkScoped);
2909 const seen = yield* session.until(
2910 (event) =>
2911 event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
2912 );
2913 const request = seen.at(-1)!;
2914 if (request.type !== "runtime_request.updated") throw new Error("Missing request");
2915 yield* session.runtime.respondToRuntimeRequest({
2916 requestId: request.runtimeRequest.id,
2917 decision: "accept",
2918 });
2919 let answer: unknown;
2920 while (answer === undefined) {
2921 const frame = (yield* Queue.take(session.outgoing)) as {
2922 readonly result?: { readonly outcome?: { readonly optionId?: string } };
2923 };
2924 answer = frame.result?.outcome;
2925 }
2926 assert.deepEqual(answer, { outcome: "selected", optionId: "plan_accept_edits" });
2927 assert.equal((yield* session.terminal).status, "completed");
2928 }).pipe(Effect.provide(layerTest), Effect.scoped),
2929 );
2930
2931 it.effect("counts per-turn usage for a local glm command", () =>
2932 Effect.gen(function* () {
2933 const session = yield* openClaudeReplaySession(
2934 [
2935 // GLM reports per-turn usage on the v1 prompt response.
2936 ...claudeFrames.open.map((entry) =>
2937 entry.frame.method === "initialize" && entry.type === "emit_inbound"
2938 ? {
2939 ...entry,
2940 frame: {
2941 ...entry.frame,
2942 result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] },
2943 },
2944 }
2945 : entry,
2946 ),
2947 {
2948 type: "expect_outbound",
2949 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2950 },
2951 {
2952 type: "emit_inbound",
2953 frame: {
2954 kind: "response",
2955 method: "session/prompt",
2956 result: {
2957 stopReason: "end_turn",
2958 usage: { totalTokens: 3_000, inputTokens: 2_500, outputTokens: 500 },
2959 },
2960 },
2961 },
2962 claudeFrames.closeRequest,
2963 claudeFrames.closed,
2964 ],
2965 undefined,
2966 false,
2967 { source: "local", commandPath: "/opt/glm/bin/glm" },
2968 );
2969 yield* session.runtime.startTurn(session.turnInput(1)).pipe(Effect.forkScoped);
2970 const events = yield* session.until((event) => event.type === "turn.terminal");
2971 const completed = events.findLast(
2972 (event) =>
2973 event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
2974 );
2975 assert.deepEqual(
2976 completed?.type === "provider_turn.updated" ? completed.providerTurn.turnTokenUsage : null,
2977 {
2978 usageScope: "main_agent",
2979 usageStatus: "complete",
2980 hasSubagents: false,
2981 inputTokens: 2_500,
2982 outputTokens: 500,
2983 },
2984 );
2985 const terminal = events.at(-1)!;
2986 if (terminal.type !== "turn.terminal") throw new Error("Missing terminal");
2987 assert.equal(terminal.status, "completed");
2988 }).pipe(Effect.provide(layerTest), Effect.scoped),
2989 );
2990
2991 it.effect("surfaces Mistral's retry notice for a local vibe command", () =>
2992 Effect.gen(function* () {
2993 const session = yield* openClaudeReplaySession(
2994 [
2995 ...claudeFrames.open,
2996 {
2997 type: "expect_outbound",
2998 frame: { kind: "request", method: "session/prompt", params: "<any>" },
2999 },
3000 claudeFrames.update(CLAUDE_ROOT_SESSION, {
3001 sessionUpdate: "user_message",
3002 messageId: "user-1",
3003 content: [{ type: "text", text: "test prompt" }],
3004 }),
3005 claudeFrames.update(CLAUDE_ROOT_SESSION, {
3006 sessionUpdate: "state_update",
3007 state: "running",
3008 }),
3009 {
3010 type: "emit_inbound",
3011 frame: {
3012 kind: "notification",
3013 method: "_session/retrying",
3014 params: {
3015 sessionId: CLAUDE_ROOT_SESSION,
3016 category: "rate_limited",
3017 detail: "Backing off for 30s",
3018 },
3019 },
3020 },
3021 claudeMarker("retry noticed"),
3022 {
3023 type: "emit_inbound",
3024 frame: {
3025 kind: "response",
3026 method: "session/prompt",
3027 result: { stopReason: "end_turn" },
3028 },
3029 },
3030 claudeFrames.idle("end_turn"),
3031 claudeFrames.closeRequest,
3032 claudeFrames.closed,
3033 ],
3034 undefined,
3035 false,
3036 { source: "local", commandPath: "/opt/vibe/bin/vibe-acp" },
3037 );
3038 yield* session.runtime.startTurn(session.turnInput(1));
3039 const events = yield* session.throughMarker("retry noticed");
3040 const retry = events.find(
3041 (event) => event.type === "turn_item.updated" && event.turnItem.type === "error",
3042 );
3043 if (retry?.type !== "turn_item.updated" || retry.turnItem.type !== "error")
3044 throw new Error("Missing provider retry item");
3045 assert.equal(retry.turnItem.title, "Provider retry");
3046 assert.equal(retry.turnItem.failure.class, "usage_limit");
3047 assert.equal(retry.turnItem.retry?.attempt, 1);
3048 const terminal = yield* session.terminal;
3049 assert.equal(terminal.status, "completed");
3050 }).pipe(Effect.provide(layerTest), Effect.scoped),
3051 );
3052
3053 it.effect("keeps stopped child tools interrupted when a late output chunk arrives", () =>
3054 Effect.gen(function* () {
3055 const { update } = claudeFrames;
3056 const session = yield* openClaudeReplaySession(
3057 [
3058 ...claudeFrames.open.map((entry) =>
3059 entry.frame.method === "initialize" && entry.type === "emit_inbound"
3060 ? {
3061 ...entry,
3062 frame: {
3063 ...entry.frame,
3064 result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] },
3065 },
3066 }
3067 : entry,
3068 ),
3069 {
3070 type: "expect_outbound",
3071 frame: { kind: "request", method: "session/prompt", params: "<any>" },
3072 },
3073 update(CLAUDE_ROOT_SESSION, {
3074 sessionUpdate: "tool_call_update",
3075 toolCallId: "spawn",
3076 status: "in_progress",
3077 _meta: { "cognition.ai/subagent_started": { agentId: "child-1", task: "Review" } },
3078 }),
3079 update("child-1", {
3080 sessionUpdate: "tool_call_update",
3081 toolCallId: "stopped-tool",
3082 status: "in_progress",
3083 }),
3084 claudeMarker("before cancel"),
3085 {
3086 type: "expect_outbound",
3087 frame: {
3088 kind: "notification",
3089 method: "session/cancel",
3090 params: { sessionId: CLAUDE_ROOT_SESSION },
3091 },
3092 },
3093 update("child-1", {
3094 sessionUpdate: "tool_call_update",
3095 toolCallId: "stopped-tool",
3096 status: "failed",
3097 }),
3098 update("child-1", {
3099 sessionUpdate: "tool_call_update",
3100 toolCallId: "stopped-tool",
3101 content: [{ type: "content", content: { type: "text", text: "stopping" } }],
3102 }),
3103 update("child-1", {
3104 sessionUpdate: "tool_call_content_chunk",
3105 toolCallId: "stopped-tool",
3106 content: { type: "content", content: { type: "text", text: "cancelled" } },
3107 }),
3108 claudeMarker("late output"),
3109 update(CLAUDE_ROOT_SESSION, {
3110 sessionUpdate: "tool_call_update",
3111 toolCallId: "spawn",
3112 status: "failed",
3113 _meta: { "cognition.ai/subagent_completed": { agentId: "child-1", success: false } },
3114 }),
3115 {
3116 type: "emit_inbound",
3117 frame: {
3118 kind: "response",
3119 method: "session/prompt",
3120 result: { stopReason: "cancelled" },
3121 },
3122 },
3123 claudeFrames.closeRequest,
3124 claudeFrames.closed,
3125 ],
3126 undefined,
3127 false,
3128 "devin",
3129 );
3130 const starting = yield* session.runtime
3131 .startTurn(session.turnInput(1))
3132 .pipe(Effect.forkScoped);
3133 const started = yield* session.throughMarker("before cancel");
3134 const running = started.findLast((event) => event.type === "provider_turn.updated");
3135 if (running?.type !== "provider_turn.updated") throw new Error("Missing active turn");
3136 const closing = yield* session.runtime
3137 .interruptTurn({
3138 providerThread: session.providerThread,
3139 providerTurnId: running.providerTurn.id,
3140 })
3141 .pipe(Effect.forkScoped);
3142 const events = yield* session.throughMarker("late output");
3143 yield* Fiber.join(closing);
3144 yield* Fiber.join(starting);
3145 const tools = events.flatMap((event) =>
3146 event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
3147 ? [event.turnItem]
3148 : [],
3149 );
3150 assert.deepEqual(
3151 tools.map((item) => item.status),
3152 ["interrupted", "interrupted", "interrupted"],
3153 );
3154 assert.deepEqual(tools.at(-1)?.output, [
3155 { type: "content", content: { type: "text", text: "stoppingcancelled" } },
3156 ]);
3157 }).pipe(Effect.provide(layerTest)),
3158 );
3159
3160 it.effect("keeps native child tools interrupted after idle and late output", () =>
3161 Effect.gen(function* () {
3162 const { update, childState } = claudeFrames;
3163 const session = yield* openClaudeReplaySession([
3164 ...claudeFrames.open,
3165 ...claudeFrames.prompt(1),
3166 ...claudeChild.slice(0, -1),
3167 update("child-1", {
3168 sessionUpdate: "tool_call_update",
3169 toolCallId: "unfinished",
3170 status: "in_progress",
3171 }),
3172 childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
3173 update("child-1", {
3174 sessionUpdate: "tool_call_content_chunk",
3175 toolCallId: "unfinished",
3176 content: { type: "content", content: { type: "text", text: "late" } },
3177 }),
3178 claudeMarker("late native output"),
3179 claudeFrames.idle("end_turn"),
3180 claudeFrames.closeRequest,
3181 claudeFrames.closed,
3182 ]);
3183 yield* session.runtime.startTurn(session.turnInput(1));
3184 const events = yield* session.throughMarker("late native output");
3185 const tools = events.flatMap((event) =>
3186 event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
3187 ? [event.turnItem]
3188 : [],
3189 );
3190 assert.deepEqual(
3191 tools.map((tool) => tool.status),
3192 ["running", "interrupted", "interrupted"],
3193 );
3194 assert.deepEqual(tools.at(-1)?.output, [
3195 { type: "content", content: { type: "text", text: "late" } },
3196 ]);
3197 }).pipe(Effect.provide(layerTest)),
3198 );
3199
3200 it.effect.each(["error", "end_turn"])(
3201 "hands live Claude child tools to the next run after %s and keeps nested output in the child",
3202 (stopReason) =>
3203 Effect.gen(function* () {
3204 const { update, childState, idle, prompt } = claudeFrames;
3205 const gate = makeProviderReplayGate(["nested-output", "nested-idle"]);
3206 const session = yield* openClaudeReplaySession(
3207 [
3208 ...claudeFrames.open,
3209 ...prompt(1),
3210 update(CLAUDE_ROOT_SESSION, {
3211 sessionUpdate: "tool_call_update",
3212 toolCallId: "agent-1",
3213 name: "Agent",
3214 title: "Review",
3215 kind: "think",
3216 status: "in_progress",
3217 rawInput: { prompt: "Review the code", description: "Review" },
3218 }),
3219 ...claudeChild.slice(1, -1),
3220 update("child-1", {
3221 sessionUpdate: "tool_call_update",
3222 toolCallId: "child-tool",
3223 name: "Bash",
3224 title: "Read package",
3225 kind: "execute",
3226 status: "in_progress",
3227 rawInput: { command: "cat package.json" },
3228 }),
3229 update("child-1", {
3230 sessionUpdate: "agent_message_chunk",
3231 messageId: "progress",
3232 content: { type: "text", text: "Review in progress." },
3233 }),
3234 idle(stopReason),
3235 ...prompt(2),
3236 childState(CLAUDE_ROOT_SESSION, "child-1", "running"),
3237 update("child-1", {
3238 sessionUpdate: "session_message",
3239 messageId: "resume-child",
3240 senderSessionId: CLAUDE_ROOT_SESSION,
3241 recipientSessionId: "child-1",
3242 content: [{ type: "text", text: "Continue the review." }],
3243 }),
3244 claudeMarker("resumed"),
3245 childState("child-1", "grandchild", "running"),
3246 childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
3247 update(CLAUDE_ROOT_SESSION, {
3248 sessionUpdate: "tool_call_update",
3249 toolCallId: "agent-1",
3250 name: "Agent",
3251 status: "completed",
3252 rawInput: { prompt: "Review the code", description: "Review" },
3253 }),
3254 idle("end_turn"),
3255 {
3256 ...update("grandchild", {
3257 sessionUpdate: "terminal_update",
3258 terminalId: "nested-terminal",
3259 command: "/usr/bin/node /srv/t3/bin.ts acp-mcp-call orchestrator_capabilities {}",
3260 }),
3261 label: "nested-output",
3262 },
3263 update("grandchild", {
3264 sessionUpdate: "terminal_output_chunk",
3265 terminalId: "nested-terminal",
3266 data: Buffer.from("{}\n").toString("base64"),
3267 }),
3268 update("grandchild", {
3269 sessionUpdate: "terminal_update",
3270 terminalId: "nested-terminal",
3271 exitStatus: { exitCode: 0 },
3272 }),
3273 update("grandchild", {
3274 sessionUpdate: "tool_call_update",
3275 toolCallId: "terminal-tool",
3276 name: "Bash",
3277 title: "Run nested command",
3278 kind: "execute",
3279 status: "in_progress",
3280 content: [{ type: "terminal", terminalId: "nested-terminal" }],
3281 }),
3282 update("grandchild", {
3283 sessionUpdate: "tool_call_update",
3284 toolCallId: "nested-tool",
3285 name: "Bash",
3286 title: "Read nested package",
3287 kind: "execute",
3288 status: "in_progress",
3289 rawInput: { command: "cat nested/package.json" },
3290 }),
3291 ...["one", "two"].map((text) =>
3292 update("grandchild", {
3293 sessionUpdate: "tool_call_content_chunk",
3294 toolCallId: "nested-tool",
3295 content: { type: "content", content: { type: "text", text } },
3296 }),
3297 ),
3298 update("grandchild", {
3299 sessionUpdate: "tool_call_update",
3300 toolCallId: "nested-tool",
3301 status: "completed",
3302 }),
3303 update("grandchild", {
3304 sessionUpdate: "agent_message_chunk",
3305 messageId: "nested-reply",
3306 content: { type: "text", text: "Nested output" },
3307 }),
3308 update(CLAUDE_ROOT_SESSION, {
3309 sessionUpdate: "user_message",
3310 messageId: "nested-wake",
3311 content: [{ type: "text", text: "Continue the review." }],
3312 }),
3313 idle("end_turn"),
3314 claudeMarker("nested"),
3315 {
3316 ...childState("child-1", "grandchild", "idle"),
3317 label: "nested-idle",
3318 },
3319 claudeMarker("nested idle"),
3320 ...prompt(4),
3321 update("child-1", {
3322 sessionUpdate: "session_message",
3323 messageId: "second-review",
3324 senderSessionId: CLAUDE_ROOT_SESSION,
3325 recipientSessionId: "child-1",
3326 content: [{ type: "text", text: "Review the fix." }],
3327 }),
3328 childState(CLAUDE_ROOT_SESSION, "child-1", "running"),
3329 update("child-1", {
3330 sessionUpdate: "agent_message_chunk",
3331 messageId: "nested-reply",
3332 content: { type: "text", text: "The fix is correct." },
3333 }),
3334 childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
3335 idle("end_turn"),
3336 claudeFrames.closeRequest,
3337 claudeFrames.closed,
3338 ],
3339 gate,
3340 );
3341 yield* session.runtime.startTurn(session.turnInput(1));
3342 const settled = yield* session.terminal;
3343 assert.equal(settled.status, stopReason === "error" ? "failed" : "completed");
3344 if (settled.status === "failed") assert.isTrue(settled.childTurnsContinue);
3345 yield* session.runtime.startTurn(session.turnInput(2));
3346 const resumed = yield* session.throughMarker("resumed");
3347 const row = resumed.find((event) => event.type === "subagent.updated");
3348 assert.isDefined(row);
3349 if (row?.type !== "subagent.updated") throw new Error("Missing resumed child");
3350 assert.equal(row.subagent.runId, session.turnInput(2).runId);
3351 assert.equal(
3352 row.subagent.result,
3353 "Review in progress.",
3354 "live handoff retains current execution progress",
3355 );
3356 assert.lengthOf(
3357 resumed.filter(
3358 (event) =>
3359 event.type === "message.updated" &&
3360 event.message.threadId === row.subagent.childThreadId &&
3361 event.message.role === "user" &&
3362 event.message.text === "Continue the review.",
3363 ),
3364 1,
3365 "child resume prompts remain visible once",
3366 );
3367 const openTools = resumed.filter(
3368 (event) =>
3369 event.type === "turn_item.updated" &&
3370 event.turnItem.type === "dynamic_tool" &&
3371 event.turnItem.status === "running",
3372 );
3373 assert.lengthOf(openTools, 1, "handoff announces each open child tool once");
3374 const foreground = yield* session.until((event) => event.type === "turn.terminal");
3375 assert.isTrue(
3376 foreground.some(
3377 (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
3378 ),
3379 "the foreground Agent tool terminalizes its visible owner",
3380 );
3381 assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
3382 gate.release("nested-output");
3383 const childOutput = yield* session.throughMarker("nested");
3384 yield* Queue.take(session.offered);
3385 assert.lengthOf(session.offers, 1);
3386 yield* session.offers[0]!.dispatchIfCurrent!(Effect.void);
3387 yield* session.runtime.startTurn(session.turnInput(3, { continuation: true }));
3388 const continued = yield* session.until((event) => event.type === "turn.terminal");
3389 const terminal = continued.at(-1)!;
3390 if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal");
3391 assert.equal(terminal.status, "completed");
3392 const nested = [...childOutput, ...continued];
3393 const messages = nested.filter(
3394 (event) => event.type === "message.updated" && event.message.text === "Nested output",
3395 );
3396 assert.lengthOf(messages, 1);
3397 if (messages[0]?.type === "message.updated") {
3398 assert.equal(messages[0].message.threadId, row.subagent.childThreadId);
3399 }
3400 const nestedTool = nested.findLast(
3401 (event) =>
3402 event.type === "turn_item.updated" &&
3403 event.turnItem.type === "dynamic_tool" &&
3404 event.turnItem.nativeItemRef?.nativeId ===
3405 "agent-1:session:grandchild:tool:nested-tool",
3406 );
3407 assert.isDefined(nestedTool);
3408 if (nestedTool?.type === "turn_item.updated") {
3409 assert.equal(nestedTool.turnItem.threadId, row.subagent.childThreadId);
3410 if (nestedTool.turnItem.type === "dynamic_tool") {
3411 assert.deepEqual(nestedTool.turnItem.input, { command: "cat nested/package.json" });
3412 assert.equal(nestedTool.turnItem.status, "completed");
3413 }
3414 const toolUpdates = nested.flatMap((event) =>
3415 event.type === "turn_item.updated" &&
3416 event.turnItem.type === "dynamic_tool" &&
3417 event.turnItem.id === nestedTool.turnItem.id
3418 ? [event.turnItem]
3419 : [],
3420 );
3421 assert.deepEqual(
3422 toolUpdates.map((item) => item.output),
3423 [
3424 null,
3425 [{ type: "content", content: { type: "text", text: "one" } }],
3426 [{ type: "content", content: { type: "text", text: "onetwo" } }],
3427 [{ type: "content", content: { type: "text", text: "onetwo" } }],
3428 ],
3429 );
3430 }
3431 assert.isFalse(
3432 nested.some(
3433 (event) =>
3434 event.type === "turn_item.updated" &&
3435 event.turnItem.threadId === session.turnInput(1).threadId &&
3436 event.turnItem.type === "dynamic_tool" &&
3437 JSON.stringify(event.turnItem.output).includes("onetwo"),
3438 ),
3439 );
3440 assert.isTrue(
3441 nested.some(
3442 (event) =>
3443 event.type === "turn_item.updated" &&
3444 event.turnItem.type === "dynamic_tool" &&
3445 event.turnItem.nativeItemRef?.nativeId ===
3446 "agent-1:session:grandchild:tool:terminal-tool" &&
3447 event.turnItem.threadId === row.subagent.childThreadId &&
3448 event.turnItem.toolName === "t3-code.orchestrator_capabilities",
3449 ),
3450 "embedded agent-terminal commands preserve nested MCP identity",
3451 );
3452 assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!);
3453 gate.release("nested-idle");
3454 const finished = yield* session.throughMarker("nested idle");
3455 assert.isTrue(
3456 finished.some(
3457 (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
3458 ),
3459 );
3460 assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
3461 assert.lengthOf(session.offers, 1, "nested frames make progress in one continuation");
3462 const firstResult = finished.findLast((event) => event.type === "subagent.updated");
3463 if (firstResult?.type !== "subagent.updated")
3464 throw new Error("Missing first review result");
3465 assert.equal(
3466 firstResult.subagent.result,
3467 "Review in progress.",
3468 "reopening the visible owner for a running descendant keeps its execution result",
3469 );
3470 yield* session.runtime.startTurn(session.turnInput(4));
3471 const reviewed = yield* session.until((event) => event.type === "turn.terminal");
3472 const currentResult = reviewed.findLast((event) => event.type === "subagent.updated");
3473 if (currentResult?.type !== "subagent.updated")
3474 throw new Error("Missing second review result");
3475 assert.equal(currentResult.subagent.id, row.subagent.id);
3476 assert.equal(currentResult.subagent.childThreadId, row.subagent.childThreadId);
3477 assert.equal(currentResult.subagent.result, "The fix is correct.");
3478 const currentItem = reviewed.findLast(
3479 (event) => event.type === "turn_item.updated" && event.turnItem.type === "subagent",
3480 );
3481 if (currentItem?.type !== "turn_item.updated" || currentItem.turnItem.type !== "subagent")
3482 throw new Error("Missing current parent item");
3483 assert.equal(currentItem.turnItem.result, "The fix is correct.");
3484 assert.lengthOf(
3485 reviewed.filter(
3486 (event) =>
3487 event.type === "message.updated" && event.message.text === "The fix is correct.",
3488 ),
3489 1,
3490 "a new execution does not append the previous execution's text",
3491 );
3492 assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
3493 }).pipe(Effect.provide(layerTest)),
3494 );
3495
3496 it.effect("writes a child's coalesced text before a restart resets it", () =>
3497 Effect.gen(function* () {
3498 const { update, childState, idle, prompt } = claudeFrames;
3499 const reply = (text: string) =>
3500 update("child-1", {
3501 sessionUpdate: "agent_message_chunk",
3502 messageId: "reply",
3503 content: { type: "text", text },
3504 });
3505 const session = yield* openClaudeReplaySession([
3506 ...claudeFrames.open,
3507 ...prompt(1),
3508 ...claudeChild.slice(0, -1),
3509 reply("Review "),
3510 reply("done."),
3511 // A working grandchild keeps the idle child from publishing (and flushing) its status.
3512 childState("child-1", "grandchild", "running"),
3513 childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
3514 childState(CLAUDE_ROOT_SESSION, "child-1", "running"),
3515 idle("end_turn"),
3516 claudeFrames.closeRequest,
3517 claudeFrames.closed,
3518 ]);
3519 yield* session.runtime.startTurn(session.turnInput(1));
3520 const events = yield* session.until((event) => event.type === "turn.terminal");
3521 assert.isTrue(
3522 events.some(
3523 (event) =>
3524 event.type === "message.updated" &&
3525 event.message.role === "assistant" &&
3526 event.message.text === "Review done.",
3527 ),
3528 );
3529 }).pipe(Effect.provide(layerTest), Effect.scoped),
3530 );
3531
3532 it.effect("fails active Claude work and releases its children when the process exits", () =>
3533 Effect.gen(function* () {
3534 const session = yield* openClaudeReplaySession([
3535 ...claudeFrames.open,
3536 ...claudeFrames.prompt(1),
3537 ...claudeChild,
3538 claudeMarker("child ready"),
3539 ]);
3540 yield* session.runtime.startTurn(session.turnInput(1));
3541 yield* session.throughMarker("child ready");
3542 yield* session.terminate();
3543 const terminal = yield* session.terminal;
3544 assert.equal(terminal.status, "failed");
3545 assert.equal(terminal.failure?.class, "transport_error");
3546 assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
3547 const settled = yield* openClaudeReplaySession([
3548 ...claudeFrames.open,
3549 ...claudeFrames.prompt(1),
3550 ...claudeChild,
3551 claudeFrames.childState("child-1", "grandchild", "running"),
3552 claudeFrames.update("grandchild", {
3553 sessionUpdate: "tool_call_update",
3554 toolCallId: "nested-tool",
3555 name: "Bash",
3556 kind: "execute",
3557 status: "in_progress",
3558 rawInput: { command: "cat package.json" },
3559 }),
3560 claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
3561 claudeFrames.idle("end_turn"),
3562 ]);
3563 yield* settled.runtime.startTurn(settled.turnInput(1));
3564 const foreground = yield* settled.until((event) => event.type === "turn.terminal");
3565 const completed = foreground.at(-1)!;
3566 if (completed.type !== "turn.terminal") throw new Error("Missing settled root terminal");
3567 assert.equal(completed.status, "completed");
3568 assert.isTrue(yield* settled.runtime.hasPendingBackgroundWork!);
3569 yield* settled.terminate();
3570 assert.isFalse(
3571 yield* settled.runtime.hasPendingBackgroundWork!,
3572 "exit releases visible owners held open by nested work",
3573 );
3574 const exited = yield* settled.until(
3575 (event) =>
3576 event.type === "turn_item.updated" &&
3577 event.turnItem.type === "subagent" &&
3578 event.turnItem.status === "failed",
3579 );
3580 assert.isTrue(
3581 exited.some(
3582 (event) => event.type === "subagent.updated" && event.subagent.status === "failed",
3583 ),
3584 );
3585 const items = new Map(
3586 [...foreground, ...exited].flatMap((event) =>
3587 event.type === "turn_item.updated" ? [[event.turnItem.id, event.turnItem] as const] : [],
3588 ),
3589 );
3590 assert.deepEqual(pendingBackgroundTurnItems({ turnItems: [...items.values()] }), []);
3591 assert.isTrue(
3592 exited.some(
3593 (event) =>
3594 event.type === "turn_item.updated" &&
3595 event.turnItem.type === "dynamic_tool" &&
3596 event.turnItem.status === "interrupted",
3597 ),
3598 );
3599 }).pipe(Effect.provide(layerTest)),
3600 );
3601
3602 it.effect.each([
3603 { stopReason: "refusal", childUpdate: "state_update" },
3604 { stopReason: "max_tokens", childUpdate: "subagent_update" },
3605 ])(
3606 "fails Claude's turn and child and closes its running tool when they stop with $stopReason via $childUpdate",
3607 ({ stopReason, childUpdate }) =>
3608 Effect.gen(function* () {
3609 const { update, idle, prompt } = claudeFrames;
3610 const session = yield* openClaudeReplaySession([
3611 ...claudeFrames.open,
3612 ...prompt(1),
3613 ...claudeChild,
3614 update(CLAUDE_ROOT_SESSION, {
3615 sessionUpdate: "tool_call_update",
3616 toolCallId: "root-tool",
3617 name: "Bash",
3618 title: "Read package",
3619 kind: "execute",
3620 status: "in_progress",
3621 rawInput: { command: "cat package.json" },
3622 }),
3623 update("child-1", { sessionUpdate: "state_update", state: "running" }),
3624 childUpdate === "state_update"
3625 ? update("child-1", { sessionUpdate: "state_update", state: "idle", stopReason })
3626 : update(CLAUDE_ROOT_SESSION, {
3627 sessionUpdate: "subagent_update",
3628 sessionId: "child-1",
3629 state: { state: "idle", stopReason },
3630 }),
3631 idle(stopReason),
3632 ]);
3633 yield* session.runtime.startTurn(session.turnInput(1));
3634 const events = yield* session.until((event) => event.type === "turn.terminal");
3635 const terminal = events.at(-1)!;
3636 if (terminal.type !== "turn.terminal") throw new Error("Missing root terminal");
3637 assert.equal(terminal.status, "failed");
3638 assert.equal(terminal.failure?.code, stopReason);
3639 const child = events.findLast((event) => event.type === "subagent.updated");
3640 if (child?.type !== "subagent.updated") throw new Error("Missing child update");
3641 assert.equal(child.subagent.status, "failed");
3642 assert.isNotNull(child.subagent.result, "the child shows why it stopped");
3643 assert.isFalse(
3644 events.some(
3645 (event) =>
3646 event.type === "message.updated" &&
3647 event.message.threadId === child.subagent.childThreadId &&
3648 event.message.role === "assistant",
3649 ),
3650 "the child's conversation has no reply it didn't send",
3651 );
3652 const tool = events.findLast(
3653 (event) =>
3654 event.type === "turn_item.updated" && event.turnItem.type === "command_execution",
3655 );
3656 if (tool?.type !== "turn_item.updated") throw new Error("Missing tool update");
3657 assert.equal(tool.turnItem.status, "failed");
3658 }).pipe(Effect.provide(layerTest), Effect.scoped),
3659 );
3660
3661 it.effect("keeps Claude activity after a refused Stop and closes it on retry", () =>
3662 Effect.gen(function* () {
3663 const gate = makeProviderReplayGate(["close-response", "queued-close-response"]);
3664 const session = yield* openClaudeReplaySession(
3665 [
3666 ...claudeFrames.open,
3667 ...claudeFrames.prompt(1),
3668 ...claudeChild,
3669 claudeMarker("before Stop"),
3670 claudeFrames.closeRequest,
3671 claudeFrames.update("child-1", {
3672 sessionUpdate: "agent_message_chunk",
3673 messageId: "closing-reply",
3674 content: { type: "text", text: "Finished during close." },
3675 }),
3676 claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"),
3677 claudeFrames.idle("end_turn"),
3678 claudeMarker("idle during close"),
3679 {
3680 type: "emit_inbound",
3681 label: "close-response",
3682 frame: {
3683 kind: "response",
3684 method: "session/close",
3685 error: { code: -32603, message: "Close refused" },
3686 },
3687 },
3688 ...claudeFrames.prompt(2),
3689 claudeMarker("before retry"),
3690 claudeFrames.closeRequest,
3691 claudeFrames.idle("cancelled"),
3692 claudeFrames.closed,
3693 ],
3694 gate,
3695 );
3696 yield* session.runtime.startTurn(session.turnInput(1));
3697 const started = yield* session.throughMarker("before Stop");
3698 const running = started.findLast((event) => event.type === "provider_turn.updated");
3699 if (running?.type !== "provider_turn.updated") throw new Error("Missing active turn");
3700 const stop = {
3701 providerThread: session.providerThread,
3702 providerTurnId: running.providerTurn.id,
3703 requestRuntimeRestart: true,
3704 };
3705 const closing = yield* session.runtime
3706 .interruptTurn(stop)
3707 .pipe(Effect.exit, Effect.forkScoped);
3708 yield* Effect.addFinalizer(() => Effect.sync(() => gate.releaseAll()));
3709 const idle = yield* session.throughMarker("idle during close");
3710 gate.release("close-response");
3711 const refused = yield* Fiber.join(closing);
3712 assert.isTrue(Exit.isFailure(refused), "a refused close must not report a successful Stop");
3713 const terminal = idle.findLast((event) => event.type === "turn.terminal");
3714 assert.equal(
3715 terminal?.type === "turn.terminal" ? terminal.status : null,
3716 "completed",
3717 "idle during a refused close must settle the foreground turn",
3718 );
3719 const result = idle.findLast((event) => event.type === "subagent.updated");
3720 if (result?.type !== "subagent.updated") throw new Error("Missing child close-time result");
3721 assert.equal(result.subagent.status, "completed");
3722 assert.equal(result.subagent.result, "Finished during close.");
3723 assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
3724 yield* session.runtime.startTurn(session.turnInput(2));
3725 const retry = yield* session.throughMarker("before retry");
3726 const retryRunning = retry.findLast((event) => event.type === "provider_turn.updated");
3727 if (retryRunning?.type !== "provider_turn.updated")
3728 throw new Error("Missing active retry turn");
3729 yield* session.runtime.interruptTurn({
3730 ...stop,
3731 providerTurnId: retryRunning.providerTurn.id,
3732 });
3733 assert.equal((yield* session.terminal).status, "interrupted");
3734 assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
3735
3736 const queued = yield* openClaudeReplaySession(
3737 [
3738 ...claudeFrames.open,
3739 {
3740 type: "expect_outbound",
3741 frame: { kind: "request", method: "session/prompt", params: "<any>" },
3742 },
3743 claudeMarker("before queued Stop"),
3744 claudeFrames.closeRequest,
3745 {
3746 type: "emit_inbound",
3747 frame: {
3748 kind: "response",
3749 method: "session/prompt",
3750 error: { code: -32800, message: "Request cancelled" },
3751 },
3752 },
3753 { ...claudeFrames.closed, label: "queued-close-response" },
3754 ],
3755 gate,
3756 );
3757 yield* queued.runtime.startTurn(queued.turnInput(3));
3758 const pending = yield* queued.throughMarker("before queued Stop");
3759 const queuedRunning = pending.findLast((event) => event.type === "provider_turn.updated");
3760 if (queuedRunning?.type !== "provider_turn.updated")
3761 throw new Error("Missing queued provider turn");
3762 const queuedClosing = yield* queued.runtime
3763 .interruptTurn({
3764 providerThread: queued.providerThread,
3765 providerTurnId: queuedRunning.providerTurn.id,
3766 requestRuntimeRestart: true,
3767 })
3768 .pipe(Effect.forkScoped);
3769 const queuedTerminal = yield* queued.terminal;
3770 gate.release("queued-close-response");
3771 yield* Fiber.join(queuedClosing);
3772 assert.equal(queuedTerminal.providerTurnId, queuedRunning.providerTurn.id);
3773 assert.equal(queuedTerminal.status, "interrupted");
3774 assert.isNull(queuedTerminal.failure);
3775 assert.isFalse(yield* queued.runtime.hasPendingBackgroundWork!);
3776 }).pipe(Effect.provide(layerTest)),
3777 );
3778
3779 it.effect.each([
3780 {
3781 failure: "a lost session",
3782 error: {
3783 code: -32603,
3784 message: "Internal error",
3785 data: {
3786 details:
3787 "Request session.send failed with message: session event delivery failed: session not found: copilot-session",
3788 },
3789 },
3790 restarts: true,
3791 },
3792 {
3793 failure: "a lost session reported in the message",
3794 error: {
3795 code: -32603,
3796 message:
3797 "Request session.send failed with message: session event delivery failed: session not found: copilot-session",
3798 },
3799 restarts: true,
3800 },
3801 {
3802 failure: "a session-lock timeout",
3803 error: {
3804 code: -32603,
3805 message: "Internal error",
3806 data: {
3807 details:
3808 "session lock unavailable during is_session_generation_current: acquisition timed out",
3809 },
3810 },
3811 restarts: true,
3812 },
3813 {
3814 failure: "a session-lock timeout reported in the message",
3815 error: {
3816 code: -32603,
3817 message:
3818 "Request session.send failed with message: session lock unavailable during is_session_generation_current: acquisition timed out",
3819 },
3820 restarts: true,
3821 },
3822 {
3823 failure: "an unrelated internal error",
3824 error: {
3825 code: -32603,
3826 message: "Request session.send failed with message: Session directory no longer exists",
3827 },
3828 restarts: false,
3829 },
3830 ] as const)("runs Copilot's next message after $failure", ({ error, restarts }) =>
3831 Effect.gen(function* () {
3832 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
3833 const fileSystem = yield* FileSystem.FileSystem;
3834 const path = yield* Path.Path;
3835 const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-copilot-lost-" });
3836 const scriptPath = yield* path.fromFileUrl(
3837 new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
3838 );
3839 const request = (method: string, params: unknown = "<any>") => ({
3840 type: "expect_outbound",
3841 frame: { kind: "request", method, params },
3842 });
3843 const respond = (method: string, response: object) => ({
3844 type: "emit_inbound",
3845 frame: { kind: "response", method, ...response },
3846 });
3847 const start = (sessionId: string) => [
3848 request("initialize"),
3849 respond("initialize", {
3850 result: { protocolVersion: 1, agentCapabilities: { loadSession: true } },
3851 }),
3852 request("session/new"),
3853 respond("session/new", { result: { sessionId } }),
3854 ];
3855 const failedPrompt = [
3856 ...start("copilot-session"),
3857 request("session/prompt"),
3858 respond("session/prompt", { error }),
3859 ];
3860 const completedPrompt = [
3861 request("session/prompt"),
3862 respond("session/prompt", { result: { stopReason: "end_turn" } }),
3863 ];
3864 const processes = restarts
3865 ? [
3866 failedPrompt,
3867 [
3868 ...start("replacement-session"),
3869 request("session/load", {
3870 sessionId: "copilot-session",
3871 cwd: "<workspace>",
3872 mcpServers: "<any>",
3873 }),
3874 respond("session/load", { result: {} }),
3875 ...completedPrompt,
3876 ],
3877 ]
3878 : [[...failedPrompt, ...completedPrompt]];
3879 let spawned = 0;
3880 const instanceId = ProviderInstanceId.make("copilot-lost-session");
3881 const adapter = yield* makeAcpRegistryAdapterV2({
3882 selfInvocation: yield* resolveSelfInvocation(),
3883 instanceId,
3884 settings: yield* decodeAcpRegistryAdapterSettings({ agentId: "github-copilot-cli" }),
3885 environment: {},
3886 makeRuntime: (runtimeInput) =>
3887 Effect.gen(function* () {
3888 const index = spawned++;
3889 const transcript = yield* decodeAcpReplayTranscript(
3890 {
3891 provider: ACP_REGISTRY_PROVIDER,
3892 protocol: "acp.ndjson-jsonrpc",
3893 version: "1",
3894 scenario: `copilot-lost-session-${index}`,
3895 entries: processes[index] as never,
3896 },
3897 ACP_REGISTRY_PROVIDER,
3898 ).pipe(Effect.orDie);
3899 return yield* makeAcpReplayRuntime({
3900 transcript,
3901 statusPath: path.join(replayDir, `status-${index}.json`),
3902 scriptPath,
3903 childProcessSpawner,
3904 fileSystem,
3905 })(runtimeInput);
3906 }),
3907 }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
3908 const threadId = ThreadId.make("thread-copilot-lost-session");
3909 const modelSelection = { instanceId, model: "default" } as const;
3910 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
3911 runtimeMode: "approval-required",
3912 interactionMode: "default",
3913 cwd: replayDir,
3914 });
3915 const runtime = yield* adapter.openSession({
3916 threadId,
3917 providerSessionId: ProviderSessionId.make("session-copilot-lost-session"),
3918 modelSelection,
3919 runtimePolicy,
3920 });
3921 const providerThread = yield* runtime.ensureThread({
3922 threadId,
3923 modelSelection,
3924 runtimePolicy,
3925 });
3926 const now = yield* DateTime.now;
3927 const runTurn = (ordinal: number) =>
3928 runtime
3929 .startTurn(
3930 makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }),
3931 )
3932 .pipe(
3933 Effect.andThen(
3934 runtime.events.pipe(
3935 Stream.filter((event) => event.type === "turn.terminal"),
3936 Stream.take(1),
3937 Stream.runCollect,
3938 ),
3939 ),
3940 Effect.map(([terminal]) => terminal?.status),
3941 );
3942 assert.equal(yield* runTurn(1), "failed");
3943 assert.equal(yield* runTurn(2), "completed");
3944 assert.equal(spawned, restarts ? 2 : 1);
3945 }).pipe(Effect.provide(layerTest)),
3946 );
3947 });