@arcforge/platform 2.0.166

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.
Files changed (207) hide show
  1. package/README.md +31 -0
  2. package/package.json +69 -0
  3. package/src/bin/supervisor.ts +102 -0
  4. package/src/bin/test-api.ts +30 -0
  5. package/src/bin/test-preload.ts +308 -0
  6. package/src/bin/update-helper.ts +32 -0
  7. package/src/build/bench/CLAUDE.md +106 -0
  8. package/src/build/bench/SPEC.md +209 -0
  9. package/src/build/bench/agents.ts +105 -0
  10. package/src/build/bench/axes.ts +84 -0
  11. package/src/build/bench/bench.ts +96 -0
  12. package/src/build/bench/discover.ts +147 -0
  13. package/src/build/bench/index.ts +7 -0
  14. package/src/build/bench/log.ts +47 -0
  15. package/src/build/bench/matrix.ts +23 -0
  16. package/src/build/bench/preload.ts +440 -0
  17. package/src/build/bench/prepare.ts +61 -0
  18. package/src/build/bench/projection.ts +112 -0
  19. package/src/build/bench/resolve.ts +54 -0
  20. package/src/build/bench/runner.ts +309 -0
  21. package/src/build/bench/schema/extract.ts +148 -0
  22. package/src/build/bench/schema/index.ts +2 -0
  23. package/src/build/bench/schema/schema.ts +95 -0
  24. package/src/build/bench/schema/worker.ts +30 -0
  25. package/src/build/bench/typegen.ts +119 -0
  26. package/src/build/bench/workspace/files.ts +139 -0
  27. package/src/build/bench/workspace/handle.ts +133 -0
  28. package/src/build/bench/workspace/index.ts +11 -0
  29. package/src/build/bench/workspace/workspace.ts +14 -0
  30. package/src/build/blueprint/blueprint.ts +398 -0
  31. package/src/build/blueprint/cognet/abi.ts +207 -0
  32. package/src/build/blueprint/cognet/bundle-worker.ts +93 -0
  33. package/src/build/blueprint/cognet/bundle.ts +664 -0
  34. package/src/build/blueprint/cognet/cognet.ts +249 -0
  35. package/src/build/blueprint/cognet/index.ts +10 -0
  36. package/src/build/blueprint/cognet/manifest.ts +38 -0
  37. package/src/build/blueprint/cognet/resolve.ts +113 -0
  38. package/src/build/blueprint/collisions.ts +51 -0
  39. package/src/build/blueprint/index.ts +29 -0
  40. package/src/build/blueprint/modules/entries.ts +117 -0
  41. package/src/build/blueprint/modules/index.ts +300 -0
  42. package/src/build/blueprint/modules/meta.ts +174 -0
  43. package/src/build/blueprint/scan/boot.ts +34 -0
  44. package/src/build/blueprint/scan/cognetImports.ts +56 -0
  45. package/src/build/blueprint/scan/components.ts +45 -0
  46. package/src/build/blueprint/scan/config.ts +234 -0
  47. package/src/build/blueprint/scan/configImports.ts +232 -0
  48. package/src/build/blueprint/scan/declare-worker.ts +61 -0
  49. package/src/build/blueprint/scan/declare.ts +393 -0
  50. package/src/build/blueprint/scan/h3-globals.ts +137 -0
  51. package/src/build/blueprint/scan/knowledge.ts +101 -0
  52. package/src/build/blueprint/scan/middleware.ts +110 -0
  53. package/src/build/blueprint/scan/moduleImports.ts +79 -0
  54. package/src/build/blueprint/scan/plugins.ts +93 -0
  55. package/src/build/blueprint/scan/promptPackages.ts +45 -0
  56. package/src/build/blueprint/scan/prompts.ts +164 -0
  57. package/src/build/blueprint/scan/published.ts +131 -0
  58. package/src/build/blueprint/scan/resolve.ts +398 -0
  59. package/src/build/blueprint/scan/routes.ts +109 -0
  60. package/src/build/blueprint/scan/scripts.ts +119 -0
  61. package/src/build/blueprint/scan/tool-bundle-worker.ts +69 -0
  62. package/src/build/blueprint/scan/tools.ts +610 -0
  63. package/src/build/blueprint/types.ts +28 -0
  64. package/src/build/extensions/config.ts +261 -0
  65. package/src/build/extensions/edit.ts +684 -0
  66. package/src/build/extensions/extensions.ts +731 -0
  67. package/src/build/extensions/index.ts +10 -0
  68. package/src/build/extensions/load.ts +350 -0
  69. package/src/build/extensions/registrations.ts +189 -0
  70. package/src/build/extensions/store.ts +200 -0
  71. package/src/build/frame/frame.ts +145 -0
  72. package/src/build/frame/index.ts +5 -0
  73. package/src/build/frame/migrate.ts +246 -0
  74. package/src/build/project/bundle/agent.ts +382 -0
  75. package/src/build/project/bundle/artifacts.ts +88 -0
  76. package/src/build/project/bundle/assets.ts +385 -0
  77. package/src/build/project/bundle/bundle.ts +160 -0
  78. package/src/build/project/bundle/imports.ts +102 -0
  79. package/src/build/project/bundle/index.ts +16 -0
  80. package/src/build/project/bundle/module.ts +130 -0
  81. package/src/build/project/bundle/source.ts +136 -0
  82. package/src/build/project/bundle/stage.ts +97 -0
  83. package/src/build/project/bundle/types.ts +111 -0
  84. package/src/build/project/cognet.ts +156 -0
  85. package/src/build/project/create/agent.ts +52 -0
  86. package/src/build/project/create/bench.ts +81 -0
  87. package/src/build/project/create/cognet.ts +102 -0
  88. package/src/build/project/create/extension.ts +63 -0
  89. package/src/build/project/create/module.ts +43 -0
  90. package/src/build/project/create/profile.ts +102 -0
  91. package/src/build/project/create/prompt.ts +68 -0
  92. package/src/build/project/create/templates.ts +88 -0
  93. package/src/build/project/deploy.ts +96 -0
  94. package/src/build/project/index.ts +40 -0
  95. package/src/build/project/installer.ts +616 -0
  96. package/src/build/project/kinds.ts +374 -0
  97. package/src/build/project/links.ts +33 -0
  98. package/src/build/project/manifest/bunfig.ts +139 -0
  99. package/src/build/project/manifest/config.ts +246 -0
  100. package/src/build/project/manifest/env.ts +184 -0
  101. package/src/build/project/manifest/index.ts +9 -0
  102. package/src/build/project/manifest/manifest.ts +49 -0
  103. package/src/build/project/manifest/model.ts +124 -0
  104. package/src/build/project/manifest/package.ts +386 -0
  105. package/src/build/project/manifest/text.ts +19 -0
  106. package/src/build/project/models/fetch.ts +123 -0
  107. package/src/build/project/models/index.ts +8 -0
  108. package/src/build/project/models/models.ts +111 -0
  109. package/src/build/project/models/specifier.ts +106 -0
  110. package/src/build/project/models/store.ts +202 -0
  111. package/src/build/project/modules/hash.ts +31 -0
  112. package/src/build/project/modules/index.ts +5 -0
  113. package/src/build/project/modules/lock.ts +78 -0
  114. package/src/build/project/modules/modules.ts +155 -0
  115. package/src/build/project/prepare.ts +709 -0
  116. package/src/build/project/project.ts +253 -0
  117. package/src/build/project/projects.ts +164 -0
  118. package/src/build/project/propagation.ts +120 -0
  119. package/src/build/project/publish/verify.ts +312 -0
  120. package/src/build/project/publish.ts +155 -0
  121. package/src/build/project/reconcile.ts +93 -0
  122. package/src/build/project/specifier.ts +42 -0
  123. package/src/build/project/tree.ts +615 -0
  124. package/src/build/project/treecache.ts +356 -0
  125. package/src/build/project/typegen/axon-dts.ts +362 -0
  126. package/src/build/project/typegen/cognet-dts.ts +91 -0
  127. package/src/build/project/typegen/components.ts +45 -0
  128. package/src/build/project/typegen/env.ts +59 -0
  129. package/src/build/project/typegen/generators.ts +108 -0
  130. package/src/build/project/typegen/hooks.ts +71 -0
  131. package/src/build/project/typegen/index.ts +137 -0
  132. package/src/build/project/typegen/prompt-dts.ts +40 -0
  133. package/src/build/project/typegen/prompts.ts +36 -0
  134. package/src/build/project/typegen/registry-dts.ts +109 -0
  135. package/src/build/project/typegen/scripts.ts +37 -0
  136. package/src/build/project/typegen/tools.ts +31 -0
  137. package/src/build/project/typegen/tsconfig.ts +243 -0
  138. package/src/build/project/typegen/tui-dts.ts +120 -0
  139. package/src/build/project/typegen/write.ts +40 -0
  140. package/src/build/project/verify.ts +268 -0
  141. package/src/build/project/watcher.ts +266 -0
  142. package/src/build/runtime/agent.ts +550 -0
  143. package/src/build/runtime/escalations.ts +159 -0
  144. package/src/build/runtime/index.ts +15 -0
  145. package/src/build/runtime/instances.ts +604 -0
  146. package/src/build/runtime/profile.ts +91 -0
  147. package/src/build/runtime/progress.ts +143 -0
  148. package/src/build/runtime/requests.ts +167 -0
  149. package/src/build/runtime/resolve.ts +159 -0
  150. package/src/build/runtime/runtime.ts +233 -0
  151. package/src/build/runtime/sessions/index.ts +5 -0
  152. package/src/build/runtime/sessions/record.ts +145 -0
  153. package/src/build/runtime/sessions/sessions.ts +240 -0
  154. package/src/build/runtime/zeno.ts +120 -0
  155. package/src/index.ts +11 -0
  156. package/src/link/agent-main.ts +395 -0
  157. package/src/link/index.ts +70 -0
  158. package/src/link/services.ts +120 -0
  159. package/src/platform.ts +293 -0
  160. package/src/procs/index.ts +15 -0
  161. package/src/procs/tree.ts +177 -0
  162. package/src/services/cloud.ts +419 -0
  163. package/src/services/control/client.ts +126 -0
  164. package/src/services/control/dispatch.ts +156 -0
  165. package/src/services/control/index.ts +17 -0
  166. package/src/services/control/protocol.ts +179 -0
  167. package/src/services/control/server.ts +241 -0
  168. package/src/services/deployments.ts +81 -0
  169. package/src/services/files.ts +329 -0
  170. package/src/services/index.ts +5 -0
  171. package/src/services/mic/capture.ts +248 -0
  172. package/src/services/mic/config.ts +109 -0
  173. package/src/services/mic/fft.ts +93 -0
  174. package/src/services/mic/index.ts +139 -0
  175. package/src/services/mic/visualizer.ts +46 -0
  176. package/src/services/ollama/catalog.ts +122 -0
  177. package/src/services/ollama/http.ts +124 -0
  178. package/src/services/ollama/index.ts +13 -0
  179. package/src/services/ollama/models.ts +153 -0
  180. package/src/services/ollama/ollama.ts +89 -0
  181. package/src/services/ollama/registry.ts +112 -0
  182. package/src/services/ollama/types.ts +72 -0
  183. package/src/services/prompts.ts +76 -0
  184. package/src/services/registry.ts +220 -0
  185. package/src/services/resources/hardware.ts +125 -0
  186. package/src/services/resources/index.ts +6 -0
  187. package/src/services/resources/reservations.ts +162 -0
  188. package/src/services/resources/resources.ts +156 -0
  189. package/src/services/running/index.ts +1 -0
  190. package/src/services/running/running.ts +200 -0
  191. package/src/services/store/disk.ts +97 -0
  192. package/src/services/store/index.ts +15 -0
  193. package/src/services/store/store.ts +729 -0
  194. package/src/services/store/types.ts +303 -0
  195. package/src/services/test/child.ts +150 -0
  196. package/src/services/test/events.ts +102 -0
  197. package/src/services/test/files.ts +26 -0
  198. package/src/services/test/frames.ts +39 -0
  199. package/src/services/test/index.ts +7 -0
  200. package/src/services/test/runner.ts +122 -0
  201. package/src/services/test/types.ts +26 -0
  202. package/src/services/update/contract.ts +77 -0
  203. package/src/services/update/index.ts +12 -0
  204. package/src/services/update/installer.ts +139 -0
  205. package/src/services/update/updates.ts +137 -0
  206. package/src/utils/fs.ts +148 -0
  207. package/src/utils/tsast.ts +102 -0
