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    hooks::ShellDispatchInfo,
16    limits::{EpochTicker, ExecutionLimits},
17    network_policy::{HookCapabilityGrant, ToolCapabilityGrant},
18    spawn_credential::{SpawnApproval, SpawnCredential},
19};
20
21pub(crate) struct DispatchOutcome {
22    pub result: ToolResult,
23    pub shell: Option<ShellDispatchInfo>,
24    /// Set instead of [`Self::shell`] when the command outran its grace period and was demoted
25    /// to the background. The two are never both `Some`: a demoted command has no exit code yet,
26    /// which is exactly why `HookEvent::Shell` does not fire for one.
27    pub detached: Option<crate::detached::DetachedDispatchInfo>,
28    /// True when the dispatch was served by reading a skill.md file rather than running
29    /// a binary or WASM component. Used by the agent loop to write a `skill_call` trace
30    /// event instead of a `tool_call` event.
31    pub is_skill: bool,
32    /// The fence source `result.data` was wrapped under, or `None` when the result carries no
33    /// fence. Set by [`crate::runtime::CapsuleStoreState::dispatch_agent_tool_async`] on the
34    /// same branch that applies the fence, so the label and the wrapping cannot drift: a caller
35    /// reading this never re-derives a source name by parsing the content back.
36    ///
37    /// `None` on every outcome that leaves the private unfenced dispatch — the skill branch,
38    /// and [`crate::runtime::CapsuleStoreState::dispatch_submit_plan`]'s route, whose step
39    /// output is fenced later as one field of a report.
40    pub fence_source: Option<String>,
41    /// Set when this dispatch failed in a way that ends the *session* rather than just this
42    /// tool call — today only a `sealed` composed-root construction failure
43    /// ([`crate::shell::ShellExecError::session_fatal`]). `result` still describes the failed
44    /// call so the trace records what was attempted; the agent turn loop then returns this
45    /// error instead of feeding the failure back to the model for another turn.
46    ///
47    /// A dispatch that merely failed leaves this `None`: a capsule reacting to a broken tool
48    /// call is ordinary, whereas a capsule continuing to run after its declared containment
49    /// boundary stopped being establishable is the silent-degradation failure mode the whole
50    /// containment-class mechanism exists to prevent.
51    pub fatal: Option<crate::errors::RuntimeError>,
52}
53
54impl DispatchOutcome {
55    pub(crate) fn tool(result: ToolResult) -> Self {
56        Self {
57            result,
58            shell: None,
59            detached: None,
60            is_skill: false,
61            fence_source: None,
62            fatal: None,
63        }
64    }
65
66    pub(crate) fn skill(result: ToolResult) -> Self {
67        Self {
68            result,
69            shell: None,
70            detached: None,
71            is_skill: true,
72            fence_source: None,
73            fatal: None,
74        }
75    }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct ArtifactRequest {
80    pub name: String,
81    pub version: String,
82    pub runtime: ArtifactRuntime,
83    /// Optional local source path (skill artifacts only). When set, the runtime resolves the
84    /// skill's `skill.md` directly from this path and skips registry resolution entirely.
85    /// Relative paths resolve against `StageRequest::manifest_dir`.
86    pub source: Option<String>,
87    /// Per-artifact capability grant copied verbatim from this artifact's entry in the
88    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::capabilities`).
89    /// Consumed for `runtime: hook` (default-deny baseline, `None` = deny everything) and for
90    /// `runtime: tool`/`runtime: driver` (ceiling baseline, `None` = the capsule-wide policy
91    /// unchanged); the manifest parser rejects the key on `runtime: skill`. Never sourced
92    /// from the artifact's own bundled `murmur.yaml`, so an artifact cannot self-grant.
93    pub capabilities: Option<murmur_artifact::Capabilities>,
94    /// What the runtime does when this hook's async job queue is full, copied verbatim from
95    /// `on_overflow:` on this artifact's entry in the capsule operator's own manifest — the
96    /// same operator-only sourcing rule `capabilities` above follows. Consumed for
97    /// `runtime: hook` and inert for every other role (the manifest parser rejects the key
98    /// there); inert too for a hook that turns out to be `execution_mode: blocking`, which is
99    /// never queued.
100    pub on_overflow: murmur_artifact::HookOverflowPolicy,
101    /// This artifact's operator-declared `config:` block, copied verbatim from its entry in the
102    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::config`) — the same
103    /// operator-only sourcing rule `capabilities` above follows, so an artifact pulled from a
104    /// registry cannot configure itself.
105    ///
106    /// Lowered to compact JSON at staging by [`crate::artifact_config::lower_artifact_config`] and
107    /// delivered to this artifact alone as [`crate::artifact_config::ARTIFACT_CONFIG_ENV`]. `None`
108    /// means the variable is absent from the guest environment. Consumed for `runtime: hook`,
109    /// `runtime: tool` and `runtime: driver`; the manifest parser rejects the key on
110    /// `runtime: skill`, and a native tool warns `W-SEC-015` because it reads no per-artifact
111    /// environment at all.
112    pub config: Option<serde_yaml::Value>,
113    /// This artifact's operator-declared `gateway:` block, copied verbatim from its entry in the
114    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::gateway`) — the same
115    /// operator-only sourcing rule `capabilities` above follows. Built into the artifact's
116    /// credential gateway at staging, which is also where the artifact's own `upstream_auth:`
117    /// declaration is read; an artifact without this block is never asked for one.
118    pub gateway: Option<murmur_artifact::ArtifactGateway>,
119}
120
121/// What `murmur.lock` pins one artifact at, already narrowed to this host.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct LockExpectation {
124    pub name: String,
125    pub resolved_version: String,
126    /// The hash the resolved payload must have. Selected by the caller from the lock entry's
127    /// `sha256` for the platform staging runs on, so it is whichever of `any` or
128    /// `platforms.<platform>` applies to this host.
129    pub sha256: String,
130}
131
132/// What staging actually resolved, for the caller to write back into `murmur.lock`.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct ResolvedLockArtifact {
135    pub name: String,
136    pub resolved_version: String,
137    /// Hash of the payload that was resolved on this host.
138    pub sha256: String,
139    /// Which platform the resolved payload is filed under, `None` for a platform-independent
140    /// one. Decides whether the lock entry pins `sha256.any` or `sha256.platforms.<platform>`.
141    pub platform: Option<String>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Default)]
145pub struct CapabilityPolicy {
146    pub network_allow: Vec<String>,
147    /// From `capabilities.peer_fetch.allow`: the peers this capsule may redeem a peer-file handle
148    /// against. Empty by default, which is deny — and which is also why no `fetch-peer-file` tool
149    /// manifest is written and the capsule's model never sees the tool exists.
150    ///
151    /// A separate list from [`Self::network_allow`], enforced with the same rule matcher but
152    /// never merged into it. Ingesting a peer's bytes lands a file in this capsule's own workdir,
153    /// so it is a prompt-injection surface and deserves its own operator control; a destination
154    /// in `network.allow` is not redeemable unless it also appears here, and declaring it here
155    /// does not widen `network.allow`.
156    pub peer_fetch_allow: Vec<String>,
157    /// From `capabilities.network.unix_sockets`. `false` by default, which makes the shell
158    /// subprocess tree's `socket(AF_UNIX, ...)` calls fail with `EACCES` at the kernel level on
159    /// both Linux tiers — `network_allow` above governs IP destinations only and would otherwise
160    /// leave a local daemon socket (`/var/run/docker.sock` — host root) completely unmediated.
161    /// `true` simply omits that seccomp rule; it is capsule-wide, not per-socket-path. See
162    /// `sandbox::denied_socket_domains`.
163    pub unix_sockets_allowed: bool,
164    pub filesystem_scope: Option<String>,
165    /// From `capabilities.filesystem.workdir_exec`. `false` by default, which withholds the
166    /// Landlock `Execute` right from the workdir's own `PathBeneath` rule — see
167    /// `sandbox::linux_enforce::workdir_access_rights`. With it withheld the kernel refuses to exec
168    /// anything under the workdir on the resolved path itself, so `shell_allow` is enforced
169    /// completely: a binary copied or compiled into the workdir cannot run under *any* name.
170    ///
171    /// `true` gives the right back for compile-and-run workflows and accepts, explicitly, that
172    /// `shell_allow` is then unenforceable for anything inside the workdir. That is why this field
173    /// is the one *grant* in this struct that also lowers the session's achieved containment class
174    /// (see `crate::containment::achieved_containment_class`) — nothing else here can.
175    pub workdir_exec_allowed: bool,
176    /// From `capabilities.filesystem.read_only`: workdir subtrees the capsule may read but must
177    /// not write, in the same vocabulary [`Self::filesystem_scope`] uses. Empty by default, which
178    /// is the whole workdir writable.
179    ///
180    /// Carried here as the declared strings and lowered once at staging into
181    /// `crate::protected_paths::ProtectedPaths`, which is what the dispatch check consults — so a
182    /// malformed entry refuses the launch rather than one call at a time. Unlike every other field
183    /// here this one grants nothing: it can only subtract from what the workdir preopen already
184    /// allows.
185    pub read_only_paths: Vec<String>,
186    pub shell_allow: Vec<String>,
187    pub spawn_allow: Vec<String>,
188    pub shell_strip_env: Vec<String>,
189    pub shell_baseline_env: Vec<String>,
190    /// Typed interpreter-runtime grants from `capabilities.shell.interpreter_runtime`: each
191    /// names an already-allowlisted binary and the exact host directories outside the workdir
192    /// its import machinery needs, with a per-directory `list_dir` enumerability flag. Empty
193    /// unless the manifest declares them. Consumed on `KernelFull` to add narrow Landlock
194    /// grants (see `sandbox::resolve_interpreter_runtime_grants`) and to fire `W-SEC-009`.
195    pub shell_interpreter_runtime: Vec<murmur_artifact::InterpreterRuntimeGrant>,
196    /// Typed staged-runtime grants from `capabilities.shell.staged_runtime`: each names an
197    /// already-allowlisted binary, the absolute host path of a pinned runtime tree, and the `pin`
198    /// identifying that tree's build. Empty unless the manifest declares them.
199    ///
200    /// Consumed at staging to enforce that declaring one requires an effective `sealed` floor (see
201    /// `crate::staged_runtime::check_staged_runtime_floor`) and to render the `staged runtime`
202    /// section of `--explain-scope`. Per-binary mutually exclusive with
203    /// [`Self::shell_interpreter_runtime`], which the manifest parser already guarantees.
204    pub shell_staged_runtime: Vec<murmur_artifact::StagedRuntimeGrant>,
205    /// Host env var names a WASM guest may observe, from `capabilities.env.allow`. Empty by
206    /// default: a guest sees only the runtime's own `MURMUR_*` injection unless the manifest
207    /// names a variable here. `shell_strip_env` and the credential patterns still apply on
208    /// top, so a credential-shaped name declared here is stripped anyway.
209    pub env_allow: Vec<String>,
210    /// Execution limits applied to every guest store in the session. Always fully
211    /// resolved — `capability_policy_from_runtime_manifest` substitutes a default for
212    /// each field `capabilities.limits` omits, so there is no "unset" state here and a
213    /// silent manifest yields [`ExecutionLimits::default`] rather than no limits.
214    pub limits: ExecutionLimits,
215    /// OS-level bounds applied to every *native subprocess* the session spawns — rlimits, the
216    /// Linux cgroup v2 scope, and the workdir-size ceiling. Resolved on exactly the same terms
217    /// as `limits` above (each omitted `capabilities.resources` field replaced by its default,
218    /// no "unset" state), but a completely different subject: `limits` bounds a WASM guest
219    /// inside its wasmtime store, this bounds the processes the host forks. See
220    /// [`crate::resources`].
221    pub resources: crate::resources::HostResourceLimits,
222    /// The containment class this capsule asked for, from `capabilities.containment`.
223    ///
224    /// Unlike every other field here it is a *requirement*, not a grant — and unlike
225    /// `StageRequest::declared_containment_floor` it is only the manifest's own vote, before the
226    /// workspace config and `--containment` are folded in. `stage_session` overwrites it with the
227    /// combined floor as soon as that is known, so anything reading it off a `StagedSession` sees
228    /// the effective value; the manifest-only value exists so a `CapabilityPolicy` built straight
229    /// from a manifest is still self-consistent.
230    ///
231    /// Read by `sandbox::ShellEnforcement::resolve` to decide whether a sealed-capable host
232    /// actually installs a composed root for this session — a capsule that declared `scoped` must
233    /// keep getting `scoped`'s mechanism. See `sandbox::applied_tier`.
234    pub containment_floor: murmur_artifact::ContainmentClass,
235    /// Whether the capsule's own top-level `capabilities.state` block was declared.
236    ///
237    /// Not a grant, and the only field here that is not: a durable state store is granted per
238    /// *artifact*, so a capsule-wide declaration reaches nothing at all. It is recorded so
239    /// `stage_session` can say that once (`W-SEC-014`) instead of leaving an operator to discover
240    /// an empty directory, and it is read by nothing else.
241    pub state_declared: bool,
242    /// Recorded for the same reason [`Self::state_declared`] is, and applied just as little: the
243    /// `murmur:conversation/read` grant is per artifact, so a capsule-wide declaration reaches
244    /// nothing and `stage_session` says so once (`W-SEC-016`).
245    pub conversation_declared: bool,
246    /// From `capabilities.plan.submit`: whether this capsule's model is offered the
247    /// runtime-provided `submit-plan` tool. `false` by default, which is deny — and which is also
248    /// why no `submit-plan` tool manifest is written and the capsule's model never sees the tool
249    /// exists.
250    ///
251    /// It grants no reach of its own: every step of a submitted plan runs through this same
252    /// session's tool dispatch, its shell allowlist and its spawn grant, so a plan reaches exactly
253    /// what the model could already call one call at a time.
254    pub plan_submit: bool,
255    /// `capabilities.limits.deadline_seconds` exactly as the manifest declared it — `None`
256    /// when it declared nothing. Retained undefaulted alongside the fully-resolved `limits`
257    /// above purely so hook calls can apply their own, lower default without mistaking an
258    /// explicit `600` for silence. See [`Self::hook_limits`].
259    pub declared_deadline_seconds: Option<u64>,
260}
261
262impl CapabilityPolicy {
263    /// Execution limits for hook lifecycle calls — [`Self::limits`] with the hook-specific
264    /// deadline default substituted when the manifest declared none.
265    ///
266    /// A hook call is one bounded piece of work, so it does not inherit the capsule-wide
267    /// ten-minute budget that exists for a capsule's whole `run`: a wedged hook would
268    /// otherwise stall the session for most of that, every event. An explicitly declared
269    /// `deadline_seconds` still wins, for hooks as for every other guest.
270    #[must_use]
271    pub fn hook_limits(&self) -> ExecutionLimits {
272        self.limits.for_hook_calls(self.declared_deadline_seconds)
273    }
274}
275
276#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct InstalledArtifactSummary {
278    pub name: String,
279    pub version: String,
280    pub runtime: ArtifactRuntime,
281    pub implementation: Option<ArtifactImplementation>,
282}
283
284#[derive(Clone)]
285pub(crate) struct StagedHookArtifact {
286    pub name: String,
287    pub version: String,
288    pub component: Component,
289    /// Behavioral contract (binding/execution_mode/commit_policy) from the hook artifact's
290    /// *own* bundled manifest. Carries no capability information — see `grant`.
291    pub config: HookConfig,
292    /// What this hook is allowed to do, lowered and validated at staging time from the
293    /// operator's own manifest entry. Applied identically by all three hook instantiation
294    /// paths in `hooks.rs`; `HookCapabilityGrant::default()` is full default-deny.
295    pub grant: HookCapabilityGrant,
296    /// What to do when this hook's async job queue is full — from the operator's manifest
297    /// entry (via [`ArtifactRequest::on_overflow`]), on the same terms as `grant` and never
298    /// from `config`. Read only when `config.execution_mode` is `Async`; a blocking hook has
299    /// no queue to overflow.
300    pub on_overflow: murmur_artifact::HookOverflowPolicy,
301    /// This hook's own credential gateway, when its operator entry declares `gateway:`. Attached
302    /// to every store the hook is instantiated on, `on-stage` included. Filled once the session's
303    /// gateways are staged, before any hook runs.
304    pub gateway: Option<Arc<crate::credential_gateway::CredentialGateway>>,
305}
306
307/// How `mur run --resume` puts the loaded conversation in front of the model.
308///
309/// `Full` is often the cheaper of the two: a verbatim reload can land on the provider's own
310/// prompt cache, while compaction changes the prefix from the first altered token, guarantees a
311/// cache miss, and costs an inference call to produce the summary. `Compact` is the answer when
312/// the conversation would not fit the context window at all.
313#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
314pub enum ResumeMode {
315    #[default]
316    Full,
317    Compact,
318}
319
320/// One operator act: continue *this* conversation, whatever the capsule's own
321/// `lifecycle.conversation` policy says about carrying one between tasks.
322///
323/// Sugar over [`StageRequest::context_id`], never a second load path: the CLI resolves a session
324/// address to the context id that session ran under and fills both this and `context_id`. What
325/// this adds is the override — the record is loaded even under `lifecycle.conversation:
326/// stateless` — and the provenance the trace records.
327#[derive(Debug, Clone)]
328pub struct ResumeRequest {
329    /// The prior session's id, recorded verbatim as `session_start.resumed_from`.
330    pub from_session: String,
331    pub mode: ResumeMode,
332}
333
334#[derive(Debug, Clone)]
335pub struct StageRequest {
336    pub manifest_dir: PathBuf,
337    pub capsule_name: String,
338    pub capsule_version: String,
339    pub capsule_component_bytes: Vec<u8>,
340    pub artifacts: Vec<ArtifactRequest>,
341    pub allowlisted_tools: HashSet<String>,
342    pub lock_expectations: Option<Vec<LockExpectation>>,
343    pub capability_policy: CapabilityPolicy,
344    pub inference: Option<InferenceConfig>,
345    /// The global config file a `${NAME}` in an artifact's `gateway.api_key` is looked up in first, as
346    /// `credentials.NAME`, and re-read from while the session runs. `None` looks in the launching
347    /// environment only.
348    pub credentials_file: Option<PathBuf>,
349    /// Whether `inference` above had its system-prompt declaration replaced by the caller
350    /// (`mur run --system-prompt`) rather than read from the manifest. Purely a provenance
351    /// signal for the trace: the override itself is already applied to `inference`, which by
352    /// this point is indistinguishable from a manifest that declared the same prompt inline.
353    /// `true` even when the override cleared the prompt to nothing.
354    pub system_prompt_overridden: bool,
355    pub context: Option<ContextConfig>,
356    /// Context id every `task.md` task of this launch runs under, from `mur run --context`.
357    /// `None` mints a fresh one per task. Validated by `stage_session` as one path segment: it is
358    /// a directory name in the conversation record path.
359    pub context_id: Option<String>,
360    /// `mur run --resume <session>`, already resolved: `context_id` above holds the context that
361    /// session ran under, and this carries the session's own id and the mode. `None` is every
362    /// ordinary launch. `stage_session` refuses a resume whose context kept no record on disk,
363    /// and a `--resume-mode compact` with no hook bound to `on-compaction`.
364    pub resume: Option<ResumeRequest>,
365    /// `mur run --forget-session`: drop the harness session `context_id` names before this
366    /// launch's first task, so that task starts a new conversation under the same context id.
367    /// `false` on every ordinary launch. `stage_session` refuses it for a capsule whose transport
368    /// keeps no harness session.
369    pub forget_session: bool,
370    /// OTLP/HTTP endpoint for span export; None = no external OTel emission.
371    pub otel_endpoint: Option<String>,
372    /// JSON-serialized EvalConfig injected into hook WASI env as MURMUR_EVAL_CONFIG.
373    pub eval_config_json: Option<String>,
374    /// Dataset case identifier injected as MURMUR_CASE_ID when running a dataset.
375    pub case_id: Option<String>,
376    /// Dataset identifier injected as MURMUR_DATASET_ID when running a dataset.
377    pub dataset_id: Option<String>,
378    /// Lifecycle config from the manifest (None = use LifecycleConfig::default()).
379    pub lifecycle: Option<LifecycleConfig>,
380    /// Optional override applied on top of lifecycle (e.g. from CLI flags or mur-roost).
381    pub lifecycle_override: Option<LifecycleOverride>,
382    /// Trace config from the manifest (None = defaults apply: input captured, output not).
383    pub trace: Option<murmur_artifact::TraceConfig>,
384    /// Optional user project directory to mount as the capsule's accessible workspace.
385    /// When set, session artifacts go into `<workdir>/.murmur/<session_id>/`.
386    /// When None, uses the default temp dir (existing behavior).
387    pub workdir: Option<std::path::PathBuf>,
388    /// Address to bind the HTTP server on. Defaults to "127.0.0.1" for local runs.
389    /// Use "0.0.0.0" when deploying to a VM so the capsule is reachable externally.
390    pub bind_addr: String,
391    /// Internal port from `network.internal_port` in the manifest. When `Some`, the runtime
392    /// binds strictly to this port and errors if it is already in use. When `None`, the OS
393    /// assigns a port.
394    pub internal_port: Option<u16>,
395    /// Minimum containment class this session must achieve, already combined across every
396    /// source that asked for one (manifest / workspace config / `--containment`) by taking the
397    /// strongest. Required rather than optional: "nobody declared anything" is
398    /// [`ContainmentClass::Advisory`], an explicit floor every host clears, not an absence.
399    /// `stage_session` refuses to stage when the host cannot meet it.
400    pub declared_containment_floor: murmur_artifact::ContainmentClass,
401    /// The manifest's top-level `exports:` block. `None` — and `Some` with no `files:` — means
402    /// the resource plane is not declared and every request to it is denied.
403    ///
404    /// Carried beside `capability_policy` rather than inside it: an export is a disclosure the
405    /// operator makes, not a capability the guest holds, and nothing derived from this field ever
406    /// reaches the achieved containment class.
407    pub exports: Option<murmur_artifact::Exports>,
408    /// The approval a delegated child was handed by its parent, presented once at registration.
409    ///
410    /// `None` for every top-level launch, which the daemon admits against its own `--spawn-allow`
411    /// instead. Unlike [`StagedSession::spawn_credential`], this exists before staging: it names
412    /// an artifact rather than a session, and the parent already held it when it started this
413    /// process.
414    pub spawn_grant: Option<SpawnApproval>,
415    /// `spend.machine_tokens_per_day` from the operator's effective `config.yaml`. `Some` makes
416    /// staging open the shared daily spend ledger for a `transport: http` session with a driver,
417    /// and refuse when it cannot; `None` — every launch that does not read the operator config —
418    /// keeps no ledger and is not counted.
419    pub machine_tokens_per_day: Option<u64>,
420}
421
422/// The `transport: process` driver this session runs its harness through, compiled and described
423/// once at staging.
424///
425/// Not a tool: it is granted nothing, never enters `tool_components`, and is reached only by the
426/// process runner, which instantiates a fresh [`crate::process_driver::ProcessDriver`] from
427/// `component` per harness run.
428pub struct StagedProcessDriver {
429    pub(crate) name: String,
430    pub(crate) version: String,
431    pub(crate) component: Component,
432    pub(crate) description: crate::process_driver::Description,
433    /// The absolute path of the executable to spawn, already resolved and checked.
434    pub(crate) binary: PathBuf,
435    /// Where [`Self::binary`]'s name came from, for diagnostics and the trace: `inference.command`
436    /// or the process driver's `describe()`.
437    pub(crate) binary_source: String,
438}
439
440pub struct StagedSession {
441    pub session_id: String,
442    pub workdir: PathBuf,
443    /// User project directory (or session dir if no --workdir). WASM tools see this at ".".
444    pub accessible_workdir: std::path::PathBuf,
445    pub(crate) manifest_dir: PathBuf,
446    pub(crate) capsule_name: String,
447    pub(crate) capsule_version: String,
448    pub(crate) capsule_url: String,
449    pub resolved_lock_artifacts: Vec<ResolvedLockArtifact>,
450    pub(crate) installed_artifacts: Vec<InstalledArtifactSummary>,
451    pub(crate) inference: Option<InferenceConfig>,
452    /// Every credential gateway of the session, built at staging from each artifact entry's
453    /// `gateway:` block and the artifact's own `upstream_auth:` declaration. Empty when no entry
454    /// declares one.
455    pub(crate) gateways: crate::credential_gateway::GatewayTable,
456    /// This session's spend account, built at staging from `inference.max_session_tokens` and
457    /// [`StageRequest::machine_tokens_per_day`]. Always present: a session with no ceiling gets a
458    /// meter that admits everything, so every driver call has an admission to open.
459    pub(crate) spend: Arc<crate::spend::SpendMeter>,
460    /// Copied from [`StageRequest::system_prompt_overridden`] — the only record left that the
461    /// prompt in `inference` came from `--system-prompt` and not from the manifest. Passed to
462    /// `TraceWriter::open`, which turns it into `session_start.system_prompt_source`.
463    pub(crate) system_prompt_overridden: bool,
464    pub(crate) context: Option<ContextConfig>,
465    /// Copied from [`StageRequest::context_id`] and already validated. Read by `launch_session`,
466    /// which uses it in place of a freshly minted id for every `task.md` task.
467    pub(crate) context_id: Option<String>,
468    /// Copied from [`StageRequest::resume`] and already checked. Read by `launch_session`, which
469    /// turns it into `session_start.resumed_from` and the agent loop's record-load override.
470    pub(crate) resume: Option<ResumeRequest>,
471    /// Copied from [`StageRequest::forget_session`] and already checked against the transport.
472    /// Read by `launch_session` as a one-shot: the launch's first task carries the forget, and no
473    /// later task of the same launch does.
474    pub(crate) forget_session: bool,
475    pub(crate) engine: Engine,
476    /// `None` for manifest-only agent capsules; `Some` for script capsules with a WASM component.
477    pub(crate) capsule_component: Option<Component>,
478    pub(crate) tool_components: HashMap<String, Component>,
479    /// The process driver, for a `transport: process` session that named one. `None` on every
480    /// other transport.
481    pub(crate) process_driver: Option<Arc<StagedProcessDriver>>,
482    /// Per-artifact narrowing for the tool/driver dispatch path, keyed by artifact name and
483    /// lowered at staging time from the operator's own manifest entries. Holds an entry only
484    /// for artifacts that actually declared a `capabilities:` block — a name absent from this
485    /// map (the overwhelmingly common case) runs on the full capsule ceiling, exactly as
486    /// before per-artifact narrowing existed.
487    pub(crate) artifact_grants: HashMap<String, ToolCapabilityGrant>,
488    pub(crate) hook_components: Vec<StagedHookArtifact>,
489    pub(crate) allowlisted_tools: HashSet<String>,
490    pub(crate) capability_policy: CapabilityPolicy,
491    pub(crate) otel_endpoint: Option<String>,
492    pub(crate) eval_config_json: Option<String>,
493    pub(crate) case_id: Option<String>,
494    pub(crate) dataset_id: Option<String>,
495    /// Resolved lifecycle config (manifest + override already applied).
496    pub(crate) lifecycle: LifecycleConfig,
497    /// How much of each turn's driver request this session's trace keeps (resolved from the
498    /// manifest's `trace:` block, or [`murmur_artifact::TraceCapture::default`] when it has
499    /// none).
500    pub(crate) trace_capture: murmur_artifact::TraceCapture,
501    /// What bounds this workdir's session directories, from the manifest's `trace.retain` block.
502    /// `None` — the overwhelmingly common case — prunes nothing, ever.
503    pub(crate) trace_retain: Option<murmur_artifact::TraceRetainConfig>,
504    /// Address the HTTP server is bound to (copied from StageRequest::bind_addr).
505    pub(crate) bind_addr: String,
506    /// Internal port from the manifest (copied from StageRequest::internal_port).
507    pub(crate) internal_port: Option<u16>,
508    /// Floor this session was staged against (copied from
509    /// StageRequest::declared_containment_floor).
510    pub(crate) declared_containment_floor: murmur_artifact::ContainmentClass,
511    /// The complete effective grant set this session was staged with — the same report
512    /// `mur run --explain-scope --json` prints, built by `containment::scope_report_for_tier`
513    /// from this session's own policy, declared floor and single host probe. Written verbatim to
514    /// `trace.jsonl`'s `session_start` as `effective_grants`, and the source of the
515    /// `containment_declared`/`containment_achieved`/`workdir_exec` fields alongside it, so the
516    /// summary and the full report cannot disagree.
517    ///
518    /// Replaces a former separate `achieved_containment` field: what the host actually provided
519    /// is `scope_report.achieved_containment`, and keeping a second copy beside it only created a
520    /// way for the two to drift.
521    pub(crate) scope_report: crate::containment::ScopeReport,
522    /// The single host reading this session was staged against, taken at the top of
523    /// `runtime::stage_session`. `launch_session` passes it to `sandbox::ShellEnforcement::resolve`
524    /// rather than taking a new one, so the mechanisms installed at launch are the ones
525    /// [`Self::scope_report`] already claims.
526    pub(crate) host_probe: crate::sandbox::HostProbe,
527    /// The declared read-only surface, lowered and validated by `stage_session` — a malformed
528    /// entry refuses the launch there rather than surfacing at the first call. Empty for every
529    /// capsule that declared no `capabilities.filesystem.read_only`.
530    pub(crate) protected_paths: crate::protected_paths::ProtectedPaths,
531    /// What each staged tool's own `input_schema` declared about where its inputs go, lowered by
532    /// `stage_session` from the manifests it wrote into `<workdir>/tools/`. Empty for a capsule
533    /// that declared no `read_only`, which reads no schema at all, and for one whose tools
534    /// annotated nothing.
535    pub(crate) tool_annotations: crate::tool_annotations::ToolAnnotationMap,
536    /// The declared read-only file surface, with its root already checked against this session's
537    /// accessible workdir by `stage_session` — a root that resolves outside it refuses the launch
538    /// rather than being served. `None` means no resource plane.
539    pub(crate) exports_files: Option<murmur_artifact::FileExport>,
540    /// The declared peer-handoff surface, with its root already checked against this session's
541    /// accessible workdir and its `max_ttl` already checked against `lifecycle.after_task` by
542    /// `stage_session`. `None` means no peer plane: nothing mints, and `/resources/peer/` answers
543    /// `no_peer_plane`.
544    pub(crate) exports_peer_files: Option<murmur_artifact::PeerFilesExport>,
545    /// Registry used to resolve this session's artifacts, retained so `manage.pull()` can
546    /// resolve additional artifacts at runtime after staging has completed.
547    pub(crate) registry: Arc<dyn Registry>,
548    /// Keeps this session's epoch ticker running: without it no epoch deadline set on any
549    /// store built from `engine` can ever fire. Held here (rather than detached) so ticking
550    /// stops when the session's `StagedSession` drops. `launch_session` moves the other
551    /// fields out one by one, which leaves this one in place until the session returns.
552    pub(crate) _epoch_ticker: EpochTicker,
553    /// The credential this session presents when it asks `mur-roost` to spawn a capsule.
554    ///
555    /// `None` for every session that cannot delegate, which is nearly all of them. Set by the
556    /// caller between `stage_session` and `launch_session` rather than carried in
557    /// [`StageRequest`]: the credential names a session id, and `stage_session` is what mints one,
558    /// so it cannot exist before staging returns.
559    pub(crate) spawn_credential: Option<SpawnCredential>,
560    /// Copied from [`StageRequest::spawn_grant`]. Read by `launch_session`, which presents it at
561    /// `POST /register` and never again — an approval covers one launch.
562    pub(crate) spawn_grant: Option<SpawnApproval>,
563    /// The handle the spawning capsule's launcher injected, read once per process at staging.
564    ///
565    /// `None` for every capsule nobody delegated. Its `session_id` and `delegation_id` become
566    /// `session_start.spawned_by` and `session_start.delegation_id`; its `report_to` — present
567    /// only for a parent that wants a completion — is what `launch_session`'s reporting guard
568    /// posts to. Read here rather than at each of those two points so one process reads
569    /// `MURMUR_SPAWNER` once and both readers see the same value.
570    pub(crate) spawner: Option<crate::delegation::SpawnerHandle>,
571}
572
573impl StagedSession {
574    /// Hands this session the credential it will present to the spawning daemon.
575    pub fn set_spawn_credential(&mut self, credential: SpawnCredential) {
576        self.spawn_credential = Some(credential);
577    }
578
579    /// The credential this session presents, if it was granted one.
580    pub fn spawn_credential(&self) -> Option<&SpawnCredential> {
581        self.spawn_credential.as_ref()
582    }
583
584    /// The grant set this session was staged with, as written to the trace.
585    pub fn scope_report(&self) -> &crate::containment::ScopeReport {
586        &self.scope_report
587    }
588}
589
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub struct LaunchResult {
592    pub session_id: String,
593    pub workdir: PathBuf,
594}
595
596pub fn capability_policy_from_runtime_manifest(
597    manifest: &murmur_artifact::RuntimeManifest,
598) -> CapabilityPolicy {
599    let caps = manifest.capabilities.as_ref();
600    let network_allow = caps
601        .and_then(|c| c.network.as_ref())
602        .map(|network| network.allow.clone())
603        .unwrap_or_default();
604    // Absent `capabilities.peer_fetch` block means denied, on the same terms — and separately
605    // from `network.allow`, which this deliberately does not read.
606    let peer_fetch_allow = caps
607        .and_then(|c| c.peer_fetch.as_ref())
608        .map(|peer_fetch| peer_fetch.allow.clone())
609        .unwrap_or_default();
610
611    // Absent `capabilities.network` block, or absent key within it, both mean denied.
612    let unix_sockets_allowed = caps
613        .and_then(|c| c.network.as_ref())
614        .is_some_and(|network| network.unix_sockets);
615
616    // Absent `capabilities.plan` block, or `submit: false` within it, both mean denied.
617    let plan_submit = caps
618        .and_then(|c| c.plan.as_ref())
619        .is_some_and(|plan| plan.submit);
620
621    // Recorded, never applied: see `CapabilityPolicy::state_declared`.
622    let state_declared = caps.is_some_and(|c| c.state.is_some());
623    let conversation_declared = caps.is_some_and(|c| c.conversation.is_some());
624
625    let filesystem_scope = caps
626        .and_then(|c| c.filesystem.as_ref())
627        .and_then(|filesystem| filesystem.scope.clone());
628    // Absent `capabilities.filesystem` block, or absent key within it, both mean denied — the same
629    // shape as `unix_sockets_allowed` above, for the same reason: the widening has to be declared.
630    let workdir_exec_allowed = caps
631        .and_then(|c| c.filesystem.as_ref())
632        .is_some_and(|filesystem| filesystem.workdir_exec);
633    // Absent block, absent key and an empty list are one declaration: nothing is protected.
634    let read_only_paths = caps
635        .and_then(|c| c.filesystem.as_ref())
636        .map(|filesystem| filesystem.read_only.clone())
637        .unwrap_or_default();
638
639    let shell_allow = caps
640        .and_then(|c| c.shell.as_ref())
641        .map(|shell| shell.allow.clone())
642        .unwrap_or_default();
643    let shell_strip_env = caps
644        .and_then(|c| c.shell.as_ref())
645        .and_then(|shell| shell.strip_env.clone())
646        .unwrap_or_default();
647    let shell_baseline_env = caps
648        .and_then(|c| c.shell.as_ref())
649        .and_then(|shell| shell.baseline_env.clone())
650        .unwrap_or_default();
651    let shell_interpreter_runtime = caps
652        .and_then(|c| c.shell.as_ref())
653        .map(|shell| shell.interpreter_runtime.clone())
654        .unwrap_or_default();
655    let shell_staged_runtime = caps
656        .and_then(|c| c.shell.as_ref())
657        .map(|shell| shell.staged_runtime.clone())
658        .unwrap_or_default();
659
660    let spawn_allow = caps
661        .and_then(|c| c.spawn.as_ref())
662        .map(|spawn| spawn.allow.clone())
663        .unwrap_or_default();
664
665    let env_allow = caps
666        .and_then(|c| c.env.as_ref())
667        .map(|env| env.allow.clone())
668        .unwrap_or_default();
669
670    let limits = ExecutionLimits::resolve(caps.and_then(|c| c.limits.as_ref()));
671    let declared_deadline_seconds = caps
672        .and_then(|c| c.limits.as_ref())
673        .and_then(|l| l.deadline_seconds);
674
675    let resources = crate::resources::resolve(caps.and_then(|c| c.resources.as_ref()));
676
677    CapabilityPolicy {
678        network_allow,
679        peer_fetch_allow,
680        unix_sockets_allowed,
681        filesystem_scope,
682        workdir_exec_allowed,
683        read_only_paths,
684        shell_allow,
685        spawn_allow,
686        shell_strip_env,
687        shell_baseline_env,
688        shell_interpreter_runtime,
689        shell_staged_runtime,
690        env_allow,
691        limits,
692        resources,
693        containment_floor: caps.and_then(|c| c.containment).unwrap_or_default(),
694        state_declared,
695        conversation_declared,
696        plan_submit,
697        declared_deadline_seconds,
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704
705    fn policy_for(manifest_yaml: &str) -> CapabilityPolicy {
706        let manifest = murmur_artifact::RuntimeManifest::from_yaml_str(manifest_yaml)
707            .expect("manifest fixture must parse");
708        capability_policy_from_runtime_manifest(&manifest)
709    }
710
711    /// `read_only` reaches the policy in declaration order, trimmed, with empty entries already
712    /// dropped by the manifest parser — and a capsule that declares none gets an empty list, which
713    /// is what makes the dispatch check free for it.
714    #[test]
715    fn read_only_paths_are_carried_through_and_default_to_empty() {
716        let declared = policy_for(
717            r#"
718name: cap
719version: 0.1.0
720capabilities:
721  filesystem:
722    read_only:
723      - tests
724      - "  bench/fixtures  "
725      - "   "
726"#,
727        );
728        assert_eq!(declared.read_only_paths, vec!["tests", "bench/fixtures"]);
729
730        let silent = policy_for(
731            "name: cap
732version: 0.1.0
733",
734        );
735        assert!(silent.read_only_paths.is_empty());
736
737        let no_key = policy_for(
738            r#"
739name: cap
740version: 0.1.0
741capabilities:
742  filesystem:
743    scope: work
744"#,
745        );
746        assert!(no_key.read_only_paths.is_empty());
747    }
748
749    /// A manifest that sets no deadline gives hook calls the hook-specific default while the
750    /// capsule's own guests keep the capsule-wide one — one manifest, two budgets.
751    #[test]
752    fn a_silent_manifest_gives_hook_calls_the_lower_deadline() {
753        let policy = policy_for(
754            r#"
755name: cap
756version: 0.1.0
757artifacts: []
758"#,
759        );
760
761        assert_eq!(
762            policy.limits.deadline_seconds,
763            crate::limits::DEFAULT_DEADLINE_SECONDS
764        );
765        assert_eq!(
766            policy.hook_limits().deadline_seconds,
767            crate::limits::HOOK_DEFAULT_DEADLINE_SECONDS
768        );
769        // The default policy a hand-built fixture gets must agree with the silent-manifest one.
770        assert_eq!(
771            CapabilityPolicy::default().hook_limits().deadline_seconds,
772            crate::limits::HOOK_DEFAULT_DEADLINE_SECONDS
773        );
774    }
775
776    /// An explicit `deadline_seconds` applies to every guest, hooks included — the hook
777    /// default only fills a silence.
778    #[test]
779    fn an_explicit_deadline_applies_to_hook_calls_too() {
780        let policy = policy_for(
781            r#"
782name: cap
783version: 0.1.0
784artifacts: []
785capabilities:
786  limits:
787    deadline_seconds: 120
788"#,
789        );
790
791        assert_eq!(policy.declared_deadline_seconds, Some(120));
792        assert_eq!(policy.limits.deadline_seconds, 120);
793        assert_eq!(policy.hook_limits().deadline_seconds, 120);
794    }
795
796    /// `capabilities.shell.staged_runtime` lowers onto the policy verbatim — binary, source path
797    /// and pin all survive, since the pin is what a human later compares across two hosts.
798    #[test]
799    fn staged_runtime_grants_lower_onto_the_policy() {
800        let policy = policy_for(
801            r#"
802name: cap
803version: 0.1.0
804artifacts: []
805capabilities:
806  containment: sealed
807  shell:
808    allow:
809      - python3
810    staged_runtime:
811      - binary: python3
812        source_path: /opt/testbed/conda/envs/django__django
813        pin: conda-4.10.3/python-3.9.19
814"#,
815        );
816
817        assert_eq!(
818            policy.shell_staged_runtime,
819            vec![murmur_artifact::StagedRuntimeGrant {
820                binary: "python3".to_string(),
821                source_path: "/opt/testbed/conda/envs/django__django".to_string(),
822                pin: "conda-4.10.3/python-3.9.19".to_string(),
823            }]
824        );
825        // The two mechanisms stay separate all the way down: lowering one must not populate the
826        // other.
827        assert!(policy.shell_interpreter_runtime.is_empty());
828    }
829
830    /// A shell block that declares no staged runtime lowers to an empty list, not to a default
831    /// grant of any kind.
832    #[test]
833    fn absent_staged_runtime_lowers_to_empty() {
834        let policy = policy_for(
835            r#"
836name: cap
837version: 0.1.0
838artifacts: []
839capabilities:
840  shell:
841    allow:
842      - bash
843"#,
844        );
845
846        assert!(policy.shell_staged_runtime.is_empty());
847    }
848
849    /// The default every existing manifest gets. Three separate "nothing was declared" shapes —
850    /// no `capabilities:` at all, no `filesystem:` within it, and a `filesystem:` that only sets
851    /// `scope` — must all lower to denied, because each one is a real manifest in the wild and any
852    /// of them silently keeping workdir `Execute` would reopen the rename-to-an-allowed-basename
853    /// bypass this default exists to close.
854    #[test]
855    fn workdir_exec_denied_for_every_shape_of_undeclared() {
856        for manifest_yaml in [
857            r#"
858name: cap
859version: 0.1.0
860artifacts: []
861"#,
862            r#"
863name: cap
864version: 0.1.0
865artifacts: []
866capabilities:
867  network:
868    allow:
869      - https://api.anthropic.com
870"#,
871            r#"
872name: cap
873version: 0.1.0
874artifacts: []
875capabilities:
876  filesystem:
877    scope: workdir
878"#,
879        ] {
880            let policy = policy_for(manifest_yaml);
881            assert!(
882                !policy.workdir_exec_allowed,
883                "an undeclared workdir_exec must lower to denied: {manifest_yaml}"
884            );
885        }
886    }
887
888    #[test]
889    fn workdir_exec_denied_when_declared_false() {
890        let policy = policy_for(
891            r#"
892name: cap
893version: 0.1.0
894artifacts: []
895capabilities:
896  filesystem:
897    workdir_exec: false
898"#,
899        );
900
901        assert!(!policy.workdir_exec_allowed);
902    }
903
904    #[test]
905    fn workdir_exec_allowed_when_declared_true() {
906        let policy = policy_for(
907            r#"
908name: cap
909version: 0.1.0
910artifacts: []
911capabilities:
912  filesystem:
913    scope: workdir
914    workdir_exec: true
915"#,
916        );
917
918        assert!(policy.workdir_exec_allowed);
919        // The two filesystem keys stay independent: lowering one must not disturb the other.
920        assert_eq!(policy.filesystem_scope.as_deref(), Some("workdir"));
921    }
922
923    /// A manifest with no `capabilities:` block at all denies unix sockets — the field must not
924    /// pick up any implicit widening from the "nothing declared" path.
925    #[test]
926    fn unix_sockets_denied_when_capabilities_block_is_absent() {
927        let policy = policy_for(
928            r#"
929name: cap
930version: 0.1.0
931artifacts: []
932"#,
933        );
934
935        assert!(!policy.unix_sockets_allowed);
936    }
937
938    /// A declared `network:` block that never mentions the key still denies.
939    #[test]
940    fn unix_sockets_denied_when_network_block_omits_the_key() {
941        let policy = policy_for(
942            r#"
943name: cap
944version: 0.1.0
945artifacts: []
946capabilities:
947  network:
948    allow:
949      - https://api.anthropic.com
950"#,
951        );
952
953        assert!(!policy.unix_sockets_allowed);
954        assert_eq!(
955            policy.network_allow,
956            vec!["https://api.anthropic.com".to_string()]
957        );
958    }
959
960    #[test]
961    fn unix_sockets_denied_when_declared_false() {
962        let policy = policy_for(
963            r#"
964name: cap
965version: 0.1.0
966artifacts: []
967capabilities:
968  network:
969    unix_sockets: false
970"#,
971        );
972
973        assert!(!policy.unix_sockets_allowed);
974    }
975
976    #[test]
977    fn unix_sockets_allowed_when_declared_true() {
978        let policy = policy_for(
979            r#"
980name: cap
981version: 0.1.0
982artifacts: []
983capabilities:
984  network:
985    unix_sockets: true
986"#,
987        );
988
989        assert!(policy.unix_sockets_allowed);
990    }
991
992    /// The opt-in is independent of the IP allowlist in both directions: a non-empty `allow`
993    /// does not imply unix sockets, and `unix_sockets: true` does not imply any IP destination.
994    #[test]
995    fn unix_sockets_opt_in_is_independent_of_the_ip_allowlist() {
996        let policy = policy_for(
997            r#"
998name: cap
999version: 0.1.0
1000artifacts: []
1001capabilities:
1002  network:
1003    unix_sockets: true
1004    allow:
1005      - https://api.anthropic.com
1006"#,
1007        );
1008
1009        assert!(policy.unix_sockets_allowed);
1010        assert_eq!(
1011            policy.network_allow,
1012            vec!["https://api.anthropic.com".to_string()]
1013        );
1014    }
1015
1016    /// `CapabilityPolicy::default()` is what the sandbox tests and every `..Default::default()`
1017    /// call site start from; it must deny, not inherit whatever a future field ordering implies.
1018    #[test]
1019    fn default_capability_policy_denies_unix_sockets() {
1020        assert!(!CapabilityPolicy::default().unix_sockets_allowed);
1021    }
1022}