@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,91 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { StoreT } from "../../services/store"
3
+ import { scaffoldProfile } from "../project/create/profile"
4
+ import type { ProjectsT, ProjectT } from "../project"
5
+
6
+ type ProfileOpts = {
7
+ store: StoreT
8
+ projects: ProjectsT
9
+ /** CLI version — pinned into the profile's own manifest, same as any scaffold. */
10
+ frameworkVersion: string
11
+ }
12
+
13
+ /**
14
+ * Profile — the user's own Axon directory, guaranteed to be prepared.
15
+ *
16
+ * `~/.axon/profiles/<email>/` became a real project the moment it gained code:
17
+ * a `main.ts`, a `plugins/` folder, and `extensions/` the user can write and
18
+ * install. So it is a project KIND (see kinds.ts), and this is the thing that
19
+ * guarantees one exists and is buildable, exactly as Zeno() guarantees an agent
20
+ * exists to send a message to.
21
+ *
22
+ * The pairing is deliberate — those are the two things a first-run user must
23
+ * have and cannot create for themselves: somewhere to send a message, and
24
+ * somewhere to configure the terminal.
25
+ *
26
+ * ── Idempotent, never destructive ────────────────────────────────────────────
27
+ *
28
+ * Unlike Zeno, a broken profile is NEVER replaced. Zeno can be re-cloned
29
+ * because it is a published artifact the user did not write; a profile holds
30
+ * their config, their credentials, their history and their agents. So
31
+ * `ensure()` only ever ADDS what is missing: scaffoldProfile() writes each file
32
+ * only when absent, and prepare() regenerates the frame, which is generated
33
+ * output by definition.
34
+ *
35
+ * That is what makes this safe to run on every boot, which is what makes a
36
+ * profile that gained `plugins/` in a later release acquire the folder without
37
+ * the user doing anything.
38
+ *
39
+ * ── Failure is not fatal ─────────────────────────────────────────────────────
40
+ *
41
+ * `prepare()` installs from the network. A user with no connection must still
42
+ * get a terminal — their config simply does not load — so the caller decides
43
+ * severity and this reports rather than throws. What must NOT happen is a
44
+ * silent skip: an unprepared profile means none of the user's commands, keys or
45
+ * extensions exist, and a terminal that quietly ignores its own config is
46
+ * indistinguishable from one that is broken.
47
+ */
48
+ export function Profile(opts: ProfileOpts) {
49
+ function root(): string {
50
+ const profile = opts.store.profiles.active()
51
+ if (!profile) throw err("NOT_AUTHENTICATED")
52
+ return profile.root
53
+ }
54
+
55
+ return {
56
+ /** Absolute path to the active profile's directory. */
57
+ get root(): string {
58
+ return root()
59
+ },
60
+
61
+ /**
62
+ * The active profile as a project, scaffolded and prepared if needed.
63
+ *
64
+ * Safe to call on every boot: an already-prepared profile costs a
65
+ * manifest read and a typegen rewrite.
66
+ */
67
+ async ensure(): Promise<ProjectT> {
68
+ const target = root()
69
+
70
+ // Writes only what is absent — a returning user's own main.ts is
71
+ // never touched, and a profile predating extensions/ gains it here.
72
+ await scaffoldProfile({
73
+ name: "profile",
74
+ dir: target,
75
+ frameworkVersion: opts.frameworkVersion,
76
+ })
77
+
78
+ const project = await opts.projects.open(target)
79
+
80
+ // Installs @arcforge/types and writes .axon/types. The frame's
81
+ // tsconfig extends a package resolved out of the profile's own
82
+ // node_modules, so the install is what makes the user's editor
83
+ // work at all — without it every global degrades to any.
84
+ await project.prepare()
85
+
86
+ return project
87
+ },
88
+ }
89
+ }
90
+
91
+ export type ProfileT = ReturnType<typeof Profile>
@@ -0,0 +1,143 @@
1
+ import type { BuildEventName } from "@arcforge/types"
2
+
3
+ /**
4
+ * Boot progress — the build's own events, collapsed to what a human should
5
+ * watch go by.
6
+ *
7
+ * A cold boot is seconds long and was reported as one word ("Booting…"), so a
8
+ * `bun install` and an already-warm start looked identical. The build has been
9
+ * fully traced for a while (see @arcforge/types' BuildEventMap); nothing here
10
+ * measures anything new, it only decides which of those spans is worth a line
11
+ * on a status bar.
12
+ *
13
+ * WHY NOT ALL OF THEM. The build has ten-odd spans and most complete in
14
+ * milliseconds — framework reconcile, typegen, each scan domain. A stage that
15
+ * flashes for 80ms is worse than no stage at all: the eye catches motion it
16
+ * cannot read, and the bar looks like it is glitching rather than progressing.
17
+ * So the fast units are grouped under the phase they belong to, and only the
18
+ * spans that genuinely take time get their own name.
19
+ *
20
+ * `build:load` (the blueprint scan) is deliberately NOT a stage. It is fast,
21
+ * and "Loading…" beside four concrete verbs reads as filler — the user cannot
22
+ * act on it and it tells them nothing the next stage won't.
23
+ */
24
+ export type BootStage =
25
+ /** Framework reconcile, module resolution, typegen — the fast units, grouped. */
26
+ | "preparing"
27
+ /** `bun install`. Reliably the slowest thing in a cold boot. */
28
+ | "dependencies"
29
+ /** Compiling the cognet. Seconds when cold, absent when cached. */
30
+ | "compiling"
31
+ /** The runtime coming up — what "booting" now means, and only that. */
32
+ | "booting"
33
+
34
+ /**
35
+ * Display order, and the reason this list exists separately from the union:
36
+ * the build does NOT emit stages in it.
37
+ *
38
+ * `build:typegen` is part of prepare but runs AFTER the cognet compiles, so a
39
+ * bar that simply followed the events would read
40
+ * "preparing → compiling → preparing" and appear to go backwards. Progress
41
+ * that regresses is worse than coarse progress: it tells the user the thing
42
+ * they are waiting on has restarted.
43
+ *
44
+ * So a stage only ever advances — see `advances()`. The rank is the contract;
45
+ * the event order is not.
46
+ */
47
+ const ORDER: readonly BootStage[] = ["preparing", "dependencies", "compiling", "booting"]
48
+
49
+ /**
50
+ * May the bar move from `from` to `to`?
51
+ *
52
+ * Monotonic: forward moves only, and never a repeat of the stage already
53
+ * showing. Callers use this to filter, so a late `build:typegen` inside prepare
54
+ * does not drag the label back from "Compiling…".
55
+ */
56
+ export function advances(from: BootStage | null, to: BootStage): boolean {
57
+ if (from === null) return true
58
+ return ORDER.indexOf(to) > ORDER.indexOf(from)
59
+ }
60
+
61
+ /**
62
+ * One progress report — the stage, plus a count when the stage has an honest
63
+ * one to give.
64
+ *
65
+ * `total` is only ever a number the build actually knows. The modules stage
66
+ * knows how many the agent declares, so it can count them; `bun install` does
67
+ * not know its package total until it has resolved the tree, so dependencies
68
+ * reports no count rather than a fabricated one. A progress number that is
69
+ * guessed is worse than none — it moves at the wrong rate and the user learns
70
+ * to distrust the bar.
71
+ */
72
+ export type BootProgress = {
73
+ stage: BootStage
74
+ /** 1-based position within the stage, when it counts. */
75
+ index?: number
76
+ /** How many in total, when the stage knows. */
77
+ total?: number
78
+ /** What is being worked on right now — a module specifier, say. */
79
+ detail?: string
80
+ }
81
+
82
+ /**
83
+ * A timed unit of the build — what it cost, reported when its span closes.
84
+ *
85
+ * Keyed by the UNIT, not by BootStage: the stages are a coarse projection for
86
+ * a status bar ("preparing" covers three units), while a timing has to name
87
+ * exactly what was measured. The header's modules row wants module install
88
+ * specifically, not the whole prepare phase it sits inside.
89
+ *
90
+ * Answers a different question at a different time from BootProgress: progress
91
+ * says "this is happening now", a timing says "that took N ms", and the latter
92
+ * is only knowable once the unit is over.
93
+ */
94
+ export type BuildUnit = "modules" | "dependencies" | "cognet"
95
+
96
+ export type UnitTiming = {
97
+ unit: BuildUnit
98
+ durationMs: number
99
+ }
100
+
101
+ /** The unit a `:complete` event closes, or null if it isn't one we time. */
102
+ export function unitFor(type: BuildEventName | string): BuildUnit | null {
103
+ switch (type) {
104
+ case "build:modules:complete": return "modules"
105
+ case "build:tree:complete": return "dependencies"
106
+ case "build:cognet:complete": return "cognet"
107
+ default: return null
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Which stage an event puts us in, or null for events that don't move the bar.
113
+ *
114
+ * Only `:start` events advance it: a stage ends because the next one begins,
115
+ * never because its own span closed. Otherwise the bar would blank between
116
+ * spans and flicker through every gap in the build.
117
+ */
118
+ export function stageFor(type: BuildEventName | string): BootStage | null {
119
+ switch (type) {
120
+ // The interior units that are too fast to name individually. They all
121
+ // report the phase they belong to, so the bar holds "Preparing…"
122
+ // across the run of them instead of strobing.
123
+ //
124
+ // `build:typegen` is here despite running AFTER the cognet compiles —
125
+ // it genuinely belongs to prepare. `advances()` is what stops it
126
+ // dragging the label back; the mapping stays honest about the phase.
127
+ case "build:prepare:start":
128
+ case "build:framework:start":
129
+ case "build:modules:start":
130
+ case "build:typegen:start":
131
+ return "preparing"
132
+ case "build:tree:start": return "dependencies"
133
+ case "build:cognet:start": return "compiling"
134
+ // Scan is fast and unactionable — it holds whatever came before rather
135
+ // than earning a name (see the note above).
136
+ //
137
+ // No case for `axon:boot:start`: it is committed by Axon()'s own
138
+ // session, not this recorder, so it never reaches here. Agent() raises
139
+ // "booting" directly at the point the build ends and the runtime
140
+ // starts — the same moment, from the side that can observe it.
141
+ default: return null
142
+ }
143
+ }
@@ -0,0 +1,167 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonRequestInput, AxonResult } from "@arcforge/types"
3
+ import type { InstancesT } from "./instances"
4
+
5
+ /**
6
+ * The envelope on agent-initiated spawning.
7
+ *
8
+ * A user may run as many agents side by side as they like — ten ambient agents
9
+ * is a normal fleet, and nothing here constrains that. These bound the one path
10
+ * that can run away without anyone asking: an agent whose own code spawns
11
+ * another agent, which spawns another. Depth caps recursion, children caps one
12
+ * agent's fan-out, descendants caps the whole tree beneath one root.
13
+ */
14
+ const MAX_DEPTH = 4
15
+ const MAX_LIVE_CHILDREN = 4
16
+ const MAX_LIVE_DESCENDANTS = 12
17
+
18
+ type RequestsOpts = {
19
+ instances: InstancesT
20
+ }
21
+
22
+ /**
23
+ * Requests — the host surface a running agent calls into.
24
+ *
25
+ * A capsule reaches the platform through exactly one method (`request`), which
26
+ * runs a prompt on a fresh instance of the caller's own project and returns its
27
+ * result. The instance is spawned unfocused, torn down in a finally, and
28
+ * abort-linked to the caller's signal, so a cancelled request never strands a
29
+ * runtime.
30
+ *
31
+ * This is the ONLY caller-initiated spawn path with limits attached, because it
32
+ * is the only one where the caller is code rather than a person.
33
+ */
34
+ export function Requests(opts: RequestsOpts) {
35
+ const instances = opts.instances
36
+
37
+ function abortError(): Error {
38
+ const error = new Error("agent request aborted")
39
+ error.name = "AbortError"
40
+ return error
41
+ }
42
+
43
+ function parse(input: unknown): AxonRequestInput {
44
+ if (!input || typeof input !== "object") {
45
+ throw err("SUBAGENT_REQUEST_INVALID", { detail: "expected { prompt }" })
46
+ }
47
+ const prompt = (input as { prompt?: unknown }).prompt
48
+ if (typeof prompt !== "string" && !(Array.isArray(prompt) && prompt.every(value => typeof value === "string"))) {
49
+ throw err("SUBAGENT_REQUEST_INVALID", { detail: "prompt must be a string or string[]" })
50
+ }
51
+ return { prompt: prompt }
52
+ }
53
+
54
+ /** Refuse before booting anything — a limit checked after the spawn has already cost the spawn. */
55
+ function checkLimits(parentSessionId: string) {
56
+ const parent = instances.get(parentSessionId)
57
+ if (!parent) throw err("PARENT_INSTANCE_NOT_RUNNING", { context: { sessionId: parentSessionId } })
58
+
59
+ if (parent.depth >= MAX_DEPTH) {
60
+ throw err("SUBAGENT_DEPTH_EXCEEDED", {
61
+ detail: `maximum depth is ${MAX_DEPTH}`,
62
+ context: { sessionId: parent.sessionId, depth: parent.depth, limit: MAX_DEPTH },
63
+ })
64
+ }
65
+ if (instances.children(parent.sessionId).length >= MAX_LIVE_CHILDREN) {
66
+ throw err("SUBAGENT_CHILD_LIMIT_EXCEEDED", {
67
+ detail: `maximum live children is ${MAX_LIVE_CHILDREN}`,
68
+ context: { sessionId: parent.sessionId, limit: MAX_LIVE_CHILDREN },
69
+ })
70
+ }
71
+ if (instances.descendants(parent.rootSessionId).length >= MAX_LIVE_DESCENDANTS) {
72
+ throw err("SUBAGENT_DESCENDANT_LIMIT_EXCEEDED", {
73
+ detail: `maximum live descendants is ${MAX_LIVE_DESCENDANTS}`,
74
+ context: { rootSessionId: parent.rootSessionId, limit: MAX_LIVE_DESCENDANTS },
75
+ })
76
+ }
77
+ return parent
78
+ }
79
+
80
+ async function request(input: {
81
+ parentSessionId: string
82
+ input: unknown
83
+ signal: AbortSignal
84
+ }): Promise<AxonResult> {
85
+ const parent = checkLimits(input.parentSessionId)
86
+ if (input.signal.aborted) throw abortError()
87
+
88
+ const parsed = parse(input.input)
89
+ // A deployed agent runs its own agents inside its own capsule — a remote
90
+ // parent has no local project to fork. A LINKED parent has one: it runs
91
+ // in its own process from a project on this disk, which is exactly what
92
+ // a subagent spawn needs.
93
+ if (parent.source.kind === "remote") {
94
+ throw err("SUBAGENT_REMOTE_PARENT", { context: { sessionId: parent.sessionId } })
95
+ }
96
+
97
+ const child = await instances.spawn(parent.source.project, {
98
+ parentSessionId: parent.sessionId,
99
+ focus: false,
100
+ })
101
+ if (child.source.kind === "remote") {
102
+ throw err("INSTANCE_NOT_LOCAL", {
103
+ detail: "spawn() must produce an instance on this machine",
104
+ context: { sessionId: child.sessionId, kind: child.source.kind },
105
+ })
106
+ }
107
+
108
+ // Routed through the SUPERVISOR either way, never by handing the
109
+ // parent a handle to its child.
110
+ //
111
+ // That distinction matters once children are real processes: giving a
112
+ // boxed agent a direct reference to another boxed agent would reopen
113
+ // the boundary this whole design closed, and it would put the depth
114
+ // and fan-out limits enforced above on the honour system. The parent
115
+ // asks this layer for work; this layer addresses the child.
116
+ const agent = child.source.agent
117
+ const interrupt = () => agent.link.interrupt("user")
118
+ input.signal.addEventListener("abort", interrupt, { once: true })
119
+
120
+ try {
121
+ // NOT WIRED — deliberately loud rather than approximated.
122
+ //
123
+ // The link carries `request`, which resolves when the wake
124
+ // SETTLES and reports `{ ok, interrupted }`. A parent needs the
125
+ // wake's CONTENT, and no verb returns that. This used to work
126
+ // only because the in-process path handed the parent its child's
127
+ // in-heap handle — which is precisely the boundary that could
128
+ // not be allowed to stay open, so its removal takes this with it.
129
+ //
130
+ // Not bridged with a collector here, because the destination is
131
+ // different: a subagent should be a subprocess the agent itself
132
+ // spawns, inheriting the same OS permissions, rather than a
133
+ // second runtime the supervisor brokers entries between. Building
134
+ // the collector would be building the wrong thing well.
135
+ throw err("SUBAGENT_LINK_UNSUPPORTED", {
136
+ detail: "subagent requests are being rebuilt on agent-spawned subprocesses — a confined agent cannot serve one today",
137
+ context: { sessionId: child.sessionId },
138
+ })
139
+ } finally {
140
+ input.signal.removeEventListener("abort", interrupt)
141
+ await instances.stop(child.sessionId)
142
+ }
143
+ }
144
+
145
+ return {
146
+ request: request,
147
+
148
+ /** The AxonHost surface handed to every spawned capsule. */
149
+ async call(input: {
150
+ callerSessionId: string
151
+ method: string
152
+ input: unknown
153
+ signal: AbortSignal
154
+ }): Promise<unknown> {
155
+ if (input.method !== "request") {
156
+ throw err("HOST_METHOD_UNKNOWN", { context: { method: input.method } })
157
+ }
158
+ return request({
159
+ parentSessionId: input.callerSessionId,
160
+ input: input.input,
161
+ signal: input.signal,
162
+ })
163
+ },
164
+ }
165
+ }
166
+
167
+ export type RequestsT = ReturnType<typeof Requests>
@@ -0,0 +1,159 @@
1
+ import { existsSync } from "node:fs"
2
+ import { isAbsolute, join, resolve as resolvePath } from "node:path"
3
+ import { homedir } from "node:os"
4
+ import { err } from "@arcforge/err"
5
+ import type { StoreT } from "../../services/store"
6
+
7
+ type ResolveOpts = {
8
+ store: StoreT
9
+ /** Directory a relative ref is resolved against — the script's own location, not the agent's. */
10
+ cwd: string
11
+ }
12
+
13
+ /**
14
+ * How a caller wrote the reference. Kept on the result because the two
15
+ * halves answer different questions: a path is a statement about WHERE an
16
+ * agent is, so a miss is the caller's mistake; a name is a request to go
17
+ * looking, so a miss means "not installed anywhere" and may be worth
18
+ * fetching.
19
+ */
20
+ export type RefKind = "path" | "name"
21
+
22
+ export type ResolvedAgent = {
23
+ /** Absolute path to the agent directory. Guaranteed to contain axon.config.ts. */
24
+ root: string
25
+ kind: RefKind
26
+ /** The reference as written, for error messages and correlation. */
27
+ ref: string
28
+ /** Which pool it came from — a watched checkout or the installed agents dir. */
29
+ pool: "watched" | "installed" | "path"
30
+ }
31
+
32
+ /**
33
+ * A path is anything explicitly anchored: relative, home-relative, or
34
+ * absolute. A bare `barry` is a NAME — it is looked up, not resolved
35
+ * against cwd — which is what makes short refs portable between scripts.
36
+ *
37
+ * A scoped name (`@cody/barry`) contains a slash but is NOT a path. The
38
+ * scope is part of the agent's identity, not a statement about where it
39
+ * lives, so it is checked first.
40
+ */
41
+ function isPathRef(ref: string): boolean {
42
+ if (ref.startsWith("@")) return false
43
+ return ref.startsWith(".") || ref.startsWith("~") || isAbsolute(ref) || ref.includes("/")
44
+ }
45
+
46
+ function expandHome(ref: string): string {
47
+ return ref.startsWith("~") ? join(homedir(), ref.slice(1)) : ref
48
+ }
49
+
50
+ /** The one test for "is there an agent here" — matches what Blueprint() will read. */
51
+ function isAgentDir(root: string): boolean {
52
+ return existsSync(join(root, "axon.config.ts"))
53
+ }
54
+
55
+ /**
56
+ * Resolve — an agent reference to a directory on disk.
57
+ *
58
+ * LOCAL ONLY. Resolution never touches the network, in any branch, for any
59
+ * kind of reference. `axon install` is the sole acquisition path; running
60
+ * an agent is pure disk.
61
+ *
62
+ * That split is the design, not an optimization. A command that sometimes
63
+ * fetches is a command whose failure modes cannot be predicted: it breaks
64
+ * offline, hangs on a slow link, and in CI pulls a version nobody
65
+ * reviewed. Worse, whatever it silently installed then shadows the
66
+ * checkout being worked on — the exact bug this shape replaced, where
67
+ * editing an agent's source did nothing because a stale clone from a
68
+ * previous run answered first.
69
+ *
70
+ * Never boots, never prepares, never loads a blueprint, never installs.
71
+ * Returns a directory and how it was found.
72
+ */
73
+ export function Resolve(opts: ResolveOpts) {
74
+ const { store } = opts
75
+
76
+ /**
77
+ * The active profile's agent surface. Named refs are profile-scoped —
78
+ * they resolve against the logged-in user's own pools — so being
79
+ * logged out is a real failure with its own message rather than an
80
+ * empty search that reports "no agent named x".
81
+ */
82
+ function agents() {
83
+ const active = store.profiles.active()
84
+ // NOT_AUTHENTICATED, not AGENT_NOT_FOUND: "you are logged out" and
85
+ // "that agent does not exist" are different problems with different
86
+ // fixes, and the caller that distinguishes them (the TUI's login
87
+ // prompt) keys off the code.
88
+ if (!active) throw err("NOT_AUTHENTICATED")
89
+ return active.agents
90
+ }
91
+
92
+ /** Every pool searched, in order, for an error message that can teach. */
93
+ function searched(): string[] {
94
+ return agents().pools().map(pool => `${pool.root} (${pool.kind})`)
95
+ }
96
+
97
+ return {
98
+ /**
99
+ * Resolve one reference against local pools.
100
+ *
101
+ * A path says WHERE an agent is, so a miss is the caller's mistake.
102
+ * A name is a request to go looking, so a miss means "not installed
103
+ * anywhere" and the fix is `axon install` — never an implicit fetch
104
+ * on the way to running something.
105
+ */
106
+ async one(ref: string): Promise<ResolvedAgent> {
107
+ if (isPathRef(ref)) {
108
+ const root = resolvePath(opts.cwd, expandHome(ref))
109
+ if (!isAgentDir(root)) {
110
+ // A path says where the agent IS. Looking elsewhere
111
+ // would be guessing at what the caller meant.
112
+ throw err("PROJECT_NOT_FOUND", { context: { ref, path: root } })
113
+ }
114
+ return { root, kind: "path", ref, pool: "path" }
115
+ }
116
+
117
+ const matches = agents().find(ref).filter(match => isAgentDir(match.root))
118
+
119
+ if (matches.length === 0) {
120
+ throw err("AGENT_NOT_FOUND", { context: { ref, searched: searched() } })
121
+ }
122
+
123
+ // A watched checkout shadowing its own installed copy is the
124
+ // normal case, not a conflict: watching a directory IS the
125
+ // statement that the checkout is the one being worked on. So
126
+ // the watched tier wins outright, and ambiguity is only ever
127
+ // asked WITHIN a tier — two checkouts, or two installs.
128
+ const watched = matches.filter(match => match.kind === "watched")
129
+ const tier = watched.length > 0 ? watched : matches
130
+
131
+ // Within a tier there is no correct way to guess. Picking by
132
+ // search order silently runs an agent nobody asked for.
133
+ if (tier.length > 1) {
134
+ throw err("AGENT_AMBIGUOUS", {
135
+ context: { ref, found: tier.map(match => `${match.root} (${match.kind})`) },
136
+ })
137
+ }
138
+
139
+ const match = tier[0]!
140
+ return { root: match.root, kind: "name", ref, pool: match.kind }
141
+ },
142
+
143
+ /**
144
+ * Resolve a whole set before any of them boots.
145
+ *
146
+ * Rejects on the first failure:
147
+ * a fleet either comes up whole or not at all, and a caller
148
+ * holding two working agents and one broken one is the outcome
149
+ * this exists to prevent.
150
+ */
151
+ async all<T extends Record<string, string>>(refs: T): Promise<{ [K in keyof T]: ResolvedAgent }> {
152
+ const names = Object.keys(refs) as (keyof T)[]
153
+ const resolved = await Promise.all(names.map(name => this.one(refs[name] as string)))
154
+ return Object.fromEntries(names.map((name, i) => [name, resolved[i]])) as { [K in keyof T]: ResolvedAgent }
155
+ },
156
+ }
157
+ }
158
+
159
+ export type ResolveT = ReturnType<typeof Resolve>