Skip to main content

capsule_runtime/
types.rs

1use std::{
2    collections::{HashMap, HashSet},
3    path::PathBuf,
4    sync::Arc,
5};
6
7use murmur_artifact::{
8    ArtifactImplementation, ArtifactRuntime, ContextConfig, HookConfig, InferenceConfig,
9    LifecycleConfig, LifecycleOverride, Registry,
10};
11use wasmtime::{component::Component, Engine};
12
13use crate::{
14    bindings::host::murmur::tool::run::ToolResult,
15    formation::FormationId,
16    formation_credentials::FormationMember,
17    hooks::ShellDispatchInfo,
18    limits::{EpochTicker, ExecutionLimits},
19    network_policy::{HookCapabilityGrant, ToolCapabilityGrant},
20    spawn_credential::{SpawnApproval, SpawnCredential},
21};
22
23pub(crate) struct DispatchOutcome {
24    pub result: ToolResult,
25    pub shell: Option<ShellDispatchInfo>,
26    /// Set instead of [`Self::shell`] when the command outran its grace period and was demoted
27    /// to the background. The two are never both `Some`: a demoted command has no exit code yet,
28    /// which is exactly why `HookEvent::Shell` does not fire for one.
29    pub detached: Option<crate::detached::DetachedDispatchInfo>,
30    /// True when the dispatch was served by reading a skill.md file rather than running
31    /// a binary or WASM component. Used by the agent loop to write a `skill_call` trace
32    /// event instead of a `tool_call` event.
33    pub is_skill: bool,
34    /// The fence source `result.data` was wrapped under, or `None` when the result carries no
35    /// fence. Set by [`crate::runtime::CapsuleStoreState::dispatch_agent_tool_async`] on the
36    /// same branch that applies the fence, so the label and the wrapping cannot drift: a caller
37    /// reading this never re-derives a source name by parsing the content back.
38    ///
39    /// `Some("tool:<name>")` on every non-skill outcome, `Some("skill:<name>")` on a skill whose
40    /// `murmur.lock` origin is `runtime`, and `None` on an operator-declared skill and on every
41    /// outcome that leaves the private unfenced dispatch — that is,
42    /// [`crate::runtime::CapsuleStoreState::dispatch_submit_plan`]'s route, whose step output is
43    /// fenced later as one field of a report.
44    pub fence_source: Option<String>,
45    /// Set when this dispatch failed in a way that ends the *session* rather than just this
46    /// tool call — today only a `sealed` composed-root construction failure
47    /// ([`crate::shell::ShellExecError::session_fatal`]). `result` still describes the failed
48    /// call so the trace records what was attempted; the agent turn loop then returns this
49    /// error instead of feeding the failure back to the model for another turn.
50    ///
51    /// A dispatch that merely failed leaves this `None`: a capsule reacting to a broken tool
52    /// call is ordinary, whereas a capsule continuing to run after its declared containment
53    /// boundary stopped being establishable is the silent-degradation failure mode the whole
54    /// containment-class mechanism exists to prevent.
55    pub fatal: Option<crate::errors::RuntimeError>,
56    /// The runtime's own words about this call, appended by
57    /// [`crate::runtime::CapsuleStoreState::dispatch_agent_tool_async`] after the fence's closing
58    /// marker, so the model reads them as the runtime's rather than as the tool's data.
59    ///
60    /// `Some` on these outcomes:
61    ///
62    /// * a `call-member` call that started, carrying [`crate::member_call::started_note`];
63    /// * an accepted `end-without-answer`;
64    /// * a pull through `pull-artifact`, and a `remove-artifact` that removed something, each
65    ///   saying when the tool list changes;
66    /// * a shell call that finished and whose failure was attributed to a
67    ///   `capabilities.resources` limit, carrying [`crate::resources::resource_limit_line`].
68    ///
69    /// `None` on every other outcome. The unfenced route of
70    /// [`crate::runtime::CapsuleStoreState::dispatch_submit_plan`] never reads it.
71    ///
72    /// The session's one deadline notice is not a note: it is appended after the note, by
73    /// [`crate::runtime::CapsuleStoreState::deliver_deadline_notice`], on whichever dispatched
74    /// outcome is first handed back inside the notice margin.
75    pub runtime_note: Option<String>,
76    /// The runtime's own text, unfenced, when it could not run the call: the
77    /// [`crate::shell::ShellExecError`] a native tool or shell dispatch returned, the same text
78    /// `result.data` carries before the fence wraps it. The agent loop records it as the
79    /// `tool_call` trace record's `error`.
80    ///
81    /// `None` whenever the tool ran, including when the tool itself reported failure or exited
82    /// non-zero.
83    pub runtime_error: Option<String>,
84}
85
86impl DispatchOutcome {
87    pub(crate) fn tool(result: ToolResult) -> Self {
88        Self {
89            result,
90            shell: None,
91            detached: None,
92            is_skill: false,
93            fence_source: None,
94            fatal: None,
95            runtime_note: None,
96            runtime_error: None,
97        }
98    }
99
100    pub(crate) fn skill(result: ToolResult) -> Self {
101        Self {
102            result,
103            shell: None,
104            detached: None,
105            is_skill: true,
106            fence_source: None,
107            fatal: None,
108            runtime_note: None,
109            runtime_error: None,
110        }
111    }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct ArtifactRequest {
116    pub name: String,
117    pub version: String,
118    pub runtime: ArtifactRuntime,
119    /// Optional local source path (skill artifacts only). When set, the runtime resolves the
120    /// skill's `skill.md` directly from this path and skips registry resolution entirely.
121    /// Relative paths resolve against `StageRequest::manifest_dir`.
122    pub source: Option<String>,
123    /// Per-artifact capability grant copied verbatim from this artifact's entry in the
124    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::capabilities`).
125    /// Consumed for `runtime: hook` (default-deny baseline, `None` = deny everything) and for
126    /// `runtime: tool`/`runtime: driver` (ceiling baseline, `None` = the capsule-wide policy
127    /// unchanged); the manifest parser rejects the key on `runtime: skill`. Never sourced
128    /// from the artifact's own bundled `murmur.yaml`, so an artifact cannot self-grant.
129    pub capabilities: Option<murmur_artifact::Capabilities>,
130    /// What the runtime does when this hook's async job queue is full, copied verbatim from
131    /// `on_overflow:` on this artifact's entry in the capsule operator's own manifest — the
132    /// same operator-only sourcing rule `capabilities` above follows. Consumed for
133    /// `runtime: hook` and inert for every other role (the manifest parser rejects the key
134    /// there); inert too for a hook that turns out to be `execution_mode: blocking`, which is
135    /// never queued.
136    pub on_overflow: murmur_artifact::HookOverflowPolicy,
137    /// This artifact's operator-declared `config:` block, copied verbatim from its entry in the
138    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::config`) — the same
139    /// operator-only sourcing rule `capabilities` above follows, so an artifact pulled from a
140    /// registry cannot configure itself.
141    ///
142    /// Lowered to compact JSON at staging by [`crate::artifact_config::lower_artifact_config`] and
143    /// delivered to this artifact alone as [`crate::artifact_config::ARTIFACT_CONFIG_ENV`]. `None`
144    /// means the variable is absent from the guest environment. Consumed for `runtime: hook`,
145    /// `runtime: tool` and `runtime: driver`; the manifest parser rejects the key on
146    /// `runtime: skill`, and a native tool warns `W-SEC-015` because it reads no per-artifact
147    /// environment at all.
148    pub config: Option<serde_norway::Value>,
149    /// This artifact's operator-declared `gateway:` block, copied verbatim from its entry in the
150    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::gateway`) — the same
151    /// operator-only sourcing rule `capabilities` above follows. Built into the artifact's
152    /// credential gateway at staging, which is also where the artifact's own `upstream_auth:`
153    /// declaration is read; an artifact without this block is never asked for one.
154    pub gateway: Option<murmur_artifact::ArtifactGateway>,
155}
156
157/// What `murmur.lock` pins one artifact at, already narrowed to this host.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct LockExpectation {
160    pub name: String,
161    pub resolved_version: String,
162    /// The hash the resolved payload must have. Selected by the caller from the lock entry's
163    /// `sha256` for the platform staging runs on, so it is whichever of `any` or
164    /// `platforms.<platform>` applies to this host.
165    pub sha256: String,
166    /// Who wrote the lock entry. A [`murmur_artifact::LockOrigin::Runtime`] pin stages only as a
167    /// tool or skill without a `gateway:` block; staging refuses anything else with
168    /// [`crate::RuntimeError::RuntimeOriginNotDeclarable`].
169    pub origin: murmur_artifact::LockOrigin,
170}
171
172/// What staging actually resolved, for the caller to write back into `murmur.lock`.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub struct ResolvedLockArtifact {
175    pub name: String,
176    pub resolved_version: String,
177    /// Hash of the payload that was resolved on this host.
178    pub sha256: String,
179    /// Which platform the resolved payload is filed under, `None` for a platform-independent
180    /// one. Decides whether the lock entry pins `sha256.any` or `sha256.platforms.<platform>`.
181    pub platform: Option<String>,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Default)]
185pub struct CapabilityPolicy {
186    pub network_allow: Vec<String>,
187    /// From `capabilities.peer_fetch.allow`: the peers this capsule may redeem a peer-file handle
188    /// against. Empty by default, which is deny — and which is also why no `fetch-peer-file` tool
189    /// manifest is written and the capsule's model never sees the tool exists.
190    ///
191    /// A separate list from [`Self::network_allow`], enforced with the same rule matcher but
192    /// never merged into it. Ingesting a peer's bytes lands a file in this capsule's own workdir,
193    /// so it is a prompt-injection surface and deserves its own operator control; a destination
194    /// in `network.allow` is not redeemable unless it also appears here, and declaring it here
195    /// does not widen `network.allow`.
196    pub peer_fetch_allow: Vec<String>,
197    /// From `capabilities.network.unix_sockets`. `false` by default, which makes the shell
198    /// subprocess tree's `socket(AF_UNIX, ...)` calls fail with `EACCES` at the kernel level on
199    /// both Linux tiers — `network_allow` above governs IP destinations only and would otherwise
200    /// leave a local daemon socket (`/var/run/docker.sock` — host root) completely unmediated.
201    /// `true` simply omits that seccomp rule; it is capsule-wide, not per-socket-path. See
202    /// `sandbox::denied_socket_domains`.
203    pub unix_sockets_allowed: bool,
204    pub filesystem_scope: Option<String>,
205    /// From `capabilities.filesystem.workdir_exec`. `false` by default, which withholds the
206    /// Landlock `Execute` right from the workdir's own `PathBeneath` rule — see
207    /// `sandbox::linux_enforce::workdir_access_rights`. With it withheld the kernel refuses to exec
208    /// anything under the workdir on the resolved path itself, so `shell_allow` is enforced
209    /// completely: a binary copied or compiled into the workdir cannot run under *any* name.
210    ///
211    /// `true` gives the right back for compile-and-run workflows and accepts, explicitly, that
212    /// `shell_allow` is then unenforceable for anything inside the workdir. That is why this field
213    /// is the one *grant* in this struct that also lowers the session's achieved containment class
214    /// (see `crate::containment::achieved_containment_class`) — nothing else here can.
215    pub workdir_exec_allowed: bool,
216    /// From `capabilities.filesystem.read_only`: workdir subtrees the capsule may read but must
217    /// not write, in the same vocabulary [`Self::filesystem_scope`] uses. Empty by default, which
218    /// is the whole workdir writable.
219    ///
220    /// Carried here as the declared strings and lowered once at staging into
221    /// `crate::protected_paths::ProtectedPaths`, which is what the dispatch check consults — so a
222    /// malformed entry refuses the launch rather than one call at a time. Unlike every other field
223    /// here this one grants nothing: it can only subtract from what the workdir preopen already
224    /// allows.
225    pub read_only_paths: Vec<String>,
226    pub shell_allow: Vec<String>,
227    pub spawn_allow: Vec<String>,
228    pub shell_strip_env: Vec<String>,
229    pub shell_baseline_env: Vec<String>,
230    /// Typed interpreter-runtime grants from `capabilities.shell.interpreter_runtime`: each
231    /// names an already-allowlisted binary and the exact host directories outside the workdir
232    /// its import machinery needs, with a per-directory `list_dir` enumerability flag. Empty
233    /// unless the manifest declares them. Consumed on `KernelFull` to add narrow Landlock
234    /// grants (see `sandbox::resolve_interpreter_runtime_grants`) and to fire `W-SEC-009`.
235    pub shell_interpreter_runtime: Vec<murmur_artifact::InterpreterRuntimeGrant>,
236    /// Typed staged-runtime grants from `capabilities.shell.staged_runtime`: each names an
237    /// already-allowlisted binary, the absolute host path of a pinned runtime tree, and the `pin`
238    /// identifying that tree's build. Empty unless the manifest declares them.
239    ///
240    /// Consumed at staging to enforce that declaring one requires an effective `sealed` floor (see
241    /// `crate::staged_runtime::check_staged_runtime_floor`) and to render the `staged runtime`
242    /// section of `--explain-scope`. Per-binary mutually exclusive with
243    /// [`Self::shell_interpreter_runtime`], which the manifest parser already guarantees.
244    pub shell_staged_runtime: Vec<murmur_artifact::StagedRuntimeGrant>,
245    /// The runtime directories of each `shell_allow` binary the runtime recognises as an
246    /// interpreter, as that interpreter reported them (see [`crate::interpreter_runtime`]). Not a
247    /// manifest field: empty from [`capability_policy_from_runtime_manifest`], filled once by
248    /// `stage_session` and by `mur run --explain-scope` through
249    /// [`crate::interpreter_runtime::derive_interpreter_runtimes`]. Each becomes a readable,
250    /// non-executable Landlock grant (`sandbox::resolve_derived_interpreter_grants`) and, on
251    /// `sealed`, an optional composed-root bind.
252    pub shell_derived_interpreter_runtime:
253        Vec<crate::interpreter_runtime::DerivedInterpreterRuntime>,
254    /// The host's TLS trust store, as staging found it for a capsule with a non-empty
255    /// `shell_allow` and a non-empty `network_allow` (see [`crate::trust_store`]). Not a manifest
256    /// field: empty from [`capability_policy_from_runtime_manifest`], filled once by
257    /// `stage_session` and by `mur run --explain-scope` through
258    /// [`crate::trust_store::derive_trust_store`]. Each becomes a readable, non-executable
259    /// Landlock grant (`sandbox::resolve_trust_store_grants`), listable for a directory.
260    pub shell_trust_store: Vec<crate::trust_store::TrustStorePath>,
261    /// Host env var names a WASM guest may observe, from `capabilities.env.allow`. Empty by
262    /// default: a guest sees only the runtime's own `MURMUR_*` injection unless the manifest
263    /// names a variable here. `shell_strip_env` and the credential patterns still apply on
264    /// top, so a credential-shaped name declared here is stripped anyway.
265    pub env_allow: Vec<String>,
266    /// Execution limits applied to every guest store in the session. Always fully
267    /// resolved — `capability_policy_from_runtime_manifest` substitutes a default for
268    /// each field `capabilities.limits` omits, so there is no "unset" state here and a
269    /// silent manifest yields [`ExecutionLimits::default`] rather than no limits.
270    pub limits: ExecutionLimits,
271    /// OS-level bounds applied to every *native subprocess* the session spawns — rlimits, the
272    /// Linux cgroup v2 scope, and the workdir-size ceiling. Resolved on exactly the same terms
273    /// as `limits` above (each omitted `capabilities.resources` field replaced by its default,
274    /// no "unset" state), but a completely different subject: `limits` bounds a WASM guest
275    /// inside its wasmtime store, this bounds the processes the host forks. See
276    /// [`crate::resources`].
277    pub resources: crate::resources::HostResourceLimits,
278    /// The containment class this capsule asked for, from `capabilities.containment`.
279    ///
280    /// Unlike every other field here it is a *requirement*, not a grant — and unlike
281    /// `StageRequest::declared_containment_floor` it is only the manifest's own vote, before the
282    /// workspace config and `--containment` are folded in. `stage_session` overwrites it with the
283    /// combined floor as soon as that is known, so anything reading it off a `StagedSession` sees
284    /// the effective value; the manifest-only value exists so a `CapabilityPolicy` built straight
285    /// from a manifest is still self-consistent.
286    ///
287    /// Read by `sandbox::ShellEnforcement::resolve` to decide whether a sealed-capable host
288    /// actually installs a composed root for this session — a capsule that declared `scoped` must
289    /// keep getting `scoped`'s mechanism. See `sandbox::applied_tier`.
290    pub containment_floor: murmur_artifact::ContainmentClass,
291    /// Whether the capsule's own top-level `capabilities.state` block was declared.
292    ///
293    /// Not a grant, and the only field here that is not: a durable state store is granted per
294    /// *artifact*, so a capsule-wide declaration reaches nothing at all. It is recorded so
295    /// `stage_session` can say that once (`W-SEC-014`) instead of leaving an operator to discover
296    /// an empty directory, and it is read by nothing else.
297    pub state_declared: bool,
298    /// Recorded for the same reason [`Self::state_declared`] is, and applied just as little: the
299    /// `murmur:conversation/read` grant is per artifact, so a capsule-wide declaration reaches
300    /// nothing and `stage_session` says so once (`W-SEC-016`).
301    pub conversation_declared: bool,
302    /// From `capabilities.plan.submit`: whether this capsule's model is offered the
303    /// runtime-provided `submit-plan` tool. `false` by default, which is deny — and which is also
304    /// why no `submit-plan` tool manifest is written and the capsule's model never sees the tool
305    /// exists.
306    ///
307    /// It grants no reach of its own: every step of a submitted plan runs through this same
308    /// session's tool dispatch, its shell allowlist and its spawn grant, so a plan reaches exactly
309    /// what the model could already call one call at a time.
310    pub plan_submit: bool,
311    /// From `capabilities.install.skill`: the entries naming which skill artifacts a pull
312    /// (`manage.pull` or the `pull-artifact` tool) may install into this session, verbatim and in
313    /// declaration order. Empty by default, which is deny. With [`Self::install_tool`] also
314    /// empty, every pull is refused.
315    ///
316    /// A pulled skill gains no grant of its own; see `install_grant`.
317    pub install_skill: Vec<String>,
318    /// From `capabilities.install.tool`: the entries naming which tool artifacts, WASM or native,
319    /// a pull may install, verbatim and in declaration order. Empty by default, which is deny.
320    ///
321    /// A pulled tool joins the session's dispatch allowlist and dispatches on this policy's own
322    /// ceiling; it gains no grant of its own.
323    pub install_tool: Vec<String>,
324    /// From `capabilities.install.from`: `true` for `[stores, sources]`, under which a pull the
325    /// stores cannot answer is fetched from the scope's GitHub source. `false` by default.
326    pub install_from_sources: bool,
327    /// `capabilities.limits.deadline_seconds` exactly as the manifest declared it — `None`
328    /// when it declared nothing. Retained undefaulted alongside the fully-resolved `limits`
329    /// above purely so hook calls can apply their own, lower default without mistaking an
330    /// explicit `600` for silence. See [`Self::hook_limits`].
331    pub declared_deadline_seconds: Option<u64>,
332}
333
334impl CapabilityPolicy {
335    /// Execution limits for hook lifecycle calls — [`Self::limits`] with the hook-specific
336    /// deadline default substituted when the manifest declared none.
337    ///
338    /// A hook call is one bounded piece of work, so it does not inherit the capsule-wide
339    /// ten-minute budget that exists for a capsule's whole `run`: a wedged hook would
340    /// otherwise stall the session for most of that, every event. An explicitly declared
341    /// `deadline_seconds` still wins, for hooks as for every other guest.
342    #[must_use]
343    pub fn hook_limits(&self) -> ExecutionLimits {
344        self.limits.for_hook_calls(self.declared_deadline_seconds)
345    }
346}
347
348#[derive(Debug, Clone, PartialEq, Eq)]
349pub struct InstalledArtifactSummary {
350    pub name: String,
351    pub version: String,
352    pub runtime: ArtifactRuntime,
353    pub implementation: Option<ArtifactImplementation>,
354    /// Who pinned the artifact: its `murmur.lock` entry's origin, both for an artifact staged
355    /// from the lock and for one `manage.pull()` installed mid-session. An artifact staged
356    /// without a lock, and a `source:` skill, are [`murmur_artifact::LockOrigin::Operator`].
357    pub origin: murmur_artifact::LockOrigin,
358}
359
360#[derive(Clone)]
361pub(crate) struct StagedHookArtifact {
362    pub name: String,
363    /// The name this hook's `artifacts:` entry declares, scope included: what a message about a
364    /// setting on that entry names it by.
365    pub entry: String,
366    pub version: String,
367    pub component: Component,
368    /// Behavioral contract (binding/execution_mode/commit_policy) from the hook artifact's
369    /// *own* bundled manifest. Carries no capability information — see `grant`.
370    pub config: HookConfig,
371    /// What this hook is allowed to do, lowered and validated at staging time from the
372    /// operator's own manifest entry. Applied identically by all three hook instantiation
373    /// paths in `hooks.rs`; `HookCapabilityGrant::default()` is full default-deny.
374    pub grant: HookCapabilityGrant,
375    /// What to do when this hook's async job queue is full — from the operator's manifest
376    /// entry (via [`ArtifactRequest::on_overflow`]), on the same terms as `grant` and never
377    /// from `config`. Read only when `config.execution_mode` is `Async`; a blocking hook has
378    /// no queue to overflow.
379    pub on_overflow: murmur_artifact::HookOverflowPolicy,
380    /// This hook's own credential gateway, when its operator entry declares `gateway:`. Attached
381    /// to every store the hook is instantiated on, `on-stage` included. Filled once the session's
382    /// gateways are staged, before any hook runs.
383    pub gateway: Option<Arc<crate::credential_gateway::CredentialGateway>>,
384}
385
386/// How `mur run --resume` puts the loaded conversation in front of the model.
387///
388/// `Full` is often the cheaper of the two: a verbatim reload can land on the provider's own
389/// prompt cache, while compaction changes the prefix from the first altered token, guarantees a
390/// cache miss, and costs an inference call to produce the summary. `Compact` is the answer when
391/// the conversation would not fit the context window at all.
392#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
393pub enum ResumeMode {
394    #[default]
395    Full,
396    Compact,
397}
398
399/// One operator act: continue *this* conversation, whatever the capsule's own
400/// `lifecycle.conversation` policy says about carrying one between tasks.
401///
402/// Sugar over [`StageRequest::context_id`], never a second load path: the CLI resolves a session
403/// address to the context id that session ran under and fills both this and `context_id`. What
404/// this adds is the override — the record is loaded even under `lifecycle.conversation:
405/// stateless` — and the provenance the trace records.
406#[derive(Debug, Clone)]
407pub struct ResumeRequest {
408    /// The prior session's id, recorded verbatim as `session_start.resumed_from`.
409    pub from_session: String,
410    pub mode: ResumeMode,
411}
412
413#[derive(Debug, Clone)]
414pub struct StageRequest {
415    pub manifest_dir: PathBuf,
416    pub capsule_name: String,
417    pub capsule_version: String,
418    /// The full `<scope>/<name>` the capsule was resolved by, for one launched by name
419    /// (`mur run --capsule`). The session registers with mur-roost and reports its completion
420    /// under it. `None` for a capsule run from a project directory, which is `local/<capsule_name>`.
421    pub capsule_artifact: Option<String>,
422    pub capsule_component_bytes: Vec<u8>,
423    pub artifacts: Vec<ArtifactRequest>,
424    pub allowlisted_tools: HashSet<String>,
425    pub lock_expectations: Option<Vec<LockExpectation>>,
426    pub capability_policy: CapabilityPolicy,
427    pub inference: Option<InferenceConfig>,
428    /// The global config file a `${NAME}` in an artifact's `gateway.api_key` is looked up in first, as
429    /// `credentials.NAME`, and re-read from while the session runs. `None` looks in the launching
430    /// environment only.
431    pub credentials_file: Option<PathBuf>,
432    /// Whether `inference` above had its system-prompt declaration replaced by the caller
433    /// (`mur run --system-prompt`) rather than read from the manifest. Purely a provenance
434    /// signal for the trace: the override itself is already applied to `inference`, which by
435    /// this point is indistinguishable from a manifest that declared the same prompt inline.
436    /// `true` even when the override cleared the prompt to nothing.
437    pub system_prompt_overridden: bool,
438    pub context: Option<ContextConfig>,
439    /// Context id every `task.md` task of this launch runs under, from `mur run --context`.
440    /// `None` mints a fresh one per task. Validated by `stage_session` as one path segment: it is
441    /// a directory name in the conversation record path.
442    pub context_id: Option<String>,
443    /// `mur run --resume <session>`, already resolved: `context_id` above holds the context that
444    /// session ran under, and this carries the session's own id and the mode. `None` is every
445    /// ordinary launch. `stage_session` refuses a resume whose context kept no record on disk,
446    /// and a `--resume-mode compact` with no hook bound to `on-compaction`.
447    pub resume: Option<ResumeRequest>,
448    /// `mur run --forget-session`: drop the harness session `context_id` names before this
449    /// launch's first task, so that task starts a new conversation under the same context id.
450    /// `false` on every ordinary launch. `stage_session` refuses it for a capsule whose transport
451    /// keeps no harness session.
452    pub forget_session: bool,
453    /// OTLP/HTTP endpoint for span export; None = no external OTel emission.
454    pub otel_endpoint: Option<String>,
455    /// JSON-serialized EvalConfig injected into hook WASI env as MURMUR_EVAL_CONFIG.
456    pub eval_config_json: Option<String>,
457    /// Dataset case identifier injected as MURMUR_CASE_ID when running a dataset.
458    pub case_id: Option<String>,
459    /// Dataset identifier injected as MURMUR_DATASET_ID when running a dataset.
460    pub dataset_id: Option<String>,
461    /// Lifecycle config from the manifest (None = use LifecycleConfig::default()).
462    pub lifecycle: Option<LifecycleConfig>,
463    /// Optional override applied on top of lifecycle (e.g. from CLI flags or mur-roost).
464    pub lifecycle_override: Option<LifecycleOverride>,
465    /// Trace config from the manifest (None = defaults apply: input captured, output not).
466    pub trace: Option<murmur_artifact::TraceConfig>,
467    /// The operator's directory to use as the capsule's work folder, `mur run --workdir`; the
468    /// runtime creates nothing in it. `None` uses `<manifest_dir>/workdir/<session_id>`.
469    pub workdir: Option<std::path::PathBuf>,
470    /// Address to bind the HTTP server on. Defaults to "127.0.0.1" for local runs.
471    /// Use "0.0.0.0" when deploying to a VM so the capsule is reachable externally.
472    pub bind_addr: String,
473    /// Internal port from `network.internal_port` in the manifest. When `Some`, the runtime
474    /// binds strictly to this port and errors if it is already in use. When `None`, the OS
475    /// assigns a port.
476    pub internal_port: Option<u16>,
477    /// Minimum containment class this session must achieve, already combined across every
478    /// source that asked for one (manifest / workspace config / `--containment`) by taking the
479    /// strongest. Required rather than optional: "nobody declared anything" is
480    /// [`ContainmentClass::Advisory`], an explicit floor every host clears, not an absence.
481    /// `stage_session` refuses to stage when the host cannot meet it.
482    pub declared_containment_floor: murmur_artifact::ContainmentClass,
483    /// The manifest's top-level `exports:` block. `None` — and `Some` with no `files:` — means
484    /// the resource plane is not declared and every request to it is denied.
485    ///
486    /// Carried beside `capability_policy` rather than inside it: an export is a disclosure the
487    /// operator makes, not a capability the guest holds, and nothing derived from this field ever
488    /// reaches the achieved containment class.
489    pub exports: Option<murmur_artifact::Exports>,
490    /// The manifest's top-level `control:` block. `None` means the session has no control
491    /// surface: no token is minted and every request under `/control` is answered `404`.
492    ///
493    /// Beside `exports` and on the same terms: what a controller may change is not a capability
494    /// the guest holds, and nothing derived from it reaches the containment class.
495    pub control: Option<murmur_artifact::ControlConfig>,
496    /// The manifest's `network.authentication` block. `None` is a public door, which answers every
497    /// caller that reaches the port; `Some` makes staging mint this session's door key and tokens.
498    pub door_authentication: Option<murmur_artifact::NetworkAuthentication>,
499    /// The approval a delegated child was handed by its parent, presented once at registration.
500    ///
501    /// `None` for every top-level launch, which the daemon admits against its own `--spawn-allow`
502    /// instead. Unlike [`StagedSession::spawn_credential`], this exists before staging: it names
503    /// an artifact rather than a session, and the parent already held it when it started this
504    /// process.
505    pub spawn_grant: Option<SpawnApproval>,
506    /// `spend.machine_tokens_per_day` from the operator's effective `config.yaml`. `Some` makes
507    /// staging open the shared daily spend ledger for a `transport: http` session with a driver,
508    /// and refuse when it cannot; `None` — every launch that does not read the operator config —
509    /// keeps no ledger and is not counted.
510    pub machine_tokens_per_day: Option<u64>,
511    /// The formation this session is a member of.
512    ///
513    /// `None` is the ordinary case: a session nobody placed in a formation, including a
514    /// standalone capsule that delegates and every child it spawns. `mur run` sets it from
515    /// [`crate::formation::FormationId::from_env`], which reads what the launcher of a formation's
516    /// members, or a member's runtime for its child, put in the environment.
517    pub formation_id: Option<FormationId>,
518    /// What this session's formation launcher handed it: its roster name, what its door checks a
519    /// formation token with, and the tokens and addresses of the members it may call.
520    ///
521    /// `Some` only for a session `mur run --roster` launched as a member: `mur run` reads it from
522    /// the channel [`crate::formation_credentials::FormationMember::from_env`] names, and refuses
523    /// the launch when that cannot be read. The door verifies formation tokens with it, every WASM
524    /// guest is handed its callees' names, and the runtime's egress resolves and authorizes calls
525    /// to them. No native process and no delegated child is handed any of it.
526    pub formation_member: Option<Arc<FormationMember>>,
527    /// Where a pull the stores cannot answer is fetched from, for a capsule granted
528    /// `capabilities.install.from: [stores, sources]`. `None` fetches from no source: every pull
529    /// is answered by the stores alone.
530    pub source_supply: Option<Arc<dyn crate::artifact_supply::SourceSupply>>,
531    /// The `(st_dev, st_ino)` the accessible workdir must have, compared with `fstat` of the
532    /// directory `stage_session` opens at [`Self::workdir`] before anything is written beneath
533    /// it; a mismatch refuses the launch with [`crate::RuntimeError::WorkdirIdentityMismatch`].
534    /// Set by a delegating parent through `mur run --workdir-identity`, for the child directory it
535    /// created. `None` checks nothing.
536    pub expected_workdir_identity: Option<(u64, u64)>,
537    /// The hard limit `mur run --deadline` set, counted from the moment `mur run` started. Only
538    /// [`crate::launch_session_handling_sigterm`] on an agent capsule enforces one: reached, it
539    /// ends the session through the termination routine a first `SIGTERM` begins. Every other
540    /// launch of a session staged with one is refused with
541    /// [`crate::RuntimeError::SessionDeadlineUnenforceable`]. `None` sets no limit.
542    pub session_deadline: Option<crate::session_status::SessionDeadline>,
543    /// The manifest file this launch read, copied into the runtime directory under its own file
544    /// name: `--manifest`, or the project's `murmur.yaml`. `None` for a launch that read none from
545    /// disk — an installed capsule run by name — which copies nothing.
546    pub manifest_file: Option<PathBuf>,
547}
548
549/// The `transport: process` driver this session runs its harness through, compiled and described
550/// once at staging.
551///
552/// Not a tool: it is granted nothing, never enters `tool_components`, and is reached only by the
553/// process runner, which instantiates a fresh [`crate::process_driver::ProcessDriver`] from
554/// `component` per harness run.
555pub struct StagedProcessDriver {
556    pub(crate) name: String,
557    pub(crate) version: String,
558    pub(crate) component: Component,
559    pub(crate) description: crate::process_driver::Description,
560    /// The absolute path of the executable to spawn, already resolved and checked.
561    pub(crate) binary: PathBuf,
562    /// Where [`Self::binary`]'s name came from, for diagnostics and the trace: `inference.command`
563    /// or the process driver's `describe()`.
564    pub(crate) binary_source: String,
565}
566
567pub struct StagedSession {
568    pub session_id: String,
569    /// The work folder: the `--workdir` directory, or `<manifest-dir>/workdir/<session-id>`
570    /// without one. Every command's current directory and every WASM tool's `"."`. The runtime
571    /// creates nothing beneath it, and reads beneath it only through [`Self::accessible_root`].
572    pub accessible_workdir: std::path::PathBuf,
573    /// [`Self::accessible_workdir`], held open.
574    pub accessible_root: crate::workdir_fs::WorkdirRoot,
575    /// `<manifest-dir>/workdir`, which holds the work folder the runtime created for a launch
576    /// without `--workdir`, and those of earlier such launches that `trace.retain` prunes. `None`
577    /// under `--workdir`, whose folder is the operator's and is never pruned.
578    pub(crate) created_workdirs: Option<PathBuf>,
579    /// The session's runtime directory, `~/.murmur/sessions/<session-id>/runtime`: the value of
580    /// `$MURMUR_RUNTIME_DIR`, holding `MURMUR.md`, `task.md`, `murmur.yaml`, `tools/` and
581    /// `plans/`. Removed when the session ends; the runtime reads and writes beneath it only
582    /// through [`Self::runtime_root`].
583    pub runtime_dir: PathBuf,
584    /// [`Self::runtime_dir`], held open, sharing [`Self::accessible_root`]'s refusal latch.
585    pub runtime_root: crate::workdir_fs::WorkdirRoot,
586    /// The three held directories beneath the session's runtime directory, with the records
587    /// directory beside them.
588    pub(crate) runtime_dirs: crate::runtime_dir::RuntimeDirRoots,
589    /// The session's records directory, `~/.murmur/records/<workdir root>/<session-id>`: the
590    /// value of `$MURMUR_RECORDS_DIR`, holding `trace.jsonl`, `blobs/`, `logs/`,
591    /// `completion.json`, `hooks/`, `out/`, `tmp/`, `home/` and `children/`. Kept after the
592    /// session ends; the runtime reads and writes beneath it only through
593    /// [`Self::records_root`].
594    pub records_dir: PathBuf,
595    /// [`Self::records_dir`], held open, sharing [`Self::accessible_root`]'s refusal latch.
596    pub records_root: crate::workdir_fs::WorkdirRoot,
597    /// The file name the launched manifest was copied into the runtime directory under, which
598    /// the `[Capsule]` notice and `MURMUR.md` name. `None` when the launch read no manifest file.
599    pub(crate) manifest_file_name: Option<String>,
600    /// What `MURMUR.md` is rendered from, for an agent session; `None` for a script capsule,
601    /// which gets no `MURMUR.md`. Its identity's capsule URL is empty until launch.
602    pub(crate) murmur_md: Option<crate::murmur_md::MurmurMdInputs>,
603    /// Owns the runtime directory: dropping it removes the directory, so it is held until the
604    /// session ends — `launch` takes it and drops it on return, and a `StagedSession` dropped
605    /// unlaunched drops it with itself.
606    pub(crate) runtime_dir_guard: Option<crate::runtime_dir::RuntimeDir>,
607    pub(crate) manifest_dir: PathBuf,
608    pub(crate) capsule_name: String,
609    pub(crate) capsule_version: String,
610    /// [`StageRequest::capsule_artifact`], or `local/<capsule_name>` for a project run.
611    pub(crate) capsule_artifact: String,
612    pub(crate) capsule_url: String,
613    pub resolved_lock_artifacts: Vec<ResolvedLockArtifact>,
614    pub(crate) installed_artifacts: Vec<InstalledArtifactSummary>,
615    /// Where staging took the facts about each allowlisted binary it examined, for
616    /// `session_start.host_facts`.
617    pub(crate) host_facts: Vec<crate::host_facts::HostFactsUse>,
618    /// Each staged artifact's full name, by the tool name the session knows it by.
619    pub(crate) artifact_full_names: std::collections::HashMap<String, String>,
620    pub(crate) inference: Option<InferenceConfig>,
621    /// Every credential gateway of the session, built at staging from each artifact entry's
622    /// `gateway:` block and the artifact's own `upstream_auth:` declaration. Empty when no entry
623    /// declares one.
624    pub(crate) gateways: crate::credential_gateway::GatewayTable,
625    /// This session's spend account, built at staging from `inference.max_session_tokens` and
626    /// [`StageRequest::machine_tokens_per_day`]. Always present: a session with no ceiling gets a
627    /// meter that admits everything, so every driver call has an admission to open.
628    pub(crate) spend: Arc<crate::spend::SpendMeter>,
629    /// What a controller has changed on this session, built at staging from
630    /// [`StageRequest::control`]. `None` for a capsule with no `control:` block, which mints no
631    /// control token and answers `404` under `/control`.
632    pub(crate) control: Option<Arc<crate::control_plane::ControlState>>,
633    /// The session's driver choices, the primary first, each with the credential staging left
634    /// it and, under `transport: http`, its model limits. `None` for a capsule with no inference
635    /// block.
636    pub(crate) driver_choices: Option<crate::driver_choice::DriverChoices>,
637    /// The output cap a hook's `run-inference` sends for each model it may call.
638    pub(crate) hook_output_caps: crate::model_limits::HookOutputCaps,
639    /// The `MURMUR_INFERENCE_DRIVER_CONFIG` a hook's `run-inference` driver sees while the hook
640    /// serves `on-compaction`: `inference.driver.config` with `inference.compaction.driver_config`
641    /// laid over it. `None` when the manifest sets no overlay, so the call sees the session's.
642    pub(crate) compaction_driver_config: Option<String>,
643    /// Copied from [`StageRequest::door_authentication`], which the cards are built from.
644    pub(crate) door_authentication: Option<murmur_artifact::NetworkAuthentication>,
645    /// This session's door key and tokens, minted at staging when
646    /// [`Self::door_authentication`] is declared. The key never leaves this value.
647    pub(crate) door_auth: Option<Arc<crate::door_auth::DoorAuth>>,
648    /// Copied from [`StageRequest::system_prompt_overridden`] — the only record left that the
649    /// prompt in `inference` came from `--system-prompt` and not from the manifest. Passed to
650    /// `TraceWriter::open`, which turns it into `session_start.system_prompt_source`.
651    pub(crate) system_prompt_overridden: bool,
652    pub(crate) context: Option<ContextConfig>,
653    /// Copied from [`StageRequest::context_id`] and already validated. Read by `launch_session`,
654    /// which uses it in place of a freshly minted id for every `task.md` task.
655    pub(crate) context_id: Option<String>,
656    /// Copied from [`StageRequest::resume`] and already checked. Read by `launch_session`, which
657    /// turns it into `session_start.resumed_from` and the agent loop's record-load override.
658    pub(crate) resume: Option<ResumeRequest>,
659    /// Copied from [`StageRequest::forget_session`] and already checked against the transport.
660    /// Read by `launch_session` as a one-shot: the launch's first task carries the forget, and no
661    /// later task of the same launch does.
662    pub(crate) forget_session: bool,
663    pub(crate) engine: Engine,
664    /// The compiled-form cache handle built for [`Self::engine`] and the capsule's writable root.
665    /// A mid-session pull compiles through it, so a pulled component is stored and
666    /// looked up under the same name a staged one is.
667    pub(crate) compiled_forms: crate::compiled_forms::CompiledForms,
668    /// `None` for manifest-only agent capsules; `Some` for script capsules with a WASM component.
669    pub(crate) capsule_component: Option<Component>,
670    pub(crate) tool_components: HashMap<String, Component>,
671    /// What each native tool installed at staging needs to start, keyed by tool name. Derived
672    /// from the image the runtime wrote; see [`crate::sandbox::NativeEntrypoint`].
673    pub(crate) native_entrypoints: HashMap<String, crate::sandbox::NativeEntrypoint>,
674    /// The process driver, for a `transport: process` session that named one. `None` on every
675    /// other transport.
676    pub(crate) process_driver: Option<Arc<StagedProcessDriver>>,
677    /// Per-artifact narrowing for the tool/driver dispatch path, keyed by artifact name and
678    /// lowered at staging time from the operator's own manifest entries. Holds an entry only
679    /// for artifacts that actually declared a `capabilities:` block — a name absent from this
680    /// map (the overwhelmingly common case) runs on the full capsule ceiling, exactly as
681    /// before per-artifact narrowing existed.
682    pub(crate) artifact_grants: HashMap<String, ToolCapabilityGrant>,
683    pub(crate) hook_components: Vec<StagedHookArtifact>,
684    pub(crate) allowlisted_tools: HashSet<String>,
685    pub(crate) capability_policy: CapabilityPolicy,
686    pub(crate) otel_endpoint: Option<String>,
687    pub(crate) eval_config_json: Option<String>,
688    pub(crate) case_id: Option<String>,
689    pub(crate) dataset_id: Option<String>,
690    /// Resolved lifecycle config (manifest + override already applied).
691    pub(crate) lifecycle: LifecycleConfig,
692    /// How much of each turn's driver request this session's trace keeps (resolved from the
693    /// manifest's `trace:` block, or [`murmur_artifact::TraceCapture::default`] when it has
694    /// none).
695    pub(crate) trace_capture: murmur_artifact::TraceCapture,
696    /// What bounds this workdir's session directories, from the manifest's `trace.retain` block.
697    /// `None` — the overwhelmingly common case — prunes nothing, ever.
698    pub(crate) trace_retain: Option<murmur_artifact::TraceRetainConfig>,
699    /// Address the HTTP server is bound to (copied from StageRequest::bind_addr).
700    pub(crate) bind_addr: String,
701    /// Internal port from the manifest (copied from StageRequest::internal_port).
702    pub(crate) internal_port: Option<u16>,
703    /// This session's containment, decided once by `stage_session` from [`Self::host_probe`],
704    /// `StageRequest::declared_containment_floor`, `workdir_exec` and where the runtime directory
705    /// lies. The floor refusal, [`Self::scope_report`], [`Self::temp_mapping`], `MURMUR.md`'s exec
706    /// facts and the tier `launch_session`'s `sandbox::ShellEnforcement::resolve` installs all
707    /// read it, so the class and tier the session reports are the ones its commands run on.
708    pub(crate) containment: crate::containment::ContainmentDecision,
709    /// The complete effective grant set this session was staged with — the same report
710    /// `mur run --explain-scope --json` prints, built by `containment::scope_report_for_tier`
711    /// from this session's own policy and [`Self::containment`]. Written verbatim to
712    /// `trace.jsonl`'s `session_start` as `effective_grants`, and the source of the
713    /// `containment_declared`/`containment_achieved`/`workdir_exec` fields alongside it, so the
714    /// summary and the full report cannot disagree.
715    ///
716    /// The session's class here, `scope_report.achieved_containment`, is copied from
717    /// [`Self::containment`] when the report is built, so the two cannot drift.
718    pub(crate) scope_report: crate::containment::ScopeReport,
719    /// The single host reading this session was staged against, taken at the top of
720    /// `runtime::stage_session`, which [`Self::containment`] was decided from. `launch_session`
721    /// passes both to `sandbox::ShellEnforcement::resolve` rather than taking a new reading, so the
722    /// mechanisms installed at launch are the ones [`Self::scope_report`] already claims.
723    pub(crate) host_probe: crate::sandbox::HostProbe,
724    /// Whether a literal `/tmp` reaches the session's temporary folder, decided once by
725    /// `stage_session` from [`Self::host_probe`]: [`Self::scope_report`]'s `temp_dir` says it and
726    /// `launch_session` hands it to the enforcement that installs it.
727    pub(crate) temp_mapping: crate::temp_dir::TempMapping,
728    /// The declared read-only surface, lowered and validated by `stage_session` — a malformed
729    /// entry refuses the launch there rather than surfacing at the first call. Empty for every
730    /// capsule that declared no `capabilities.filesystem.read_only`.
731    pub(crate) protected_paths: crate::protected_paths::ProtectedPaths,
732    /// What each staged tool's own `input_schema` declared about where its inputs go, lowered by
733    /// `stage_session` from the manifests it wrote into `<runtime dir>/tools/`. Empty for a capsule
734    /// that declared no `read_only`, which reads no schema at all, and for one whose tools
735    /// annotated nothing.
736    pub(crate) tool_annotations: crate::tool_annotations::ToolAnnotationMap,
737    /// The declared read-only file surface, with its root already checked against this session's
738    /// accessible workdir by `stage_session` — a root that resolves outside it refuses the launch
739    /// rather than being served. `None` means no resource plane.
740    pub(crate) exports_files: Option<murmur_artifact::FileExport>,
741    /// The declared peer-handoff surface, with its root already checked against this session's
742    /// accessible workdir and its `max_ttl` already checked against `lifecycle.after_task` by
743    /// `stage_session`. `None` means no peer plane: nothing mints, and `/resources/peer/` answers
744    /// `no_peer_plane`.
745    pub(crate) exports_peer_files: Option<murmur_artifact::PeerFilesExport>,
746    /// Whether the door serves a task a peer capsule's runtime sends, read from the manifest's
747    /// own `exports.peer_tasks` by [`murmur_artifact::Exports::accepts_peer_tasks`]. `false`
748    /// answers every peer-origin request on the door with `403 peer_not_accepted`.
749    pub(crate) accepts_peer_tasks: bool,
750    /// Registry used to resolve this session's artifacts, retained so a pull can
751    /// resolve additional artifacts at runtime after staging has completed.
752    pub(crate) registry: Arc<dyn Registry>,
753    /// Copied from [`StageRequest::source_supply`]: where a runtime pull the stores cannot answer
754    /// is fetched from. `None` unless the capsule declared `capabilities.install.from: [stores,
755    /// sources]` and the launcher supplied one.
756    pub(crate) source_supply: Option<Arc<dyn crate::artifact_supply::SourceSupply>>,
757    /// Keeps this session's epoch ticker running: without it no epoch deadline set on any
758    /// store built from `engine` can ever fire. Held here (rather than detached) so ticking
759    /// stops when the session's `StagedSession` drops. `launch_session` moves the other
760    /// fields out one by one, which leaves this one in place until the session returns.
761    pub(crate) _epoch_ticker: EpochTicker,
762    /// The credential this session presents when it asks `mur-roost` to spawn a capsule.
763    ///
764    /// `None` for every session that cannot delegate, which is nearly all of them. Set by the
765    /// caller between `stage_session` and `launch_session` rather than carried in
766    /// [`StageRequest`]: the credential names a session id, and `stage_session` is what mints one,
767    /// so it cannot exist before staging returns.
768    pub(crate) spawn_credential: Option<SpawnCredential>,
769    /// Copied from [`StageRequest::spawn_grant`]. Read by `launch_session`, which presents it at
770    /// `POST /register` and never again — an approval covers one launch.
771    pub(crate) spawn_grant: Option<SpawnApproval>,
772    /// The handle the spawning capsule's launcher injected, read once per process at staging.
773    ///
774    /// `None` for every capsule nobody delegated. Its `session_id` and `delegation_id` become
775    /// `session_start.spawned_by` and `session_start.delegation_id`; its `report_to` — present
776    /// only for a parent that wants a completion — is what `launch_session`'s reporting guard
777    /// posts to. Read here rather than at each of those two points so one process reads
778    /// `MURMUR_SPAWNER` once and both readers see the same value.
779    pub(crate) spawner: Option<crate::delegation::SpawnerHandle>,
780    /// Copied from [`StageRequest::formation_id`]. Hooks see it as `MURMUR_FORMATION_ID` and the
781    /// delegation plane hands it to every child this session spawns.
782    pub(crate) formation_id: Option<FormationId>,
783    /// Copied from [`StageRequest::formation_member`].
784    pub(crate) formation_member: Option<Arc<FormationMember>>,
785    /// This member's formation lifeline, attached after staging by
786    /// [`StagedSession::attach_formation_lifeline`]. A process property rather than a staged
787    /// one, so it never travels on [`StageRequest`].
788    #[cfg(unix)]
789    pub(crate) formation_lifeline: Option<crate::lifeline::FormationLifeline>,
790    /// This delegated child's spawner lifeline, attached after staging by
791    /// [`StagedSession::attach_spawner_lifeline`]. A process property on the same terms as
792    /// [`Self::formation_lifeline`].
793    #[cfg(unix)]
794    pub(crate) spawner_lifeline: Option<crate::lifeline::SpawnerLifeline>,
795    /// [`StageRequest::session_deadline`], carried to the launch that enforces it.
796    pub(crate) session_deadline: Option<crate::session_status::SessionDeadline>,
797}
798
799impl StagedSession {
800    /// Writes `bytes` as the task input, `task.md` in the runtime directory, which the capsule's
801    /// commands can read and not change. A launch with one finds nothing to import from the
802    /// workdir.
803    pub fn write_task_input(&self, bytes: &[u8]) -> Result<(), crate::workdir_fs::WorkdirError> {
804        self.runtime_root.write_file(
805            crate::runtime::TASK_INPUT_FILE,
806            bytes,
807            crate::workdir_fs::DEFAULT_FILE_MODE,
808        )
809    }
810
811    /// Writes `bytes` as `rel` in the accessible workdir before launch, the folder the capsule's
812    /// tools see as their working directory. A link at `rel` is refused rather than written
813    /// through, and missing parent directories are created.
814    pub fn write_workdir_file(
815        &self,
816        rel: &str,
817        bytes: &[u8],
818    ) -> Result<(), crate::workdir_fs::WorkdirError> {
819        self.accessible_root
820            .write_file(rel, bytes, crate::workdir_fs::DEFAULT_FILE_MODE)
821    }
822
823    /// Hands this session the credential it will present to the spawning daemon.
824    pub fn set_spawn_credential(&mut self, credential: SpawnCredential) {
825        self.spawn_credential = Some(credential);
826    }
827
828    /// The credential this session presents, if it was granted one.
829    pub fn spawn_credential(&self) -> Option<&SpawnCredential> {
830        self.spawn_credential.as_ref()
831    }
832
833    /// The grant set this session was staged with, as written to the trace.
834    pub fn scope_report(&self) -> &crate::containment::ScopeReport {
835        &self.scope_report
836    }
837
838    /// Every door token this session minted, operator first, then the declared credentials by
839    /// name. Empty for a capsule that declares no `network.authentication`.
840    pub fn door_tokens(&self) -> Vec<(String, crate::door_auth::DoorToken)> {
841        self.door_auth
842            .as_ref()
843            .map(|auth| auth.tokens().to_vec())
844            .unwrap_or_default()
845    }
846
847    /// The formation this session is a member of, or `None` for a session nobody placed in one.
848    pub fn formation_id(&self) -> Option<&FormationId> {
849        self.formation_id.as_ref()
850    }
851
852    /// Hand this session the lifeline its process was launched with. Honoured only by
853    /// [`crate::launch_session_handling_sigterm`] on an agent capsule: every other launch of a
854    /// session holding one is refused with [`crate::RuntimeError::FormationLifelineUnreadable`]
855    /// before anything is instantiated.
856    #[cfg(unix)]
857    pub fn attach_formation_lifeline(&mut self, lifeline: crate::lifeline::FormationLifeline) {
858        self.formation_lifeline = Some(lifeline);
859    }
860
861    /// Hand this session the spawner lifeline its process was launched with. Honoured only by
862    /// [`crate::launch_session_handling_sigterm`], for an agent and a script capsule alike: every
863    /// other launch of a session holding one is refused with
864    /// [`crate::RuntimeError::SpawnerLifelineUnreadable`] before anything is instantiated.
865    #[cfg(unix)]
866    pub fn attach_spawner_lifeline(&mut self, lifeline: crate::lifeline::SpawnerLifeline) {
867        self.spawner_lifeline = Some(lifeline);
868    }
869}
870
871#[derive(Debug, Clone, PartialEq, Eq)]
872pub struct LaunchResult {
873    pub session_id: String,
874    /// The session's work folder, [`StagedSession::accessible_workdir`].
875    pub workdir: PathBuf,
876    /// The session's records directory, where its trace is, kept after the session.
877    pub records_dir: PathBuf,
878    /// How a launch that reports no error ended.
879    pub ending: LaunchEnding,
880}
881
882/// How a launch that reports no error ended. A launch whose task did not complete for any other
883/// reason is a [`crate::RuntimeError::TaskDidNotComplete`], not an ending.
884#[derive(Debug, Clone, Copy, PartialEq, Eq)]
885pub enum LaunchEnding {
886    /// Every task the launch ran completed, or it ran none: `session_end.exit_status` `ok`.
887    Completed,
888    /// The session's formation ended while it was running a task, and the wind-down that followed
889    /// cancelled that task: `session_end.exit_status` `formation_ended`.
890    FormationEnded,
891    /// The session reached its `mur run --deadline`, and the wind-down that followed cancelled
892    /// the task it was running, or it reached it before any task ran:
893    /// `session_end.exit_status` `deadline_reached`.
894    DeadlineReached,
895}
896
897impl LaunchEnding {
898    /// The `exit_status` `session_end` and `on-session-end` carry for this ending.
899    pub fn as_str(self) -> &'static str {
900        match self {
901            Self::Completed => "ok",
902            Self::FormationEnded => "formation_ended",
903            Self::DeadlineReached => "deadline_reached",
904        }
905    }
906}
907
908pub fn capability_policy_from_runtime_manifest(
909    manifest: &murmur_artifact::RuntimeManifest,
910) -> CapabilityPolicy {
911    let caps = manifest.capabilities.as_ref();
912    let network_allow = caps
913        .and_then(|c| c.network.as_ref())
914        .map(|network| network.allow.clone())
915        .unwrap_or_default();
916    // Absent `capabilities.peer_fetch` block means denied, on the same terms — and separately
917    // from `network.allow`, which this deliberately does not read.
918    let peer_fetch_allow = caps
919        .and_then(|c| c.peer_fetch.as_ref())
920        .map(|peer_fetch| peer_fetch.allow.clone())
921        .unwrap_or_default();
922
923    // Absent `capabilities.network` block, or absent key within it, both mean denied.
924    let unix_sockets_allowed = caps
925        .and_then(|c| c.network.as_ref())
926        .is_some_and(|network| network.unix_sockets);
927
928    // Absent `capabilities.plan` block, or `submit: false` within it, both mean denied.
929    let plan_submit = caps
930        .and_then(|c| c.plan.as_ref())
931        .is_some_and(|plan| plan.submit);
932
933    // Absent `capabilities.install` block means both lists are empty, which is deny.
934    let install = caps.and_then(|c| c.install.as_ref());
935    let install_skill = install.map(|i| i.skill.clone()).unwrap_or_default();
936    let install_tool = install.map(|i| i.tool.clone()).unwrap_or_default();
937    let install_from_sources = install.is_some_and(|i| i.from.sources());
938
939    // Recorded, never applied: see `CapabilityPolicy::state_declared`.
940    let state_declared = caps.is_some_and(|c| c.state.is_some());
941    let conversation_declared = caps.is_some_and(|c| c.conversation.is_some());
942
943    let filesystem_scope = caps
944        .and_then(|c| c.filesystem.as_ref())
945        .and_then(|filesystem| filesystem.scope.clone());
946    // Absent `capabilities.filesystem` block, or absent key within it, both mean denied — the same
947    // shape as `unix_sockets_allowed` above, for the same reason: the widening has to be declared.
948    let workdir_exec_allowed = caps
949        .and_then(|c| c.filesystem.as_ref())
950        .is_some_and(|filesystem| filesystem.workdir_exec);
951    // Absent block, absent key and an empty list are one declaration: nothing is protected.
952    let read_only_paths = caps
953        .and_then(|c| c.filesystem.as_ref())
954        .map(|filesystem| filesystem.read_only.clone())
955        .unwrap_or_default();
956
957    let shell_allow = caps
958        .and_then(|c| c.shell.as_ref())
959        .map(|shell| shell.allow.clone())
960        .unwrap_or_default();
961    let shell_strip_env = caps
962        .and_then(|c| c.shell.as_ref())
963        .and_then(|shell| shell.strip_env.clone())
964        .unwrap_or_default();
965    let shell_baseline_env = caps
966        .and_then(|c| c.shell.as_ref())
967        .and_then(|shell| shell.baseline_env.clone())
968        .unwrap_or_default();
969    let shell_interpreter_runtime = caps
970        .and_then(|c| c.shell.as_ref())
971        .map(|shell| shell.interpreter_runtime.clone())
972        .unwrap_or_default();
973    let shell_staged_runtime = caps
974        .and_then(|c| c.shell.as_ref())
975        .map(|shell| shell.staged_runtime.clone())
976        .unwrap_or_default();
977
978    let spawn_allow = caps
979        .and_then(|c| c.spawn.as_ref())
980        .map(|spawn| spawn.allow.clone())
981        .unwrap_or_default();
982
983    let env_allow = caps
984        .and_then(|c| c.env.as_ref())
985        .map(|env| env.allow.clone())
986        .unwrap_or_default();
987
988    let limits = ExecutionLimits::resolve(caps.and_then(|c| c.limits.as_ref()));
989    let declared_deadline_seconds = caps
990        .and_then(|c| c.limits.as_ref())
991        .and_then(|l| l.deadline_seconds);
992
993    let resources = crate::resources::resolve(caps.and_then(|c| c.resources.as_ref()));
994
995    CapabilityPolicy {
996        network_allow,
997        peer_fetch_allow,
998        unix_sockets_allowed,
999        filesystem_scope,
1000        workdir_exec_allowed,
1001        read_only_paths,
1002        shell_allow,
1003        spawn_allow,
1004        shell_strip_env,
1005        shell_baseline_env,
1006        shell_interpreter_runtime,
1007        shell_staged_runtime,
1008        shell_derived_interpreter_runtime: Vec::new(),
1009        shell_trust_store: Vec::new(),
1010        env_allow,
1011        limits,
1012        resources,
1013        containment_floor: caps.and_then(|c| c.containment).unwrap_or_default(),
1014        state_declared,
1015        conversation_declared,
1016        plan_submit,
1017        install_skill,
1018        install_tool,
1019        install_from_sources,
1020        declared_deadline_seconds,
1021    }
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026    use super::*;
1027
1028    fn policy_for(manifest_yaml: &str) -> CapabilityPolicy {
1029        let manifest = murmur_artifact::RuntimeManifest::from_yaml_str(manifest_yaml)
1030            .expect("manifest fixture must parse");
1031        capability_policy_from_runtime_manifest(&manifest)
1032    }
1033
1034    /// `read_only` reaches the policy in declaration order, trimmed, with empty entries already
1035    /// dropped by the manifest parser — and a capsule that declares none gets an empty list, which
1036    /// is what makes the dispatch check free for it.
1037    #[test]
1038    fn read_only_paths_are_carried_through_and_default_to_empty() {
1039        let declared = policy_for(
1040            r#"
1041name: cap
1042version: 0.1.0
1043capabilities:
1044  filesystem:
1045    read_only:
1046      - tests
1047      - "  bench/fixtures  "
1048      - "   "
1049"#,
1050        );
1051        assert_eq!(declared.read_only_paths, vec!["tests", "bench/fixtures"]);
1052
1053        let silent = policy_for(
1054            "name: cap
1055version: 0.1.0
1056",
1057        );
1058        assert!(silent.read_only_paths.is_empty());
1059
1060        let no_key = policy_for(
1061            r#"
1062name: cap
1063version: 0.1.0
1064capabilities:
1065  filesystem:
1066    scope: work
1067"#,
1068        );
1069        assert!(no_key.read_only_paths.is_empty());
1070    }
1071
1072    /// A manifest that sets no deadline gives hook calls the hook-specific default while the
1073    /// capsule's own guests keep the capsule-wide one — one manifest, two budgets.
1074    #[test]
1075    fn a_silent_manifest_gives_hook_calls_the_lower_deadline() {
1076        let policy = policy_for(
1077            r#"
1078name: cap
1079version: 0.1.0
1080artifacts: []
1081"#,
1082        );
1083
1084        assert_eq!(
1085            policy.limits.deadline_seconds,
1086            crate::limits::DEFAULT_DEADLINE_SECONDS
1087        );
1088        assert_eq!(
1089            policy.hook_limits().deadline_seconds,
1090            crate::limits::HOOK_DEFAULT_DEADLINE_SECONDS
1091        );
1092        // The default policy a hand-built fixture gets must agree with the silent-manifest one.
1093        assert_eq!(
1094            CapabilityPolicy::default().hook_limits().deadline_seconds,
1095            crate::limits::HOOK_DEFAULT_DEADLINE_SECONDS
1096        );
1097    }
1098
1099    /// An explicit `deadline_seconds` applies to every guest, hooks included — the hook
1100    /// default only fills a silence.
1101    #[test]
1102    fn an_explicit_deadline_applies_to_hook_calls_too() {
1103        let policy = policy_for(
1104            r#"
1105name: cap
1106version: 0.1.0
1107artifacts: []
1108capabilities:
1109  limits:
1110    deadline_seconds: 120
1111"#,
1112        );
1113
1114        assert_eq!(policy.declared_deadline_seconds, Some(120));
1115        assert_eq!(policy.limits.deadline_seconds, 120);
1116        assert_eq!(policy.hook_limits().deadline_seconds, 120);
1117    }
1118
1119    /// `capabilities.shell.staged_runtime` lowers onto the policy verbatim — binary, source path
1120    /// and pin all survive, since the pin is what a human later compares across two hosts.
1121    #[test]
1122    fn staged_runtime_grants_lower_onto_the_policy() {
1123        let policy = policy_for(
1124            r#"
1125name: cap
1126version: 0.1.0
1127artifacts: []
1128capabilities:
1129  containment: sealed
1130  shell:
1131    allow:
1132      - python3
1133    staged_runtime:
1134      - binary: python3
1135        source_path: /opt/testbed/conda/envs/django__django
1136        pin: conda-4.10.3/python-3.9.19
1137"#,
1138        );
1139
1140        assert_eq!(
1141            policy.shell_staged_runtime,
1142            vec![murmur_artifact::StagedRuntimeGrant {
1143                binary: "python3".to_string(),
1144                source_path: "/opt/testbed/conda/envs/django__django".to_string(),
1145                pin: "conda-4.10.3/python-3.9.19".to_string(),
1146            }]
1147        );
1148        // The two mechanisms stay separate all the way down: lowering one must not populate the
1149        // other.
1150        assert!(policy.shell_interpreter_runtime.is_empty());
1151        // Derived at staging, never lowered from the manifest.
1152        assert!(policy.shell_derived_interpreter_runtime.is_empty());
1153        assert!(policy.shell_trust_store.is_empty());
1154    }
1155
1156    /// A shell block that declares no staged runtime lowers to an empty list, not to a default
1157    /// grant of any kind.
1158    #[test]
1159    fn absent_staged_runtime_lowers_to_empty() {
1160        let policy = policy_for(
1161            r#"
1162name: cap
1163version: 0.1.0
1164artifacts: []
1165capabilities:
1166  shell:
1167    allow:
1168      - bash
1169"#,
1170        );
1171
1172        assert!(policy.shell_staged_runtime.is_empty());
1173    }
1174
1175    /// The default every existing manifest gets. Three separate "nothing was declared" shapes —
1176    /// no `capabilities:` at all, no `filesystem:` within it, and a `filesystem:` that only sets
1177    /// `scope` — must all lower to denied, because each one is a real manifest in the wild and any
1178    /// of them silently keeping workdir `Execute` would reopen the rename-to-an-allowed-basename
1179    /// bypass this default exists to close.
1180    #[test]
1181    fn workdir_exec_denied_for_every_shape_of_undeclared() {
1182        for manifest_yaml in [
1183            r#"
1184name: cap
1185version: 0.1.0
1186artifacts: []
1187"#,
1188            r#"
1189name: cap
1190version: 0.1.0
1191artifacts: []
1192capabilities:
1193  network:
1194    allow:
1195      - https://api.anthropic.com
1196"#,
1197            r#"
1198name: cap
1199version: 0.1.0
1200artifacts: []
1201capabilities:
1202  filesystem:
1203    scope: workdir
1204"#,
1205        ] {
1206            let policy = policy_for(manifest_yaml);
1207            assert!(
1208                !policy.workdir_exec_allowed,
1209                "an undeclared workdir_exec must lower to denied: {manifest_yaml}"
1210            );
1211        }
1212    }
1213
1214    #[test]
1215    fn workdir_exec_denied_when_declared_false() {
1216        let policy = policy_for(
1217            r#"
1218name: cap
1219version: 0.1.0
1220artifacts: []
1221capabilities:
1222  filesystem:
1223    workdir_exec: false
1224"#,
1225        );
1226
1227        assert!(!policy.workdir_exec_allowed);
1228    }
1229
1230    #[test]
1231    fn workdir_exec_allowed_when_declared_true() {
1232        let policy = policy_for(
1233            r#"
1234name: cap
1235version: 0.1.0
1236artifacts: []
1237capabilities:
1238  filesystem:
1239    scope: workdir
1240    workdir_exec: true
1241"#,
1242        );
1243
1244        assert!(policy.workdir_exec_allowed);
1245        // The two filesystem keys stay independent: lowering one must not disturb the other.
1246        assert_eq!(policy.filesystem_scope.as_deref(), Some("workdir"));
1247    }
1248
1249    /// A manifest with no `capabilities:` block at all denies unix sockets — the field must not
1250    /// pick up any implicit widening from the "nothing declared" path.
1251    #[test]
1252    fn unix_sockets_denied_when_capabilities_block_is_absent() {
1253        let policy = policy_for(
1254            r#"
1255name: cap
1256version: 0.1.0
1257artifacts: []
1258"#,
1259        );
1260
1261        assert!(!policy.unix_sockets_allowed);
1262    }
1263
1264    /// A declared `network:` block that never mentions the key still denies.
1265    #[test]
1266    fn unix_sockets_denied_when_network_block_omits_the_key() {
1267        let policy = policy_for(
1268            r#"
1269name: cap
1270version: 0.1.0
1271artifacts: []
1272capabilities:
1273  network:
1274    allow:
1275      - https://api.anthropic.com
1276"#,
1277        );
1278
1279        assert!(!policy.unix_sockets_allowed);
1280        assert_eq!(
1281            policy.network_allow,
1282            vec!["https://api.anthropic.com".to_string()]
1283        );
1284    }
1285
1286    #[test]
1287    fn unix_sockets_denied_when_declared_false() {
1288        let policy = policy_for(
1289            r#"
1290name: cap
1291version: 0.1.0
1292artifacts: []
1293capabilities:
1294  network:
1295    unix_sockets: false
1296"#,
1297        );
1298
1299        assert!(!policy.unix_sockets_allowed);
1300    }
1301
1302    #[test]
1303    fn unix_sockets_allowed_when_declared_true() {
1304        let policy = policy_for(
1305            r#"
1306name: cap
1307version: 0.1.0
1308artifacts: []
1309capabilities:
1310  network:
1311    unix_sockets: true
1312"#,
1313        );
1314
1315        assert!(policy.unix_sockets_allowed);
1316    }
1317
1318    /// The opt-in is independent of the IP allowlist in both directions: a non-empty `allow`
1319    /// does not imply unix sockets, and `unix_sockets: true` does not imply any IP destination.
1320    #[test]
1321    fn unix_sockets_opt_in_is_independent_of_the_ip_allowlist() {
1322        let policy = policy_for(
1323            r#"
1324name: cap
1325version: 0.1.0
1326artifacts: []
1327capabilities:
1328  network:
1329    unix_sockets: true
1330    allow:
1331      - https://api.anthropic.com
1332"#,
1333        );
1334
1335        assert!(policy.unix_sockets_allowed);
1336        assert_eq!(
1337            policy.network_allow,
1338            vec!["https://api.anthropic.com".to_string()]
1339        );
1340    }
1341
1342    /// `CapabilityPolicy::default()` is what the sandbox tests and every `..Default::default()`
1343    /// call site start from; it must deny, not inherit whatever a future field ordering implies.
1344    #[test]
1345    fn default_capability_policy_denies_unix_sockets() {
1346        assert!(!CapabilityPolicy::default().unix_sockets_allowed);
1347    }
1348}