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