Skip to content

Agent Access and Permissions

matthew edited this page Sep 14, 2026 · 2 revisions

Agent access and permissions

How Studio bounds what an AI agent can see and do: providers and connections, authentication, write and network confinement, tool permissions, the audit log, and the live-session lifecycle. The tools an agent reaches on each tab type are on Agent MCP capabilities.

5. AI agent — access & permission model

How Studio bounds what an AI agent can see and do. Enforcement lives in the main process (src/shared/electron/ai/*); the renderer runtime is src/shared/angular/services/ai-runtime.

Providers & connections. Providers are data, not code. A user-editable list of connections (AiConnection: id, kind, label, base URL, auth kind, model list) is persisted in settings and managed in the AI settings section; the built-in seeds (Claude, an Anthropic API-key connection, and a local Ollama) can be extended with any OpenAI-compatible, xAI, Google, DeepSeek, or custom endpoint without new code. Three provider implementations back them, dispatched on the connection's auth kind: ClaudeAgentProvider (the Claude Agent SDK, local-login path) for a claude-login connection, CodexAgentProvider (OpenAI Codex via @openai/codex-sdk) for a codex-login connection, and the generic AiSdkAdapter (Vercel AI SDK, dispatched by kind + base URL) for every other. The renderer passes its connections to AiManager.listProviders, which rebuilds its provider set from them, so a user's own connection is immediately runnable; AgentEngine owns the active connection + per-connection model selection.

Authentication. Each connection resolves its own credential, keyed by connection id, through an AuthStrategy (api-key / none / claude-login / codex-login; OAuth is a future drop-in). A claude-login connection uses the user's local Claude login (~/.claude, the same credential Claude Code uses) and a codex-login connection the user's local Codex login (~/.codex) — independent probes; an api-key connection uses a per-connection API key stored encrypted at rest via OS secure-storage (safeStorage, in AiAuthManager over a pure CredentialStore). Keys never cross the contextBridge; only narrow per-connection status, config, and run-control calls are exposed. A key stored by a pre-connections build migrates onto the built-in Anthropic API-key connection.

Scope of a run. The working directory is the open workspace root (or the user's home when none is open) — never Studio's install directory. Every run is cancellable; aborting interrupts the current turn — a held-open live session survives for the next turn (see Session lifecycle below) — and denies any pending permission prompt.

Write confinement. When a workspace is open, a granted file write (Write/Edit/MultiEdit/ NotebookEdit) is refused if its target resolves outside the workspace root — a hard boundary that approving the action cannot widen (a prompt authorises what an action does, not where; a single click must not be able to escape the root). Widening the allowed area is a configuration decision, not a per-prompt override: settings carry allowed write paths (extra directories the agent may write to) and denied write paths (paths it may never write to — an absolute path or a bare segment like .git/.env — a sharper guard applied even inside an allowed root). Bash writes cannot be range-checked from the command text, so they are backed by the SDK OS sandbox instead (enabled, degrading gracefully where unavailable) — the deny list therefore guards the file-write tools, not Bash. A no-workspace (home) run is root-unconfined but still honours the deny list. Confinement is evaluated before the posture, so it holds even under an auto-allowing posture.

Network confinement. The agent's egress is bounded by the same widen/narrow pair, in a different medium: allowed network locations (host patterns — api.example.com, *.corp.example; empty means anywhere, so the setting is opt-in) and denied network locations, which win over the allowed list. Patterns match the sandbox's way, label for label: *.example.com covers api.example.com but not deep.api.example.com, the wildcard lives in the leftmost label only, and * and *.com are refused as too broad (where they are typed, not silently on the way out). One convenience is layered on top — a wildcard is taken to include its apex — and it is expanded into the list handed to the sandbox rather than matched loosely here, so both enforcement points answer the same question the same way. Note github.com and api.github.com are different hosts to both: allowing a site does not allow its API. Cloud-metadata addresses (169.254.169.254, metadata.google.internal) are refused whatever is configured — unauthenticated role credentials one request away — while loopback is deliberately not, because testing a local service is what the API Explorer is for. Two enforcement points, and the difference matters:

  • The OS sandbox carries the lists as sandbox.network.allowedDomains/deniedDomains, which is what reaches Bash and the SDK's own web access — the paths canUseTool cannot see, because a gate reads a tool's arguments and a sandbox sees syscalls. The same call now also carries the write paths as sandbox.filesystem.allowWrite/denyWrite, so the deny list finally covers shell writes as well as the file-write tools. Only absolute deny entries go over: a bare segment like .git is a gate pattern and would be meaningless as a sandbox path.
  • The API tools are checked in the renderer before a send leaves (ApiWorkspace.send(id, 'agent')). A user's own send is never checked — the view exists to point at any endpoint you like; the setting names what the agent may reach.

Codex has one network switch, not a host list, so a non-empty allow list fails closed there: the user asked for these hosts and the provider can only offer all or none. Sandbox availability is still graceful (failIfUnavailable: false), which means a machine missing the platform sandbox runs unconfined — the network list then applies only to the API tools.

Tool permissions (machine). Built-in tools are gated in main through the Agent SDK's canUseTool hook. Three layers decide, in order: write confinement (above) refuses out-of-root writes outright; the user's per-tool policy is consulted next; the permission posture decides the rest.

  • Per-tool policy — a user default of allow / ask / deny per gateable tool (set in AI settings, keyed by tool display name). deny refuses even when the posture would auto-allow; allow runs without prompting (still subject to confinement); ask (the default) defers to the posture.
  • Permission posture — prompt (ask before every mutating/exec tool), auto-edits (also auto-allow file edits), or auto-all (auto-allow everything).
Tool class Examples Default (posture prompt, policy ask)
Read-only Read, Glob, Grep Auto-allowed within the run.
Mutating / exec Edit, Write, Bash Ask the user before each use.

A gated tool calls requestPermission(name, detail); AiManager emits a permission event (tool + one-line summary including the target path/command); the renderer surfaces an inline Allow/Deny prompt; the tool runs only on explicit Allow. A deny policy is enforced by removing the tool from the model via the SDK's disallowedTools, not only at the gate: the Claude Code CLI auto-runs shell commands its own safety classifier deems safe (e.g. echo) without consulting canUseTool, so a gate-only deny would leak them.

Audit log. Every executed mutating/exec action is appended to a best-effort, size-bounded JSONL log under userData (AgentAuditLog): tool, one-line target, workspace root, timestamp, and a coarse grant source (policy / posture / gated-or-auto). Auditing happens at the execution point — a PostToolUse hook on the Claude path, the gated wrapper on the AI-SDK path — so commands the CLI safety classifier auto-runs (without the canUseTool gate) are captured too; denials never execute so they are not logged, and read-only / in-app tools are skipped. The exact grant path is not distinguishable at execution, hence the coarse source.

In-app capabilities. The agent can also act inside the app (e.g. read/replace the live editor document) via the renderer capability registry: providers call context.bridge.request(capability, input), correlated over RendererBridge to a handler registered on AiRuntime. Only registered capabilities are reachable; unknown names are rejected. (AgentEditorCapabilities in features/agent registers read/replace-active-document, preferring the markdown editor then the code editor.) Which capabilities a run is offered is decided by its surface; the full set per surface, the workspace surface's confinement rule, and the user-owned prompt and skill layers are on Agent surfaces, prompts and skills.

Session lifecycle (live-harness vs stateless). A provider is one of two shapes (AgentProvider.sessionModel). A live-harness provider — the Claude Agent SDK or OpenAI Codex — is an external agentic runtime driven as a subprocess that owns its own loop, tools, and session, so Studio holds one session open per conversation and pushes each turn into it. A stateless-model provider — the AiSdkAdapter over OpenAI / Ollama / … — has no live process; its "session" is the transcript replayed each call, so every turn is independent. Both sit behind the same AgentSession seam (turn / interrupt / close) and look identical to the renderer (an agent with history).

The two live-harnesses differ under the seam. Claude holds one streaming query() subprocess open across turns and enforces confinement through a per-tool canUseTool gate (plus its OS sandbox), so Studio's permission posture, deny list, and audit log all apply. Codex (CodexAgentSession over @openai/codex-sdk) is a Thread whose each runStreamed turn resumes the persisted thread (~/.codex/sessions) — no subprocess is held between turns, so close/reap are cheap — and it exposes no per-tool callback: confinement is enforced purely by the harness sandbox (sandboxMode: 'workspace-write' scoped to the workspace root plus the allowed write paths; 'read-only' in chat mode), consistent with the hard-boundary ruling (Decision 5 in Decision: live sessions) but meaning the deny list, audit log, and interactive per-tool prompts do not apply to Codex — the sandbox is the boundary. Both keep context across turns and reopen via resume after reap/restart; a Codex model change takes effect on the next fresh session (the SDK has no per-thread model swap).

On the Claude live path (ClaudeAgentSession), AiManager keys held-open sessions by a renderer-minted agentSessionId — stable per conversation, not the SDK session id (which avoids a before-id-known race and decouples routing from resume). A turn for a known conversation continues its session; the SDK result message ends a turn, not the session. The session's options split in two:

  • Frozen at open — bound once into the subprocess: the working directory, the surface/mode-scoped MCP tool set, allowed / disallowedTools, the OS sandbox, the system prompt, resume, env, and the opening model. A later turn that changes a field these derive from (provider, surface, workspace, mode, agent shell) is incompatible — the router closes the session and reopens a fresh one.
  • Per turn — the in-app tool handlers, canUseTool, and the audit hook read the current turn's context, so each turn's permission gate, audit sink, request id, bridge, posture, and policies apply. A model change is applied live via Query.setModel.

Teardown. Stop interrupts the current turn (the SDK ends it and the session stays live for the next turn) — it does not end the session. Only New chat, closing the owning tab, or app shutdown closes it (the renderer drives closeSession; the session's master abort controller terminates the subprocess). A turn whose stream fails evicts the session so the next turn opens fresh. A kill switch (LIVE_SESSIONS_ENABLED) falls the whole path back to a transient open→one-turn→close per run.

Reap & cold-start (#328). A live session does not live forever. An idle session past ai.agentSessionLifetime (Settings › AI: 30 min / 60 min / 1 day / indefinite) is reaped — its subprocess closed — and a memory-pressure LRU valve caps how many sessions stay open at once (MAX_LIVE_SESSIONS), applied even under an indefinite lifetime so held-open sessions can never exhaust the machine (the actively-running session is never the victim — lastActivity is stamped at turn start). On app restart the subprocess is gone entirely. Either way, reopening is transparent: the next turn carries the conversation's persisted resumeSessionId, which dispatchLive turns into a cold-start openSession that resumes the SDK session — so context is preserved with only a small reconnect delay, no user action.

Source of truth (store vs SDK session). Two things persist, at different layers, joined by the session id — not double storage. The SDK owns the model's live context and persists its own session transcript on disk (resumed by id); Studio's AgentConversationStore persists the displayed transcript (items), the resumeSessionId, and the pending queue. On restore, Studio rehydrates the UI from items and hands the resumeSessionId to the next turn — the model re-reads its own session, never Studio's items. So the store is authoritative for what the user sees; the resumed SDK session is authoritative for what the model remembers.

Capabilities & commands (#330). Provider capabilities are declared, then gated uniformly. Each provider states what it offers — supportsImages and supportedEfforts (the reasoning-effort levels: Claude low…max, Codex minimal…xhigh, the stateless AI-SDK path none) — on AgentProvider, surfaced to the renderer on AiProviderInfo. The composer reads the active provider's set to gate features: it rejects image attach when unsupported, and shows /effort <level> (a per-conversation choice on the Agent, clamped to the provider's range and applied at session open) only for providers that offer it. Live command discovery: a live-harness session can be asked for its slash commands at any time — ClaudeAgentSession calls Query.supportedCommands() on open and handles the commands_changed push, emitting a commands event the composer merges into its / menu (minus app-native and a conservative non-dispatchable deny-list). A picked command drops /name into the draft and dispatches into the live session as input. This is what the persistent-session work unlocked (it supersedes the deferred #322).

Enforcement points: AiAuthManager (credentials stay in main) · ClaudeAgentProvider.canUseTool (confinement → per-tool policy → posture, plus disallowedTools for denials) · ClaudeAgentSession (held-open query; frozen-at-open vs per-turn context indirection; interrupt-not-close) · AiManager (permission broker, per-tool-policy sanitising, AgentAuditLog, the live-session registry + compatibility router in dispatchLive, and idle-reap + the LRU valve) · RendererBridge + AiRuntime (in-app capability surface).

Clone this wiki locally