From 37c3a4072d1b59574c29b13de6c8617e37c7f8c4 Mon Sep 17 00:00:00 2001 From: kousw Date: Thu, 19 Nov 2026 01:27:44 +0900 Subject: [PATCH] feat(runtime): approval_mode.set RPC for GUI clients Add a user-action JSON-RPC request that sets the approval mode of the current project (or the store-wide default) in projects.json, behind the new supports_approval_mode_set capability. - Writes through ProjectsPolicyStore (0600, atomic); other entries kept. - Refused with -32602 and error.data.source when --approval-mode or CODELIA_APPROVAL_MODE decides the mode, so a change that cannot take effect is never reported as applied. - An unparseable policy file is never overwritten. - Idle-only under the run admission lock; a changed file drops the cached agent so the next run rebuilds sandbox/PermissionService. - Result reports the post-write resolved mode (a default write shadowed by a project entry stays visible). Specs: ui-protocol 4.2/5.18, approval-mode 5.2/5.3. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- dev-docs/specs/approval-mode.md | 20 +- dev-docs/specs/ui-protocol.md | 41 ++- packages/protocol/src/capabilities.ts | 2 + packages/protocol/src/methods.ts | 1 + packages/protocol/src/permissions.ts | 24 ++ packages/runtime/AGENTS.md | 1 + packages/runtime/src/agent-factory.ts | 7 +- packages/runtime/src/environment.ts | 11 + .../runtime/src/permissions/approval-mode.ts | 79 ++++- packages/runtime/src/rpc/AGENTS.md | 12 +- packages/runtime/src/rpc/approval-mode.ts | 173 ++++++++++ packages/runtime/src/rpc/handlers.ts | 12 + .../runtime/tests/approval-mode-rpc.test.ts | 304 ++++++++++++++++++ 14 files changed, 670 insertions(+), 19 deletions(-) create mode 100644 packages/runtime/src/rpc/approval-mode.ts create mode 100644 packages/runtime/tests/approval-mode-rpc.test.ts diff --git a/AGENTS.md b/AGENTS.md index a7c667e9..413b1b76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,7 +26,7 @@ Deferred/Backlog ideas are consolidated in `dev-docs/specs/backlog.md`. The UI protocol (Core ⇄ UI) is located in `dev-docs/specs/ui-protocol.md` and `packages/protocol`. Clients that resume a session must bind it with `session.open` before a session-scope `model.set`; otherwise the first `run.start` replaces that choice with the session's saved model override. The runtime environment contract (`dev-docs/specs/runtime-environment-contract.md`) and `packages/runtime/src/environment.ts` define the MVP embedding boundary: omitted runtime options preserve TUI-local behavior, while non-TUI hosts use the side-effect-free `@codelia/runtime/sdk` entrypoint to provide explicit environment contracts and adapters. -GUI-facing management RPCs (spec: `dev-docs/specs/ui-protocol.md` 5.16+) are user actions over JSON-RPC, never model tools: `auth.status` / `auth.login` / `auth.login.complete` / `auth.login.cancel` (+ `auth.login.status` notification, pre-confirmed `auth.logout`) behind `supports_auth_management` (runtime-owned auth only; status never returns credentials; logins invalidate the cached agent via `RuntimeState.requestAgentInvalidation()`); `config.get` / `config.set` behind `supports_config_rw` (allow-listed scalar keys in `packages/runtime/src/config-keys.ts`, value origin per layer, explicit scope, idle-only writes that drop the cached agent); `permissions.list` / `permissions.remove` behind `supports_permissions_rw` (config-file allow/deny rules by structural identity, resolved approval mode read-only); `context.usage` + opt-in `run.context.usage` behind `supports_context_usage` (core `Agent.getContextUsage()`; breakdown is an estimate, used/left provider-reported); subagent `TaskSummary.progress` + opt-in `task.progress` behind `supports_task_progress` (step/phase/tool names only, in-memory, coalesced to 250 ms). +GUI-facing management RPCs (spec: `dev-docs/specs/ui-protocol.md` 5.16+) are user actions over JSON-RPC, never model tools: `auth.status` / `auth.login` / `auth.login.complete` / `auth.login.cancel` (+ `auth.login.status` notification, pre-confirmed `auth.logout`) behind `supports_auth_management` (runtime-owned auth only; status never returns credentials; logins invalidate the cached agent via `RuntimeState.requestAgentInvalidation()`); `config.get` / `config.set` behind `supports_config_rw` (allow-listed scalar keys in `packages/runtime/src/config-keys.ts`, value origin per layer, explicit scope, idle-only writes that drop the cached agent); `permissions.list` / `permissions.remove` behind `supports_permissions_rw` (config-file allow/deny rules by structural identity, resolved approval mode read-only); `approval_mode.set { value, scope: project|default }` behind `supports_approval_mode_set` (writes `projects.json` via the policy store, refused with `-32602` + `error.data.source` when `--approval-mode`/`CODELIA_APPROVAL_MODE` decides the mode, result reports the post-write resolution); `context.usage` + opt-in `run.context.usage` behind `supports_context_usage` (core `Agent.getContextUsage()`; breakdown is an estimate, used/left provider-reported); subagent `TaskSummary.progress` + opt-in `task.progress` behind `supports_task_progress` (step/phase/tool names only, in-memory, coalesced to 250 ms). Client-provided per-run runtime tools use `run.start.tools` / `client.tool.call`; see `dev-docs/specs/ui-protocol.md` and `packages/runtime/src/tools/client.ts`. When adding a custom client tool, keep the tool definition self-sufficient for model use: describe when to prefer it, its limits, sentinel ids/update keys, and result behavior in the schema rather than relying on prompt-side hints. Client tool image results should use `ContentPart.image_url` with inline base64 data URLs and bounded payload sizes. The TUI defines its model-callable client tools in `crates/tui/src/app/runtime/client.rs`: `tui_ask_user_choice`, `tui_open_selector`, `tui_preview_artifact`, `tui_focus_context`, and `tui_show_progress`. Built-in tools created through `defineTool` use `strict: false`, preserve Zod optional/defaulted fields as optional, and rely on runtime Zod validation. Keep model-visible descriptions concise and omit unavailable optional values instead of adding nullable-required sentinels. Stable cross-boundary types (event/session summary, etc.) are placed in packages/shared-types. diff --git a/dev-docs/specs/approval-mode.md b/dev-docs/specs/approval-mode.md index f40c6465..7e7071a7 100644 --- a/dev-docs/specs/approval-mode.md +++ b/dev-docs/specs/approval-mode.md @@ -91,7 +91,25 @@ Rules: - On non-Windows platforms, chmod failures are surfaced as errors (not ignored). 3. Use atomic write (temp file + rename). 4. Never write this file from model tool execution paths (`read`/`write`/`edit`/`bash`). - - Update is only via runtime-owned settings path (startup flow and future explicit CLI command). + - Update is only via runtime-owned settings paths: the startup flow (§8), the + client RPC `approval_mode.set` (§5.3), and a future explicit CLI command. +5. Never overwrite a file that cannot be parsed; report the error instead. + +### 5.3 Client updates (`approval_mode.set`) + +GUI clients change the mode through the `approval_mode.set` JSON-RPC request +(`dev-docs/specs/ui-protocol.md` §5.18, capability `supports_approval_mode_set`). +It is an explicit user action, not a model tool. + +- `scope: "project"` writes `projects[]` for the runtime's current + workspace (§6); `scope: "default"` writes `default`. Other entries are kept. +- If a higher-priority source (§4: CLI flag or `CODELIA_APPROVAL_MODE`) decides + the mode, the request is rejected and nothing is written; the runtime never + reports a change that cannot take effect. +- The result includes the mode resolved after the write, so a `default` write + shadowed by a project entry is visible to the client. +- Writes are rejected during an active run. A change drops the cached agent; the + next run rebuilds it with the new mode. --- diff --git a/dev-docs/specs/ui-protocol.md b/dev-docs/specs/ui-protocol.md index 4e39243a..563d4fb6 100644 --- a/dev-docs/specs/ui-protocol.md +++ b/dev-docs/specs/ui-protocol.md @@ -158,6 +158,8 @@ Runtime side: `auth.logout`, see 5.16) - `supports_config_rw` (`config.get` / `config.set` over registry keys, see 5.17) - `supports_permissions_rw` (`permissions.list` / `permissions.remove`, see 5.18) +- `supports_approval_mode_set` (`approval_mode.set` writes the approval-mode + policy store, see 5.18) - `supports_context_usage` (`context.usage` request and opt-in `run.context.usage` notification, see 5.19) - `supports_task_progress` (`TaskSummary.progress` and opt-in `task.progress` @@ -1151,8 +1153,43 @@ type PermissionRuleEntry = { drops the cached agent so its `PermissionService` (including in-memory remembered rules) is rebuilt on the next run. - Removing a `deny` rule loosens policy; clients should confirm with the user. - The approval mode itself is not changed by this API (§5 of approval-mode.md - keeps mode updates in runtime-owned setup flows). + The approval mode itself is not changed by `permissions.remove`; use + `approval_mode.set` below. + +`approval_mode.set` is a separate request behind +`server_capabilities.supports_approval_mode_set` (runtime-owned config and a +local runtime whose agent resolves its mode from the policy store; other hosts +always run `minimal` and reject with `-32602`). It is a user action over +JSON-RPC, never a model tool, and writes the global policy file +(`projects.json`, `dev-docs/specs/approval-mode.md` §5) with its 0600 / +atomic-write rules. + +- `approval_mode.set { value: "minimal" | "trusted" | "full-access", scope: + "project" | "default" }` → + `{ scope, value, path, changed, approval_mode: { value, source }, applies: "next_run" }`. + `scope` is required. `project` sets the entry keyed by this workspace's + normalized root (approval-mode.md §6, the same root the agent resolves); + `default` sets the store-wide default entry. Other entries are preserved. + `changed: false` means the entry already had that value and nothing was + written. +- `approval_mode` is the mode the next run resolves for this workspace after the + write, as in `permissions.list`. It can differ from `value`: a `default` write + under an existing project entry reports `source: "project"`. +- Overrides: when `--approval-mode` or `CODELIA_APPROVAL_MODE` is set (or is + invalid), the request is rejected with `-32602` and + `error.data = { source: "cli" | "env", value }` (no `data` when the override is + invalid). Nothing is written, so a client never shows a change that cannot + take effect for this runtime. Clients should disable the control when + `permissions.list` reports `source: "cli" | "env"`. +- An unparseable policy file is never overwritten: the request fails with + `-32000` and the file is left as-is (no contents echoed). +- Writes are idle-only (`-32001` during a run, rechecked under the run + admission lock). A write that changes the file drops the cached agent; the + next `run.start` rebuilds the sandbox context and `PermissionService` with the + new mode and restores the session history. Running subagents keep their + snapshot. +- Raising the mode (especially to `full-access`) loosens policy; clients should + confirm with the user. ### 5.19 Context usage (`context.usage` / `run.context.usage`, optional) diff --git a/packages/protocol/src/capabilities.ts b/packages/protocol/src/capabilities.ts index 16524b4e..f16490f6 100644 --- a/packages/protocol/src/capabilities.ts +++ b/packages/protocol/src/capabilities.ts @@ -49,6 +49,8 @@ export type ServerCapabilities = { supports_config_rw?: boolean; /** permissions.list/permissions.remove over config-file rules. */ supports_permissions_rw?: boolean; + /** approval_mode.set writes the policy store (`projects.json`). */ + supports_approval_mode_set?: boolean; /** context.usage request and opt-in run.context.usage notification. */ supports_context_usage?: boolean; supports_tool_call?: boolean; diff --git a/packages/protocol/src/methods.ts b/packages/protocol/src/methods.ts index c5f6c107..a10f5d14 100644 --- a/packages/protocol/src/methods.ts +++ b/packages/protocol/src/methods.ts @@ -35,6 +35,7 @@ export type ProtocolMethod = | "config.set" | "permissions.list" | "permissions.remove" + | "approval_mode.set" | "model.list" | "model.set" | "image.model.get" diff --git a/packages/protocol/src/permissions.ts b/packages/protocol/src/permissions.ts index 441e90b2..bb0e3dd2 100644 --- a/packages/protocol/src/permissions.ts +++ b/packages/protocol/src/permissions.ts @@ -61,3 +61,27 @@ export type PermissionsRemoveResult = { path: string; removed: number; }; + +/** `project` = this workspace's entry, `default` = the store-wide default entry. */ +export type ApprovalModeScope = "project" | "default"; + +export type ApprovalModeSetParams = { + value: ApprovalMode; + /** Required; there is no implicit target. */ + scope: ApprovalModeScope; +}; + +export type ApprovalModeSetResult = { + scope: ApprovalModeScope; + value: ApprovalMode; + /** Global policy file (`projects.json`). */ + path: string; + /** false when the entry already had this value (nothing written). */ + changed: boolean; + /** + * Mode the next run resolves for this workspace after the write. It can + * differ from `value`, e.g. a `default` write under an existing project entry. + */ + approval_mode: { value: ApprovalMode; source: ApprovalModeSource }; + applies: "next_run"; +}; diff --git a/packages/runtime/AGENTS.md b/packages/runtime/AGENTS.md index 8398e398..bf44842c 100644 --- a/packages/runtime/AGENTS.md +++ b/packages/runtime/AGENTS.md @@ -128,6 +128,7 @@ Before running the tool, determine permission and obtain approval using UI confi System tool allowlist (`minimal`/`trusted`) includes `read_line` and `tool_output_cache_line` so fail-fast read fallbacks can continue without extra confirms. Approval mode is resolved in runtime with precedence `--approval-mode` flag > `CODELIA_APPROVAL_MODE` > global `projects.json` project entry > global `projects.json` default > startup selection (UI pick, unresolved only) > fallback `minimal`. Invalid approval-mode values from CLI/env are surfaced as explicit errors (not silently ignored). +Clients change the stored mode only through `approval_mode.set` (`src/rpc/approval-mode.ts`, `writeApprovalModePolicy`); it is refused while a CLI/env override decides the mode. Model tools never write `projects.json`. `projects.json` is loaded from storage config dir (`~/.codelia/projects.json` or XDG config equivalent) and keyed by normalized sandbox root/project path. If `projects.json` is malformed/invalid, runtime surfaces an explicit load error (no silent fallback). When logging permission preflight context, flush those `agent.event` messages before sending `ui.confirm.request` so UI history is rendered before the modal confirm appears (legacy raw-args JSON text is not emitted; use structured `permission.preview`/`permission.ready` events). diff --git a/packages/runtime/src/agent-factory.ts b/packages/runtime/src/agent-factory.ts index de55113a..12e085ea 100644 --- a/packages/runtime/src/agent-factory.ts +++ b/packages/runtime/src/agent-factory.ts @@ -21,7 +21,7 @@ import { openBrowser } from "./auth/openai-oauth"; import { resolveImageGenerationConfig } from "./config"; import { createDecisionTool } from "./decisions/tool"; import { resolveEffectiveModelConfig } from "./effective-model"; -import { isTuiLocalEnvironment } from "./environment"; +import { isLocalRuntimeEnabled, isTuiLocalEnvironment } from "./environment"; import { appendEnvironmentPermissionAllowRules, createEnvironmentAuthResolver, @@ -218,10 +218,7 @@ export const createAgentFactory = ( state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? undefined; - const localRuntimeEnabled = - environment.workspace.filesystem === "enabled" || - environment.workspace.process === "runtime" || - environment.tools.builtin === "full-coding-agent"; + const localRuntimeEnabled = isLocalRuntimeEnabled(environment); let approvalModeResolution: { approvalMode: ApprovalMode; source: string; diff --git a/packages/runtime/src/environment.ts b/packages/runtime/src/environment.ts index f9137bb8..ffb9d817 100644 --- a/packages/runtime/src/environment.ts +++ b/packages/runtime/src/environment.ts @@ -458,3 +458,14 @@ export const isProcessEnabled = ( export const isFilesystemEnabled = ( environment: EffectiveRuntimeEnvironment, ): boolean => environment.workspace.filesystem === "enabled"; + +/** + * The agent builds a local sandbox and resolves the approval mode from + * CLI/env/`projects.json`; otherwise the mode is fixed to `minimal`. + */ +export const isLocalRuntimeEnabled = ( + environment: EffectiveRuntimeEnvironment, +): boolean => + environment.workspace.filesystem === "enabled" || + environment.workspace.process === "runtime" || + environment.tools.builtin === "full-coding-agent"; diff --git a/packages/runtime/src/permissions/approval-mode.ts b/packages/runtime/src/permissions/approval-mode.ts index fd63a489..bbaa2ecf 100644 --- a/packages/runtime/src/permissions/approval-mode.ts +++ b/packages/runtime/src/permissions/approval-mode.ts @@ -126,6 +126,74 @@ const persistProjectApprovalModeOrThrow = async ( }); }; +/** + * CLI flag / `CODELIA_APPROVAL_MODE`, which take precedence over the policy + * store. Throws on an invalid value (no silent fallthrough). + */ +export const resolveApprovalModeOverride = (): + | { approvalMode: ApprovalMode; source: "cli" | "env" } + | undefined => { + const cliMode = resolveCliApprovalModeOrThrow(process.argv.slice(2)); + if (cliMode) return { approvalMode: cliMode, source: "cli" }; + const envMode = resolveEnvApprovalModeOrThrow(process.env); + if (envMode) return { approvalMode: envMode, source: "env" }; + return undefined; +}; + +export type ApprovalModePolicyScope = "project" | "default"; + +/** The existing policy store could not be read; nothing was written. */ +export class ApprovalModePolicyUnreadableError extends Error {} + +/** + * Sets one entry of the policy store. An unreadable store throws instead of + * being overwritten. Returns whether the file was written. + */ +export const writeApprovalModePolicy = async ( + { + scope, + projectKey, + approvalMode, + }: { + scope: ApprovalModePolicyScope; + projectKey: string; + approvalMode: ApprovalMode; + }, + deps: ResolveApprovalModeDeps = {}, +): Promise<{ changed: boolean; path: string }> => { + const store = deps.store ?? new ProjectsPolicyStore(); + let policy: ProjectsPolicyFile; + try { + policy = (await loadProjectsPolicyOrThrow(store)) ?? { version: 1 }; + } catch (error) { + throw new ApprovalModePolicyUnreadableError( + error instanceof Error ? error.message : String(error), + ); + } + const current = + scope === "project" + ? policy.projects?.[projectKey]?.approval_mode + : policy.default?.approval_mode; + if (current === approvalMode) { + return { changed: false, path: store.getFilePath() }; + } + if (scope === "project") { + await persistProjectApprovalModeOrThrow( + store, + projectKey, + approvalMode, + policy, + ); + } else { + await store.save({ + ...policy, + version: 1, + default: { ...(policy.default ?? {}), approval_mode: approvalMode }, + }); + } + return { changed: true, path: store.getFilePath() }; +}; + export type ApprovalModeResolutionSource = | "cli" | "env" @@ -161,14 +229,9 @@ export const resolveApprovalModeForRuntime = async ( options.runtimeSandboxRoot, ); - const cliMode = resolveCliApprovalModeOrThrow(process.argv.slice(2)); - if (cliMode) { - return { approvalMode: cliMode, source: "cli", projectKey }; - } - - const envMode = resolveEnvApprovalModeOrThrow(process.env); - if (envMode) { - return { approvalMode: envMode, source: "env", projectKey }; + const override = resolveApprovalModeOverride(); + if (override) { + return { ...override, projectKey }; } const store = deps.store ?? new ProjectsPolicyStore(); diff --git a/packages/runtime/src/rpc/AGENTS.md b/packages/runtime/src/rpc/AGENTS.md index c74a7b20..ddd917f0 100644 --- a/packages/runtime/src/rpc/AGENTS.md +++ b/packages/runtime/src/rpc/AGENTS.md @@ -41,6 +41,14 @@ resolves the approval mode without startup selection (never prompts/persists). Removal is structural (all rule fields), idle-only, and invalidates the cached agent; it never edits `projects.json`. +`approval-mode.ts` implements `approval_mode.set` behind +`supports_approval_mode_set` (runtime-owned config and `isLocalRuntimeEnabled`). +It writes one `projects.json` entry (`project` = the agent's workspace key, +`default`) through `writeApprovalModePolicy` / `ProjectsPolicyStore` (0600, +atomic). A CLI/env override is refused before any write; an unparseable store +is never overwritten. Idle-only under the admission lock; only a changed file +invalidates the cached agent. The result reports the post-write resolution. + `context-usage.ts` serves `context.usage` from the cached agent only (never builds one) and emits opt-in `run.context.usage` once per new provider usage object or compaction. Emission is best-effort and never fails a run. @@ -49,8 +57,8 @@ object or compaction. Emission is best-effort and never fails a run. streams opt-in `task.progress` (state changes immediately, progress coalesced to 250 ms per task, trailing timer unref'd). -Idle-only management writes (`config.set`, `permissions.remove`, API-key -`auth.login`) recheck `activeRunId` and write inside +Idle-only management writes (`config.set`, `permissions.remove`, +`approval_mode.set`, API-key `auth.login`) recheck `activeRunId` and write inside `RuntimeState.withAdmissionLock()`, which `run.start` admission also holds until `beginRun`; a write and a run admission can never interleave. Credential changes go through `AuthStore.update()` / `clearAll()` (per-file queue). An diff --git a/packages/runtime/src/rpc/approval-mode.ts b/packages/runtime/src/rpc/approval-mode.ts new file mode 100644 index 00000000..c37a136c --- /dev/null +++ b/packages/runtime/src/rpc/approval-mode.ts @@ -0,0 +1,173 @@ +import { + type ApprovalModeSetParams, + type ApprovalModeSetResult, + RPC_ERROR_CODE, +} from "@codelia/protocol"; +import { parseApprovalMode } from "@codelia/shared-types"; +import { isLocalRuntimeEnabled } from "../environment"; +import { + ApprovalModePolicyUnreadableError, + resolveApprovalModeForRuntime, + resolveApprovalModeOverride, + resolveProjectPolicyKey, + writeApprovalModePolicy, +} from "../permissions/approval-mode"; +import type { RuntimeState } from "../runtime-state"; +import { resolveConfigWorkspaceDir, supportsConfigReadWrite } from "./config"; +import { sendError, sendResult } from "./transport"; + +/** + * Runtime-owned config, and an agent that actually resolves its approval mode + * from the policy store (non-local hosts always run `minimal`). + */ +export const supportsApprovalModeSet = (state: RuntimeState): boolean => + supportsConfigReadWrite(state) && + isLocalRuntimeEnabled(state.effectiveEnvironment); + +const OVERRIDE_LABEL = { + cli: "--approval-mode", + env: "CODELIA_APPROVAL_MODE", +} as const; + +export const createApprovalModeHandlers = ({ + state, + log, +}: { + state: RuntimeState; + log: (message: string) => void; +}) => { + const handleApprovalModeSet = async ( + id: string, + params: ApprovalModeSetParams | undefined, + ): Promise => { + const invalid = (message: string, data?: unknown) => + sendError(id, { + code: RPC_ERROR_CODE.INVALID_PARAMS, + message, + ...(data !== undefined ? { data } : {}), + }); + if (!supportsApprovalModeSet(state)) { + invalid("approval mode is not configurable for this runtime"); + return; + } + const scope = params?.scope; + if (scope !== "project" && scope !== "default") { + invalid("scope must be project or default"); + return; + } + const value = + typeof params?.value === "string" + ? parseApprovalMode(params.value) + : undefined; + if (!value) { + invalid("value must be minimal, trusted or full-access"); + return; + } + if (state.activeRunId) { + sendError(id, { + code: RPC_ERROR_CODE.RUNTIME_BUSY, + message: "runtime busy", + }); + return; + } + // A higher-priority source decides the mode for this runtime process, so a + // store write could not take effect: refuse instead of pretending it applied. + let override: ReturnType; + try { + override = resolveApprovalModeOverride(); + } catch { + invalid("approval mode override (--approval-mode or env) is invalid"); + return; + } + if (override) { + invalid( + `approval mode is fixed by ${OVERRIDE_LABEL[override.source]} for this runtime`, + { source: override.source, value: override.approvalMode }, + ); + return; + } + + // Same root the agent factory resolves the project key from. + const sandboxRoot = resolveConfigWorkspaceDir(state) ?? process.cwd(); + type Outcome = + | "busy" + | { changed: boolean; path: string } + | { failed: "load" | "write" }; + let outcome: Outcome; + try { + // Recheck idleness under the admission lock so no run starts mid-write. + outcome = await state.withAdmissionLock(async (): Promise => { + if (state.activeRunId) return "busy"; + const projectKey = await resolveProjectPolicyKey( + sandboxRoot, + sandboxRoot, + ); + let written: { changed: boolean; path: string }; + try { + written = await writeApprovalModePolicy({ + scope, + projectKey, + approvalMode: value, + }); + } catch (error) { + return { + failed: + error instanceof ApprovalModePolicyUnreadableError + ? "load" + : "write", + }; + } + // The mode is baked into the sandbox context and PermissionService. + if (written.changed) state.requestAgentInvalidation(); + return written; + }); + } catch { + outcome = { failed: "write" }; + } + if (outcome === "busy") { + sendError(id, { + code: RPC_ERROR_CODE.RUNTIME_BUSY, + message: "runtime busy", + }); + return; + } + if ("failed" in outcome) { + sendError(id, { + code: RPC_ERROR_CODE.RUNTIME_INTERNAL, + message: + outcome.failed === "load" + ? "approval mode policy could not be parsed; nothing was written" + : "approval mode policy write failed", + }); + return; + } + let resolved: Awaited>; + try { + // No startup selection: never prompts or persists. + resolved = await resolveApprovalModeForRuntime({ + workingDir: sandboxRoot, + runtimeSandboxRoot: sandboxRoot, + }); + } catch { + sendError(id, { + code: RPC_ERROR_CODE.RUNTIME_INTERNAL, + message: "approval mode could not be resolved after the write", + }); + return; + } + const result: ApprovalModeSetResult = { + scope, + value, + path: outcome.path, + changed: outcome.changed, + approval_mode: { value: resolved.approvalMode, source: resolved.source }, + applies: "next_run", + }; + sendResult(id, result); + log( + `approval_mode.set scope=${scope} value=${value} changed=${outcome.changed} resolved=${resolved.approvalMode}/${resolved.source}`, + ); + }; + + return { handleApprovalModeSet }; +}; diff --git a/packages/runtime/src/rpc/handlers.ts b/packages/runtime/src/rpc/handlers.ts index 49ef55da..a7b0b257 100644 --- a/packages/runtime/src/rpc/handlers.ts +++ b/packages/runtime/src/rpc/handlers.ts @@ -7,6 +7,7 @@ import type { ToolOutputCacheStore, } from "@codelia/core"; import { + type ApprovalModeSetParams, type AuthLoginCancelParams, type AuthLoginCompleteParams, type AuthLoginParams, @@ -81,6 +82,10 @@ import { VolatileSessionStateStore, VolatileToolOutputCacheStore, } from "../volatile-stores"; +import { + createApprovalModeHandlers, + supportsApprovalModeSet, +} from "./approval-mode"; import { handleAttachmentUpload } from "./attachment"; import { createAuthLogoutHandler } from "./auth"; import { @@ -578,6 +583,7 @@ export const createRuntimeHandlers = ({ supports_context_inspect: true, supports_config_rw: supportsConfigReadWrite(state), supports_permissions_rw: supportsConfigReadWrite(state), + supports_approval_mode_set: supportsApprovalModeSet(state), supports_context_usage: true, supports_tool_call: true, supports_theme_set: themeSetEnabled, @@ -662,6 +668,7 @@ export const createRuntimeHandlers = ({ const authHandlers = createAuthManagementHandlers({ state, log }); const configHandlers = createConfigHandlers({ state, log }); const permissionsHandlers = createPermissionsHandlers({ state, log }); + const approvalModeHandlers = createApprovalModeHandlers({ state, log }); const contextUsageHandlers = createContextUsageHandlers({ state, log }); const handleRequest = async (req: RpcRequest): Promise => { @@ -744,6 +751,11 @@ export const createRuntimeHandlers = ({ req.id, req.params as PermissionsRemoveParams, ); + case "approval_mode.set": + return approvalModeHandlers.handleApprovalModeSet( + req.id, + req.params as ApprovalModeSetParams, + ); case "model.list": return handleModelList(req.id, req.params as ModelListParams); case "image.model.get": diff --git a/packages/runtime/tests/approval-mode-rpc.test.ts b/packages/runtime/tests/approval-mode-rpc.test.ts new file mode 100644 index 00000000..589ab1d7 --- /dev/null +++ b/packages/runtime/tests/approval-mode-rpc.test.ts @@ -0,0 +1,304 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { + mkdir, + mkdtemp, + readFile, + realpath, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { Agent } from "@codelia/core"; +import type { RpcMessage } from "@codelia/protocol"; +import { createRuntimeHandlers } from "../src/rpc/handlers"; +import { RuntimeState } from "../src/runtime-state"; + +let root: string; +let workspace: string; +let projectKey: string; +let projectsPath: string; +let state: RuntimeState; +let messages: RpcMessage[]; +let restoreStdout: () => void; +let handlers: ReturnType; +const env = new Map(); +const originalArgv = process.argv; + +const setEnv = (key: string, value: string | undefined): void => { + if (!env.has(key)) env.set(key, process.env[key]); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; +}; + +const newAgent = (): Agent => + new Agent({ + tools: [], + llm: { + provider: "openai", + model: "gpt-6-astra", + async ainvoke() { + throw new Error("Must not generate"); + }, + }, + }); + +beforeEach(async () => { + root = await mkdtemp(path.join(os.tmpdir(), "codelia-approval-mode-rpc-")); + workspace = path.join(root, "workspace"); + await mkdir(workspace, { recursive: true }); + for (const [key, value] of Object.entries({ + CODELIA_LAYOUT: "xdg", + CODELIA_CONFIG_PATH: path.join(root, "global.json"), + CODELIA_SANDBOX_ROOT: workspace, + XDG_CONFIG_HOME: path.join(root, "config"), + XDG_STATE_HOME: path.join(root, "state"), + XDG_DATA_HOME: path.join(root, "data"), + XDG_CACHE_HOME: path.join(root, "cache"), + })) { + setEnv(key, value); + } + setEnv("CODELIA_APPROVAL_MODE", undefined); + projectKey = await realpath(workspace); + projectsPath = path.join(root, "config", "codelia", "projects.json"); + state = new RuntimeState(); + state.runtimeWorkingDir = workspace; + state.approvalMode = "minimal"; + state.agent = newAgent(); + messages = []; + const write = process.stdout.write; + process.stdout.write = ((chunk: string | Uint8Array) => { + messages.push(JSON.parse(String(chunk)) as RpcMessage); + return true; + }) as typeof process.stdout.write; + restoreStdout = () => { + process.stdout.write = write; + }; + handlers = createRuntimeHandlers({ + state, + log: () => {}, + getAgent: async () => { + throw new Error("Must not create an agent for approval_mode.set"); + }, + }); +}); + +afterEach(async () => { + restoreStdout(); + process.argv = originalArgv; + for (const [key, value] of env) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + env.clear(); + await rm(root, { recursive: true, force: true }); +}); + +type Response = { + id?: string; + method?: string; + result?: Record; + error?: { code: number; message: string; data?: unknown }; +}; + +let seq = 0; +const request = async (method: string, params?: unknown): Promise => { + seq += 1; + const id = `approval-mode-${seq}`; + handlers.processMessage({ jsonrpc: "2.0", id, method, params }); + const deadline = Date.now() + 2000; + for (;;) { + const found = (messages as Response[]).find( + (message) => message.id === id && !message.method, + ); + if (found) return found; + if (Date.now() > deadline) throw new Error(`${method} did not settle`); + await Bun.sleep(1); + } +}; + +const readPolicy = async (): Promise => + JSON.parse(await readFile(projectsPath, "utf8")); + +test("initialize advertises approval_mode.set for runtime-owned config", async () => { + const response = await request("initialize", { + protocol_version: "0", + client: { name: "gui", version: "0" }, + }); + expect( + (response.result?.server_capabilities as Record) + ?.supports_approval_mode_set, + ).toBe(true); +}); + +test("approval_mode.set project writes this workspace's entry 0600 and drops the cached agent", async () => { + const response = await request("approval_mode.set", { + scope: "project", + value: "trusted", + }); + expect(response.result).toEqual({ + scope: "project", + value: "trusted", + path: projectsPath, + changed: true, + approval_mode: { value: "trusted", source: "project" }, + applies: "next_run", + }); + expect(await readPolicy()).toEqual({ + version: 1, + projects: { [projectKey]: { approval_mode: "trusted" } }, + }); + if (process.platform !== "win32") { + expect((await stat(projectsPath)).mode & 0o777).toBe(0o600); + } + expect(state.agent).toBeNull(); + + const listed = await request("permissions.list"); + expect(listed.result?.approval_mode).toEqual({ + value: "trusted", + source: "project", + }); + + // Same value again: nothing is written and a rebuilt agent stays cached. + const agent = newAgent(); + state.agent = agent; + const before = await readFile(projectsPath, "utf8"); + const again = await request("approval_mode.set", { + scope: "project", + value: "trusted", + }); + expect(again.result?.changed).toBe(false); + expect(await readFile(projectsPath, "utf8")).toBe(before); + expect(state.agent).toBe(agent); +}); + +test("approval_mode.set default keeps other entries and reports a shadowing project entry", async () => { + const other = path.join(root, "other-project"); + await mkdir(path.dirname(projectsPath), { recursive: true }); + await writeFile( + projectsPath, + JSON.stringify({ + version: 1, + projects: { + [other]: { approval_mode: "full-access" }, + [projectKey]: { approval_mode: "minimal" }, + }, + }), + ); + const response = await request("approval_mode.set", { + scope: "default", + value: "trusted", + }); + expect(response.result).toMatchObject({ + scope: "default", + value: "trusted", + changed: true, + // The project entry still wins for this workspace. + approval_mode: { value: "minimal", source: "project" }, + }); + expect(await readPolicy()).toEqual({ + version: 1, + default: { approval_mode: "trusted" }, + projects: { + [other]: { approval_mode: "full-access" }, + [projectKey]: { approval_mode: "minimal" }, + }, + }); +}); + +test("approval_mode.set refuses when the CLI flag or env decides the mode", async () => { + setEnv("CODELIA_APPROVAL_MODE", "full-access"); + const byEnv = await request("approval_mode.set", { + scope: "project", + value: "minimal", + }); + expect(byEnv.error).toMatchObject({ + code: -32602, + data: { source: "env", value: "full-access" }, + }); + setEnv("CODELIA_APPROVAL_MODE", undefined); + process.argv = [...originalArgv, "--approval-mode=trusted"]; + const byCli = await request("approval_mode.set", { + scope: "default", + value: "minimal", + }); + expect(byCli.error).toMatchObject({ + code: -32602, + data: { source: "cli", value: "trusted" }, + }); + process.argv = [...originalArgv, "--approval-mode", "bogus"]; + expect( + (await request("approval_mode.set", { scope: "project", value: "minimal" })) + .error?.code, + ).toBe(-32602); + await expect(stat(projectsPath)).rejects.toThrow(); + expect(state.agent).not.toBeNull(); +}); + +test("approval_mode.set with bad input, while busy, or over a broken store writes nothing", async () => { + for (const params of [ + { scope: "global", value: "trusted" }, + { scope: "project", value: "yolo" }, + { scope: "project", value: 1 }, + { value: "trusted" }, + { scope: "project" }, + ]) { + expect((await request("approval_mode.set", params)).error?.code).toBe( + -32602, + ); + } + state.activeRunId = "run-1"; + expect( + (await request("approval_mode.set", { scope: "project", value: "trusted" })) + .error?.code, + ).toBe(-32001); + state.activeRunId = null; + await expect(stat(projectsPath)).rejects.toThrow(); + + await mkdir(path.dirname(projectsPath), { recursive: true }); + await writeFile(projectsPath, "{ not json"); + const broken = await request("approval_mode.set", { + scope: "project", + value: "trusted", + }); + expect(broken.error).toMatchObject({ code: -32000 }); + expect(broken.error?.message).not.toContain("not json"); + expect(await readFile(projectsPath, "utf8")).toBe("{ not json"); + expect(state.agent).not.toBeNull(); +}); + +test("approval_mode.set waits for an in-flight run admission and then reports busy", async () => { + let releaseAdmission!: () => void; + const admission = state.withAdmissionLock( + () => + new Promise((resolve) => { + releaseAdmission = () => { + state.activeRunId = "run-admitted"; + resolve(); + }; + }), + ); + const pending = request("approval_mode.set", { + scope: "project", + value: "trusted", + }); + await Bun.sleep(20); + releaseAdmission(); + await admission; + expect((await pending).error?.code).toBe(-32001); + await expect(stat(projectsPath)).rejects.toThrow(); +}); + +test("approval_mode.set is unavailable for host-owned config", async () => { + state.effectiveEnvironment = { + ...state.effectiveEnvironment, + config: { ...state.effectiveEnvironment.config, source: "host" }, + }; + const response = await request("approval_mode.set", { + scope: "project", + value: "trusted", + }); + expect(response.error?.code).toBe(-32602); + await expect(stat(projectsPath)).rejects.toThrow(); +});