@@ -0,0 +1,120 @@
1
+ import { existsSync } from "node:fs"
2
+ import { rm } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import { err } from "@arcforge/err"
5
+ import type { StoreT } from "../../services/store"
6
+ import { detectKind, type ProjectsT, type ProjectT } from "../project"
7
+
8
+ /** The default agent's name, and the directory it occupies under the profile. */
9
+ export const ZENO = "zeno"
10
+
11
+ /** The published artifact zeno is cloned from. */
12
+ export const ZENO_REF = "@axon/zeno"
13
+
14
+ /** Registry modules zeno ships with — enough to be useful on first launch. */
15
+ const MODULES = ["@axon/fs", "@axon/subagent"]
16
+
17
+ type ZenoOpts = {
18
+ store: StoreT
19
+ projects: ProjectsT
20
+ /**
21
+ * Fetches a published artifact and prepares it in place.
22
+ *
23
+ * A thunk rather than the Registry handle: `registry` is constructed after
24
+ * `Runtime` in platform.ts and is defined in terms of `projects`, so taking
25
+ * a value here would force a reorder. Same idiom as the bench axis.
26
+ */
27
+ clone: (ref: string, cwd: string, options?: { dir?: string }) => Promise<{ root: string }>
28
+ }
29
+
30
+ /**
31
+ * Zeno — the agent that is always there.
32
+ *
33
+ * A first-run user has no agents, and an agent is now the only thing that can
34
+ * be run: models are a property of an agent, not a thing you run instead of
35
+ * one. Something has to exist for the very first message to go to, so the
36
+ * platform guarantees exactly one agent — zeno — and nothing else about it.
37
+ *
38
+ * Zeno is an ORDINARY agent project, CLONED FROM THE REGISTRY (`@axon/zeno`)
39
+ * into the profile's own agents directory, then owned by the user: editable,
40
+ * renameable in content, and never written to again. That is the whole
41
+ * difference from the managed base workspace this replaced — base regenerated
42
+ * its config from a template on every model pick, which forced an ownership
43
+ * hash to detect the user's edits and refuse them. Nothing here writes a config
44
+ * after creation, so there is nothing to guard.
45
+ *
46
+ * From the REGISTRY rather than the local scaffold template, deliberately: zeno
47
+ * is the first thing a new user meets and the de facto face of the product, so
48
+ * improving it must not require shipping a CLI release. Publishing a new
49
+ * `@axon/zeno` reaches every install on its next first-run. A local template
50
+ * would freeze the mascot at whatever version each user happened to install.
51
+ *
52
+ * "Cannot be deleted" is therefore not enforcement — delete the directory and
53
+ * `ensure()` simply scaffolds it again on the next boot. It is a guarantee that
54
+ * the TUI always has somewhere to send a message, not a lock on the file.
55
+ */
56
+ export function Zeno(opts: ZenoOpts) {
57
+ function root(): string {
58
+ const profile = opts.store.profiles.active()
59
+ if (!profile) throw err("NOT_AUTHENTICATED")
60
+ return join(profile.agents.root, ZENO)
61
+ }
62
+
63
+ return {
64
+ get name(): string {
65
+ return ZENO
66
+ },
67
+
68
+ /**
69
+ * True once zeno is USABLE for the active profile — the directory
70
+ * alone is not enough. A zeno whose axon.config.ts was deleted or
71
+ * mangled is a directory that exists and a project that cannot open,
72
+ * which is precisely the state ensure() has to repair. Detecting the
73
+ * config is the same check projects.open() makes, so `exists` and
74
+ * "can be opened" can never disagree.
75
+ */
76
+ get exists(): boolean {
77
+ return detectKind(root()) === "agent"
78
+ },
79
+
80
+ /**
81
+ * The default agent, scaffolded if it is not there — and re-cloned if
82
+ * what IS there is broken. Idempotent: a healthy zeno is opened
83
+ * untouched, never re-templated.
84
+ *
85
+ * Self-repairing by design. Zeno is the one agent the platform
86
+ * guarantees, so "the user deleted or mangled it" cannot be a dead end:
87
+ * a directory that fails to open is replaced rather than reported. That
88
+ * is the whole point of the guarantee — the TUI must always have
89
+ * somewhere to send a message.
90
+ */
91
+ async ensure(): Promise<ProjectT> {
92
+ const profile = opts.store.profiles.active()
93
+ if (!profile) throw err("NOT_AUTHENTICATED")
94
+
95
+ const target = join(profile.agents.root, ZENO)
96
+ // Not existsSync(target): a directory with no (or a broken) config
97
+ // is unopenable, and returning it here just moves the failure to
98
+ // the caller. Re-clone over it instead.
99
+ if (detectKind(target) === "agent") return opts.projects.open(target)
100
+ if (existsSync(target)) await rm(target, { recursive: true, force: true })
101
+
102
+ // clone() downloads, extracts and prepares — so the agent surface
103
+ // (node_modules, compiled brain, typegen) is materialized before
104
+ // this returns. `dir` pins the directory name to ZENO rather than
105
+ // letting it derive from the scoped artifact name.
106
+ await opts.clone(ZENO_REF, profile.agents.root, { dir: ZENO })
107
+ const project = await opts.projects.open(target)
108
+
109
+ // Through the installer rather than a config edit: these have to be
110
+ // present in node_modules for zeno's first boot, not merely named in
111
+ // the config. clone() already prepared the project, so this is the
112
+ // one install that follows.
113
+ await project.modules.install(MODULES)
114
+
115
+ return project
116
+ },
117
+ }
118
+ }
119
+
120
+ export type ZenoT = ReturnType<typeof Zeno>
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ export { Platform, type PlatformT } from "./platform"
2
+ export type { ProjectKind, ProjectT } from "./build/project"
3
+ // The `@` palette renders these rows, so the shape is part of the platform's
4
+ // public surface rather than an internal of the walk that produces it.
5
+ export type { FileEntry, FilesT } from "./services/files"
6
+ // The process tree every surface renders — folded from the session log, so a
7
+ // local runtime and an attached deployment read identically.
8
+ export { procTree, appendOutput, type ProcNode } from "./procs"
9
+ // The supervisor ↔ agent transport. Moves bytes; the verbs it carries are
10
+ // SupervisorToAgent / AgentToSupervisor in @arcforge/types.
11
+ export { serve, connect, Channel, type LinkChannels, type SocketPaths, type ChannelT } from "./link"
@@ -0,0 +1,395 @@
1
+ #!/usr/bin/env bun
2
+ import { err } from "@arcforge/err"
3
+ /**
4
+ * The confined agent process — what the box execs.
5
+ *
6
+ * Replaces the capsule's `process/main.ts` as the program inside the wall. The
7
+ * difference is what it contains: the capsule held only model-emitted code and
8
+ * tools, with the cognet and the kernel outside it. This holds the WHOLE agent
9
+ * — cognet, kernel, tools, scripts, routes, and model-emitted code — one heap,
10
+ * one context, bounded by one OS box.
11
+ *
12
+ * What stays outside is what must never enter: the provider credential, the
13
+ * session log, and the escalation decider. The agent asks for those over the
14
+ * link and can never obtain, transfer, or outlive them.
15
+ *
16
+ * Boot order matters:
17
+ * 1. read the link paths (a missing carrier means nobody supervises us)
18
+ * 2. dial both channels BEFORE booting — the runtime commits during boot,
19
+ * and a commit with no link would be a lost audit record
20
+ * 3. boot Axon() with `remote` set, which is what puts tools in this heap
21
+ * and inference on the wire
22
+ * 4. serve the four verbs until told to stop
23
+ */
24
+ import { readFileSync } from "node:fs"
25
+ import { Axon, AxonBus } from "@arcforge/core"
26
+ import { Routes, Middleware, Plugins } from "../build/blueprint"
27
+ import type { AxonMiddleware, AxonPartialBlueprint, AxonPlugin, AxonRoute } from "@arcforge/types"
28
+ import {
29
+ AGENT_BLUEPRINT_ENV,
30
+ AgentRuntime,
31
+ RemoteDriver,
32
+ agentHandlers,
33
+ connect,
34
+ readLinkEnv,
35
+ supervisorProxy,
36
+ } from "@arcforge/link"
37
+
38
+ /** Boot-stage tracing, for diagnosing an agent that comes up but never reports. */
39
+ const trace = (stage: string) => {
40
+ if (process.env.AXON_TRACE_BOOT) process.stderr.write(`[boot] ${stage}\n`)
41
+ }
42
+
43
+ export async function main(): Promise<void> {
44
+ trace("start")
45
+ const paths = readLinkEnv()
46
+
47
+ const blueprintPath = process.env[AGENT_BLUEPRINT_ENV]
48
+ if (!blueprintPath) {
49
+ throw err("AGENT_BLUEPRINT_MISSING", { detail: `${AGENT_BLUEPRINT_ENV} is not set`, context: { env: AGENT_BLUEPRINT_ENV } })
50
+ }
51
+ const blueprint = JSON.parse(readFileSync(blueprintPath, "utf-8")) as AxonPartialBlueprint
52
+
53
+ // The one thing JSON could not carry.
54
+ await rehydrateServer(blueprint)
55
+
56
+ // Deferred: the handlers need the runtime, and the runtime needs the link
57
+ // to commit through. Neither can be built first, so the handlers close
58
+ // over a slot that is filled once the runtime exists.
59
+ /**
60
+ * Verbs arriving before the runtime exists WAIT rather than fail.
61
+ *
62
+ * The link connects before Axon() runs — deliberately, so a boot failure
63
+ * is reportable — which leaves a window where the agent is addressable but
64
+ * not yet able to answer. A caller that sent during that window got
65
+ * AGENT_NOT_READY, and because the throw happened inside the channel's
66
+ * dispatch it took the whole process down: the TUI sent a message, the
67
+ * agent refused and died, and neither the message nor a reply ever
68
+ * appeared.
69
+ *
70
+ * Waiting is the honest behaviour. A stimulus sent to a booting agent is
71
+ * not an error — it is early, and boot is measured in seconds. The wait
72
+ * ends when the runtime is ready, or rejects with the real reason if boot
73
+ * fails.
74
+ */
75
+ let serving: ReturnType<typeof AgentRuntime> | null = null
76
+ /** An interrupt that arrived before the runtime existed — replayed at ready. */
77
+ let pendingInterrupt: "user" | "shutdown" | null = null
78
+ let markReady!: () => void
79
+ let markFailed!: (error: Error) => void
80
+ const ready = new Promise<void>((resolve, reject) => {
81
+ markReady = resolve
82
+ markFailed = reject
83
+ })
84
+
85
+ const handlers = agentHandlers({
86
+ stimulus: entry => serve().then(s => s.stimulus(entry)),
87
+ update: bp => serve().then(s => s.update(bp)),
88
+ /**
89
+ * Interrupt is sync and fire-and-forget — but it must not be LOST.
90
+ *
91
+ * `serving?.interrupt()` silently dropped an interrupt that arrived
92
+ * while the runtime was still booting. That window is exactly when a
93
+ * user is most likely to press Escape: a slow boot looks like a hung
94
+ * agent, and the one thing they can do is cancel.
95
+ *
96
+ * Recorded and replayed instead. Sync by contract, so it cannot await
97
+ * the runtime — the flag is what carries the intent across the gap.
98
+ */
99
+ interrupt: reason => {
100
+ if (!serving) {
101
+ pendingInterrupt = reason
102
+ return
103
+ }
104
+ serving.interrupt(reason)
105
+ },
106
+ /**
107
+ * Drain, answer, then LEAVE.
108
+ *
109
+ * The exit is deliberate rather than left to the event loop draining
110
+ * on its own. An agent holds a cognet, a capsule, sockets and
111
+ * whatever a module's setup() opened; any one of those keeping a
112
+ * handle alive turned "shutdown" into "linger until the supervisor
113
+ * gives up and kills it" — five seconds of dead time on every
114
+ * `axon -s`, with all the work already finished.
115
+ *
116
+ * Deferred one turn so the reply reaches the supervisor first: exiting
117
+ * inside the handler drops the response, and the caller then waits out
118
+ * its own timeout for an answer that will never arrive.
119
+ */
120
+ shutdown: () => serve().then(async s => {
121
+ await s.shutdown()
122
+ setTimeout(() => process.exit(0), 0).unref?.()
123
+ }),
124
+ request: entry => serve().then(s => s.request(entry)),
125
+ run: code => serve().then(s => s.run(code)),
126
+ prompts: request => serve().then(s => s.prompts(request)),
127
+ // `serve()` here is the READINESS gate (wait for the runtime), not
128
+ // the HTTP verb — the agent binds its port only once its routes
129
+ // exist, which is exactly what that gate guarantees.
130
+ serve: port => serve().then(s => s.serve(port)),
131
+ })
132
+ async function serve() {
133
+ if (!serving) await ready
134
+ // Unreachable unless `ready` resolved without the runtime being set,
135
+ // which would be a wiring fault rather than a timing one.
136
+ if (!serving) throw err("AGENT_NOT_READY", { detail: "the runtime never became available" })
137
+ return serving
138
+ }
139
+
140
+ const channels = await connect({
141
+ paths,
142
+ ...handlers,
143
+ onError: error => process.stderr.write(`agent link error: ${error.message}\n`),
144
+ })
145
+
146
+ trace("connected")
147
+ const supervisor = supervisorProxy(channels)
148
+
149
+ /**
150
+ * Boot the runtime, REPORTING any failure through the link before dying.
151
+ *
152
+ * The link is deliberately connected first, so that a boot failure is
153
+ * reportable at all — but that only helps if something actually reports
154
+ * it. Without this the sequence was: link connects, Axon() throws, the
155
+ * process exits, the socket closes, and the supervisor says
156
+ * LINK_PEER_CLOSED. The agent knew exactly what was wrong (a missing
157
+ * cognet, a tool that would not compile) and took the diagnosis with it.
158
+ *
159
+ * Committed rather than written to stderr, because the supervisor owns
160
+ * this agent's log and a boot failure belongs in the record beside every
161
+ * other thing that happened to it.
162
+ */
163
+ /**
164
+ * Forward every event to the supervisor, which owns the log.
165
+ *
166
+ * Buffered until the runtime exists, because the bus this subscribes to is
167
+ * BUILT BY Axon() — and everything it announces during boot
168
+ * (axon:boot:start, the agent's identity, its blueprint) is emitted before
169
+ * that call returns. Subscribing afterwards silently dropped all of it,
170
+ * which is why the TUI's header came up blank: the facts it renders had
171
+ * already gone past.
172
+ */
173
+ const pending: Array<{ type: string; data: unknown }> = []
174
+ let forward = (type: string, data: unknown) => { pending.push({ type, data }) }
175
+
176
+ /**
177
+ * The bus, built HERE and handed to Axon() — so this can subscribe
178
+ * BEFORE boot rather than after it.
179
+ *
180
+ * Everything boot announces (axon:boot:start, the kernel coming up,
181
+ * each module's setup, every tool load) fires during the `Axon()` call.
182
+ * Subscribing to `runtime.bus` afterwards is subscribing to a stream
183
+ * whose first act is already over. Those events went into the record
184
+ * anyway while the agent wrote its own log; once the supervisor became
185
+ * the only writer, they had nowhere to go and silently disappeared.
186
+ */
187
+ const bus = AxonBus()
188
+ bus.onAny((type: string, payload: unknown) => announce(type, payload))
189
+
190
+ let runtime: Awaited<ReturnType<typeof Axon>>
191
+ try {
192
+ runtime = await Axon({
193
+ blueprint,
194
+ bus,
195
+ // The two facts that make this runtime confined:
196
+ // remote — inference crosses the link, so no credential is here
197
+ // (tools then load in this heap, see Axon())
198
+ remote: role => RemoteDriver({ role, supervisor }),
199
+ })
200
+ } catch (cause) {
201
+ const failure = err(cause)
202
+ supervisor.commit("axon:boot:failed" as never, {
203
+ error: failure.toJSON(),
204
+ durationMs: 0,
205
+ } as never)
206
+ // Give the commit a turn to reach the wire before the process ends —
207
+ // it is fire-and-forget, and an exit here would drop it.
208
+ await new Promise(resolve => setTimeout(resolve, 100))
209
+ // Anything waiting on the runtime gets the real reason, not a timeout.
210
+ markFailed(failure)
211
+ throw failure
212
+ }
213
+
214
+ trace("axon-booted")
215
+ // No cast: RuntimeForAgent names exactly what the link needs from the
216
+ // runtime — the kernel verbs, the prompt surface, and the server whose
217
+ // handler `serve` binds. An `as never` here used to hide a missing
218
+ // member until it failed at call time.
219
+ serving = AgentRuntime(runtime)
220
+ markReady()
221
+
222
+ // An Escape pressed during boot applies to the wake that boot was for.
223
+ if (pendingInterrupt) {
224
+ serving.interrupt(pendingInterrupt)
225
+ pendingInterrupt = null
226
+ }
227
+
228
+ // Every event this runtime records goes to the supervisor, which owns the
229
+ // log. The agent may APPEND to the record and can never rewrite it — an
230
+ // attacker able to edit the audit trail has erased the evidence of
231
+ // everything else.
232
+ /**
233
+ * The bus carries the WHOLE ENVELOPE, not the bare payload: `session.commit`
234
+ * announces through `bus.forward(event)`, which emits `{ type, time, data }`
235
+ * under the event's own name. Forwarding that straight into
236
+ * `commit(type, data)` re-wraps it — the supervisor stores `data.data.meta`
237
+ * and every reader looking for `data.meta` finds undefined.
238
+ *
239
+ * Unwrapped HERE rather than on the far side, because this is where the
240
+ * shape is known: the supervisor receives (type, data) and cannot tell an
241
+ * envelope from a payload that happens to have a `data` field of its own.
242
+ */
243
+ function announce(type: string, payload: unknown): void {
244
+ /**
245
+ * Two shapes travel this bus, and the difference is not cosmetic.
246
+ *
247
+ * Everything committed goes through `session.commit`/`commitEntry`,
248
+ * which announce via `bus.forward(event)` — a full ENVELOPE,
249
+ * `{ type, time, context, data }`. But the kernel forwards TRANSIENT
250
+ * capsule events raw (`kernel/src/capsule.ts`: `bus.forward(event)`
251
+ * where event is `{ type, ...fields }`), so those arrive with their
252
+ * fields at the top level and no `data` at all.
253
+ *
254
+ * Reading `envelope.data` off both was the bug behind the markdown
255
+ * crash: a raw event has no `data`, so the whole object — `type`
256
+ * included — was committed AS the payload, and a reader doing
257
+ * `data.content` got an object where the contract promised a string.
258
+ *
259
+ * Discriminated on `time`, which the envelope stamps and a raw event
260
+ * never carries. Explicit rather than a "has data" sniff, because a
261
+ * payload with its own `data` field is a shape nobody should have to
262
+ * reason about at this seam.
263
+ */
264
+ const carrier = payload as { time?: unknown; data?: unknown; type?: unknown } | undefined
265
+ if (carrier && typeof carrier === "object" && "time" in carrier) {
266
+ forward(type, carrier.data)
267
+ return
268
+ }
269
+ // A raw event: strip the name it already travels under, keep the rest.
270
+ if (carrier && typeof carrier === "object" && "type" in carrier) {
271
+ const { type: _name, ...fields } = carrier as Record<string, unknown>
272
+ forward(type, fields)
273
+ return
274
+ }
275
+ forward(type, payload)
276
+ }
277
+
278
+ // Live from here — and everything boot produced goes first, in order.
279
+ forward = (type, data) => { supervisor.commit(type as never, data as never) }
280
+ for (const event of pending.splice(0)) forward(event.type, event.data)
281
+
282
+ /**
283
+ * The agent's last words.
284
+ *
285
+ * Without this an unhandled throw kills the process and the supervisor
286
+ * sees only a socket close — the actual error dies with the process it
287
+ * happened in. Same reasoning as the capsule's own crash handler, and the
288
+ * same deliberate immediate exit: an unhandled error means state is
289
+ * unknown, and an agent that keeps serving after that is worse than one
290
+ * that dies loudly.
291
+ */
292
+ for (const event of ["uncaughtException", "unhandledRejection"] as const) {
293
+ process.on(event, (cause: unknown) => {
294
+ supervisor.commit("axon:log:error" as never, {
295
+ message: cause instanceof Error ? cause.message : String(cause),
296
+ } as never)
297
+ process.exit(1)
298
+ })
299
+ }
300
+
301
+ /**
302
+ * An agent with no supervisor has nobody to serve — so it exits.
303
+ *
304
+ * The `exit` handler on the supervisor side covers a clean shutdown and an
305
+ * unhandled throw, but not SIGKILL: kill -9 the TUI and nothing runs. The
306
+ * agent notices the same event from its own side — both channels closing —
307
+ * and stops itself.
308
+ *
309
+ * This is what keeps a crashed supervisor from leaving an agent holding a
310
+ * cognet, a capsule and two sockets indefinitely. Deliberately not a
311
+ * timeout: a closed socket is a fact, and waiting on one is not.
312
+ */
313
+ const watchdog = setInterval(() => {
314
+ if (channels.control.isClosed && channels.data.isClosed) {
315
+ trace("orphaned")
316
+ process.exit(0)
317
+ }
318
+ }, 1_000)
319
+ // Never hold the process open on our own account.
320
+ watchdog.unref?.()
321
+
322
+ // Readiness is the SOCKET connecting, which the supervisor already races
323
+ // against process exit — nothing ever read this line. It stayed harmless
324
+ // only while the agent's stdout went to an unread pipe; now that stdout
325
+ // is the agent's own output forwarded to the user's terminal, a boot
326
+ // marker printed there is noise on every single run.
327
+ trace("ready")
328
+ }
329
+
330
+ /**
331
+ * Rebuild the authored server surface, agent-side.
332
+ *
333
+ * The blueprint reaches this process as JSON, and routes, middleware and
334
+ * plugins are the three things on it that are FUNCTIONS. `JSON.stringify`
335
+ * drops a function silently, so each entry arrived carrying its metadata and
336
+ * nothing to call: `mountRoute` registered a route whose handler was
337
+ * `undefined`, h3 accepted it, and every request to an authored path 404'd
338
+ * with no warning at either end.
339
+ *
340
+ * Middleware was the dangerous half. Its own type doc calls a dropped
341
+ * middleware "a request path running without the checks its author wrote — a
342
+ * security hole that looks like a working server", and that is exactly what
343
+ * shipped: an agent whose auth middleware silently did not run.
344
+ *
345
+ * SCANNED here rather than re-resolved from a file path on each entry.
346
+ * Routes carry `file` and could have been recovered that way, but middleware
347
+ * and plugins carry none — and the deeper reason is the same one that put the
348
+ * agent in its own cwd: the agent owns what it is, rather than depending on
349
+ * what the caller managed to marshal across. The supervisor's copy of these
350
+ * lists is now advisory; this is the one that runs.
351
+ *
352
+ * Order is preserved exactly as the supervisor assembles it (see
353
+ * blueprint.ts): the agent's own entries first, then each module's in
354
+ * declaration order. Routes mount first-wins, and the agent's middleware
355
+ * gates before any module's — a module must not be able to slip a handler
356
+ * ahead of an auth check the author wrote.
357
+ */
358
+ async function rehydrateServer(blueprint: AxonPartialBlueprint): Promise<void> {
359
+ const root = blueprint.paths?.root
360
+ if (!root) return
361
+
362
+ const roots: Array<{ root: string; required: boolean }> = [
363
+ // The agent's own source is required: an agent running a subset of
364
+ // what its author wrote is an agent nobody asked for.
365
+ { root, required: true },
366
+ // A module's is not. An agent that installed a broken module is the
367
+ // agent it was before the install, and crashing here would leave the
368
+ // user unable to boot the terminal they need to remove it.
369
+ ...(blueprint.modules ?? []).map(module => ({ root: module.root, required: false })),
370
+ ]
371
+
372
+ const routes: AxonRoute[] = []
373
+ const middleware: AxonMiddleware[] = []
374
+ const plugins: AxonPlugin[] = []
375
+
376
+ for (const source of roots) {
377
+ const opts = { required: source.required }
378
+ const [scannedRoutes, scannedMiddleware, scannedPlugins] = await Promise.all([
379
+ Routes(source.root, opts),
380
+ Middleware(source.root, opts),
381
+ Plugins(source.root, opts),
382
+ ])
383
+ routes.push(...scannedRoutes.entries)
384
+ middleware.push(...scannedMiddleware.entries)
385
+ plugins.push(...scannedPlugins.entries)
386
+ }
387
+
388
+ blueprint.server = { routes, middleware, plugins }
389
+ }
390
+
391
+ // Run only when executed directly, never on import — the tests import `main`
392
+ // and the module must not boot an agent as a side effect of being read.
393
+ if (import.meta.main) {
394
+ await main()
395
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The supervisor ↔ agent transport, re-exported from `@arcforge/link`.
3
+ *
4
+ * The transport moved out when the daemon needed it: a daemon depending on the
5
+ * whole platform to move bytes down a socket would invert the dependency the
6
+ * daemon exists to establish. See that package for the layering.
7
+ *
8
+ * This shim stays because the platform genuinely still uses it — `agent-main`
9
+ * and `services` run INSIDE the box and are built here, and every consumer
10
+ * inside the platform imports through this path. Re-exporting is what let the
11
+ * move land without touching any of them.
12
+ */
13
+ export {
14
+ Channel,
15
+ type ChannelT,
16
+ type ChannelHandlers,
17
+ type ChannelSocket,
18
+ FrameReader,
19
+ encodeFrame,
20
+ encodeMessage,
21
+ decodeMessage,
22
+ MAX_FRAME_BYTES,
23
+ serve,
24
+ connect,
25
+ type LinkChannels,
26
+ type SocketPaths,
27
+ SupervisorLink,
28
+ supervisorHandlers,
29
+ agentServices,
30
+ VERB,
31
+ type SupervisorServices,
32
+ agentHandlers,
33
+ supervisorProxy,
34
+ RemoteDriver,
35
+ type AgentServices,
36
+ AgentRuntime,
37
+ type RuntimeForAgent,
38
+ readLinkEnv,
39
+ writeLinkEnv,
40
+ AGENT_LINK_ENV,
41
+ AGENT_BLUEPRINT_ENV,
42
+ type AgentEntryEnv,
43
+ prepare,
44
+ socketRoot,
45
+ socketPaths,
46
+ type SpawnedAgent,
47
+ spawnConfined,
48
+ agentEntrypoint,
49
+ agentEntrypoints,
50
+ type ConfinedAgent,
51
+ } from "@arcforge/link"
52
+ import { agentEntrypoints } from "@arcforge/link"
53
+
54
+ /**
55
+ * The supervisor-side services an agent's box is wired with, and the entry the
56
+ * box execs. Platform-owned: both reach the cloud, the session log and the
57
+ * blueprint scanners, which is precisely what does not belong in the wire.
58
+ */
59
+ export { SupervisorSideServices } from "./services"
60
+
61
+ /**
62
+ * Where the agent entrypoint lives — resolved against THIS package.
63
+ *
64
+ * `agent-main.ts` runs inside the box and reaches the cloud, the session log
65
+ * and the blueprint scanners, so it stayed here when the wire moved to
66
+ * `@arcforge/link`. The candidate list is therefore the platform's to state:
67
+ * the transport composes the box, but only its owner knows where the program
68
+ * it execs is written.
69
+ */
70
+ export const AGENT_ENTRYPOINTS = agentEntrypoints(import.meta.dir)