Managed project execution
Interactive web terminals
Bundled Terminal resolves ctx.control('sandbox').openShell({project,cols,rows}) inside a verified signed-in web API request. Sandbox loads the Project and membership itself and returns {kind,displayCwd,start()}. The single-use start() returns a TerminalChannel with sanitized byte output, framed input and resize, queued-input length, an exit promise and immediate shell cancellation. Without a live Sandbox provider the caller reports unavailable. Host targets use Bash's existing direct or bubblewrap preparation.
An agent's in-turn host command is distinct from this signed-in interactive shell. In
plugins/sandbox/lib/execution.mjs::prepare and plugins/terminal/index.mjs::prepareLaunch, effective
access.admin with identity.platform === 'elowen' && identity.conversation === 'shared' admits the
personal conversation's owner-authorized host target even when its current writer is not an operator.
Sandbox's derived owner admission permits direct preparation unless forceConfined overrides it;
Terminal also accepts this predicate for its direct host path without Sandbox. Core derives host
placement from the conversation in TurnContextBuilder and still checks its live owner policy.
Neither a channel role nor conversation:'shared' alone qualifies. Read identity and access at command
preparation; retain the writer's own account, tool grants and permissions. Participation grants no
standalone openShell or out-of-conversation Project access; without an ambient shared turn these
existing request and membership checks are unchanged. Delegated descendants carry core-validated
identity.sharedConversation: {sessionId, writerUserId} from the persisted delegated scope. With
effective access.admin, Sandbox and Terminal treat this like the parent's personal shared identity,
not an operator account. Forward currentAccess().sharedConversation unchanged when creating children;
core rechecks participation and conversation ownership live, including on continuations and recovery.
It grants no API account: guest descendants retain their durable ElowenApi denial.
Terminal reserves both its four-shell account slot and its 32-shell instance slot before the first asynchronous request read or shell preparation; every failed open releases the reservation. On attach, only the ring's absolute offset supplies replay, replacing any unsent bytes queued for the previous socket. A paused socket has one repeating drain check until it falls below the low-water mark, so producers resume even after prolonged backpressure.
For managed Projects, preparation uses the same ready, authorization, admission and durable lease owners as prepareExecution. Deferred start rechecks membership, runtime generation, admission and cancellation before launching. A stopped environment answers ENVIRONMENT_STOPPED. The fixed isolated Python helper is installed by digest through ensure-guest-file-helper with helperKind:'pty'; the worker admits its exact argv under lifetime:'connection' in a separate 32-session terminal pool. It has no 15-minute execution deadline. Initial shell argv, guest cwd, size and the account environment travel only in the first stdin frame. Eligible GitHub credentials follow Bash's account mapping rules and output redaction. Sandbox heartbeats the lease every five seconds; close, membership revocation and transport loss retain verified guest-unit cancellation and lease retirement. Sessions do not survive a daemon restart.
The internal preparation actor carries the managed-shell size and the host credential Project reference. Public prepareExecution rebuilds its actor from the exact admitted keys and does not forward either field. This adds one helper installation per machine and digest, one streaming worker session and one lease per terminal; ordinary command preparation is unchanged. Operators must install matching root helper files before starting the updated daemon, as the "Managed guest file agents and terminals" section of docs/DEPLOYMENT.md in the source repository describes.
Local execution through Sandbox
src/plugins/environmentTypes.ts owns SandboxLocalExecution and its target, turn, binding and request
types alongside the managed file controls. It imports only shared contracts; plugin-api re-exports the
same definitions and SandboxControl composes them. Core file consumers such as GuestFileSandbox in
managedArtifacts narrow localFiles from this low-level seam rather than importing the full plugin
API. This keeps artifact and upload dependencies acyclic without copying method signatures or adding
runtime work. The optional local method grants no provider by itself: a missing live Sandbox still
refuses local I/O, and managed consumers retain their existing file controls.
Local targets and turn bindings
Use ctx.control('sandbox') for a local ProjectExecutionRef. Await its resolveLocalTarget({target,accountUserId}), bindLocalTurn({target,accountUserId,sessionId,parentSessionId?}), localFiles({...turn,operation},{signal}?) and localRequest({...turn,plugin,tool,operation},{signal,onResult}?) calls. Targets contain projectId,targetId,label,cwd,home,platform,arch,shell,connected; local refs name the Project id. Resolve the current account and scope through awaited ctx.currentAccountUserId() and ctx.currentAccess() before calling. Files and Terminal await target metadata before choosing native path and shell semantics. A computer's connected reports the authenticated connection-ready handshake, not the bare socket: a connection that is attaching, or has not acknowledged the current retry policy, reads false and is refused as offline.
await bindLocalTurn(...) returns {target,signal,release()}. Hold it through the admitted turn, including model-only work. In the daemon it pins the actual connection; a fresh turn for a computer with no live connection throws LOCAL_TARGET_OFFLINE (status 409) instead, while a missing or aborted existing or parent pin stays LOCAL_EXECUTION_LOST. In a runner, Sandbox validates the inherited target and account against both the dispatch and current policy account, requires the active policy session or a child admission from that parent, and subscribes to ctx.localExecutionTurn().signal. Runner release removes that subscription; the daemon retains its socket pin until the delegated call settles. Core's unchanged withLocalExecution uses either binding for startup instruction reads and channel turns, aborts the existing PI session on loss and releases in finally. Each runner binding costs one abort subscription and no RPC or provider request. Missing or aborted dispatch refuses admission. Socket identity stays in the daemon's core connection owner (src/remoteCli/connections.ts); reconnect cannot replace an admitted connection.
Local prepared execution and lease kinds
The coordinated execution contract keeps leaseKind on SandboxControl.prepareExecution and its derived runCommand input, but describes purpose rather than plugin identity:
| Purpose | Use and real consumer | Local computer |
|---|---|---|
terminal |
Interactive command preparation; bundled Terminal. Only this purpose can receive eligible account GitHub credentials, never with backgroundMode:'service'. |
Supported |
files |
Existing file-related helper command; bundled Files. | Supported |
protocol |
Argv protocol processes and their bounded setup/status commands; bundled MCP and registry LSP. | Supported within existing tool/delegation policy |
project-command |
Bounded account-scoped Project commands; registry Editor Git reads. | Supported, including the existing explicit-account no-turn path |
background |
Scheduled noninteractive check; registry Cronjob. | Refused with LOCAL_TARGET_UNSUPPORTED |
This is a coordinated compatibility cut, not evidence that all runtime changes have landed. Sandbox preparation, daemon and runner admission, callers and lease migration must be integrated and verified together before activation. Retired editor, lsp, mcp, cron, sites and browser inputs have no aliases: the preparation boundary must reject old or unknown values before host, managed or local side effects, and local transport must reject unsupported values before dispatch. Execution purposes remain part of shared API 16, without a purpose-specific bump; consumers declare requiresSharedApi:16 and the actual first shipping requiresCore floor. Update paired core/plugin artifacts together, not only the declaration.
A purpose grants no permission. Live control/tool ownership, delegated policy, account grants and Project membership still decide admission. Only project-command retains the existing no-turn local exception: the caller supplies an explicit account actor and local Project, and core binds that member's original connection until close or lease release, including failed preparation/start. An ambient turn always retains its inherited pin, regardless of purpose; reconnect cannot replace it. Other purposes do not acquire a no-turn exception. Daemon createCliConnections admits exactly terminal, files, protocol and project-command before dispatch and rejects background, retired and unknown values with LOCAL_TARGET_UNSUPPORTED. Its temporary bindings use project-command:<uuid> and project-files:<uuid>; failed preparation, failed start, normal process close and pre-start lease release retain the original binding cleanup. This daemon transport proof does not replace the coordinated Sandbox runner, producer or lease-migration gates.
prepareExecution may return mode local with a local reference and single-use start() returning ManagedExecutionSession. Its optional cwd readable carries Terminal's shell directory reports alongside stdout/stderr. Shell and argv commands share canonical LocalExecutionCommand. LOCAL_EXECUTION_LOST leaves dispatched mutation effects unknown and forbids replay. Core's runProjectCommand waits for stdout/stderr to drain as well as the exit verdict, so an early client exit retains buffered output. Admission still checks the live tool owner, every delegated scope and current account tool grants. Sub-agent's WorkflowStart may only read definition files. A read-only protocol tool must remain declared read-only and may launch its admitted argv server and write protocol stdin, not file mutations or unrestricted shell commands. The purpose adds no process, RPC, timer or provider request by itself.
Host LSP workspace selection uses core realAbs and realPathWithin, with the current turn's workDir as the base for relative candidates. LSP owns marker discovery within the permitted floor; containment never replaces file authorization or grants unbounded symbol access. Managed and computer namespaces keep target-side path operations, not host realpath.
Purpose does not define process lifetime and backgroundMode is not another purpose vocabulary. MCP's prepared protocol session is operation-scoped, including handshake failure, cancellation and lease release. LSP keeps its raw prepared session with the owning conversation/process manager and drains transport cancellation and lease cleanup on release; its setup/status commands use bounded runCommand. A service may outlive the dispatch that admitted it, but keeps the same connection, live membership and existing process owner; protocol never authorizes a replacement socket or interactive credentials. Missing Sandbox is unavailable, never an empty result or host fallback. See lease migration and runtime ownership.
Sandbox resolves the plugin-owned GitHub credential peer for each eligible terminal launch through the generic control resolver with the exhaustive {sessionCredential:true} method descriptor and a local consumed view. The resolver checks that the current owner and its required dependency exist and that the consumed method is callable before returning it; it invokes no peer methods while checking shape. Missing or incomplete peers leave the launch unauthenticated. The account and Project are still supplied to the provider's live holder/mapping checks, credentials are awaited, and tokens reach only the launch environment and existing sanitization closures, never public launch metadata, arguments or logs. Each lookup costs one method-shape check plus the existing credential request; no peer instance or credential is cached across launches.
A launch path reads synchronous ctx.vaultEnvironment() while preparing the current tool call.
It contains only that call's referenced VAULT_<NAME> values, and is empty outside such a call.
Terminal rewrites {{vault:NAME}} with rewriteVaultPlaceholders from
elowen-plugin-shared/vaultPlaceholders: POSIX references for host/confined/managed execution and
the paired computer's advertised sh, pwsh or powershell syntax. Keep the original command for
policy word checks, process listings and exit notices. Merge the environment into this child only,
beside agentShellEnvironment(); never mutate the daemon environment, watchdog environment or durable
process metadata. The real spawn cwd stays private; the launch's sanitizeOutput redacts its
display form before Terminal registers it or shows it in process metadata and result framing.
Background work keeps its launch snapshot after the call ends.
Sandbox appends literal rules to that launch's outputRedactions, using
vaultRedactionMarker(name) («vault:NAME»). The existing bounded streaming sanitizer chooses the
longest value first and sanitizes before capture files or rolling process buffers receive text.
The direct Terminal fallback uses the same rules. Marker identity rules make repeated sanitization
stable even for a value such as vault; command display sanitizes only spans outside canonical
placeholders. Rules carrying values are non-enumerable launch
metadata, not serializable state. Paired process-start operations include env only when nonempty;
ordinary commands retain their old wire shape.
Managed command preparation routes both GH_TOKEN and all VAULT_ variables through one stdin
bootstrap: a four-byte big-endian length followed by a UTF-8 JSON string map, bounded by the existing
1 MiB command-input limit. The isolated Python bootstrap reads exactly that frame, sets the child
environment without shell parsing and execs the command with the remaining stdin untouched.
Newlines, quotes and Unicode are data; NUL is not representable in a process environment and is
refused. Neither secret reaches the worker request, systemd-run --setenv argv or logs.
The privileged gateway refuses these names on its public argv environment channel.
Empty vault scope adds no bootstrap by itself, and the GitHub account/mapping eligibility is unchanged.
This adds only per-launch environment/rule copies and, for managed secrets, one bootstrap process.
Install the matching privileged helpers before activation; see docs/DEPLOYMENT.md in the source repository.
Artifact files on a computer
Core artifact operations use the separate sandboxArtifacts.artifactFiles control. Sandbox carries its explicit artifact:true intent across runner IPC without borrowing the active tool's identity; daemon routing invokes the same core-only control used for in-daemon capture. The selected computer's ~/.elowen confines both source and destination, including under read-only delegated Bash. The intent comes only from core's artifact call site. A model-supplied path reaching localFiles stays ordinary file I/O even if it names that namespace. Missing artifact authority fails persistence explicitly; this path adds no connection, retry or provider call.
Terminal timeouts
Bundled Terminal obtains { defaultTimeoutMs, maxTimeoutMs } once at registration from
ctx.host.terminalTimeouts(). This read-only accessor is restricted to Terminal and projects only
its two values from the daemon's frozen harness snapshot. It performs no I/O, exposes no path or
configuration mutator and does not raise root execution caps. Embedded hosts use the core schema
defaults. Runner boot carries the same snapshot, so later runners keep the daemon generation even
if the operator edits the file. See harness limits.
One-shot commands through runCommand
SandboxControl.runCommand(input, actor?, options?) executes one bounded command over the plugin's prepareExecution result. Core supplies this method when resolving the Sandbox control; providers implement preparation, not a second runner. Input is the existing command/cwd/leaseKind/projectRef shape. An explicit actor carries accountUserId and roots and retains preparation's confinement and tenancy rules. Without an actor the existing turn scope applies. Example: sandbox.runCommand({ command: { type: 'argv', file: 'git', args: ['status'] }, cwd, leaseKind: 'project-command', projectRef }, { accountUserId, roots: [] }, { timeout: 30000, outputLimit: { combined: 8 * 1024 * 1024 } }).
Core owns capture, 5-second lease heartbeats, cancellation and release. The default timeout is 10 seconds and the default limit is 1 MiB per stream; callers may instead specify a combined byte limit. Decode and sanitize captured stdout/stderr after collection. Completed commands resolve with stdout, stderr, code and signal, including nonzero exits. Timeout, abort, overflow, transport and cleanup failures reject with SandboxCommandError and sanitized partial output; they never invent an exit code. Completed nonzero commands release their lease without being cancelled again. Cleanup failures remain failures. Missing Sandbox resolves undefined and callers report unavailable. This seam is for one-shot commands such as Editor Git reads; long-lived LSP services retain prepareExecution's raw session.
SandboxCommandOptions.onPrepared receives the prepared execution before launch, so the owning domain can admit or refuse it. A throw refuses the command, and core cancels its preparation lease. Cancellation and lease release stay with core.
Foreground detach controls
Terminal, Subagent and Workflow register the shared DetachControl on their existing
control keys. Core awaits control.detachForeground({ sessionId, principal }),
which returns Promise<{ detached: number }>. Providers match both the origin
conversation and principal; a foreign or already-background run contributes zero.
The work continues after its foreground waiter is released. Subagent awaits its
progress persistence before releasing that waiter, so a failed write cannot report
a successful background handoff.
Computer Project editor files
Use the same sandbox.projectFiles({project,accountUserId,operation}) binding as a managed editor,
with project:{kind:'local',projectId}. No session id is required. Core authorizes canExecute,
holds a daemon connection binding for each operation and counts completed file mutations on the device.
Shared guestFiles helpers retain CAS versions, chunking and source pins. Offline and older clients
throw typed LOCAL_TARGET_OFFLINE and LOCAL_CLIENT_OUTDATED errors, both status 409; a non-member,
including an administrator, receives local_target_forbidden with status 403. Missing Sandbox is
unavailable. Registry Editor is the consumer; local Git and commit inspection use its existing
editorExecute wrapper with leaseKind:'project-command', local ref, explicit account and bounded capture.
See paired computers for the binding lifetime.
Project Git reads
Use ctx.host.git().projectRemotes(root, options?) for repository detection without worktree status. It returns { isRepo: boolean, remotes: { name, fetchUrl, pushUrl }[] }. Fetch and push URLs share the snapshot reader's sanitization of URL credentials, query strings and fragments; SCP-style SSH remotes remain intact. One remote costs four Git processes: repository probe, remote list, fetch URL and push URL. A managed read uses one guest execution session per process. A checkout without remotes costs two processes; a non-repository stops after its probe. No call means no Git work.
The registry GitHub plugin uses this read for its repository panel and mapping suggestions. For a host Project, authorize the Project and pass its checkout path. For a managed Project, pass its canonical guest root and explicit authority:
const { remotes } = await ctx.host.git().projectRemotes(root, {
managed: { project: { kind: 'managed', projectId }, accountUserId },
signal,
});
Declare reads: ['git'] and, for managed or computer reads, consumesControls: ['sandbox']. All ten methods share the same host facade: projectRemotes, projectSnapshot, projectStatus, projectChangedFiles, projectWorkingDiff, projectFileAtHead, projectCommit, projectCommitFileDiff, projectListedFiles and projectIgnoredAmong. Computer reads pass local: { project: { kind: 'local', projectId }, accountUserId } instead of managed; supplying both, or a mismatched target kind, rejects. Host reads omit both options and retain caller path authorization. projectStatus and the seven newer reads authorize the discovered repository root before reading its contents.
The facade checks the current API/turn account and selected Project before dispatch and again before delivery, including turn liveness and the native Project scope. Out-of-turn guest work requires the authoritative daemon; absence of a Policy is not administrator authority. The provider retains live membership, managed generation/worktree and original computer socket admission. Computer reads do not acquire a new no-turn path. Declaring the Sandbox dependency does not require raw Sandbox control authority. Missing host wiring/provider, denied roots, cancellation and runtime failures throw; guest reads never fall back to the host.
Plugin Git uses the existing project-command execution purpose. Core inspection/telemetry callers retain files by default, and the native daemon local-Git binding remains separate. The remaining read budget crosses that same executor, with signal forwarding and lease cleanup; no configurable timeout, stdin channel or raw-execution API is added.
The seven newer reads use literal paths and strict filename/object parsing. projectListedFiles returns cached plus untracked nonignored files relative to the requested scan root. projectIgnoredAmong considers only supplied paths with --no-index semantics, bounded argv batches and no stdin; an empty list launches nothing. NUL filename records and Git's argv-only C-quoted ignore output are parsed by the canonical reader, not consumers. Missing objects, corrupt indexes and malformed output remain errors, not empty success. Host scans have one 30-second budget, guest scans 120 seconds; aggregate inventory/ignore output is capped at 64 MiB, whole patches at 8 MiB and file/file-patch/file-list reads at 4 MiB. Existing remotes/snapshot recovery semantics are unchanged; only attested missing repositories yield their empty result. GitHub repository detection and Files status keep using this seam; Editor and OneDrive consumer migrations are separate.
Privileged transport and worker protocol
The Sandbox control's prepareExecution() returns the union SandboxPreparedExecution: LocalPreparedExecution for direct or confined host execution, or ManagedPreparedExecution for a managed Project. Managed preparation exposes start(): Promise<ManagedExecutionSession> and cancel(); the session provides stdin, stdout, stderr, and a settled closed promise. The session that start() resolves to is ManagedExecutionSession: stdin, stdout, stderr and closed (src/plugins/api.ts, ManagedExecutionSession). Managed consumers must use this start() contract and must not expect the { launch, stdin, cancel } shape, which belongs only to LocalPreparedExecution (direct or confined execution, src/plugins/api.ts).
The host supplies privilegedTransport to buildBrainCore explicitly; the daemon forwards it through buildApp. Without it, Sandbox machine-runtime calls reject locally with no privileged transport in this process, and daemon-mode Sites gateway calls report unavailable with that detail. Runners receive only the machine gateway: the delegated runner builds its core with role: 'runner' (src/subagent/runner.ts), which leaves the plugin-service manager and the published Sites control null (src/daemon/brainCore.ts). Registry loading never deactivates the published gateway because Sites is absent, disabled, or failed to load. These controls still enforce their existing consumer restrictions and stamp their own domains; a supplied transport does not broaden plugin access.
The machine runtime gateway runs managed sessions through the persistent privileged worker. Worker protocol 2 uses framed control messages plus direct socket-stdio attachment with exec-start, exec-accepted, exec-attach, exec-started, exec-exit, and exec-cancel. onInterrupted records interruption before the execution promises settle. The core-only sandboxArtifacts control is composed with the Sandbox control only inside core; plugins cannot resolve it directly.