// @effect-diagnostics nodeBuiltinImport:off -- workflow fixtures use files and the fake Claude CLI uses Node streams
import * as NodeEvents from "node:events";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeStream from "node:stream";
import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
import { beforeEach, vi } from "vite-plus/test";
import type {
ElicitationRequest,
Query as ClaudeQuery,
SDKMessage,
SDKResultMessage,
SDKUserMessage,
SpawnedProcess,
SpawnOptions,
} from "@anthropic-ai/claude-agent-sdk";
import type {
AskUserQuestionInput,
TaskCreateInput,
TaskCreateOutput,
TaskListOutput,
TaskUpdateInput,
TaskUpdateOutput,
} from "@anthropic-ai/claude-agent-sdk/sdk-tools";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { toolOutputImages } from "@t3tools/shared/toolOutput";
import {
ChatAttachmentId,
type ChatAttachment,
ChatFileAttachment,
ChatImageAttachment,
CheckpointId,
ClaudeSettings,
EnvironmentId,
MessageId,
type ModelSelection,
NodeId,
type OrchestrationV2AppThread,
type OrchestrationV2PendingBackgroundTask,
OrchestrationV2ProviderThread,
ProjectId,
ProviderInstanceId,
type ResolvedProviderInstanceEnvironment,
ProviderDriverKind,
type ProviderReplayTranscript,
type ProviderApprovalDecision,
ProviderSessionId,
ProviderTurnId,
RunAttemptId,
RunId,
ThreadId,
} from "@t3tools/contracts";
import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
import { assert, describe, it } from "@effect/vitest";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { Tool } from "effect/ai";
import { formatClaudeResumeCompactionQuestion } from "@t3tools/shared/claudeCompaction";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import * as PortScanner from "../../preview/PortScanner.ts";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { WorkflowAgentTranscriptReadObserver } from "../workflowAgentTranscript.ts";
import * as ServerConfig from "../../config.ts";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import { T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH } from "@t3tools/provider-core/server/orchestrationInstructions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools.ts";
import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts";
import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts";
import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts";
import { WorktreeToolkit } from "../../mcp/toolkits/worktree/tools.ts";
import { ThreadToolkit } from "../../mcp/toolkits/thread/tools.ts";
import { OrchestratorToolkit } from "../../mcp/toolkits/orchestrator/tools.ts";
import { ClaudeExecutableFileCheck } from "../../provider/Drivers/ClaudeExecutable.ts";
import {
BUNDLED_CLAUDE_MODEL_CATALOG,
type ClaudeModelCatalog,
} from "../../provider/ClaudeModelCatalog.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import { ClaudeOrchestratorReplayHarness } from "./ClaudeAdapterV2.testkit.ts";
import { provideDeterministicTestRuntime } from "../testkit/DeterministicRuntime.ts";
import { runOrchestratorV2Scenario } from "../testkit/OrchestratorScenario.ts";
import { layerProviderReplay } from "../testkit/ProviderReplayHarness.ts";
import {
assertBaseProjection,
assertSemanticProjectionIntegrity,
CLAUDE_MODEL_SELECTION,
materializeFixtureInput,
projectionFor,
} from "../testkit/fixtures/shared.ts";
vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => ({
...(await importOriginal<typeof ClaudeSdk>()),
resolveSettings: vi.fn(),
}));
beforeEach(() => {
vi.mocked(ClaudeSdk.resolveSettings).mockReset().mockResolvedValue({
effective: {},
provenance: {},
sources: [],
});
});
const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({});
const AUTO_COMPACT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
autoCompactWindow: "300000",
});
const CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
customModels: [
"opus",
{
slug: "claude-custom-tuned",
name: "Tuned",
capabilities: {
optionDescriptors: [
{
id: "effort",
label: "Reasoning",
type: "select",
options: [
{ id: "gentle", label: "Gentle", isDefault: true },
{ id: "brutal", label: "Brutal" },
],
},
],
},
},
],
});
const ULTRACODE_CUSTOM_MODEL_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({
customModels: [
{
slug: "claude-custom-tuned",
capabilities: {
optionDescriptors: [
{
id: "effort",
label: "Reasoning",
type: "select",
options: [
{ id: "high", label: "High", isDefault: true },
{ id: "ultracode", label: "Ultracode" },
],
},
],
},
},
],
});
const CLAUDE_TEST_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
model: "claude-sonnet-4-6",
options: [{ id: "effort", value: "ultrathink" }],
} satisfies ModelSelection;
const CLAUDE_TEST_RESTART_MODEL_SELECTION = {
...CLAUDE_TEST_MODEL_SELECTION,
model: "claude-haiku-4-5-20251001",
options: [{ id: "thinking", value: false }],
} satisfies ModelSelection;
const CLAUDE_TEST_RUNTIME_POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace",
});
function makeClaudeTestAppThread(input: {
readonly threadId: ThreadId;
readonly providerThread: OrchestrationV2ProviderThread;
readonly now: DateTime.Utc;
}): OrchestrationV2AppThread {
return {
createdBy: "user",
creationSource: "web",
id: input.threadId,
projectId: ProjectId.make(`project-${input.threadId}`),
title: "Claude attachment test",
providerInstanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: input.providerThread.id,
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: input.threadId,
},
forkedFrom: null,
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
}
function makeClaudeTestTurnInput(input: {
readonly threadId: ThreadId;
readonly providerThread: OrchestrationV2ProviderThread;
readonly now: DateTime.Utc;
readonly attemptId: RunAttemptId;
readonly text: string;
readonly attachments: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["attachments"];
readonly providerTurnOrdinal?: number;
readonly nativeThreadHasTurns?: boolean;
readonly messageCreatedBy?: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["createdBy"];
readonly messageCreationSource?: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["creationSource"];
readonly modelSelection?: ModelSelection;
readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
}): ProviderAdapter.ProviderAdapterV2TurnInput {
return {
appThread: makeClaudeTestAppThread(input),
threadId: input.threadId,
runId: RunId.make(`run-${input.attemptId}`),
runOrdinal: 1,
providerTurnOrdinal: input.providerTurnOrdinal ?? 1,
...(input.nativeThreadHasTurns === undefined
? {}
: { nativeThreadHasTurns: input.nativeThreadHasTurns }),
attemptId: input.attemptId,
rootNodeId: NodeId.make(`node-${input.attemptId}`),
providerThread: input.providerThread,
message: {
createdBy: input.messageCreatedBy ?? "user",
creationSource: input.messageCreationSource ?? "web",
messageId: MessageId.make(`message-${input.attemptId}`),
text: input.text,
attachments: input.attachments,
},
modelSelection: input.modelSelection ?? CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: input.runtimePolicy ?? CLAUDE_TEST_RUNTIME_POLICY,
};
}
describe("ClaudeAdapterV2 runtime query policy", () => {
it.each([
"-- --thinking-display omitted",
"--thinking-display summarized -- --thinking-display omitted",
])("does not treat operands after -- as SDK flags: %s", (launchArgs) => {
const options = ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
nativeThreadId: "thinking-thread",
resume: false,
cwd: "/workspace",
settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs },
});
assert.deepEqual(options.thinking, { type: "adaptive", display: "summarized" });
assert.equal(options.extraArgs?.["thinking-display"], "summarized");
});
it.each([
["--permission-mode acceptEdits", "acceptEdits"],
["--dangerously-skip-permissions", "bypassPermissions"],
["--dangerously-skip-permissions --permission-mode plan", "plan"],
])("folds %s into the SDK permission mode", (launchArgs, expected) => {
const options = ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
nativeThreadId: "native-permission-override",
resume: false,
cwd: "/workspace",
permissionMode: "default",
settings: { ...AUTO_COMPACT_CLAUDE_SETTINGS, launchArgs },
});
assert.equal(options.permissionMode, expected);
assert.isUndefined(options.extraArgs?.["permission-mode"]);
assert.isUndefined(options.extraArgs?.["dangerously-skip-permissions"]);
});
it("passes every --add-dir launch directory to Claude", () => {
const options = ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
nativeThreadId: "native-add-dir",
resume: false,
cwd: "/workspace",
attachmentsDir: "/attachments",
settings: {
...AUTO_COMPACT_CLAUDE_SETTINGS,
launchArgs: "--add-dir ../apps ../lib --verbose --add-dir=/shared",
},
});
assert.deepEqual(options.additionalDirectories, [
"/workspace",
"/attachments",
"../apps",
"../lib",
"/shared",
]);
assert.isUndefined(options.extraArgs?.["add-dir"]);
});
it("gives delegated children Claude's subagent prompt cache TTL", () => {
const lineage = (relationshipToParent: "fork" | "subagent" | null) => ({
lineage: {
parentThreadId: null,
relationshipToParent,
rootThreadId: ThreadId.make("thread-root"),
},
});
const env = { PATH: "/bin" };
const ttl = (environment: NodeJS.ProcessEnv, ...args: Parameters<typeof lineage>) =>
ClaudeAdapterV2.claudeQueryEnvironment(environment, lineage(...args), "5m")
.CLAUDE_CODE_PROMPT_CACHE_TTL;
assert.equal(ttl(env, "subagent"), "5m");
assert.isUndefined(ttl(env, null));
assert.isUndefined(ttl(env, "fork"));
assert.equal(ttl({ ...env, CLAUDE_CODE_PROMPT_CACHE_TTL: "1h" }, "subagent"), "1h");
assert.strictEqual(
ClaudeAdapterV2.claudeQueryEnvironment(env, lineage("subagent"), undefined),
env,
);
});
it("pins Claude's auto tool search on through flag settings", () => {
const override = ClaudeAdapterV2.claudeToolSearchOverride;
for (const value of ["auto", "auto:10", "auto:99.5", "auto:x", "auto:Infinity"]) {
assert.equal(override(value), "true", value);
}
for (const value of [
undefined,
"true",
"false",
"auto:0",
"auto:-5",
"auto:100",
"auto:1e2",
"auto:1_000",
"auto:1,000",
"AUTO",
]) {
assert.isUndefined(override(value), String(value));
}
const options = ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
nativeThreadId: "native-tool-search",
resume: false,
cwd: "/workspace",
sdkSettings: { env: { OTHER: "kept" } },
toolSearchOverride: "true",
});
assert.deepEqual((options.settings as { env?: Record<string, string> }).env, {
OTHER: "kept",
ENABLE_TOOL_SEARCH: "true",
});
});
it("projects AskUserQuestion input with question text as the answer key", () => {
const preview = "\n **Proposed change**\n\n```ts\n\tconst enabled = true;\n```\n ";
assert.deepEqual(
ClaudeAdapterV2.claudeUserInputQuestions({
questions: [
{
header: "Approach",
question: "Which approach?",
options: [
{ label: "Simple", description: "Use fewer moving parts", preview },
{ label: "Safe", description: "Keep the current setup" },
],
multiSelect: true,
},
],
}),
[
{
id: "Which approach?",
header: "Approach",
question: "Which approach?",
options: [
{ label: "Simple", description: "Use fewer moving parts", preview },
{ label: "Safe", description: "Keep the current setup" },
],
multiSelect: true,
},
],
);
const sdkAnswers: NonNullable<AskUserQuestionInput["answers"]> =
ClaudeAdapterV2.claudeSdkUserInputAnswers({
"Which approach?": ["Simple", "Safe"],
"Deploy now?": "Yes",
});
assert.deepEqual(sdkAnswers, {
"Which approach?": "Simple, Safe",
"Deploy now?": "Yes",
});
assert.isTrue(
ClaudeAdapterV2.ClaudeProviderCapabilitiesV2.planning.supportsStructuredQuestions,
);
});
it("maps canonical read-only never policy to Claude dontAsk with read-only tools", () => {
const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace",
approvalPolicy: "never",
sandboxPolicy: {
type: "readOnly",
access: { type: "fullAccess" },
networkAccess: false,
},
}),
);
assert.deepEqual(queryPolicy, {
permissionMode: "dontAsk",
tools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
allowedTools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
installPermissionCallback: false,
});
});
it("does not auto-allow reads for canonical restricted read-only never policy", () => {
const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace",
approvalPolicy: "never",
sandboxPolicy: {
type: "readOnly",
access: {
type: "restricted",
includePlatformDefaults: false,
readableRoots: [],
},
networkAccess: false,
},
}),
);
assert.deepEqual(queryPolicy, {
permissionMode: "dontAsk",
tools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
installPermissionCallback: false,
});
});
it("maps default full-access policy to Claude bypass permissions", () => {
const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace",
}),
);
assert.deepEqual(queryPolicy, {
permissionMode: "bypassPermissions",
allowDangerouslySkipPermissions: true,
installPermissionCallback: false,
});
});
it("keeps approval checks when Full access must fall back to an allowed Claude mode", () => {
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace",
approvalPolicy: "never",
});
assert.deepEqual(
ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(runtimePolicy, {
bypassDisabled: true,
autoDisabled: false,
}),
{ permissionMode: "auto", installPermissionCallback: true },
);
assert.deepEqual(
ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(runtimePolicy, {
bypassDisabled: true,
autoDisabled: true,
}),
{ permissionMode: "default", installPermissionCallback: true },
);
});
it("keeps approval-required mode interactive with danger-full-access sandboxing", () => {
const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "approval-required",
interactionMode: "default",
cwd: "/workspace",
sandboxPolicy: {
type: "dangerFullAccess",
},
}),
);
assert.deepEqual(queryPolicy, {
permissionMode: "default",
installPermissionCallback: true,
});
});
});
describe("ClaudeAdapterV2 MCP query overrides", () => {
const T3_MCP_SERVERS = {
"t3-code": {
type: "http",
url: "http://127.0.0.1:43123/mcp",
headers: {
Authorization: "Bearer secret-claude-token",
},
timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,
},
} as const;
const mcpSessionFor = (
threadId: ThreadId,
authorizationHeader = "Bearer secret-claude-token",
): McpProviderSession.McpProviderSessionConfig => ({
environmentId: EnvironmentId.make(`environment-${threadId}`),
threadId,
providerSessionId: `mcp-session-${threadId}`,
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
endpoint: "http://127.0.0.1:43123/mcp",
authorizationHeader,
browserToolsAvailable: true,
});
it("pre-approves only read-only t3-code tools in a read-only sandbox", () => {
const threadId = ThreadId.make("thread-claude-mcp-read-only");
const mcpSession = mcpSessionFor(threadId);
const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({
mcpSession,
readOnlySandbox: true,
allowedTools: [...ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS],
});
assert.deepEqual(overrides, {
allowedTools: [
...ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
...ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS,
],
mcpServers: T3_MCP_SERVERS,
});
assert.isFalse(overrides.allowedTools?.includes(ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD));
});
it("invalidates live-query reuse when MCP credentials rotate", () => {
const threadId = ThreadId.make("thread-claude-mcp-credential-rotation");
const mcpSession = mcpSessionFor(threadId);
const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "approval-required",
interactionMode: "default",
cwd: "/workspace",
}),
);
const initialKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
queryPolicy,
ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: false }),
);
const rotatedKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
queryPolicy,
ClaudeAdapterV2.claudeMcpQueryOverrides({
mcpSession: mcpSessionFor(threadId, "Bearer rotated-claude-token"),
readOnlySandbox: false,
}),
);
assert.notEqual(rotatedKey, initialKey);
});
it("matches the read-only allowlist to the orchestrator toolkit annotations", () => {
const readOnlyToolNames = [
...Object.values(OrchestratorToolkit.tools),
...Object.values(ThreadToolkit.tools),
...Object.values(WorktreeToolkit.tools),
...Object.values(ProjectToolkit.tools),
...Object.values(EnvironmentToolkit.tools),
...Object.values(PreviewControlsToolkit.tools),
...Object.values(HtmlToolkit.tools),
]
.filter((tool) => Context.get(tool.annotations, Tool.Readonly))
.map((tool) => `mcp__t3-code__${tool.name}`)
.sort();
assert.deepEqual(
[...ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS].sort(),
readOnlyToolNames,
);
});
});
describe("ClaudeAdapterV2 native protocol logging", () => {
it("injects thread-scoped MCP configuration without logging the credential", () => {
const threadId = ThreadId.make("thread-claude-mcp");
const mcpSession = {
environmentId: EnvironmentId.make("environment-claude-mcp"),
threadId,
providerSessionId: "mcp-session-claude",
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
endpoint: "http://127.0.0.1:43123/mcp",
authorizationHeader: "Bearer secret-claude-token",
browserToolsAvailable: true,
};
const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({
mcpSession,
readOnlySandbox: false,
allowedTools: ["Read"],
});
assert.deepEqual(overrides, {
allowedTools: ["Read", "mcp__t3-code__*"],
mcpServers: {
"t3-code": {
type: "http",
url: "http://127.0.0.1:43123/mcp",
headers: {
Authorization: "Bearer secret-claude-token",
},
timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,
},
},
});
const options = ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
nativeThreadId: "native-thread-claude-mcp",
resume: false,
cwd: "/workspace",
allowedTools: overrides.allowedTools ?? [],
mcpServers: overrides.mcpServers ?? {},
environment: {},
});
assert.isObject(options.systemPrompt);
const systemPrompt = options.systemPrompt as {
readonly type: string;
readonly preset: string;
readonly append?: string;
};
assert.equal(systemPrompt.type, "preset");
assert.equal(systemPrompt.preset, "claude_code");
assert.include(systemPrompt.append ?? "", "Use `delegate_task`");
assert.include(systemPrompt.append ?? "", "call `t3_background_wait`");
assert.notInclude(systemPrompt.append ?? "", "## T3 Code devices");
const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
assert.equal(logged.hasMcpServers, true);
assert.notInclude(JSON.stringify(logged), "secret-claude-token");
});
it("logs --settings key names without their values", () => {
const options = ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
nativeThreadId: "native-thread-claude-settings-log",
resume: false,
cwd: "/workspace",
sdkSettings: { env: { ANTHROPIC_API_KEY: "secret-settings-key" } },
});
const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
assert.deepEqual(logged.settingKeys, ["env", "showThinkingSummaries"]);
assert.notInclude(JSON.stringify(logged), "secret-settings-key");
});
});
describe("ClaudeAdapterV2 device instructions", () => {
const options = (input: { readonly mcp: boolean; readonly deviceToolsAvailable: boolean }) =>
ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-5-5",
},
nativeThreadId: "native-thread-claude-devices",
resume: false,
cwd: "/workspace",
...(input.mcp
? { mcpServers: { "t3-code": { type: "http" as const, url: "http://127.0.0.1/mcp" } } }
: {}),
deviceToolsAvailable: input.deviceToolsAvailable,
environment: {},
});
const append = (input: { readonly mcp: boolean; readonly deviceToolsAvailable: boolean }) =>
(options(input).systemPrompt as { readonly append?: string }).append ?? "";
it("gives a session with device access the device block and the ToolSearch line to load it", () => {
const text = append({ mcp: true, deviceToolsAvailable: true });
assert.include(text, T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH);
assert.include(text, "Use `delegate_task`");
});
it("leaves the device block out without device access or without T3 tools", () => {
assert.notInclude(append({ mcp: true, deviceToolsAvailable: false }), "## T3 Code devices");
assert.notInclude(append({ mcp: false, deviceToolsAvailable: true }), "## T3 Code devices");
});
it("gives native subagents the device block only in a session with device access", async () => {
// Subagents start from their task prompt, not the parent's system prompt.
const subagentContext = (input: {
readonly mcp: boolean;
readonly deviceToolsAvailable: boolean;
}) =>
Promise.all(
(options(input).hooks?.SubagentStart ?? []).flatMap((matcher) =>
matcher.hooks.map((hook) =>
hook(
{
hook_event_name: "SubagentStart",
agent_id: "agent-1",
agent_type: "general-purpose",
session_id: "native-thread-claude-devices",
transcript_path: "/transcript.jsonl",
cwd: "/workspace",
},
undefined,
{ signal: new AbortController().signal },
),
),
),
);
assert.deepEqual(await subagentContext({ mcp: true, deviceToolsAvailable: true }), [
{
hookSpecificOutput: {
hookEventName: "SubagentStart",
additionalContext: T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH,
},
},
]);
assert.deepEqual(await subagentContext({ mcp: true, deviceToolsAvailable: false }), []);
assert.deepEqual(await subagentContext({ mcp: false, deviceToolsAvailable: true }), []);
});
});
describe("ClaudeAdapterV2 context usage", () => {
it("dates cache expiry from the request start, not the response end", () => {
const usage = ClaudeAdapterV2.claudeProviderTurnTokenUsage(
{
input_tokens: 1,
output_tokens: 1,
cache_creation: { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 300 },
},
null,
"2026-08-29T00:03:00.000Z",
"",
DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"),
);
assert.strictEqual(usage.promptCacheExpiresAt, "2026-08-29T00:05:00.000Z");
});
});
describe("ClaudeAdapterV2 approval presentation", () => {
it("marks asks that full access could not auto-allow and keeps the CLI's reason", () => {
const presentation = ClaudeAdapterV2.claudeApprovalPresentation({
permissionMode: "bypassPermissions",
prompt: 'Claude wants to run rm -r -- "$rr/$h"',
callbackOptions: {
decisionReason: "\u001b[33mDangerous rm on a path built from a variable\u001b[39m",
suppressAlwaysAllowRule: true,
},
});
assert.deepEqual(presentation, {
reason: "Dangerous rm on a path built from a variable",
fullAccessOverride: "provider_check",
options: [
{ decision: "decline", label: "Decline" },
{ decision: "accept", label: "Approve" },
],
});
});
it("attributes a bypass ask to the user's ask rule when one matched", () => {
const presentation = ClaudeAdapterV2.claudeApprovalPresentation({
permissionMode: "bypassPermissions",
prompt: "Claude wants to run git push",
callbackOptions: {
matchedAskRule: { source: "userSettings", toolName: "Bash", ruleContent: "git push:*" },
},
});
assert.deepEqual(presentation, { fullAccessOverride: "ask_rule" });
});
it("adds nothing to ordinary approvals outside full access", () => {
const presentation = ClaudeAdapterV2.claudeApprovalPresentation({
permissionMode: "default",
prompt: "Run make?",
callbackOptions: { decisionReason: "Run make?" },
});
assert.deepEqual(presentation, {});
});
});
describe("ClaudeAdapterV2 session permissions", () => {
// regression: #15892 an explicit user refusal must stay user_reject, not a tool failure
it("keeps explicit user refusals classified as user_reject", () => {
const result = ClaudeAdapterV2.permissionResultFromDecision({
toolName: "Bash",
decision: "decline",
toolInput: { command: "make" },
toolUseID: "denied-build",
});
assert.equal(result.behavior, "deny");
if (result.behavior !== "deny") return;
assert.equal(result.decisionClassification, "user_reject");
assert.equal(result.message, "User declined tool execution.");
assert.equal(result.interrupt, undefined);
});
it("forces suggested permission updates to session scope", () => {
const result = ClaudeAdapterV2.permissionResultFromDecision({
toolName: "Bash",
decision: "acceptForSession",
toolInput: { command: "git status" },
toolUseID: "tool-1",
suggestions: [
{
type: "addRules",
rules: [{ toolName: "Bash", ruleContent: "git status" }],
behavior: "allow",
destination: "localSettings",
},
],
});
assert.equal(result.behavior, "allow");
if (result.behavior !== "allow") {
return;
}
assert.deepEqual(result.updatedPermissions, [
{
type: "addRules",
rules: [{ toolName: "Bash", ruleContent: "git status" }],
behavior: "allow",
destination: "session",
},
]);
// Under an administrator's ceiling a suggested mode switch is dropped; the rule stays.
const managed = ClaudeAdapterV2.permissionResultFromDecision({
toolName: "Edit",
decision: "acceptForSession",
toolInput: {},
toolUseID: "tool-2",
managedCeiling: true,
suggestions: [
{ type: "setMode", mode: "acceptEdits", destination: "session" },
{
type: "addRules",
rules: [{ toolName: "Edit" }],
behavior: "allow",
destination: "session",
},
],
});
assert.deepEqual(managed.behavior === "allow" ? managed.updatedPermissions : undefined, [
{
type: "addRules",
rules: [{ toolName: "Edit" }],
behavior: "allow",
destination: "session",
},
]);
});
it("adds a whole-tool session rule when Claude offers no suggestion", () => {
const result = ClaudeAdapterV2.permissionResultFromDecision({
toolName: "mcp__t3__custom_tool",
decision: "acceptForSession",
toolInput: {},
toolUseID: "tool-2",
});
assert.equal(result.behavior, "allow");
if (result.behavior !== "allow") {
return;
}
assert.deepEqual(result.updatedPermissions, [
{
type: "addRules",
rules: [{ toolName: "mcp__t3__custom_tool" }],
behavior: "allow",
destination: "session",
},
]);
});
});
describe("ClaudeAdapterV2 Auto-accept edits", () => {
it.effect("asks before a command instead of allowing it", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-claude-accept-edits-",
});
let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
environment: {},
attachmentsDir,
fileSystem,
path: yield* Path.Path,
random: yield* SecureRandom.SecureRandom,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-accept-edits"),
open: (input) =>
Effect.sync(() => {
openedOptions = input.options;
return {
messages: Stream.never,
offer: () => Effect.void,
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
backgroundTasks: () => Effect.succeed(false),
mcpServerStatus: Effect.succeed([]),
readMcpResource: () => Effect.die("unexpected MCP resource read"),
callMcpTool: () => Effect.die("unexpected MCP tool call"),
listPermissionRules: Effect.die("unexpected permission rules read"),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
};
}),
forkSession: () => Effect.die("unused"),
subagentLaunchToolUseId: () => Effect.succeed(null),
assertComplete: Effect.void,
},
});
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "auto-accept-edits",
interactionMode: "default",
cwd: "/workspace",
});
const threadId = ThreadId.make("thread-claude-accept-edits");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-accept-edits"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy,
});
const now = yield* DateTime.now;
yield* runtime.startTurn(
makeClaudeTestTurnInput({
threadId,
providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-accept-edits"),
text: "Run node.",
attachments: [],
runtimePolicy,
}),
);
assert.equal(openedOptions?.permissionMode, "acceptEdits");
const canUseTool = openedOptions?.canUseTool;
assert.isFunction(canUseTool);
const requestEvent = yield* runtime.events.pipe(
Stream.takeUntil(
(event) =>
event.type === "turn_item.updated" && event.turnItem.type === "approval_request",
),
Stream.runCollect,
Effect.forkScoped,
);
const command = { command: "node -e 'console.log(42)'" };
const decision = yield* Effect.promise(() =>
canUseTool!("Bash", command, {
signal: new AbortController().signal,
toolUseID: "tool-bash-accept-edits",
requestId: "request-bash-accept-edits",
description: "Check the Node runtime",
}),
).pipe(Effect.forkScoped);
const first = yield* Effect.raceFirst(
Fiber.join(requestEvent).pipe(
Effect.map((event) => ({ type: "request", event }) as const),
),
Fiber.join(decision).pipe(
Effect.map((result) => ({ type: "decision", result }) as const),
),
);
assert.equal(first.type, "request", "the command ran without asking");
if (first.type !== "request") return;
const event = first.event.find((event) => event.type === "runtime_request.updated");
assert.equal(event?.runtimeRequest.kind, "command");
const approval = first.event.findLast((event) => event.type === "turn_item.updated");
assert.equal(
approval?.turnItem.type === "approval_request" ? approval.turnItem.prompt : undefined,
command.command,
);
yield* runtime.respondToRuntimeRequest({
requestId: event!.runtimeRequest.id,
decision: "accept",
});
assert.equal((yield* Fiber.join(decision))?.behavior, "allow");
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
),
);
});
describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
const startTurnWithLaunchArgs = Effect.fnUntraced(function* (launchArgs: string, cwd: string) {
const fileSystem = yield* FileSystem.FileSystem;
const opened: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOptions> = [];
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs },
environment: {},
attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-" }),
fileSystem,
path: yield* Path.Path,
random: yield* SecureRandom.SecureRandom,
idAllocator: yield* IdAllocator.IdAllocatorV2,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-append-file"),
open: (input) =>
Effect.sync(() => {
opened.push(input.options);
return {
messages: Stream.never,
offer: () => Effect.void,
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
backgroundTasks: () => Effect.succeed(false),
mcpServerStatus: Effect.succeed([]),
readMcpResource: () => Effect.die("unexpected MCP resource read"),
callMcpTool: () => Effect.die("unexpected MCP tool call"),
listPermissionRules: Effect.die("unexpected permission rules read"),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
};
}),
forkSession: () => Effect.die("unused"),
subagentLaunchToolUseId: () => Effect.succeed(null),
assertComplete: Effect.void,
},
});
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd,
});
const threadId = ThreadId.make("thread-claude-append-file");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-append-file"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy,
});
const exit = yield* runtime
.startTurn(
makeClaudeTestTurnInput({
threadId,
providerThread,
now: yield* DateTime.now,
attemptId: RunAttemptId.make("attempt-claude-append-file"),
text: "What is the sentinel?",
attachments: [],
runtimePolicy,
}),
)
.pipe(Effect.exit);
return { exit, opened };
});
const appendSystemPrompt = (options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined) =>
(options?.systemPrompt as { readonly append?: string } | undefined)?.append;
it.effect("sends append launch arguments to Claude after the T3 instructions", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
yield* fileSystem.writeFileString(NodePath.join(cwd, "rules.md"), "File sentinel\n");
const plain = yield* startTurnWithLaunchArgs("", cwd);
const { exit, opened } = yield* startTurnWithLaunchArgs(
'--append-system-prompt "Inline sentinel" --append-system-prompt-file rules.md --system-prompt Replacement',
cwd,
);
assert.isTrue(Exit.isSuccess(exit));
assert.lengthOf(opened, 1);
assert.equal(
appendSystemPrompt(opened[0]),
`${appendSystemPrompt(plain.opened[0])}\n\nFile sentinel\n\nInline sentinel`,
);
assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt"]);
assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt-file"]);
assert.equal(opened[0]!.extraArgs?.["system-prompt"], "Replacement");
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
),
);
// regression: #15073 the SDK replaced the --settings launch argument with T3's settings
it.effect.each([
`--settings '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}'`,
"--settings user-settings.json",
])("merges %s beneath T3's settings", (launchArgs) =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-settings-" });
yield* fileSystem.writeFileString(
NodePath.join(cwd, "user-settings.json"),
'{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}',
);
const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
assert.isTrue(Exit.isSuccess(exit));
assert.deepInclude(opened[0]!.settings, {
skillOverrides: { lint: "off" },
showThinkingSummaries: true,
});
assert.isUndefined(opened[0]!.extraArgs?.["settings"]);
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
),
);
// regression: #20413 malformed append-system-prompt launch args fail before a query opens
it.effect.each([
[
"--append-system-prompt-file missing.md",
(cwd: string) =>
new ClaudeAdapterV2.ClaudeAppendSystemPromptFileError({
path: NodePath.join(cwd, "missing.md"),
}).message,
],
[
"--append-system-prompt-file",
() =>
new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
flag: "--append-system-prompt-file",
}).message,
],
[
"--append-system-prompt-file=",
() =>
new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
flag: "--append-system-prompt-file",
}).message,
],
[
"--append-system-prompt",
() =>
new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({
flag: "--append-system-prompt",
}).message,
],
[
"--settings missing.json",
(cwd: string) =>
new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({
path: NodePath.join(cwd, "missing.json"),
}).message,
],
["--settings '{not json}'", () => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message],
// Without a closing brace this must not become a file path that echoes the secret.
[
`--settings '{"env":{"ANTHROPIC_API_KEY":"secret-settings-key"},'`,
() => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message,
],
] as const)("fails the turn before opening Claude for %s", ([launchArgs, expectedMessage]) =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
assert.lengthOf(opened, 0);
assert.isTrue(Exit.isFailure(exit));
if (!Exit.isFailure(exit)) return;
assert.equal(
makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message,
expectedMessage(cwd),
);
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
),
);
});
describe("ClaudeAdapterV2 approval cancellation", () => {
it.effect("observes an approval signal that was already aborted", () =>
Effect.gen(function* () {
const decision = yield* Deferred.make<{
decision: ProviderApprovalDecision;
feedback?: string;
}>();
const result = yield* ClaudeAdapterV2.awaitClaudeApprovalDecision(
decision,
AbortSignal.abort(),
);
assert.deepEqual(result, { decision: "cancel" });
}),
);
});
describe("ClaudeAdapterV2 MCP elicitation acceptance", () => {
const form = (
properties: Record<string, unknown>,
required?: ReadonlyArray<string>,
): ElicitationRequest => ({
serverName: "deploys",
message: "Deploy web?",
mode: "form",
requestedSchema: { type: "object", properties, ...(required ? { required } : {}) },
});
it("answers an empty-properties form with empty content", () => {
assert.deepEqual(ClaudeAdapterV2.claudeMcpElicitationAcceptance(form({})), {
action: "accept",
content: {},
});
});
it("picks the one-time choice however the server spells it", () => {
for (const choice of [
"allow_once",
"Allow",
"accept_once",
"Approve once",
"allow_this_time",
"allow_once_only",
]) {
assert.deepEqual(
ClaudeAdapterV2.claudeMcpElicitationAcceptance(
form({ decision: { type: "string", enum: ["disallow", choice, "always"] } }, [
"decision",
]),
),
{ action: "accept", content: { decision: choice } },
);
}
});
it("answers a persistence toggle with false", () => {
assert.deepEqual(
ClaudeAdapterV2.claudeMcpElicitationAcceptance(
form({ remember: { type: "boolean", title: "Always allow" } }, ["remember"]),
),
{ action: "accept", content: { remember: false } },
);
});
it("leaves out optional fields the card does not show", () => {
assert.deepEqual(
ClaudeAdapterV2.claudeMcpElicitationAcceptance(
form({ scope: { type: "string", enum: ["once", "always"], default: "always" } }),
),
{ action: "accept", content: { scope: "once" } },
);
assert.deepEqual(
ClaudeAdapterV2.claudeMcpElicitationAcceptance(
form({ limit: { type: "number", default: 500 } }),
),
{ action: "accept", content: {} },
);
});
it("has no answer for URL mode or a form asking for a value", () => {
for (const request of [
{ serverName: "deploys", message: "Sign in", mode: "url", url: "https://example.com" },
form({ reason: { type: "string" } }, ["reason"]),
form({ grant: { type: "string", enum: ["always", "session"] } }, ["grant"]),
form({ grant: { type: "string", enum: ["deny", "always"], default: "always" } }, ["grant"]),
form({ limit: { type: "number", default: 500 } }, ["limit"]),
{ serverName: "deploys", message: "Deploy web?", mode: "form" },
] satisfies ReadonlyArray<ElicitationRequest>) {
assert.isUndefined(ClaudeAdapterV2.claudeMcpElicitationAcceptance(request));
}
});
});
const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(function* (
binaryPath: string,
environment: ResolvedProviderInstanceEnvironment = [],
) {
const executablePaths: Array<string | undefined> = [];
const taskToolEnvironment: Array<string | undefined> = [];
const adapter = yield* ClaudeAdapterV2.createClaudeAdapterV2(
{
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
displayName: undefined,
environment,
enabled: true,
config: { ...DEFAULT_CLAUDE_SETTINGS, binaryPath },
},
{},
).pipe(
Effect.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-claude-binary-path-",
}),
),
Effect.provideService(ClaudeAdapterV2.ClaudeAgentSdkQueryRunner, {
allocateSessionId: Effect.succeed("native-thread-claude-binary-path"),
open: (input) =>
Effect.sync(() => {
executablePaths.push(input.options.pathToClaudeCodeExecutable);
taskToolEnvironment.push(input.options.env?.CLAUDE_CODE_ENABLE_TODO_TOOLS);
return {
messages: Stream.never,
offer: () => Effect.void,
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
backgroundTasks: () => Effect.succeed(false),
mcpServerStatus: Effect.succeed([]),
readMcpResource: () => Effect.die("unexpected MCP resource read"),
callMcpTool: () => Effect.die("unexpected MCP tool call"),
listPermissionRules: Effect.die("unexpected permission rules read"),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
};
}),
forkSession: () => Effect.die("unused"),
subagentLaunchToolUseId: () => Effect.succeed(null),
assertComplete: Effect.void,
}),
);
const threadId = ThreadId.make("thread-claude-binary-path");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-binary-path"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
yield* runtime.startTurn(
makeClaudeTestTurnInput({
threadId,
providerThread,
now: yield* DateTime.now,
attemptId: RunAttemptId.make("attempt-claude-binary-path"),
text: "hello",
attachments: [],
}),
);
return { executablePaths, taskToolEnvironment };
});
describe("ClaudeAdapterV2 executable path", () => {
it.effect("follows a bare claude on Windows to the npm package executable", () =>
Effect.scoped(
Effect.gen(function* () {
const npmDir = "C:\\Users\\dev\\AppData\\Roaming\\npm";
const packageExe = `${npmDir}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`;
const { executablePaths } = yield* captureSdkExecutablePaths("claude").pipe(
Effect.provideService(HostProcess.Platform, "win32"),
Effect.provideService(SpawnExecutableResolution, () => `${npmDir}\\claude.cmd`),
Effect.provideService(ClaudeExecutableFileCheck, (filePath) => filePath === packageExe),
);
assert.deepEqual(executablePaths, [packageExe]);
}),
).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
);
});
describe("ClaudeAdapterV2 resumeThread", () => {
it.effect("fails for a transcript without messages so a fresh session replaces it", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const configDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-claude-empty-session-",
});
const projectDir = path.join(configDir, "projects", "-workspace");
yield* fileSystem.makeDirectory(projectDir, { recursive: true });
yield* fileSystem.writeFileString(
path.join(projectDir, "native-thread-empty.jsonl"),
[
`{"type":"last-prompt","lastPrompt":"hello","sessionId":"native-thread-empty"}`,
`{"type":"atis-latch","atis":"","sessionId":"native-thread-empty"}`,
`{"type":"cost-state","sessionId":"native-thread-empty","totalCostUSD":0}`,
"",
].join("\n"),
);
yield* fileSystem.writeFileString(
path.join(projectDir, "native-thread-saved.jsonl"),
`{"type":"user","message":{"role":"user","content":"hello"},"sessionId":"native-thread-saved"}\n`,
);
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
environment: { CLAUDE_CONFIG_DIR: configDir },
attachmentsDir: configDir,
fileSystem,
path,
random: yield* SecureRandom.SecureRandom,
idAllocator: yield* IdAllocator.IdAllocatorV2,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-empty"),
open: () => Effect.die("unused"),
forkSession: () => Effect.die("unused"),
subagentLaunchToolUseId: () => Effect.succeed(null),
assertComplete: Effect.void,
},
});
const threadId = ThreadId.make("thread-claude-empty-session");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-empty-session"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const error = yield* Effect.flip(runtime.resumeThread({ providerThread }));
assert.equal(error._tag, "ProviderAdapterResumeThreadError");
const saved = yield* runtime.resumeThread({
providerThread: {
...providerThread,
nativeThreadRef: {
driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
nativeId: "native-thread-saved",
strength: "strong",
},
},
});
assert.equal(saved.nativeThreadRef?.nativeId, "native-thread-saved");
const missing = yield* runtime.resumeThread({
providerThread: {
...providerThread,
nativeThreadRef: {
driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
nativeId: "native-thread-missing",
strength: "strong",
},
},
});
assert.equal(missing.nativeThreadRef?.nativeId, "native-thread-missing");
}),
).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
);
});
describe("ClaudeAdapterV2 resume compaction", () => {
it.effect("resolves and cancels the SDK resume dialog through structured runtime input", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-claude-resume-",
});
let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
environment: {},
attachmentsDir,
fileSystem,
path: yield* Path.Path,
random: yield* SecureRandom.SecureRandom,
idAllocator,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-resume"),
open: (input) =>
Effect.sync(() => {
openedOptions = input.options;
return {
messages: Stream.never,
offer: () => Effect.void,
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
backgroundTasks: () => Effect.succeed(false),
mcpServerStatus: Effect.succeed([]),
readMcpResource: () => Effect.die("unexpected MCP resource read"),
callMcpTool: () => Effect.die("unexpected MCP tool call"),
listPermissionRules: Effect.die("unexpected permission rules read"),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
};
}),
forkSession: () => Effect.die("unused"),
subagentLaunchToolUseId: () => Effect.succeed(null),
assertComplete: Effect.void,
},
});
const threadId = ThreadId.make("thread-claude-resume");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-resume"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const now = yield* DateTime.now;
yield* runtime.startTurn(
makeClaudeTestTurnInput({
threadId,
providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-resume"),
text: "continue",
attachments: [],
}),
);
const callback = openedOptions?.onUserDialog;
assert.isFunction(callback);
const canUseTool = openedOptions?.canUseTool;
assert.isFunction(canUseTool);
const shellSafetyReason =
"Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed";
for (const [safetyIndex, { askRule, reason }] of [
{ askRule: false, reason: shellSafetyReason },
{ askRule: true, reason: shellSafetyReason },
{
askRule: false,
reason:
"Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.",
},
{ askRule: false, reason: "This shell -c script runs rm and could not be checked" },
{ askRule: false, reason: "A permission rule denies a command in this shell -c script" },
].entries()) {
const safetyRequest = yield* runtime.events.pipe(
Stream.filter((event) => event.type === "runtime_request.updated"),
Stream.runHead,
Effect.forkScoped,
);
const safetySignal = yield* Effect.abortSignal;
const safetyDecision = yield* Effect.promise(() =>
canUseTool!(
"Bash",
{ command: "for pair in a b; do echo $pair; done" },
{
signal: safetySignal,
toolUseID: `tool-shell-safety-${safetyIndex}`,
requestId: `request-shell-safety-${safetyIndex}`,
decisionReason: `\u001b[33m${reason}\u001b[39m`,
suppressAlwaysAllowRule: true,
...(askRule
? {
matchedAskRule: {
source: "userSettings" as const,
toolName: "Bash",
ruleContent: "*",
},
}
: {}),
},
),
).pipe(Effect.forkScoped);
const safety = yield* Effect.raceFirst(
Fiber.join(safetyDecision).pipe(
Effect.map((result) => ({ type: "decision", result }) as const),
),
Fiber.join(safetyRequest).pipe(
Effect.map((event) => ({ type: "approval", event }) as const),
),
);
assert.equal(safety.type, askRule ? "approval" : "decision");
if (safety.type === "decision") {
assert.equal(safety.result?.behavior, "deny");
if (safety.result?.behavior === "deny") {
assert.include(safety.result.message, reason);
assert.notInclude(safety.result.message, "\u001b[");
}
} else if (
Option.isSome(safety.event) &&
safety.event.value.type === "runtime_request.updated"
) {
yield* runtime.respondToRuntimeRequest({
requestId: safety.event.value.runtimeRequest.id,
decision: "decline",
});
assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny");
}
yield* Fiber.interrupt(safetyRequest);
}
const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`;
const questionRequestEvent = yield* runtime.events.pipe(
Stream.filter((event) => event.type === "runtime_request.updated"),
Stream.runHead,
Effect.forkScoped,
);
const questionResult = yield* Effect.promise(() =>
canUseTool!(
"AskUserQuestion",
{
questions: [
{
header: "Target",
question: longQuestion,
options: [
{ label: "Production", description: "Deploy to production." },
{ label: "Staging", description: "Deploy to staging." },
],
multiSelect: true,
},
],
},
{
signal: new AbortController().signal,
toolUseID: "tool-question-full-access",
requestId: "request-question-full-access",
},
),
).pipe(Effect.forkScoped);
const questionEvent = yield* Fiber.join(questionRequestEvent);
assert.isTrue(Option.isSome(questionEvent));
if (
Option.isNone(questionEvent) ||
questionEvent.value.type !== "runtime_request.updated"
) {
return;
}
yield* runtime.respondToRuntimeRequest({
requestId: questionEvent.value.runtimeRequest.id,
answers: { [longQuestion]: ["Production", "Staging"] },
});
assert.deepEqual(yield* Fiber.join(questionResult), {
behavior: "allow",
updatedInput: {
questions: [
{
header: "Target",
question: longQuestion,
options: [
{ label: "Production", description: "Deploy to production." },
{ label: "Staging", description: "Deploy to staging." },
],
multiSelect: true,
},
],
answers: { [longQuestion]: "Production, Staging" },
},
toolUseID: "tool-question-full-access",
});
const longPlan = `# Deployment plan\n\n${"Validate every region before promotion.\n".repeat(120)}`;
const proposedPlanEvent = yield* runtime.events.pipe(
Stream.filter((event) => event.type === "plan.updated"),
Stream.runHead,
Effect.forkScoped,
);
const exitPlanResult = yield* Effect.promise(() =>
canUseTool!(
"ExitPlanMode",
{ plan: longPlan },
{
signal: new AbortController().signal,
toolUseID: "tool-exit-plan-full-access",
requestId: "request-exit-plan-full-access",
},
),
);
assert.deepEqual(exitPlanResult, {
behavior: "deny",
message: