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

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 22:00 UTC

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

Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com>

Julius Marminge committed Oct 19, 2026 at 22:31 UTC 0b84aa3fa7853e2645322feebc0859802ccc1a31
3 files changed +692 -66
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+510 -39
@@ -5,6 +5,9 @@ import * as NodeOS from "node:os";
5 import * as NodePath from "node:path";
6 import * as NodeStream from "node:stream";
7
8 +import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
9 +import { beforeEach, vi } from "vite-plus/test";
10 +
11 import type {
12 Query as ClaudeQuery,
13 SDKMessage,
@@ -103,6 +106,18 @@ import {
106 projectionFor,
107 } from "../testkit/fixtures/shared.ts";
108
109 +vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => ({
110 + ...(await importOriginal<typeof ClaudeSdk>()),
111 + resolveSettings: vi.fn(),
112 +}));
113 +
114 +beforeEach(() => {
115 + vi.mocked(ClaudeSdk.resolveSettings).mockReset().mockResolvedValue({
116 + effective: {},
117 + provenance: {},
118 + sources: [],
119 + });
120 +});
121 const decodeUserInputQuestions = Schema.decodeUnknownSync(
122 Schema.Array(OrchestrationV2UserInputQuestion),
123 );
@@ -1503,22 +1518,6 @@ describe("ClaudeAdapterV2 resume compaction", () => {
1518 assert.isFunction(callback);
1519 const canUseTool = openedOptions?.canUseTool;
1520 assert.isFunction(canUseTool);
1506 - const ordinaryToolResult = yield* Effect.promise(() =>
1507 - canUseTool!(
1508 - "Bash",
1509 - { command: "pwd" },
1510 - {
1511 - signal: new AbortController().signal,
1512 - toolUseID: "tool-bash-full-access",
1513 - requestId: "request-bash-full-access",
1514 - },
1515 - ),
1516 - );
1517 - assert.deepEqual(ordinaryToolResult, {
1518 - behavior: "allow",
1519 - updatedInput: { command: "pwd" },
1520 - toolUseID: "tool-bash-full-access",
1521 - });
1521 const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`;
1522 const questionRequestEvent = yield* runtime.events.pipe(
1523 Stream.filter((event) => event.type === "runtime_request.updated"),
@@ -2525,6 +2524,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2524 const makeWakeHarnessWithOptions = (options?: {
2525 readonly close?: (sdkMessages: Queue.Queue<SDKMessage>) => Effect.Effect<void>;
2526 readonly interrupt?: Effect.Effect<void>;
2527 + readonly setPermissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setPermissionMode"];
2528 readonly stopTask?: (
2529 taskId: string,
2530 ) => Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
@@ -2554,7 +2554,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2554 ) {
2555 const processed = yield* Deferred.make<void>();
2556 processedMessages.set(message, processed);
2557 - yield* Queue.offer(sdkMessages, message);
2557 + yield* Queue.offer(processQueues.at(-1) ?? sdkMessages, message);
2558 if (offered !== undefined) yield* Deferred.succeed(offered, undefined);
2559 yield* Deferred.await(processed);
2560 });
@@ -2608,18 +2608,42 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2608 open: (input) =>
2609 Effect.gen(function* () {
2610 openedOptions = input.options;
2611 + const processMessages =
2612 + options?.freshQueueOnReopen === true && processQueues.length > 0
2613 + ? yield* Queue.unbounded<SDKMessage>()
2614 + : sdkMessages;
2615 + const messages = Stream.fromQueue(processMessages).pipe(
2616 + Stream.flatMap((message) =>
2617 + Stream.make(message).pipe(
2618 + Stream.concat(
2619 + Stream.fromEffect(
2620 + Effect.suspend(() => {
2621 + const processed = processedMessages.get(message);
2622 + return processed === undefined
2623 + ? Effect.void
2624 + : Deferred.succeed(processed, undefined);
2625 + }),
2626 + ).pipe(Stream.drain),
2627 + ),
2628 + ),
2629 + ),
2630 + );
2631 if (options?.freshQueueOnReopen === true && processQueues.length > 0) {
2612 - const processMessages = yield* Queue.unbounded<SDKMessage>();
2632 processQueues.push(processMessages);
2633 return {
2615 - messages: Stream.fromQueue(processMessages),
2634 + messages,
2635 offer: (message: SDKUserMessage) =>
2636 Effect.sync(() => {
2637 offeredMessages.push(message);
2638 }),
2639 setModel: () => Effect.void,
2640 applyFlagSettings: () => Effect.void,
2622 - setPermissionMode: () => Effect.void,
2641 + setPermissionMode: (mode) =>
2642 + Effect.sync(() => {
2643 + permissionModeChanges.push(mode);
2644 + }).pipe(
2645 + Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void),
2646 + ),
2647 backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
2648 stopTask: options?.stopTask ?? (() => Effect.void),
2649 interrupt: Effect.void,
@@ -2628,22 +2652,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2652 }
2653 processQueues.push(sdkMessages);
2654 return {
2631 - messages: Stream.fromQueue(sdkMessages).pipe(
2632 - Stream.flatMap((message) =>
2633 - Stream.make(message).pipe(
2634 - Stream.concat(
2635 - Stream.fromEffect(
2636 - Effect.suspend(() => {
2637 - const processed = processedMessages.get(message);
2638 - return processed === undefined
2639 - ? Effect.void
2640 - : Deferred.succeed(processed, undefined);
2641 - }),
2642 - ).pipe(Stream.drain),
2643 - ),
2644 - ),
2645 - ),
2646 - ),
2655 + messages,
2656 offer: (message) =>
2657 Effect.sync(() => {
2658 offeredMessages.push(message);
@@ -2659,7 +2668,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2668 setPermissionMode: (mode) =>
2669 Effect.sync(() => {
2670 permissionModeChanges.push(mode);
2662 - }),
2671 + }).pipe(Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void)),
2672 backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)),
2673 stopTask: options?.stopTask ?? (() => Effect.void),
2674 interrupt: options?.interrupt ?? Effect.void,
@@ -2749,6 +2758,462 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2758 });
2759 const makeWakeHarness = makeWakeHarnessWithOptions();
2760
2761 + describe("Claude settings restrictions", () => {
2762 + it.effect("resolves cached managed policy from the configured home through the real SDK", () =>
2763 + Effect.gen(function* () {
2764 + const fileSystem = yield* FileSystem.FileSystem;
2765 + const path = yield* Path.Path;
2766 + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-" });
2767 + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-cwd-" });
2768 + const remoteFile = path.join(home, "remote-settings.json");
2769 + const sdk = yield* Effect.promise(() =>
2770 + vi.importActual<typeof ClaudeSdk>("@anthropic-ai/claude-agent-sdk"),
2771 + );
2772 + vi.mocked(ClaudeSdk.resolveSettings).mockImplementation(sdk.resolveSettings);
2773 + const open = Effect.scoped(
2774 + Effect.gen(function* () {
2775 + const harness = yield* makeWakeHarnessWithOptions({
2776 + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
2777 + });
2778 + yield* harness.runtime.startTurn(
2779 + makeClaudeTestTurnInput({
2780 + threadId: harness.threadId,
2781 + providerThread: harness.providerThread,
2782 + now: yield* DateTime.now,
2783 + attemptId: RunAttemptId.make("attempt-cached-managed-policy"),
2784 + text: "Run git status.",
2785 + attachments: [],
2786 + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2787 + runtimeMode: "full-access",
2788 + interactionMode: "default",
2789 + cwd,
2790 + }),
2791 + }),
2792 + );
2793 + return harness.getOpenedOptions()!;
2794 + }),
2795 + );
2796 + yield* fileSystem.writeFileString(
2797 + remoteFile,
2798 + JSON.stringify({
2799 + permissions: { disableBypassPermissionsMode: "disable" },
2800 + disableAutoMode: "disable",
2801 + managedSourcesBehavior: "merge",
2802 + }),
2803 + );
2804 + const restricted = yield* open;
2805 + assert.equal(restricted.permissionMode, "default");
2806 + assert.isUndefined(restricted.allowDangerouslySkipPermissions);
2807 + yield* fileSystem.remove(remoteFile);
2808 + assert.equal((yield* open).permissionMode, "bypassPermissions");
2809 + yield* fileSystem.writeFileString(remoteFile, "{ invalid json");
2810 + assert.equal((yield* open).permissionMode, "auto");
2811 + yield* fileSystem.remove(remoteFile);
2812 + yield* fileSystem.makeDirectory(remoteFile);
2813 + assert.equal((yield* open).permissionMode, "auto");
2814 + }).pipe(
2815 + Effect.provide(
2816 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
2817 + ),
2818 + ),
2819 + );
2820 +
2821 + it.effect("asks before restricted Full access tools and follows policy across turns", () =>
2822 + Effect.gen(function* () {
2823 + const resolveSettings = vi
2824 + .mocked(ClaudeSdk.resolveSettings)
2825 + .mockImplementation(async (options) => ({
2826 + effective:
2827 + options?.cwd === "/unrestricted"
2828 + ? {}
2829 + : {
2830 + permissions: {
2831 + disableBypassPermissionsMode: "disable",
2832 + ...(options?.cwd === "/restricted-worktree"
2833 + ? { disableAutoMode: "disable" as const }
2834 + : {}),
2835 + },
2836 + },
2837 + provenance: {},
2838 + sources: [],
2839 + }));
2840 + const harness = yield* makeWakeHarnessWithOptions({
2841 + close: Queue.shutdown,
2842 + freshQueueOnReopen: true,
2843 + setPermissionMode: (mode) =>
2844 + mode === "bypassPermissions"
2845 + ? Effect.fail(
2846 + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
2847 + method: "setPermissionMode",
2848 + cause: new Error(
2849 + "Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration",
2850 + ),
2851 + }),
2852 + )
2853 + : Effect.void,
2854 + });
2855 + const now = yield* DateTime.now;
2856 + let ordinal = 0;
2857 + const start = (cwd: string, runtimeMode: "full-access" | "auto" = "full-access") =>
2858 + harness.runtime.startTurn(
2859 + makeClaudeTestTurnInput({
2860 + threadId: harness.threadId,
2861 + providerThread: harness.providerThread,
2862 + now,
2863 + attemptId: RunAttemptId.make(`attempt-policy-${++ordinal}`),
2864 + providerTurnOrdinal: ordinal,
2865 + text: "Run git status.",
2866 + attachments: [],
2867 + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2868 + runtimeMode,
2869 + interactionMode: "default",
2870 + cwd,
2871 + }),
2872 + }),
2873 + );
2874 + const finish = Effect.gen(function* () {
2875 + yield* harness.offerAndWait(
2876 + makeResultFrame({ uuid: `policy-result-${ordinal}`, result: "Done." }),
2877 + );
2878 + yield* Queue.take(harness.terminalReceipts);
2879 + });
2880 + const notices = () =>
2881 + harness.events.filter(
2882 + (event) =>
2883 + event.type === "turn_item.updated" && event.turnItem.type === "system_notice",
2884 + );
2885 +
2886 + yield* start("/restricted-worktree", "auto");
2887 + assert.equal(harness.getOpenedOptions()?.permissionMode, "auto");
2888 + yield* finish;
2889 + assert.equal(notices().length, 0);
2890 + assert.equal(resolveSettings.mock.calls.length, 0);
2891 +
2892 + yield* start("/restricted");
2893 + const openedOptions = harness.getOpenedOptions()!;
2894 + const decision = yield* Effect.promise(() =>
2895 + openedOptions.canUseTool!(
2896 + "Bash",
2897 + { command: "git status" },
2898 + {
2899 + signal: new AbortController().signal,
2900 + toolUseID: "policy-command",
2901 + requestId: "request-policy-command",
2902 + },
2903 + ),
2904 + ).pipe(Effect.forkScoped);
2905 + const first = yield* Effect.raceFirst(
2906 + Queue.take(harness.runtimeRequestReceipts).pipe(
2907 + Effect.map((event) => ({ type: "request", event }) as const),
2908 + ),
2909 + Fiber.join(decision).pipe(
2910 + Effect.map((result) => ({ type: "decision", result }) as const),
2911 + ),
2912 + );
2913 + assert.equal(
2914 + first.type,
2915 + "request",
2916 + "Full access must not auto-allow a policy-restricted command",
2917 + );
2918 + if (first.type !== "request") return;
2919 + assert.equal(first.event.runtimeRequest.kind, "command");
2920 + yield* harness.runtime.respondToRuntimeRequest({
2921 + requestId: first.event.runtimeRequest.id,
2922 + decision: "decline",
2923 + });
2924 + assert.equal((yield* Fiber.join(decision))?.behavior, "deny");
2925 + assert.equal(openedOptions.permissionMode, "auto");
2926 + assert.isUndefined(openedOptions.allowDangerouslySkipPermissions);
2927 +
2928 + yield* harness.offerAndWait(
2929 + claudeSdkFrame({
2930 + type: "system",
2931 + subtype: "status",
2932 + status: null,
2933 + permissionMode: "plan",
2934 + uuid: "policy-enter-plan",
2935 + session_id: WAKE_NATIVE_SESSION,
2936 + }),
2937 + );
2938 + yield* finish;
2939 + assert.equal(notices().length, 1);
2940 + yield* start("/restricted");
2941 + assert.strictEqual(harness.getOpenedOptions(), openedOptions);
2942 + assert.deepEqual(harness.permissionModeChanges, ["auto"]);
2943 + assert.equal(resolveSettings.mock.calls.length, 1);
2944 + yield* finish;
2945 +
2946 + yield* start("/restricted-worktree");
2947 + assert.equal(harness.getOpenedOptions()?.permissionMode, "default");
2948 + assert.isUndefined(harness.getOpenedOptions()?.allowDangerouslySkipPermissions);
2949 + assert.equal(resolveSettings.mock.calls.length, 2);
2950 + yield* finish;
2951 +
2952 + yield* start("/unrestricted");
2953 + assert.equal(harness.getOpenedOptions()?.permissionMode, "bypassPermissions");
2954 + assert.equal(harness.getOpenedOptions()?.allowDangerouslySkipPermissions, true);
2955 + // Forwarded asks (including ask rules and settings fallback) still need a decision
2956 + // before queued init/status frames arrive.
2957 + for (const { phase, frame } of [
2958 + {
2959 + phase: "init",
2960 + frame: claudeSdkFrame({
2961 + type: "system",
2962 + subtype: "init",
2963 + permissionMode: "bypassPermissions",
2964 + uuid: "policy-cli-init",
2965 + session_id: WAKE_NATIVE_SESSION,
2966 + }),
2967 + },
2968 + {
2969 + phase: "status",
2970 + frame: claudeSdkFrame({
2971 + type: "system",
2972 + subtype: "status",
2973 + status: null,
2974 + permissionMode: "default",
2975 + uuid: "policy-cli-downgrade",
2976 + session_id: WAKE_NATIVE_SESSION,
2977 + }),
2978 + },
2979 + ]) {
2980 + const forwardedDecision = yield* Effect.promise(() =>
2981 + harness.getOpenedOptions()!.canUseTool!(
2982 + "Bash",
2983 + { command: "git status" },
2984 + {
2985 + signal: new AbortController().signal,
2986 + toolUseID: `forwarded-before-${phase}`,
2987 + requestId: `request-forwarded-before-${phase}`,
2988 + },
2989 + ),
2990 + ).pipe(Effect.forkScoped);
2991 + const forwardedFirst = yield* Effect.raceFirst(
2992 + Queue.take(harness.runtimeRequestReceipts).pipe(
2993 + Effect.map((event) => ({ type: "request", event }) as const),
2994 + ),
2995 + Fiber.join(forwardedDecision).pipe(
2996 + Effect.map((result) => ({ type: "decision", result }) as const),
2997 + ),
2998 + );
2999 + assert.equal(
3000 + forwardedFirst.type,
3001 + "request",
3002 + `CLI-forwarded Bash must ask before the queued ${phase} frame reaches the adapter`,
3003 + );
3004 + if (forwardedFirst.type !== "request") return;
3005 + assert.equal(forwardedFirst.event.runtimeRequest.kind, "command");
3006 + yield* harness.runtime.respondToRuntimeRequest({
3007 + requestId: forwardedFirst.event.runtimeRequest.id,
3008 + decision: "decline",
3009 + });
3010 + assert.equal((yield* Fiber.join(forwardedDecision))?.behavior, "deny");
3011 + yield* harness.offerAndWait(frame);
3012 + }
3013 + yield* finish;
3014 + const unrestrictedOptions = harness.getOpenedOptions();
3015 + yield* start("/unrestricted");
3016 + assert.strictEqual(harness.getOpenedOptions(), unrestrictedOptions);
3017 + assert.deepEqual(
3018 + harness.permissionModeChanges,
3019 + ["auto"],
3020 + "A CLI policy downgrade must not be restored to bypass on the next turn",
3021 + );
3022 + assert.equal(resolveSettings.mock.calls.length, 3);
3023 + yield* harness.offerAndWait(
3024 + claudeSdkFrame({
3025 + type: "system",
3026 + subtype: "status",
3027 + status: null,
3028 + permissionMode: "plan",
3029 + uuid: "policy-restricted-enter-plan",
3030 + session_id: WAKE_NATIVE_SESSION,
3031 + }),
3032 + );
3033 + yield* finish;
3034 + assert.equal(notices().length, 1);
3035 +
3036 + for (const phase of ["restore", "reuse"]) {
3037 + const started = yield* start("/unrestricted").pipe(Effect.exit);
3038 + assert.isTrue(
3039 + Exit.isSuccess(started),
3040 + `A rejected bypass restore must not fail the ${phase} turn`,
3041 + );
3042 + assert.strictEqual(harness.getOpenedOptions(), unrestrictedOptions);
3043 + assert.deepEqual(harness.permissionModeChanges, ["auto", "bypassPermissions", "default"]);
3044 + assert.equal(harness.offeredMessages.length, ordinal);
3045 + const restoredDecision = yield* Effect.promise(() =>
3046 + harness.getOpenedOptions()!.canUseTool!(
3047 + "Bash",
3048 + { command: "git status" },
3049 + {
3050 + signal: new AbortController().signal,
3051 + toolUseID: `forwarded-after-plan-${phase}`,
3052 + requestId: `request-after-plan-${phase}`,
3053 + },
3054 + ),
3055 + ).pipe(Effect.forkScoped);
3056 + const restoredFirst = yield* Effect.raceFirst(
3057 + Queue.take(harness.runtimeRequestReceipts).pipe(
3058 + Effect.map((event) => ({ type: "request", event }) as const),
3059 + ),
3060 + Fiber.join(restoredDecision).pipe(
3061 + Effect.map((result) => ({ type: "decision", result }) as const),
3062 + ),
3063 + );
3064 + assert.equal(restoredFirst.type, "request");
3065 + if (restoredFirst.type !== "request") return;
3066 + assert.equal(restoredFirst.event.runtimeRequest.kind, "command");
3067 + yield* harness.runtime.respondToRuntimeRequest({
3068 + requestId: restoredFirst.event.runtimeRequest.id,
3069 + decision: "decline",
3070 + });
3071 + assert.equal((yield* Fiber.join(restoredDecision))?.behavior, "deny");
3072 + yield* finish;
3073 + assert.equal(harness.terminalEvents().at(-1)?.status, "completed");
3074 + }
3075 + assert.equal(notices().length, 1);
3076 + }).pipe(
3077 + Effect.provide(
3078 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3079 + ),
3080 + ),
3081 + );
3082 +
3083 + it.effect(
3084 + "combines a normalized custom home with project policy without reading the ambient user tier",
3085 + () =>
3086 + Effect.gen(function* () {
3087 + const fileSystem = yield* FileSystem.FileSystem;
3088 + const path = yield* Path.Path;
3089 + const home = yield* fileSystem.makeTempDirectoryScoped({
3090 + prefix: "t3-claude-policy-home-",
3091 + });
3092 + yield* fileSystem.makeDirectory(path.join(home, "profile"));
3093 + yield* fileSystem.writeFileString(
3094 + path.join(home, "profile", "settings.json"),
3095 + `{
3096 + // Claude accepts comments and trailing commas.
3097 + "permissions": { "disableBypassPermissionsMode": "disable", },
3098 + }`,
3099 + );
3100 + const resolveSettings = vi.mocked(ClaudeSdk.resolveSettings).mockResolvedValue({
3101 + effective: { disableAutoMode: "disable" },
3102 + provenance: {},
3103 + sources: [{ source: "project", settings: { disableAutoMode: "disable" } }],
3104 + });
3105 + const harness = yield* makeWakeHarnessWithOptions({
3106 + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: " ~/profile " },
3107 + }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
3108 + yield* harness.runtime.startTurn(
3109 + makeClaudeTestTurnInput({
3110 + threadId: harness.threadId,
3111 + providerThread: harness.providerThread,
3112 + now: yield* DateTime.now,
3113 + attemptId: RunAttemptId.make("attempt-custom-home"),
3114 + text: "Run git status.",
3115 + attachments: [],
3116 + }),
3117 + );
3118 + assert.equal(harness.getOpenedOptions()?.permissionMode, "default");
3119 + assert.isUndefined(harness.getOpenedOptions()?.allowDangerouslySkipPermissions);
3120 + assert.deepEqual(resolveSettings.mock.calls[0]?.[0]?.settingSources, [
3121 + "project",
3122 + "local",
3123 + ]);
3124 + }).pipe(
3125 + Effect.provide(
3126 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3127 + ),
3128 + ),
3129 + );
3130 +
3131 + it.effect(
3132 + "distinguishes missing custom settings from unreadable, malformed, or unresolved policy",
3133 + () =>
3134 + Effect.gen(function* () {
3135 + const fileSystem = yield* FileSystem.FileSystem;
3136 + const path = yield* Path.Path;
3137 + const home = yield* fileSystem.makeTempDirectoryScoped({
3138 + prefix: "t3-claude-policy-failure-",
3139 + });
3140 + const settingsFile = path.join(home, "settings.json");
3141 + const open = Effect.scoped(
3142 + Effect.gen(function* () {
3143 + const harness = yield* makeWakeHarnessWithOptions({
3144 + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
3145 + });
3146 + yield* harness.runtime.startTurn(
3147 + makeClaudeTestTurnInput({
3148 + threadId: harness.threadId,
3149 + providerThread: harness.providerThread,
3150 + now: yield* DateTime.now,
3151 + attemptId: RunAttemptId.make("attempt-settings-failure"),
3152 + text: "Run git status.",
3153 + attachments: [],
3154 + }),
3155 + );
3156 + return harness.getOpenedOptions()!;
3157 + }),
3158 + );
3159 + assert.equal((yield* open).permissionMode, "bypassPermissions");
3160 + yield* fileSystem.makeDirectory(settingsFile);
3161 + const unreadable = yield* open;
3162 + assert.equal(unreadable.permissionMode, "auto");
3163 + assert.isUndefined(unreadable.allowDangerouslySkipPermissions);
3164 + yield* fileSystem.remove(settingsFile, { recursive: true });
3165 + yield* fileSystem.writeFileString(settingsFile, "{ invalid json");
3166 + assert.equal((yield* open).permissionMode, "auto");
3167 + yield* fileSystem.remove(settingsFile);
3168 + const resolveSettings = vi
3169 + .mocked(ClaudeSdk.resolveSettings)
3170 + .mockClear()
3171 + .mockRejectedValueOnce(new Error("Cannot resolve managed settings"))
3172 + .mockResolvedValue({ effective: {}, provenance: {}, sources: [] });
3173 + const harness = yield* makeWakeHarnessWithOptions({
3174 + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
3175 + close: Queue.shutdown,
3176 + freshQueueOnReopen: true,
3177 + });
3178 + for (const ordinal of [1, 2]) {
3179 + yield* harness.runtime.startTurn(
3180 + makeClaudeTestTurnInput({
3181 + threadId: harness.threadId,
3182 + providerThread: harness.providerThread,
3183 + now: yield* DateTime.now,
3184 + attemptId: RunAttemptId.make(`attempt-settings-recovery-${ordinal}`),
3185 + providerTurnOrdinal: ordinal,
3186 + text: "Run git status.",
3187 + attachments: [],
3188 + }),
3189 + );
3190 + const options = harness.getOpenedOptions()!;
3191 + assert.equal(
3192 + options.permissionMode,
3193 + ordinal === 1 ? "auto" : "bypassPermissions",
3194 + "A transient resolver failure must only downgrade the failing turn",
3195 + );
3196 + if (ordinal === 1) assert.isUndefined(options.allowDangerouslySkipPermissions);
3197 + else assert.equal(options.allowDangerouslySkipPermissions, true);
3198 + assert.equal(resolveSettings.mock.calls.length, ordinal);
3199 + yield* harness.offerAndWait(
3200 + makeResultFrame({ uuid: `settings-recovery-result-${ordinal}`, result: "Done." }),
3201 + );
3202 + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed");
3203 + }
3204 + assert.equal(harness.offeredMessages.length, 2);
3205 + assert.equal(
3206 + resolveSettings.mock.calls[0]?.[0]?.cwd,
3207 + resolveSettings.mock.calls[1]?.[0]?.cwd,
3208 + );
3209 + }).pipe(
3210 + Effect.provide(
3211 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3212 + ),
3213 + ),
3214 + );
3215 + });
3216 +
3217 describe("Plan-mode tool approval", () => {
3218 const openPlanTurn = Effect.fn("openPlanTurn")(function* (
3219 runtimeMode: "auto" | "full-access",
@@ -2990,7 +3455,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3455 );
3456 const toolName = "mcp__weather__get_weather";
3457 const id = "weather-call";
2993 - yield* Effect.promise(() =>
3458 + const permission = yield* Effect.promise(() =>
3459 harness.getOpenedOptions()!.canUseTool!(
3460 toolName,
3461 { city: "Berlin" },
@@ -3000,7 +3465,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3465 requestId: "weather-request",
3466 },
3467 ),
3003 - );
3468 + ).pipe(Effect.forkScoped);
3469 + const request = yield* Queue.take(harness.runtimeRequestReceipts);
3470 + yield* harness.runtime.respondToRuntimeRequest({
3471 + requestId: request.runtimeRequest.id,
3472 + decision: "accept",
3473 + });
3474 + yield* Fiber.join(permission);
3475 yield* harness.offerAndWait(
3476 claudeSdkFrame({
3477 type: "assistant",
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+179 -27
@@ -29,6 +29,7 @@ import {
29 getSessionMessages,
30 getSubagentMessages,
31 query,
32 + resolveSettings as resolveClaudeSettings,
33 type Options as ClaudeQueryOptions,
34 type PermissionMode,
35 type PermissionResult,
@@ -51,6 +52,7 @@ import type {
52 // @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK takes a Node ChildProcess for the CLI.
53 import * as NodeChildProcess from "node:child_process";
54 import { parseCliArgs } from "@t3tools/shared/cliArgs";
55 +import { fromLenientJson } from "@t3tools/shared/schemaJson";
56 import { AgentScope } from "@t3tools/shared/AgentScope";
57 import * as HostProcess from "@t3tools/shared/HostProcess";
58 import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
@@ -2026,14 +2028,40 @@ export function claudeRuntimeQueryPolicyForRuntimePolicy(
2028 };
2029 }
2030
2029 -function shouldInstallClaudePermissionCallback(policy: ClaudeRuntimeQueryPolicy): boolean {
2030 - return policy.installPermissionCallback;
2031 +const ClaudeBypassSettings = Schema.StructWithRest(
2032 + Schema.Struct({
2033 + disableAutoMode: Schema.optionalKey(Schema.Literal("disable")),
2034 + permissions: Schema.optionalKey(
2035 + Schema.StructWithRest(
2036 + Schema.Struct({
2037 + disableBypassPermissionsMode: Schema.optionalKey(Schema.Literal("disable")),
2038 + disableAutoMode: Schema.optionalKey(Schema.Literal("disable")),
2039 + }),
2040 + [Schema.Record(Schema.String, Schema.Unknown)],
2041 + ),
2042 + ),
2043 + }),
2044 + [Schema.Record(Schema.String, Schema.Unknown)],
2045 +);
2046 +const decodeClaudeBypassSettings = Schema.decodeUnknownEffect(
2047 + fromLenientJson(ClaudeBypassSettings),
2048 +);
2049 +
2050 +function claudeBypassAvailability(
2051 + settings: typeof ClaudeBypassSettings.Type,
2052 +): ClaudeBypassAvailability {
2053 + return {
2054 + bypassDisabled: settings.permissions?.disableBypassPermissionsMode === "disable",
2055 + autoDisabled:
2056 + settings.disableAutoMode === "disable" || settings.permissions?.disableAutoMode === "disable",
2057 + };
2058 }
2059
2060 function requiresClaudeApproval(context: ActiveClaudeTurnContext): boolean {
2034 - return shouldInstallClaudePermissionCallback(
2035 - claudeRuntimeQueryPolicyForRuntimePolicy(context.input.runtimePolicy),
2036 - );
2061 + // CLI-forwarded requests need a person's decision even under bypass (ask rules,
2062 + // safety checks, or settings fallback). Do not wait for queued init/status updates.
2063 + const policy = context.queryPolicy;
2064 + return policy.installPermissionCallback || policy.permissionMode === "bypassPermissions";
2065 }
2066
2067 function claudeRuntimeQueryPolicyKey(policy: ClaudeRuntimeQueryPolicy): string {
@@ -3189,6 +3217,7 @@ function formatClaudeUsageLimitWait(waitMs: number): string {
3217 }
3218
3219 interface ActiveClaudeTurnContext {
3220 + readonly queryPolicy: ClaudeRuntimeQueryPolicy;
3221 readonly input: ProviderAdapter.ProviderAdapterV2TurnInput;
3222 readonly nativeThreadId: string;
3223 readonly nativeTurnId: string;
@@ -3281,6 +3310,7 @@ interface ActiveClaudeSubagent {
3310 }
3311
3312 interface ClaudeLiveQueryContext {
3313 + readonly queryPolicy: ClaudeRuntimeQueryPolicy;
3314 readonly nativeThreadId: string;
3315 readonly query: ClaudeAgentSdkQuerySession;
3316 readonly queryPolicyKey: string;
@@ -3689,6 +3719,44 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
3719 const continuationRequests = adapterOptions.continuationRequests ?? {
3720 offer: () => Effect.void,
3721 };
3722 + const homePath = yield* resolveClaudeHomePath(
3723 + adapterOptions.settings,
3724 + adapterOptions.environment,
3725 + ).pipe(Effect.provideService(Path.Path, path));
3726 + const hostEnvironment = yield* HostProcess.Environment;
3727 + const customHome =
3728 + adapterOptions.settings.homePath.trim().length > 0 ||
3729 + adapterOptions.environment.CLAUDE_CONFIG_DIR !== hostEnvironment.CLAUDE_CONFIG_DIR;
3730 + const announcedBypassDowngrades = new Set<ThreadId>();
3731 + const readBypassSettings = (filePath: string) =>
3732 + fileSystem.readFileString(filePath).pipe(
3733 + Effect.flatMap(decodeClaudeBypassSettings),
3734 + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed({})),
3735 + );
3736 + const resolveBypassAvailability = Effect.fn("ClaudeAdapterV2.resolveBypassAvailability")(
3737 + function* (cwd: string | null) {
3738 + // resolveSettings does not initialize remote-cache eligibility in the SDK host.
3739 + // Keep the payload intact so the SDK also honors managedSourcesBehavior.
3740 + const remote = yield* readBypassSettings(path.join(homePath, "remote-settings.json"));
3741 + const home = customHome
3742 + ? yield* readBypassSettings(path.join(homePath, "settings.json"))
3743 + : {};
3744 + const resolved = yield* Effect.tryPromise(() =>
3745 + resolveClaudeSettings({
3746 + ...(cwd === null ? {} : { cwd }),
3747 + settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
3748 + serverManagedSettings: remote,
3749 + }),
3750 + );
3751 + const cascade = claudeBypassAvailability(resolved.effective);
3752 + const user = claudeBypassAvailability(home);
3753 + const cached = claudeBypassAvailability(remote);
3754 + return {
3755 + bypassDisabled: cascade.bypassDisabled || user.bypassDisabled || cached.bypassDisabled,
3756 + autoDisabled: cascade.autoDisabled || user.autoDisabled || cached.autoDisabled,
3757 + };
3758 + },
3759 + );
3760
3761 const userInvocableSkills = (cwd: string | null) =>
3762 discoverClaudeSkills(
@@ -3777,6 +3845,33 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
3845 const interruptedTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());
3846 const steeredTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());
3847 const queryContext = yield* Ref.make<ClaudeLiveQueryContext | null>(null);
3848 + // A worktree handoff changes the project settings even within one session.
3849 + let bypassCache: { cwd: string | null; availability: ClaudeBypassAvailability } | null =
3850 + null;
3851 + const queryPolicyForTurn = Effect.fnUntraced(function* (
3852 + turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
3853 + ) {
3854 + if (
3855 + permissionModeForClaudeRuntimePolicy(turnInput.runtimePolicy) !== "bypassPermissions"
3856 + ) {
3857 + return claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy);
3858 + }
3859 + const cwd = turnInput.runtimePolicy.cwd;
3860 + if (bypassCache === null || bypassCache.cwd !== cwd) {
3861 + const resolved = yield* resolveBypassAvailability(cwd).pipe(Effect.option);
3862 + if (Option.isNone(resolved)) {
3863 + return claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy, {
3864 + bypassDisabled: true,
3865 + autoDisabled: false,
3866 + });
3867 + }
3868 + bypassCache = { cwd, availability: resolved.value };
3869 + }
3870 + return claudeRuntimeQueryPolicyForRuntimePolicy(
3871 + turnInput.runtimePolicy,
3872 + bypassCache.availability,
3873 + );
3874 + });
3875 const openedNativeThreads = yield* Ref.make(new Set<string>());
3876 const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>());
3877 // Claude 5 task tools edit one list per native session, across turns.
@@ -8824,7 +8919,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8919 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
8920 nativeThreadId: string,
8921 ) {
8827 - const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy);
8922 + const queryPolicy = yield* queryPolicyForTurn(turnInput);
8923 const mcpOverrides = claudeMcpQueryOverrides({
8924 mcpSession: yield* mcpSessions.read(turnInput.threadId),
8925 readOnlySandbox:
@@ -8875,12 +8970,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8970 existing.queryPolicyKey === queryPolicyKey &&
8971 existing.selection.queryIdentity === compiledSelection.queryIdentity
8972 ) {
8878 - // Claude can switch its own mode mid-session (EnterPlanMode), and
8879 - // a denied ExitPlanMode leaves it there. Put the live process back
8880 - // in its initial mode before the next prompt.
8881 - if (existing.permissionMode !== existing.openedPermissionMode) {
8882 - yield* existing.query.setPermissionMode(existing.openedPermissionMode);
8883 - existing.permissionMode = existing.openedPermissionMode;
8973 + // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan:
8974 + // Auto/default may reflect a policy restriction that forbids restoring bypass.
8975 + if (existing.permissionMode === "plan" && existing.openedPermissionMode !== "plan") {
8976 + existing.permissionMode = yield* existing.query
8977 + .setPermissionMode(existing.openedPermissionMode)
8978 + .pipe(
8979 + Effect.as(existing.openedPermissionMode),
8980 + Effect.catchTags({
8981 + ClaudeAgentSdkQueryRunnerError: (error) =>
8982 + existing.openedPermissionMode === "bypassPermissions"
8983 + ? existing.query
8984 + .setPermissionMode("default")
8985 + .pipe(Effect.as("default" as const))
8986 + : Effect.fail(error),
8987 + }),
8988 + );
8989 }
8990 return existing;
8991 }
@@ -8976,6 +9081,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9081 });
9082 const closed = yield* Deferred.make<void, never>();
9083 const context: ClaudeLiveQueryContext = {
9084 + queryPolicy,
9085 nativeThreadId,
9086 query: querySession,
9087 queryPolicyKey,
@@ -9097,8 +9203,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9203 if (!goalsByNativeThread.has(nativeThreadId)) {
9204 goalsByNativeThread.set(nativeThreadId, turnInput.providerThread.goal ?? null);
9205 }
9206 + const userMessage =
9207 + promptUuid === null
9208 + ? null
9209 + : yield* makeClaudeUserMessageWithAttachments({
9210 + text: applyClaudePromptEffortPrefix(
9211 + turnInput.message.text,
9212 + compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
9213 + ),
9214 + attachments: turnInput.message.attachments,
9215 + attachmentsDir,
9216 + fileSystem,
9217 + skills: yield* userInvocableSkills(turnInput.runtimePolicy.cwd),
9218 + uuid: promptUuid,
9219 + });
9220 + const querySession = yield* openQuery(turnInput, nativeThreadId);
9221 const context: ActiveClaudeTurnContext = {
9222 input: turnInput,
9223 + queryPolicy: querySession.queryPolicy,
9224 nativeThreadId,
9225 nativeTurnId,
9226 nativeMessageCursor: null,
@@ -9142,24 +9264,54 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9264 gatedFramesBeforeEcho: 0,
9265 heldRootFrames: [],
9266 };
9145 - const userMessage =
9146 - promptUuid === null
9147 - ? null
9148 - : yield* makeClaudeUserMessageWithAttachments({
9149 - text: applyClaudePromptEffortPrefix(
9150 - turnInput.message.text,
9151 - compileClaudeModelSelection(turnInput.modelSelection).promptEffort,
9152 - ),
9153 - attachments: turnInput.message.attachments,
9154 - attachmentsDir,
9155 - fileSystem,
9156 - skills: yield* userInvocableSkills(turnInput.runtimePolicy.cwd),
9157 - uuid: promptUuid,
9158 - });
9159 - const querySession = yield* openQuery(turnInput, nativeThreadId);
9267 const attachTurn = Effect.gen(function* () {
9268 querySession.lastTurn = context;
9269 yield* Ref.set(activeTurn, context);
9270 + if (
9271 + !isClaudeProviderContinuationTurn(turnInput) &&
9272 + permissionModeForClaudeRuntimePolicy(turnInput.runtimePolicy) ===
9273 + "bypassPermissions" &&
9274 + context.queryPolicy.permissionMode !== "bypassPermissions" &&
9275 + !announcedBypassDowngrades.has(turnInput.threadId)
9276 + ) {
9277 + announcedBypassDowngrades.add(turnInput.threadId);
9278 + if (announcedBypassDowngrades.size > 1000) {
9279 + const oldest = announcedBypassDowngrades.values().next().value;
9280 + if (oldest !== undefined) announcedBypassDowngrades.delete(oldest);
9281 + }
9282 + const nativeItemId = `bypass-policy-downgrade:${context.providerTurnId}`;
9283 + const notice =
9284 + "T3 could not confirm Claude bypass permissions here, so Full access is running with approval checks.";
9285 + yield* emitProviderEvent({
9286 + type: "turn_item.updated",
9287 + driver: CLAUDE_PROVIDER,
9288 + turnItem: {
9289 + id: idAllocator.derive.turnItemFromProviderItem({
9290 + driver: CLAUDE_PROVIDER,
9291 + nativeItemId,
9292 + }),
9293 + threadId: turnInput.threadId,
9294 + runId: turnInput.runId,
9295 + nodeId: turnInput.rootNodeId,
9296 + providerThreadId: turnInput.providerThread.id,
9297 + providerTurnId: context.providerTurnId,
9298 + nativeItemRef: {
9299 + driver: CLAUDE_PROVIDER,
9300 + nativeId: nativeItemId,
9301 + strength: "weak",
9302 + },
9303 + parentItemId: null,
9304 + ordinal: yield* resolveItemOrdinal(context, nativeItemId),
9305 + type: "system_notice",
9306 + status: "completed",
9307 + title: notice,
9308 + message: notice,
9309 + startedAt,
9310 + completedAt: startedAt,
9311 + updatedAt: startedAt,
9312 + },
9313 + });
9314 + }
9315 yield* emitProviderEvent({
9316 type: "provider_turn.updated",
9317 driver: CLAUDE_PROVIDER,
docs/user/permission-modes.md
+3
@@ -35,6 +35,9 @@ session-wide choice, because Grok would remember that command for the whole proj
35 ACP Registry agents run their own tools in their own mode; T3 Code answers their approval requests
36 by the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals).
37
38 +Claude can still ask in **Full access** when its settings disable bypass permissions or require
39 +approval for an action.
40 +
41 Antigravity can still send native approval requests in **Full access**. It only offers remembered
42 approvals for actions that support them.
43