@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,40 @@
1
+ // project — finding, opening, creating, and preparing agent/module projects.
2
+ // Projects() is the module's single entry point.
3
+
4
+ export { Projects, type ProjectsT, type CreateStep } from "./projects"
5
+ export type { ProjectKind, ProjectT } from "./project"
6
+ export { detectKind } from "./kinds"
7
+ // Exported because the extension loader watches a PROFILE, which is a project
8
+ // root that nothing calls Project() on — it is scaffolded and loaded rather
9
+ // than opened. The watcher itself is kind-agnostic.
10
+ export { Watcher, type WatcherT } from "./watcher"
11
+ export type { PrepareResult } from "./prepare"
12
+ // PublishStep is the CLI's progress contract — a publish spends real time in
13
+ // each step, and the renderer needs the union to know what it is showing.
14
+ export type { PublishResult, PublishStep } from "./publish"
15
+ export type { InstallResult, UninstallResult, ModuleUpdate } from "./installer"
16
+ export type { AgentImage, ModuleImage, SourceImage, BundleArtifact, BundleIdentity } from "./bundle"
17
+ export { Assets, type AssetsT, type AssetReport, type AssetsResult } from "./bundle"
18
+ export type { TypegenResult } from "./typegen"
19
+ export { Manifest, type ManifestT, type ConfigArray } from "./manifest"
20
+ export type { ModelT, ModelSetResult } from "./manifest"
21
+ export type { EngineEffort } from "@arcforge/types"
22
+ export { SourceModules, type SourceModulesT, type SourceModule, type LinkResult } from "./modules"
23
+ export { Tree, type TreeT } from "./tree"
24
+ export { TreeCache, type TreeCacheT } from "./treecache"
25
+ export { reconcile, type ReconcileResult } from "./reconcile"
26
+ export { verify, graftBroken, describeFaults, type Fault, type VerifyReport } from "./verify"
27
+
28
+ // The frame layout, for consumers that need to POINT at generated output they
29
+ // did not write — Fleet linking a user to their tool scope, say. Exported
30
+ // because the alternative is what Fleet actually did: hand-spell
31
+ // `.agent/tool-globals.d.ts`, miss that the frame groups declarations under
32
+ // `types/`, and silently render an existsSync() that is now never true. A
33
+ // layout with one owner needs one accessor reachable from outside it.
34
+ export { Frame, type FrameT, type FrameArea } from "../frame"
35
+
36
+ // Model weights — declared by a cognet, fetched and verified here, handed to
37
+ // the brain as absolute paths. An asset store that happens to be used for ML.
38
+ export { Models, ModelStore, parseModel, parseModels, downloadUrl, basenameOf, fetchModel } from "./models"
39
+ export type { ModelsT, ResolveResult, ModelStoreT, StoredModel, ParsedModel } from "./models"
40
+ export { parseSpecifier } from "./specifier"
@@ -0,0 +1,616 @@
1
+ import { HttpError, resolveDefaultBaseUrl, type AxonCloudClient } from "@arcforge/cloud"
2
+ import { err } from "@arcforge/err"
3
+ import type { ManifestT } from "./manifest"
4
+ import type { TreeT } from "./tree"
5
+ import { parseSpecifier } from "./specifier"
6
+
7
+ /**
8
+ * Installer — add and remove registry modules from an agent.
9
+ *
10
+ * Three writes and a `bun install`. Axon decides WHAT the agent has;
11
+ * Bun decides how those bytes arrive:
12
+ *
13
+ * package.json the dependency (semver range) — presence
14
+ * axon.config.ts the module entry — activation
15
+ * bun.lock the exact resolved version — Bun's, not ours
16
+ *
17
+ * That split is Nuxt's: a module is both a dependency and a declared
18
+ * feature, and those are genuinely different facts. A package can be
19
+ * installed but not activated.
20
+ *
21
+ * This used to be a hand-rolled package manager — download, extract,
22
+ * sha256, a bespoke lockfile, a parallel .agent/modules store, symlinks
23
+ * into node_modules, and a flat dependency hoister that threw on version
24
+ * conflicts Bun resolves by nesting. All of it existed only because Bun
25
+ * did not know where Axon modules came from. It does now (see the npm
26
+ * protocol surface in the backend), so all of it is gone.
27
+ */
28
+
29
+ export type InstallResult =
30
+ | { status: "installed"; name: string; version: string }
31
+ | { status: "already-installed"; name: string; version: string }
32
+ /**
33
+ * No such module in the registry — a mistyped or unpublished name.
34
+ * Separate from "error" because it is not a fault: nothing is broken,
35
+ * the thing asked for simply does not exist. Callers report it as
36
+ * information; only a real failure (network, disk, a broken install)
37
+ * deserves to be raised as one.
38
+ */
39
+ | { status: "not-found"; name: string }
40
+ | { status: "error"; name: string; error: string }
41
+
42
+ /**
43
+ * `source-declared` is a REFUSAL, not a failure: the module is declared by an
44
+ * import statement in axon.config.ts rather than by a registry name, and that
45
+ * import is the author's own code. Uninstall does not rewrite it, so it
46
+ * removes nothing at all — touching package.json alone would strip the
47
+ * dependency while the config still imported it, and the agent would keep
48
+ * loading a module whose package was gone.
49
+ *
50
+ * `path` names the file to edit, because "remove it by hand" is only
51
+ * actionable if the user is told where.
52
+ */
53
+ export type UninstallResult =
54
+ | { status: "removed" | "not-installed"; name: string }
55
+ | { status: "source-declared"; name: string; path: string }
56
+
57
+ /**
58
+ * One module's position relative to the registry — what `updates()` reports
59
+ * and an update surface renders.
60
+ *
61
+ * `current` and `range` are both here because they answer different questions,
62
+ * and conflating them is the mistake this type exists to prevent. See
63
+ * `updates()`.
64
+ */
65
+ export type ModuleUpdate = {
66
+ name: string
67
+ /** The declared constraint in package.json — `^1.2.0`, `~1.2.0`, `1.2.0`. */
68
+ range: string
69
+ /**
70
+ * The version materialized in node_modules — what the agent actually
71
+ * loads. Null when the module is declared but not installed.
72
+ */
73
+ current: string | null
74
+ /** Newest published. Null when the registry could not be reached. */
75
+ latest: string | null
76
+ /**
77
+ * True only when both versions are known and differ. An unknown on either
78
+ * side is never an update — see `updates()` for why each is reported as
79
+ * itself instead.
80
+ */
81
+ outdated: boolean
82
+ }
83
+
84
+ export type InstallOptions = {
85
+ /**
86
+ * Register the package in axon.config.ts's modules array. Default true.
87
+ * False for dependencies that are not modules — notably the cognet.
88
+ */
89
+ declare?: boolean
90
+ /**
91
+ * Re-resolve to the registry's latest on every install, overwriting the
92
+ * declared range instead of respecting it as a pin.
93
+ *
94
+ * Only for dependencies the user did NOT choose — today just the default
95
+ * cognet. An unchosen default should not silently freeze at whatever was
96
+ * current when the agent was scaffolded, and it must not be poisonable:
97
+ * a range that cannot resolve (a workspace sibling's version leaking into
98
+ * package.json, say) would otherwise be honoured forever and surface to
99
+ * the user as a boot failure.
100
+ *
101
+ * Never set this for something the user asked for by name. An explicit
102
+ * `cognet: "@axon/zero@0.1.4"` is a pin and stays one.
103
+ */
104
+ track?: "latest"
105
+ /**
106
+ * Resolve only versions targeting this kernel ABI.
107
+ *
108
+ * For the cognet, whose bundle is fused to one kernel contract: "latest" on
109
+ * its own can name a version this runtime cannot load, and the mismatch
110
+ * would otherwise surface after install, at compile time. Passing the ABI
111
+ * means an incompatible version is never selected in the first place.
112
+ *
113
+ * Has no effect on an explicitly pinned specifier — the registry honours
114
+ * the pin and the prepare-time ABI gate is what refuses a bad pairing,
115
+ * naming the file to edit.
116
+ */
117
+ abi?: string
118
+ /**
119
+ * Write the resolved version back under the range OPERATOR the manifest
120
+ * already declares (`^1.2.0` → `^1.3.0`), instead of as the exact pin an
121
+ * explicit constraint normally produces.
122
+ *
123
+ * Exists for `update()`. An explicit constraint is written through
124
+ * verbatim, so without this, moving a module to 1.3.0 lands `1.3.0` in
125
+ * package.json and silently converts the user's caret range into a hard
126
+ * pin. They asked to move a version, not to stop receiving patches, and
127
+ * the loss surfaces much later as a module that stopped tracking. A name
128
+ * with no declared operator was a deliberate exact pin and stays exact.
129
+ *
130
+ * Never set for a constraint the USER typed: `axon install @x/y@1.2.0`
131
+ * means that version, and widening it would install something else.
132
+ */
133
+ keepRange?: boolean
134
+ }
135
+
136
+ type InstallerOpts = {
137
+ root: string
138
+ cloud: AxonCloudClient
139
+ /** The project's declaration files — what install adds a dependency to. */
140
+ manifest: ManifestT
141
+ /** The installed node_modules — what install materializes. */
142
+ tree: TreeT
143
+ /**
144
+ * Runs `fn` with the project's file watcher suspended.
145
+ *
146
+ * An install rewrites the manifests AND node_modules; the watcher would
147
+ * see the manifest writes and fire a reload into the middle of the tree
148
+ * rebuild. A thunk rather than the Watcher handle because Watcher() is
149
+ * constructed after Installer() in project.ts — same idiom as the bench
150
+ * axis and Zeno's clone.
151
+ */
152
+ during: <T>(fn: () => Promise<T>, options?: { selfReloads?: boolean }) => Promise<T>
153
+ /** Backend base URL — where the agent's registry scopes point. Defaults to this process's backend. */
154
+ apiBase?: string
155
+ }
156
+
157
+ export function Installer(opts: InstallerOpts) {
158
+ const { cloud, manifest, tree } = opts
159
+ /** Where bun fetches tarballs from. */
160
+ const registryUrl = `${opts.apiBase ?? resolveDefaultBaseUrl()}/api/registry/npm/-`
161
+ /**
162
+ * Which registry auto-resolved ranges are attributed to.
163
+ *
164
+ * The API BASE rather than the npm sub-path, because that is the identity
165
+ * of the registry as a whole — the same base answers both the resolve
166
+ * endpoint that produces a range and the npm endpoint that serves the
167
+ * tarball, and comparing bases is what tells staging from production.
168
+ */
169
+ const registryOrigin = opts.apiBase ?? resolveDefaultBaseUrl()
170
+
171
+ /**
172
+ * Confirm the module exists and pin the range against a real published
173
+ * version. Bun would fail on a missing package anyway, but its error
174
+ * speaks about a registry URL; resolving first lets a bad specifier
175
+ * fail as an Axon error naming the module.
176
+ */
177
+ async function resolveVersion(name: string, constraint?: string, abi?: string): Promise<string> {
178
+ const resolved = await cloud.registry.artifacts.resolve(name, constraint, abi ? { abi } : undefined)
179
+
180
+ // A prompt is not installable into an agent. Prompts are content a
181
+ // person picks off a palette: they resolve into a global cache and
182
+ // render on the spot, so no agent ever depends on one. Declaring it
183
+ // in modules: [...] instead would put content through the code path —
184
+ // an ABI check, a node_modules link and an agent reload — for
185
+ // something that needs none of them.
186
+ if (resolved.kind === "prompt") {
187
+ throw err("PROMPT_NOT_INSTALLABLE", {
188
+ detail: `"${name}" is a prompt, not a module. Prompts are not installed into an agent — they resolve from the global cache and render on demand, so any agent can use one without declaring it.`,
189
+ context: { name },
190
+ })
191
+ }
192
+
193
+ return resolved.version
194
+ }
195
+
196
+ return {
197
+ /**
198
+ * Ensure every specifier is a dependency of this agent and declared
199
+ * in its config, then materialize node_modules once for the batch.
200
+ *
201
+ * `declare: false` installs the dependency WITHOUT adding it to the
202
+ * config's modules array — how a cognet is installed. A cognet is a
203
+ * dependency of the agent but not a module of it: it is selected by
204
+ * `cognet:`, and listing it under `modules:` would try to load the
205
+ * brain as a capability bundle.
206
+ */
207
+ /**
208
+ * Re-resolve any auto-written range that came from a DIFFERENT registry.
209
+ *
210
+ * Must run before anything calls `tree.install()`, and that ordering is
211
+ * the whole point. Bun resolves the WHOLE manifest at once, so a single
212
+ * unresolvable range fails the install of every other package — a
213
+ * poisoned `@axon/zero` range killed the modules install long before
214
+ * the cognet step that would have re-resolved it ever ran. Fixing it
215
+ * per-install-path is therefore not enough; the manifest has to be
216
+ * coherent before the first install, not after the one that owns it.
217
+ *
218
+ * Only ranges Axon wrote itself (`axon.trackedFrom`) are touched. A
219
+ * user's pin carries no origin and is never second-guessed.
220
+ *
221
+ * Returns the names it repaired, for the caller to report.
222
+ */
223
+ async repairForeignRanges(): Promise<Array<{ name: string; from: string; to: string; origin: string }>> {
224
+ const origins = await manifest.package.dependencies.trackedFrom()
225
+ const foreign = Object.entries(origins).filter(([, origin]) => origin !== registryOrigin)
226
+ if (foreign.length === 0) return []
227
+
228
+ const declared = await manifest.package.dependencies.all()
229
+ const additions: Record<string, string> = {}
230
+ const stamps: Record<string, string> = {}
231
+ const repaired: Array<{ name: string; from: string; to: string; origin: string }> = []
232
+
233
+ for (const [name, origin] of foreign) {
234
+ const existing = declared[name]
235
+ if (existing === undefined) continue
236
+ try {
237
+ // No constraint: this range was auto-resolved to begin
238
+ // with, so re-resolving is restoring it, not overriding a
239
+ // choice. No ABI either — the caller that owns the ABI
240
+ // constraint (the cognet path) re-resolves under it
241
+ // immediately after, and guessing one here could pick a
242
+ // version that path would reject.
243
+ const version = await resolveVersion(name)
244
+ const range = `^${version}`
245
+ stamps[name] = registryOrigin
246
+ if (range !== existing) {
247
+ additions[name] = range
248
+ repaired.push({ name, from: existing, to: range, origin })
249
+ }
250
+ } catch {
251
+ // Unresolvable here too. Left alone deliberately: the
252
+ // install that follows fails with the package manager's own
253
+ // message, which is more specific than anything this could
254
+ // invent about a package it could not reach.
255
+ }
256
+ }
257
+
258
+ if (Object.keys(additions).length > 0 || Object.keys(stamps).length > 0) {
259
+ await manifest.package.dependencies.set(additions, stamps)
260
+ }
261
+ return repaired
262
+ },
263
+
264
+ async install(specifiers: string[], options: InstallOptions = {}): Promise<InstallResult[]> {
265
+ if (specifiers.length === 0) return []
266
+
267
+ // Read once, decide across the whole batch, then hand the
268
+ // additions to Manifest in one write — several specifiers commonly
269
+ // resolve in one call, and each is a decision about the same map.
270
+ const declared = await manifest.package.dependencies.all()
271
+ // Which registry each existing auto-resolved range came from, so a
272
+ // range derived elsewhere can be re-resolved rather than honoured
273
+ // into a permanent failure.
274
+ const origins = await manifest.package.dependencies.trackedFrom()
275
+ const trackedOrigin = (name: string): string | undefined => origins[name]
276
+ const additions: Record<string, string> = {}
277
+ const trackedOrigins: Record<string, string> = {}
278
+ const results: InstallResult[] = []
279
+
280
+ for (const specifier of specifiers) {
281
+ // Inside the try: a malformed specifier is one bad entry in
282
+ // the batch, reported like any other per-specifier failure,
283
+ // not something that aborts the whole install.
284
+ let name = specifier
285
+ try {
286
+ // An unscoped name can never resolve, so it is the same
287
+ // outcome as a name that doesn't exist: nothing found.
288
+ if (!specifier.startsWith("@")) {
289
+ results.push({ status: "not-found", name })
290
+ continue
291
+ }
292
+
293
+ const parsed = parseSpecifier(specifier)
294
+ name = parsed.name
295
+ const constraint = parsed.version
296
+ const existingRange = declared[name] ?? additions[name]
297
+ // A `file:` dependency is a LOCAL source module, not a
298
+ // registry install. Asking to install from the registry
299
+ // is asking to replace it, so it must not count as
300
+ // already-installed — otherwise the local copy wins
301
+ // forever and the registry version can never land.
302
+ //
303
+ // `workspace:*` is the same situation with a worse failure
304
+ // mode. An agent inside a monorepo can acquire one (a bare
305
+ // `bun update` rewrites the range when a workspace member
306
+ // shares the name), and installDependencies() resolves
307
+ // against an ISOLATED copy of this manifest where no
308
+ // workspace exists — so it doesn't just shadow the
309
+ // registry version, it can't resolve at all. Treat it as
310
+ // absent so the registry range replaces it.
311
+ const isLocalRange = existingRange?.startsWith("file:") || existingRange?.startsWith("workspace:")
312
+ const existing = isLocalRange ? undefined : existingRange
313
+
314
+ // An unconstrained install of an already-declared module
315
+ // leaves its range alone. Re-resolving to latest here
316
+ // would turn `axon install x` into a silent upgrade of a
317
+ // version someone deliberately pinned — only an explicit
318
+ // constraint may move a pin. The declared range is the
319
+ // answer, so this asks the registry nothing: it is a
320
+ // range ("^0.1.0"), not a version the registry could
321
+ // resolve anyway.
322
+ // `track: "latest"` skips this: the whole point is to
323
+ // re-resolve and overwrite the declared range, so treating
324
+ // it as an untouchable pin is exactly the wrong answer.
325
+ if (existing !== undefined && !constraint && options.track !== "latest") {
326
+ // …unless the range was auto-resolved against a
327
+ // DIFFERENT registry than the one now configured. Such
328
+ // a range describes a version this registry may never
329
+ // have heard of, and honouring it means every install
330
+ // from here on fails to resolve. Re-resolving is the
331
+ // only way back, and it is safe precisely because the
332
+ // range was never the user's claim — we wrote it.
333
+ const origin = trackedOrigin(name)
334
+ if (origin !== undefined && origin !== registryOrigin) {
335
+ // Fall through to re-resolve against this registry.
336
+ } else {
337
+ results.push({ status: "already-installed", name, version: existing.replace(/^[\^~>=<\s]*/, "") })
338
+ continue
339
+ }
340
+ }
341
+
342
+ const version = await resolveVersion(name, constraint, options.abi)
343
+ // `keepRange` re-applies the operator already declared, so
344
+ // an update moves the version without narrowing the user's
345
+ // constraint into a pin. See InstallOptions.
346
+ const range = options.keepRange && constraint
347
+ ? `${existingRange?.match(/^[\^~]/)?.[0] ?? ""}${version}`
348
+ : constraint ?? `^${version}`
349
+
350
+ if (existing === range) {
351
+ results.push({ status: "already-installed", name, version })
352
+ continue
353
+ }
354
+
355
+ // A range written here is derived from ONE registry, but it
356
+ // is stored in a manifest that outlives the session and is
357
+ // read by every later install, whichever registry is
358
+ // configured then. Those are not the same fact, and nothing
359
+ // in package.json records the difference.
360
+ //
361
+ // The failure this closes, observed: a `track: "latest"`
362
+ // resolve ran against local staging (which had @axon/zero
363
+ // 1.0.5 from test publishes), wrote "^1.0.5" into a real
364
+ // agent's package.json, and every subsequent install
365
+ // against PRODUCTION — whose latest is 1.0.4 — failed to
366
+ // resolve. The manifest permanently demanded a version that
367
+ // only ever existed on one machine's localhost.
368
+ //
369
+ // Recording the origin costs one field and makes the
370
+ // mismatch detectable instead of mysterious. Only tracked
371
+ // (auto-resolved) ranges are stamped: a range the USER
372
+ // pinned is their claim, not ours, and must not be
373
+ // second-guessed by which registry happens to be current.
374
+ if (options.track === "latest") {
375
+ trackedOrigins[name] = registryOrigin
376
+ }
377
+
378
+ additions[name] = range
379
+ results.push({ status: "installed", name, version })
380
+ } catch (error) {
381
+ // A 404 from resolve means no such module — the user
382
+ // mistyped, or it was never published. Not a fault.
383
+ if (error instanceof HttpError && error.status === 404) {
384
+ results.push({ status: "not-found", name })
385
+ continue
386
+ }
387
+ results.push({ status: "error", name, error: error instanceof Error ? error.message : String(error) })
388
+ }
389
+ }
390
+
391
+ // Everything from here rewrites the project: three manifest files
392
+ // and then node_modules. Suspended as ONE span so the watcher
393
+ // cannot fire a reload between the manifest writes and the tree
394
+ // rebuild — the window where package.json declares a dependency
395
+ // the tree has not materialized yet, and a rescan sees an
396
+ // incoherent project. The caller reloads once when this returns.
397
+ //
398
+ // `selfReloads` is what makes that "once" true. Suspension alone
399
+ // only DEFERS the notification — it is delivered on resume, so the
400
+ // caller's reload and the watcher's fired back to back and every
401
+ // install rescanned the whole project twice.
402
+ return opts.during(async () => {
403
+ const changed = Object.keys(additions).length > 0 || Object.keys(trackedOrigins).length > 0
404
+ if (changed) {
405
+ await manifest.package.dependencies.set(additions, trackedOrigins)
406
+ // Bun resolves by scope, so a namespace it has never seen
407
+ // (any user or org publishing here) must be mapped before
408
+ // the install runs or it asks npmjs.com and 404s. Only the
409
+ // scopes actually resolved through Axon are mapped —
410
+ // everything else must keep resolving against public npm.
411
+ const resolved = results
412
+ .filter(r => r.status === "installed" || r.status === "already-installed")
413
+ .map(r => r.name)
414
+ await manifest.bunfig.ensureAll(resolved, registryUrl)
415
+ if (options.declare !== false) {
416
+ for (const result of results) {
417
+ if (result.status === "installed") {
418
+ await manifest.config.add(result.name, "modules")
419
+ }
420
+ }
421
+ }
422
+ }
423
+
424
+ // Materialize node_modules only when there's a real reason to:
425
+ // the manifest actually changed (a new install), OR node_modules
426
+ // is missing (a previous run wrote the manifest then failed before
427
+ // installing, so "already-installed" would otherwise mean "declared
428
+ // but absent"). A warm boot where everything is already declared
429
+ // AND present must NOT run `bun install` — that no-op install was
430
+ // costing ~1.5s on every `axon dev` / TUI boot.
431
+ const anyResolved = results.some(r => r.status === "installed" || r.status === "already-installed")
432
+ if (anyResolved && (changed || !tree.frameworkInstalled())) {
433
+ await tree.install()
434
+ }
435
+
436
+ return results
437
+ }, { selfReloads: true })
438
+ },
439
+
440
+ /**
441
+ * Drop a registry module from this agent's dependencies and config.
442
+ *
443
+ * A malformed specifier reports "not-installed" rather than
444
+ * throwing: nothing by that name is installed, which is exactly
445
+ * what the caller asked about. Removing something absent is not a
446
+ * failure, and a mistyped name is a user correcting themselves —
447
+ * not a fault the UI should render as a crash.
448
+ */
449
+ async uninstall(specifier: string): Promise<UninstallResult> {
450
+ let name: string
451
+ try {
452
+ ; ({ name } = parseSpecifier(specifier))
453
+ } catch {
454
+ return { status: "not-installed", name: specifier }
455
+ }
456
+
457
+ // Suspended for the same reason install() is: the manifest writes
458
+ // and the tree rebuild are one transition, and a reload landing
459
+ // between them rescans a project whose files and node_modules
460
+ // disagree. `selfReloads` for the same reason too — the caller
461
+ // reloads when a removal actually happened.
462
+ return opts.during(async () => {
463
+ // BEFORE any write. A source-declared module is one this
464
+ // uninstall cannot complete — `config.remove()` matches the
465
+ // registry NAME as a string, and a source module's declaration
466
+ // is an import binding, so it would find nothing and report
467
+ // false. That false used to be discarded: the dependency came
468
+ // out of package.json, the import stayed, and the whole thing
469
+ // reported "removed" while the agent went right on loading the
470
+ // module from a package it no longer declared.
471
+ //
472
+ // Refusing here keeps the two manifests consistent — either
473
+ // both change or neither does.
474
+ if (!(await manifest.config.declaresName(name))) {
475
+ return { status: "source-declared" as const, name, path: manifest.config.path }
476
+ }
477
+
478
+ const removed = await manifest.package.dependencies.remove([name])
479
+ if (removed.length === 0) return { status: "not-installed" as const, name }
480
+ // Which array it lives in is a property of the file, not of the
481
+ // caller — remove() drops the declaring line wherever it sits, so
482
+ // uninstall never needs to know the kind.
483
+ await manifest.config.remove(name)
484
+ await tree.install()
485
+
486
+ return { status: "removed" as const, name }
487
+ }, { selfReloads: true })
488
+ },
489
+
490
+ /**
491
+ * The registry artifacts this agent declares, as name → version range.
492
+ *
493
+ * An installed artifact is a dependency the agent's config also
494
+ * ACTIVATES, so that is the test. Filtering on "@" alone would
495
+ * count every scoped npm package (@vue/compiler-sfc, @types/bun) as
496
+ * installed — the same conflation between "a dependency" and "a
497
+ * module" that put npm internals into the agent's tool scope.
498
+ *
499
+ * Modules are the whole set: prompts are no longer installable into
500
+ * an agent at all. They resolve from the global cache and render on
501
+ * demand, so nothing about a prompt is a property of one agent.
502
+ */
503
+ /**
504
+ * The newest published version of one artifact, optionally constrained
505
+ * and optionally gated to a kernel ABI.
506
+ *
507
+ * Exposed for the cognet, which resolves ONE package rather than the
508
+ * declared-module set `updates()` walks, and must pass an ABI so a
509
+ * version this runtime cannot load is never selected. Throws when the
510
+ * registry cannot answer — callers decide whether that is a row saying
511
+ * "could not reach the registry" or a failure.
512
+ */
513
+ resolve(name: string, constraint?: string, abi?: string): Promise<string> {
514
+ return resolveVersion(name, constraint, abi)
515
+ },
516
+
517
+ async installed(): Promise<Record<string, string>> {
518
+ const dependencies = await manifest.package.dependencies.all()
519
+ const activated = new Set(await manifest.config.declared("modules"))
520
+ return Object.fromEntries(
521
+ Object.entries(dependencies).filter(([name]) => activated.has(name)),
522
+ )
523
+ },
524
+
525
+ /**
526
+ * This agent's modules, each with the newest published version.
527
+ *
528
+ * Read-only, deliberately: nothing here fetches a tarball, writes a
529
+ * manifest or rebuilds a tree. Asking the registry what exists is safe
530
+ * and happens on a palette render; applying it is `update()`.
531
+ *
532
+ * ── `current` is the TREE, not the range ────────────────────────────
533
+ *
534
+ * An extension is pinned exactly in `profile.config.ts`, so "what am I
535
+ * on" is a string in a config and "outdated" is a string compare. A
536
+ * module is a semver RANGE in package.json resolved to an exact version
537
+ * in bun.lock, and those are not the same fact. `^1.2.0` with 1.2.7 on
538
+ * disk is current at 1.2.7 — reading the range's floor would report an
539
+ * update `prepare` had already applied, every time, for every module
540
+ * anyone ever installed with a caret.
541
+ *
542
+ * So `current` is `tree.installedVersion()` — what the agent actually
543
+ * loads — and `range` rides alongside, because an update that crosses
544
+ * the declared range rewrites the user's constraint and a surface has
545
+ * to be able to say so.
546
+ *
547
+ * ── Two unknowns, each reported as itself ───────────────────────────
548
+ *
549
+ * `current: null` is declared-but-not-materialized (a fresh clone
550
+ * before `prepare`). That is a missing install, not an update, and
551
+ * rendering it as outdated sends the user to the wrong fix.
552
+ *
553
+ * `latest: null` is a registry that could not be reached. Kept as a row
554
+ * rather than dropped, because "could not ask" and "nothing new" look
555
+ * identical from the outside and mean opposite things — a failed check
556
+ * shown as up to date is the one wrong reading that costs something.
557
+ *
558
+ * Neither is ever `outdated`, so a caller that only reads that flag
559
+ * cannot act on a version it does not know.
560
+ */
561
+ async updates(): Promise<ModuleUpdate[]> {
562
+ const declared = await this.installed()
563
+
564
+ return await Promise.all(Object.entries(declared).map(async ([name, range]): Promise<ModuleUpdate> => {
565
+ const current = tree.installedVersion(name)
566
+ try {
567
+ const latest = await resolveVersion(name)
568
+ return { name, range, current, latest, outdated: current !== null && latest !== current }
569
+ } catch {
570
+ return { name, range, current, latest: null, outdated: false }
571
+ }
572
+ }))
573
+ },
574
+
575
+ /**
576
+ * Move modules to explicit versions, in ONE transition.
577
+ *
578
+ * ── A batch, not a loop ─────────────────────────────────────────────
579
+ *
580
+ * `install()` already reads the manifest once, decides across the whole
581
+ * set, writes once and runs `bun install` once — all under a single
582
+ * watcher suspension. Updating three modules one at a time would
583
+ * rebuild node_modules three times to reach the state the batch reaches
584
+ * once, with the agent reloading between each.
585
+ *
586
+ * This is where modules and extensions genuinely differ. Extensions
587
+ * update sequentially because each is a separate AST edit to one shared
588
+ * `profile.config.ts`, and two of those racing is how one silently
589
+ * loses. Modules write one manifest as a unit, so the batch is both
590
+ * faster and the safer shape.
591
+ *
592
+ * ── Just install(), at explicit refs ────────────────────────────────
593
+ *
594
+ * An update IS an install of a different version. The pinning, the
595
+ * registry-origin bookkeeping, the already-installed short circuit —
596
+ * all of it is what an update needs, and a second code path would be
597
+ * the same operation written twice, free to disagree about any of it.
598
+ *
599
+ * Versions are REQUIRED, never defaulted to latest: the caller has
600
+ * already resolved and shown the user what it is moving to, and
601
+ * re-resolving here could land somewhere newer than they agreed to
602
+ * between the list rendering and their pressing enter.
603
+ *
604
+ * `keepRange` is what stops the write narrowing the manifest — the
605
+ * exact version drives resolution, the declared operator survives.
606
+ */
607
+ async update(targets: Array<{ name: string; version: string }>): Promise<InstallResult[]> {
608
+ return await this.install(
609
+ targets.map(target => `${target.name}@${target.version}`),
610
+ { keepRange: true },
611
+ )
612
+ },
613
+ }
614
+ }
615
+
616
+ export type InstallerT = ReturnType<typeof Installer>