@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,550 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { join, resolve } from "node:path"
3
+ import { Axon } from "@arcforge/core"
4
+ import type { AxonHost, AxonT } from "@arcforge/core"
5
+ import type { AxonEscalate } from "@arcforge/types"
6
+ import type { AxonBlueprint, AxonPartialBlueprint, SupervisorToAgent } from "@arcforge/types"
7
+ import type { AxonSessionT } from "@arcforge/session"
8
+ import { err } from "@arcforge/err"
9
+ import type { AxonCloudClient } from "@arcforge/cloud"
10
+ import { BuildRecorder, span } from "@arcforge/session"
11
+ import { Blueprint } from "../blueprint"
12
+ import { readPolicy, ProfileConfigFile } from "../extensions"
13
+ import { advances, stageFor, unitFor } from "./progress"
14
+ import type { BootProgress, BootStage, UnitTiming } from "./progress"
15
+ import { Frame } from "../frame"
16
+ import { Watcher } from "../project/watcher"
17
+ import type { ProjectT } from "../project"
18
+ import type { StoreT } from "../../services/store"
19
+
20
+ type AgentOpts = {
21
+ project: ProjectT
22
+ /** Platform invocation directory inherited by every capsule incarnation. */
23
+ cwd: string
24
+ /** The platform's authenticated cloud client — the agent runs AS the logged-in user. */
25
+ cloud: AxonCloudClient
26
+ /** Registers this process in ~/.axon/running for the duration of the instance — see Store().running. */
27
+ store: StoreT
28
+ /** Resume an existing session instead of minting a new one — the id of a sessions/<id>.jsonl on disk. */
29
+ session?: string
30
+ /** Platform-owned services exposed to this instance's capsule. */
31
+ host?: AxonHost
32
+ /**
33
+ * The platform's policy decider, bound to THIS agent.
34
+ *
35
+ * Bound rather than generic because a grant is written against an agent
36
+ * name, and the decider has no way to know which agent raised a call — the
37
+ * capsule only reports the fn and its arguments. Runtime() closes over the
38
+ * name when it builds this.
39
+ */
40
+ escalate?: AxonEscalate
41
+ parentSessionId?: string | null
42
+ rootSessionId?: string
43
+ depth?: number
44
+ /** Job directory this run answers, for correlation — see RunningRecord.job. */
45
+ job?: string
46
+ /**
47
+ * A local control channel this instance is listening on, published on
48
+ * the running record so an editor can find and dial it.
49
+ *
50
+ * Supplied by the surface that HAS one — the TUI serves a conversation
51
+ * something can drive; a headless `axon run` does not, and passes
52
+ * nothing. Threaded through here rather than written separately
53
+ * because the record is created once, at the moment the runtime comes
54
+ * up, and a second writer racing this one is how a reader ends up
55
+ * seeing a port whose process is not ready.
56
+ */
57
+ control?: { port: number; token: string }
58
+ /**
59
+ * Watch the project (and its cognet source) for changes and hot-reload.
60
+ * Default true — a TUI or `axon dev` instance is edited while it runs.
61
+ *
62
+ * A script that boots several agents and exits gets nothing from this
63
+ * and pays two watchers per instance for it, so Axon()/Fleet() pass
64
+ * false. Only the watching is skipped: the same blueprint is loaded,
65
+ * the same runtime boots, and reload() still works when called
66
+ * directly.
67
+ */
68
+ /**
69
+ * Boot this agent as a CONFINED PROCESS instead of an in-heap runtime.
70
+ *
71
+ * Supplied by the caller that owns the supervisor (Instances), because
72
+ * spawning a box needs sockets and a policy this layer has no business
73
+ * resolving.
74
+ *
75
+ * REQUIRED. An agent is always its own process — there is no in-heap
76
+ * variant to fall back to. The path that used to exist when this was
77
+ * absent booted agent code, its tools and every model-emitted block
78
+ * inside the CALLER's heap, where no OS box surrounds it and policy
79
+ * cannot be enforced against the process doing the enforcing. That is a
80
+ * hole in the user policy contract, not an optimisation, so the option
81
+ * to open it is gone rather than defaulted.
82
+ *
83
+ * Sits BELOW the whole build: the scan, the compile, the blueprint and
84
+ * the session all run before it.
85
+ */
86
+ confined: (input: {
87
+ blueprint: AxonPartialBlueprint
88
+ sessionId: string
89
+ /** Rescan the project and return the blueprint that produced — what a reload sends. */
90
+ rescan: () => Promise<AxonPartialBlueprint>
91
+ }) => Promise<LinkedRuntime>
92
+
93
+ watch?: boolean
94
+ /**
95
+ * Live boot progress, for a surface that shows one.
96
+ *
97
+ * A cold boot is seconds long — mostly `bun install` — and reported as a
98
+ * single word it looks hung. This fires as each stage begins so the caller
99
+ * can say which. Purely observational: it cannot fail the boot, and a
100
+ * caller that passes nothing (every headless one) is unaffected.
101
+ *
102
+ * Separate from the session log rather than read back off it: the log is
103
+ * the durable record, written through an async chain, and a status bar
104
+ * needs the event as it happens, not after it lands on disk.
105
+ */
106
+ onProgress?: (progress: BootProgress) => void
107
+ /**
108
+ * What each timed unit of the build cost, as its span closes.
109
+ *
110
+ * The spans already measure this for the log; this only forwards it so a
111
+ * surface can report the cost without timing anything itself. Same
112
+ * observational contract as onProgress — it cannot fail the boot.
113
+ */
114
+ onTiming?: (timing: UnitTiming) => void
115
+ }
116
+
117
+ /**
118
+ * Agent — the running instance of one project's blueprint. Boots once,
119
+ * then reacts to the project's file watcher by rescanning and pushing the
120
+ * fresh AxonPartialBlueprint through the live runtime's update() — the
121
+ * kernel fans it out to its own organs (engine, loop, capsule). No reboot:
122
+ * update() is core's contract for exactly this.
123
+ *
124
+ * Watching is the project's concern (Watcher knows only "a file changed"),
125
+ * turning that into "reload the agent" is this module's job.
126
+ *
127
+ * Every caller that boots an instance (Agents(), `axon dev`) converges
128
+ * here, so the running-registry write lives at this one seam rather than
129
+ * being each caller's responsibility to remember.
130
+ */
131
+ export async function Agent(opts: AgentOpts) {
132
+ const { project } = opts
133
+ const blueprint = Blueprint({ root: project.root })
134
+
135
+ /**
136
+ * The active profile's policy ceiling, re-read on every load.
137
+ *
138
+ * Resolved HERE rather than inside Blueprint(), which knows a root
139
+ * directory and nothing about profiles, auth or deployment. This module
140
+ * already holds the store, so it is the nearest place that legitimately
141
+ * knows which user is running.
142
+ *
143
+ * Re-read per load rather than captured once, so a reload picks up an
144
+ * edited ceiling. That is the honest boundary of "takes effect on save":
145
+ * the capsule's policy is fixed at construction, so a tightened profile
146
+ * applies from the next boot or reload — not retroactively to a call
147
+ * already in flight.
148
+ *
149
+ * Never throws. An unreadable or absent profile means no ceiling, which is
150
+ * the correct state for `axon run` outside one and for a deployment. A
151
+ * ceiling that failed CLOSED here would make a broken config unbootable;
152
+ * one that fails open is the same posture the rest of the profile takes,
153
+ * and the config's own loader is what reports the breakage.
154
+ */
155
+ async function profileCeiling(): Promise<AxonPartialBlueprint["profilePolicy"]> {
156
+ try {
157
+ const active = opts.store.profiles.active()
158
+ if (!active) return undefined
159
+ const policy = await readPolicy(active.root)
160
+ return Object.keys(policy).length > 0 ? (policy as AxonPartialBlueprint["profilePolicy"]) : undefined
161
+ } catch {
162
+ return undefined
163
+ }
164
+ }
165
+
166
+ /**
167
+ * The active profile's declared inference sources, re-read on every load.
168
+ *
169
+ * Sibling of profileCeiling() above and resolved for the same reason: this
170
+ * module holds the store, so it is the nearest place that legitimately
171
+ * knows which user is running. Blueprint() knows a root directory and
172
+ * must not learn about profiles.
173
+ *
174
+ * Re-read per load so a provider added or a key connected takes effect on
175
+ * the next boot or reload, rather than only after restarting the terminal.
176
+ *
177
+ * Never throws. An unreadable profile means no providers, which is the
178
+ * correct state for `axon run` outside one and for a deployment — and a
179
+ * throw here would make a broken profile config unbootable, when the
180
+ * config's own loader is what reports the breakage.
181
+ */
182
+ async function profileProviders(): Promise<AxonPartialBlueprint["profileProviders"]> {
183
+ try {
184
+ const active = opts.store.profiles.active()
185
+ if (!active) return undefined
186
+ const { providers } = await ProfileConfigFile(active.root)
187
+ // Carried VERBATIM, including an empty array. `[]` is a user who
188
+ // declared no providers and absent is one who was never asked —
189
+ // collapsing the first into the second would silently hand them
190
+ // the default pool they had deliberately cleared.
191
+ return providers ? [...providers] : undefined
192
+ } catch {
193
+ return undefined
194
+ }
195
+ }
196
+
197
+ /**
198
+ * The build's own log, opened before anything can fail.
199
+ *
200
+ * The session id is minted HERE rather than by Axon(), because the
201
+ * whole point is that the build reports into a session that exists
202
+ * before there is a runtime to open one. Axon() is handed the same id
203
+ * below, so a successful build and the run it produced are one file —
204
+ * not a build log orphaned beside the session it belongs to.
205
+ *
206
+ * The data path mirrors Blueprint()'s own, resolved through the same
207
+ * Frame() so the two cannot disagree. That location is a convention, not
208
+ * a configurable, and resolving it here rather than from a loaded
209
+ * blueprint is what lets the log exist before the scan.
210
+ */
211
+ const sessionId = opts.session ?? randomUUID()
212
+ /**
213
+ * Translate recorded build events into boot progress for the caller.
214
+ *
215
+ * Reads the events already being emitted for the log — nothing new is
216
+ * measured — and forwards only the few that name a stage (progress.ts).
217
+ * One observer on the recorder covers every emitter, so no individual
218
+ * call site needs intercepting.
219
+ */
220
+ const recorder = BuildRecorder({
221
+ root: Frame({ root: project.root, kind: "agent" }).path("data"),
222
+ sessionId,
223
+ ...(opts.onProgress || opts.onTiming ? { onEmit: reportProgress } : {}),
224
+ })
225
+
226
+ /** The last stage reported, so the bar only ever moves forward. */
227
+ let reported: BootStage | null = null
228
+
229
+ function raise(progress: BootProgress): void {
230
+ // Monotonic: `build:typegen` belongs to prepare but runs after the
231
+ // cognet compiles, so following the events literally would read
232
+ // "Preparing… → Compiling… → Preparing…". Progress that goes backwards
233
+ // reads as the work having restarted.
234
+ if (!advances(reported, progress.stage)) return
235
+ reported = progress.stage
236
+ opts.onProgress?.(progress)
237
+ }
238
+
239
+ function reportProgress(type: string, data: unknown): void {
240
+ // A closing span carries what it cost. Reported alongside progress so
241
+ // a surface can show "4 mods, 15 tools (42ms)" without timing the
242
+ // build itself — the span already measured it.
243
+ const unit = unitFor(type)
244
+ if (unit) {
245
+ const durationMs = (data as { durationMs?: number }).durationMs
246
+ if (typeof durationMs === "number") opts.onTiming?.({ unit, durationMs })
247
+ return
248
+ }
249
+
250
+ const stage = stageFor(type)
251
+ if (!stage) return
252
+ // The modules stage is the one with an honest count — the agent
253
+ // declares them, so the total is known before the work starts.
254
+ // Everything else reports a bare stage (see BootProgress).
255
+ const specifiers = type === "build:modules:start"
256
+ ? (data as { specifiers?: string[] }).specifiers
257
+ : undefined
258
+ raise(
259
+ specifiers?.length
260
+ ? { stage, total: specifiers.length, detail: specifiers[0] }
261
+ : { stage },
262
+ )
263
+ }
264
+
265
+ /**
266
+ * The warnings currently live for this agent, keyed by domain+message.
267
+ *
268
+ * ── Why this is instance-scoped and not per-build ───────────────────────
269
+ *
270
+ * A warning is a fact about the agent's CURRENT state — "@axon/arxiv's
271
+ * tools do not compile" — not about the build that noticed it. Every
272
+ * build re-derives the whole set from scratch, so a broken module is
273
+ * rediscovered by boot, by prepare, by load, and by every reload after.
274
+ * Emitting on each rediscovery stacked identical cards until the timeline
275
+ * was mostly one repeated paragraph, which reads as many problems rather
276
+ * than one persistent one.
277
+ *
278
+ * So emission is edge-triggered: a warning is announced when it APPEARS
279
+ * and stays silent while it persists. `syncWarnings` replaces the set
280
+ * wholesale from each build's output, which is what makes the suppression
281
+ * safe to hold across reloads — a warning the user has fixed drops out of
282
+ * the new set, so if it ever returns it announces itself again.
283
+ */
284
+ const liveWarnings = new Set<string>()
285
+
286
+ type ScanWarning = { domain: string; error: string; cause?: unknown }
287
+
288
+ function warningKey(warning: ScanWarning): string {
289
+ return `${warning.domain}\u0000${warning.error}`
290
+ }
291
+
292
+ function emitWarning(warning: ScanWarning): void {
293
+ recorder.emit("build:warning", {
294
+ domain: warning.domain,
295
+ message: warning.error,
296
+ ...(warning.cause ? { error: warning.cause as never } : {}),
297
+ })
298
+ }
299
+
300
+ /**
301
+ * Announce whatever is newly wrong, and forget whatever has been fixed.
302
+ *
303
+ * Takes the COMPLETE warning set a build produced, not an increment: the
304
+ * scan is the authority on what is currently broken, so anything absent
305
+ * from it is resolved by definition. Called once per build with every
306
+ * stage's warnings concatenated — prepare and load both scan, and a
307
+ * module that will not compile is found by each.
308
+ */
309
+ function syncWarnings(warnings: ScanWarning[]): void {
310
+ const current = new Set<string>()
311
+ for (const warning of warnings) {
312
+ const key = warningKey(warning)
313
+
314
+ // `current` is checked BEFORE it is added, so a warning appearing
315
+ // twice in ONE batch announces once.
316
+ //
317
+ // That is the common case, not an edge case: prepare() runs a full
318
+ // blueprint.load() internally and returns its warnings, then boot()
319
+ // loads again and concatenates both lists. A module that will not
320
+ // compile is therefore found by each scan and arrives here twice,
321
+ // in the same array, at the same millisecond. Checking only
322
+ // `liveWarnings` (what the PREVIOUS build announced) let both
323
+ // through — two identical cards for one broken module, which is
324
+ // exactly the duplication this function exists to prevent.
325
+ if (current.has(key) || liveWarnings.has(key)) {
326
+ current.add(key)
327
+ continue
328
+ }
329
+ current.add(key)
330
+ emitWarning(warning)
331
+ }
332
+
333
+ // Replace rather than merge — a key that is gone is a warning that no
334
+ // longer applies, and keeping it would suppress the announcement if
335
+ // the same breakage came back.
336
+ liveWarnings.clear()
337
+ for (const key of current) liveWarnings.add(key)
338
+ }
339
+
340
+ /**
341
+ * The booted agent — an in-heap runtime, or a linked process.
342
+ *
343
+ * `booted` rather than `runtime` for the linked case, because everything
344
+ * below that name (reload, serve, the watcher) is about an `AxonT` in this
345
+ * heap. A linked agent returns before any of it is wired.
346
+ */
347
+ // A linked agent returns HERE, before any of the in-heap machinery below
348
+ /**
349
+ * Everything both boot paths share: prepare, load, warnings, identify,
350
+ * flush — ending with the blueprint the runtime will be built from.
351
+ *
352
+ * Extracted rather than duplicated because this is the expensive and
353
+ * failure-prone half, and two copies would drift on exactly the stages
354
+ * that matter (a scan warning reported by one path and not the other is
355
+ * indistinguishable from a build that produced none).
356
+ *
357
+ * Runs INSIDE the caller's "build" span — both callers open one, so this
358
+ * stays a plain function and the span stays where the timing belongs.
359
+ */
360
+ async function build(): Promise<AxonPartialBlueprint> {
361
+ const prepared = await span(
362
+ recorder,
363
+ "build:prepare",
364
+ { root: project.root },
365
+ // The reporter is what gives the prepare span an interior:
366
+ // framework, modules, cognet, tree and typegen each report
367
+ // themselves through it, so a five-second build decomposes
368
+ // instead of being one opaque bar.
369
+ () => project.prepare({ report: (type, data) => recorder.emit(type as never, data as never) }),
370
+ result => ({ warnings: result.warnings.length }),
371
+ )
372
+
373
+ const { blueprint: loaded, warnings } = await span(
374
+ recorder,
375
+ "build:load",
376
+ { root: project.root },
377
+ async () => blueprint.load({ profilePolicy: await profileCeiling(), profileProviders: await profileProviders() }),
378
+ result => ({
379
+ // A scan that produced no agent identity is a scan that
380
+ // failed to find one — recorded as the empty string
381
+ // rather than invented, so the log says what was read.
382
+ agent: result.blueprint.agent?.name ?? "",
383
+ tools: result.blueprint.tools?.length ?? 0,
384
+ prompts: result.blueprint.prompts?.length ?? 0,
385
+ modules: result.blueprint.modules?.length ?? 0,
386
+ warnings: result.warnings.length,
387
+ }),
388
+ )
389
+ if (loaded.agent?.name) recorder.identify(loaded.agent.name)
390
+
391
+ // Scan warnings — a tool or prompt shadowed by one of the same
392
+ // name, where the scope stays coherent and one export is
393
+ // unreachable. Reported as build:warning above rather than
394
+ // committed after boot: they are facts about the BUILD, and
395
+ // emitting them from the runtime meant a build that never
396
+ // reached one reported nothing. (It also emitted
397
+ // "axon:scan:warning", which is not in the event registry — so
398
+ // those commits were failing type-check at the call site and
399
+ // would never have landed.)
400
+ //
401
+ // Both stages' warnings go in as ONE set. prepare() scans and
402
+ // load() scans again, so a module that will not compile is found
403
+ // by each — passing them separately would announce the first set,
404
+ // then immediately treat the second as the complete picture and
405
+ // re-announce everything prepare() already reported.
406
+ syncWarnings([...prepared.warnings, ...warnings])
407
+ // Drain before the session opens. AxonSession restores its seq
408
+ // high-water mark by READING this file, so any build append
409
+ // still queued at that moment is invisible to it and both
410
+ // writers then issue the same number. The queue is a handful of
411
+ // small lines; waiting costs nothing beside the boot it precedes.
412
+ await recorder.flush()
413
+
414
+ return { ...loaded, session: { id: sessionId } }
415
+ }
416
+ // An agent is ALWAYS its own process. There is no second boot path to
417
+ // choose between — the build above is shared by nothing else, and the
418
+ // supervisor takes it from here.
419
+ return await bootLinked(opts.confined)
420
+
421
+ /**
422
+ * The confined boot.
423
+ *
424
+ * Reuses `build()` — the scan, compile, blueprint load, warnings and
425
+ * identify — and diverges only at the final step, where the in-process
426
+ * path constructs `Axon()` and this one hands the prepared blueprint to a
427
+ * supervisor. Sharing that stage is the whole reason the fork sits this
428
+ * deep rather than at the call site.
429
+ */
430
+ async function bootLinked(confined: NonNullable<AgentOpts["confined"]>): Promise<LinkedRuntime> {
431
+ return span(recorder, "build", { root: project.root }, async () => {
432
+ const loaded = await build()
433
+ const linked = await confined({
434
+ blueprint: { ...loaded, session: { id: sessionId } },
435
+ sessionId,
436
+ /**
437
+ * A REAL reload: rescan the project, then hand the agent the
438
+ * blueprint that produced.
439
+ *
440
+ * The first cut re-sent the blueprint captured at boot, which
441
+ * is a reload that cannot observe an edit — a tool the author
442
+ * had just added never appeared, and the call reported success.
443
+ * `build()` is the same scan+compile+load the boot path runs,
444
+ * so a reload and a fresh boot see the project identically.
445
+ *
446
+ * The session id is preserved: a reload is the same
447
+ * conversation with new code, and minting a new one would
448
+ * split the log at every edit.
449
+ */
450
+ rescan: () => build().then(next => ({ ...next, session: { id: sessionId } })),
451
+ })
452
+ // The supervisor-held session owns this log from here, so build
453
+ // events commit through the same writer the agent's own will —
454
+ // one serialized writer per file, which the envelope depends on.
455
+ recorder.handOver((type, data) => {
456
+ void linked.session.commit(type as never, data as never)
457
+ })
458
+
459
+ /**
460
+ * The liveness record is the DAEMON'S to write.
461
+ *
462
+ * It was written here, with the agent's pid, because this was the
463
+ * only place that knew it. The daemon supervises now — it spawns
464
+ * the process, holds its link, and is still running when the
465
+ * record needs removing — so it owns the record too. Writing it in
466
+ * both places gave one fact two owners, which is the shape that
467
+ * drifts.
468
+ *
469
+ * Everything the record carries beyond the pid travels across the
470
+ * seam: see AgentSupervisor.supervise.
471
+ */
472
+ return linked
473
+ })
474
+ }
475
+ }
476
+
477
+
478
+ /** Bun.serve throws synchronously when the port is taken — match the address-in-use shape. */
479
+ function isAddrInUse(cause: unknown): boolean {
480
+ const code = (cause as { code?: string })?.code
481
+ const message = cause instanceof Error ? cause.message : String(cause)
482
+ return code === "EADDRINUSE" || /address already in use|in use|EADDRINUSE/i.test(message)
483
+ }
484
+
485
+ /**
486
+ * An agent running as its own process, reached over the link.
487
+ *
488
+ * Deliberately has NO `current`: there is no in-heap runtime to hand out, and
489
+ * offering one that returned undefined would let a consumer forget the
490
+ * difference until runtime. The session is here because the SUPERVISOR holds
491
+ * it — the agent appends through `commit` and can never rewrite the record.
492
+ */
493
+ export type LinkedRuntime = {
494
+ kind: "linked"
495
+ /** This agent's session id — the same accessor the process variant exposes. */
496
+ sessionId: string
497
+ link: SupervisorToAgent & { close(): void }
498
+ /** The supervisor-held log. Read directly; written only by the agent's commits. */
499
+ session: AxonSessionT
500
+ /**
501
+ * Where surfaces watch this agent.
502
+ *
503
+ * The linked counterpart of `runtime.bus`. A linked agent has no in-heap
504
+ * runtime to announce on, so its commits fan out here — same events, same
505
+ * order, one hop earlier than the log.
506
+ */
507
+ bus: { onAny(handler: (type: string, data: unknown) => void): () => void }
508
+ /**
509
+ * The blueprint this agent booted with — held on THIS side.
510
+ *
511
+ * The supervisor prepares it (scan, compile, resolve) and writes it beside
512
+ * the sockets, so it is already here; the agent is handed a copy rather
513
+ * than being the source of one. Exposed because every surface fact a
514
+ * header renders — the agent's name, its home, what it is carrying —
515
+ * reads off this, and reaching across the link for values the supervisor
516
+ * already holds would be a round trip to learn what it just wrote.
517
+ *
518
+ * Live for as long as this boot is: a reload replaces the whole handle.
519
+ */
520
+ blueprint: AxonBlueprint
521
+ /**
522
+ * The resolved inference roles, held supervisor-side.
523
+ *
524
+ * A linked agent has no in-heap kernel to read `engines` off, so this is
525
+ * where a model picker rebinds and where a header reads what actually
526
+ * answered. Undefined for a cognet that declared no roles.
527
+ */
528
+ engines?: { select(model: string): unknown; readonly primary?: string; has(role: string): boolean; get(role: string): { binding: { capability: { provider: string; id: string } } } }
529
+ /** Which containment tier actually built the box. Reported, never assumed. */
530
+ tier: "none" | "auto" | "container" | "hardened"
531
+ /**
532
+ * The AGENT process's pid — what a liveness probe checks.
533
+ *
534
+ * Not the supervisor's: a reader uses this to decide whether the session
535
+ * is still alive, and reporting the wrong one would keep a dead agent
536
+ * looking healthy for as long as its supervisor outlived it.
537
+ */
538
+ pid: number
539
+ reload(): Promise<void>
540
+ shutdown(): Promise<void>
541
+ }
542
+
543
+ /**
544
+ * An agent — always its own process, reached over the link.
545
+ *
546
+ * Was a discriminated union while an in-heap variant still existed. There is
547
+ * one kind now, so consumers reach the link directly instead of narrowing.
548
+ */
549
+ export type AgentT = Awaited<ReturnType<typeof Agent>>
550
+