@arcforge/types 2.0.155 → 2.0.157

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcforge/types",
3
- "version": "2.0.155",
3
+ "version": "2.0.157",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./src/index.ts",
package/src/index.ts CHANGED
@@ -16,6 +16,9 @@ export * from "./module"
16
16
  export * from "./plugin"
17
17
  export * from "./policy"
18
18
  export * from "./policy-resolve"
19
+ export * from "./policy-normalize"
20
+ export * from "./policy-build"
21
+ export * from "./supervisor"
19
22
  export * from "./capsule-config"
20
23
  export * from "./capsule-scope"
21
24
  export * from "./knowledge"
@@ -0,0 +1,107 @@
1
+ import type { AxonBlueprint } from "./blueprint"
2
+ import type { CapsulePolicy } from "./policy"
3
+ import { intersect, keyed, resolveFsPaths, type NormalizedPolicy } from "./policy-normalize"
4
+
5
+ /**
6
+ * Policy — the ONE place a user's intent becomes a machine-enforceable policy.
7
+ *
8
+ * Resolution used to happen twice, in two packages: the kernel intersected the
9
+ * profile ceiling with the agent's own policy, then the capsule's Blueprint()
10
+ * normalised the result again at its own seam. Two normalisations meant two
11
+ * wildcard literals kept in step by a test — see POLICY_WILDCARD. With the
12
+ * agent boundary moving out to the whole process, both consumers now live
13
+ * below this seam and there is exactly one resolution.
14
+ *
15
+ * ── The two outputs, and why they are not the same thing ────────────────────
16
+ *
17
+ * A resolved policy feeds two enforcement layers with DIFFERENT expressive
18
+ * power, and conflating them is how a ceiling springs a leak:
19
+ *
20
+ * confinement — the OS wall. Paths become bind mounts, network becomes a
21
+ * namespace, limits become cgroup caps. It cannot express a
22
+ * glob: `process: { allow: ["git *"] }` is not something a
23
+ * mount namespace has any opinion about.
24
+ *
25
+ * mediation — the in-agent gate. Globs, per-host rules, per-command
26
+ * patterns, escalation to a human. It runs INSIDE the box and
27
+ * so can only ever narrow what the box already permits.
28
+ *
29
+ * The invariant between them: **the OS wall is the ceiling and mediation
30
+ * narrows within it.** A mediator that allowed what the wall denies would
31
+ * produce calls that pass policy and then fail as ENOENT — a confusing bug
32
+ * class that is cheap to prevent here and expensive to diagnose later.
33
+ */
34
+ export type ResolvedPolicy = {
35
+ /**
36
+ * What the capsule/agent enforces — the keyed, fully-normalised shape.
37
+ * Every bare rule is expanded, every fs path is absolute.
38
+ */
39
+ policy: CapsulePolicy
40
+ /** Which containment tier this policy asked for, after the ceiling applied. */
41
+ isolation: NonNullable<CapsulePolicy["isolation"]>
42
+ }
43
+
44
+ /**
45
+ * The capsule's own defaults are deny-by-default — correct for a sandbox that
46
+ * must never silently grant an undeclared capability to arbitrary loaded code.
47
+ * Axon is a different trust boundary: it is wiring up a box for its OWN
48
+ * declared blueprint, not sandboxing foreign code, so its default posture is
49
+ * the opposite — allow everything the blueprint's own policy doesn't restrict.
50
+ *
51
+ * Scoped to loadable tools: a rule naming a namespace that is never installed
52
+ * grants nothing and only makes the policy surface read as larger than it is.
53
+ */
54
+ type PolicyOpts = {
55
+ blueprint: AxonBlueprint
56
+ /** Tool namespaces actually installed — each gets an allow rule unless the policy says otherwise. */
57
+ tools: string[]
58
+ }
59
+
60
+ export function Policy(opts: PolicyOpts): ResolvedPolicy {
61
+ const { blueprint } = opts
62
+
63
+ // The two layers, intersected into what the agent enforces.
64
+ //
65
+ // The profile is a CEILING: an agent narrows within it and can never widen
66
+ // it. Resolved HERE rather than in the TUI, because this is the one seam
67
+ // every consumer passes through — `axon dev`, `axon run` in a script, a
68
+ // test harness. A ceiling applied only on the TUI's spawn path would be
69
+ // advisory, and the CLI is exactly where someone scripting would bypass it
70
+ // without meaning to.
71
+ //
72
+ // Both layers normalised to the KEYED shape before they meet: a bare
73
+ // `tools: "escalate"` is an authoring convenience, and every rule below
74
+ // reads one shape.
75
+ const userPolicy: NormalizedPolicy = intersect(
76
+ blueprint.profilePolicy ? keyed(blueprint.profilePolicy) : undefined,
77
+ keyed(blueprint.config.policy ?? {}),
78
+ )
79
+
80
+ // The invariant: not setting a security policy means "I don't care" — the
81
+ // agent gets full access to the machine, no hassle, no dependencies.
82
+ // Setting ANY containment intent (fs/network/limits) opts into rootless
83
+ // confinement, which needs no privilege and just works. A user can always
84
+ // name isolation explicitly to force a tier ("hardened", or "none" despite
85
+ // having fs).
86
+ //
87
+ // Read off the INTERSECTED policy, so a profile declaring containment opts
88
+ // every agent on the machine into it — an agent that declares nothing still
89
+ // gets the wall its profile asked for.
90
+ const wantsContainment =
91
+ userPolicy.fs !== undefined || userPolicy.network !== undefined || userPolicy.limits !== undefined
92
+ const isolation = userPolicy.isolation ?? (wantsContainment ? "auto" : "none")
93
+
94
+ const tools: Record<string, true> = {}
95
+ for (const name of opts.tools) tools[name] = true
96
+
97
+ return {
98
+ isolation,
99
+ policy: {
100
+ ...userPolicy,
101
+ isolation,
102
+ ...(userPolicy.fs ? { fs: resolveFsPaths(userPolicy.fs, blueprint.paths.root) } : {}),
103
+ process: { spawn: true, run: true, ...userPolicy.process },
104
+ tools: { ...tools, ...userPolicy.tools },
105
+ } as CapsulePolicy,
106
+ }
107
+ }
@@ -0,0 +1,228 @@
1
+ import { resolveIsolation } from "./policy-resolve"
2
+ import type { CapsulePolicy, PolicyBucket, PolicyRule } from "./policy"
3
+
4
+ /**
5
+ * The key a blanket rule normalises to — see `PolicyBucket`.
6
+ *
7
+ * ONE declaration now. It used to exist three times (capsule's Blueprint, the
8
+ * kernel's ceiling resolver, and the guest mediator) with a test asserting the
9
+ * literals matched, because the guest could not import across the subprocess
10
+ * boundary. Resolution happens here, above every consumer, so the duplicates
11
+ * and their guard are gone.
12
+ */
13
+ export const POLICY_WILDCARD = "*"
14
+
15
+ /** A rule with no keys of its own — `true`, `false`, `"escalate"`, or a glob object. */
16
+ function isBareRule(value: PolicyBucket | Partial<CapsulePolicy["process"]>): value is PolicyRule {
17
+ if (typeof value === "boolean" || value === "escalate") return true
18
+ // The glob object form. Distinguished from a keyed bucket by its OWN keys:
19
+ // `allow`/`deny`/`escalate` are the rule's vocabulary, and a bucket keyed
20
+ // by a module actually named "allow" is a collision nobody can author
21
+ // (module names are scoped identifiers, not bare verbs).
22
+ if (typeof value !== "object" || value === null) return false
23
+ const keys = Object.keys(value)
24
+ return keys.length > 0 && keys.every(key => key === "allow" || key === "deny" || key === "escalate")
25
+ }
26
+
27
+ function bucket(value: PolicyBucket | undefined): Record<string, PolicyRule> {
28
+ if (value === undefined) return {}
29
+ return isBareRule(value) ? { [POLICY_WILDCARD]: value } : value
30
+ }
31
+
32
+ export type NormalizedPolicy = Omit<AuthoredPolicy, "tools" | "network" | "process"> & {
33
+ tools?: Record<string, PolicyRule>
34
+ network?: Record<string, PolicyRule>
35
+ process?: Partial<CapsulePolicy["process"]>
36
+ }
37
+
38
+ /** A policy as a human authored it — bare rules still un-expanded. */
39
+ export type AuthoredPolicy = Omit<Partial<CapsulePolicy>, "tools" | "network" | "process"> & {
40
+ tools?: PolicyBucket
41
+ network?: PolicyBucket
42
+ process?: Partial<CapsulePolicy["process"]> | PolicyRule
43
+ }
44
+
45
+ /**
46
+ * One authored policy, with every bare surface rule expanded to `{ "*": rule }`.
47
+ *
48
+ * `tools: "escalate"` and `tools: { "*": "escalate" }` are the same statement;
49
+ * this makes them the same VALUE, so nothing downstream has to ask which was
50
+ * written. `process` is a fixed pair rather than an open bucket, so a bare rule
51
+ * there applies to both verbs instead of becoming a key no verb would match.
52
+ */
53
+ export function keyed(policy: AuthoredPolicy): NormalizedPolicy {
54
+ const { tools, network, process: proc, ...rest } = policy
55
+ return {
56
+ ...rest,
57
+ ...(tools !== undefined ? { tools: bucket(tools) } : {}),
58
+ ...(network !== undefined ? { network: bucket(network) } : {}),
59
+ ...(proc !== undefined
60
+ ? { process: isBareRule(proc) ? { spawn: proc, run: proc } : proc }
61
+ : {}),
62
+ }
63
+ }
64
+
65
+ /**
66
+ * One capability's rule under both layers.
67
+ *
68
+ * A bare profile verdict wins outright — it cannot be narrowed further by a
69
+ * pattern and cannot be widened at all. Otherwise the agent's rule stands and
70
+ * the profile's is carried alongside for the mediator to evaluate against.
71
+ */
72
+ function pairRule(profile: PolicyRule | undefined, agent: PolicyRule | undefined): PolicyRule {
73
+ if (profile === false) return false
74
+ if (profile === "escalate" && agent !== false) return "escalate"
75
+ if (profile === undefined) return agent ?? true
76
+ if (profile === true) return agent ?? true
77
+ // Profile is glob-shaped: the agent narrows within it, and the pair is
78
+ // evaluated per call. With no agent rule, the profile IS the rule.
79
+ return agent ?? profile
80
+ }
81
+
82
+ /** pairRule across two keyed maps, over the union of their keys. */
83
+ function pairRules(
84
+ profile: Record<string, PolicyRule> | undefined,
85
+ agent: Record<string, PolicyRule> | undefined,
86
+ ): Record<string, PolicyRule> {
87
+ const keys = new Set([...Object.keys(profile ?? {}), ...Object.keys(agent ?? {})])
88
+ const out: Record<string, PolicyRule> = {}
89
+
90
+ // A profile WILDCARD applies to every key, not only to `*`.
91
+ //
92
+ // Without this the ceiling leaks in exactly the case the wildcard exists
93
+ // for: a profile saying `tools: "escalate"` normalises to `{ "*":
94
+ // "escalate" }`, an agent's `tools: { fs: true }` keeps its own key, and
95
+ // the mediator's exact-match then hands back `true` — the profile's
96
+ // blanket never consulted. A ceiling a named grant can punch through is
97
+ // not a ceiling.
98
+ //
99
+ // Paired per key rather than replacing the agent's rule, so the profile's
100
+ // blanket and the agent's specific are BOTH carried to the mediator and
101
+ // the verdict can still name which layer decided.
102
+ const blanket = profile?.[POLICY_WILDCARD]
103
+
104
+ for (const key of keys) out[key] = pairRule(profile?.[key] ?? blanket, agent?.[key])
105
+ return out
106
+ }
107
+
108
+ /**
109
+ * Intersect the profile ceiling with an agent's own policy.
110
+ *
111
+ * ── Why this is a UNION of keys, not of permissions ─────────────────────────
112
+ *
113
+ * Both layers' rules are carried forward per capability, and the MEDIATOR
114
+ * evaluates the pair at call time (see resolveVerdict in @arcforge/types).
115
+ * That split is deliberate: merging two glob rules into one is where a ceiling
116
+ * silently springs a leak — `allow: ["git status"]` unioned with
117
+ * `allow: ["git push"]` permits a command neither layer permitted alone.
118
+ *
119
+ * So this composes the SHAPE (which capabilities each layer has an opinion
120
+ * about) and leaves the VERDICT to per-call evaluation, where both rules are
121
+ * still separately available and the answer can name which one decided.
122
+ *
123
+ * ── The bare cases collapse here ────────────────────────────────────────────
124
+ *
125
+ * `true`/`false`/`"escalate"` carry no patterns, so there is nothing to defer:
126
+ * a profile `false` is final regardless of what the agent says, and a profile
127
+ * `true` adds no constraint the agent could violate. Collapsing them at this
128
+ * seam keeps the common case (a profile that just says "no shell") from
129
+ * costing a pair lookup on every call.
130
+ *
131
+ * fs and limits are NOT intersected: they are OS-layer facts (bind mounts,
132
+ * cgroups) with no verdict to evaluate, and the mediator never sees them. The
133
+ * profile's are taken when present, since a ceiling that a bind mount ignores
134
+ * is not a ceiling.
135
+ */
136
+ export function intersect(
137
+ profile: NormalizedPolicy | undefined,
138
+ agent: NormalizedPolicy,
139
+ ): NormalizedPolicy {
140
+ if (!profile) return agent
141
+
142
+ // resolveIsolation returns undefined only when BOTH layers are silent, in
143
+ // which case the key must stay absent rather than become an explicit
144
+ // `undefined` — Policy() reads its absence to infer the tier from whether
145
+ // containment was asked for at all.
146
+ const isolation = resolveIsolation(profile.isolation, agent.isolation)
147
+
148
+ return {
149
+ ...agent,
150
+ ...(isolation !== undefined ? { isolation } : {}),
151
+
152
+ // The OS wall. A profile grant is the outer bound, so an agent's paths
153
+ // are kept only where the profile has no opinion at all — otherwise a
154
+ // narrower mount would have to be computed, which bind mounts cannot
155
+ // express as an intersection of globs.
156
+ ...(profile.fs ? { fs: profile.fs } : {}),
157
+ ...(profile.limits ? { limits: profile.limits } : {}),
158
+
159
+ ...(profile.network || agent.network
160
+ ? { network: pairRules(profile.network, agent.network) }
161
+ : {}),
162
+ ...(profile.tools || agent.tools
163
+ ? { tools: pairRules(profile.tools, agent.tools) }
164
+ : {}),
165
+
166
+ process: {
167
+ spawn: pairRule(profile.process?.spawn, agent.process?.spawn),
168
+ run: pairRule(profile.process?.run, agent.process?.run),
169
+ },
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Path resolution WITHOUT `node:path`.
175
+ *
176
+ * This package is the cross-package contract — it is imported by the runtime,
177
+ * the kernel, the TUI and the website, and it declares no runtime
178
+ * dependencies. A top-level `import { isAbsolute, resolve } from "node:path"`
179
+ * here reached the browser through the barrel in `index.ts`: Vite replaced the
180
+ * builtin with a stub that exports only `default`, so the named import threw
181
+ * `does not provide an export named 'resolve'` at module-evaluation time and
182
+ * took down every page on the site with a 500 — including ones that never
183
+ * touch a policy.
184
+ *
185
+ * The two operations are POSIX string manipulation, not filesystem access, so
186
+ * they are written out rather than imported. Policy paths are always POSIX:
187
+ * they are authored in `axon.config.ts` and consumed by the capsule's Linux
188
+ * sandbox, so Windows drive letters and backslashes are not in scope. If that
189
+ * ever changes, this needs a real path implementation — NOT `node:path` back,
190
+ * which would reintroduce exactly this failure.
191
+ */
192
+ function isAbsolutePath(p: string): boolean {
193
+ return p.startsWith("/")
194
+ }
195
+
196
+ /**
197
+ * `root` + `p`, with `.` and `..` segments resolved. Mirrors
198
+ * `path.resolve(root, p)` for the relative-POSIX case this seam sees.
199
+ */
200
+ function joinPath(root: string, p: string): string {
201
+ const segments: string[] = []
202
+ for (const segment of `${root}/${p}`.split("/")) {
203
+ if (segment === "" || segment === ".") continue
204
+ // `..` pops, but never past the root — a policy path that climbs out
205
+ // of the project is a broken grant, and silently letting it escape is
206
+ // the one outcome a sandbox must not have.
207
+ if (segment === "..") {
208
+ segments.pop()
209
+ continue
210
+ }
211
+ segments.push(segment)
212
+ }
213
+ return `/${segments.join("/")}`
214
+ }
215
+
216
+ /**
217
+ * fs paths are authored relative to the AGENT PROJECT, not the directory the
218
+ * user happened to launch from. `fs: { read: ["./workspace"] }` in
219
+ * agents/foo/axon.config.ts means agents/foo/workspace, wherever axon was run.
220
+ * Resolved at this one seam, so the OS builders only ever see absolute paths.
221
+ */
222
+ export function resolveFsPaths(fs: NonNullable<CapsulePolicy["fs"]>, root: string): CapsulePolicy["fs"] {
223
+ const abs = (p: string) => (isAbsolutePath(p) ? p : joinPath(root, p))
224
+ return {
225
+ ...(fs.read ? { read: fs.read.map(abs) } : {}),
226
+ ...(fs.write ? { write: fs.write.map(abs) } : {}),
227
+ }
228
+ }
@@ -147,7 +147,26 @@ export function resolveVerdict(
147
147
  * through the verdict ranking: a profile asking for `hardened` cannot be
148
148
  * loosened to `none` by an agent, but an agent may harden beyond its profile.
149
149
  */
150
- const ISOLATION_RANK = { none: 0, auto: 1, hardened: 2 } as const
150
+ /**
151
+ * `container` sits between `none` and `auto`, and the placement is deliberate.
152
+ *
153
+ * The rank answers one question: if a profile asks for X and an agent asks for
154
+ * Y, which wins? Higher wins, so the order must express "strictly more
155
+ * per-agent enforcement than".
156
+ *
157
+ * `container` gives MORE than `none` (a tenant boundary exists, and it is a
158
+ * strong one) but LESS per-agent than `auto` (the user's own fs/network/limits
159
+ * get no OS enforcement inside it — see CapsulePolicy.isolation). So a profile
160
+ * demanding `auto` must not be satisfiable by an agent declaring `container`,
161
+ * which this ordering guarantees: the profile's higher rank wins.
162
+ *
163
+ * The reverse is the case that matters in practice — a deploy declaring
164
+ * `container` under a profile asking for `auto` keeps `auto` and then fails
165
+ * loudly at build, which is correct. A hosted runtime that cannot provide
166
+ * `auto` must say so at the DEPLOY path, not by quietly out-ranking the
167
+ * profile that asked for a wall.
168
+ */
169
+ const ISOLATION_RANK = { none: 0, container: 1, auto: 2, hardened: 3 } as const
151
170
 
152
171
  export function resolveIsolation(
153
172
  profile: CapsulePolicy["isolation"],
package/src/policy.ts CHANGED
@@ -87,6 +87,30 @@ export type CapsulePolicy = {
87
87
  * tier: light security that just works. The default when any
88
88
  * fs/network/limits policy is set.
89
89
  *
90
+ * - `"container"` — the CONTAINER is the box. Declared, never inferred.
91
+ *
92
+ * For a hosted runtime (Cloud Run, a managed platform) where the process
93
+ * is already inside a per-tenant sandbox and cannot nest another. That is
94
+ * not a preference: bwrap needs unprivileged user namespaces plus mount
95
+ * operations, and a standard container gives it neither — measured, it
96
+ * needs `seccomp=unconfined` AND `apparmor=unconfined` AND CAP_SYS_ADMIN
97
+ * together, and Cloud Run offers none of the three (gVisor implements
98
+ * user namespaces but not the mount operations bwrap performs).
99
+ *
100
+ * The honest consequence, stated rather than hidden: the USER'S declared
101
+ * fs/network/limits policy gets no OS enforcement here. The container
102
+ * boundary handles tenant isolation and the mediator remains the only
103
+ * per-agent layer. This is NOT weaker hosting — gVisor is a stronger
104
+ * sandbox than bwrap — it is a different thing being enforced by a
105
+ * different party.
106
+ *
107
+ * DECLARED, never inferred, precisely because it is weaker per-agent: a
108
+ * runtime that quietly fell back here when namespaces were unavailable
109
+ * would turn a misconfigured host into a silent downgrade, which is the
110
+ * failure mode `Confinement.build()` already refuses. The deploy path
111
+ * knows it is deploying and says so; everywhere else, asking for `auto`
112
+ * and not getting it stays fatal.
113
+ *
90
114
  * - `"hardened"` — privileged containment. Everything in `"auto"` plus a
91
115
  * dedicated unprivileged OS user (true uid separation), system cgroups,
92
116
  * and kernel network allowlisting. This is the org / VPS / untrusted-agent
@@ -94,7 +118,7 @@ export type CapsulePolicy = {
94
118
  * helper at runtime; a missing primitive is a hard boot error, never a
95
119
  * silent downgrade. Explicit opt-in only — never defaulted into.
96
120
  */
97
- isolation?: "none" | "auto" | "hardened"
121
+ isolation?: "none" | "auto" | "container" | "hardened"
98
122
 
99
123
  /**
100
124
  * Filesystem view, enforced by the mount namespace under `isolation: "auto"`.
@@ -13,16 +13,32 @@ import { ENTRY_EVENT_PREFIXES } from "./events/entries"
13
13
  /**
14
14
  * Internal machinery telemetry — devtools/flame-graph material, never a
15
15
  * runtime/continuity fact. kernel:* is the machinery's own record; cognet:* is
16
- * the brain narrating its world; capsule:* is the sandbox's own stream.
16
+ * the brain narrating its world; process:* is the agent's own execution stream.
17
17
  *
18
18
  * Two carve-outs: entry families under cognet:* are entries, not telemetry (so
19
- * isEntryEvent is checked first by classifyEvent), and capsule:attach/detach are
19
+ * isEntryEvent is checked first by classifyEvent), and process:attach/detach are
20
20
  * the runtime's continuity facts — same namespace, different role — which
21
21
  * hydration and humans read from the session view.
22
+ *
23
+ * ── `capsule:` is still accepted, and must stay that way ────────────────────
24
+ *
25
+ * The prefix was renamed when the agent itself became the process: "capsule"
26
+ * named a sandbox subprocess that no longer describes anything. But session
27
+ * logs are DURABLE — a `.jsonl` written last week still carries the old names,
28
+ * and every reader here (the flame graph, the process tree, readSession)
29
+ * matches on these literals. Dropping the old prefix would not break a test;
30
+ * it would silently make historical sessions render as empty timelines.
31
+ *
32
+ * So this reads both and emitters write only the new one. The compatibility
33
+ * arm can go once no log anyone cares about predates the rename.
22
34
  */
23
35
  export function isKernelEvent(type: string): boolean {
24
- if (type === "capsule:attach" || type === "capsule:detach") return false
25
- return type.startsWith("kernel:") || type.startsWith("cognet:") || type.startsWith("capsule:")
36
+ if (type === "process:attach" || type === "process:detach") return false
37
+ if (type === "process:attach" || type === "process:detach") return false
38
+ return type.startsWith("kernel:")
39
+ || type.startsWith("cognet:")
40
+ || type.startsWith("process:")
41
+ || type.startsWith("capsule:")
26
42
  }
27
43
 
28
44
  /** An interaction — what cognition and clients see. Derived from the canonical prefix list. */
@@ -51,16 +51,16 @@ export type CapsuleCommandOrigin = "cognet" | "host"
51
51
 
52
52
  export type CapsuleEventMap =
53
53
  // ── Lifecycle ────────────────────────────────────────────────────────────
54
- & AxonSpan<"capsule:boot", {}, {}, { error: AxonErrorJSON }>
54
+ & AxonSpan<"process:boot", {}, {}, { error: AxonErrorJSON }>
55
55
  & {
56
- "capsule:ready": {}
57
- "capsule:shutdown": {}
56
+ "process:ready": {}
57
+ "process:shutdown": {}
58
58
  /** Unhandled error inside the subprocess. Exit usually follows. */
59
- "capsule:crash": { error: AxonErrorJSON }
59
+ "process:crash": { error: AxonErrorJSON }
60
60
  /** The capsule subprocess itself exited (not a managed child process). */
61
- "capsule:exit": { code: number | null; reason?: string }
61
+ "process:exit": { code: number | null; reason?: string }
62
62
  /** A wire line failed to parse — the sandbox is speaking garbage. Never dropped silently. */
63
- "capsule:parse:error": { error: AxonErrorJSON; line?: string }
63
+ "process:parse:error": { error: AxonErrorJSON; line?: string }
64
64
 
65
65
  /**
66
66
  * Supervision gave up — the capsule is gone and will not come back on
@@ -68,11 +68,11 @@ export type CapsuleEventMap =
68
68
  * also fires when the restart budget is exhausted, which is a
69
69
  * supervision verdict rather than one restart going wrong.
70
70
  */
71
- "capsule:dead": { error: AxonErrorJSON }
71
+ "process:dead": { error: AxonErrorJSON }
72
72
  }
73
73
  // ── Supervision (host-side) — one crash-and-recover cycle ───────────────
74
74
  & AxonSpan<
75
- "capsule:restart",
75
+ "process:restart",
76
76
  { restartCount: number },
77
77
  { restartCount: number },
78
78
  { restartCount: number; error: AxonErrorJSON }
@@ -86,20 +86,20 @@ export type CapsuleEventMap =
86
86
  // Absent means "cognet" — every command predating this field, and
87
87
  // every command the runtime itself issues.
88
88
  & AxonCancellableSpan<
89
- "capsule:cmd",
89
+ "process:cmd",
90
90
  { id: string; origin?: CapsuleCommandOrigin },
91
91
  { id: string; result: unknown; scope: CapsuleScope },
92
92
  { id: string; error: AxonErrorJSON },
93
93
  { id: string; durationMs: number }
94
94
  >
95
95
  & {
96
- "capsule:cmd:stdout": { id: string; data: string }
97
- "capsule:cmd:interrupt:requested": { id: string; reason: "abort" | "timeout" }
96
+ "process:cmd:stdout": { id: string; data: string }
97
+ "process:cmd:interrupt:requested": { id: string; reason: "abort" | "timeout" }
98
98
  "capsule:cmd:hard-killed": { id: string; graceMs: number }
99
99
  }
100
100
  // ── Tool call spans (mediated fn calls inside a command) ────────────────
101
101
  & AxonSpan<
102
- "capsule:fn",
102
+ "process:fn",
103
103
  { commandId: string; module: string; fn: string; args: unknown[] },
104
104
  { commandId: string; module: string; fn: string; result: unknown },
105
105
  { commandId: string; module: string; fn: string; error: AxonErrorJSON }
@@ -108,7 +108,7 @@ export type CapsuleEventMap =
108
108
  // A dynamic import inside the sandbox: genuinely bracketed, and slow
109
109
  // or hanging often enough that the :start half earns its place.
110
110
  & AxonSpan<
111
- "capsule:tool:load",
111
+ "process:tool:load",
112
112
  { namespace: string },
113
113
  { namespace: string; fns: string[] },
114
114
  { namespace: string; error: AxonErrorJSON }
@@ -120,7 +120,7 @@ export type CapsuleEventMap =
120
120
  // breaking (the child could not be reaped, the handle was lost), which
121
121
  // is why its payload carries no exit code: there isn't one.
122
122
  & AxonSpan<
123
- "capsule:proc",
123
+ "process:proc",
124
124
  { procId: string; pid: number; command: string; cwd: string; kind: "managed" | "run" },
125
125
  { procId: string; code: number },
126
126
  { procId: string; error: AxonErrorJSON }
@@ -130,15 +130,15 @@ export type CapsuleEventMap =
130
130
  * Unloading is a synchronous map delete — a settled fact with no
131
131
  * interior, so it stays a bare event rather than a one-tick span.
132
132
  */
133
- "capsule:tool:unloaded": { namespace: string }
133
+ "process:tool:unloaded": { namespace: string }
134
134
 
135
135
  // ── Trusted host bridge ──────────────────────────────────────────────
136
136
  /** Private request transport for the capsule Axon facade. Never durable. */
137
- "capsule:host:request": { id: string; commandId: string | null; method: string; input: unknown }
137
+ "process:host:request": { id: string; commandId: string | null; method: string; input: unknown }
138
138
 
139
139
  // ── Child process byte streams ───────────────────────────────────────
140
- "capsule:proc:stdout": { procId: string; data: string }
141
- "capsule:proc:stderr": { procId: string; data: string }
140
+ "process:proc:stdout": { procId: string; data: string }
141
+ "process:proc:stderr": { procId: string; data: string }
142
142
  /**
143
143
  * A process the sandbox asked for was never created — refused by
144
144
  * policy, killed before it could spawn, or the spawn itself failed.
@@ -146,14 +146,14 @@ export type CapsuleEventMap =
146
146
  * bracket to close. Same rule as capsule:fn, which opens only once
147
147
  * policy admits the call.
148
148
  */
149
- "capsule:proc:denied": { procId: string; command: string; error: AxonErrorJSON }
150
- "capsule:proc:stdin:error": { procId: string; error: AxonErrorJSON }
149
+ "process:proc:denied": { procId: string; command: string; error: AxonErrorJSON }
150
+ "process:proc:stdin:error": { procId: string; error: AxonErrorJSON }
151
151
 
152
152
  // ── Policy ───────────────────────────────────────────────────────────
153
- "capsule:policy:denied": { id: string; module: string; fn: string; args: unknown[]; rule: string }
154
- "capsule:policy:escalation": { id: string; module: string; fn: string; args: unknown[]; rule: string }
153
+ "process:policy:denied": { id: string; module: string; fn: string; args: unknown[]; rule: string }
154
+ "process:policy:escalation": { id: string; module: string; fn: string; args: unknown[]; rule: string }
155
155
  /** Host-side: the escalate callback's verdict for a pending escalation. */
156
- "capsule:policy:decision": { id: string; allow: boolean; durationMs: number }
156
+ "process:policy:decision": { id: string; allow: boolean; durationMs: number }
157
157
 
158
158
  // ── Activities (semantic tool emissions) ─────────────────────────────
159
159
  /**
@@ -161,12 +161,12 @@ export type CapsuleEventMap =
161
161
  * the ambient axon.activity(). Correlated to the running command the
162
162
  * same way capsule:console is; null only if emitted outside any command.
163
163
  */
164
- "capsule:activity": Activity & { commandId: string | null }
164
+ "process:activity": Activity & { commandId: string | null }
165
165
 
166
166
  // ── Console + state ──────────────────────────────────────────────────
167
167
  /** User console output, captured — correlated to the running command, never raw on stdout. */
168
- "capsule:console": { level: "log" | "info" | "warn" | "error" | "debug"; commandId: string | null; args: unknown[] }
169
- "capsule:cwd": { cwd: string }
168
+ "process:console": { level: "log" | "info" | "warn" | "error" | "debug"; commandId: string | null; args: unknown[] }
169
+ "process:cwd": { cwd: string }
170
170
  }
171
171
 
172
172
  export type CapsuleEventName = keyof CapsuleEventMap
@@ -182,9 +182,9 @@ export type AnyCapsuleEvent = {
182
182
  * derives its split from here, never from its own type sniff.
183
183
  */
184
184
  export const CAPSULE_TRANSIENT_EVENTS = new Set<CapsuleEventName>([
185
- "capsule:cmd:stdout",
186
- "capsule:proc:stdout",
187
- "capsule:proc:stderr",
188
- "capsule:console",
189
- "capsule:host:request",
185
+ "process:cmd:stdout",
186
+ "process:proc:stdout",
187
+ "process:proc:stderr",
188
+ "process:console",
189
+ "process:host:request",
190
190
  ])
@@ -284,8 +284,8 @@ export type AxonRuntimeEvent =
284
284
  "axon:session:closed": {}
285
285
 
286
286
  // ── Capsule attachment (one capsule per session; telemetry lives in the capsule package) ──
287
- "capsule:attach": { capsuleId: string; cwd: string }
288
- "capsule:detach": { capsuleId: string; reason: "shutdown" | "crash" | "reload" }
287
+ "process:attach": { capsuleId: string; cwd: string }
288
+ "process:detach": { capsuleId: string; reason: "shutdown" | "crash" | "reload" }
289
289
 
290
290
  // ── Server ───────────────────────────────────────────────────────────────
291
291
  "axon:server:request": { method: string; path: string; status: number; durationMs: number }
@@ -0,0 +1,229 @@
1
+ import type { AxonEngineRawEvent, AxonEngineRequest } from "./engine"
2
+ import type { AxonRunResult } from "./kernel/abi"
3
+ import type { AxonBlueprint } from "./blueprint"
4
+ import type { AxonEventMap } from "./session/session"
5
+ import type { AxonStimulusEntry } from "./session/events/stdio/stimuli"
6
+ import type { EscalationCall } from "./policy"
7
+
8
+ /**
9
+ * The supervisor ↔ agent wire.
10
+ *
11
+ * ── What the boundary is FOR ────────────────────────────────────────────────
12
+ *
13
+ * One confined process per agent: cognet, tools, scripts, routes and
14
+ * model-emitted code all in one heap, bounded by an OS box (bwrap mount/pid/
15
+ * net namespaces + cgroup limits). Everything in that box is agent-side code
16
+ * at one trust level — distinct AUTHORSHIP (a registry cognet, an agent
17
+ * author, the model) but identical AUTHORITY, all narrowed by the user's
18
+ * profile ceiling.
19
+ *
20
+ * The supervisor holds what must never enter that box. The rule that decides
21
+ * membership, and the only one worth remembering:
22
+ *
23
+ * An asset whose loss is UNRECOVERABLE and whose stolen form is PORTABLE
24
+ * must never enter the untrusted process. Vend a capability to use it.
25
+ *
26
+ * A stolen file is one machine's data. A stolen provider key is a live
27
+ * capability that works from anywhere, forever, until someone notices and
28
+ * rotates it. That asymmetry is why `infer` streams across this wire instead
29
+ * of the agent simply being handed a token: the agent can CAUSE inference, and
30
+ * can never obtain, transfer, or outlive the credential that performs it.
31
+ *
32
+ * The same reasoning keeps the session log outside — an attacker who can
33
+ * rewrite the audit trail has erased the evidence of everything else — and
34
+ * keeps `escalate` outside, because a program able to reach the decider could
35
+ * answer its own escalations.
36
+ *
37
+ * ── What is deliberately NOT here ───────────────────────────────────────────
38
+ *
39
+ * `store` and `knowledge` live INSIDE the box. They are the agent's own state;
40
+ * the supervisor gains nothing by mediating a kv the agent owns, and their
41
+ * stolen form is not portable. Keeping them in cuts four verbs.
42
+ *
43
+ * `run`, `scope` and the rest of KernelAbi are gone from the wire entirely.
44
+ * They are the cognet talking to its own kernel, and after the reshuffle both
45
+ * are in the same heap — putting them here would re-create, one layer out, the
46
+ * boundary this exists to remove.
47
+ *
48
+ * ── Direction ───────────────────────────────────────────────────────────────
49
+ *
50
+ * The dominant direction INVERTS versus the capsule wire. That one carried
51
+ * "run this code" host→guest, with a reverse channel bolted on. Here the guest
52
+ * drives: inference, telemetry and escalation all flow agent→supervisor, and
53
+ * that is the hot path.
54
+ */
55
+
56
+ // ── supervisor → agent ───────────────────────────────────────────────────────
57
+
58
+ /**
59
+ * Everything the outside can say to a running agent.
60
+ *
61
+ * Note there is NO `wake`. The outside emits a STIMULUS and the brain decides
62
+ * whether to wake for it — that is the scheduler's own admission policy
63
+ * (kernel/src/scheduler), which may legitimately drop a stimulus arriving
64
+ * mid-wake. A `wake()` verb on the wire would steamroll that decision from
65
+ * outside the mind it belongs to.
66
+ */
67
+ export type SupervisorToAgent = {
68
+ /**
69
+ * Deliver a stimulus. Resolves on ADMISSION, never on completion.
70
+ *
71
+ * A continuous cognet is ticked by its own plugin and wakes whether or not
72
+ * the last wake finished; resolving on completion here would serialise
73
+ * that overlap and turn a mind under a clock into a queue. Admission is
74
+ * the contract — see Scheduler's `reserve({ exclusive })`.
75
+ */
76
+ stimulus(entry: AxonStimulusEntry): Promise<{ admitted: boolean }>
77
+
78
+ /** Hot reload: a re-normalised blueprint replaces the live one. */
79
+ update(blueprint: AxonBlueprint): Promise<void>
80
+
81
+ /**
82
+ * Abort the active wake.
83
+ *
84
+ * Out-of-band on the CONTROL channel, which is the reason there are two
85
+ * channels at all: an interrupt must land WHILE inference is streaming,
86
+ * and on one line-buffered pipe it would queue behind exactly the traffic
87
+ * it exists to stop. The capsule papered over this by killing and
88
+ * rebuilding its subprocess (a hard reset racing a 50ms timeout); a
89
+ * separate channel removes the need.
90
+ */
91
+ interrupt(reason: "user" | "shutdown"): void
92
+
93
+ /** Drain and exit. The supervisor SIGKILLs if this does not settle in time. */
94
+ shutdown(): Promise<void>
95
+
96
+ /**
97
+ * Deliver a stimulus and wait for the wake it caused to SETTLE.
98
+ *
99
+ * The completion counterpart to `stimulus`, and the reason both exist.
100
+ * `stimulus` answers "did the brain admit this" and returns immediately,
101
+ * which is the only honest answer for a continuous cognet whose wakes
102
+ * overlap. But an interactive caller — someone typing at a terminal — needs
103
+ * to know when the reply is finished, and a UI that renders a spinner
104
+ * forever because nothing said "done" is broken in a way that admission
105
+ * cannot fix.
106
+ *
107
+ * Resolves on the wake's own bracket closing (`kernel:run:complete` /
108
+ * `:failed` / `:interrupted`), which the agent already commits — so this
109
+ * verb reads a signal that exists rather than inventing one.
110
+ *
111
+ * REFUSED for a continuous cognet: several wakes may be in flight, so
112
+ * "the wake this stimulus caused" names nothing. Such a caller wants
113
+ * `stimulus` and the commit stream.
114
+ */
115
+ request(entry: AxonStimulusEntry): Promise<{ ok: boolean; interrupted?: boolean }>
116
+
117
+ /**
118
+ * Execute code in the agent's scope — the console/devtools eval.
119
+ *
120
+ * The same conversation a model-emitted `<typescript>` block gets: same
121
+ * mediation, same policy, same span events. `origin: "host"` marks it as
122
+ * a human's request rather than the model's, so the timeline can tell them
123
+ * apart — a debugging eval that looked like cognition would corrupt the
124
+ * record of what the agent decided on its own.
125
+ *
126
+ * A VERB rather than a stimulus, because it is not something the brain
127
+ * decides about: nothing wakes, no wake admits it, and the caller wants
128
+ * the value back.
129
+ */
130
+ run(code: string): Promise<AxonRunResult>
131
+
132
+ /**
133
+ * The agent's prompt surface — list, fetch one, render an entry.
134
+ *
135
+ * One verb with a discriminated action rather than three, for the same
136
+ * reason `commit` is one verb: the supervisor's job is identical for each
137
+ * and three near-identical round trips would be three places to keep in
138
+ * step.
139
+ */
140
+ prompts(request: PromptRequest): Promise<unknown>
141
+ }
142
+
143
+ /** What a caller wants from the agent's prompt surface. */
144
+ export type PromptRequest =
145
+ | { action: "list" }
146
+ | { action: "get"; name: string }
147
+ | { action: "render"; entry: unknown }
148
+
149
+ // ── agent → supervisor ───────────────────────────────────────────────────────
150
+
151
+ /**
152
+ * One inference call, as it crosses the wire.
153
+ *
154
+ * The boundary lands on a seam that already existed: `AxonEngineDriver` is
155
+ * documented as "a dumb token pipe: messages in, raw deltas out — no AIR
156
+ * parsing, no bus, no blocks", while the Engine() MANAGER owns parsing,
157
+ * retries, telemetry and the stall guard. The driver stays supervisor-side
158
+ * because it holds the credential; the manager moves agent-side because it is
159
+ * cognition-adjacent.
160
+ *
161
+ * So what crosses is `AxonEngineRawEvent` — three variants of {type, content}.
162
+ * AIR never crosses. The supervisor never learns what the model sees, which is
163
+ * what the kernel already claimed and only now becomes structurally true.
164
+ */
165
+ export type InferCall = {
166
+ /** Which declared ROLE to infer with. The agent never names a model or a key. */
167
+ role: string
168
+ request: AxonEngineRequest
169
+ }
170
+
171
+ export type AgentToSupervisor = {
172
+ /**
173
+ * Stream inference for one call. THE hot path.
174
+ *
175
+ * Back-pressures naturally: the agent consumes this as an async generator,
176
+ * so a slow consumer fills the socket buffer and the supervisor stops
177
+ * draining the driver. That only holds if the transport respects it —
178
+ * which is why this is not a fire-and-forget write like `commit`.
179
+ *
180
+ * The idle-stall guard (`STREAM_IDLE_DEFAULT_MS`) stays with the MANAGER,
181
+ * agent-side: it is the consumer, and it is the thing that must not hang.
182
+ */
183
+ infer(call: InferCall, signal: AbortSignal): AsyncGenerator<AxonEngineRawEvent>
184
+
185
+ /**
186
+ * Append one event to the session log.
187
+ *
188
+ * ONE verb, not five. `output()`, `emit()`, `fault()`, `proc:*` and `fn:*`
189
+ * are separate paths today that all end at `session.commit`; the
190
+ * supervisor's job is identical for every one of them — append, then
191
+ * forward to the bus. Collapsing them keeps the wire honest about what is
192
+ * actually happening.
193
+ *
194
+ * FIRE-AND-FORGET but strictly ORDERED. It is the audit trail: two writers
195
+ * interleaving would corrupt the record of what happened, so a single
196
+ * writer per agent is an invariant of the transport, not an accident of it.
197
+ *
198
+ * The event NAMES are unchanged (`capsule:*` included) — Fleet folds the
199
+ * flame graph and the process tree straight out of this stream, so keeping
200
+ * the vocabulary keeps every existing surface working across the move.
201
+ */
202
+ commit<K extends keyof AxonEventMap>(type: K, data: AxonEventMap[K]): void
203
+
204
+ /**
205
+ * Ask a human about one call. Resolves with the verdict.
206
+ *
207
+ * Outside the box because a program that could reach the decider could
208
+ * raise and answer its own escalations. Fails CLOSED on timeout — and
209
+ * commits a record before it does: the mediator's remaining job after the
210
+ * OS wall takes over is escalation and audit, so an unrecorded timeout is
211
+ * a hole in its only function.
212
+ */
213
+ escalate(call: EscalationCall): Promise<{ allow: boolean }>
214
+ }
215
+
216
+ /**
217
+ * The transport contract.
218
+ *
219
+ * TWO channels, because `interrupt` must not queue behind `infer`. Framed
220
+ * datagrams (SOCK_SEQPACKET) rather than line-delimited JSON: each message is
221
+ * atomic, so there is no partial-line buffering and no length-prefix parsing,
222
+ * and the `undefined`→`null` replacer the JSONL wire needed has nothing to fix.
223
+ */
224
+ export type AgentTransport = {
225
+ /** Control: stimulus/update/interrupt/shutdown, escalate. Never blocked by inference. */
226
+ control: "control"
227
+ /** Data: the infer stream and the commit log. */
228
+ data: "data"
229
+ }