Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 19 additions & 1 deletion dev-docs/specs/approval-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -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[<project key>]` 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.

---

Expand Down
41 changes: 39 additions & 2 deletions dev-docs/specs/ui-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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)

Expand Down
2 changes: 2 additions & 0 deletions packages/protocol/src/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions packages/protocol/src/methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export type ProtocolMethod =
| "config.set"
| "permissions.list"
| "permissions.remove"
| "approval_mode.set"
| "model.list"
| "model.set"
| "image.model.get"
Expand Down
24 changes: 24 additions & 0 deletions packages/protocol/src/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
};
1 change: 1 addition & 0 deletions packages/runtime/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
7 changes: 2 additions & 5 deletions packages/runtime/src/agent-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions packages/runtime/src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
79 changes: 71 additions & 8 deletions packages/runtime/src/permissions/approval-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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();
Expand Down
12 changes: 10 additions & 2 deletions packages/runtime/src/rpc/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
Loading
Loading