diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 5dbaf3628b11d..e2cf88a15df99 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -215,7 +215,7 @@ const directoryModels = (directory: string): ReadonlyArray ]; const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" }; -const policy = (runtimeMode: "full-access" | "approval-required" = "full-access") => ({ +const policy = (runtimeMode: "full-access" | "approval-required" | "auto" = "full-access") => ({ runtimeMode, interactionMode: "default" as const, cwd: WORK, @@ -242,7 +242,7 @@ const providerThread = (now: DateTime.Utc): OrchestrationV2ProviderThread => ({ const turnInput = ( thread: OrchestrationV2ProviderThread, modelSelection: ModelSelection = bigPickle, - runtimeMode: "full-access" | "approval-required" = "full-access", + runtimeMode: "full-access" | "approval-required" | "auto" = "full-access", ) => ({ appThread: { title: TITLE } as OrchestrationV2AppThread, threadId, @@ -282,7 +282,14 @@ const agentList = { description: "The default agent.", mode: "primary", hidden: false, - permissions: [{ action: "*", resource: "*", effect: "allow" }, ...buildPaths], + permissions: [ + { action: "*", resource: "*", effect: "allow" }, + { action: "shell", resource: "*", effect: "ask" }, + { action: "shell", resource: "rm *", effect: "allow" }, + { action: "shell", resource: "printf *", effect: "allow" }, + { action: "shell", resource: "*", effect: "deny" }, + ...buildPaths, + ], }, ], }; @@ -293,6 +300,20 @@ const supervisedRules = [ ...buildPaths, ...mcpRules, ]; +// Auto keeps the shared asks, then the agent's rules in native order (last match wins), minus +// the catch-all allow so Auto stays stricter than Full access. +const autoRules = [ + { action: "shell", resource: "*", effect: "ask" }, + { action: "edit", resource: "*", effect: "ask" }, + { action: "external_directory", resource: "*", effect: "ask" }, + { action: "shell", resource: "*", effect: "ask" }, + { action: "shell", resource: "rm *", effect: "allow" }, + { action: "shell", resource: "printf *", effect: "allow" }, + { action: "shell", resource: "*", effect: "deny" }, + ...buildPaths, + ...buildPaths, + ...mcpRules, +]; const shellAsk = { data: { @@ -333,6 +354,7 @@ const resumed = ( readonly contextUsage?: OrchestrationV2ProviderThread["contextUsage"]; readonly external?: boolean; readonly supervised?: boolean; + readonly auto?: boolean; readonly processExit?: Effect.Effect; readonly beforeResponse?: (path: string) => Effect.Effect; readonly borrowers?: { current: number }; @@ -362,11 +384,14 @@ const resumed = ( : emptyShellInventory), ])), ...withInstructions([ - ...(options?.supervised === true + ...(options?.supervised === true || options?.auto === true ? [ out("agent.list", ""), reply("agent.list", agentList), - out("session.update", { sessionID: SESSION, permissions: supervisedRules }), + out("session.update", { + sessionID: SESSION, + permissions: options?.auto === true ? autoRules : supervisedRules, + }), reply("session.update", null), ] : []), @@ -406,7 +431,13 @@ const resumed = ( }, threadId, modelSelection: bigPickle, - runtimePolicy: policy(options?.supervised === true ? "approval-required" : "full-access"), + runtimePolicy: policy( + options?.auto === true + ? "auto" + : options?.supervised === true + ? "approval-required" + : "full-access", + ), }); return { runtime, thread }; }); @@ -1575,52 +1606,71 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); - it.effect("gives a background subagent the rules of a mode changed while it runs", () => - Effect.gen(function* () { - const { runtime, thread } = yield* resumed([ - ...backgroundLaunch(CHILD), - event("session.execution.succeeded", { sessionID: SESSION }), - out("agent.list", ""), - reply("agent.list", agentList), - out("session.update", { sessionID: SESSION, permissions: supervisedRules }), - reply("session.update", null), - out("session.update", { - sessionID: CHILD, - permissions: [...supervisedRules.slice(0, 3), ...mcpRules], - }), - reply("session.update", null), - out("session.prompt", { sessionID: SESSION, text: "" }), - promptAccepted, - event("session.execution.succeeded", { sessionID: SESSION }), - ]); - const firstEnded = yield* Deferred.make(); - const ended = yield* runtime.events.pipe( - Stream.filter( - ( - event, - ): event is Extract => - event.type === "turn.terminal", - ), - Stream.tap(() => Deferred.succeed(firstEnded, undefined)), - Stream.take(2), - Stream.runCollect, - Effect.forkScoped, - ); - yield* runtime.startTurn(withLineage(thread)); - yield* Deferred.await(firstEnded); - yield* runtime.startTurn({ - ...withLineage(thread), - runId: RunId.make("run:opencode2-adapter:2"), - runOrdinal: 2, - providerTurnOrdinal: 2, - attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"), - runtimePolicy: policy("approval-required"), - }); - assert.deepEqual( - [...(yield* Fiber.join(ended))].map((terminal) => terminal.status), - ["completed", "completed"], - ); - }), + it.effect.each(["approval-required", "auto"] as const)( + "gives a background subagent the %s rules of a mode changed while it runs", + (mode) => + Effect.gen(function* () { + // Built-in subagents such as explore ship their own allows; Auto must not copy them. + const general = { + ...agentList.data[0]!, + id: "general", + name: "General", + mode: "subagent", + permissions: [ + { action: "*", resource: "*", effect: "deny" }, + { action: "shell", resource: "*", effect: "allow" }, + { action: "external_directory", resource: "*", effect: "allow" }, + ], + }; + const { runtime, thread } = yield* resumed([ + ...backgroundLaunch(CHILD), + event("session.execution.succeeded", { sessionID: SESSION }), + out("agent.list", ""), + reply("agent.list", { ...agentList, data: [...agentList.data, general] }), + out("session.update", { + sessionID: SESSION, + permissions: mode === "auto" ? autoRules : supervisedRules, + }), + reply("session.update", null), + out("session.update", { + sessionID: CHILD, + permissions: [...supervisedRules.slice(0, 3), ...mcpRules], + }), + reply("session.update", null), + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const firstEnded = yield* Deferred.make(); + const ended = yield* runtime.events.pipe( + Stream.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "turn.terminal" } + > => event.type === "turn.terminal", + ), + Stream.tap(() => Deferred.succeed(firstEnded, undefined)), + Stream.take(2), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(withLineage(thread)); + yield* Deferred.await(firstEnded); + yield* runtime.startTurn({ + ...withLineage(thread), + runId: RunId.make("run:opencode2-adapter:2"), + runOrdinal: 2, + providerTurnOrdinal: 2, + attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"), + runtimePolicy: policy(mode), + }); + assert.deepEqual( + [...(yield* Fiber.join(ended))].map((terminal) => terminal.status), + ["completed", "completed"], + ); + }), ); it.effect( @@ -3182,6 +3232,22 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("Auto applies the selected agent's action-specific native rules", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { auto: true }, + ); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn(turnInput(thread, bigPickle, "auto")); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }), + ); + it.effect("counts an answer to a request OpenCode already dropped as delivered", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed( @@ -4394,6 +4460,44 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("Auto reloads native rules after a reconnect", () => + Effect.gen(function* () { + const [build] = agentList.data; + const denied = { action: "shell", resource: "rm *", effect: "deny" }; + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "" }), + promptAccepted, + ...reconnected({}, "succeeded"), + out("agent.list", ""), + reply("agent.list", { + ...agentList, + data: [{ ...build, permissions: [...build!.permissions, denied] }], + }), + out("session.update", { + sessionID: SESSION, + permissions: [ + ...autoRules.slice(0, -mcpRules.length - buildPaths.length), + denied, + ...buildPaths, + ...mcpRules, + ], + }), + reply("session.update", null), + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { auto: true }, + ); + for (let turn = 0; turn < 2; turn++) { + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn(turnInput(thread, bigPickle, "auto")); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + } + }), + ); + it.effect("continues a reply still streaming at reconnect from the text already shown", () => Effect.gen(function* () { const delta = (text: string) => diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index a8f1cf8391221..dea5115ccc65a 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -28,8 +28,10 @@ the parent conversation with the subagent's name, so you can respond without swi Providers enforce permissions differently. Some read-only actions can proceed in **Supervised**. **Auto** uses automatic review on Codex, Claude, Cursor, Grok, Antigravity, and fx; providers without -an equivalent, including OpenCode, fall back to asking. On Grok and Antigravity, actions their review -does not approve come to you for approval. On fx, prompts it still sends also come to you. +an equivalent fall back to asking. OpenCode 2's **Auto** also applies action-specific native permission +rules, so a configured allow can run without a prompt; without those rules it asks. On Grok and +Antigravity, actions their review does not approve come to you for approval. On fx, prompts it still +sends also come to you. Antigravity offers **Auto** only when your Antigravity sign-in provides its Auto mode; some accounts, including some personal Google accounts, do not. Without it, an Antigravity thread already set to diff --git a/docs/user/providers-opencode.md b/docs/user/providers-opencode.md index c686fe10a7c8d..e4dc69659d9c6 100644 --- a/docs/user/providers-opencode.md +++ b/docs/user/providers-opencode.md @@ -62,8 +62,14 @@ session. ## Approvals -OpenCode follows the shared [permission modes](./permission-modes.md). **Auto** has -the same rules as **Supervised** because OpenCode has no AI approval reviewer. +OpenCode follows the shared [permission modes](./permission-modes.md). OpenCode 2's +**Auto** applies the selected agent's native permission rules for specific actions, +so the `permission` (v1) or `permissions` (v2) block in `opencode.jsonc` can allow +routine commands while other commands still ask. Without those rules, **Auto** asks +as **Supervised** does; a catch-all `"*": "allow"` does not remove Auto's default +approval requirements. Subagents' own rules are not applied, so their +commands ask as in **Supervised**. OpenCode 1.x keeps its existing mode rules, where **Auto** +has the same rules as **Supervised**. Environment files such as `.env` and `.env.local` need approval in restricted modes even though normal file reads do not; `.env.example` is allowed. diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9815a3caa96bf..32478534dd0f4 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -447,6 +447,7 @@ const mcpRules = (mcpServerName: string | null): ReadonlyArray => const sessionRules = ( policy: RulesPolicy, + nativeRules: ReadonlyArray, paths: ReadonlyArray, grants: ReadonlyArray, mcpServerName: string | null, @@ -458,6 +459,9 @@ const sessionRules = ( rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"), rule("external_directory", "ask"), ]), + // Auto has no reviewer of its own, so honor the user's action-specific OpenCode rules after + // T3's asks. The default agent's catch-all allow is not an explicit opt-in to unrestricted Auto. + ...nativeRules.filter((entry) => entry.action !== "*" || entry.effect !== "allow"), ...grants, // Plan edits are re-allowed only for plan paths; free-tier sessions refuse denied shell/read. ...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []), @@ -3863,6 +3867,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const previous = currentScope; connection = next; client = next.client; + // A restarted server may have reloaded its config, so relist agent permissions. + agentRules.clear(); nativeGoalSupport = supportsNativeGoals(); session = { ...session, @@ -4048,7 +4054,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* readModels(session.cwd); const agentRules = new Map>>(); - const pathsFor = Effect.fnUntraced(function* ( + const agentRulesFor = Effect.fnUntraced(function* ( directory: string, agents: ReadonlyArray, ) { @@ -4063,39 +4069,43 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr Effect.timeout("5 seconds"), Effect.tapCause((cause) => Effect.logWarning( - "Could not list OpenCode agents; their path rules are skipped.", + "Could not list OpenCode agents; their native rules are skipped.", cause, ).pipe(Effect.annotateLogs({ errorTag: causeErrorTag(cause) })), ), Effect.option, ); if (listed._tag === "None") return []; - known = new Map( - listed.value.data.map((agent) => [agent.id, agentPaths(agent.permissions)]), - ); + known = new Map(listed.value.data.map((agent) => [agent.id, agent.permissions])); agentRules.set(directory, known); } - const paths = new Map(); - for (const agent of agents) { - for (const entry of known.get(agent) ?? []) { - paths.set(`${entry.action}\u0000${entry.resource}`, entry); - } - } - return [...paths.values()]; + // Keep native order: OpenCode's last matching rule wins, so deduplicating would reorder it. + return agents.flatMap((agent) => known.get(agent) ?? []); }); const rulesFor = Effect.fnUntraced(function* ( - thread: Pick, + thread: Pick, policy: RulesPolicy, appThreadId: string | null, ) { const plan = policy.interactionMode === "plan"; + // Built-in subagents ship their own allows (explore allows any shell), so only root agents count. + const nativeRules = + policy.runtimeMode === "auto" && thread.subagent === undefined + ? yield* agentRulesFor(thread.directory, [thread.agent]) + : []; const paths = policy.runtimeMode === "full-access" && !plan ? [] - : yield* pathsFor(thread.directory, plan ? [thread.agent, "plan"] : [thread.agent]); + : agentPaths( + yield* agentRulesFor( + thread.directory, + plan ? [thread.agent, "plan"] : [thread.agent], + ), + ); return sessionRules( policy, + nativeRules, paths, policy.runtimeMode === "full-access" ? [] : thread.grants, appThreadId === null ? null : yield* mcpServerNameFor(appThreadId), @@ -4786,7 +4796,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const directory = threadInput.runtimePolicy.cwd ?? host.paths.cwd; const policy = threadInput.runtimePolicy; const permissions = yield* rulesFor( - { directory, agent: "build", grants: [] }, + { directory, agent: "build", grants: [], subagent: undefined }, policy, threadInput.threadId, );