Skip to content
TypeScript

fix(claude): honor effective bypass restrictions (#21806)

Julius Marminge0b84aa3fa785
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 82e3e0d423b..b2738b11776 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -5,6 +5,9 @@ import * as NodeOS from "node:os";
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 {
Query as ClaudeQuery,
SDKMessage,
@@ -103,6 +106,18 @@ import {
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 decodeUserInputQuestions = Schema.decodeUnknownSync(
Schema.Array(OrchestrationV2UserInputQuestion),
);
@@ -1503,22 +1518,6 @@ describe("ClaudeAdapterV2 resume compaction", () => {
assert.isFunction(callback);
const canUseTool = openedOptions?.canUseTool;
assert.isFunction(canUseTool);
- const ordinaryToolResult = yield* Effect.promise(() =>
- canUseTool!(
- "Bash",
- { command: "pwd" },
- {
- signal: new AbortController().signal,
- toolUseID: "tool-bash-full-access",
- requestId: "request-bash-full-access",
- },
- ),
- );
- assert.deepEqual(ordinaryToolResult, {
- behavior: "allow",
- updatedInput: { command: "pwd" },
- toolUseID: "tool-bash-full-access",
- });
const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`;
const questionRequestEvent = yield* runtime.events.pipe(
Stream.filter((event) => event.type === "runtime_request.updated"),
@@ -2525,6 +2524,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const makeWakeHarnessWithOptions = (options?: {
readonly close?: (sdkMessages: Queue.Queue<SDKMessage>) => Effect.Effect<void>;
readonly interrupt?: Effect.Effect<void>;
+ readonly setPermissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setPermissionMode"];
readonly stopTask?: (
taskId: string,
) => Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
@@ -2554,7 +2554,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
) {
const processed = yield* Deferred.make<void>();
processedMessages.set(message, processed);
- yield* Queue.offer(sdkMessages, message);
+ yield* Queue.offer(processQueues.at(-1) ?? sdkMessages, message);
if (offered !== undefined) yield* Deferred.succeed(offered, undefined);
yield* Deferred.await(processed);
});
@@ -2608,18 +2608,42 @@ describe("ClaudeAdapterV2 background wake turns", () => {
open: (input) =>
Effect.gen(function* () {
openedOptions = input.options;
+ const processMessages =
+ options?.freshQueueOnReopen === true && processQueues.length > 0
+ ? yield* Queue.unbounded<SDKMessage>()
+ : sdkMessages;
+ const messages = Stream.fromQueue(processMessages).pipe(
+ Stream.flatMap((message) =>
+ Stream.make(message).pipe(
+ Stream.concat(
+ Stream.fromEffect(
+ Effect.suspend(() => {
+ const processed = processedMessages.get(message);
+ return processed === undefined
+ ? Effect.void
+ : Deferred.succeed(processed, undefined);
+ }),
+ ).pipe(Stream.drain),
+ ),
+ ),
+ ),
+ );
if (options?.freshQueueOnReopen === true && processQueues.length > 0) {
- const processMessages = yield* Queue.unbounded<SDKMessage>();
processQueues.push(processMessages);
return {
- messages: Stream.fromQueue(processMessages),
+ messages,
offer: (message: SDKUserMessage) =>
Effect.sync(() => {
offeredMessages.push(message);
}),
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
- setPermissionMode: () => Effect.void,
+ setPermissionMode: (mode) =>
+ Effect.sync(() => {
+ permissionModeChanges.push(mode);
+ }).pipe(
+ Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void),
+ ),
backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
stopTask: options?.stopTask ?? (() => Effect.void),
interrupt: Effect.void,
@@ -2628,22 +2652,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
}
processQueues.push(sdkMessages);
return {
- messages: Stream.fromQueue(sdkMessages).pipe(
- Stream.flatMap((message) =>
- Stream.make(message).pipe(
- Stream.concat(
- Stream.fromEffect(
- Effect.suspend(() => {
- const processed = processedMessages.get(message);
- return processed === undefined
- ? Effect.void
- : Deferred.succeed(processed, undefined);
- }),
- ).pipe(Stream.drain),
- ),
- ),
- ),
- ),
+ messages,
offer: (message) =>
Effect.sync(() => {
offeredMessages.push(message);
@@ -2659,7 +2668,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
setPermissionMode: (mode) =>
Effect.sync(() => {
permissionModeChanges.push(mode);
- }),
+ }).pipe(Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void)),
backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
stopTask: options?.stopTask ?? (() => Effect.void),
interrupt: options?.interrupt ?? Effect.void,
@@ -2749,6 +2758,462 @@ describe("ClaudeAdapterV2 background wake turns", () => {
});
const makeWakeHarness = makeWakeHarnessWithOptions();
+ describe("Claude settings restrictions", () => {
+ it.effect("resolves cached managed policy from the configured home through the real SDK", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-" });
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-cwd-" });
+ const remoteFile = path.join(home, "remote-settings.json");
+ const sdk = yield* Effect.promise(() =>
+ vi.importActual<typeof ClaudeSdk>("@anthropic-ai/claude-agent-sdk"),
+ );
+ vi.mocked(ClaudeSdk.resolveSettings).mockImplementation(sdk.resolveSettings);
+ const open = Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarnessWithOptions({
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
+ });
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-cached-managed-policy"),
+ text: "Run git status.",
+ attachments: [],
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd,
+ }),
+ }),
+ );
+ return harness.getOpenedOptions()!;
+ }),
+ );
+ yield* fileSystem.writeFileString(
+ remoteFile,
+ JSON.stringify({
+ permissions: { disableBypassPermissionsMode: "disable" },
+ disableAutoMode: "disable",
+ managedSourcesBehavior: "merge",
+ }),
+ );
+ const restricted = yield* open;
+ assert.equal(restricted.permissionMode, "default");
+ assert.isUndefined(restricted.allowDangerouslySkipPermissions);
+ yield* fileSystem.remove(remoteFile);
+ assert.equal((yield* open).permissionMode, "bypassPermissions");
+ yield* fileSystem.writeFileString(remoteFile, "{ invalid json");
+ assert.equal((yield* open).permissionMode, "auto");
+ yield* fileSystem.remove(remoteFile);
+ yield* fileSystem.makeDirectory(remoteFile);
+ assert.equal((yield* open).permissionMode, "auto");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
+ it.effect("asks before restricted Full access tools and follows policy across turns", () =>
+ Effect.gen(function* () {
+ const resolveSettings = vi
+ .mocked(ClaudeSdk.resolveSettings)
+ .mockImplementation(async (options) => ({
+ effective:
+ options?.cwd === "/unrestricted"
+ ? {}
+ : {
+ permissions: {
+ disableBypassPermissionsMode: "disable",
+ ...(options?.cwd === "/restricted-worktree"
+ ? { disableAutoMode: "disable" as const }
+ : {}),
+ },
+ },
+ provenance: {},
+ sources: [],
+ }));
+ const harness = yield* makeWakeHarnessWithOptions({
+ close: Queue.shutdown,
+ freshQueueOnReopen: true,
+ setPermissionMode: (mode) =>
+ mode === "bypassPermissions"
+ ? Effect.fail(
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
+ method: "setPermissionMode",
+ cause: new Error(
+ "Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration",
+ ),
+ }),
+ )
+ : Effect.void,
+ });
+ const now = yield* DateTime.now;
+ let ordinal = 0;
+ const start = (cwd: string, runtimeMode: "full-access" | "auto" = "full-access") =>
+ harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make(`attempt-policy-${++ordinal}`),
+ providerTurnOrdinal: ordinal,
+ text: "Run git status.",
+ attachments: [],
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode,
+ interactionMode: "default",
+ cwd,
+ }),
+ }),
+ );
+ const finish = Effect.gen(function* () {
+ yield* harness.offerAndWait(
+ makeResultFrame({ uuid: `policy-result-${ordinal}`, result: "Done." }),
+ );
+ yield* Queue.take(harness.terminalReceipts);
+ });
+ const notices = () =>
+ harness.events.filter(
+ (event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "system_notice",
+ );
+
+ yield* start("/restricted-worktree", "auto");
+ assert.equal(harness.getOpenedOptions()?.permissionMode, "auto");
+ yield* finish;
+ assert.equal(notices().length, 0);
+ assert.equal(resolveSettings.mock.calls.length, 0);
+
+ yield* start("/restricted");
+ const openedOptions = harness.getOpenedOptions()!;
+ const decision = yield* Effect.promise(() =>
+ openedOptions.canUseTool!(
+ "Bash",
+ { command: "git status" },
+ {
+ signal: new AbortController().signal,
+ toolUseID: "policy-command",
+ requestId: "request-policy-command",
+ },
+ ),
+ ).pipe(Effect.forkScoped);
+ const first = yield* Effect.raceFirst(
+ Queue.take(harness.runtimeRequestReceipts).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",
+ "Full access must not auto-allow a policy-restricted command",
+ );
+ if (first.type !== "request") return;
+ assert.equal(first.event.runtimeRequest.kind, "command");
+ yield* harness.runtime.respondToRuntimeRequest({
+ requestId: first.event.runtimeRequest.id,
+ decision: "decline",
+ });
+ assert.equal((yield* Fiber.join(decision))?.behavior, "deny");
+ assert.equal(openedOptions.permissionMode, "auto");
+ assert.isUndefined(openedOptions.allowDangerouslySkipPermissions);
+
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "system",
+ subtype: "status",
+ status: null,
+ permissionMode: "plan",
+ uuid: "policy-enter-plan",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ yield* finish;
+ assert.equal(notices().length, 1);
+ yield* start("/restricted");
+ assert.strictEqual(harness.getOpenedOptions(), openedOptions);
+ assert.deepEqual(harness.permissionModeChanges, ["auto"]);
+ assert.equal(resolveSettings.mock.calls.length, 1);
+ yield* finish;
+
+ yield* start("/restricted-worktree");
+ assert.equal(harness.getOpenedOptions()?.permissionMode, "default");
+ assert.isUndefined(harness.getOpenedOptions()?.allowDangerouslySkipPermissions);
+ assert.equal(resolveSettings.mock.calls.length, 2);
+ yield* finish;
+
+ yield* start("/unrestricted");
+ assert.equal(harness.getOpenedOptions()?.permissionMode, "bypassPermissions");
+ assert.equal(harness.getOpenedOptions()?.allowDangerouslySkipPermissions, true);
+ // Forwarded asks (including ask rules and settings fallback) still need a decision
+ // before queued init/status frames arrive.
+ for (const { phase, frame } of [
+ {
+ phase: "init",
+ frame: claudeSdkFrame({
+ type: "system",
+ subtype: "init",
+ permissionMode: "bypassPermissions",
+ uuid: "policy-cli-init",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ },
+ {
+ phase: "status",
+ frame: claudeSdkFrame({
+ type: "system",
+ subtype: "status",
+ status: null,
+ permissionMode: "default",
+ uuid: "policy-cli-downgrade",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ },
+ ]) {
+ const forwardedDecision = yield* Effect.promise(() =>
+ harness.getOpenedOptions()!.canUseTool!(
+ "Bash",
+ { command: "git status" },
+ {
+ signal: new AbortController().signal,
+ toolUseID: `forwarded-before-${phase}`,
+ requestId: `request-forwarded-before-${phase}`,
+ },
+ ),
+ ).pipe(Effect.forkScoped);
+ const forwardedFirst = yield* Effect.raceFirst(
+ Queue.take(harness.runtimeRequestReceipts).pipe(
+ Effect.map((event) => ({ type: "request", event }) as const),
+ ),
+ Fiber.join(forwardedDecision).pipe(
+ Effect.map((result) => ({ type: "decision", result }) as const),
+ ),
+ );
+ assert.equal(
+ forwardedFirst.type,
+ "request",
+ `CLI-forwarded Bash must ask before the queued ${phase} frame reaches the adapter`,
+ );
+ if (forwardedFirst.type !== "request") return;
+ assert.equal(forwardedFirst.event.runtimeRequest.kind, "command");
+ yield* harness.runtime.respondToRuntimeRequest({
+ requestId: forwardedFirst.event.runtimeRequest.id,
+ decision: "decline",
+ });
+ assert.equal((yield* Fiber.join(forwardedDecision))?.behavior, "deny");
+ yield* harness.offerAndWait(frame);
+ }
+ yield* finish;
+ const unrestrictedOptions = harness.getOpenedOptions();
+ yield* start("/unrestricted");
+ assert.strictEqual(harness.getOpenedOptions(), unrestrictedOptions);
+ assert.deepEqual(
+ harness.permissionModeChanges,
+ ["auto"],
+ "A CLI policy downgrade must not be restored to bypass on the next turn",
+ );
+ assert.equal(resolveSettings.mock.calls.length, 3);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "system",
+ subtype: "status",
+ status: null,
+ permissionMode: "plan",
+ uuid: "policy-restricted-enter-plan",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ yield* finish;
+ assert.equal(notices().length, 1);
+
+ for (const phase of ["restore", "reuse"]) {
+ const started = yield* start("/unrestricted").pipe(Effect.exit);
+ assert.isTrue(
+ Exit.isSuccess(started),
+ `A rejected bypass restore must not fail the ${phase} turn`,
+ );
+ assert.strictEqual(harness.getOpenedOptions(), unrestrictedOptions);
+ assert.deepEqual(harness.permissionModeChanges, ["auto", "bypassPermissions", "default"]);
+ assert.equal(harness.offeredMessages.length, ordinal);
+ const restoredDecision = yield* Effect.promise(() =>
+ harness.getOpenedOptions()!.canUseTool!(
+ "Bash",
+ { command: "git status" },
+ {
+ signal: new AbortController().signal,
+ toolUseID: `forwarded-after-plan-${phase}`,
+ requestId: `request-after-plan-${phase}`,
+ },
+ ),
+ ).pipe(Effect.forkScoped);
+ const restoredFirst = yield* Effect.raceFirst(
+ Queue.take(harness.runtimeRequestReceipts).pipe(
+ Effect.map((event) => ({ type: "request", event }) as const),
+ ),
+ Fiber.join(restoredDecision).pipe(
+ Effect.map((result) => ({ type: "decision", result }) as const),
+ ),
+ );
+ assert.equal(restoredFirst.type, "request");
+ if (restoredFirst.type !== "request") return;
+ assert.equal(restoredFirst.event.runtimeRequest.kind, "command");
+ yield* harness.runtime.respondToRuntimeRequest({
+ requestId: restoredFirst.event.runtimeRequest.id,
+ decision: "decline",
+ });
+ assert.equal((yield* Fiber.join(restoredDecision))?.behavior, "deny");
+ yield* finish;
+ assert.equal(harness.terminalEvents().at(-1)?.status, "completed");
+ }
+ assert.equal(notices().length, 1);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
+ it.effect(
+ "combines a normalized custom home with project policy without reading the ambient user tier",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const home = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-claude-policy-home-",
+ });
+ yield* fileSystem.makeDirectory(path.join(home, "profile"));
+ yield* fileSystem.writeFileString(
+ path.join(home, "profile", "settings.json"),
+ `{
+ // Claude accepts comments and trailing commas.
+ "permissions": { "disableBypassPermissionsMode": "disable", },
+ }`,
+ );
+ const resolveSettings = vi.mocked(ClaudeSdk.resolveSettings).mockResolvedValue({
+ effective: { disableAutoMode: "disable" },
+ provenance: {},
+ sources: [{ source: "project", settings: { disableAutoMode: "disable" } }],
+ });
+ const harness = yield* makeWakeHarnessWithOptions({
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: " ~/profile " },
+ }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-custom-home"),
+ text: "Run git status.",
+ attachments: [],
+ }),
+ );
+ assert.equal(harness.getOpenedOptions()?.permissionMode, "default");
+ assert.isUndefined(harness.getOpenedOptions()?.allowDangerouslySkipPermissions);
+ assert.deepEqual(resolveSettings.mock.calls[0]?.[0]?.settingSources, [
+ "project",
+ "local",
+ ]);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
+ it.effect(
+ "distinguishes missing custom settings from unreadable, malformed, or unresolved policy",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const home = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-claude-policy-failure-",
+ });
+ const settingsFile = path.join(home, "settings.json");
+ const open = Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarnessWithOptions({
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
+ });
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-settings-failure"),
+ text: "Run git status.",
+ attachments: [],
+ }),
+ );
+ return harness.getOpenedOptions()!;
+ }),
+ );
+ assert.equal((yield* open).permissionMode, "bypassPermissions");
+ yield* fileSystem.makeDirectory(settingsFile);
+ const unreadable = yield* open;
+ assert.equal(unreadable.permissionMode, "auto");
+ assert.isUndefined(unreadable.allowDangerouslySkipPermissions);
+ yield* fileSystem.remove(settingsFile, { recursive: true });
+ yield* fileSystem.writeFileString(settingsFile, "{ invalid json");
+ assert.equal((yield* open).permissionMode, "auto");
+ yield* fileSystem.remove(settingsFile);
+ const resolveSettings = vi
+ .mocked(ClaudeSdk.resolveSettings)
+ .mockClear()
+ .mockRejectedValueOnce(new Error("Cannot resolve managed settings"))
+ .mockResolvedValue({ effective: {}, provenance: {}, sources: [] });
+ const harness = yield* makeWakeHarnessWithOptions({
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
+ close: Queue.shutdown,
+ freshQueueOnReopen: true,
+ });
+ for (const ordinal of [1, 2]) {
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make(`attempt-settings-recovery-${ordinal}`),
+ providerTurnOrdinal: ordinal,
+ text: "Run git status.",
+ attachments: [],
+ }),
+ );
+ const options = harness.getOpenedOptions()!;
+ assert.equal(
+ options.permissionMode,
+ ordinal === 1 ? "auto" : "bypassPermissions",
+ "A transient resolver failure must only downgrade the failing turn",
+ );
+ if (ordinal === 1) assert.isUndefined(options.allowDangerouslySkipPermissions);
+ else assert.equal(options.allowDangerouslySkipPermissions, true);
+ assert.equal(resolveSettings.mock.calls.length, ordinal);
+ yield* harness.offerAndWait(
+ makeResultFrame({ uuid: `settings-recovery-result-${ordinal}`, result: "Done." }),
+ );
+ assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed");
+ }
+ assert.equal(harness.offeredMessages.length, 2);
+ assert.equal(
+ resolveSettings.mock.calls[0]?.[0]?.cwd,
+ resolveSettings.mock.calls[1]?.[0]?.cwd,
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+ });
+
describe("Plan-mode tool approval", () => {
const openPlanTurn = Effect.fn("openPlanTurn")(function* (
runtimeMode: "auto" | "full-access",
@@ -2990,7 +3455,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);
const toolName = "mcp__weather__get_weather";
const id = "weather-call";
- yield* Effect.promise(() =>
+ const permission = yield* Effect.promise(() =>
harness.getOpenedOptions()!.canUseTool!(
toolName,
{ city: "Berlin" },
@@ -3000,7 +3465,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
requestId: "weather-request",
},
),
- );
+ ).pipe(Effect.forkScoped);
+ const request = yield* Queue.take(harness.runtimeRequestReceipts);
+ yield* harness.runtime.respondToRuntimeRequest({
+ requestId: request.runtimeRequest.id,
+ decision: "accept",
+ });
+ yield* Fiber.join(permission);
yield* harness.offerAndWait(
claudeSdkFrame({
type: "assistant",
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 34bc92b5624..795844ba8cd 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -29,6 +29,7 @@ import {
getSessionMessages,
getSubagentMessages,
query,
+ resolveSettings as resolveClaudeSettings,
type Options as ClaudeQueryOptions,
type PermissionMode,
type PermissionResult,
@@ -51,6 +52,7 @@ import type {
// @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK takes a Node ChildProcess for the CLI.
import * as NodeChildProcess from "node:child_process";
import { parseCliArgs } from "@t3tools/shared/cliArgs";
+import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { AgentScope } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
@@ -2026,14 +2028,40 @@ export function claudeRuntimeQueryPolicyForRuntimePolicy(
};
}
-function shouldInstallClaudePermissionCallback(policy: ClaudeRuntimeQueryPolicy): boolean {
- return policy.installPermissionCallback;
+const ClaudeBypassSettings = Schema.StructWithRest(
+ Schema.Struct({
+ disableAutoMode: Schema.optionalKey(Schema.Literal("disable")),
+ permissions: Schema.optionalKey(
+ Schema.StructWithRest(
+ Schema.Struct({
+ disableBypassPermissionsMode: Schema.optionalKey(Schema.Literal("disable")),
+ disableAutoMode: Schema.optionalKey(Schema.Literal("disable")),
+ }),
+ [Schema.Record(Schema.String, Schema.Unknown)],
+ ),
+ ),
+ }),
+ [Schema.Record(Schema.String, Schema.Unknown)],
+);
+const decodeClaudeBypassSettings = Schema.decodeUnknownEffect(
+ fromLenientJson(ClaudeBypassSettings),
+);
+
+function claudeBypassAvailability(
+ settings: typeof ClaudeBypassSettings.Type,
+): ClaudeBypassAvailability {
+ return {
+ bypassDisabled: settings.permissions?.disableBypassPermissionsMode === "disable",
+ autoDisabled:
+ settings.disableAutoMode === "disable" || settings.permissions?.disableAutoMode === "disable",
+ };
}
function requiresClaudeApproval(context: ActiveClaudeTurnContext): boolean {
- return shouldInstallClaudePermissionCallback(
- claudeRuntimeQueryPolicyForRuntimePolicy(context.input.runtimePolicy),
- );
+ // CLI-forwarded requests need a person's decision even under bypass (ask rules,
+ // safety checks, or settings fallback). Do not wait for queued init/status updates.
+ const policy = context.queryPolicy;
+ return policy.installPermissionCallback || policy.permissionMode === "bypassPermissions";
}
function claudeRuntimeQueryPolicyKey(policy: ClaudeRuntimeQueryPolicy): string {
@@ -3189,6 +3217,7 @@ function formatClaudeUsageLimitWait(waitMs: number): string {
}
interface ActiveClaudeTurnContext {
+ readonly queryPolicy: ClaudeRuntimeQueryPolicy;
readonly input: ProviderAdapter.ProviderAdapterV2TurnInput;
readonly nativeThreadId: string;
readonly nativeTurnId: string;
@@ -3281,6 +3310,7 @@ interface ActiveClaudeSubagent {
}
interface ClaudeLiveQueryContext {
+ readonly queryPolicy: ClaudeRuntimeQueryPolicy;
readonly nativeThreadId: string;
readonly query: ClaudeAgentSdkQuerySession;
readonly queryPolicyKey: string;
@@ -3689,6 +3719,44 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
const continuationRequests = adapterOptions.continuationRequests ?? {
offer: () => Effect.void,
};
+ const homePath = yield* resolveClaudeHomePath(
+ adapterOptions.settings,
+ adapterOptions.environment,
+ ).pipe(Effect.provideService(Path.Path, path));
+ const hostEnvironment = yield* HostProcess.Environment;
+ const customHome =
+ adapterOptions.settings.homePath.trim().length > 0 ||
+ adapterOptions.environment.CLAUDE_CONFIG_DIR !== hostEnvironment.CLAUDE_CONFIG_DIR;
+ const announcedBypassDowngrades = new Set<ThreadId>();
+ const readBypassSettings = (filePath: string) =>
+ fileSystem.readFileString(filePath).pipe(
+ Effect.flatMap(decodeClaudeBypassSettings),
+ Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed({})),
+ );
+ const resolveBypassAvailability = Effect.fn("ClaudeAdapterV2.resolveBypassAvailability")(
+ function* (cwd: string | null) {
+ // resolveSettings does not initialize remote-cache eligibility in the SDK host.
+ // Keep the payload intact so the SDK also honors managedSourcesBehavior.
+ const remote = yield* readBypassSettings(path.join(homePath, "remote-settings.json"));
+ const home = customHome
+ ? yield* readBypassSettings(path.join(homePath, "settings.json"))
+ : {};
+ const resolved = yield* Effect.tryPromise(() =>
+ resolveClaudeSettings({
+ ...(cwd === null ? {} : { cwd }),
+ settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
+ serverManagedSettings: remote,
+ }),
+ );
+ const cascade = claudeBypassAvailability(resolved.effective);
+ const user = claudeBypassAvailability(home);
+ const cached = claudeBypassAvailability(remote);
+ return {
+ bypassDisabled: cascade.bypassDisabled || user.bypassDisabled || cached.bypassDisabled,
+ autoDisabled: cascade.autoDisabled || user.autoDisabled || cached.autoDisabled,
+ };
+ },
+ );
const userInvocableSkills = (cwd: string | null) =>
discoverClaudeSkills(
@@ -3777,6 +3845,33 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
const interruptedTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());
const steeredTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());
const queryContext = yield* Ref.make<ClaudeLiveQueryContext | null>(null);
+ // A worktree handoff changes the project settings even within one session.
+ let bypassCache: { cwd: string | null; availability: ClaudeBypassAvailability } | null =
+ null;
+ const queryPolicyForTurn = Effect.fnUntraced(function* (
+ turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
+ ) {
+ if (
+ permissionModeForClaudeRuntimePolicy(turnInput.runtimePolicy) !== "bypassPermissions"
+ ) {
+ return claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy);
+ }
+ const cwd = turnInput.runtimePolicy.cwd;
+ if (bypassCache === null || bypassCache.cwd !== cwd) {
+ const resolved = yield* resolveBypassAvailability(cwd).pipe(Effect.option);
+ if (Option.isNone(resolved)) {
+ return claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy, {
+ bypassDisabled: true,
+ autoDisabled: false,
+ });
+ }
+ bypassCache = { cwd, availability: resolved.value };
+ }
+ return claudeRuntimeQueryPolicyForRuntimePolicy(
+ turnInput.runtimePolicy,
+ bypassCache.availability,
+ );
+ });
const openedNativeThreads = yield* Ref.make(new Set<string>());
const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>());
// Claude 5 task tools edit one list per native session, across turns.
@@ -8824,7 +8919,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
nativeThreadId: string,
) {
- const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy);
+ const queryPolicy = yield* queryPolicyForTurn(turnInput);
const mcpOverrides = claudeMcpQueryOverrides({
mcpSession: yield* mcpSessions.read(turnInput.threadId),
readOnlySandbox:
@@ -8875,12 +8970,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
existing.queryPolicyKey === queryPolicyKey &&
existing.selection.queryIdentity === compiledSelection.queryIdentity
) {
- // Claude can switch its own mode mid-session (EnterPlanMode), and
- // a denied ExitPlanMode leaves it there. Put the live process back
- // in its initial mode before the next prompt.
- if (existing.permissionMode !== existing.openedPermissionMode) {
- yield* existing.query.setPermissionMode(existing.openedPermissionMode);
- existing.permissionMode = existing.openedPermissionMode;
+ // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan:
+ // Auto/default may reflect a policy restriction that forbids restoring bypass.
+ if (existing.permissionMode === "plan" && existing.openedPermissionMode !== "plan") {
+ existing.permissionMode = yield* existing.query
+ .setPermissionMode(existing.openedPermissionMode)
+ .pipe(
+ Effect.as(existing.openedPermissionMode),
+ Effect.catchTags({
+ ClaudeAgentSdkQueryRunnerError: (error) =>
+ existing.openedPermissionMode === "bypassPermissions"
+ ? existing.query
+ .setPermissionMode("default")
+ .pipe(Effect.as("default" as const))
+ : Effect.fail(error),
+ }),
+ );
}
return existing;
}
@@ -8976,6 +9081,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
});
const closed = yield* Deferred.make<void, never>();
const context: ClaudeLiveQueryContext = {
+ queryPolicy,
nativeThreadId,
query: querySession,
queryPolicyKey,
@@ -9097,8 +9203,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (!goalsByNativeThread.has(nativeThreadId)) {
goalsByNativeThread.set(nativeThreadId, turnInput.providerThread.goal ?? null);
}
+ const userMessage =
+ promptUuid === null
+ ? null
+ : yield* makeClaudeUserMessageWithAttachments({
+ text: applyClaudePromptEffortPrefix(
+ turnInput.message.text,
+ compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
+ ),
+ attachments: turnInput.message.attachments,
+ attachmentsDir,
+ fileSystem,
+ skills: yield* userInvocableSkills(turnInput.runtimePolicy.cwd),
+ uuid: promptUuid,
+ });
+ const querySession = yield* openQuery(turnInput, nativeThreadId);
const context: ActiveClaudeTurnContext = {
input: turnInput,
+ queryPolicy: querySession.queryPolicy,
nativeThreadId,
nativeTurnId,
nativeMessageCursor: null,
@@ -9142,24 +9264,54 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
gatedFramesBeforeEcho: 0,
heldRootFrames: [],
};
- const userMessage =
- promptUuid === null
- ? null
- : yield* makeClaudeUserMessageWithAttachments({
- text: applyClaudePromptEffortPrefix(
- turnInput.message.text,
- compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
- ),
- attachments: turnInput.message.attachments,
- attachmentsDir,
- fileSystem,
- skills: yield* userInvocableSkills(turnInput.runtimePolicy.cwd),
- uuid: promptUuid,
- });
- const querySession = yield* openQuery(turnInput, nativeThreadId);
const attachTurn = Effect.gen(function* () {
querySession.lastTurn = context;
yield* Ref.set(activeTurn, context);
+ if (
+ !isClaudeProviderContinuationTurn(turnInput) &&
+ permissionModeForClaudeRuntimePolicy(turnInput.runtimePolicy) ===
+ "bypassPermissions" &&
+ context.queryPolicy.permissionMode !== "bypassPermissions" &&
+ !announcedBypassDowngrades.has(turnInput.threadId)
+ ) {
+ announcedBypassDowngrades.add(turnInput.threadId);
+ if (announcedBypassDowngrades.size > 1000) {
+ const oldest = announcedBypassDowngrades.values().next().value;
+ if (oldest !== undefined) announcedBypassDowngrades.delete(oldest);
+ }
+ const nativeItemId = `bypass-policy-downgrade:${context.providerTurnId}`;
+ const notice =
+ "T3 could not confirm Claude bypass permissions here, so Full access is running with approval checks.";
+ yield* emitProviderEvent({
+ type: "turn_item.updated",
+ driver: CLAUDE_PROVIDER,
+ turnItem: {
+ id: idAllocator.derive.turnItemFromProviderItem({
+ driver: CLAUDE_PROVIDER,
+ nativeItemId,
+ }),
+ threadId: turnInput.threadId,
+ runId: turnInput.runId,
+ nodeId: turnInput.rootNodeId,
+ providerThreadId: turnInput.providerThread.id,
+ providerTurnId: context.providerTurnId,
+ nativeItemRef: {
+ driver: CLAUDE_PROVIDER,
+ nativeId: nativeItemId,
+ strength: "weak",
+ },
+ parentItemId: null,
+ ordinal: yield* resolveItemOrdinal(context, nativeItemId),
+ type: "system_notice",
+ status: "completed",
+ title: notice,
+ message: notice,
+ startedAt,
+ completedAt: startedAt,
+ updatedAt: startedAt,
+ },
+ });
+ }
yield* emitProviderEvent({
type: "provider_turn.updated",
driver: CLAUDE_PROVIDER,
diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md
index 1bcdeffee5c..150c857db94 100644
--- a/docs/user/permission-modes.md
+++ b/docs/user/permission-modes.md
@@ -35,6 +35,9 @@ session-wide choice, because Grok would remember that command for the whole proj
ACP Registry agents run their own tools in their own mode; T3 Code answers their approval requests
by the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals).
+Claude can still ask in **Full access** when its settings disable bypass permissions or require
+approval for an action.
+
Antigravity can still send native approval requests in **Full access**. It only offers remembered
approvals for actions that support them.