Skip to main content

capsule_runtime/
errors.rs

1use std::path::PathBuf;
2
3use murmur_artifact::{level_has_phrase, ContractDirection, UnservedInterface};
4use thiserror::Error;
5
6/// Where the reference docs state the cgroup delegation a subprocess-capable capsule needs on
7/// Linux, cited by [`RuntimeError::CgroupDelegationUnavailable`].
8const RESOURCE_LIMITS_PLATFORM_URL: &str =
9    murmur_artifact::docs_reference_url!("resource-limits/#platform-behavior");
10
11/// One `capabilities.shell.allow` entry that resolved to a script whose interpreter's package
12/// tree nothing declared could reach inside a `sealed` composed root.
13///
14/// Defined here rather than in [`crate::reachability`] — which is a `pub(crate)` module — because
15/// it is a field of a public [`RuntimeError`] variant and so has to be nameable by anything that
16/// matches on one (`murmur-cli`'s `CliError` conversion, above all).
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct UnreachableEntrypoint {
19    /// The `capabilities.shell.allow` entry, verbatim as the manifest wrote it.
20    pub binary: String,
21    /// Where that entry resolves on this host — the first `PATH` match, i.e. the one `execvp`
22    /// would run.
23    pub resolved_path: PathBuf,
24    /// The bare interpreter name read out of the file's `#!` line, with one level of
25    /// `env NAME` indirection resolved. This is the name a covering
26    /// `interpreter_runtime`/`staged_runtime` grant would have to declare.
27    pub interpreter: String,
28}
29
30impl std::fmt::Display for UnreachableEntrypoint {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(
33            f,
34            "'{}' ({}, a script run by '{}')",
35            self.binary,
36            self.resolved_path.display(),
37            self.interpreter
38        )
39    }
40}
41
42// The four codes below live beside the variants that raise them because two callers name them:
43// murmur-cli renders them on the terminal, and the A2A terminal status a process attempt writes
44// carries the same code. Defining them twice would let a client and an operator be shown
45// different codes for one failure.
46
47/// The code [`RuntimeError::HarnessTurnFailed`] renders under.
48pub const E_RUN_033: &str = "E-RUN-033";
49/// The code [`RuntimeError::ProcessDriverCallFailed`] renders under.
50pub const E_RUN_034: &str = "E-RUN-034";
51/// The code [`RuntimeError::ProcessHarnessInactive`] renders under.
52pub const E_RUN_035: &str = "E-RUN-035";
53/// The code [`RuntimeError::HarnessSessionGone`] renders under.
54pub const E_RUN_036: &str = "E-RUN-036";
55
56#[derive(Debug, Error)]
57pub enum RuntimeError {
58    #[error("artifact {name}@{version} is not in the store")]
59    ArtifactNotFound { name: String, version: String },
60
61    #[error("artifact integrity check failed for {name}@{version}")]
62    ArtifactIntegrityFailed { name: String, version: String },
63
64    #[error("lockfile missing artifact entry for '{name}'")]
65    LockMissingEntry { name: String },
66
67    #[error(
68        "lockfile version mismatch for '{name}': manifest requested {requested}, lock pinned {pinned}"
69    )]
70    LockVersionMismatch {
71        name: String,
72        requested: String,
73        pinned: String,
74    },
75
76    /// A `murmur.lock` pin written by `manage.pull()` is declared in a role only an
77    /// operator-declared pin may carry. `declared_as` is the offending manifest text:
78    /// `runtime: hook`, `runtime: driver`, `gateway:` or `inference.system_prompt_artifact`.
79    #[error(
80        "murmur.lock pins '{name}@{version}' from a runtime pull by session {session}, and \
81         murmur.yaml declares it with {declared_as}, which only an operator-declared pin may carry"
82    )]
83    RuntimeOriginNotDeclarable {
84        name: String,
85        version: String,
86        session: String,
87        declared_as: &'static str,
88    },
89
90    #[error("failed to read artifact archive for {name}@{version}: {message}")]
91    ArtifactArchive {
92        name: String,
93        version: String,
94        message: String,
95    },
96
97    #[error("failed to compile component for {name}@{version}: {message}")]
98    ToolComponentCompile {
99        name: String,
100        version: String,
101        message: String,
102    },
103
104    #[error("failed to compile capsule component: {0}")]
105    CapsuleCompile(String),
106
107    #[error("failed to create workdir at {path}: {source}")]
108    CreateWorkdir {
109        path: String,
110        #[source]
111        source: std::io::Error,
112    },
113
114    /// A runtime write, append, read, create or removal inside the capsule's workdir met a
115    /// symbolic link, a hard-linked or non-regular file, or an invalid path component, and did
116    /// nothing. `mur` renders it as `E-RUN-050`.
117    #[error("{refusal}")]
118    WorkdirPathRefused {
119        refusal: crate::workdir_fs::WorkdirRefusal,
120    },
121
122    /// `~/.murmur/sessions/<session-id>/`, the session's runtime directory, could not be created
123    /// or locked. `mur` renders it as `E-IO-003`.
124    #[error("failed to create the runtime directory: {reason}")]
125    RuntimeDirUnavailable { reason: String },
126
127    /// `~/.murmur/records/<workdir root>/<session-id>/`, the session's records directory, could not
128    /// be created. `mur` renders it as `E-IO-003`.
129    #[error("failed to create the records directory: {reason}")]
130    RecordsDirUnavailable { reason: String },
131
132    /// `HOME` cannot hold `~/.murmur`, so there is nowhere to put a session's runtime and records
133    /// directories. Checked before anything is created; `mur` renders it as `E-IO-004`.
134    #[error(transparent)]
135    HomeUnusable(#[from] crate::murmur_home::HomeUnusable),
136
137    /// A delegated child's `--workdir` is not the directory its parent created: its
138    /// `(st_dev, st_ino)` differs from `--workdir-identity`. Nothing was written. `mur` renders it
139    /// as `E-RUN-051`.
140    #[error(
141        "the workdir {workdir} is not the directory the delegating capsule created (expected \
142         {expected}, found {found})"
143    )]
144    WorkdirIdentityMismatch {
145        workdir: String,
146        expected: String,
147        found: String,
148    },
149
150    /// A tool name that is not one normal path component, so its staged manifest would land
151    /// outside the runtime directory's `tools/`.
152    #[error(
153        "tool name '{}' is not a bare name, so its manifest would be written outside the \
154         workdir's tools/ directory",
155        name.escape_debug()
156    )]
157    ToolNameNotAComponent { name: String },
158
159    #[error("failed to write tool manifest at {path}: {source}")]
160    WriteToolManifest {
161        path: String,
162        #[source]
163        source: std::io::Error,
164    },
165
166    #[error("failed to read inference.system_prompt_file at {path}: {source}")]
167    SystemPromptFileRead {
168        path: String,
169        #[source]
170        source: std::io::Error,
171    },
172
173    #[error("failed to read inference.compaction.system_prompt_file at {path}: {source}")]
174    CompactionSystemPromptFileRead {
175        path: String,
176        #[source]
177        source: std::io::Error,
178    },
179
180    #[error(
181        "inference.system_prompt_artifact '{name}': skill.md not found or unreadable; \
182         ensure the skill is declared in artifacts: and the capsule was staged"
183    )]
184    SystemPromptArtifactRead {
185        name: String,
186        #[source]
187        source: std::io::Error,
188    },
189
190    #[error("skill source path not found: {path}")]
191    SkillSourceNotFound { path: String },
192
193    #[error("skill source directory '{path}' contains no skill.md")]
194    SkillSourceMissingSkillMd { path: String },
195
196    #[error("failed to read skill source at {path}: {source}")]
197    SkillSourceRead {
198        path: String,
199        #[source]
200        source: std::io::Error,
201    },
202
203    #[error("invalid network capability allow entry '{entry}': {message}")]
204    InvalidNetworkAllowEntry { entry: String, message: String },
205
206    #[error("invalid filesystem capability scope '{scope}': {message}")]
207    InvalidFilesystemScope { scope: String, message: String },
208
209    /// A `capabilities.filesystem.read_only` entry is not a usable workdir subpath: it is
210    /// absolute, or it escapes the workdir via `..`. The exact parallel of
211    /// [`Self::InvalidFilesystemScope`], raised from
212    /// [`crate::protected_paths::ProtectedPaths::from_declared`] at staging — before any registry
213    /// pull, workdir creation or component instantiation — so no call is ever checked against a
214    /// rule the runtime could not build.
215    #[error("invalid read-only path '{path}': {message}")]
216    InvalidReadOnlyPath { path: String, message: String },
217
218    /// An artifact entry's `config:` block cannot be delivered as `MURMUR_ARTIFACT_CONFIG`: it is
219    /// not a string-keyed mapping, does not serialize to JSON, or exceeds
220    /// [`crate::artifact_config::MAX_ARTIFACT_CONFIG_BYTES`]. Raised at staging (and from `mur run
221    /// --explain-scope`), before any registry pull, workdir creation or component instantiation,
222    /// so a malformed channel is refused once at launch rather than one tool call at a time.
223    #[error("invalid config for artifact '{artifact}': {message}")]
224    InvalidArtifactConfig { artifact: String, message: String },
225
226    /// A `capabilities.state.store` name is not a single usable directory segment under
227    /// `~/.murmur/state/`. Raised at staging (and from `mur run --explain-scope`), before any
228    /// registry pull, workdir creation or component instantiation, so a bad name never gets as far
229    /// as creating something on disk.
230    #[error("invalid state store name '{store}': {message}")]
231    InvalidStateStore { store: String, message: String },
232
233    /// A `context.record_store` value, or a `mur run --context` value, is not a single usable
234    /// directory segment of a conversation record path. Raised at staging, before any registry
235    /// pull, workdir creation or component instantiation, so a bad name never gets as far as
236    /// creating something on disk.
237    ///
238    /// Distinct from [`Self::InvalidStateStore`] because the remedies point at different keys, and
239    /// because a record is on by default while a state store is declared: an operator seeing this
240    /// may not have written a `context:` block at all, only a `--context` flag.
241    #[error("invalid {field} '{value}': {message}")]
242    InvalidConversationRecord {
243        field: String,
244        value: String,
245        message: String,
246    },
247
248    /// `mur run --resume` named a session whose context kept no conversation record on disk, so
249    /// there is nothing to continue. Raised at staging, before this launch's workdir exists: a
250    /// resume that silently started fresh would be indistinguishable from one that worked.
251    #[error(
252        "cannot resume session {session}: context '{context_id}' has no conversation record ({reason})"
253    )]
254    ResumeRecordMissing {
255        session: String,
256        context_id: String,
257        reason: String,
258    },
259
260    /// `mur run --resume-mode compact` on a capsule with no hook bound to `on-compaction`. There
261    /// is nothing to produce the summary, and falling back to `full` would silently give the
262    /// operator the mode they did not ask for.
263    #[error(
264        "--resume-mode compact needs a hook bound to on-compaction; this capsule declares none"
265    )]
266    ResumeCompactionHookMissing,
267
268    /// `mur run --resume-mode compact` on a `transport: process` capsule. The harness holds the
269    /// conversation and the runtime has no message list to hand a compaction hook, so there is
270    /// nothing `compact` could summarize.
271    #[error(
272        "--resume-mode compact is not available under inference.transport: process; the harness \
273         holds this conversation and murmur has no history to compact"
274    )]
275    ResumeCompactUnsupportedTransport,
276
277    /// The state store directory a validated name resolves to could not be resolved or created.
278    /// Distinct from [`Self::InvalidStateStore`]: the declaration is well-formed and the failure is
279    /// the host's — an unset `HOME`, or a path that cannot be made a `0700` directory.
280    #[error("state store '{store}' is unavailable at {path}: {message}")]
281    StateStoreUnavailable {
282        store: String,
283        path: String,
284        message: String,
285    },
286
287    /// The declared containment floor is stronger than what this host's kernel can back.
288    /// Raised in the stage/launch seam, before any registry pull, component compile or workdir
289    /// creation — `achieved` always comes from a live host probe, never from the manifest.
290    #[error(
291        "declared containment class '{declared}' is not achievable on this host (achieved: '{achieved}'): {reason}"
292    )]
293    ContainmentFloorUnmet {
294        declared: murmur_artifact::ContainmentClass,
295        achieved: murmur_artifact::ContainmentClass,
296        reason: String,
297        /// Why the floor is unmet, which decides what the operator is told to change.
298        cause: crate::containment::ShortfallCause,
299    },
300    /// A capsule declares an `exports.files.root` that, once resolved against the session's
301    /// accessible workdir, lands somewhere else — the root already exists as a symlink pointing
302    /// out of it.
303    ///
304    /// Refused at launch rather than per request: an export root outside the workdir is a
305    /// misconfiguration the operator can fix, and discovering it one served file at a time would
306    /// mean the first file had already left.
307    #[error(
308        "{field} '{declared}' resolves to '{resolved}', which is outside the capsule \
309         workdir '{workdir}'"
310    )]
311    ExportRootOutsideWorkdir {
312        /// The manifest key that declared it — `exports.files.root` or
313        /// `exports.peer_files.root`. Carried rather than hard-coded because the two roots are
314        /// separate authorisers and an operator fixing one must be told which.
315        field: String,
316        declared: String,
317        resolved: String,
318        workdir: String,
319    },
320
321    /// A capsule declares an artifact whose name collides with a tool the runtime provides
322    /// itself.
323    ///
324    /// Every name in [`crate::runtime::RESERVED_TOOL_NAMES`] is answered inside
325    /// `dispatch_agent_tool_unfenced` before any allowlist check is reached, and their synthetic
326    /// manifests are written after the staging loop. An artifact installed under one of them would
327    /// have its manifest overwritten and every call to it answered by the runtime, so the collision
328    /// is refused rather than resolved into a tool the capsule can never reach.
329    #[error(
330        "artifact '{name}' has the tool name '{}', which collides with a tool the runtime \
331         provides itself; the reserved names are {}",
332        murmur_artifact::tool_name_of(name),
333        crate::runtime::RESERVED_TOOL_NAMES.join(", ")
334    )]
335    ReservedToolName {
336        /// The declared artifact name whose tool name collides.
337        name: String,
338    },
339
340    /// Two declared artifacts share a tool name, the bare part a session offers the model and
341    /// stages under `<runtime dir>/tools/`.
342    #[error(
343        "artifacts '{first}' and '{second}' share the tool name '{tool}'; a capsule offers each \
344         artifact to the model by its tool name, so no two may share one"
345    )]
346    DuplicateToolName {
347        first: String,
348        second: String,
349        tool: String,
350    },
351
352    /// A capsule's `capabilities.env.allow` names variables the credential backstop strips from
353    /// every guest environment.
354    ///
355    /// The strip in `build_declared_env` is not negotiable from a manifest, so the entries
356    /// can only ever deliver nothing; the declaration is refused rather than left silently inert.
357    #[error(
358        "capabilities.env.allow names {}; these entries are removed from every guest environment \
359         before any guest is built, so the grant would deliver nothing",
360        crate::runtime::describe_stripped_env_allow_entries(entries)
361    )]
362    EnvAllowStrippedByBackstop {
363        /// Every distinct stripped entry, in first-declaration order.
364        entries: Vec<crate::runtime::StrippedEnvAllowEntry>,
365    },
366
367    /// A synthetic tool manifest was written under a name absent from
368    /// [`crate::runtime::RESERVED_TOOL_NAMES`].
369    ///
370    /// The inverse of [`Self::ReservedToolName`], and the reason a further runtime-provided tool
371    /// cannot be added without reserving its name: an unreserved name is claimable by an artifact,
372    /// which would then be installed and silently shadowed at dispatch.
373    #[error(
374        "'{name}' is written as a runtime-provided tool but is not one of {}; add it to \
375         RESERVED_TOOL_NAMES so no artifact can claim the name",
376        crate::runtime::RESERVED_TOOL_NAMES.join(", ")
377    )]
378    RuntimeProvidedToolNotReserved {
379        /// The name the synthetic write was attempted under.
380        name: String,
381    },
382
383    /// A capsule declares `exports.peer_files` together with `lifecycle.after_task: sleep`, and
384    /// either declared no `max_ttl` or declared one above the persistent ceiling.
385    ///
386    /// An ephemeral capsule needs no ceiling: teardown destroys the minting key, so every
387    /// outstanding handle stops verifying at once and the declared lifetime can never outlive the
388    /// process. `sleep` withdraws that bound deliberately, which makes the declared lifetime the
389    /// only one there is — so it has to be declared, and it has to be short.
390    #[error(
391        "exports.peer_files with lifecycle.after_task: sleep requires exports.peer_files.max_ttl \
392         to be declared and at most {ceiling_secs}s{}; a handle's lifetime is not a durability \
393         mechanism",
394        match declared_secs {
395            Some(secs) => format!(" (declared {secs}s)"),
396            None => String::new(),
397        }
398    )]
399    PersistentCapsuleNeedsHandleTtl {
400        /// The declared `max_ttl` in seconds, or `None` when the manifest declared none.
401        declared_secs: Option<u64>,
402        ceiling_secs: u64,
403    },
404
405    /// A capsule declares `capabilities.shell.staged_runtime` without an effective `sealed`
406    /// containment floor.
407    ///
408    /// Deliberately distinct from [`Self::ContainmentFloorUnmet`]: that one compares the declared
409    /// floor against what the *host* can back, and its remedy is to lower the floor or move hosts.
410    /// This one is decided against the declared floor alone and never looks at the host at all, so
411    /// it fires identically on a machine that could deliver `sealed` — a staged runtime has no
412    /// composed root to be staged into unless the capsule asked for one, and quietly launching it
413    /// without the mount would leave the interpreter simply absent. Its remedy is to raise the
414    /// declared floor (or drop the grant), which is the opposite advice.
415    ///
416    /// `binaries` names every offending `staged_runtime` binary so the operator does not have to
417    /// re-run to find the second one.
418    #[error(
419        "capabilities.shell.staged_runtime is declared for {} but the effective containment floor \
420         is '{declared}' — staging a runtime tree requires the 'sealed' floor, because there is no \
421         composed root to bind-mount it into below that",
422        .binaries.join(", ")
423    )]
424    StagedRuntimeRequiresSealed {
425        binaries: Vec<String>,
426        declared: murmur_artifact::ContainmentClass,
427    },
428
429    /// A `sealed` capsule allowlists a script whose interpreter's package tree nothing declared
430    /// could make reachable inside the composed root.
431    ///
432    /// Deliberately distinct from [`Self::StagedRuntimeRequiresSealed`], which it sits next to in
433    /// `stage_session`: that one fires when a grant *was* declared at too low a floor, this one
434    /// fires when no grant was declared at all and the floor is already `sealed`. Their remedies
435    /// point in opposite directions — raise the floor there, add a grant here.
436    ///
437    /// `entries` names every offending allowlist entry so an operator fixing this does not have to
438    /// re-run to discover the second script, following the same precedent.
439    #[error(
440        "capabilities.shell.allow grants {} under the 'sealed' containment floor, but nothing \
441         declared makes the interpreted entrypoint's own package tree reachable inside the \
442         composed root — the script's ELF/DT_NEEDED closure is empty, so staging it stages \
443         nothing its interpreter imports, and the capsule would fail with a module-not-found \
444         error partway into a run rather than here. Declare \
445         capabilities.shell.interpreter_runtime or capabilities.shell.staged_runtime naming the \
446         interpreter (measure the real directories with \
447         `strace -f -e trace=openat,getdents64 <the command>`), or use a copy of the interpreter \
448         and its packages that already lives under a fixed sealed runtime path",
449        .entries
450            .iter()
451            .map(UnreachableEntrypoint::to_string)
452            .collect::<Vec<_>>()
453            .join("; ")
454    )]
455    ShellBinaryPackageUnreachable { entries: Vec<UnreachableEntrypoint> },
456
457    /// A `sealed` session's composed root could not be built in the forked child, *after* the
458    /// pre-launch probe reported the mechanism available.
459    ///
460    /// Deliberately distinct from [`Self::ContainmentFloorUnmet`]: that one is a refusal decided
461    /// before anything is staged, on a host that never claimed to offer `sealed`. This one is a
462    /// host that claimed it and then failed to deliver — a race, a mount table that changed under
463    /// the runtime, or an edge case the cheap probe cannot catch. Conflating the two would tell an
464    /// operator to lower their declared floor when the real answer is that something moved.
465    ///
466    /// `detail` is the message the child wrote to the `pre_exec` diagnostic pipe, which names the
467    /// exact step (`unshare`, a specific bind mount, `pivot_root`) and its errno.
468    #[error(
469        "the sealed containment class was achievable at launch but its composed root could not be \
470         built for this subprocess: {detail}"
471    )]
472    SealedRootConstructionFailed { detail: String },
473
474    /// This host cannot give a capsule's native subprocess tree its own network namespace, so the
475    /// egress boundary that mediates `capabilities.network.allow` cannot be built.
476    ///
477    /// Raised before any registry pull, component compile or workdir creation, and raised for
478    /// **every** Linux capsule that can spawn a subprocess — including one whose
479    /// `capabilities.network.allow` is empty. That breadth is the point: with the namespace
480    /// missing, an empty allowlist would mean *unrestricted* egress rather than none, because the
481    /// seccomp `connect`/`sendto` interception that used to back it was deleted as unsound rather
482    /// than kept as a fallback. There is deliberately no path that continues at reduced
483    /// enforcement.
484    ///
485    /// Deliberately distinct from [`Self::ContainmentFloorUnmet`], which this would otherwise
486    /// look like: that one compares a *declared* containment class against what the host can
487    /// back, and its remedy is to lower the declared floor. A network namespace is not part of
488    /// the containment ladder — every class needs it equally — so lowering the floor fixes
489    /// nothing here, and offering that advice would be actively misleading.
490    #[error(
491        "this host cannot give the capsule's subprocess tree its own network namespace, so \
492         capabilities.network.allow cannot be enforced for it: {reason}"
493    )]
494    EgressNamespaceUnavailable {
495        blocker: crate::network_namespace::EgressNamespaceBlocker,
496        reason: String,
497    },
498
499    #[error(
500        "capsule component missing export murmur:capsule/run@0.1.0#run; rebuild the artifact against the versioned WIT (run `mur install` for a default artifact, or rebuild from source otherwise)"
501    )]
502    CapsuleExportMissing,
503
504    #[error(
505        "tool component '{name}' missing export murmur:tool/run@0.1.0#run; rebuild the artifact against the versioned WIT (run `mur install` for a default artifact, or rebuild from source otherwise)"
506    )]
507    ToolExportMissing { name: String },
508
509    #[error("capsule execution trapped: {0}")]
510    CapsuleTrap(String),
511
512    #[error(
513        "capsule execution exceeded its {seconds}s deadline and was interrupted; \
514         raise capabilities.limits.deadline_seconds in murmur.yaml if the capsule \
515         legitimately needs longer"
516    )]
517    CapsuleDeadlineExceeded { seconds: u64 },
518
519    #[error("capsule execution exceeded its configured resource limits: {message}")]
520    CapsuleResourceLimit { message: String },
521
522    #[error(
523        "shell subprocess '{binary}' was killed for exceeding \
524         capabilities.resources.{limit}: {detail}"
525    )]
526    ShellResourceLimitExceeded {
527        binary: String,
528        limit: String,
529        detail: String,
530    },
531
532    #[error(
533        "tool '{tool}' returned data_path '{path}', which does not resolve to a readable file \
534         beneath the session workdir ({code}): {detail}"
535    )]
536    ToolDataPathRefused {
537        tool: String,
538        path: String,
539        code: String,
540        detail: String,
541    },
542
543    #[error(
544        "this capsule can spawn native subprocesses but no cgroup v2 scope could be created to \
545         bound them ({reason}); on Linux the runtime refuses to launch rather than run a \
546         subprocess tree with no aggregate memory/pids/cpu ceiling — see the systemd user \
547         delegation requirement at {}",
548        RESOURCE_LIMITS_PLATFORM_URL
549    )]
550    CgroupDelegationUnavailable { reason: String },
551
552    #[error(
553        "session workdir grew to {observed_bytes} bytes, past the {max_bytes} byte ceiling \
554         (capabilities.resources.workdir_max_bytes)"
555    )]
556    WorkdirSizeExceeded { max_bytes: u64, observed_bytes: u64 },
557
558    #[error("failed to initialize WASI for {path}: {message}")]
559    WasiInit { path: String, message: String },
560
561    #[error("inference driver is not configured; add inference.driver.artifact to murmur.yaml")]
562    DriverNotConfigured,
563
564    #[error("inference driver '{0}' is not installed in the local tool registry")]
565    DriverNotInstalled(String),
566
567    /// An artifact whose operator entry declares `gateway:` has a bundled manifest with no usable
568    /// `upstream_auth:` block, so the runtime cannot tell how its upstream expects the key.
569    /// Refused at staging, before any component runs, whether or not `gateway.api_key` is set.
570    /// `reason` is `None` when the block is absent and says what is wrong when it is malformed.
571    #[error(
572        "artifact '{name}@{version}' declares no usable upstream_auth: block{}",
573        .reason.as_ref().map(|reason| format!(" ({reason})")).unwrap_or_default()
574    )]
575    GatewayArtifactDeclaresNoUpstreamAuth {
576        name: String,
577        version: String,
578        reason: Option<String>,
579    },
580
581    /// A `gateway:` block is declared on a `runtime: tool` entry whose artifact ships a native
582    /// implementation. A native tool's requests leave through the egress proxy and never pass the
583    /// credential gateway, so the key could never be attached. Refused at staging.
584    #[error(
585        "artifact '{name}' declares 'gateway:' but ships a native implementation, whose requests \
586         never pass the credential gateway"
587    )]
588    GatewayOnNativeArtifact { name: String },
589
590    /// The launch's `--lifecycle-task-acceptance queue` override turns a manifest that declares
591    /// `lifecycle.queue_depth: 0` under another acceptance into a queue with no room for a waiting
592    /// task. The manifest refuses `queue` at depth 0 at load; this is the one combination load
593    /// cannot see. Refused at staging, before any registry pull or workdir creation.
594    #[error(
595        "the launch sets lifecycle.task_acceptance to queue, and murmur.yaml declares \
596         lifecycle.queue_depth: 0, which leaves the queue no room for a waiting task"
597    )]
598    QueueWithoutRoom,
599
600    /// An [`crate::types::ArtifactRequest`]'s gateway carries neither a credential nor the
601    /// operator's `keyless: true`. The manifest parser refuses that shape first; staging refuses
602    /// it again so no caller can build a gateway that sends keyless by omission.
603    #[error("artifact '{name}' declares gateway.endpoint '{endpoint}' but binds no credential")]
604    GatewayWithoutCredential { name: String, endpoint: String },
605
606    /// `gateway.api_key: ${variable}` on artifact `artifact` names a credential that neither the
607    /// global config's `credentials:` map nor the launching environment holds. Refused at staging,
608    /// before the session directory exists.
609    #[error(
610        "murmur.yaml: gateway.api_key on artifact '{artifact}' references ${{{variable}}}, but \
611         neither credentials.{variable} in {} nor the environment variable {variable} is set",
612        .credentials_file
613            .as_ref()
614            .map(|path| path.display().to_string())
615            .unwrap_or_else(|| "the global config".to_string())
616    )]
617    GatewayCredentialNotFound {
618        artifact: String,
619        variable: String,
620        credentials_file: Option<std::path::PathBuf>,
621    },
622
623    /// `spend.machine_tokens_per_day` is in effect and the shared ledger it is kept in cannot be
624    /// used — an unset `HOME`, a `~/.murmur/spend` that cannot be made a `0700` directory, or a
625    /// daily file that cannot be opened. Raised at staging, before the session directory exists
626    /// and before any provider request.
627    #[error("spend ledger at {path} is unavailable: {message}")]
628    SpendLedgerUnavailable { path: String, message: String },
629
630    /// A capsule declaring `control:` could not mint its control token or write it beside its
631    /// running record. Raised before the door is announced: a capsule whose declared
632    /// controllability no controller could reach does not run. `reason` names the path and the
633    /// failure, never the token.
634    #[error("this capsule declares control: and its control token could not be written: {reason}")]
635    ControlTokenUnwritable { reason: String },
636
637    #[error("agent loop failed: {0}")]
638    AgentLoopFailed(String),
639
640    /// The launch ran, and the task it was run for did not complete. The session itself shut down
641    /// cleanly: everything it records — `out/result.txt`, the trace, a delegated child's
642    /// completion — was written before this was returned.
643    ///
644    /// `exit_status` is the `task_end`/`session_end` vocabulary, never `"ok"`: `"failed"`,
645    /// `"max_turns_reached"`, `"spend_ceiling_reached"` or `"canceled"`. `reason` is never empty;
646    /// for `"failed"` it is the reason the run's `task_failed` trace line carries.
647    #[error("the task ended {exit_status}: {reason}")]
648    TaskDidNotComplete {
649        exit_status: &'static str,
650        reason: String,
651    },
652
653    #[error("internal_port {port} is already bound; choose another port or omit internal_port to use an OS-assigned port")]
654    PortInUse { port: u16 },
655
656    /// A session whose manifest declares `capabilities.spawn.allow` could not register with
657    /// `mur-roost`, so the daemon does not hold the grants it would referee that session's
658    /// delegations against.
659    ///
660    /// Fatal rather than a warning: a capsule that can delegate but is unknown to the daemon is a
661    /// capsule running outside the only thing that bounds what it may spawn. A capsule that
662    /// declares no spawn capability never registers and never reaches this.
663    ///
664    /// `reason` is the transport or daemon-side failure verbatim. Neither this nor anything
665    /// derived from it carries a credential or an approval: the registration request's tokens
666    /// travel in headers, and the HTTP client never puts a request header into an error.
667    #[error(
668        "failed to register this session with mur-roost at {roost_url}: {reason}; a capsule \
669         declaring capabilities.spawn.allow must be known to the daemon that referees its \
670         spawns, so the launch is refused rather than run unrefereed"
671    )]
672    SpawnRegistrationFailed { roost_url: String, reason: String },
673
674    /// `MURMUR_SPAWNER` was set to something that is not a spawner handle.
675    ///
676    /// `reason` names what about the value could not be read, and nothing derived from it carries
677    /// the value itself: a handle names a parent's address and session, which is not this
678    /// process's to print back out.
679    #[error(
680        "MURMUR_SPAWNER does not carry a readable spawner handle: {reason}; a delegated child \
681         must be able to tell its spawner that it finished, so the launch is refused rather than \
682         run unreportable"
683    )]
684    SpawnerHandleUnreadable { reason: String },
685
686    /// `MURMUR_FORMATION_ID` was set to something that is not a formation id.
687    ///
688    /// `reason` names what about the value is wrong — its prefix, its length, or a character
689    /// outside lowercase hex — and never carries the value itself.
690    #[error(
691        "MURMUR_FORMATION_ID does not carry a formation id: {reason}; a session that cannot tell \
692         which formation it belongs to would be grouped with the wrong one, so the launch is \
693         refused"
694    )]
695    FormationIdUnreadable { reason: String },
696
697    /// `MURMUR_FORMATION_PEERS` is set in `mur run`'s own process environment, where nothing
698    /// legitimately puts it, or a list of peers is not one a guest could be handed.
699    ///
700    /// `reason` says where the variable was found, or names the pair at fault by its position and
701    /// what is wrong with it. It never carries the value.
702    #[error("MURMUR_FORMATION_PEERS cannot be used: {reason}, so the launch is refused")]
703    FormationPeersUnreadable { reason: String },
704
705    /// The formation channel `MURMUR_FORMATION_CHANNEL` names could not be read: the descriptor is
706    /// not open, its first line did not arrive in time or is not a member's bundle, or it names
707    /// another formation.
708    ///
709    /// `reason` names the problem and never quotes the line: the line carries the member's
710    /// formation tokens.
711    #[error(
712        "MURMUR_FORMATION_CHANNEL does not carry this member's formation credentials: {reason}; a \
713         member that cannot read what its launcher handed it could neither prove who it is nor \
714         call anyone, so the launch is refused"
715    )]
716    FormationChannelUnreadable { reason: String },
717
718    /// `MURMUR_FORMATION_LIFELINE` does not name a lifeline this session can hold: the value is
719    /// not a pipe's read end, it was read twice, it came without a formation id, or the session
720    /// cannot honour one (a script capsule, or a caller that does not own its process).
721    ///
722    /// `reason` names what is wrong, by descriptor number where there is one.
723    #[error(
724        "MURMUR_FORMATION_LIFELINE does not carry this member's formation lifeline: {reason}; a \
725         member that cannot hear its lifeline would keep running after its formation ends, so \
726         the launch is refused"
727    )]
728    FormationLifelineUnreadable { reason: String },
729
730    /// `MURMUR_SPAWNER_LIFELINE` does not name a lifeline this session can hold: the value is not
731    /// a pipe's read end, it was read twice, or the launch cannot honour one (a caller that does
732    /// not own its process).
733    ///
734    /// `reason` names what is wrong, by descriptor number where there is one.
735    #[error(
736        "MURMUR_SPAWNER_LIFELINE does not carry this session's spawner lifeline: {reason}; a \
737         delegated child that cannot hear its spawner would keep running after the session that \
738         delegated to it has ended, so the launch is refused"
739    )]
740    SpawnerLifelineUnreadable { reason: String },
741
742    /// A native tool's `bin/<name>` payload was built for another operating system or CPU
743    /// architecture than this host.
744    ///
745    /// Raised before any byte of any native binary in the same staging batch reaches the session
746    /// workdir: an image this host cannot exec would otherwise be written, made executable, and
747    /// then die on a raw `Exec format error` mid-run, at a point where nothing left says which
748    /// artifact was wrong.
749    ///
750    /// Both platforms are `current_platform()`-shaped strings, or the bare `darwin` a fat Mach-O
751    /// identifies as.
752    #[error(
753        "native tool '{name}' cannot run on this host: its binary is built for \
754         {binary_platform}, this host is {host_platform}"
755    )]
756    NativeBinaryPlatformMismatch {
757        name: String,
758        binary_platform: String,
759        host_platform: String,
760    },
761
762    /// The artifact a `transport: process` manifest names under `inference.driver` exports no
763    /// version of the `murmur:driver/process` interface at all, so it is not a process driver.
764    /// One exporting another version is [`RuntimeError::WitLevelMismatch`] instead.
765    #[error(
766        "artifact '{name}@{version}' is the transport: process driver but does not export \
767         {expected}; a process driver must be built against the process-driver world"
768    )]
769    ProcessDriverInterfaceMissing {
770        name: String,
771        version: String,
772        expected: String,
773    },
774
775    /// An artifact a launch stages names a `murmur:*` interface at a version other than the one
776    /// the WIT level this host serves lists for its package. `mismatched` holds every such
777    /// interface, in recorded order, and is never empty.
778    #[error(
779        "artifact '{name}@{version}' does not fit WIT level {level}, the level this mur serves: {}",
780        level_mismatch_clauses(*.level, .mismatched)
781    )]
782    WitLevelMismatch {
783        name: String,
784        version: String,
785        level: u64,
786        mismatched: Vec<UnservedInterface>,
787    },
788
789    /// The artifact a `transport: http` manifest names under `inference.driver` exports a
790    /// `murmur:driver/process@*` instance, so it drives a CLI rather than an HTTP API.
791    #[error(
792        "artifact '{name}@{version}' is the transport: http inference driver but exports {}, the \
793         process driver interface; name it under transport: process, or name an http driver",
794        .exported.join(", ")
795    )]
796    HttpDriverExportsProcessInterface {
797        name: String,
798        version: String,
799        exported: Vec<String>,
800    },
801
802    /// A `runtime: driver` artifact imports a `murmur:stream/*` instance at the served version of
803    /// the package under another interface name than `expected`, so it names an interface that
804    /// does not exist. `imported` holds every such import. A stream or `murmur:text/*` import at
805    /// another version is [`RuntimeError::WitLevelMismatch`] instead.
806    #[error(
807        "artifact '{name}@{version}' imports {}, which this host does not serve; a driver must \
808         import {expected} in its place",
809        .imported.join(", ")
810    )]
811    DriverStreamInterfaceNotServed {
812        name: String,
813        version: String,
814        imported: Vec<String>,
815        expected: String,
816    },
817
818    /// A process driver's `describe().required-env` names variables the manifest's
819    /// `capabilities.env.allow` does not declare. `missing` is in the driver's order, each name
820    /// once.
821    #[error(
822        "process driver '{name}@{version}' requires {} in its environment, which \
823         capabilities.env.allow does not declare",
824        .missing.join(", ")
825    )]
826    ProcessDriverRequiredEnvNotAllowed {
827        name: String,
828        version: String,
829        missing: Vec<String>,
830    },
831
832    /// A spend ceiling is in effect against a process driver whose `describe().reports-usage` is
833    /// `false`, so no turn it drives could ever be counted against that ceiling.
834    ///
835    /// `ceilings` names each ceiling in effect, in the order the operator would read them: the
836    /// manifest's `inference.max_session_tokens` first, then the effective config's
837    /// `spend.machine_tokens_per_day`.
838    #[error(
839        "process driver '{name}@{version}' reports no usage — its describe() sets \
840         reports-usage: false — so {} could never be enforced",
841        .ceilings.join(" and ")
842    )]
843    ProcessDriverReportsNoUsage {
844        name: String,
845        version: String,
846        ceilings: Vec<String>,
847    },
848
849    /// A process driver could not be instantiated with no grants, trapped in `describe`, or
850    /// described itself with an unusable `required-env` name. `message` is wasmtime's error, which
851    /// names an unsatisfied import, or names the unusable variable.
852    #[error("process driver '{name}@{version}' could not be loaded with no grants: {message}")]
853    ProcessDriverLoad {
854        name: String,
855        version: String,
856        message: String,
857    },
858
859    /// The executable a process capsule's harness runs as could not be resolved at staging.
860    /// `binary_source` names where the name came from, so the operator knows which field to
861    /// change: `inference.command`, or the process driver's own `describe()`.
862    #[error("harness binary '{binary}', named by {binary_source}, was not found on this host")]
863    HarnessBinaryNotFound {
864        binary: String,
865        binary_source: String,
866    },
867
868    /// The harness ended a turn in failure. Renders as [`E_RUN_033`]. `kind` is the driver's
869    /// `failure-kind`, spelled as it is in the WIT, or `max-turns` when this runtime stopped the
870    /// harness at the attempt's turn budget; `origin` distinguishes those two (`harness` /
871    /// `runtime`) and is what the trace's `harness_failed.source` records.
872    #[error("the harness turn failed ({kind}): {message}")]
873    HarnessTurnFailed {
874        kind: String,
875        message: String,
876        origin: String,
877    },
878
879    /// A turn launched `mode: resume` failed without the harness ever reporting the session it
880    /// was handed: the conversation this context names is gone from the harness's own store.
881    /// Renders as [`E_RUN_036`].
882    ///
883    /// `path` is the map file that still holds the id, or `None` on a launch that kept none. The
884    /// entry is deliberately left as it is — the next task in this context fails the same way
885    /// rather than quietly starting a new conversation, until somebody asks for it to be dropped
886    /// with `mur run --forget-session` or a message whose metadata carries `forgetSession: true`
887    /// under the door extension's key.
888    #[error(
889        "the harness '{harness}' could not continue session {session_id}, which context \
890         '{context_id}' names: {detail}{}",
891        harness_session_file_tail(.path)
892    )]
893    HarnessSessionGone {
894        context_id: String,
895        session_id: String,
896        harness: String,
897        path: Option<PathBuf>,
898        detail: String,
899    },
900
901    /// A forget was asked of a capsule that keeps no harness session: only
902    /// `inference.transport: process` has one, because only there does a harness own the
903    /// conversation. Raised at staging, so the launch leaves nothing behind.
904    ///
905    /// `transport` is the transport the capsule declared, or `none` for a capsule with no
906    /// `inference:` block at all.
907    #[error(
908        "--forget-session forgets the harness session a context names, and only \
909         inference.transport: process has one; this capsule's transport is '{transport}'"
910    )]
911    ForgetSessionUnsupportedTransport { transport: String },
912
913    /// A call into the process driver trapped, ran out of time, or refused. Renders as
914    /// [`E_RUN_034`]. `call` is the WIT function name; `message` is the driver's own refusal or
915    /// the failure's description.
916    #[error("process driver '{name}@{version}' failed in {call}: {message}")]
917    ProcessDriverCallFailed {
918        name: String,
919        version: String,
920        call: String,
921        message: String,
922    },
923
924    /// The harness went quiet: no stdout line and no bridge request for the whole inactivity
925    /// window, so the runtime killed it rather than waiting on a process that had stopped working.
926    /// Renders as [`E_RUN_035`].
927    #[error(
928        "the harness produced neither a line of output nor a tool call for {seconds}s and was \
929         killed"
930    )]
931    ProcessHarnessInactive { seconds: u64 },
932
933    #[error("runtime failure: {0}")]
934    Runtime(String),
935}
936
937/// The clauses of [`RuntimeError::WitLevelMismatch`]'s message, one per mismatched interface:
938/// `it exports <interface>, and level <N> has <package>@<version>`, joined with `; `.
939fn level_mismatch_clauses(level: u64, mismatched: &[UnservedInterface]) -> String {
940    mismatched
941        .iter()
942        .map(|mismatch| {
943            let direction = match mismatch.direction {
944                ContractDirection::Export => "exports",
945                ContractDirection::Import => "imports",
946            };
947            format!(
948                "it {direction} {}, and {}",
949                mismatch.interface,
950                level_has_phrase(level, mismatch)
951            )
952        })
953        .collect::<Vec<_>>()
954        .join("; ")
955}
956
957/// The tail of [`RuntimeError::HarnessSessionGone`]'s message: where the session id that could
958/// not be continued is recorded, so the operator can read it, or that this launch recorded it
959/// nowhere.
960fn harness_session_file_tail(path: &Option<PathBuf>) -> String {
961    match path {
962        Some(path) => format!(" (that id is recorded in {})", path.display()),
963        None => " (this launch recorded that id in memory only)".to_string(),
964    }
965}
966
967impl RuntimeError {
968    #[must_use]
969    pub fn artifact_not_found(name: impl Into<String>, version: impl Into<String>) -> Self {
970        Self::ArtifactNotFound {
971            name: name.into(),
972            version: version.into(),
973        }
974    }
975
976    #[must_use]
977    pub fn artifact_integrity_failed(name: impl Into<String>, version: impl Into<String>) -> Self {
978        Self::ArtifactIntegrityFailed {
979            name: name.into(),
980            version: version.into(),
981        }
982    }
983
984    #[must_use]
985    pub fn wasi(path: PathBuf, message: impl Into<String>) -> Self {
986        Self::WasiInit {
987            path: path.display().to_string(),
988            message: message.into(),
989        }
990    }
991}
992
993impl RuntimeError {
994    /// `error` as a runtime error: a refusal is [`Self::WorkdirPathRefused`], and an I/O failure
995    /// whatever `io` makes of its path and source.
996    pub(crate) fn from_workdir(
997        error: crate::workdir_fs::WorkdirError,
998        io: impl FnOnce(String, std::io::Error) -> Self,
999    ) -> Self {
1000        match error {
1001            crate::workdir_fs::WorkdirError::Refused(refusal) => {
1002                Self::WorkdirPathRefused { refusal }
1003            }
1004            crate::workdir_fs::WorkdirError::Io { path, source } => io(path, source),
1005        }
1006    }
1007}
1008
1009/// A refusal is [`RuntimeError::WorkdirPathRefused`]; any I/O failure is
1010/// [`RuntimeError::CreateWorkdir`]. Use [`RuntimeError::from_workdir`] where that variant is wrong.
1011impl From<crate::workdir_fs::WorkdirError> for RuntimeError {
1012    fn from(error: crate::workdir_fs::WorkdirError) -> Self {
1013        Self::from_workdir(error, |path, source| Self::CreateWorkdir { path, source })
1014    }
1015}
1016
1017#[cfg(test)]
1018mod tests {
1019    use super::*;
1020
1021    #[test]
1022    fn cgroup_delegation_refusal_links_the_published_platform_section() {
1023        let message = RuntimeError::CgroupDelegationUnavailable { reason: "x".into() }.to_string();
1024        assert!(message.contains("(x)"), "{message}");
1025        assert!(
1026            message
1027                .contains("https://docs.murmur.nexus/reference/resource-limits/#platform-behavior"),
1028            "{message}"
1029        );
1030        assert!(!message.contains("docs/content"), "{message}");
1031    }
1032}