The best way to control Claude Code, Codex and more from any computer or phone

main
ts 25,309 lines 929 KB
Raw
Large file — syntax highlighting disabled.
1 // @effect-diagnostics nodeBuiltinImport:off -- workflow fixtures use files and the fake Claude CLI uses Node streams
2 import * as NodeEvents from "node:events";
3 import * as NodeFS from "node:fs";
4 import * as NodePath from "node:path";
5 import * as NodeStream from "node:stream";
6
7 import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
8 import { beforeEach, vi } from "vite-plus/test";
9
10 import type {
11 ElicitationRequest,
12 ElicitationResult,
13 Query as ClaudeQuery,
14 SDKMessage,
15 SDKResultMessage,
16 SDKUserMessage,
17 SpawnedProcess,
18 SpawnOptions,
19 } from "@anthropic-ai/claude-agent-sdk";
20 import type {
21 AskUserQuestionInput,
22 TaskCreateInput,
23 TaskCreateOutput,
24 TaskListOutput,
25 TaskUpdateInput,
26 TaskUpdateOutput,
27 } from "@anthropic-ai/claude-agent-sdk/sdk-tools";
28 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
29 import * as NodeServices from "@effect/platform-node/NodeServices";
30 import { toolOutputImages } from "@t3tools/shared/toolOutput";
31 import {
32 ChatAttachmentId,
33 type ChatAttachment,
34 ChatFileAttachment,
35 ChatImageAttachment,
36 CheckpointId,
37 ClaudeSettings,
38 EnvironmentId,
39 MessageId,
40 type ModelSelection,
41 NodeId,
42 type OrchestrationV2AppThread,
43 type OrchestrationV2PendingBackgroundTask,
44 OrchestrationV2ProviderThread,
45 ProjectId,
46 ProviderInstanceId,
47 type ResolvedProviderInstanceEnvironment,
48 ProviderDriverKind,
49 type ProviderReplayTranscript,
50 type ProviderApprovalDecision,
51 ProviderSessionId,
52 ProviderTurnId,
53 RunAttemptId,
54 RunId,
55 ThreadId,
56 } from "@t3tools/contracts";
57 import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
58 import { assert, describe, it } from "@effect/vitest";
59 import * as Cause from "effect/Cause";
60 import * as Context from "effect/Context";
61 import * as DateTime from "effect/DateTime";
62 import * as Deferred from "effect/Deferred";
63 import * as SecureRandom from "effect/crypto/SecureRandom";
64 import * as Effect from "effect/Effect";
65 import * as Exit from "effect/Exit";
66 import * as FileSystem from "effect/FileSystem";
67 import * as Fiber from "effect/Fiber";
68 import * as Layer from "effect/Layer";
69 import * as Option from "effect/Option";
70 import * as Path from "effect/Path";
71 import * as PubSub from "effect/PubSub";
72 import * as Queue from "effect/Queue";
73 import * as Ref from "effect/Ref";
74 import * as Schema from "effect/Schema";
75 import * as Scope from "effect/Scope";
76 import * as Stream from "effect/Stream";
77 import * as TestClock from "effect/testing/TestClock";
78 import { Tool } from "effect/ai";
79 import { formatClaudeResumeCompactionQuestion } from "@t3tools/shared/claudeCompaction";
80 import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
81 import * as HostProcess from "@t3tools/shared/HostProcess";
82 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
83 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
84
85 import * as PortScanner from "../../preview/PortScanner.ts";
86 import { attachmentRelativePath } from "../../attachmentStore.ts";
87 import { WorkflowAgentTranscriptReadObserver } from "../workflowAgentTranscript.ts";
88 import * as ServerConfig from "../../config.ts";
89 import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
90 import { T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH } from "@t3tools/provider-core/server/orchestrationInstructions";
91 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
92 import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools.ts";
93 import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts";
94 import { MessageToolkit } from "../../mcp/toolkits/message/tools.ts";
95 import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts";
96 import { ThemeToolkit } from "../../mcp/toolkits/theme/tools.ts";
97 import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts";
98 import { WorktreeToolkit } from "../../mcp/toolkits/worktree/tools.ts";
99 import { ThreadToolkit } from "../../mcp/toolkits/thread/tools.ts";
100 import { OrchestratorToolkit } from "../../mcp/toolkits/orchestrator/tools.ts";
101 import { ClaudeExecutableFileCheck } from "../../provider/Drivers/ClaudeExecutable.ts";
102 import {
103 BUNDLED_CLAUDE_MODEL_CATALOG,
104 type ClaudeModelCatalog,
105 resolveClaudeModelCatalog,
106 scopeClaudeModelCatalog,
107 withClaudeCodeModelRoutes,
108 } from "../../provider/ClaudeModelCatalog.ts";
109 import {
110 makeClaudeCodeModelRoutes,
111 resolveClaudeModelSettingsKey,
112 } from "../../provider/ClaudeCodeModelRoutes.ts";
113 import { resolveProviderCatalog } from "../../provider/ModelManifest.ts";
114 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
115 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
116 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
117 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
118 import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts";
119 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
120 import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts";
121 import { ClaudeOrchestratorReplayHarness } from "./ClaudeAdapterV2.testkit.ts";
122 import { withInlineContext } from "../ContextHandoffDelivery.ts";
123 import { provideDeterministicTestRuntime } from "../testkit/DeterministicRuntime.ts";
124 import { runOrchestratorV2Scenario } from "../testkit/OrchestratorScenario.ts";
125 import { layerProviderReplay } from "../testkit/ProviderReplayHarness.ts";
126 import {
127 assertBaseProjection,
128 assertSemanticProjectionIntegrity,
129 CLAUDE_MODEL_SELECTION,
130 materializeFixtureInput,
131 projectionFor,
132 } from "../testkit/fixtures/shared.ts";
133
134 vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => ({
135 ...(await importOriginal<typeof ClaudeSdk>()),
136 resolveSettings: vi.fn(),
137 }));
138
139 beforeEach(() => {
140 vi.mocked(ClaudeSdk.resolveSettings).mockReset().mockResolvedValue({
141 effective: {},
142 provenance: {},
143 sources: [],
144 });
145 });
146
147 const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({});
148 const AUTO_COMPACT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
149 autoCompactWindow: "300000",
150 });
151 const CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
152 customModels: [
153 "opus",
154 {
155 slug: "claude-custom-tuned",
156 name: "Tuned",
157 capabilities: {
158 optionDescriptors: [
159 {
160 id: "effort",
161 label: "Reasoning",
162 type: "select",
163 options: [
164 { id: "gentle", label: "Gentle", isDefault: true },
165 { id: "brutal", label: "Brutal" },
166 ],
167 },
168 ],
169 },
170 },
171 ],
172 });
173 const ALIAS_CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
174 customModels: ["haiku", "sonnet"],
175 });
176 const ULTRACODE_CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
177 customModels: [
178 {
179 slug: "claude-custom-tuned",
180 capabilities: {
181 optionDescriptors: [
182 {
183 id: "effort",
184 label: "Reasoning",
185 type: "select",
186 options: [
187 { id: "high", label: "High", isDefault: true },
188 { id: "ultracode", label: "Ultracode" },
189 ],
190 },
191 ],
192 },
193 },
194 ],
195 });
196 const CLAUDE_TEST_MODEL_SELECTION = {
197 instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
198 model: "claude-sonnet-4-6",
199 options: [{ id: "effort", value: "ultrathink" }],
200 } satisfies ModelSelection;
201 const CLAUDE_TEST_RESTART_MODEL_SELECTION = {
202 ...CLAUDE_TEST_MODEL_SELECTION,
203 model: "claude-haiku-4-5-20251001",
204 options: [{ id: "thinking", value: false }],
205 } satisfies ModelSelection;
206 const CLAUDE_TEST_RUNTIME_POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
207 runtimeMode: "full-access",
208 interactionMode: "default",
209 cwd: "/workspace",
210 });
211
212 function makeClaudeTestAppThread(input: {
213 readonly threadId: ThreadId;
214 readonly providerThread: OrchestrationV2ProviderThread;
215 readonly now: DateTime.Utc;
216 readonly title?: string;
217 }): OrchestrationV2AppThread {
218 return {
219 createdBy: "user",
220 creationSource: "web",
221 id: input.threadId,
222 projectId: ProjectId.make(`project-${input.threadId}`),
223 title: input.title ?? "Claude attachment test",
224 providerInstanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
225 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
226 runtimeMode: "full-access",
227 interactionMode: "default",
228 branch: null,
229 worktreePath: null,
230 activeProviderThreadId: input.providerThread.id,
231 lineage: {
232 parentThreadId: null,
233 relationshipToParent: null,
234 rootThreadId: input.threadId,
235 },
236 forkedFrom: null,
237 createdAt: input.now,
238 updatedAt: input.now,
239 archivedAt: null,
240 settledOverride: null,
241 settledAt: null,
242 lastVisitedAt: null,
243 deletedAt: null,
244 };
245 }
246
247 function makeClaudeTestTurnInput(input: {
248 readonly threadId: ThreadId;
249 readonly providerThread: OrchestrationV2ProviderThread;
250 readonly now: DateTime.Utc;
251 readonly attemptId: RunAttemptId;
252 readonly text: string;
253 readonly attachments: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["attachments"];
254 readonly providerTurnOrdinal?: number;
255 readonly nativeThreadHasTurns?: boolean;
256 readonly title?: string;
257 readonly messageCreatedBy?: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["createdBy"];
258 readonly messageCreationSource?: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["creationSource"];
259 readonly modelSelection?: ModelSelection;
260 readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
261 }): ProviderAdapter.ProviderAdapterV2TurnInput {
262 return {
263 appThread: makeClaudeTestAppThread(input),
264 threadId: input.threadId,
265 runId: RunId.make(`run-${input.attemptId}`),
266 runOrdinal: 1,
267 providerTurnOrdinal: input.providerTurnOrdinal ?? 1,
268 ...(input.nativeThreadHasTurns === undefined
269 ? {}
270 : { nativeThreadHasTurns: input.nativeThreadHasTurns }),
271 attemptId: input.attemptId,
272 rootNodeId: NodeId.make(`node-${input.attemptId}`),
273 providerThread: input.providerThread,
274 message: {
275 createdBy: input.messageCreatedBy ?? "user",
276 creationSource: input.messageCreationSource ?? "web",
277 messageId: MessageId.make(`message-${input.attemptId}`),
278 text: input.text,
279 attachments: input.attachments,
280 },
281 modelSelection: input.modelSelection ?? CLAUDE_TEST_MODEL_SELECTION,
282 runtimePolicy: input.runtimePolicy ?? CLAUDE_TEST_RUNTIME_POLICY,
283 };
284 }
285
286 describe("ClaudeAdapterV2 native resume history", () => {
287 const entry = (uuid: string, type: string, content: unknown) => ({
288 uuid,
289 type,
290 message: { content },
291 });
292 const prompt = entry("prompt", "user", "Run the task");
293 const completed = entry("completed-tool", "user", [
294 { type: "tool_result", tool_use_id: "done", content: "Saved", is_error: false },
295 ]);
296 const call = entry("call", "assistant", [
297 { type: "tool_use", id: "pending", name: "Bash", input: {} },
298 ]);
299 const interrupted = entry("stopped-tool", "user", [
300 {
301 type: "tool_result",
302 tool_use_id: "pending",
303 content: "The user doesn't want to proceed with this tool use. STOP",
304 is_error: true,
305 },
306 ]);
307 it.each([
308 {
309 name: "an interrupted reply",
310 messages: [
311 prompt,
312 entry("reply", "assistant", "Partial response"),
313 entry("stop", "user", [{ type: "text", text: "[Request interrupted by user]" }]),
314 ],
315 head: "reply",
316 },
317 {
318 name: "an interrupted tool after completed work",
319 messages: [
320 prompt,
321 completed,
322 call,
323 interrupted,
324 entry("stop", "user", "[Request interrupted by user for tool use]"),
325 ],
326 head: "call",
327 },
328 {
329 name: "an interrupted request before any reply",
330 messages: [prompt, entry("stop", "user", "[Request interrupted by user]")],
331 head: "prompt",
332 },
333 {
334 name: "completed tool results",
335 messages: [prompt, completed, entry("stop", "user", "[Request interrupted by user]")],
336 head: "completed-tool",
337 },
338 { name: "an explicit refusal", messages: [prompt, call, interrupted], head: undefined },
339 {
340 name: "ordinary conversation text",
341 messages: [prompt, entry("reply", "assistant", "Continue where you left off.")],
342 head: undefined,
343 },
344 ])("selects the native history head for $name", ({ messages, head }) => {
345 assert.equal(ClaudeAdapterV2.claudeResumeSessionAt(messages), head);
346 });
347 });
348
349 describe("ClaudeAdapterV2 runtime query policy", () => {
350 it.each([
351 "-- --thinking-display omitted",
352 "--thinking-display summarized -- --thinking-display omitted",
353 ])("does not treat operands after -- as SDK flags: %s", (launchArgs) => {
354 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
355 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
356 nativeThreadId: "thinking-thread",
357 resume: false,
358 cwd: "/workspace",
359 settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs },
360 });
361 assert.deepEqual(options.thinking, { type: "adaptive", display: "summarized" });
362 assert.equal(options.extraArgs?.["thinking-display"], "summarized");
363 });
364
365 it.each([
366 ["--permission-mode acceptEdits", "acceptEdits"],
367 ["--dangerously-skip-permissions", "bypassPermissions"],
368 ["--dangerously-skip-permissions --permission-mode plan", "plan"],
369 ])("folds %s into the SDK permission mode", (launchArgs, expected) => {
370 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
371 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
372 nativeThreadId: "native-permission-override",
373 resume: false,
374 cwd: "/workspace",
375 permissionMode: "default",
376 settings: { ...AUTO_COMPACT_CLAUDE_SETTINGS, launchArgs },
377 });
378 assert.equal(options.permissionMode, expected);
379 assert.isUndefined(options.extraArgs?.["permission-mode"]);
380 assert.isUndefined(options.extraArgs?.["dangerously-skip-permissions"]);
381 });
382
383 it("passes every --add-dir and --plugin-dir launch directory to Claude", () => {
384 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
385 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
386 nativeThreadId: "native-add-dir",
387 resume: false,
388 cwd: "/workspace",
389 attachmentsDir: "/attachments",
390 settings: {
391 ...AUTO_COMPACT_CLAUDE_SETTINGS,
392 launchArgs:
393 '--add-dir ../apps ../lib --verbose --add-dir=/shared --plugin-dir ./a --plugin-dir=./b.zip --append-system-prompt "--plugin-dir=./prompt"',
394 },
395 });
396 assert.deepEqual(options.additionalDirectories, [
397 "/workspace",
398 "/attachments",
399 "../apps",
400 "../lib",
401 "/shared",
402 ]);
403 assert.isUndefined(options.extraArgs?.["add-dir"]);
404 assert.deepEqual(options.plugins, [
405 { type: "local", path: "./a" },
406 { type: "local", path: "./b.zip" },
407 ]);
408 assert.isUndefined(options.extraArgs?.["plugin-dir"]);
409 const bare = ClaudeAdapterV2.makeClaudeQueryOptions({
410 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
411 nativeThreadId: "native-bare-plugin-dir",
412 resume: false,
413 cwd: "/workspace",
414 settings: { ...AUTO_COMPACT_CLAUDE_SETTINGS, launchArgs: "--plugin-dir --verbose" },
415 });
416 assert.isUndefined(bare.plugins);
417 assert.isNull(bare.extraArgs?.["plugin-dir"]);
418 });
419
420 it("gives delegated children Claude's subagent prompt cache TTL", () => {
421 const lineage = (relationshipToParent: "fork" | "subagent" | null) => ({
422 lineage: {
423 parentThreadId: null,
424 relationshipToParent,
425 rootThreadId: ThreadId.make("thread-root"),
426 },
427 });
428 const env = { PATH: "/bin" };
429 const ttl = (environment: NodeJS.ProcessEnv, ...args: Parameters<typeof lineage>) =>
430 ClaudeAdapterV2.claudeQueryEnvironment(environment, lineage(...args), "5m")
431 .CLAUDE_CODE_PROMPT_CACHE_TTL;
432 assert.equal(ttl(env, "subagent"), "5m");
433 assert.isUndefined(ttl(env, null));
434 assert.isUndefined(ttl(env, "fork"));
435 assert.equal(ttl({ ...env, CLAUDE_CODE_PROMPT_CACHE_TTL: "1h" }, "subagent"), "1h");
436 assert.strictEqual(
437 ClaudeAdapterV2.claudeQueryEnvironment(env, lineage("subagent"), undefined),
438 env,
439 );
440 });
441
442 it("makes a resumed Claude session wait for its MCP servers before the first request", () => {
443 const appThread = {
444 lineage: {
445 parentThreadId: null,
446 relationshipToParent: null,
447 rootThreadId: ThreadId.make("t"),
448 },
449 };
450 const nonblocking = (environment: NodeJS.ProcessEnv, resume: boolean) =>
451 ClaudeAdapterV2.claudeQueryEnvironment(environment, appThread, undefined, resume)
452 .MCP_CONNECTION_NONBLOCKING;
453 assert.equal(nonblocking({}, true), "0");
454 assert.isUndefined(nonblocking({}, false));
455 assert.equal(nonblocking({ MCP_CONNECTION_NONBLOCKING: "1" }, true), "1");
456 });
457
458 it("pins Claude's auto tool search on through flag settings", () => {
459 const override = ClaudeAdapterV2.claudeToolSearchOverride;
460 for (const value of ["auto", "auto:10", "auto:99.5", "auto:x", "auto:Infinity"]) {
461 assert.equal(override(value), "true", value);
462 }
463 for (const value of [
464 undefined,
465 "true",
466 "false",
467 "auto:0",
468 "auto:-5",
469 "auto:100",
470 "auto:1e2",
471 "auto:1_000",
472 "auto:1,000",
473 "AUTO",
474 ]) {
475 assert.isUndefined(override(value), String(value));
476 }
477
478 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
479 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
480 nativeThreadId: "native-tool-search",
481 resume: false,
482 cwd: "/workspace",
483 sdkSettings: { env: { OTHER: "kept" } },
484 toolSearchOverride: "true",
485 });
486 assert.deepEqual((options.settings as { env?: Record<string, string> }).env, {
487 OTHER: "kept",
488 ENABLE_TOOL_SEARCH: "true",
489 });
490 });
491
492 it("sends the auto-compact window as the env var Claude Code prefers", () => {
493 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
494 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
495 nativeThreadId: "native-auto-compact",
496 resume: false,
497 cwd: "/workspace",
498 settings: { ...DEFAULT_CLAUDE_SETTINGS, autoCompactWindow: "400000" },
499 });
500 assert.equal(
501 (options.settings as { env?: Record<string, string> }).env?.CLAUDE_CODE_AUTO_COMPACT_WINDOW,
502 "400000",
503 );
504 });
505
506 it("sends a custom model named like a Claude Code alias to the API unchanged", () => {
507 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
508 modelSelection: { instanceId: CLAUDE_TEST_MODEL_SELECTION.instanceId, model: "opus" },
509 modelCatalog: scopeClaudeModelCatalog(
510 BUNDLED_CLAUDE_MODEL_CATALOG,
511 CUSTOM_MODEL_CLAUDE_SETTINGS.customModels,
512 ),
513 nativeThreadId: "native-custom-alias",
514 resume: false,
515 cwd: "/workspace",
516 settings: CUSTOM_MODEL_CLAUDE_SETTINGS,
517 });
518 // Claude Code expands a bare alias to its own model unless ANTHROPIC_DEFAULT_<ALIAS>_MODEL overrides it.
519 const settingsEnv =
520 typeof options.settings === "object" && options.settings !== null
521 ? (options.settings as { env?: Record<string, string> }).env
522 : undefined;
523 const aliasOverride =
524 settingsEnv?.ANTHROPIC_DEFAULT_OPUS_MODEL ?? options.env?.ANTHROPIC_DEFAULT_OPUS_MODEL;
525 const requestedModel =
526 options.model === "opus" ? (aliasOverride ?? "claude-opus-5-5") : options.model;
527 assert.equal(requestedModel, "opus");
528 });
529
530 it("projects AskUserQuestion input with question text as the answer key", () => {
531 const preview = "\n **Proposed change**\n\n```ts\n\tconst enabled = true;\n```\n ";
532 assert.deepEqual(
533 ClaudeAdapterV2.claudeUserInputQuestions({
534 questions: [
535 {
536 header: "Approach",
537 question: "Which approach?",
538 options: [
539 { label: "Simple", description: "Use fewer moving parts", preview },
540 { label: "Safe", description: "Keep the current setup" },
541 ],
542 multiSelect: true,
543 },
544 ],
545 }),
546 [
547 {
548 id: "Which approach?",
549 header: "Approach",
550 question: "Which approach?",
551 options: [
552 { label: "Simple", description: "Use fewer moving parts", preview },
553 { label: "Safe", description: "Keep the current setup" },
554 ],
555 multiSelect: true,
556 },
557 ],
558 );
559 const sdkAnswers: NonNullable<AskUserQuestionInput["answers"]> =
560 ClaudeAdapterV2.claudeSdkUserInputAnswers({
561 "Which approach?": ["Simple", "Safe"],
562 "Deploy now?": "Yes",
563 });
564 assert.deepEqual(sdkAnswers, {
565 "Which approach?": "Simple, Safe",
566 "Deploy now?": "Yes",
567 });
568 assert.isTrue(
569 ClaudeAdapterV2.ClaudeProviderCapabilitiesV2.planning.supportsStructuredQuestions,
570 );
571 });
572
573 it("maps canonical read-only never policy to Claude dontAsk with read-only tools", () => {
574 const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
575 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
576 runtimeMode: "full-access",
577 interactionMode: "default",
578 cwd: "/workspace",
579 approvalPolicy: "never",
580 sandboxPolicy: {
581 type: "readOnly",
582 access: { type: "fullAccess" },
583 networkAccess: false,
584 },
585 }),
586 );
587
588 assert.deepEqual(queryPolicy, {
589 permissionMode: "dontAsk",
590 tools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
591 allowedTools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
592 installPermissionCallback: false,
593 });
594 });
595
596 it("does not auto-allow reads for canonical restricted read-only never policy", () => {
597 const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
598 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
599 runtimeMode: "full-access",
600 interactionMode: "default",
601 cwd: "/workspace",
602 approvalPolicy: "never",
603 sandboxPolicy: {
604 type: "readOnly",
605 access: {
606 type: "restricted",
607 includePlatformDefaults: false,
608 readableRoots: [],
609 },
610 networkAccess: false,
611 },
612 }),
613 );
614
615 assert.deepEqual(queryPolicy, {
616 permissionMode: "dontAsk",
617 tools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
618 installPermissionCallback: false,
619 });
620 });
621
622 it("maps default full-access policy to Claude bypass permissions", () => {
623 const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
624 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
625 runtimeMode: "full-access",
626 interactionMode: "default",
627 cwd: "/workspace",
628 }),
629 );
630
631 assert.deepEqual(queryPolicy, {
632 permissionMode: "bypassPermissions",
633 allowDangerouslySkipPermissions: true,
634 installPermissionCallback: false,
635 });
636 });
637
638 it("keeps approval checks when Full access must fall back to an allowed Claude mode", () => {
639 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
640 runtimeMode: "full-access",
641 interactionMode: "default",
642 cwd: "/workspace",
643 approvalPolicy: "never",
644 });
645
646 assert.deepEqual(
647 ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(runtimePolicy, {
648 bypassDisabled: true,
649 autoDisabled: false,
650 }),
651 { permissionMode: "auto", installPermissionCallback: true },
652 );
653 assert.deepEqual(
654 ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(runtimePolicy, {
655 bypassDisabled: true,
656 autoDisabled: true,
657 }),
658 { permissionMode: "default", installPermissionCallback: true },
659 );
660 });
661
662 it("keeps approval-required mode interactive with danger-full-access sandboxing", () => {
663 const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
664 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
665 runtimeMode: "approval-required",
666 interactionMode: "default",
667 cwd: "/workspace",
668 sandboxPolicy: {
669 type: "dangerFullAccess",
670 },
671 }),
672 );
673
674 assert.deepEqual(queryPolicy, {
675 permissionMode: "default",
676 installPermissionCallback: true,
677 });
678 });
679 });
680
681 describe("ClaudeAdapterV2 MCP query overrides", () => {
682 const T3_MCP_SERVERS = {
683 "t3-code": {
684 type: "http",
685 url: "http://127.0.0.1:43123/mcp",
686 headers: {
687 Authorization: "Bearer secret-claude-token",
688 },
689 timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,
690 },
691 } as const;
692
693 const mcpSessionFor = (
694 threadId: ThreadId,
695 authorizationHeader = "Bearer secret-claude-token",
696 ): McpProviderSession.McpProviderSessionConfig => ({
697 environmentId: EnvironmentId.make(`environment-${threadId}`),
698 threadId,
699 providerSessionId: `mcp-session-${threadId}`,
700 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
701 endpoint: "http://127.0.0.1:43123/mcp",
702 authorizationHeader,
703 browserToolsAvailable: true,
704 });
705
706 it("pre-approves only read-only t3-code tools in a read-only sandbox", () => {
707 const threadId = ThreadId.make("thread-claude-mcp-read-only");
708 const mcpSession = mcpSessionFor(threadId);
709 const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({
710 mcpSession,
711 readOnlySandbox: true,
712 allowedTools: [...ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS],
713 });
714
715 assert.deepEqual(overrides, {
716 allowedTools: [
717 ...ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
718 ...ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS,
719 ],
720 mcpServers: T3_MCP_SERVERS,
721 });
722 assert.isFalse(overrides.allowedTools?.includes(ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD));
723 });
724
725 it("invalidates live-query reuse when MCP credentials rotate", () => {
726 const threadId = ThreadId.make("thread-claude-mcp-credential-rotation");
727 const mcpSession = mcpSessionFor(threadId);
728 const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
729 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
730 runtimeMode: "approval-required",
731 interactionMode: "default",
732 cwd: "/workspace",
733 }),
734 );
735 const initialKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
736 queryPolicy,
737 ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: false }),
738 );
739
740 const rotatedKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
741 queryPolicy,
742 ClaudeAdapterV2.claudeMcpQueryOverrides({
743 mcpSession: mcpSessionFor(threadId, "Bearer rotated-claude-token"),
744 readOnlySandbox: false,
745 }),
746 );
747 assert.notEqual(rotatedKey, initialKey);
748 });
749
750 it("matches the read-only allowlist to the orchestrator toolkit annotations", () => {
751 const readOnlyToolNames = [
752 ...Object.values(OrchestratorToolkit.tools),
753 ...Object.values(ThreadToolkit.tools),
754 ...Object.values(WorktreeToolkit.tools),
755 ...Object.values(ProjectToolkit.tools),
756 ...Object.values(EnvironmentToolkit.tools),
757 ...Object.values(ThemeToolkit.tools),
758 ...Object.values(PreviewControlsToolkit.tools),
759 ...Object.values(HtmlToolkit.tools),
760 ...Object.values(MessageToolkit.tools),
761 ]
762 .filter((tool) => Context.get(tool.annotations, Tool.Readonly))
763 .map((tool) => `mcp__t3-code__${tool.name}`)
764 .sort();
765
766 // regression: #32022 Claude Plan mode asks before every non-read-only MCP call
767 assert.include(readOnlyToolNames, "mcp__t3-code__t3_background_wait");
768 assert.deepEqual(
769 [...ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS].sort(),
770 readOnlyToolNames,
771 );
772 });
773 });
774
775 describe("ClaudeAdapterV2 SDK warnings", () => {
776 it("drops only the SDK's canUseTool shadowing warning while opening a query", async () => {
777 using emitWarning = vi.spyOn(process, "emitWarning").mockImplementation(() => {});
778 for (const options of [
779 { permissionMode: "default", allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD] },
780 { permissionMode: "bypassPermissions", allowDangerouslySkipPermissions: true },
781 ] satisfies ReadonlyArray<ClaudeSdk.Options>) {
782 const query = ClaudeAdapterV2.withoutClaudeCanUseToolShadowedWarning(() =>
783 ClaudeSdk.query({
784 prompt: "",
785 options: {
786 ...options,
787 canUseTool: async (_toolName, input) => ({ behavior: "allow", updatedInput: input }),
788 pathToClaudeCodeExecutable: "/nonexistent/claude",
789 },
790 }),
791 );
792 await query.next().catch(() => undefined);
793 }
794 ClaudeAdapterV2.withoutClaudeCanUseToolShadowedWarning(() =>
795 process.emitWarning("unrelated", { code: "UNRELATED_WARNING" }),
796 );
797
798 assert.deepEqual(
799 emitWarning.mock.calls.map(([, options]) =>
800 typeof options === "object" ? options.code : options,
801 ),
802 ["UNRELATED_WARNING"],
803 );
804 assert.strictEqual<unknown>(process.emitWarning, emitWarning);
805 });
806 });
807
808 describe("ClaudeAdapterV2 native protocol logging", () => {
809 it("injects thread-scoped MCP configuration without logging the credential", () => {
810 const threadId = ThreadId.make("thread-claude-mcp");
811 const mcpSession = {
812 environmentId: EnvironmentId.make("environment-claude-mcp"),
813 threadId,
814 providerSessionId: "mcp-session-claude",
815 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
816 endpoint: "http://127.0.0.1:43123/mcp",
817 authorizationHeader: "Bearer secret-claude-token",
818 browserToolsAvailable: true,
819 };
820
821 const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({
822 mcpSession,
823 readOnlySandbox: false,
824 allowedTools: ["Read"],
825 });
826 assert.deepEqual(overrides, {
827 allowedTools: ["Read", "mcp__t3-code__*"],
828 mcpServers: {
829 "t3-code": {
830 type: "http",
831 url: "http://127.0.0.1:43123/mcp",
832 headers: {
833 Authorization: "Bearer secret-claude-token",
834 },
835 timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,
836 },
837 },
838 });
839
840 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
841 modelSelection: {
842 instanceId: ProviderInstanceId.make("claudeAgent"),
843 model: "claude-sonnet-4-6",
844 },
845 nativeThreadId: "native-thread-claude-mcp",
846 resume: false,
847 cwd: "/workspace",
848 allowedTools: overrides.allowedTools ?? [],
849 mcpServers: overrides.mcpServers ?? {},
850 environment: {},
851 });
852 assert.isObject(options.systemPrompt);
853 const systemPrompt = options.systemPrompt as {
854 readonly type: string;
855 readonly preset: string;
856 readonly append?: string;
857 };
858 assert.equal(systemPrompt.type, "preset");
859 assert.equal(systemPrompt.preset, "claude_code");
860 assert.include(systemPrompt.append ?? "", "Use `delegate_task`");
861 assert.include(systemPrompt.append ?? "", "call `t3_background_wait`");
862 assert.notInclude(systemPrompt.append ?? "", "## T3 Code devices");
863 const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
864 assert.equal(logged.hasMcpServers, true);
865 assert.notInclude(JSON.stringify(logged), "secret-claude-token");
866 });
867
868 it("logs --settings key names without their values", () => {
869 const options = ClaudeAdapterV2.makeClaudeQueryOptions({
870 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
871 nativeThreadId: "native-thread-claude-settings-log",
872 resume: false,
873 cwd: "/workspace",
874 sdkSettings: { env: { ANTHROPIC_API_KEY: "secret-settings-key" } },
875 });
876 const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
877 assert.deepEqual(logged.settingKeys, ["env", "showThinkingSummaries"]);
878 assert.notInclude(JSON.stringify(logged), "secret-settings-key");
879 });
880 });
881
882 describe("ClaudeAdapterV2 device instructions", () => {
883 const options = (input: { readonly mcp: boolean; readonly deviceToolsAvailable: boolean }) =>
884 ClaudeAdapterV2.makeClaudeQueryOptions({
885 modelSelection: {
886 instanceId: ProviderInstanceId.make("claudeAgent"),
887 model: "claude-opus-5-5",
888 },
889 nativeThreadId: "native-thread-claude-devices",
890 resume: false,
891 cwd: "/workspace",
892 ...(input.mcp
893 ? { mcpServers: { "t3-code": { type: "http" as const, url: "http://127.0.0.1/mcp" } } }
894 : {}),
895 deviceToolsAvailable: input.deviceToolsAvailable,
896 environment: {},
897 });
898 const append = (input: { readonly mcp: boolean; readonly deviceToolsAvailable: boolean }) =>
899 (options(input).systemPrompt as { readonly append?: string }).append ?? "";
900
901 it("gives a session with device access the device block and the ToolSearch line to load it", () => {
902 const text = append({ mcp: true, deviceToolsAvailable: true });
903 assert.include(text, T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH);
904 assert.include(text, "Use `delegate_task`");
905 });
906
907 it("leaves the device block out without device access or without T3 tools", () => {
908 assert.notInclude(append({ mcp: true, deviceToolsAvailable: false }), "## T3 Code devices");
909 assert.notInclude(append({ mcp: false, deviceToolsAvailable: true }), "## T3 Code devices");
910 });
911
912 it("gives native subagents the device block only in a session with device access", async () => {
913 // Subagents start from their task prompt, not the parent's system prompt.
914 const subagentContext = (input: {
915 readonly mcp: boolean;
916 readonly deviceToolsAvailable: boolean;
917 }) =>
918 Promise.all(
919 (options(input).hooks?.SubagentStart ?? []).flatMap((matcher) =>
920 matcher.hooks.map((hook) =>
921 hook(
922 {
923 hook_event_name: "SubagentStart",
924 agent_id: "agent-1",
925 agent_type: "general-purpose",
926 session_id: "native-thread-claude-devices",
927 transcript_path: "/transcript.jsonl",
928 cwd: "/workspace",
929 },
930 undefined,
931 { signal: new AbortController().signal },
932 ),
933 ),
934 ),
935 );
936 assert.deepEqual(await subagentContext({ mcp: true, deviceToolsAvailable: true }), [
937 {
938 hookSpecificOutput: {
939 hookEventName: "SubagentStart",
940 additionalContext: T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
941 },
942 },
943 ]);
944 assert.deepEqual(await subagentContext({ mcp: true, deviceToolsAvailable: false }), []);
945 assert.deepEqual(await subagentContext({ mcp: false, deviceToolsAvailable: true }), []);
946 });
947 });
948
949 describe("ClaudeAdapterV2 context usage", () => {
950 it("dates cache expiry from the request start, not the response end", () => {
951 const usage = ClaudeAdapterV2.claudeProviderTurnTokenUsage(
952 {
953 input_tokens: 1,
954 output_tokens: 1,
955 cache_creation: { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 300 },
956 },
957 null,
958 "2026-08-29T00:03:00.000Z",
959 "",
960 DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"),
961 );
962 assert.strictEqual(usage.promptCacheExpiresAt, "2026-08-29T00:05:00.000Z");
963 });
964 });
965
966 describe("ClaudeAdapterV2 approval presentation", () => {
967 it("marks asks that full access could not auto-allow and keeps the CLI's reason", () => {
968 const presentation = ClaudeAdapterV2.claudeApprovalPresentation({
969 permissionMode: "bypassPermissions",
970 prompt: 'Claude wants to run rm -r -- "$rr/$h"',
971 callbackOptions: {
972 decisionReason: "\u001b[33mDangerous rm on a path built from a variable\u001b[39m",
973 suppressAlwaysAllowRule: true,
974 },
975 });
976 assert.deepEqual(presentation, {
977 reason: "Dangerous rm on a path built from a variable",
978 fullAccessOverride: "provider_check",
979 options: [
980 { decision: "decline", label: "Decline" },
981 { decision: "accept", label: "Approve" },
982 ],
983 });
984 });
985
986 it("attributes a bypass ask to the user's ask rule when one matched", () => {
987 const presentation = ClaudeAdapterV2.claudeApprovalPresentation({
988 permissionMode: "bypassPermissions",
989 prompt: "Claude wants to run git push",
990 callbackOptions: {
991 matchedAskRule: { source: "userSettings", toolName: "Bash", ruleContent: "git push:*" },
992 },
993 });
994 assert.deepEqual(presentation, { fullAccessOverride: "ask_rule" });
995 });
996
997 it("adds nothing to ordinary approvals outside full access", () => {
998 const presentation = ClaudeAdapterV2.claudeApprovalPresentation({
999 permissionMode: "default",
1000 prompt: "Run make?",
1001 callbackOptions: { decisionReason: "Run make?" },
1002 });
1003 assert.deepEqual(presentation, {});
1004 });
1005 });
1006
1007 describe("ClaudeAdapterV2 session permissions", () => {
1008 // regression: #15892 an explicit user refusal must stay user_reject, not a tool failure
1009 it("keeps explicit user refusals classified as user_reject", () => {
1010 const result = ClaudeAdapterV2.permissionResultFromDecision({
1011 toolName: "Bash",
1012 decision: "decline",
1013 toolInput: { command: "make" },
1014 toolUseID: "denied-build",
1015 });
1016 assert.equal(result.behavior, "deny");
1017 if (result.behavior !== "deny") return;
1018 assert.equal(result.decisionClassification, "user_reject");
1019 assert.equal(result.message, "User declined tool execution.");
1020 assert.equal(result.interrupt, undefined);
1021
1022 // regression: #27854 bare feedback read to Claude as a tool error, not the user's words
1023 const withFeedback = ClaudeAdapterV2.permissionResultFromDecision({
1024 toolName: "Bash",
1025 decision: "decline",
1026 toolInput: { command: "make" },
1027 toolUseID: "denied-build",
1028 feedback: " Use the dry-run flag first. ",
1029 });
1030 assert.equal(withFeedback.behavior, "deny");
1031 if (withFeedback.behavior !== "deny") return;
1032 assert.equal(withFeedback.decisionClassification, "user_reject");
1033 assert.equal(
1034 withFeedback.message,
1035 "The user declined this tool call and said:\nUse the dry-run flag first.",
1036 );
1037 });
1038
1039 it("forces suggested permission updates to session scope", () => {
1040 const result = ClaudeAdapterV2.permissionResultFromDecision({
1041 toolName: "Bash",
1042 decision: "acceptForSession",
1043 toolInput: { command: "git status" },
1044 toolUseID: "tool-1",
1045 suggestions: [
1046 {
1047 type: "addRules",
1048 rules: [{ toolName: "Bash", ruleContent: "git status" }],
1049 behavior: "allow",
1050 destination: "localSettings",
1051 },
1052 ],
1053 });
1054
1055 assert.equal(result.behavior, "allow");
1056 if (result.behavior !== "allow") {
1057 return;
1058 }
1059 assert.deepEqual(result.updatedPermissions, [
1060 {
1061 type: "addRules",
1062 rules: [{ toolName: "Bash", ruleContent: "git status" }],
1063 behavior: "allow",
1064 destination: "session",
1065 },
1066 ]);
1067
1068 // Under an administrator's ceiling a suggested mode switch is dropped; the rule stays.
1069 const managed = ClaudeAdapterV2.permissionResultFromDecision({
1070 toolName: "Edit",
1071 decision: "acceptForSession",
1072 toolInput: {},
1073 toolUseID: "tool-2",
1074 managedCeiling: true,
1075 suggestions: [
1076 { type: "setMode", mode: "acceptEdits", destination: "session" },
1077 {
1078 type: "addRules",
1079 rules: [{ toolName: "Edit" }],
1080 behavior: "allow",
1081 destination: "session",
1082 },
1083 ],
1084 });
1085 assert.deepEqual(managed.behavior === "allow" ? managed.updatedPermissions : undefined, [
1086 {
1087 type: "addRules",
1088 rules: [{ toolName: "Edit" }],
1089 behavior: "allow",
1090 destination: "session",
1091 },
1092 ]);
1093 });
1094
1095 it("adds a whole-tool session rule when Claude offers no suggestion", () => {
1096 const result = ClaudeAdapterV2.permissionResultFromDecision({
1097 toolName: "mcp__t3__custom_tool",
1098 decision: "acceptForSession",
1099 toolInput: {},
1100 toolUseID: "tool-2",
1101 });
1102
1103 assert.equal(result.behavior, "allow");
1104 if (result.behavior !== "allow") {
1105 return;
1106 }
1107 assert.deepEqual(result.updatedPermissions, [
1108 {
1109 type: "addRules",
1110 rules: [{ toolName: "mcp__t3__custom_tool" }],
1111 behavior: "allow",
1112 destination: "session",
1113 },
1114 ]);
1115 });
1116 });
1117
1118 describe("ClaudeAdapterV2 Auto-accept edits", () => {
1119 it.effect("asks before a command instead of allowing it", () =>
1120 Effect.gen(function* () {
1121 const fileSystem = yield* FileSystem.FileSystem;
1122 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1123 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
1124 prefix: "t3-claude-accept-edits-",
1125 });
1126 let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
1127 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1128 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1129 settings: DEFAULT_CLAUDE_SETTINGS,
1130 environment: {},
1131 attachmentsDir,
1132 fileSystem,
1133 path: yield* Path.Path,
1134 random: yield* SecureRandom.SecureRandom,
1135 idAllocator,
1136 queryRunner: {
1137 allocateSessionId: Effect.succeed("native-thread-claude-accept-edits"),
1138 open: (input) =>
1139 Effect.sync(() => {
1140 openedOptions = input.options;
1141 return {
1142 messages: Stream.never,
1143 offer: () => Effect.void,
1144 setModel: () => Effect.void,
1145 applyFlagSettings: () => Effect.void,
1146 setPermissionMode: () => Effect.void,
1147 renameSession: () => Effect.void,
1148 backgroundTasks: () => Effect.succeed(false),
1149 mcpServerStatus: Effect.succeed([]),
1150 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1151 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1152 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1153 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1154 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1155 listPermissionRules: Effect.die("unexpected permission rules read"),
1156 stopTask: () => Effect.void,
1157 interrupt: Effect.void,
1158 close: Effect.void,
1159 };
1160 }),
1161 forkSession: () => Effect.die("unused"),
1162 subagentLaunchToolUseId: () => Effect.succeed(null),
1163 subagentModel: () => Effect.succeed(null),
1164 assertComplete: Effect.void,
1165 },
1166 });
1167 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1168 runtimeMode: "auto-accept-edits",
1169 interactionMode: "default",
1170 cwd: "/workspace",
1171 });
1172 const threadId = ThreadId.make("thread-claude-accept-edits");
1173 const runtime = yield* adapter.openSession({
1174 threadId,
1175 providerSessionId: ProviderSessionId.make("provider-session-claude-accept-edits"),
1176 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1177 runtimePolicy,
1178 });
1179 const providerThread = yield* runtime.ensureThread({
1180 threadId,
1181 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1182 runtimePolicy,
1183 });
1184 const now = yield* DateTime.now;
1185 yield* runtime.startTurn(
1186 makeClaudeTestTurnInput({
1187 threadId,
1188 providerThread,
1189 now,
1190 attemptId: RunAttemptId.make("attempt-claude-accept-edits"),
1191 text: "Run node.",
1192 attachments: [],
1193 runtimePolicy,
1194 }),
1195 );
1196 assert.equal(openedOptions?.permissionMode, "acceptEdits");
1197 const canUseTool = openedOptions?.canUseTool;
1198 assert.isFunction(canUseTool);
1199
1200 const requestEvent = yield* runtime.events.pipe(
1201 Stream.takeUntil(
1202 (event) =>
1203 event.type === "turn_item.updated" && event.turnItem.type === "approval_request",
1204 ),
1205 Stream.runCollect,
1206 Effect.forkScoped,
1207 );
1208 const command = { command: "node -e 'console.log(42)'" };
1209 const decision = yield* Effect.promise(() =>
1210 canUseTool!("Bash", command, {
1211 signal: new AbortController().signal,
1212 toolUseID: "tool-bash-accept-edits",
1213 requestId: "request-bash-accept-edits",
1214 description: "Check the Node runtime",
1215 }),
1216 ).pipe(Effect.forkScoped);
1217 const first = yield* Effect.raceFirst(
1218 Fiber.join(requestEvent).pipe(Effect.map((event) => ({ type: "request", event }) as const)),
1219 Fiber.join(decision).pipe(Effect.map((result) => ({ type: "decision", result }) as const)),
1220 );
1221 assert.equal(first.type, "request", "the command ran without asking");
1222 if (first.type !== "request") return;
1223 const event = first.event.find((event) => event.type === "runtime_request.updated");
1224 assert.equal(event?.runtimeRequest.kind, "command");
1225 const approval = first.event.findLast((event) => event.type === "turn_item.updated");
1226 assert.equal(
1227 approval?.turnItem.type === "approval_request" ? approval.turnItem.prompt : undefined,
1228 command.command,
1229 );
1230
1231 yield* runtime.respondToRuntimeRequest({
1232 requestId: event!.runtimeRequest.id,
1233 decision: "accept",
1234 });
1235 assert.equal((yield* Fiber.join(decision))?.behavior, "allow");
1236 }).pipe(
1237 Effect.provide(
1238 Layer.mergeAll(
1239 IdAllocator.layer,
1240 McpProviderSessions.layer,
1241 NodeServices.layer,
1242 NodeCrypto.layer,
1243 ),
1244 ),
1245 ),
1246 );
1247 });
1248
1249 describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1250 const startTurnWithLaunchArgs = Effect.fnUntraced(function* (launchArgs: string, cwd: string) {
1251 const fileSystem = yield* FileSystem.FileSystem;
1252 const opened: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOptions> = [];
1253 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1254 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1255 settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs },
1256 environment: {},
1257 attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-" }),
1258 fileSystem,
1259 path: yield* Path.Path,
1260 random: yield* SecureRandom.SecureRandom,
1261 idAllocator: yield* IdAllocator.IdAllocatorV2,
1262 queryRunner: {
1263 allocateSessionId: Effect.succeed("native-thread-claude-append-file"),
1264 open: (input) =>
1265 Effect.sync(() => {
1266 opened.push(input.options);
1267 return {
1268 messages: Stream.never,
1269 offer: () => Effect.void,
1270 setModel: () => Effect.void,
1271 applyFlagSettings: () => Effect.void,
1272 setPermissionMode: () => Effect.void,
1273 renameSession: () => Effect.void,
1274 backgroundTasks: () => Effect.succeed(false),
1275 mcpServerStatus: Effect.succeed([]),
1276 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1277 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1278 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1279 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1280 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1281 listPermissionRules: Effect.die("unexpected permission rules read"),
1282 stopTask: () => Effect.void,
1283 interrupt: Effect.void,
1284 close: Effect.void,
1285 };
1286 }),
1287 forkSession: () => Effect.die("unused"),
1288 subagentLaunchToolUseId: () => Effect.succeed(null),
1289 subagentModel: () => Effect.succeed(null),
1290 assertComplete: Effect.void,
1291 },
1292 });
1293 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1294 runtimeMode: "full-access",
1295 interactionMode: "default",
1296 cwd,
1297 });
1298 const threadId = ThreadId.make("thread-claude-append-file");
1299 const runtime = yield* adapter.openSession({
1300 threadId,
1301 providerSessionId: ProviderSessionId.make("provider-session-claude-append-file"),
1302 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1303 runtimePolicy,
1304 });
1305 const providerThread = yield* runtime.ensureThread({
1306 threadId,
1307 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1308 runtimePolicy,
1309 });
1310 const exit = yield* runtime
1311 .startTurn(
1312 makeClaudeTestTurnInput({
1313 threadId,
1314 providerThread,
1315 now: yield* DateTime.now,
1316 attemptId: RunAttemptId.make("attempt-claude-append-file"),
1317 text: "What is the sentinel?",
1318 attachments: [],
1319 runtimePolicy,
1320 }),
1321 )
1322 .pipe(Effect.exit);
1323 return { exit, opened };
1324 });
1325
1326 const appendSystemPrompt = (options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined) =>
1327 (options?.systemPrompt as { readonly append?: string } | undefined)?.append;
1328
1329 // regression: #35594 append text starting with "--" was read as a missing value
1330 it.effect("sends append launch text that starts with two hyphens to Claude", () =>
1331 Effect.scoped(
1332 Effect.gen(function* () {
1333 const fileSystem = yield* FileSystem.FileSystem;
1334 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
1335 const plain = yield* startTurnWithLaunchArgs("", cwd);
1336 const { exit, opened } = yield* startTurnWithLaunchArgs(
1337 '--append-system-prompt "-- Always answer in English"',
1338 cwd,
1339 );
1340 assert.isTrue(Exit.isSuccess(exit));
1341 assert.lengthOf(opened, 1);
1342 assert.equal(
1343 appendSystemPrompt(opened[0]),
1344 `${appendSystemPrompt(plain.opened[0])}\n\n-- Always answer in English`,
1345 );
1346 }).pipe(
1347 Effect.provide(
1348 Layer.mergeAll(
1349 IdAllocator.layer,
1350 McpProviderSessions.layer,
1351 NodeServices.layer,
1352 NodeCrypto.layer,
1353 ),
1354 ),
1355 ),
1356 ),
1357 );
1358
1359 it.effect("sends append launch arguments to Claude after the T3 instructions", () =>
1360 Effect.gen(function* () {
1361 const fileSystem = yield* FileSystem.FileSystem;
1362 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
1363 yield* fileSystem.writeFileString(NodePath.join(cwd, "rules.md"), "File sentinel\n");
1364 const plain = yield* startTurnWithLaunchArgs("", cwd);
1365 const { exit, opened } = yield* startTurnWithLaunchArgs(
1366 '--append-system-prompt "Inline sentinel" --append-system-prompt-file rules.md --system-prompt Replacement',
1367 cwd,
1368 );
1369 assert.isTrue(Exit.isSuccess(exit));
1370 assert.lengthOf(opened, 1);
1371 assert.equal(
1372 appendSystemPrompt(opened[0]),
1373 `${appendSystemPrompt(plain.opened[0])}\n\nFile sentinel\n\nInline sentinel`,
1374 );
1375 assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt"]);
1376 assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt-file"]);
1377 assert.equal(opened[0]!.extraArgs?.["system-prompt"], "Replacement");
1378 }).pipe(
1379 Effect.provide(
1380 Layer.mergeAll(
1381 IdAllocator.layer,
1382 McpProviderSessions.layer,
1383 NodeServices.layer,
1384 NodeCrypto.layer,
1385 ),
1386 ),
1387 ),
1388 );
1389
1390 // regression: #15073 the SDK replaced the --settings launch argument with T3's settings
1391 it.effect.each([
1392 `--settings '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}'`,
1393 "--settings user-settings.json",
1394 ])("merges %s beneath T3's settings", (launchArgs) =>
1395 Effect.gen(function* () {
1396 const fileSystem = yield* FileSystem.FileSystem;
1397 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-settings-" });
1398 yield* fileSystem.writeFileString(
1399 NodePath.join(cwd, "user-settings.json"),
1400 '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}',
1401 );
1402 const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
1403 assert.isTrue(Exit.isSuccess(exit));
1404 assert.deepInclude(opened[0]!.settings, {
1405 skillOverrides: { lint: "off" },
1406 showThinkingSummaries: true,
1407 });
1408 assert.isUndefined(opened[0]!.extraArgs?.["settings"]);
1409 }).pipe(
1410 Effect.provide(
1411 Layer.mergeAll(
1412 IdAllocator.layer,
1413 McpProviderSessions.layer,
1414 NodeServices.layer,
1415 NodeCrypto.layer,
1416 ),
1417 ),
1418 ),
1419 );
1420
1421 // regression: #26631 `~/` launch argument paths resolved under the project cwd
1422 it.effect.each([
1423 [
1424 "--settings ~/.claude/settings.json",
1425 (options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions) =>
1426 assert.deepInclude(options.settings, { skillOverrides: { lint: "off" } }),
1427 ],
1428 [
1429 "--append-system-prompt-file ~/.claude/settings.json",
1430 (options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions) =>
1431 assert.include(appendSystemPrompt(options), '{"skillOverrides":{"lint":"off"}}'),
1432 ],
1433 ] as const)("reads %s from the home directory", ([launchArgs, assertOptions]) =>
1434 Effect.gen(function* () {
1435 const fileSystem = yield* FileSystem.FileSystem;
1436 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-" });
1437 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-cwd-" });
1438 yield* fileSystem.makeDirectory(NodePath.join(home, ".claude"));
1439 yield* fileSystem.writeFileString(
1440 NodePath.join(home, ".claude", "settings.json"),
1441 '{"skillOverrides":{"lint":"off"}}',
1442 );
1443 const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd).pipe(
1444 Effect.provideService(HostProcess.HomeDirectory, home),
1445 );
1446 if (Exit.isFailure(exit)) {
1447 assert.fail(makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message);
1448 }
1449 assert.lengthOf(opened, 1);
1450 assertOptions(opened[0]!);
1451 }).pipe(
1452 Effect.provide(
1453 Layer.mergeAll(
1454 IdAllocator.layer,
1455 McpProviderSessions.layer,
1456 NodeServices.layer,
1457 NodeCrypto.layer,
1458 ),
1459 ),
1460 ),
1461 );
1462
1463 // regression: #20413 malformed append-system-prompt launch args fail before a query opens
1464 it.effect.each([
1465 [
1466 "--append-system-prompt-file missing.md",
1467 (cwd: string) =>
1468 new ClaudeAdapterV2.ClaudeAppendSystemPromptFileError({
1469 path: NodePath.join(cwd, "missing.md"),
1470 }).message,
1471 ],
1472 [
1473 "--append-system-prompt-file",
1474 () =>
1475 new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
1476 flag: "--append-system-prompt-file",
1477 }).message,
1478 ],
1479 [
1480 "--append-system-prompt-file=",
1481 () =>
1482 new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
1483 flag: "--append-system-prompt-file",
1484 }).message,
1485 ],
1486 [
1487 "--append-system-prompt",
1488 () =>
1489 new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
1490 flag: "--append-system-prompt",
1491 }).message,
1492 ],
1493 [
1494 "--settings missing.json",
1495 (cwd: string) =>
1496 new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({
1497 path: NodePath.join(cwd, "missing.json"),
1498 }).message,
1499 ],
1500 ["--settings '{not json}'", () => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message],
1501 // Without a closing brace this must not become a file path that echoes the secret.
1502 [
1503 `--settings '{"env":{"ANTHROPIC_API_KEY":"secret-settings-key"},'`,
1504 () => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message,
1505 ],
1506 ] as const)("fails the turn before opening Claude for %s", ([launchArgs, expectedMessage]) =>
1507 Effect.gen(function* () {
1508 const fileSystem = yield* FileSystem.FileSystem;
1509 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
1510 const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
1511 assert.lengthOf(opened, 0);
1512 assert.isTrue(Exit.isFailure(exit));
1513 if (!Exit.isFailure(exit)) return;
1514 assert.equal(
1515 makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message,
1516 expectedMessage(cwd),
1517 );
1518 }).pipe(
1519 Effect.provide(
1520 Layer.mergeAll(
1521 IdAllocator.layer,
1522 McpProviderSessions.layer,
1523 NodeServices.layer,
1524 NodeCrypto.layer,
1525 ),
1526 ),
1527 ),
1528 );
1529 });
1530
1531 describe("ClaudeAdapterV2 provider installation gate", () => {
1532 it.effect("opens each turn's Claude process inside the installation gate", () =>
1533 Effect.gen(function* () {
1534 const fileSystem = yield* FileSystem.FileSystem;
1535 const log: Array<string> = [];
1536 const instanceId = ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID;
1537 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1538 instanceId,
1539 settings: DEFAULT_CLAUDE_SETTINGS,
1540 environment: {},
1541 attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-" }),
1542 fileSystem,
1543 path: yield* Path.Path,
1544 random: yield* SecureRandom.SecureRandom,
1545 idAllocator: yield* IdAllocator.IdAllocatorV2,
1546 installationGate: ProviderInstallationGate.ProviderInstallationGate.of({
1547 execute: (gatedInstanceId, effect) =>
1548 Effect.sync(() => log.push(`enter ${gatedInstanceId}`)).pipe(
1549 Effect.andThen(effect),
1550 Effect.ensuring(Effect.sync(() => log.push("exit"))),
1551 ),
1552 update: () => Effect.die("unused"),
1553 }),
1554 queryRunner: {
1555 allocateSessionId: Effect.succeed("native-thread-claude-gate"),
1556 open: () =>
1557 Effect.sync(() => {
1558 log.push("open query");
1559 return {
1560 messages: Stream.never,
1561 offer: () => Effect.void,
1562 setModel: () => Effect.void,
1563 applyFlagSettings: () => Effect.void,
1564 setPermissionMode: () => Effect.void,
1565 renameSession: () => Effect.void,
1566 backgroundTasks: () => Effect.succeed(false),
1567 mcpServerStatus: Effect.succeed([]),
1568 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1569 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1570 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1571 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1572 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1573 listPermissionRules: Effect.die("unexpected permission rules read"),
1574 stopTask: () => Effect.void,
1575 interrupt: Effect.void,
1576 close: Effect.void,
1577 };
1578 }),
1579 forkSession: () => Effect.die("unused"),
1580 subagentLaunchToolUseId: () => Effect.succeed(null),
1581 subagentModel: () => Effect.succeed(null),
1582 assertComplete: Effect.void,
1583 },
1584 });
1585 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1586 runtimeMode: "full-access",
1587 interactionMode: "default",
1588 cwd: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-cwd-" }),
1589 });
1590 const threadId = ThreadId.make("thread-claude-gate");
1591 const runtime = yield* adapter.openSession({
1592 threadId,
1593 providerSessionId: ProviderSessionId.make("provider-session-claude-gate"),
1594 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1595 runtimePolicy,
1596 });
1597 const providerThread = yield* runtime.ensureThread({
1598 threadId,
1599 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1600 runtimePolicy,
1601 });
1602 assert.deepStrictEqual(log, []);
1603
1604 yield* runtime.startTurn(
1605 makeClaudeTestTurnInput({
1606 threadId,
1607 providerThread,
1608 now: yield* DateTime.now,
1609 attemptId: RunAttemptId.make("attempt-claude-gate"),
1610 text: "Hello",
1611 attachments: [],
1612 runtimePolicy,
1613 }),
1614 );
1615
1616 assert.deepStrictEqual(log, [`enter ${instanceId}`, "open query", "exit"]);
1617 }).pipe(
1618 Effect.provide(
1619 Layer.mergeAll(
1620 IdAllocator.layer,
1621 McpProviderSessions.layer,
1622 NodeServices.layer,
1623 NodeCrypto.layer,
1624 ),
1625 ),
1626 ),
1627 );
1628 });
1629
1630 describe("ClaudeAdapterV2 approval cancellation", () => {
1631 it.effect("observes an approval signal that was already aborted", () =>
1632 Effect.gen(function* () {
1633 const decision = yield* Deferred.make<{
1634 decision: ProviderApprovalDecision;
1635 feedback?: string;
1636 }>();
1637 const result = yield* ClaudeAdapterV2.awaitClaudeApprovalDecision(
1638 decision,
1639 AbortSignal.abort(),
1640 );
1641
1642 assert.deepEqual(result, { decision: "cancel" });
1643 }),
1644 );
1645 });
1646
1647 describe("ClaudeAdapterV2 MCP elicitation acceptance", () => {
1648 const form = (
1649 properties: Record<string, unknown>,
1650 required?: ReadonlyArray<string>,
1651 ): ElicitationRequest => ({
1652 serverName: "deploys",
1653 message: "Deploy web?",
1654 mode: "form",
1655 requestedSchema: { type: "object", properties, ...(required ? { required } : {}) },
1656 });
1657
1658 it("answers an empty-properties form with empty content", () => {
1659 assert.deepEqual(ClaudeAdapterV2.claudeMcpElicitationAcceptance(form({})), {
1660 action: "accept",
1661 content: {},
1662 });
1663 });
1664
1665 it("picks the one-time choice however the server spells it", () => {
1666 for (const choice of [
1667 "allow_once",
1668 "Allow",
1669 "accept_once",
1670 "Approve once",
1671 "allow_this_time",
1672 "allow_once_only",
1673 ]) {
1674 assert.deepEqual(
1675 ClaudeAdapterV2.claudeMcpElicitationAcceptance(
1676 form({ decision: { type: "string", enum: ["disallow", choice, "always"] } }, [
1677 "decision",
1678 ]),
1679 ),
1680 { action: "accept", content: { decision: choice } },
1681 );
1682 }
1683 });
1684
1685 it("answers a persistence toggle with false", () => {
1686 assert.deepEqual(
1687 ClaudeAdapterV2.claudeMcpElicitationAcceptance(
1688 form({ remember: { type: "boolean", title: "Always allow" } }, ["remember"]),
1689 ),
1690 { action: "accept", content: { remember: false } },
1691 );
1692 });
1693
1694 it("leaves out optional fields the card does not show", () => {
1695 assert.deepEqual(
1696 ClaudeAdapterV2.claudeMcpElicitationAcceptance(
1697 form({ scope: { type: "string", enum: ["once", "always"], default: "always" } }),
1698 ),
1699 { action: "accept", content: { scope: "once" } },
1700 );
1701 assert.deepEqual(
1702 ClaudeAdapterV2.claudeMcpElicitationAcceptance(
1703 form({ limit: { type: "number", default: 500 } }),
1704 ),
1705 { action: "accept", content: {} },
1706 );
1707 });
1708
1709 it("has no answer for URL mode or a form asking for a value", () => {
1710 for (const request of [
1711 { serverName: "deploys", message: "Sign in", mode: "url", url: "https://example.com" },
1712 form({ reason: { type: "string" } }, ["reason"]),
1713 form({ grant: { type: "string", enum: ["always", "session"] } }, ["grant"]),
1714 form({ grant: { type: "string", enum: ["deny", "always"], default: "always" } }, ["grant"]),
1715 form({ limit: { type: "number", default: 500 } }, ["limit"]),
1716 { serverName: "deploys", message: "Deploy web?", mode: "form" },
1717 ] satisfies ReadonlyArray<ElicitationRequest>) {
1718 assert.isUndefined(ClaudeAdapterV2.claudeMcpElicitationAcceptance(request));
1719 }
1720 });
1721 });
1722
1723 const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(function* (
1724 binaryPath: string,
1725 environment: ResolvedProviderInstanceEnvironment = [],
1726 ) {
1727 const executablePaths: Array<string | undefined> = [];
1728 const taskToolEnvironment: Array<string | undefined> = [];
1729 const adapter = yield* ClaudeAdapterV2.createClaudeAdapterV2(
1730 {
1731 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1732 displayName: undefined,
1733 environment,
1734 enabled: true,
1735 config: { ...DEFAULT_CLAUDE_SETTINGS, binaryPath },
1736 },
1737 {},
1738 ).pipe(
1739 Effect.provide(
1740 ServerConfig.layerTest(process.cwd(), {
1741 prefix: "t3-claude-binary-path-",
1742 }),
1743 ),
1744 Effect.provideService(ClaudeAdapterV2.ClaudeAgentSdkQueryRunner, {
1745 allocateSessionId: Effect.succeed("native-thread-claude-binary-path"),
1746 open: (input) =>
1747 Effect.sync(() => {
1748 executablePaths.push(input.options.pathToClaudeCodeExecutable);
1749 taskToolEnvironment.push(input.options.env?.CLAUDE_CODE_ENABLE_TODO_TOOLS);
1750 return {
1751 messages: Stream.never,
1752 offer: () => Effect.void,
1753 setModel: () => Effect.void,
1754 applyFlagSettings: () => Effect.void,
1755 setPermissionMode: () => Effect.void,
1756 renameSession: () => Effect.void,
1757 backgroundTasks: () => Effect.succeed(false),
1758 mcpServerStatus: Effect.succeed([]),
1759 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1760 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1761 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1762 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1763 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1764 listPermissionRules: Effect.die("unexpected permission rules read"),
1765 stopTask: () => Effect.void,
1766 interrupt: Effect.void,
1767 close: Effect.void,
1768 };
1769 }),
1770 forkSession: () => Effect.die("unused"),
1771 subagentLaunchToolUseId: () => Effect.succeed(null),
1772 subagentModel: () => Effect.succeed(null),
1773 assertComplete: Effect.void,
1774 }),
1775 );
1776 const threadId = ThreadId.make("thread-claude-binary-path");
1777 const runtime = yield* adapter.openSession({
1778 threadId,
1779 providerSessionId: ProviderSessionId.make("provider-session-claude-binary-path"),
1780 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1781 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1782 });
1783 const providerThread = yield* runtime.ensureThread({
1784 threadId,
1785 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1786 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1787 });
1788 yield* runtime.startTurn(
1789 makeClaudeTestTurnInput({
1790 threadId,
1791 providerThread,
1792 now: yield* DateTime.now,
1793 attemptId: RunAttemptId.make("attempt-claude-binary-path"),
1794 text: "hello",
1795 attachments: [],
1796 }),
1797 );
1798 return { executablePaths, taskToolEnvironment };
1799 });
1800
1801 describe("ClaudeAdapterV2 executable path", () => {
1802 it.effect("follows a bare claude on Windows to the npm package executable", () =>
1803 Effect.scoped(
1804 Effect.gen(function* () {
1805 const npmDir = "C:\\Users\\dev\\AppData\\Roaming\\npm";
1806 const packageExe = `${npmDir}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`;
1807 const { executablePaths } = yield* captureSdkExecutablePaths("claude").pipe(
1808 Effect.provideService(HostProcess.Platform, "win32"),
1809 Effect.provideService(SpawnExecutableResolution, () => `${npmDir}\\claude.cmd`),
1810 Effect.provideService(ClaudeExecutableFileCheck, (filePath) => filePath === packageExe),
1811 );
1812
1813 assert.deepEqual(executablePaths, [packageExe]);
1814 }),
1815 ).pipe(
1816 Effect.provide(
1817 Layer.mergeAll(
1818 IdAllocator.layer,
1819 McpProviderSessions.layer,
1820 ProviderInstallationGate.layer,
1821 NodeServices.layer,
1822 NodeCrypto.layer,
1823 ),
1824 ),
1825 ),
1826 );
1827 });
1828
1829 describe("ClaudeAdapterV2 resumeThread", () => {
1830 it.effect("fails for a transcript without messages so a fresh session replaces it", () =>
1831 Effect.scoped(
1832 Effect.gen(function* () {
1833 const fileSystem = yield* FileSystem.FileSystem;
1834 const path = yield* Path.Path;
1835 const configDir = yield* fileSystem.makeTempDirectoryScoped({
1836 prefix: "t3-claude-empty-session-",
1837 });
1838 const projectDir = path.join(configDir, "projects", "-workspace");
1839 yield* fileSystem.makeDirectory(projectDir, { recursive: true });
1840 yield* fileSystem.writeFileString(
1841 path.join(projectDir, "native-thread-empty.jsonl"),
1842 [
1843 `{"type":"last-prompt","lastPrompt":"hello","sessionId":"native-thread-empty"}`,
1844 `{"type":"atis-latch","atis":"","sessionId":"native-thread-empty"}`,
1845 `{"type":"cost-state","sessionId":"native-thread-empty","totalCostUSD":0}`,
1846 "",
1847 ].join("\n"),
1848 );
1849 yield* fileSystem.writeFileString(
1850 path.join(projectDir, "native-thread-saved.jsonl"),
1851 `{"type":"user","message":{"role":"user","content":"hello"},"sessionId":"native-thread-saved"}\n`,
1852 );
1853 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1854 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1855 settings: DEFAULT_CLAUDE_SETTINGS,
1856 environment: { CLAUDE_CONFIG_DIR: configDir },
1857 attachmentsDir: configDir,
1858 fileSystem,
1859 path,
1860 random: yield* SecureRandom.SecureRandom,
1861 idAllocator: yield* IdAllocator.IdAllocatorV2,
1862 queryRunner: {
1863 allocateSessionId: Effect.succeed("native-thread-empty"),
1864 open: () => Effect.die("unused"),
1865 forkSession: () => Effect.die("unused"),
1866 subagentLaunchToolUseId: () => Effect.succeed(null),
1867 subagentModel: () => Effect.succeed(null),
1868 assertComplete: Effect.void,
1869 },
1870 });
1871 const threadId = ThreadId.make("thread-claude-empty-session");
1872 const runtime = yield* adapter.openSession({
1873 threadId,
1874 providerSessionId: ProviderSessionId.make("provider-session-claude-empty-session"),
1875 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1876 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1877 });
1878 const providerThread = yield* runtime.ensureThread({
1879 threadId,
1880 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1881 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1882 });
1883
1884 const error = yield* Effect.flip(runtime.resumeThread({ providerThread }));
1885 assert.equal(error._tag, "ProviderAdapterResumeThreadError");
1886
1887 const saved = yield* runtime.resumeThread({
1888 providerThread: {
1889 ...providerThread,
1890 nativeThreadRef: {
1891 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1892 nativeId: "native-thread-saved",
1893 strength: "strong",
1894 },
1895 },
1896 });
1897 assert.equal(saved.nativeThreadRef?.nativeId, "native-thread-saved");
1898
1899 const missing = yield* runtime.resumeThread({
1900 providerThread: {
1901 ...providerThread,
1902 nativeThreadRef: {
1903 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1904 nativeId: "native-thread-missing",
1905 strength: "strong",
1906 },
1907 },
1908 });
1909 assert.equal(missing.nativeThreadRef?.nativeId, "native-thread-missing");
1910
1911 // An imported session's history lives only in its transcript.
1912 const missingImport = yield* Effect.flip(
1913 runtime.resumeThread({
1914 providerThread: { ...missing, id: providerThread.id },
1915 importedNativeSession: true,
1916 }),
1917 );
1918 assert.equal(missingImport._tag, "ProviderAdapterResumeThreadError");
1919 }),
1920 ).pipe(
1921 Effect.provide(
1922 Layer.mergeAll(
1923 IdAllocator.layer,
1924 McpProviderSessions.layer,
1925 NodeServices.layer,
1926 NodeCrypto.layer,
1927 ),
1928 ),
1929 ),
1930 );
1931 });
1932
1933 describe("ClaudeAdapterV2 resume compaction", () => {
1934 it.effect("resolves and cancels the SDK resume dialog through structured runtime input", () =>
1935 Effect.gen(function* () {
1936 const fileSystem = yield* FileSystem.FileSystem;
1937 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1938 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
1939 prefix: "t3-claude-resume-",
1940 });
1941 let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
1942 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1943 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1944 settings: DEFAULT_CLAUDE_SETTINGS,
1945 environment: {},
1946 attachmentsDir,
1947 fileSystem,
1948 path: yield* Path.Path,
1949 random: yield* SecureRandom.SecureRandom,
1950 idAllocator,
1951 queryRunner: {
1952 allocateSessionId: Effect.succeed("native-thread-claude-resume"),
1953 open: (input) =>
1954 Effect.sync(() => {
1955 openedOptions = input.options;
1956 return {
1957 messages: Stream.never,
1958 offer: () => Effect.void,
1959 setModel: () => Effect.void,
1960 applyFlagSettings: () => Effect.void,
1961 setPermissionMode: () => Effect.void,
1962 renameSession: () => Effect.void,
1963 backgroundTasks: () => Effect.succeed(false),
1964 mcpServerStatus: Effect.succeed([]),
1965 readMcpResource: () => Effect.die("unexpected MCP resource read"),
1966 callMcpTool: () => Effect.die("unexpected MCP tool call"),
1967 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
1968 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
1969 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
1970 listPermissionRules: Effect.die("unexpected permission rules read"),
1971 stopTask: () => Effect.void,
1972 interrupt: Effect.void,
1973 close: Effect.void,
1974 };
1975 }),
1976 forkSession: () => Effect.die("unused"),
1977 subagentLaunchToolUseId: () => Effect.succeed(null),
1978 subagentModel: () => Effect.succeed(null),
1979 assertComplete: Effect.void,
1980 },
1981 });
1982 const threadId = ThreadId.make("thread-claude-resume");
1983 const runtime = yield* adapter.openSession({
1984 threadId,
1985 providerSessionId: ProviderSessionId.make("provider-session-claude-resume"),
1986 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1987 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1988 });
1989 const providerThread = yield* runtime.ensureThread({
1990 threadId,
1991 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1992 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1993 });
1994 const now = yield* DateTime.now;
1995 yield* runtime.startTurn(
1996 makeClaudeTestTurnInput({
1997 threadId,
1998 providerThread,
1999 now,
2000 attemptId: RunAttemptId.make("attempt-claude-resume"),
2001 text: "continue",
2002 attachments: [],
2003 }),
2004 );
2005 const callback = openedOptions?.onUserDialog;
2006 assert.isFunction(callback);
2007 const canUseTool = openedOptions?.canUseTool;
2008 assert.isFunction(canUseTool);
2009 const shellSafetyReason =
2010 "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed";
2011 for (const [safetyIndex, { askRule, reason }] of [
2012 { askRule: false, reason: shellSafetyReason },
2013 { askRule: true, reason: shellSafetyReason },
2014 {
2015 askRule: false,
2016 reason:
2017 "Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.",
2018 },
2019 { askRule: false, reason: "This shell -c script runs rm and could not be checked" },
2020 { askRule: false, reason: "A permission rule denies a command in this shell -c script" },
2021 {
2022 askRule: false,
2023 reason:
2024 "Claude Code can't be sure it read this command the way the shell will, so it can't rule out a dangerous removal. Read the command, and don't go ahead if you can't tell what it does.",
2025 },
2026 ].entries()) {
2027 const safetyRequest = yield* runtime.events.pipe(
2028 Stream.filter((event) => event.type === "runtime_request.updated"),
2029 Stream.runHead,
2030 Effect.forkScoped,
2031 );
2032 const safetySignal = yield* Effect.abortSignal;
2033 const safetyDecision = yield* Effect.promise(() =>
2034 canUseTool!(
2035 "Bash",
2036 { command: "for pair in a b; do echo $pair; done" },
2037 {
2038 signal: safetySignal,
2039 toolUseID: `tool-shell-safety-${safetyIndex}`,
2040 requestId: `request-shell-safety-${safetyIndex}`,
2041 decisionReason: `\u001b[33m${reason}\u001b[39m`,
2042 suppressAlwaysAllowRule: true,
2043 ...(askRule
2044 ? {
2045 matchedAskRule: {
2046 source: "userSettings" as const,
2047 toolName: "Bash",
2048 ruleContent: "*",
2049 },
2050 }
2051 : {}),
2052 },
2053 ),
2054 ).pipe(Effect.forkScoped);
2055 const safety = yield* Effect.raceFirst(
2056 Fiber.join(safetyDecision).pipe(
2057 Effect.map((result) => ({ type: "decision", result }) as const),
2058 ),
2059 Fiber.join(safetyRequest).pipe(
2060 Effect.map((event) => ({ type: "approval", event }) as const),
2061 ),
2062 );
2063 assert.equal(safety.type, askRule ? "approval" : "decision");
2064 if (safety.type === "decision") {
2065 assert.equal(safety.result?.behavior, "deny");
2066 if (safety.result?.behavior === "deny") {
2067 assert.include(safety.result.message, reason);
2068 assert.notInclude(safety.result.message, "\u001b[");
2069 }
2070 } else if (
2071 Option.isSome(safety.event) &&
2072 safety.event.value.type === "runtime_request.updated"
2073 ) {
2074 yield* runtime.respondToRuntimeRequest({
2075 requestId: safety.event.value.runtimeRequest.id,
2076 decision: "decline",
2077 });
2078 assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny");
2079 }
2080 yield* Fiber.interrupt(safetyRequest);
2081 }
2082 const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`;
2083 const questionRequestEvent = yield* runtime.events.pipe(
2084 Stream.filter((event) => event.type === "runtime_request.updated"),
2085 Stream.runHead,
2086 Effect.forkScoped,
2087 );
2088 const questionResult = yield* Effect.promise(() =>
2089 canUseTool!(
2090 "AskUserQuestion",
2091 {
2092 questions: [
2093 {
2094 header: "Target",
2095 question: longQuestion,
2096 options: [
2097 { label: "Production", description: "Deploy to production." },
2098 { label: "Staging", description: "Deploy to staging." },
2099 ],
2100 multiSelect: true,
2101 },
2102 ],
2103 },
2104 {
2105 signal: new AbortController().signal,
2106 toolUseID: "tool-question-full-access",
2107 requestId: "request-question-full-access",
2108 },
2109 ),
2110 ).pipe(Effect.forkScoped);
2111 const questionEvent = yield* Fiber.join(questionRequestEvent);
2112 assert.isTrue(Option.isSome(questionEvent));
2113 if (Option.isNone(questionEvent) || questionEvent.value.type !== "runtime_request.updated") {
2114 return;
2115 }
2116 yield* runtime.respondToRuntimeRequest({
2117 requestId: questionEvent.value.runtimeRequest.id,
2118 answers: { [longQuestion]: ["Production", "Staging"] },
2119 });
2120 assert.deepEqual(yield* Fiber.join(questionResult), {
2121 behavior: "allow",
2122 updatedInput: {
2123 questions: [
2124 {
2125 header: "Target",
2126 question: longQuestion,
2127 options: [
2128 { label: "Production", description: "Deploy to production." },
2129 { label: "Staging", description: "Deploy to staging." },
2130 ],
2131 multiSelect: true,
2132 },
2133 ],
2134 answers: { [longQuestion]: "Production, Staging" },
2135 },
2136 toolUseID: "tool-question-full-access",
2137 });
2138 const longPlan = `# Deployment plan\n\n${"Validate every region before promotion.\n".repeat(120)}`;
2139 const proposedPlanEvent = yield* runtime.events.pipe(
2140 Stream.filter((event) => event.type === "plan.updated"),
2141 Stream.runHead,
2142 Effect.forkScoped,
2143 );
2144 const exitPlanResult = yield* Effect.promise(() =>
2145 canUseTool!(
2146 "ExitPlanMode",
2147 { plan: longPlan },
2148 {
2149 signal: new AbortController().signal,
2150 toolUseID: "tool-exit-plan-full-access",
2151 requestId: "request-exit-plan-full-access",
2152 },
2153 ),
2154 );
2155 assert.deepEqual(exitPlanResult, {
2156 behavior: "deny",
2157 message:
2158 "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
2159 toolUseID: "tool-exit-plan-full-access",
2160 });
2161 const planEvent = yield* Fiber.join(proposedPlanEvent);
2162 assert.isTrue(Option.isSome(planEvent));
2163 if (Option.isSome(planEvent) && planEvent.value.type === "plan.updated") {
2164 assert.equal(planEvent.value.plan.kind, "proposed_plan");
2165 if (planEvent.value.plan.kind === "proposed_plan") {
2166 assert.equal(planEvent.value.plan.markdown, longPlan.trim());
2167 }
2168 }
2169 const requestEvent = yield* runtime.events.pipe(
2170 Stream.filter((event) => event.type === "runtime_request.updated"),
2171 Stream.runHead,
2172 Effect.forkScoped,
2173 );
2174 const signal = yield* Effect.abortSignal;
2175 const dialog = yield* Effect.promise(() =>
2176 callback!(
2177 {
2178 dialogKind: "resume_return",
2179 payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 },
2180 },
2181 { signal, requestId: "dialog-resume-1" },
2182 ),
2183 ).pipe(Effect.forkScoped);
2184 const event = yield* Fiber.join(requestEvent);
2185 assert.isTrue(Option.isSome(event));
2186 if (Option.isNone(event) || event.value.type !== "runtime_request.updated") return;
2187 const question = formatClaudeResumeCompactionQuestion({
2188 ageMinutes: 90,
2189 estimatedTokens: 120000,
2190 });
2191 yield* runtime.respondToRuntimeRequest({
2192 requestId: event.value.runtimeRequest.id,
2193 answers: { [question]: "Compact and continue" },
2194 });
2195 assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "compact" });
2196
2197 assert.deepEqual(
2198 yield* Effect.promise(() =>
2199 callback!(
2200 {
2201 dialogKind: "resume_return",
2202 payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 },
2203 },
2204 { signal: AbortSignal.abort(), requestId: "dialog-resume-2" },
2205 ),
2206 ),
2207 { behavior: "cancelled" },
2208 );
2209 }).pipe(
2210 Effect.provide(
2211 Layer.mergeAll(
2212 IdAllocator.layer,
2213 McpProviderSessions.layer,
2214 NodeServices.layer,
2215 NodeCrypto.layer,
2216 ),
2217 ),
2218 ),
2219 );
2220 });
2221
2222 describe("ClaudeAdapterV2 attachments", () => {
2223 it.effect.each([
2224 ...[
2225 "retained-images",
2226 "retained-text",
2227 "same-message-images",
2228 "retained-documents",
2229 "later-images",
2230 "partial-images",
2231 "cancelled-send",
2232 "cancelled-steer",
2233 ].map((budget) => ({
2234 name: budget,
2235 prompt: "Read this PDF.",
2236 expectedText: "Read this PDF.",
2237 command: undefined,
2238 ultrathink: false,
2239 resumed: false,
2240 budget,
2241 })),
2242 {
2243 name: "ordinary text",
2244 prompt: "What’s in this image?",
2245 expectedText: "Ultrathink:\nWhat’s in this image?",
2246 command: undefined,
2247 ultrathink: true,
2248 resumed: false,
2249 budget: "none",
2250 },
2251 {
2252 name: "mid-sentence skill",
2253 prompt: "please $implement fixes\n\nThen report the result",
2254 expectedText: "Ultrathink:\nplease /implement fixes\n\nThen report the result",
2255 command: "/implement fixes\n\nThen report the result",
2256 ultrathink: true,
2257 resumed: false,
2258 budget: "none",
2259 },
2260 {
2261 name: "prompt-leading skill",
2262 prompt: "$implement fixes",
2263 expectedText: "/implement fixes",
2264 command: undefined,
2265 ultrathink: false,
2266 resumed: false,
2267 budget: "none",
2268 },
2269 {
2270 name: "resumed history without persisted counters",
2271 prompt: "Inspect this file",
2272 expectedText: "Ultrathink:\nInspect this file",
2273 command: undefined,
2274 ultrathink: true,
2275 resumed: true,
2276 budget: "none",
2277 },
2278 ])(
2279 "preserves $name with native PDFs, images, and paths on sends and steering",
2280 ({ prompt, expectedText, command, ultrathink, resumed, budget }) =>
2281 Effect.gen(function* () {
2282 const fileSystem = yield* FileSystem.FileSystem;
2283 const idAllocator = yield* IdAllocator.IdAllocatorV2;
2284 const path = yield* Path.Path;
2285 const claudeHome = yield* fileSystem.makeTempDirectoryScoped({
2286 prefix: "t3-claude-v2-skills-home-",
2287 });
2288 yield* fileSystem.makeDirectory(path.join(claudeHome, "skills", "implement"), {
2289 recursive: true,
2290 });
2291 yield* fileSystem.writeFileString(
2292 path.join(claudeHome, "skills", "implement", "SKILL.md"),
2293 "---\ndescription: Implement the requested change\n---\nImplement it.\n",
2294 );
2295 const modelSelection = {
2296 ...CLAUDE_TEST_MODEL_SELECTION,
2297 options: ultrathink ? CLAUDE_TEST_MODEL_SELECTION.options : [],
2298 };
2299 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
2300 prefix: "t3-claude-v2-attachments-",
2301 });
2302 const offeredMessages: Array<SDKUserMessage> = [];
2303 let failOpen = false;
2304 let failOffer = false;
2305 let cancelAfterQueue = false;
2306 const queued = yield* Deferred.make<void>();
2307 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
2308 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
2309 settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome },
2310 environment: {},
2311 attachmentsDir,
2312 fileSystem,
2313 path: yield* Path.Path,
2314 random: yield* SecureRandom.SecureRandom,
2315 idAllocator,
2316 queryRunner: {
2317 allocateSessionId: Effect.succeed("native-thread-claude-attachments"),
2318 open: () =>
2319 Effect.gen(function* () {
2320 if (failOpen) {
2321 failOpen = false;
2322 return yield* new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
2323 method: "open",
2324 cause: "rejected open",
2325 });
2326 }
2327 const messages = yield* Queue.unbounded<SDKMessage>();
2328 return {
2329 messages: Stream.fromQueue(messages),
2330 offer: (message, onQueued) =>
2331 Effect.suspend(() => {
2332 if (failOffer) {
2333 failOffer = false;
2334 return Effect.fail(
2335 new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
2336 method: "offer",
2337 cause: "rejected offer",
2338 }),
2339 );
2340 }
2341 return Effect.sync(() => {
2342 offeredMessages.push(message);
2343 onQueued?.();
2344 }).pipe(
2345 Effect.andThen(() =>
2346 cancelAfterQueue
2347 ? Deferred.succeed(queued, undefined).pipe(Effect.andThen(Effect.never))
2348 : Effect.void,
2349 ),
2350 );
2351 }),
2352 setModel: () => Effect.void,
2353 applyFlagSettings: () => Effect.void,
2354 setPermissionMode: () => Effect.void,
2355 renameSession: () => Effect.void,
2356 backgroundTasks: () => Effect.succeed(false),
2357 mcpServerStatus: Effect.succeed([]),
2358 readMcpResource: () => Effect.die("unexpected MCP resource read"),
2359 callMcpTool: () => Effect.die("unexpected MCP tool call"),
2360 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
2361 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
2362 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
2363 listPermissionRules: Effect.die("unexpected permission rules read"),
2364 stopTask: () => Effect.void,
2365 interrupt: Effect.void,
2366 close: Queue.shutdown(messages),
2367 };
2368 }),
2369 forkSession: () => Effect.die("unused forkSession"),
2370 subagentLaunchToolUseId: () => Effect.succeed(null),
2371 subagentModel: () => Effect.succeed(null),
2372 assertComplete: Effect.void,
2373 },
2374 });
2375 const threadId = ThreadId.make("thread-claude-attachments");
2376 const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments");
2377 const runtime = yield* adapter.openSession({
2378 threadId,
2379 providerSessionId,
2380 modelSelection,
2381 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
2382 });
2383 const providerThread = yield* runtime.ensureThread({
2384 threadId,
2385 modelSelection,
2386 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
2387 });
2388 const attachment = ChatImageAttachment.make({
2389 type: "image",
2390 id: ChatAttachmentId.make(
2391 "thread-claude-attachments-12345678-1234-1234-1234-123456789abc",
2392 ),
2393 name: "diagram.png",
2394 mimeType: "image/png",
2395 sizeBytes: 4,
2396 });
2397 const document = ChatFileAttachment.make({
2398 type: "file",
2399 id: ChatAttachmentId.make(
2400 "thread-claude-attachments-abcdefab-1234-1234-1234-123456789abc",
2401 ),
2402 name: "requirements.pdf",
2403 mimeType: "application/pdf",
2404 sizeBytes: 4,
2405 });
2406 yield* fileSystem.writeFile(
2407 path.join(attachmentsDir, attachmentRelativePath(attachment)!),
2408 Uint8Array.from([1, 2, 3, 4]),
2409 );
2410 const pdfBytes = Buffer.from(
2411 "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF",
2412 );
2413 yield* fileSystem.writeFile(
2414 path.join(attachmentsDir, attachmentRelativePath(document)!),
2415 pdfBytes,
2416 );
2417 const attemptId = RunAttemptId.make("attempt-claude-attachments");
2418 const now = yield* DateTime.now;
2419
2420 const turnInput = {
2421 ...makeClaudeTestTurnInput({
2422 threadId,
2423 providerThread,
2424 now,
2425 attemptId,
2426 modelSelection,
2427 text: prompt,
2428 attachments: resumed ? [attachment] : [attachment, document],
2429 }),
2430 nativeThreadHasTurns: resumed,
2431 };
2432 if (budget === "cancelled-send" || budget === "cancelled-steer") {
2433 const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2434 const pages = Buffer.from(
2435 `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
2436 );
2437 yield* fileSystem.writeFile(
2438 documentPath,
2439 Buffer.concat([
2440 pages,
2441 Buffer.alloc(19 * 1024 * 1024 - pages.length - 5, 32),
2442 Buffer.from("%%EOF"),
2443 ]),
2444 );
2445 const message = { ...turnInput.message, attachments: [document] };
2446 if (budget === "cancelled-steer") {
2447 yield* runtime.startTurn({ ...turnInput, message: { ...message, attachments: [] } });
2448 }
2449 const deliver =
2450 budget === "cancelled-send"
2451 ? runtime.startTurn({ ...turnInput, message })
2452 : runtime.steerTurn({
2453 threadId,
2454 runId: turnInput.runId,
2455 providerThread,
2456 providerTurnId: idAllocator.derive.providerTurn({
2457 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2458 nativeTurnId: `turn:${attemptId}`,
2459 }),
2460 message,
2461 });
2462 cancelAfterQueue = true;
2463 const delivering = yield* deliver.pipe(Effect.forkChild);
2464 yield* Deferred.await(queued);
2465 yield* Fiber.interrupt(delivering);
2466 const delivered = offeredMessages.at(-1)!.message.content;
2467 assert.include(JSON.stringify(delivered), '"type":"document"');
2468 cancelAfterQueue = false;
2469 if (budget === "cancelled-send") {
2470 yield* runtime.interruptTurn({
2471 providerThread,
2472 providerTurnId: idAllocator.derive.providerTurn({
2473 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2474 nativeTurnId: `turn:${attemptId}`,
2475 }),
2476 });
2477 }
2478 yield* deliver;
2479 const retried = offeredMessages.at(-1)!.message.content;
2480 assert.notInclude(JSON.stringify(retried), '"type":"document"');
2481 assert.include(JSON.stringify(retried), JSON.stringify(documentPath).slice(1, -1));
2482 assert.isBelow(Buffer.byteLength(JSON.stringify(offeredMessages)), 32_000_000);
2483 return;
2484 }
2485 if (budget !== "none") {
2486 const providerTurnId = idAllocator.derive.providerTurn({
2487 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2488 nativeTurnId: `turn:${attemptId}`,
2489 });
2490 const imagePath = path.join(attachmentsDir, attachmentRelativePath(attachment)!);
2491 // The on-disk length deliberately disagrees with sizeBytes.
2492 yield* fileSystem.writeFile(imagePath, Buffer.alloc(4 * 1024 * 1024));
2493 if (["later-images", "partial-images"].includes(budget)) {
2494 const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2495 yield* fileSystem.writeFile(
2496 documentPath,
2497 Buffer.concat([
2498 pdfBytes.subarray(0, -5),
2499 Buffer.alloc(
2500 (budget === "later-images" ? 19 : 16) * 1024 * 1024 - pdfBytes.length,
2501 32,
2502 ),
2503 Buffer.from("%%EOF"),
2504 ]),
2505 );
2506 yield* runtime.startTurn({
2507 ...turnInput,
2508 message: { ...turnInput.message, attachments: [document] },
2509 });
2510 assert.include(
2511 JSON.stringify(offeredMessages[0]!.message.content),
2512 '"type":"document"',
2513 );
2514 const message = { ...turnInput.message, attachments: [attachment, attachment] };
2515 yield* runtime.interruptTurn({ providerThread, providerTurnId });
2516 const laterAttemptId = RunAttemptId.make("attempt-claude-attachments-later");
2517 yield* runtime.startTurn({
2518 ...turnInput,
2519 attemptId: laterAttemptId,
2520 providerTurnOrdinal: 2,
2521 nativeThreadHasTurns: true,
2522 message,
2523 });
2524 const sent = offeredMessages.at(-1)!.message.content;
2525 assert.isArray(sent);
2526 assert.lengthOf(
2527 typeof sent === "string" ? [] : sent.filter((block) => block.type === "image"),
2528 budget === "partial-images" ? 1 : 0,
2529 );
2530 assert.include(JSON.stringify(sent), JSON.stringify(imagePath).slice(1, -1));
2531 yield* runtime.steerTurn({
2532 threadId,
2533 runId: RunId.make("run-claude-attachments"),
2534 providerThread,
2535 providerTurnId: idAllocator.derive.providerTurn({
2536 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2537 nativeTurnId: `turn:${laterAttemptId}`,
2538 }),
2539 message,
2540 });
2541 const steered = offeredMessages.at(-1)!.message.content;
2542 assert.isArray(steered);
2543 assert.lengthOf(
2544 typeof steered === "string" ? [] : steered.filter((block) => block.type === "image"),
2545 0,
2546 );
2547 assert.include(JSON.stringify(steered), JSON.stringify(imagePath).slice(1, -1));
2548 assert.isBelow(
2549 Buffer.byteLength(JSON.stringify(offeredMessages.map((message) => message.message))),
2550 32_000_000,
2551 );
2552 return;
2553 }
2554 if (budget === "retained-documents") {
2555 yield* fileSystem.writeFile(
2556 path.join(attachmentsDir, attachmentRelativePath(document)!),
2557 Buffer.concat([
2558 pdfBytes.subarray(0, pdfBytes.length - 5),
2559 Buffer.alloc(10 * 1024 * 1024, 32),
2560 Buffer.from("%%EOF"),
2561 ]),
2562 );
2563 }
2564 yield* runtime.startTurn({
2565 ...turnInput,
2566 message: {
2567 ...turnInput.message,
2568 text: budget === "retained-text" ? "x".repeat(10 * 1024 * 1024) : prompt,
2569 attachments:
2570 budget === "retained-text"
2571 ? []
2572 : budget === "retained-documents"
2573 ? [document]
2574 : [attachment, attachment],
2575 },
2576 });
2577 const largePdf = Buffer.concat([
2578 pdfBytes.subarray(0, pdfBytes.length - 5),
2579 Buffer.alloc(
2580 (budget === "retained-documents" ? 20 : 19) * 1024 * 1024 - pdfBytes.length,
2581 32,
2582 ),
2583 Buffer.from("%%EOF"),
2584 ]);
2585 const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2586 yield* fileSystem.writeFile(documentPath, largePdf);
2587 yield* runtime.steerTurn({
2588 threadId,
2589 runId: RunId.make("run-claude-attachments"),
2590 providerThread,
2591 providerTurnId,
2592 message: {
2593 ...turnInput.message,
2594 attachments:
2595 budget === "same-message-images" ? [document, attachment, attachment] : [document],
2596 },
2597 });
2598 const sent = offeredMessages.at(-1)!.message.content;
2599 assert.isArray(sent);
2600 assert.lengthOf(
2601 typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"),
2602 0,
2603 budget,
2604 );
2605 assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1));
2606 return;
2607 }
2608 if (!resumed) {
2609 const undelivered = Buffer.from(
2610 `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
2611 );
2612 yield* fileSystem.writeFile(
2613 path.join(attachmentsDir, attachmentRelativePath(document)!),
2614 undelivered,
2615 );
2616 failOpen = true;
2617 assert.isTrue(Exit.isFailure(yield* runtime.startTurn(turnInput).pipe(Effect.exit)));
2618 assert.lengthOf(offeredMessages, 0);
2619 yield* fileSystem.writeFile(
2620 path.join(attachmentsDir, attachmentRelativePath(document)!),
2621 pdfBytes,
2622 );
2623 }
2624 yield* runtime.startTurn(turnInput);
2625
2626 const expectedImageBlock = {
2627 type: "image",
2628 source: {
2629 type: "base64",
2630 media_type: "image/png",
2631 data: "AQIDBA==",
2632 },
2633 } as const;
2634 const expectedDocumentBlock = {
2635 type: "document",
2636 source: {
2637 type: "base64",
2638 media_type: "application/pdf",
2639 data: Buffer.from(pdfBytes).toString("base64"),
2640 },
2641 } as const;
2642 const expectedAttachmentPath = path.join(
2643 attachmentsDir,
2644 attachmentRelativePath(attachment)!,
2645 );
2646 const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2647 const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]${resumed ? "" : `\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`}`;
2648 const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes };
2649 const expectedContent = command
2650 ? [
2651 requestBlock,
2652 expectedImageBlock,
2653 ...(!resumed ? [expectedDocumentBlock] : []),
2654 { type: "text" as const, text: command + attachmentNotes },
2655 ]
2656 : [expectedImageBlock, ...(!resumed ? [expectedDocumentBlock] : []), requestBlock];
2657 assert.deepEqual(offeredMessages[0]?.message.content, expectedContent);
2658
2659 const providerTurnId = idAllocator.derive.providerTurn({
2660 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2661 nativeTurnId: `turn:${attemptId}`,
2662 });
2663 yield* runtime.steerTurn({
2664 threadId,
2665 runId: RunId.make("run-claude-attachments"),
2666 providerThread,
2667 providerTurnId,
2668 message: {
2669 createdBy: "user",
2670 creationSource: "web",
2671 messageId: MessageId.make("message-claude-attachments-steer"),
2672 text: prompt,
2673 attachments: resumed ? [attachment] : [attachment, document],
2674 },
2675 });
2676
2677 assert.equal(offeredMessages[1]?.priority, "next");
2678 assert.deepEqual(offeredMessages[1]?.message.content, expectedContent);
2679 const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2680 for (const scenario of [
2681 "pages",
2682 "bytes",
2683 "invalid",
2684 "invalid-page-tree",
2685 "object-stream",
2686 "encrypted",
2687 "cyclic-tree",
2688 "unterminated-string",
2689 "missing-eof",
2690 "escaped-name",
2691 "incremental",
2692 "indirect-count",
2693 "indirect-type",
2694 "indirect-kids",
2695 "indirect-101-pages",
2696 "aggregate-pages",
2697 "retained-pages",
2698 "delivery-failure",
2699 "pasted-text",
2700 "text-only",
2701 ]) {
2702 let attachments: ReadonlyArray<ChatAttachment> = [document];
2703 if (
2704 ["pages", "aggregate-pages", "retained-pages", "delivery-failure"].includes(scenario)
2705 ) {
2706 const pages = scenario === "pages" ? 101 : scenario === "delivery-failure" ? 30 : 60;
2707 const large = Buffer.from(
2708 `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count ${pages} >> endobj\n${Array.from({ length: pages }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
2709 );
2710 yield* fileSystem.writeFile(documentPath, large);
2711 if (scenario === "aggregate-pages") {
2712 const second = {
2713 ...document,
2714 id: ChatAttachmentId.make("second-pdf"),
2715 name: "second.pdf",
2716 };
2717 yield* fileSystem.copyFile(
2718 documentPath,
2719 path.join(attachmentsDir, attachmentRelativePath(second)!),
2720 );
2721 attachments = [document, second];
2722 }
2723 } else if (scenario.startsWith("indirect-")) {
2724 const raw =
2725 scenario === "indirect-count" || scenario === "indirect-101-pages"
2726 ? `%PDF-1.7\n1 0 obj ${scenario === "indirect-count" ? 1 : 101} endobj\n2 0 obj << /Type /Catalog /Pages 3 0 R >> endobj\n3 0 obj << /Type /Pages /Count 1 0 R /Kids [${Array.from({ length: scenario === "indirect-count" ? 1 : 101 }, (_, i) => `${i + 4} 0 R`).join(" ")}] >> endobj\n4 0 obj << /Type /Page /Parent 3 0 R >> endobj\n${scenario === "indirect-count" ? "" : Array.from({ length: 100 }, (_, i) => `${i + 5} 0 obj << /Type 105 0 R /Parent 3 0 R >> endobj`).join("\n")}\n105 0 obj /Page endobj\n%%EOF`
2727 : scenario === "indirect-type"
2728 ? pdfBytes
2729 .toString()
2730 .replace(
2731 "%%EOF",
2732 "4 0 obj << /Type 5 0 R >> endobj\n5 0 obj /Annot endobj\n%%EOF",
2733 )
2734 : pdfBytes
2735 .toString()
2736 .replace("/Kids [3 0 R]", "/Kids 4 0 R")
2737 .replace("%%EOF", "4 0 obj [3 0 R] endobj\n%%EOF");
2738 yield* fileSystem.writeFileString(documentPath, raw);
2739 } else if (scenario === "bytes") {
2740 yield* fileSystem.truncate(documentPath, 20 * 1024 * 1024 + 1);
2741 } else if (scenario === "invalid") {
2742 yield* fileSystem.writeFileString(documentPath, "This is not a PDF");
2743 } else if (scenario === "invalid-page-tree") {
2744 const malformedBytes = Buffer.from(
2745 "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 42 >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF",
2746 );
2747 yield* fileSystem.writeFile(documentPath, malformedBytes);
2748 } else if (["object-stream", "encrypted", "cyclic-tree"].includes(scenario)) {
2749 const suffix =
2750 scenario === "encrypted"
2751 ? "/Encrypt 9 0 R"
2752 : scenario === "cyclic-tree"
2753 ? "/Count 0 /Kids [2 0 R]"
2754 : "/Type /ObjStm /Filter /FlateDecode /Length 1000000000";
2755 yield* fileSystem.writeFile(
2756 documentPath,
2757 Buffer.concat([
2758 pdfBytes.subarray(0, pdfBytes.length - 5),
2759 Buffer.from(`\n4 0 obj << ${suffix} >> stream\nx\nendstream endobj\n%%EOF`),
2760 ]),
2761 );
2762 } else if (
2763 ["unterminated-string", "missing-eof", "escaped-name", "incremental"].includes(scenario)
2764 ) {
2765 const raw = pdfBytes.toString();
2766 yield* fileSystem.writeFileString(
2767 documentPath,
2768 scenario === "missing-eof"
2769 ? raw.slice(0, -5)
2770 : scenario === "escaped-name"
2771 ? raw.replace("/Type /Page ", "/Type /Pa#67e ")
2772 : raw.replace(
2773 "%%EOF",
2774 scenario === "incremental" ? "/Prev 42\n%%EOF" : "(unfinished\n%%EOF",
2775 ),
2776 );
2777 } else if (scenario === "pasted-text") {
2778 yield* fileSystem.writeFile(documentPath, pdfBytes);
2779 attachments = [{ ...document, source: { _tag: "pasted-text" } }];
2780 } else {
2781 attachments = [];
2782 yield* fileSystem.remove(documentPath);
2783 }
2784 const steering = {
2785 threadId,
2786 runId: RunId.make("run-claude-attachments"),
2787 providerThread,
2788 providerTurnId,
2789 message: {
2790 createdBy: "user",
2791 creationSource: "web",
2792 messageId: MessageId.make(`message-${scenario}`),
2793 text: "Continue.",
2794 attachments,
2795 },
2796 } satisfies ProviderAdapter.ProviderAdapterV2SteerInput;
2797 if (scenario === "delivery-failure") {
2798 failOffer = true;
2799 assert.isTrue(Exit.isFailure(yield* runtime.steerTurn(steering).pipe(Effect.exit)));
2800 }
2801 yield* runtime.steerTurn(steering);
2802
2803 const sent = offeredMessages.at(-1)!.message.content;
2804 const documents =
2805 typeof sent === "string" ? [] : sent.filter((block) => block.type === "document");
2806 assert.lengthOf(
2807 documents,
2808 ["aggregate-pages", "delivery-failure"].includes(scenario) ? 1 : 0,
2809 scenario,
2810 );
2811 if (scenario === "text-only")
2812 assert.equal(sent, ultrathink ? "Ultrathink:\nContinue." : "Continue.");
2813 else assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1));
2814 }
2815 }).pipe(
2816 Effect.provide(
2817 Layer.mergeAll(
2818 IdAllocator.layer,
2819 McpProviderSessions.layer,
2820 NodeServices.layer,
2821 NodeCrypto.layer,
2822 ),
2823 ),
2824 ),
2825 );
2826 });
2827
2828 describe("ClaudeAdapterV2 native fork", () => {
2829 it.effect("forks a session from its original directory after the workspace root changes", () =>
2830 Effect.gen(function* () {
2831 const fileSystem = yield* FileSystem.FileSystem;
2832 const idAllocator = yield* IdAllocator.IdAllocatorV2;
2833 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
2834 prefix: "t3-claude-v2-fork-attachments-",
2835 });
2836 const configDir = yield* fileSystem.makeTempDirectoryScoped({
2837 prefix: "t3-claude-root-change-",
2838 });
2839 const sourceSessionId = "11111111-1111-4111-8111-111111111111";
2840 const sourceCursor = "aaaaaaaa-0000-4000-8000-000000000002";
2841 const projectDir = NodePath.join(configDir, "projects", "-old-workspace");
2842 yield* fileSystem.makeDirectory(projectDir, { recursive: true });
2843 const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({
2844 type: parentUuid === null ? "user" : "assistant",
2845 uuid,
2846 parentUuid,
2847 sessionId: sourceSessionId,
2848 cwd: "/old-workspace",
2849 isSidechain: false,
2850 timestamp: "2026-10-01T00:00:00.000Z",
2851 message,
2852 });
2853 yield* fileSystem.writeFileString(
2854 NodePath.join(projectDir, `${sourceSessionId}.jsonl`),
2855 [
2856 entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
2857 entry(sourceCursor, "aaaaaaaa-0000-4000-8000-000000000001", {
2858 role: "assistant",
2859 content: [{ type: "text", text: "inherited answer" }],
2860 }),
2861 ]
2862 .map((line) => JSON.stringify(line))
2863 .join("\n"),
2864 );
2865 const realRunner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.pipe(
2866 Effect.provide(
2867 ClaudeAdapterV2.layerQueryRunner.pipe(
2868 Layer.provide(PortScanner.layerTest),
2869 Layer.provide(
2870 Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, {
2871 native: undefined,
2872 canonical: undefined,
2873 }),
2874 ),
2875 ),
2876 ),
2877 );
2878 const openedQueries: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput> = [];
2879 const forkCalls: Array<ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput> = [];
2880 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
2881 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
2882 settings: DEFAULT_CLAUDE_SETTINGS,
2883 environment: { CLAUDE_CONFIG_DIR: configDir },
2884 attachmentsDir,
2885 fileSystem,
2886 path: yield* Path.Path,
2887 random: yield* SecureRandom.SecureRandom,
2888 idAllocator,
2889 queryRunner: {
2890 allocateSessionId: Effect.succeed(sourceSessionId),
2891 open: (input) =>
2892 Effect.sync(() => {
2893 openedQueries.push(input);
2894 return {
2895 messages: Stream.never,
2896 offer: () => Effect.void,
2897 setModel: () => Effect.void,
2898 applyFlagSettings: () => Effect.void,
2899 setPermissionMode: () => Effect.void,
2900 renameSession: () => Effect.void,
2901 backgroundTasks: () => Effect.succeed(false),
2902 mcpServerStatus: Effect.succeed([]),
2903 readMcpResource: () => Effect.die("unexpected MCP resource read"),
2904 callMcpTool: () => Effect.die("unexpected MCP tool call"),
2905 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
2906 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
2907 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
2908 listPermissionRules: Effect.die("unexpected permission rules read"),
2909 stopTask: () => Effect.void,
2910 interrupt: Effect.void,
2911 close: Effect.void,
2912 };
2913 }),
2914 forkSession: (input) =>
2915 Effect.gen(function* () {
2916 forkCalls.push(input);
2917 return yield* realRunner.forkSession(input);
2918 }),
2919 subagentLaunchToolUseId: () => Effect.succeed(null),
2920 subagentModel: () => Effect.succeed(null),
2921 assertComplete: Effect.void,
2922 },
2923 });
2924 const providerSessionId = ProviderSessionId.make("provider-session-claude-fork");
2925 const sourceThreadId = ThreadId.make("thread-claude-fork-source");
2926 const targetThreadId = ThreadId.make("thread-claude-fork-target");
2927 const runtime = yield* adapter.openSession({
2928 threadId: sourceThreadId,
2929 providerSessionId,
2930 modelSelection: {
2931 instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2932 model: "claude-sonnet-4-6",
2933 },
2934 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2935 runtimeMode: "full-access",
2936 interactionMode: "default",
2937 cwd: "/workspace",
2938 }),
2939 });
2940 const sourceProviderThread = yield* runtime.ensureThread({
2941 threadId: sourceThreadId,
2942 modelSelection: {
2943 instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2944 model: "claude-sonnet-4-6",
2945 },
2946 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2947 runtimeMode: "full-access",
2948 interactionMode: "default",
2949 cwd: "/workspace",
2950 }),
2951 });
2952 const now = yield* DateTime.now;
2953 const providerTurnId = ProviderTurnId.make("provider-turn-claude-source");
2954 const forkedProviderThread = yield* runtime.forkThread({
2955 sourceProviderThread,
2956 sourceProviderTurns: [
2957 {
2958 id: providerTurnId,
2959 providerThreadId: sourceProviderThread.id,
2960 nodeId: NodeId.make("node-claude-source"),
2961 runAttemptId: RunAttemptId.make("run-attempt-claude-source"),
2962 nativeTurnRef: {
2963 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2964 nativeId: sourceCursor,
2965 strength: "weak",
2966 },
2967 ordinal: 1,
2968 status: "completed",
2969 startedAt: now,
2970 completedAt: now,
2971 },
2972 ],
2973 providerTurnId,
2974 targetThreadId,
2975 });
2976
2977 assert.deepEqual(forkCalls, [
2978 {
2979 sessionId: sourceSessionId,
2980 options: {
2981 upToMessageId: sourceCursor,
2982 },
2983 environment: { CLAUDE_CONFIG_DIR: configDir },
2984 threadId: targetThreadId,
2985 providerSessionId,
2986 },
2987 ]);
2988 const forkedSessionId = forkedProviderThread.nativeThreadRef?.nativeId;
2989 assert.isString(forkedSessionId);
2990 assert.notEqual(forkedSessionId, sourceSessionId);
2991 const forkedTranscript = yield* fileSystem.readFileString(
2992 NodePath.join(projectDir, `${forkedSessionId}.jsonl`),
2993 );
2994 assert.include(forkedTranscript, "inherited answer");
2995 assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id);
2996 assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId);
2997
2998 yield* runtime.startTurn({
2999 appThread: {
3000 createdBy: "user",
3001 creationSource: "web",
3002 id: targetThreadId,
3003 projectId: ProjectId.make("project-claude-fork-target"),
3004 title: "Claude fork target",
3005 providerInstanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
3006 modelSelection: {
3007 instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
3008 model: "claude-sonnet-4-6",
3009 },
3010 runtimeMode: "full-access",
3011 interactionMode: "default",
3012 branch: null,
3013 worktreePath: null,
3014 activeProviderThreadId: forkedProviderThread.id,
3015 lineage: {
3016 parentThreadId: sourceThreadId,
3017 relationshipToParent: "fork",
3018 rootThreadId: sourceThreadId,
3019 },
3020 forkedFrom: null,
3021 createdAt: now,
3022 updatedAt: now,
3023 archivedAt: null,
3024 settledOverride: null,
3025 settledAt: null,
3026 lastVisitedAt: null,
3027 deletedAt: null,
3028 },
3029 threadId: targetThreadId,
3030 runId: RunId.make("run-claude-fork-target"),
3031 runOrdinal: 1,
3032 providerTurnOrdinal: 1,
3033 attemptId: RunAttemptId.make("run-attempt-claude-fork-target"),
3034 rootNodeId: NodeId.make("node-claude-fork-target-root"),
3035 providerThread: forkedProviderThread,
3036 message: {
3037 createdBy: "user",
3038 creationSource: "web",
3039 messageId: MessageId.make("message-claude-fork-target"),
3040 text: "Respond with fork ok",
3041 attachments: [],
3042 },
3043 modelSelection: {
3044 instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
3045 model: "claude-sonnet-4-6",
3046 },
3047 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
3048 runtimeMode: "full-access",
3049 interactionMode: "default",
3050 cwd: "/workspace",
3051 }),
3052 });
3053
3054 assert.equal(openedQueries[0]?.options.resume, forkedSessionId);
3055 assert.equal(openedQueries[0]?.options.sessionId, undefined);
3056 assert.equal(openedQueries[0]?.options.cwd, NodePath.resolve("/workspace"));
3057 }).pipe(
3058 Effect.provide(
3059 Layer.mergeAll(
3060 IdAllocator.layer,
3061 McpProviderSessions.layer,
3062 NodeServices.layer,
3063 NodeCrypto.layer,
3064 ),
3065 ),
3066 ),
3067 );
3068 });
3069
3070 function makeFakeClaudeCli(answerSetServers = true) {
3071 const spawns: Array<SpawnOptions> = [];
3072 const controlRequests: Array<object> = [];
3073 const stdins: Array<NodeStream.PassThrough> = [];
3074 const spawn = (options: SpawnOptions): SpawnedProcess => {
3075 spawns.push(options);
3076 const stdin = new NodeStream.PassThrough();
3077 const stdout = new NodeStream.PassThrough();
3078 stdins.push(stdin);
3079 const child = Object.assign(new NodeEvents.EventEmitter(), {
3080 stdin,
3081 stdout,
3082 killed: false,
3083 exitCode: null as number | null,
3084 kill: () => {
3085 stdout.end();
3086 child.emit("exit", null, "SIGTERM");
3087 return true;
3088 },
3089 });
3090 let pending = "";
3091 stdin.on("data", (chunk: Buffer) => {
3092 pending += chunk.toString("utf8");
3093 for (let end = pending.indexOf("\n"); end >= 0; end = pending.indexOf("\n")) {
3094 const frame = JSON.parse(pending.slice(0, end));
3095 pending = pending.slice(end + 1);
3096 if (frame.type !== "control_request") continue;
3097 controlRequests.push(frame.request);
3098 const setServers = frame.request.subtype === "mcp_set_servers";
3099 if (setServers && !answerSetServers) continue;
3100 const response = {
3101 subtype: "success",
3102 request_id: frame.request_id,
3103 response: setServers ? { added: [], removed: [], errors: {} } : {},
3104 };
3105 stdout.write(`${JSON.stringify({ type: "control_response", response })}\n`);
3106 }
3107 });
3108 stdin.on("end", () => {
3109 stdout.end();
3110 child.emit("exit", 0, null);
3111 });
3112 return child;
3113 };
3114 const closed = () => stdins.length > 0 && stdins.every((stdin) => stdin.writableEnded);
3115 return { spawn, spawns, controlRequests, closed };
3116 }
3117
3118 describe("ClaudeAdapterV2 MCP credential channel", () => {
3119 const t3McpServer = {
3120 type: "http" as const,
3121 url: "http://127.0.0.1:43123/mcp",
3122 headers: { Authorization: "Bearer dummy-mcp-credential" },
3123 };
3124 const openWith = (
3125 cli: ReturnType<typeof makeFakeClaudeCli>,
3126 native?: ProviderEventLoggers.EventNdjsonLogger,
3127 ) =>
3128 Effect.gen(function* () {
3129 const runner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner;
3130 return yield* runner.open({
3131 threadId: ThreadId.make("thread-claude-mcp-channel"),
3132 providerSessionId: ProviderSessionId.make("provider-session-claude-mcp-channel"),
3133 options: {
3134 ...ClaudeAdapterV2.makeClaudeQueryOptions({
3135 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
3136 nativeThreadId: "native-thread-claude-mcp-channel",
3137 title: "Existing T3 title",
3138 resume: false,
3139 cwd: null,
3140 environment: { PATH: "/usr/bin" },
3141 mcpServers: { "t3-code": t3McpServer },
3142 }),
3143 pathToClaudeCodeExecutable: "/opt/claude/cli.js",
3144 spawnClaudeCodeProcess: cli.spawn,
3145 },
3146 });
3147 }).pipe(
3148 Effect.provide(ClaudeAdapterV2.layerQueryRunner.pipe(Layer.provide(PortScanner.layerTest))),
3149 Effect.provideService(ProviderEventLoggers.ProviderEventLoggers, {
3150 ...ProviderEventLoggers.NoOpProviderEventLoggers,
3151 native,
3152 }),
3153 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
3154 );
3155
3156 it.effect("commits queued delivery before interruptible protocol logging", () =>
3157 Effect.gen(function* () {
3158 const logging = yield* Deferred.make<void>();
3159 let committed = false;
3160 const cli = makeFakeClaudeCli();
3161 const session = yield* openWith(cli, {
3162 filePath: "/tmp/claude-queued-delivery.log",
3163 write: () =>
3164 committed
3165 ? Deferred.succeed(logging, undefined).pipe(Effect.andThen(Effect.never))
3166 : Effect.void,
3167 close: () => Effect.void,
3168 });
3169 const offering = yield* session
3170 .offer(ClaudeAdapterV2.makeClaudeUserMessage({ text: "Inspect the attachment." }), () => {
3171 committed = true;
3172 })
3173 .pipe(Effect.forkChild);
3174 yield* Deferred.await(logging);
3175 yield* Fiber.interrupt(offering);
3176 assert.isTrue(committed);
3177 committed = false;
3178 yield* session.close;
3179 }),
3180 );
3181
3182 it.effect("sends MCP servers over stdin, not argv or the environment", () =>
3183 Effect.gen(function* () {
3184 const cli = makeFakeClaudeCli();
3185 const session = yield* openWith(cli);
3186 yield* session.close;
3187
3188 assert.deepInclude(cli.controlRequests, {
3189 subtype: "mcp_set_servers",
3190 servers: { "t3-code": t3McpServer },
3191 });
3192 assert.deepInclude(
3193 cli.controlRequests.find((request) => Reflect.get(request, "subtype") === "initialize"),
3194 { title: "Existing T3 title" },
3195 );
3196 const spawned = JSON.stringify(cli.spawns);
3197 assert.notInclude(spawned, "--title");
3198 assert.notInclude(spawned, "--mcp-config");
3199 assert.notInclude(spawned, "dummy-mcp-credential");
3200 }),
3201 );
3202 });
3203
3204 describe("ClaudeAdapterV2 native session identity", () => {
3205 const openTurnWithOrdinal = (
3206 providerTurnOrdinal: number,
3207 nativeThreadHasTurns?: boolean,
3208 importedNativeThreadId?: string,
3209 ) =>
3210 Effect.scoped(
3211 Effect.gen(function* () {
3212 const fileSystem = yield* FileSystem.FileSystem;
3213 const idAllocator = yield* IdAllocator.IdAllocatorV2;
3214 const path = yield* Path.Path;
3215 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
3216 prefix: "t3-claude-v2-session-identity-",
3217 });
3218 if (importedNativeThreadId !== undefined) {
3219 // An unreadable copy in another project must not hide the readable one.
3220 yield* fileSystem.makeDirectory(
3221 path.join(attachmentsDir, "projects", "-other", `${importedNativeThreadId}.jsonl`),
3222 { recursive: true },
3223 );
3224 const projectDir = path.join(attachmentsDir, "projects", "-workspace");
3225 yield* fileSystem.makeDirectory(projectDir, { recursive: true });
3226 yield* fileSystem.writeFileString(
3227 path.join(projectDir, `${importedNativeThreadId}.jsonl`),
3228 `{"type":"user","message":{"role":"user","content":"hello"},"sessionId":"${importedNativeThreadId}"}\n`,
3229 );
3230 }
3231 const openedQueries: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput> = [];
3232 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
3233 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
3234 settings: DEFAULT_CLAUDE_SETTINGS,
3235 environment: { CLAUDE_CONFIG_DIR: attachmentsDir },
3236 attachmentsDir,
3237 fileSystem,
3238 path,
3239 random: yield* SecureRandom.SecureRandom,
3240 idAllocator,
3241 queryRunner: {
3242 allocateSessionId: Effect.succeed("native-session-identity"),
3243 open: (input) =>
3244 Effect.sync(() => {
3245 openedQueries.push(input);
3246 return {
3247 messages: Stream.never,
3248 offer: () => Effect.void,
3249 setModel: () => Effect.void,
3250 applyFlagSettings: () => Effect.void,
3251 setPermissionMode: () => Effect.void,
3252 renameSession: () => Effect.void,
3253 backgroundTasks: () => Effect.succeed(false),
3254 mcpServerStatus: Effect.succeed([]),
3255 readMcpResource: () => Effect.die("unexpected MCP resource read"),
3256 callMcpTool: () => Effect.die("unexpected MCP tool call"),
3257 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
3258 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
3259 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
3260 listPermissionRules: Effect.die("unexpected permission rules read"),
3261 stopTask: () => Effect.void,
3262 interrupt: Effect.void,
3263 close: Effect.void,
3264 };
3265 }),
3266 forkSession: () => Effect.die("unused forkSession"),
3267 subagentLaunchToolUseId: () => Effect.succeed(null),
3268 subagentModel: () => Effect.succeed(null),
3269 assertComplete: Effect.void,
3270 },
3271 });
3272 const threadId = ThreadId.make("thread-claude-session-identity");
3273 const providerSessionId = ProviderSessionId.make("provider-session-claude-identity");
3274 const runtime = yield* adapter.openSession({
3275 threadId,
3276 providerSessionId,
3277 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
3278 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
3279 });
3280 const now = yield* DateTime.now;
3281 // Mirrors the provider thread a session import records: a strong native
3282 // ref with no conversation head and no provider turns.
3283 const providerThread =
3284 importedNativeThreadId === undefined
3285 ? yield* runtime.ensureThread({
3286 threadId,
3287 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
3288 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
3289 })
3290 : yield* runtime.resumeThread({
3291 threadId,
3292 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
3293 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
3294 providerThread: {
3295 id: idAllocator.derive.providerThread({
3296 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
3297 providerInstanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
3298 nativeThreadId: importedNativeThreadId,
3299 }),
3300 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
3301 providerInstanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
3302 providerSessionId: null,
3303 appThreadId: threadId,
3304 ownerNodeId: null,
3305 nativeThreadRef: {
3306 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
3307 nativeId: importedNativeThreadId,
3308 strength: "strong",
3309 },
3310 nativeConversationHeadRef: null,
3311 status: "not_loaded",
3312 firstRunOrdinal: null,
3313 lastRunOrdinal: null,
3314 handoffIds: [],
3315 forkedFrom: null,
3316 contextUsage: null,
3317 nativeMetadata: null,
3318 goal: null,
3319 createdAt: now,
3320 updatedAt: now,
3321 },
3322 });
3323 yield* runtime.startTurn(
3324 makeClaudeTestTurnInput({
3325 threadId,
3326 providerThread,
3327 now,
3328 attemptId: RunAttemptId.make("run-attempt-claude-session-identity"),
3329 text: "Respond with identity ok",
3330 attachments: [],
3331 providerTurnOrdinal,
3332 ...(nativeThreadHasTurns === undefined ? {} : { nativeThreadHasTurns }),
3333 }),
3334 );
3335 return openedQueries;
3336 }).pipe(
3337 Effect.provide(
3338 Layer.mergeAll(
3339 IdAllocator.layer,
3340 McpProviderSessions.layer,
3341 NodeServices.layer,
3342 NodeCrypto.layer,
3343 ),
3344 ),
3345 ),
3346 );
3347
3348 it.effect(
3349 "resumes the native session on a fresh session instance when prior provider turns exist",
3350 () =>
3351 Effect.gen(function* () {
3352 const openedQueries = yield* openTurnWithOrdinal(2);
3353 assert.equal(openedQueries.length, 1);
3354 assert.equal(openedQueries[0]?.options.resume, "native-session-identity");
3355 assert.equal(openedQueries[0]?.options.sessionId, undefined);
3356 assert.equal(openedQueries[0]?.options.title, "Claude attachment test");
3357 }),
3358 );
3359
3360 it.effect("creates a fresh native session despite earlier provider-thread turns", () =>
3361 Effect.gen(function* () {
3362 const openedQueries = yield* openTurnWithOrdinal(4, false);
3363 assert.equal(openedQueries[0]?.options.sessionId, "native-session-identity");
3364 assert.equal(openedQueries[0]?.options.resume, undefined);
3365 assert.equal(openedQueries[0]?.options.title, "Claude attachment test");
3366 }),
3367 );
3368
3369 it.effect("resumes an imported native session on its first T3 turn", () =>
3370 Effect.gen(function* () {
3371 const openedQueries = yield* openTurnWithOrdinal(1, false, "imported-native-session");
3372 assert.equal(openedQueries.length, 1);
3373 assert.equal(openedQueries[0]?.options.resume, "imported-native-session");
3374 assert.equal(openedQueries[0]?.options.sessionId, undefined);
3375 }),
3376 );
3377 });
3378
3379 const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
3380 const providerThreadJson = Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ProviderThread));
3381 const encodeProviderThreadJson = Schema.encodeEffect(providerThreadJson);
3382 const decodeProviderThreadJson = Schema.decodeUnknownEffect(providerThreadJson);
3383
3384 describe("ClaudeAdapterV2 background wake turns", () => {
3385 const WAKE_NATIVE_SESSION = "native-thread-claude-wake";
3386 const WAKE_TASK_ID = "bdqirlcyw";
3387 const WAKE_TOOL_USE_ID = "toolu_01Rs6JNNf5SqHRxpq5DeJHrW";
3388 const WAKE_TASK_DESCRIPTION = "Background sleep test";
3389 const WAKE_SUMMARY = 'Background command "Background sleep test" completed (exit code 0)';
3390 const WAKE_ASSISTANT_TEXT = "WAKE_DONE";
3391 const WAKE_RESULT_TEXT = "WAKE_DONE";
3392
3393 function claudeSdkFrame(frame: unknown): SDKMessage {
3394 if (
3395 typeof frame !== "object" ||
3396 frame === null ||
3397 typeof Reflect.get(frame, "type") !== "string"
3398 ) {
3399 throw new Error("Frame is not a Claude Agent SDK message.");
3400 }
3401 return frame as SDKMessage;
3402 }
3403
3404 const wakeTaskStarted = claudeSdkFrame({
3405 type: "system",
3406 subtype: "task_started",
3407 task_id: WAKE_TASK_ID,
3408 tool_use_id: WAKE_TOOL_USE_ID,
3409 description: WAKE_TASK_DESCRIPTION,
3410 is_backgrounded: true,
3411 task_type: "local_bash",
3412 uuid: "00000000-0000-4000-8000-000000000101",
3413 session_id: WAKE_NATIVE_SESSION,
3414 });
3415 const makeAssistantTextFrame = (input: {
3416 readonly uuid: string;
3417 readonly text: string;
3418 readonly model?: string;
3419 }) =>
3420 claudeSdkFrame({
3421 type: "assistant",
3422 message: {
3423 model: input.model ?? "claude-sonnet-4-6",
3424 id: `msg_${input.uuid}`,
3425 type: "message",
3426 role: "assistant",
3427 content: [{ type: "text", text: input.text }],
3428 stop_reason: null,
3429 stop_sequence: null,
3430 usage: {
3431 input_tokens: 1,
3432 output_tokens: 1,
3433 cache_creation_input_tokens: 0,
3434 cache_read_input_tokens: 0,
3435 },
3436 },
3437 parent_tool_use_id: null,
3438 uuid: input.uuid,
3439 session_id: WAKE_NATIVE_SESSION,
3440 });
3441 const makeAssistantErrorFrame = (input: {
3442 readonly uuid: string;
3443 readonly error:
3444 | "authentication_failed"
3445 | "invalid_request"
3446 | "rate_limit"
3447 | "server_error"
3448 | undefined;
3449 readonly text?: string;
3450 readonly parentToolUseId?: string | null;
3451 readonly apiErrorParams?: unknown;
3452 }) =>
3453 claudeSdkFrame({
3454 type: "assistant",
3455 message: {
3456 model: "claude-sonnet-4-6",
3457 id: `msg_${input.uuid}`,
3458 type: "message",
3459 role: "assistant",
3460 content: [{ type: "text", text: input.text ?? "Claude could not complete this request." }],
3461 stop_reason: null,
3462 stop_sequence: null,
3463 usage: {
3464 input_tokens: 1,
3465 output_tokens: 1,
3466 cache_creation_input_tokens: 0,
3467 cache_read_input_tokens: 0,
3468 },
3469 },
3470 parent_tool_use_id: input.parentToolUseId ?? null,
3471 ...(input.error === undefined ? {} : { error: input.error }),
3472 ...(input.apiErrorParams === undefined ? {} : { api_error_params: input.apiErrorParams }),
3473 uuid: input.uuid,
3474 session_id: WAKE_NATIVE_SESSION,
3475 });
3476 const makeResultFrame = (input: {
3477 readonly uuid: string;
3478 readonly result: string;
3479 readonly numTurns?: number;
3480 readonly origin?: { readonly kind: "task-notification" };
3481 readonly subtype?: string;
3482 readonly isError?: boolean;
3483 readonly errors?: ReadonlyArray<string>;
3484 readonly apiErrorStatus?: number;
3485 // null omits the field, as the CLI does on a zero-turn result.
3486 readonly terminalReason?: SDKResultMessage["terminal_reason"] | null;
3487 readonly usage?: {
3488 readonly input_tokens: number;
3489 readonly output_tokens: number;
3490 readonly cache_creation_input_tokens: number;
3491 readonly cache_read_input_tokens: number;
3492 };
3493 readonly modelUsage?: SDKResultMessage["modelUsage"];
3494 }) =>
3495 claudeSdkFrame({
3496 type: "result",
3497 subtype: input.subtype ?? "success",
3498 duration_ms: 10,
3499 duration_api_ms: 10,
3500 is_error: input.isError ?? false,
3501 num_turns: input.numTurns ?? 1,
3502 result: input.result,
3503 stop_reason: "end_turn",
3504 total_cost_usd: 0,
3505 usage: input.usage ?? {
3506 input_tokens: 1,
3507 output_tokens: 1,
3508 cache_creation_input_tokens: 0,
3509 cache_read_input_tokens: 0,
3510 },
3511 modelUsage: input.modelUsage ?? {},
3512 permission_denials: [],
3513 uuid: input.uuid,
3514 session_id: WAKE_NATIVE_SESSION,
3515 ...(input.origin === undefined ? {} : { origin: input.origin }),
3516 ...(input.errors === undefined ? {} : { errors: input.errors }),
3517 ...(input.apiErrorStatus === undefined ? {} : { api_error_status: input.apiErrorStatus }),
3518 ...(input.terminalReason === null
3519 ? {}
3520 : { terminal_reason: input.terminalReason ?? "completed" }),
3521 });
3522 const turnOneResult = makeResultFrame({
3523 uuid: "00000000-0000-4000-8000-000000000102",
3524 result: "Kicked off the build in the background.",
3525 });
3526 const wakeNotification = claudeSdkFrame({
3527 type: "system",
3528 subtype: "task_notification",
3529 task_id: WAKE_TASK_ID,
3530 tool_use_id: WAKE_TOOL_USE_ID,
3531 status: "completed",
3532 output_file: `/tmp/claude-replay/tasks/${WAKE_TASK_ID}.output`,
3533 summary: WAKE_SUMMARY,
3534 uuid: "00000000-0000-4000-8000-000000000103",
3535 session_id: WAKE_NATIVE_SESSION,
3536 });
3537 const wakeAssistant = makeAssistantTextFrame({
3538 uuid: "00000000-0000-4000-8000-000000000107",
3539 text: WAKE_ASSISTANT_TEXT,
3540 });
3541 const wakeTurnInit = claudeSdkFrame({
3542 type: "system",
3543 subtype: "init",
3544 uuid: "00000000-0000-4000-8000-000000000110",
3545 session_id: WAKE_NATIVE_SESSION,
3546 });
3547 const wakeResult = makeResultFrame({
3548 uuid: "00000000-0000-4000-8000-000000000104",
3549 result: WAKE_RESULT_TEXT,
3550 origin: { kind: "task-notification" },
3551 });
3552 const STALE_TASK_NOTIFICATION_RESULT_TEXT =
3553 "Stale task-notification origin text that must not appear.";
3554 const staleTaskNotificationResult = makeResultFrame({
3555 uuid: "00000000-0000-4000-8000-000000000106",
3556 result: STALE_TASK_NOTIFICATION_RESULT_TEXT,
3557 numTurns: 0,
3558 origin: { kind: "task-notification" },
3559 terminalReason: null,
3560 });
3561
3562 // Harnesses notify after every recorded event, continuation, or prompt, so a
3563 // wait re-checks exactly when the state it reads changes. Subscribing before
3564 // the first check means a change that lands in between is not lost.
3565 const makeChangeSignal = Effect.gen(function* () {
3566 const changes = yield* PubSub.unbounded<void>();
3567 const until = (predicate: () => boolean): Effect.Effect<void> =>
3568 Effect.scoped(
3569 Effect.gen(function* () {
3570 const subscription = yield* PubSub.subscribe(changes);
3571 while (!predicate()) yield* PubSub.take(subscription);
3572 }),
3573 );
3574 return { notify: PubSub.publish(changes, undefined), until };
3575 });
3576
3577 // Fixed quiet windows for asserting that nothing happens after input the
3578 // harness cannot observe being handled (a shut-down query, a replaced process).
3579 const yieldTicks = (ticks: number): Effect.Effect<void> =>
3580 Effect.gen(function* () {
3581 for (let tick = 0; tick < ticks; tick++) yield* Effect.yieldNow;
3582 });
3583
3584 const makeWakeHarnessWithOptions = (options?: {
3585 readonly close?: (sdkMessages: Queue.Queue<SDKMessage>) => Effect.Effect<void>;
3586 readonly interrupt?: Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
3587 readonly setPermissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setPermissionMode"];
3588 readonly setModel?: (
3589 model: string,
3590 offerAndWait: (message: SDKMessage) => Effect.Effect<void>,
3591 ) => Effect.Effect<void>;
3592 readonly renameSession?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["renameSession"];
3593 readonly applyFlagSettings?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"];
3594 readonly stopTask?: (
3595 taskId: string,
3596 ) => Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
3597 readonly backgroundTasks?: (
3598 toolUseId: string,
3599 ) => Effect.Effect<boolean, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
3600 readonly mcp?: Pick<
3601 ClaudeAdapterV2.ClaudeAgentSdkQuerySession,
3602 "mcpServerStatus" | "readMcpResource" | "callMcpTool"
3603 > &
3604 Partial<Pick<ClaudeAdapterV2.ClaudeAgentSdkQuerySession, "listPermissionRules">>;
3605 readonly environment?: NodeJS.ProcessEnv;
3606 readonly onSessionInit?: (cwd: string) => Effect.Effect<void>;
3607 readonly subagentLaunchToolUseId?: string;
3608 readonly subagentModel?: string;
3609 readonly nativeSessionId?: string;
3610 readonly settings?: ClaudeSettings;
3611 readonly modelCatalog?: Effect.Effect<ClaudeModelCatalog>;
3612 readonly freshQueueOnReopen?: boolean;
3613 readonly forkSession?: ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerShape["forkSession"];
3614 readonly allocateSessionId?: Effect.Effect<string>;
3615 readonly offer?: (message: SDKUserMessage) => Effect.Effect<void>;
3616 readonly promptSuggestions?: boolean;
3617 readonly routeModelCatalog?: ClaudeAdapterV2.ClaudeAdapterV2Options["routeModelCatalog"];
3618 }) =>
3619 Effect.gen(function* () {
3620 const fileSystem = yield* FileSystem.FileSystem;
3621 const idAllocator = yield* IdAllocator.IdAllocatorV2;
3622 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
3623 prefix: "t3-claude-v2-wake-",
3624 });
3625 const sdkMessages = yield* Queue.unbounded<SDKMessage>();
3626 const processQueues: Array<Queue.Queue<SDKMessage>> = [];
3627 const processedMessages = new WeakMap<SDKMessage, Deferred.Deferred<void>>();
3628 const offerAndWait = Effect.fnUntraced(function* (
3629 message: SDKMessage,
3630 offered?: Deferred.Deferred<void>,
3631 ) {
3632 const processed = yield* Deferred.make<void>();
3633 processedMessages.set(message, processed);
3634 yield* Queue.offer(processQueues.at(-1) ?? sdkMessages, message);
3635 if (offered !== undefined) yield* Deferred.succeed(offered, undefined);
3636 yield* Deferred.await(processed);
3637 });
3638 const changes = yield* makeChangeSignal;
3639 const offeredMessages: Array<SDKUserMessage> = [];
3640 const permissionModeChanges: Array<string> = [];
3641 const renameCalls: Array<string> = [];
3642 const liveSelectionChanges: Array<unknown> = [];
3643 const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
3644 [];
3645 const continuationReceipts =
3646 yield* Queue.unbounded<ProviderContinuationRequests.ProviderContinuationRequest>();
3647 const terminalReceipts =
3648 yield* Queue.unbounded<
3649 Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }>
3650 >();
3651 const subagentReceipts =
3652 yield* Queue.unbounded<
3653 Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "subagent.updated" }>
3654 >();
3655 const systemNoticeReceipts =
3656 yield* Queue.unbounded<
3657 Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn_item.updated" }>
3658 >();
3659 const runtimeRequestReceipts =
3660 yield* Queue.unbounded<
3661 Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "runtime_request.updated" }>
3662 >();
3663 const planReceipts =
3664 yield* Queue.unbounded<
3665 Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "plan.updated" }>
3666 >();
3667 const providerThreadReceipts =
3668 yield* Queue.unbounded<
3669 Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "provider_thread.updated" }>
3670 >();
3671 let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
3672 const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
3673 instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
3674 settings: options?.settings ?? DEFAULT_CLAUDE_SETTINGS,
3675 ...(options?.modelCatalog === undefined ? {} : { modelCatalog: options.modelCatalog }),
3676 environment: options?.environment ?? {},
3677 attachmentsDir,
3678 fileSystem,
3679 path: yield* Path.Path,
3680 random: yield* SecureRandom.SecureRandom,
3681 idAllocator,
3682 ...(options?.onSessionInit ? { onSessionInit: options.onSessionInit } : {}),
3683 ...(options?.routeModelCatalog ? { routeModelCatalog: options.routeModelCatalog } : {}),
3684 continuationRequests: {
3685 offer: (request) =>
3686 Effect.sync(() => {
3687 continuationRequests.push(request);
3688 }).pipe(
3689 Effect.andThen(Queue.offer(continuationReceipts, request)),
3690 Effect.andThen(changes.notify),
3691 ),
3692 },
3693 queryRunner: {
3694 allocateSessionId:
3695 options?.allocateSessionId ??
3696 Effect.succeed(options?.nativeSessionId ?? WAKE_NATIVE_SESSION),
3697 open: (input) =>
3698 Effect.gen(function* () {
3699 openedOptions = input.options;
3700 const processMessages =
3701 options?.freshQueueOnReopen === true && processQueues.length > 0
3702 ? yield* Queue.unbounded<SDKMessage>()
3703 : sdkMessages;
3704 const messages = Stream.fromQueue(processMessages).pipe(
3705 Stream.flatMap((message) =>
3706 Stream.make(message).pipe(
3707 Stream.concat(
3708 Stream.fromEffect(
3709 Effect.suspend(() => {
3710 const processed = processedMessages.get(message);
3711 return processed === undefined
3712 ? Effect.void
3713 : Deferred.succeed(processed, undefined);
3714 }),
3715 ).pipe(Stream.drain),
3716 ),
3717 ),
3718 ),
3719 );
3720 if (options?.freshQueueOnReopen === true && processQueues.length > 0) {
3721 processQueues.push(processMessages);
3722 return {
3723 messages,
3724 offer: (message: SDKUserMessage) =>
3725 Effect.sync(() => {
3726 offeredMessages.push(message);
3727 }).pipe(Effect.andThen(changes.notify)),
3728 setModel: () => Effect.void,
3729 applyFlagSettings: () => Effect.void,
3730 setPermissionMode: (mode) =>
3731 Effect.sync(() => {
3732 permissionModeChanges.push(mode);
3733 }).pipe(
3734 Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void),
3735 ),
3736 renameSession: (title) =>
3737 Effect.sync(() => {
3738 renameCalls.push(title);
3739 }).pipe(Effect.andThen(() => options?.renameSession?.(title) ?? Effect.void)),
3740 backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
3741 mcpServerStatus: Effect.succeed([]),
3742 readMcpResource: () => Effect.die("unexpected MCP resource read"),
3743 callMcpTool: () => Effect.die("unexpected MCP tool call"),
3744 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
3745 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
3746 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
3747 listPermissionRules: Effect.die("unexpected permission rules read"),
3748 stopTask: options?.stopTask ?? (() => Effect.void),
3749 interrupt: Effect.void,
3750 close: Queue.shutdown(processMessages),
3751 };
3752 }
3753 processQueues.push(sdkMessages);
3754 return {
3755 messages,
3756 offer: (message) =>
3757 Effect.sync(() => {
3758 offeredMessages.push(message);
3759 }).pipe(
3760 Effect.andThen(changes.notify),
3761 Effect.andThen(options?.offer?.(message) ?? Effect.void),
3762 ),
3763 setModel: (model) =>
3764 Effect.sync(() => {
3765 liveSelectionChanges.push({ model });
3766 }).pipe(
3767 Effect.andThen(() => options?.setModel?.(model, offerAndWait) ?? Effect.void),
3768 ),
3769 applyFlagSettings: (settings) =>
3770 Effect.sync(() => {
3771 liveSelectionChanges.push(settings);
3772 }).pipe(
3773 Effect.andThen(() => options?.applyFlagSettings?.(settings) ?? Effect.void),
3774 ),
3775 setPermissionMode: (mode) =>
3776 Effect.sync(() => {
3777 permissionModeChanges.push(mode);
3778 }).pipe(Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void)),
3779 renameSession: (title) =>
3780 Effect.sync(() => {
3781 renameCalls.push(title);
3782 }).pipe(Effect.andThen(() => options?.renameSession?.(title) ?? Effect.void)),
3783 backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
3784 mcpServerStatus: options?.mcp?.mcpServerStatus ?? Effect.succeed([]),
3785 readMcpResource:
3786 options?.mcp?.readMcpResource ??
3787 (() => Effect.die("unexpected MCP resource read")),
3788 callMcpTool:
3789 options?.mcp?.callMcpTool ?? (() => Effect.die("unexpected MCP tool call")),
3790 mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"),
3791 mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"),
3792 reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"),
3793 listPermissionRules: options?.mcp?.listPermissionRules ?? Effect.succeed([]),
3794 stopTask: options?.stopTask ?? (() => Effect.void),
3795 interrupt: options?.interrupt ?? Effect.void,
3796 close: options?.close?.(sdkMessages) ?? Effect.void,
3797 };
3798 }),
3799 forkSession: options?.forkSession ?? (() => Effect.die("unused forkSession")),
3800 subagentLaunchToolUseId: () => Effect.succeed(options?.subagentLaunchToolUseId ?? null),
3801 subagentModel: () => Effect.succeed(options?.subagentModel ?? null),
3802 assertComplete: Effect.void,
3803 },
3804 });
3805 const threadId = ThreadId.make("thread-claude-wake");
3806 const runtime = yield* adapter.openSession({
3807 threadId,
3808 providerSessionId: ProviderSessionId.make("provider-session-claude-wake"),
3809 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
3810 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
3811 promptSuggestions: Effect.succeed(options?.promptSuggestions === true),
3812 });
3813 const providerThread = yield* runtime.ensureThread({
3814 threadId,
3815 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
3816 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
3817 });
3818 const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
3819 yield* runtime.events.pipe(
3820 Stream.runForEach((event) =>
3821 Effect.gen(function* () {
3822 events.push(event);
3823 if (event.type === "subagent.updated") {
3824 yield* Queue.offer(subagentReceipts, event);
3825 }
3826 if (event.type === "turn.terminal") {
3827 yield* Queue.offer(terminalReceipts, event);
3828 }
3829 if (event.type === "runtime_request.updated") {
3830 yield* Queue.offer(runtimeRequestReceipts, event);
3831 }
3832 if (event.type === "plan.updated") {
3833 yield* Queue.offer(planReceipts, event);
3834 }
3835 if (event.type === "provider_thread.updated") {
3836 yield* Queue.offer(providerThreadReceipts, event);
3837 }
3838 if (event.type === "turn_item.updated" && event.turnItem.type === "system_notice") {
3839 yield* Queue.offer(systemNoticeReceipts, event);
3840 }
3841 yield* changes.notify;
3842 }),
3843 ),
3844 Effect.forkScoped,
3845 );
3846 if (runtime.hasPendingBackgroundWork === undefined) {
3847 throw new Error("Claude adapter runtime must expose hasPendingBackgroundWork.");
3848 }
3849 const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
3850 const terminalEvents = () =>
3851 events.filter(
3852 (
3853 event,
3854 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
3855 event.type === "turn.terminal",
3856 );
3857 return {
3858 adapter,
3859 attachmentsDir,
3860 runtime,
3861 providerThread,
3862 threadId,
3863 sdkMessages,
3864 processQueues,
3865 offerAndWait,
3866 offeredMessages,
3867 promptUuid: (index: number) => {
3868 const uuid = offeredMessages[index]?.uuid;
3869 if (uuid === undefined) throw new Error(`No prompt offered at index ${index}.`);
3870 return uuid;
3871 },
3872 permissionModeChanges,
3873 renameCalls,
3874 liveSelectionChanges,
3875 continuationRequests,
3876 continuationReceipts,
3877 events,
3878 terminalReceipts,
3879 subagentReceipts,
3880 systemNoticeReceipts,
3881 runtimeRequestReceipts,
3882 planReceipts,
3883 providerThreadReceipts,
3884 getOpenedOptions: () => openedOptions,
3885 terminalEvents,
3886 hasPendingBackgroundWork,
3887 until: changes.until,
3888 awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count),
3889 awaitContinuation: (count: number) =>
3890 changes.until(() => continuationRequests.length >= count),
3891 };
3892 });
3893 const makeWakeHarness = makeWakeHarnessWithOptions();
3894
3895 describe("ClaudeAdapterV2 session title sync", () => {
3896 type TitleSyncHarness = Effect.Success<ReturnType<typeof makeWakeHarnessWithOptions>>;
3897 const startTurn = Effect.fnUntraced(function* (
3898 harness: TitleSyncHarness,
3899 title: string,
3900 ordinal: number,
3901 nativeThreadHasTurns?: boolean,
3902 runtimeOverride?: TitleSyncHarness["runtime"],
3903 providerThreadOverride?: OrchestrationV2ProviderThread,
3904 ) {
3905 const runtime = runtimeOverride ?? harness.runtime;
3906 const providerThread = providerThreadOverride ?? harness.providerThread;
3907 yield* runtime.startTurn(
3908 makeClaudeTestTurnInput({
3909 threadId: harness.threadId,
3910 providerThread,
3911 now: yield* DateTime.now,
3912 attemptId: RunAttemptId.make(`attempt-title-sync-${ordinal}`),
3913 providerTurnOrdinal: ordinal,
3914 title,
3915 text: "What is the sentinel?",
3916 attachments: [],
3917 ...(nativeThreadHasTurns === undefined ? {} : { nativeThreadHasTurns }),
3918 }),
3919 );
3920 });
3921 const finishTurn = Effect.fnUntraced(function* (harness: TitleSyncHarness, ordinal: number) {
3922 yield* harness.offerAndWait(
3923 makeResultFrame({ uuid: `title-result-${ordinal}`, result: "Done." }),
3924 );
3925 yield* Queue.take(harness.terminalReceipts);
3926 });
3927
3928 it.effect("renames the native session only when the thread title changed", () =>
3929 Effect.gen(function* () {
3930 const harness = yield* makeWakeHarnessWithOptions();
3931 yield* startTurn(harness, "First title", 1);
3932 assert.deepEqual(harness.renameCalls, []);
3933 yield* finishTurn(harness, 1);
3934
3935 yield* startTurn(harness, "First title", 2);
3936 assert.deepEqual(harness.renameCalls, []);
3937 yield* finishTurn(harness, 2);
3938
3939 yield* startTurn(harness, "Renamed title", 3);
3940 assert.deepEqual(harness.renameCalls, ["Renamed title"]);
3941 yield* finishTurn(harness, 3);
3942
3943 yield* startTurn(harness, "Renamed title", 4);
3944 assert.deepEqual(harness.renameCalls, ["Renamed title"]);
3945 yield* finishTurn(harness, 4);
3946 }).pipe(
3947 Effect.provide(
3948 Layer.mergeAll(
3949 IdAllocator.layer,
3950 McpProviderSessions.layer,
3951 NodeServices.layer,
3952 NodeCrypto.layer,
3953 ),
3954 ),
3955 ),
3956 );
3957
3958 it.effect("a native /rename retitles the thread without renaming it back", () =>
3959 Effect.gen(function* () {
3960 const harness = yield* makeWakeHarnessWithOptions();
3961 yield* startTurn(harness, "First title", 1);
3962 yield* harness.offerAndWait(
3963 claudeSdkFrame({
3964 type: "system",
3965 subtype: "session_title_changed",
3966 title: "Native title",
3967 uuid: "title-changed-1",
3968 session_id: WAKE_NATIVE_SESSION,
3969 }),
3970 );
3971 yield* harness.offerAndWait({
3972 ...makeResultFrame({
3973 uuid: "title-result-1",
3974 result: "Session renamed to: Native title",
3975 numTurns: 0,
3976 }),
3977 local_command: "rename",
3978 } as SDKMessage);
3979 yield* Queue.take(harness.terminalReceipts);
3980 assert.deepEqual(
3981 harness.events.flatMap((event) =>
3982 event.type === "app_thread.created" ? [event.appThread.title] : [],
3983 ),
3984 ["Native title"],
3985 );
3986
3987 yield* startTurn(harness, "Native title", 2);
3988 assert.deepEqual(harness.renameCalls, []);
3989 yield* finishTurn(harness, 2);
3990 }).pipe(
3991 Effect.provide(
3992 Layer.mergeAll(
3993 IdAllocator.layer,
3994 McpProviderSessions.layer,
3995 NodeServices.layer,
3996 NodeCrypto.layer,
3997 ),
3998 ),
3999 ),
4000 );
4001
4002 it.effect("renames a resumed session whose stored title is stale", () =>
4003 Effect.gen(function* () {
4004 const harness = yield* makeWakeHarnessWithOptions();
4005 yield* startTurn(harness, "First title", 1, true);
4006 assert.deepEqual(harness.renameCalls, ["First title"]);
4007 yield* finishTurn(harness, 1);
4008
4009 yield* startTurn(harness, "First title", 2, true);
4010 assert.deepEqual(harness.renameCalls, ["First title"]);
4011 yield* finishTurn(harness, 2);
4012 }).pipe(
4013 Effect.provide(
4014 Layer.mergeAll(
4015 IdAllocator.layer,
4016 McpProviderSessions.layer,
4017 NodeServices.layer,
4018 NodeCrypto.layer,
4019 ),
4020 ),
4021 ),
4022 );
4023
4024 it.effect(
4025 "a rename blocked past the deadline still offers the prompt and retries next turn",
4026 () =>
4027 Effect.gen(function* () {
4028 const entered = yield* Deferred.make<void>();
4029 let attempts = 0;
4030 const harness = yield* makeWakeHarnessWithOptions({
4031 renameSession: () =>
4032 ++attempts === 1
4033 ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never))
4034 : Effect.void,
4035 });
4036 const firstTurn = yield* Effect.forkScoped(startTurn(harness, "First title", 1, true));
4037 yield* Deferred.await(entered);
4038 yield* TestClock.adjust("10 seconds");
4039 yield* Fiber.join(firstTurn);
4040 assert.deepEqual(harness.renameCalls, ["First title"]);
4041 assert.equal(harness.offeredMessages.length, 1);
4042 assert.equal(attempts, 1);
4043
4044 yield* finishTurn(harness, 1);
4045 assert.deepEqual(harness.renameCalls, ["First title"]);
4046
4047 yield* startTurn(harness, "First title", 2, true);
4048 assert.deepEqual(harness.renameCalls, ["First title", "First title"]);
4049 assert.equal(attempts, 2);
4050 yield* finishTurn(harness, 2);
4051 }).pipe(
4052 Effect.provide(
4053 Layer.mergeAll(
4054 IdAllocator.layer,
4055 McpProviderSessions.layer,
4056 NodeServices.layer,
4057 NodeCrypto.layer,
4058 ),
4059 ),
4060 ),
4061 );
4062
4063 it.effect("renames when reverting to an earlier title after a failed or timed out update", () =>
4064 Effect.gen(function* () {
4065 const harness = yield* makeWakeHarnessWithOptions({
4066 renameSession: (title) =>
4067 title === "Title B"
4068 ? Effect.fail(
4069 new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
4070 method: "renameSession",
4071 cause: new Error("timed out or refused"),
4072 }),
4073 )
4074 : Effect.void,
4075 });
4076 yield* startTurn(harness, "Title A", 1, true);
4077 yield* finishTurn(harness, 1);
4078 assert.deepEqual(harness.renameCalls, ["Title A"]);
4079
4080 yield* startTurn(harness, "Title B", 2, true);
4081 yield* finishTurn(harness, 2);
4082 assert.deepEqual(harness.renameCalls, ["Title A", "Title B"]);
4083
4084 yield* startTurn(harness, "Title A", 3, true);
4085 yield* finishTurn(harness, 3);
4086 assert.deepEqual(harness.renameCalls, ["Title A", "Title B", "Title A"]);
4087
4088 yield* startTurn(harness, "Title A", 4, true);
4089 yield* finishTurn(harness, 4);
4090 assert.deepEqual(harness.renameCalls, ["Title A", "Title B", "Title A"]);
4091 }).pipe(
4092 Effect.provide(
4093 Layer.mergeAll(
4094 IdAllocator.layer,
4095 McpProviderSessions.layer,
4096 NodeServices.layer,
4097 NodeCrypto.layer,
4098 ),
4099 ),
4100 ),
4101 );
4102
4103 it.effect(
4104 "preserves the last-applied title across provider-session recreation so a native /rename survives",
4105 () =>
4106 Effect.gen(function* () {
4107 const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true });
4108 yield* startTurn(harness, "First title", 1);
4109 assert.deepEqual(harness.renameCalls, []);
4110 yield* finishTurn(harness, 1);
4111
4112 const lastEvent = harness.events.findLast(
4113 (
4114 e,
4115 ): e is Extract<
4116 ProviderAdapter.ProviderAdapterV2Event,
4117 { type: "provider_thread.updated" }
4118 > => e.type === "provider_thread.updated",
4119 );
4120 assert.equal(lastEvent?.providerThread.nativeMetadata?.title, "First title");
4121 const threadAfterTurn1 = lastEvent!.providerThread;
4122
4123 const runtime2 = yield* harness.adapter.openSession({
4124 threadId: harness.threadId,
4125 providerSessionId: ProviderSessionId.make("provider-session-claude-wake-2"),
4126 modelSelection: CLAUDE_TEST_MODEL_SELECTION,
4127 runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
4128 });
4129 yield* runtime2.events.pipe(
4130 Stream.runForEach((event) =>
4131 Effect.gen(function* () {
4132 harness.events.push(event);
4133 if (event.type === "turn.terminal") {
4134 yield* Queue.offer(harness.terminalReceipts, event);
4135 }
4136 }),
4137 ),
4138 Effect.forkScoped,
4139 );
4140 const resumedThread = yield* runtime2.resumeThread({
4141 providerThread: threadAfterTurn1,
4142 });
4143 assert.equal(resumedThread.nativeMetadata?.title, "First title");
4144
4145 yield* startTurn(harness, "First title", 2, true, runtime2, resumedThread);
4146 assert.deepEqual(harness.renameCalls, []);
4147 yield* finishTurn(harness, 2);
4148
4149 yield* startTurn(harness, "Second title", 3, true, runtime2, resumedThread);
4150 assert.deepEqual(harness.renameCalls, ["Second title"]);
4151 yield* finishTurn(harness, 3);
4152 }).pipe(
4153 Effect.provide(
4154 Layer.mergeAll(
4155 IdAllocator.layer,
4156 McpProviderSessions.layer,
4157 NodeServices.layer,
4158 NodeCrypto.layer,
4159 ),
4160 ),
4161 ),
4162 );
4163 });
4164
4165 it.effect.each([false, true])(
4166 "resumes a stopped query with empty SDK content and a fresh native process, buffered: %s",
4167 (buffered) =>
4168 Effect.gen(function* () {
4169 const harness = yield* makeWakeHarnessWithOptions({
4170 freshQueueOnReopen: true,
4171 close: (queue) => Queue.shutdown(queue),
4172 });
4173 const input = makeClaudeTestTurnInput({
4174 threadId: harness.threadId,
4175 providerThread: harness.providerThread,
4176 now: DateTime.makeUnsafe(0),
4177 attemptId: RunAttemptId.make("native-resume"),
4178 text: "Initial task",
4179 attachments: [],
4180 providerTurnOrdinal: 1,
4181 });
4182 yield* harness.runtime.startTurn(input);
4183 yield* harness.offerAndWait(turnOneResult);
4184 yield* Queue.take(harness.terminalReceipts);
4185 if (buffered) {
4186 yield* harness.offerAndWait(wakeAssistant);
4187 yield* harness.offerAndWait(wakeResult);
4188 }
4189 const { message, ...turn } = input;
4190 yield* harness.runtime.resumeTurn!({
4191 ...turn,
4192 providerTurnOrdinal: 2,
4193 messageId: message.messageId,
4194 });
4195 assert.equal(harness.processQueues.length, 2);
4196 assert.equal(
4197 harness.getOpenedOptions()?.resume,
4198 harness.providerThread.nativeThreadRef?.nativeId,
4199 );
4200 if (buffered) {
4201 assert.equal(harness.offeredMessages.length, 1);
4202 } else {
4203 assert.deepEqual(harness.offeredMessages.at(-1)?.message.content, []);
4204 yield* harness.offerAndWait(turnOneResult);
4205 }
4206 yield* Queue.take(harness.terminalReceipts);
4207 assert.equal(harness.terminalEvents().length, 2);
4208 if (buffered) {
4209 assert.isTrue(
4210 harness.events.some(
4211 (event) =>
4212 event.type === "turn_item.updated" &&
4213 event.turnItem.type === "assistant_message" &&
4214 event.turnItem.text === WAKE_ASSISTANT_TEXT,
4215 ),
4216 );
4217 }
4218 }).pipe(
4219 Effect.scoped,
4220 Effect.provide(
4221 Layer.mergeAll(
4222 IdAllocator.layer,
4223 McpProviderSessions.layer,
4224 NodeServices.layer,
4225 NodeCrypto.layer,
4226 ),
4227 ),
4228 ),
4229 );
4230
4231 it.effect("reports the session cwd on each process's first init, not on repeated inits", () =>
4232 Effect.gen(function* () {
4233 const initCwds: Array<string> = [];
4234 const harness = yield* makeWakeHarnessWithOptions({
4235 freshQueueOnReopen: true,
4236 close: (queue) => Queue.shutdown(queue),
4237 onSessionInit: (cwd) =>
4238 Effect.sync(() => {
4239 initCwds.push(cwd);
4240 }),
4241 });
4242 // The CLI may report a resolved path, not the cwd clients key their snapshots on.
4243 const init = (uuid: string) =>
4244 claudeSdkFrame({
4245 type: "system",
4246 subtype: "init",
4247 cwd: "/private/workspace",
4248 session_id: WAKE_NATIVE_SESSION,
4249 uuid,
4250 });
4251 const latest = (): OrchestrationV2ProviderThread => {
4252 const event = harness.events.findLast(
4253 (candidate) => candidate.type === "provider_thread.updated",
4254 );
4255 return event?.type === "provider_thread.updated"
4256 ? event.providerThread
4257 : harness.providerThread;
4258 };
4259 const turn = (ordinal: number) =>
4260 makeClaudeTestTurnInput({
4261 threadId: harness.threadId,
4262 providerThread: latest(),
4263 now: DateTime.makeUnsafe(0),
4264 attemptId: RunAttemptId.make(`session-init-${ordinal}`),
4265 text: `Turn ${ordinal}`,
4266 attachments: [],
4267 providerTurnOrdinal: ordinal,
4268 });
4269 yield* harness.runtime.startTurn(turn(1));
4270 assert.deepEqual(initCwds, []);
4271 yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000701"));
4272 assert.deepEqual(initCwds, ["/workspace"]);
4273 yield* harness.offerAndWait(turnOneResult);
4274 yield* Queue.take(harness.terminalReceipts);
4275 // The CLI repeats init on every turn of one process; its startup hooks ran once.
4276 yield* harness.runtime.startTurn(turn(2));
4277 yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000702"));
4278 yield* harness.offerAndWait(
4279 makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000703", result: "Two." }),
4280 );
4281 yield* Queue.take(harness.terminalReceipts);
4282 assert.deepEqual(initCwds, ["/workspace"]);
4283 yield* harness.runtime.interruptTurn({
4284 providerThread: latest(),
4285 providerTurnId: lastProviderTurn(harness.events).id,
4286 requestRuntimeRestart: true,
4287 });
4288 yield* harness.runtime.startTurn(turn(3));
4289 assert.equal(harness.processQueues.length, 2);
4290 yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000704"));
4291 assert.deepEqual(initCwds, ["/workspace", "/workspace"]);
4292 }).pipe(
4293 Effect.scoped,
4294 Effect.provide(
4295 Layer.mergeAll(
4296 IdAllocator.layer,
4297 McpProviderSessions.layer,
4298 NodeServices.layer,
4299 NodeCrypto.layer,
4300 ),
4301 ),
4302 ),
4303 );
4304
4305 it.effect("resumes the session a /clear selected after the Claude process is replaced", () =>
4306 Effect.gen(function* () {
4307 const harness = yield* makeWakeHarnessWithOptions({
4308 freshQueueOnReopen: true,
4309 close: (queue) => Queue.shutdown(queue),
4310 });
4311 const turn = (ordinal: number, providerThread: OrchestrationV2ProviderThread) =>
4312 makeClaudeTestTurnInput({
4313 threadId: harness.threadId,
4314 providerThread,
4315 now: DateTime.makeUnsafe(0),
4316 attemptId: RunAttemptId.make(`clear-session-${ordinal}`),
4317 text: ordinal === 1 ? "/clear" : "Continue the cleared conversation",
4318 attachments: [],
4319 providerTurnOrdinal: ordinal,
4320 });
4321 yield* harness.runtime.startTurn(turn(1, harness.providerThread));
4322 // Claude Code reports the session /clear started in its next init frame.
4323 yield* harness.offerAndWait(
4324 claudeSdkFrame({
4325 type: "system",
4326 subtype: "init",
4327 session_id: "cleared-native-session",
4328 uuid: "00000000-0000-4000-8000-000000000501",
4329 }),
4330 );
4331 yield* harness.offerAndWait(turnOneResult);
4332 yield* Queue.take(harness.terminalReceipts);
4333 const latest = (): OrchestrationV2ProviderThread => {
4334 const event = harness.events.findLast(
4335 (candidate) => candidate.type === "provider_thread.updated",
4336 );
4337 return event?.type === "provider_thread.updated"
4338 ? event.providerThread
4339 : harness.providerThread;
4340 };
4341 assert.equal(latest().nativeThreadRef?.nativeId, "cleared-native-session");
4342 yield* harness.runtime.interruptTurn({
4343 providerThread: latest(),
4344 providerTurnId: lastProviderTurn(harness.events).id,
4345 requestRuntimeRestart: true,
4346 });
4347 yield* harness.runtime.startTurn(turn(2, latest()));
4348 assert.equal(harness.processQueues.length, 2);
4349 assert.equal(harness.getOpenedOptions()?.resume, "cleared-native-session");
4350 }).pipe(
4351 Effect.scoped,
4352 Effect.provide(
4353 Layer.mergeAll(
4354 IdAllocator.layer,
4355 McpProviderSessions.layer,
4356 NodeServices.layer,
4357 NodeCrypto.layer,
4358 ),
4359 ),
4360 ),
4361 );
4362
4363 it.effect.each(["release-after", "cancel-after", "release-before", "resume-pending"] as const)(
4364 "keeps attachment reservations across compaction: %s boundary",
4365 (outcome) =>
4366 Effect.gen(function* () {
4367 const fileSystem = yield* FileSystem.FileSystem;
4368 const path = yield* Path.Path;
4369 const idAllocator = yield* IdAllocator.IdAllocatorV2;
4370 const backgrounding = yield* Deferred.make<void>();
4371 const release = yield* Deferred.make<void>();
4372 const harness = yield* makeWakeHarnessWithOptions({
4373 backgroundTasks: () =>
4374 Deferred.succeed(backgrounding, undefined).pipe(
4375 Effect.andThen(Deferred.await(release)),
4376 Effect.as(true),
4377 ),
4378 });
4379 const document = ChatFileAttachment.make({
4380 type: "file",
4381 id: ChatAttachmentId.make("compacting-document"),
4382 name: "compacting.pdf",
4383 mimeType: "application/pdf",
4384 sizeBytes: 19 * 1024 * 1024,
4385 });
4386 const pages = Buffer.from(
4387 `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
4388 );
4389 yield* fileSystem.writeFile(
4390 path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
4391 Buffer.concat([
4392 pages,
4393 Buffer.alloc(document.sizeBytes - pages.length - 5, 32),
4394 Buffer.from("%%EOF"),
4395 ]),
4396 );
4397 const input = makeClaudeTestTurnInput({
4398 threadId: harness.threadId,
4399 providerThread: harness.providerThread,
4400 now: yield* DateTime.now,
4401 attemptId: RunAttemptId.make("compacting-reservation"),
4402 text: "Audit with a subagent.",
4403 attachments: [],
4404 });
4405 yield* harness.runtime.startTurn(input);
4406 yield* harness.offerAndWait(
4407 claudeSdkFrame({
4408 type: "system",
4409 subtype: "task_started",
4410 task_id: "compacting-task",
4411 tool_use_id: "compacting-tool",
4412 description: "Audit",
4413 subagent_type: "general-purpose",
4414 is_backgrounded: false,
4415 task_type: "local_agent",
4416 prompt: "Audit.",
4417 uuid: "00000000-0000-4000-8000-000000000811",
4418 session_id: WAKE_NATIVE_SESSION,
4419 }),
4420 );
4421 const steer = harness.runtime.steerTurn({
4422 threadId: harness.threadId,
4423 runId: input.runId,
4424 providerThread: harness.providerThread,
4425 providerTurnId: idAllocator.derive.providerTurn({
4426 driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
4427 nativeTurnId: `turn:${input.attemptId}`,
4428 }),
4429 message: {
4430 createdBy: "user",
4431 creationSource: "web",
4432 messageId: MessageId.make("compacting-steer"),
4433 text: "Read this PDF.",
4434 attachments: [document],
4435 },
4436 });
4437 const pending = yield* Effect.forkScoped(steer);
4438 yield* Deferred.await(backgrounding);
4439 assert.lengthOf(harness.offeredMessages, 1);
4440 yield* harness.offerAndWait(
4441 claudeSdkFrame({
4442 type: "system",
4443 subtype: "status",
4444 status: "compacting",
4445 uuid: "00000000-0000-4000-8000-000000000812",
4446 session_id: WAKE_NATIVE_SESSION,
4447 }),
4448 );
4449 if (outcome === "release-before") {
4450 yield* Deferred.succeed(release, undefined);
4451 yield* Fiber.join(pending);
4452 }
4453 yield* harness.offerAndWait(
4454 claudeSdkFrame({
4455 type: "system",
4456 subtype: "compact_boundary",
4457 compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 },
4458 uuid: "00000000-0000-4000-8000-000000000813",
4459 session_id: WAKE_NATIVE_SESSION,
4460 }),
4461 );
4462 if (outcome === "cancel-after") {
4463 yield* Fiber.interrupt(pending);
4464 assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(pending)));
4465 } else if (outcome === "release-after") {
4466 yield* Deferred.succeed(release, undefined);
4467 yield* Fiber.join(pending);
4468 }
4469 // Flush the budget update through the event stream before trying again.
4470 yield* harness.offerAndWait(
4471 makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000814", result: "Read." }),
4472 );
4473 yield* Queue.take(harness.terminalReceipts);
4474 const updates = harness.events.flatMap((event) =>
4475 event.type === "provider_thread.updated" ? [event.providerThread] : [],
4476 );
4477 for (const thread of updates) {
4478 yield* decodeProviderThreadJson(yield* encodeProviderThreadJson(thread));
4479 }
4480 const persisted = yield* decodeProviderThreadJson(
4481 yield* encodeProviderThreadJson(updates.at(-1)!),
4482 );
4483 const usage = persisted.nativeMetadata?.claudeAttachmentBudget;
4484 const undelivered = outcome === "cancel-after" || outcome === "resume-pending";
4485 assert.equal(usage?.pagesUsed, undelivered ? 0 : 60);
4486 if (undelivered) assert.equal(usage?.bytesUsed, 0);
4487 else assert.isAbove(usage?.bytesUsed ?? 0, 25 * 1024 * 1024);
4488 const next = outcome === "resume-pending" ? yield* makeWakeHarness : harness;
4489 const providerThread =
4490 outcome === "resume-pending"
4491 ? yield* next.runtime.resumeThread({ providerThread: persisted })
4492 : persisted;
4493 if (outcome === "resume-pending") {
4494 assert.lengthOf(harness.offeredMessages, 1);
4495 yield* fileSystem.copyFile(
4496 path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
4497 path.join(next.attachmentsDir, attachmentRelativePath(document)!),
4498 );
4499 }
4500 yield* next.runtime.startTurn(
4501 makeClaudeTestTurnInput({
4502 threadId: next.threadId,
4503 providerThread,
4504 now: yield* DateTime.now,
4505 attemptId: RunAttemptId.make("after-compacting-reservation"),
4506 text: "Read this PDF again.",
4507 attachments: [document],
4508 providerTurnOrdinal: 2,
4509 nativeThreadHasTurns: true,
4510 }),
4511 );
4512 if (outcome === "resume-pending") {
4513 assert.equal(next.getOpenedOptions()?.resume, WAKE_NATIVE_SESSION);
4514 }
4515 const delivered = next.offeredMessages.slice(outcome === "resume-pending" ? 0 : 1);
4516 const documents = delivered.flatMap((message) =>
4517 Array.isArray(message.message.content)
4518 ? message.message.content.filter((block) => block.type === "document")
4519 : [],
4520 );
4521 assert.lengthOf(documents, 1);
4522 assert.isBelow(
4523 Buffer.byteLength(encodeJsonString(delivered.map((message) => message.message.content))),
4524 32_000_000,
4525 );
4526 }).pipe(
4527 Effect.provide(
4528 Layer.mergeAll(
4529 IdAllocator.layer,
4530 McpProviderSessions.layer,
4531 NodeServices.layer,
4532 NodeCrypto.layer,
4533 ),
4534 ),
4535 ),
4536 );
4537
4538 const attachmentBudgetOutcomes = [
4539 "resume",
4540 "legacy",
4541 "compacted",
4542 "preserved-segment",
4543 "preserved-messages",
4544 "failed",
4545 "stopped",
4546 "fork-bytes",
4547 "fork-pages",
4548 ] as const;
4549 it.effect.each(attachmentBudgetOutcomes)(
4550 "restores retained attachment counters after %s",
4551 (outcome) =>
4552 Effect.gen(function* () {
4553 const fileSystem = yield* FileSystem.FileSystem;
4554 const path = yield* Path.Path;
4555 const document = ChatFileAttachment.make({
4556 type: "file",
4557 id: ChatAttachmentId.make("budget-document"),
4558 name: "budget.pdf",
4559 mimeType: "application/pdf",
4560 sizeBytes: 19 * 1024 * 1024,
4561 });
4562 const image = ChatImageAttachment.make({
4563 type: "image",
4564 id: ChatAttachmentId.make("budget-image"),
4565 name: "budget.png",
4566 mimeType: "image/png",
4567 sizeBytes: 4 * 1024 * 1024,
4568 });
4569 const pages = Buffer.from(
4570 `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 100 >> endobj\n${Array.from({ length: 100 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
4571 );
4572 const persisted = yield* Effect.scoped(
4573 Effect.gen(function* () {
4574 const harness = yield* makeWakeHarness;
4575 yield* fileSystem.writeFile(
4576 path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
4577 Buffer.concat([
4578 pages,
4579 Buffer.alloc(document.sizeBytes - pages.length - 5, 32),
4580 Buffer.from("%%EOF"),
4581 ]),
4582 );
4583 yield* harness.runtime.startTurn(
4584 makeClaudeTestTurnInput({
4585 threadId: harness.threadId,
4586 providerThread: harness.providerThread,
4587 now: yield* DateTime.now,
4588 attemptId: RunAttemptId.make("spend-attachment-budget"),
4589 text: "Read this PDF.",
4590 attachments: [document],
4591 }),
4592 );
4593 const first = harness.offeredMessages[0]?.message.content;
4594 assert.isArray(first);
4595 if (Array.isArray(first)) assert.equal(first[0]?.type, "document");
4596 if (
4597 [
4598 "compacted",
4599 "preserved-segment",
4600 "preserved-messages",
4601 "failed",
4602 "stopped",
4603 ].includes(outcome)
4604 ) {
4605 yield* harness.offerAndWait(
4606 claudeSdkFrame({
4607 type: "system",
4608 subtype: "status",
4609 status: "compacting",
4610 uuid: "00000000-0000-4000-8000-000000000801",
4611 session_id: WAKE_NATIVE_SESSION,
4612 }),
4613 );
4614 yield* harness.offerAndWait(
4615 claudeSdkFrame(
4616 outcome === "compacted" ||
4617 outcome === "preserved-segment" ||
4618 outcome === "preserved-messages"
4619 ? {
4620 type: "system",
4621 subtype: "compact_boundary",
4622 compact_metadata: {
4623 trigger: "auto",
4624 pre_tokens: 1500,
4625 post_tokens: 400,
4626 ...(outcome === "preserved-segment"
4627 ? {
4628 preserved_segment: {
4629 head_uuid: harness.promptUuid(0),
4630 tail_uuid: harness.promptUuid(0),
4631 anchor_uuid: "00000000-0000-4000-8000-000000000802",
4632 },
4633 }
4634 : outcome === "preserved-messages"
4635 ? {
4636 preserved_messages: {
4637 anchor_uuid: "00000000-0000-4000-8000-000000000802",
4638 uuids: [harness.promptUuid(0)],
4639 },
4640 }
4641 : {}),
4642 },
4643 uuid: "00000000-0000-4000-8000-000000000802",
4644 session_id: WAKE_NATIVE_SESSION,
4645 }
4646 : {
4647 type: "system",
4648 subtype: "status",
4649 status: null,
4650 ...(outcome === "failed"
4651 ? { compact_result: "failed", compact_error: "Could not compact." }
4652 : {}),
4653 uuid: "00000000-0000-4000-8000-000000000802",
4654 session_id: WAKE_NATIVE_SESSION,
4655 },
4656 ),
4657 );
4658 }
4659 yield* harness.offerAndWait(
4660 makeResultFrame({
4661 uuid: "00000000-0000-4000-8000-000000000803",
4662 result: "Read.",
4663 }),
4664 );
4665 yield* Queue.take(harness.terminalReceipts);
4666 const event = harness.events.findLast(
4667 (entry) => entry.type === "provider_thread.updated",
4668 );
4669 assert.equal(event?.type, "provider_thread.updated");
4670 if (event?.type !== "provider_thread.updated")
4671 return yield* Effect.die("Missing persisted thread");
4672 const budget = event.providerThread.nativeMetadata?.claudeAttachmentBudget;
4673 assert.isDefined(budget);
4674 if (outcome === "compacted") assert.deepEqual(budget, { bytesUsed: 0, pagesUsed: 0 });
4675 else {
4676 assert.equal(budget?.pagesUsed, 100);
4677 assert.isAbove(budget?.bytesUsed ?? 0, 25 * 1024 * 1024);
4678 }
4679 // Exercise the same schema boundary as the persisted provider thread.
4680 return yield* decodeProviderThreadJson(
4681 yield* encodeProviderThreadJson({
4682 ...event.providerThread,
4683 ...(outcome === "legacy" ? { nativeMetadata: null } : {}),
4684 }),
4685 );
4686 }),
4687 );
4688 const fork = outcome === "fork-bytes" || outcome === "fork-pages";
4689 const inherited = fork
4690 ? yield* Effect.scoped(
4691 Effect.gen(function* () {
4692 const harness = yield* makeWakeHarnessWithOptions({
4693 forkSession: () =>
4694 Effect.succeed({
4695 sessionId: "forked-native-session",
4696 ...(outcome === "fork-bytes"
4697 ? { headMessageId: "forked-assistant-head" }
4698 : {}),
4699 }),
4700 });
4701 const forked = yield* harness.runtime.forkThread({
4702 sourceProviderThread: persisted,
4703 targetThreadId: harness.threadId,
4704 });
4705 return yield* decodeProviderThreadJson(yield* encodeProviderThreadJson(forked));
4706 }),
4707 )
4708 : persisted;
4709 const resumed = yield* makeWakeHarness;
4710 const providerThread = yield* resumed.runtime.resumeThread({ providerThread: inherited });
4711 yield* fileSystem.writeFileString(
4712 path.join(resumed.attachmentsDir, attachmentRelativePath(document)!),
4713 "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF",
4714 );
4715 yield* fileSystem.writeFile(
4716 path.join(resumed.attachmentsDir, attachmentRelativePath(image)!),
4717 Buffer.alloc(image.sizeBytes, 1),
4718 );
4719 yield* resumed.runtime.startTurn({
4720 ...makeClaudeTestTurnInput({
4721 threadId: resumed.threadId,
4722 providerThread,
4723 now: yield* DateTime.now,
4724 attemptId: RunAttemptId.make("resume-attachment-budget"),
4725 text: "Read the PDF and both images.",
4726 attachments:
4727 outcome === "fork-bytes"
4728 ? [image, image]
4729 : outcome === "fork-pages"
4730 ? [document]
4731 : [document, image, image],
4732 }),
4733 nativeThreadHasTurns: true,
4734 });
4735 assert.equal(
4736 resumed.getOpenedOptions()?.resume,
4737 fork ? "forked-native-session" : WAKE_NATIVE_SESSION,
4738 );
4739 const content = resumed.offeredMessages[0]?.message.content;
4740 assert.isArray(content);
4741 if (!Array.isArray(content)) return;
4742 const native = outcome === "legacy" || outcome === "compacted";
4743 assert.equal(content.filter((block) => block.type === "document").length, native ? 1 : 0);
4744 assert.equal(content.filter((block) => block.type === "image").length, native ? 2 : 0);
4745 assert.isBelow(Buffer.byteLength(encodeJsonString(content)), 32_000_000);
4746 if (fork) {
4747 assert.deepEqual(
4748 inherited.nativeMetadata?.claudeAttachmentBudget,
4749 persisted.nativeMetadata?.claudeAttachmentBudget,
4750 );
4751 assert.equal(
4752 inherited.nativeMetadata?.forkHeadMessageId,
4753 outcome === "fork-bytes" ? "forked-assistant-head" : undefined,
4754 );
4755 assert.isBelow(
4756 (persisted.nativeMetadata?.claudeAttachmentBudget?.bytesUsed ?? 0) +
4757 Buffer.byteLength(encodeJsonString(content)),
4758 32_000_000,
4759 );
4760 assert.include(encodeJsonString(content), "budget.");
4761 }
4762 }).pipe(
4763 Effect.provide(
4764 Layer.mergeAll(
4765 IdAllocator.layer,
4766 McpProviderSessions.layer,
4767 NodeServices.layer,
4768 NodeCrypto.layer,
4769 ),
4770 ),
4771 ),
4772 );
4773
4774 describe("Claude settings restrictions", () => {
4775 it.effect("resolves cached managed policy from the configured home through the real SDK", () =>
4776 Effect.gen(function* () {
4777 const fileSystem = yield* FileSystem.FileSystem;
4778 const path = yield* Path.Path;
4779 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-" });
4780 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-cwd-" });
4781 const remoteFile = path.join(home, "remote-settings.json");
4782 const sdk = yield* Effect.promise(() =>
4783 vi.importActual<typeof ClaudeSdk>("@anthropic-ai/claude-agent-sdk"),
4784 );
4785 vi.mocked(ClaudeSdk.resolveSettings).mockImplementation(sdk.resolveSettings);
4786 const openWith = (launchArgs: string) =>
4787 Effect.scoped(
4788 Effect.gen(function* () {
4789 const harness = yield* makeWakeHarnessWithOptions({
4790 settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home, launchArgs },
4791 });
4792 yield* harness.runtime.startTurn(
4793 makeClaudeTestTurnInput({
4794 threadId: harness.threadId,
4795 providerThread: harness.providerThread,
4796 now: yield* DateTime.now,
4797 attemptId: RunAttemptId.make("attempt-cached-managed-policy"),
4798 text: "Run git status.",
4799 attachments: [],
4800 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4801 runtimeMode: "full-access",
4802 interactionMode: "default",
4803 cwd,
4804 }),
4805 }),
4806 );
4807 return harness.getOpenedOptions()!;
4808 }),
4809 );
4810 const open = openWith("");
4811 yield* fileSystem.writeFileString(
4812 remoteFile,
4813 JSON.stringify({
4814 permissions: { disableBypassPermissionsMode: "disable" },
4815 disableAutoMode: "disable",
4816 managedSourcesBehavior: "merge",
4817 }),
4818 );
4819 const restricted = yield* open;
4820 assert.equal(restricted.permissionMode, "default");
4821 assert.isUndefined(restricted.allowDangerouslySkipPermissions);
4822 yield* fileSystem.writeFileString(
4823 remoteFile,
4824 JSON.stringify({
4825 permissions: { disableBypassPermissionsMode: false, disableAutoMode: false },
4826 disableAutoMode: false,
4827 managedSourcesBehavior: "merge",
4828 }),
4829 );
4830 const unrestricted = yield* open;
4831 assert.equal(unrestricted.permissionMode, "bypassPermissions");
4832 assert.equal(unrestricted.allowDangerouslySkipPermissions, true);
4833 yield* fileSystem.writeFileString(
4834 remoteFile,
4835 JSON.stringify({
4836 permissions: { disableBypassPermissionsMode: "disable", disableAutoMode: "disable" },
4837 disableAutoMode: false,
4838 }),
4839 );
4840 const mixed = yield* open;
4841 assert.equal(mixed.permissionMode, "default");
4842 assert.isUndefined(mixed.allowDangerouslySkipPermissions);
4843 yield* fileSystem.writeFileString(
4844 remoteFile,
4845 JSON.stringify({ permissions: { disableBypassPermissionsMode: true } }),
4846 );
4847 assert.equal((yield* open).permissionMode, "auto");
4848 yield* fileSystem.remove(remoteFile);
4849 assert.equal((yield* open).permissionMode, "bypassPermissions");
4850 const launchRestricted = yield* openWith(
4851 `--settings '{"permissions":{"disableBypassPermissionsMode":"disable"}}'`,
4852 );
4853 assert.equal(launchRestricted.permissionMode, "auto");
4854 assert.isUndefined(launchRestricted.allowDangerouslySkipPermissions);
4855 yield* fileSystem.writeFileString(remoteFile, "{ invalid json");
4856 assert.equal((yield* open).permissionMode, "auto");
4857 yield* fileSystem.remove(remoteFile);
4858 yield* fileSystem.makeDirectory(remoteFile);
4859 assert.equal((yield* open).permissionMode, "auto");
4860 }).pipe(
4861 Effect.provide(
4862 Layer.mergeAll(
4863 IdAllocator.layer,
4864 McpProviderSessions.layer,
4865 NodeServices.layer,
4866 NodeCrypto.layer,
4867 ),
4868 ),
4869 ),
4870 );
4871
4872 it.effect("drops false bypass switches from --settings before they reach the SDK", () =>
4873 Effect.gen(function* () {
4874 const fileSystem = yield* FileSystem.FileSystem;
4875 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-launch-" });
4876 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-launch-cwd-" });
4877 const sdk = yield* Effect.promise(() =>
4878 vi.importActual<typeof ClaudeSdk>("@anthropic-ai/claude-agent-sdk"),
4879 );
4880 vi.mocked(ClaudeSdk.resolveSettings).mockImplementation(sdk.resolveSettings);
4881 const openWith = (settings: Record<string, unknown>) =>
4882 Effect.scoped(
4883 Effect.gen(function* () {
4884 const harness = yield* makeWakeHarnessWithOptions({
4885 settings: {
4886 ...DEFAULT_CLAUDE_SETTINGS,
4887 homePath: home,
4888 launchArgs: `--settings '${JSON.stringify(settings)}'`,
4889 },
4890 });
4891 yield* harness.runtime.startTurn(
4892 makeClaudeTestTurnInput({
4893 threadId: harness.threadId,
4894 providerThread: harness.providerThread,
4895 now: yield* DateTime.now,
4896 attemptId: RunAttemptId.make("attempt-launch-arg-settings"),
4897 text: "Run git status.",
4898 attachments: [],
4899 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4900 runtimeMode: "full-access",
4901 interactionMode: "default",
4902 cwd,
4903 }),
4904 }),
4905 );
4906 const options = harness.getOpenedOptions()!;
4907 return {
4908 permissionMode: options.permissionMode,
4909 settings: options.settings as {
4910 disableAutoMode?: unknown;
4911 permissions?: Record<string, unknown>;
4912 env?: Record<string, unknown>;
4913 },
4914 };
4915 }),
4916 );
4917 const unrestricted = yield* openWith({
4918 disableAutoMode: false,
4919 permissions: { disableBypassPermissionsMode: false, disableAutoMode: false, allow: [] },
4920 env: { KEPT: "1" },
4921 });
4922 assert.equal(unrestricted.permissionMode, "bypassPermissions");
4923 assert.notProperty(unrestricted.settings, "disableAutoMode");
4924 assert.deepEqual(unrestricted.settings.permissions, { allow: [] });
4925 assert.equal(unrestricted.settings.env?.KEPT, "1");
4926 const restricted = yield* openWith({
4927 disableAutoMode: false,
4928 permissions: { disableBypassPermissionsMode: "disable", disableAutoMode: "disable" },
4929 });
4930 assert.equal(restricted.permissionMode, "default");
4931 assert.notProperty(restricted.settings, "disableAutoMode");
4932 assert.deepEqual(restricted.settings.permissions, {
4933 disableBypassPermissionsMode: "disable",
4934 disableAutoMode: "disable",
4935 });
4936 }).pipe(
4937 Effect.provide(
4938 Layer.mergeAll(
4939 IdAllocator.layer,
4940 McpProviderSessions.layer,
4941 NodeServices.layer,
4942 NodeCrypto.layer,
4943 ),
4944 ),
4945 ),
4946 );
4947
4948 it.effect("asks before restricted Full access tools and follows policy across turns", () =>
4949 Effect.gen(function* () {
4950 const resolveSettings = vi
4951 .mocked(ClaudeSdk.resolveSettings)
4952 .mockImplementation(async (options) => ({
4953 effective:
4954 options?.cwd === "/unrestricted"
4955 ? {}
4956 : {
4957 permissions: {
4958 disableBypassPermissionsMode: "disable",
4959 ...(options?.cwd === "/restricted-worktree"
4960 ? { disableAutoMode: "disable" as const }
4961 : {}),
4962 },
4963 },
4964 provenance: {},
4965 sources: [],
4966 }));
4967 const harness = yield* makeWakeHarnessWithOptions({
4968 close: Queue.shutdown,
4969 freshQueueOnReopen: true,
4970 setPermissionMode: (mode) =>
4971 mode === "bypassPermissions"
4972 ? Effect.fail(
4973 new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
4974 method: "setPermissionMode",
4975 cause: new Error(
4976 "Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration",
4977 ),
4978 }),
4979 )
4980 : Effect.void,
4981 });
4982 const now = yield* DateTime.now;
4983 let ordinal = 0;
4984 const start = (cwd: string, runtimeMode: "full-access" | "auto" = "full-access") =>
4985 harness.runtime.startTurn(
4986 makeClaudeTestTurnInput({
4987 threadId: harness.threadId,
4988 providerThread: harness.providerThread,
4989 now,
4990 attemptId: RunAttemptId.make(`attempt-policy-${++ordinal}`),
4991 providerTurnOrdinal: ordinal,
4992 text: "Run git status.",
4993 attachments: [],
4994 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4995 runtimeMode,
4996 interactionMode: "default",
4997 cwd,
4998 }),
4999 }),
5000 );
Showing first 5,000 of 25,309 lines. View raw