@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,246 @@
1
+ import { readFile, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { err } from "@arcforge/err"
4
+ import { text } from "./text"
5
+
6
+ /**
7
+ * The declaration arrays this leaf edits. Both hold registry names and behave
8
+ * identically — a module brings capabilities, a prompt brings work — so one set
9
+ * of surgical edits serves both.
10
+ */
11
+ export type ConfigArray = "modules" | "prompts"
12
+
13
+ type ConfigOpts = {
14
+ root: string
15
+ }
16
+
17
+ /**
18
+ * axon.config.ts — surgical edits to the agent's `modules: [...]` array.
19
+ *
20
+ * The config is the activation record: what the agent actually has. `install`
21
+ * adds an entry here the same way `npm install --save` adds to package.json,
22
+ * and for the same reason — the user should not have to hand-edit a manifest to
23
+ * finish an install they already asked for.
24
+ *
25
+ * Registry modules are referenced by STRING ("@axon/obsidian"), not by import,
26
+ * so this only ever inserts into or removes from one array literal. Source
27
+ * modules are imports and are never touched here — their declaration is the
28
+ * import statement itself, which belongs to the author.
29
+ */
30
+ export function Config(opts: ConfigOpts) {
31
+ const path = join(opts.root, "axon.config.ts")
32
+
33
+ /** Whether the config already references this module name as a string entry. */
34
+ function declares(source: string, name: string): boolean {
35
+ return new RegExp(`["']${text.escape(name)}["']`).test(source)
36
+ }
37
+
38
+ return {
39
+ path,
40
+ declares,
41
+
42
+ /** Add a registry module to `modules: [...]`, if not already declared. */
43
+ async add(name: string, key: ConfigArray = "modules"): Promise<boolean> {
44
+ const source = await readFile(path, "utf-8")
45
+ if (declares(source, name)) return false
46
+
47
+ const array = locate(source, key)
48
+ if (!array) {
49
+ // A scaffolded agent has no modules key until its first install.
50
+ // Creating it is part of installing, not something to make the
51
+ // user do by hand.
52
+ if (await insertKey(path, source, name, key)) return true
53
+
54
+ throw err("CONFIG_MODULES_UNPARSEABLE", {
55
+ detail: `could not find a "${key}: [...]" array in axon.config.ts — add "${name}" to it by hand`,
56
+ context: { name },
57
+ })
58
+ }
59
+
60
+ const body = source.slice(array.start, array.end)
61
+ const entry = `"${name}"`
62
+
63
+ // Always emit the multi-line form: an entry per line keeps
64
+ // subsequent adds and removes to a single whole line, which is what
65
+ // makes the line-oriented edits exact rather than a guess.
66
+ const existing = body.trim().replace(/,$/, "")
67
+ const lines = existing === ""
68
+ ? [entry]
69
+ : [...existing.split("\n").map(line => line.trim()).filter(Boolean), entry]
70
+
71
+ const updated = `\n${lines.map(line => `${array.indent}${line.replace(/,$/, "")},`).join("\n")}\n${array.closingIndent}`
72
+
73
+ await writeFile(path, source.slice(0, array.start) + updated + source.slice(array.end))
74
+ return true
75
+ },
76
+
77
+ /** Remove a registry module entry. Returns false when it was not declared. */
78
+ async remove(name: string): Promise<boolean> {
79
+ const source = await readFile(path, "utf-8")
80
+ if (!declares(source, name)) return false
81
+
82
+ // Drop the whole line, plus its trailing comma and newline.
83
+ const updated = source.replace(
84
+ new RegExp(`^[ \\t]*["']${text.escape(name)}["'][ \\t]*,?[ \\t]*\\r?\\n`, "m"),
85
+ "",
86
+ )
87
+ if (updated === source) {
88
+ throw err("CONFIG_MODULES_UNPARSEABLE", {
89
+ detail: `"${name}" is declared in axon.config.ts but not on a line of its own — remove it by hand`,
90
+ context: { name },
91
+ })
92
+ }
93
+
94
+ await writeFile(path, updated)
95
+ return true
96
+ },
97
+
98
+ /**
99
+ * Every registry module the config activates, by package name.
100
+ *
101
+ * Read textually, from the same `modules: [...]` span the add/remove
102
+ * edits target — this answers "what did the author declare", which is a
103
+ * property of the file, not of an evaluated blueprint. Callers that need
104
+ * the resolved module surface load a Blueprint instead.
105
+ */
106
+ async declared(key: ConfigArray = "modules"): Promise<Set<string>> {
107
+ const source = await readFile(path, "utf-8").catch(() => "")
108
+ const array = locate(source, key)
109
+ if (!array) return new Set()
110
+
111
+ const body = source.slice(array.start, array.end)
112
+ return new Set([...body.matchAll(/["'](@[^"']+)["']/g)].map(match => match[1]!))
113
+ },
114
+
115
+ /**
116
+ * Whether the config declares this module BY REGISTRY NAME — the
117
+ * string form the add/remove edits act on.
118
+ *
119
+ * False for a SOURCE module, whose declaration is an import binding
120
+ * (`import Mod from "../telegram/module.config"` plus `Mod` in the
121
+ * array) rather than a name. That is not "not installed": the agent
122
+ * loads it and it appears in the blueprint. It means this leaf cannot
123
+ * edit the declaration, because the import statement is the author's
124
+ * own code.
125
+ *
126
+ * Exists so uninstall can REFUSE before touching anything, rather
127
+ * than removing the dependency and discovering afterwards that the
128
+ * declaration is one it does not know how to remove.
129
+ */
130
+ async declaresName(name: string): Promise<boolean> {
131
+ const source = await readFile(path, "utf-8").catch(() => "")
132
+ return declares(source, name)
133
+ },
134
+
135
+ /**
136
+ * The cognet this agent declares — `cognet: "@axon/zero"` — or null
137
+ * when the key is absent.
138
+ *
139
+ * A SCALAR, which is why it cannot go through `declared()`: there is
140
+ * exactly one brain, so the declaration is a single string rather than
141
+ * an array. Null means the author never wrote the key and the agent
142
+ * runs the default; the caller decides what that default is, because
143
+ * this leaf reads the file and nothing more.
144
+ *
145
+ * Read textually for the same reason `declared()` is: this answers
146
+ * what the AUTHOR wrote, which is a property of the file. A caller
147
+ * that needs the resolved brain loads a Blueprint.
148
+ */
149
+ async cognet(): Promise<string | null> {
150
+ const source = await readFile(path, "utf-8").catch(() => "")
151
+ // Anchored to a line start so a `cognet:` inside a comment or a
152
+ // nested object cannot be mistaken for the declaration.
153
+ const match = /(^|\n)[ \t]*cognet\s*:\s*["']([^"']+)["']/.exec(source)
154
+ return match?.[2] ?? null
155
+ },
156
+ }
157
+ }
158
+
159
+ export type ConfigT = ReturnType<typeof Config>
160
+
161
+ /**
162
+ * Locate the interior of the `modules: [...]` array — the span between its
163
+ * brackets — tracking nesting so a nested array (options tuples like
164
+ * ["@axon/x", { ... }]) cannot terminate the scan early.
165
+ */
166
+ function locate(
167
+ source: string,
168
+ key: ConfigArray,
169
+ ): { start: number; end: number; indent: string; closingIndent: string } | null {
170
+ const match = new RegExp(`(^|\\n)([ \\t]*)${key}\\s*:\\s*\\[`).exec(source)
171
+ if (!match) return null
172
+
173
+ const open = match.index + match[0].length - 1
174
+ const declarationIndent = match[2] ?? ""
175
+
176
+ let depth = 0
177
+ for (let i = open; i < source.length; i++) {
178
+ const char = source[i]
179
+ if (char === "[") depth++
180
+ else if (char === "]") {
181
+ depth--
182
+ if (depth === 0) {
183
+ return {
184
+ start: open + 1,
185
+ end: i,
186
+ indent: `${declarationIndent} `,
187
+ closingIndent: declarationIndent,
188
+ }
189
+ }
190
+ }
191
+ }
192
+
193
+ return null
194
+ }
195
+
196
+ /**
197
+ * Add a `modules: [...]` key to a config that has none, immediately after
198
+ * `defineAgent({`. Returns false when even that anchor is missing, leaving the
199
+ * caller to fail loudly rather than write somewhere it guessed.
200
+ *
201
+ * Two shapes, because a config is written by a human OR by the scaffolder:
202
+ *
203
+ * defineAgent({ an object already spanning lines — insert a key
204
+ * description: "…", at the top, matching the indentation in use
205
+ * })
206
+ *
207
+ * defineAgent({}) the scaffolded config, empty and on ONE line —
208
+ * it has to be opened up before a key fits
209
+ *
210
+ * The second shape used to fall through to the error, which meant the FIRST
211
+ * `axon install` into every freshly scaffolded agent failed to record what it
212
+ * had just installed: the package landed on disk, the config never listed it,
213
+ * and the agent did not load it. Silent half-success, on the most common path
214
+ * there is. `tests/…/installer/config.test.ts` covered only multi-line
215
+ * fixtures, which is why it survived.
216
+ */
217
+ async function insertKey(path: string, source: string, name: string, key: ConfigArray): Promise<boolean> {
218
+ const entry = (indent: string) => `${indent}${key}: [\n${indent}${indent}"${name}",\n${indent}],`
219
+
220
+ // An object that is already open across lines: insert after the newline.
221
+ const open = /defineAgent\s*\(\s*\{[ \t]*\r?\n/.exec(source)
222
+ if (open) {
223
+ const at = open.index + open[0].length
224
+ // Match the indentation of whatever key already follows the brace.
225
+ const indent = /^([ \t]+)\S/m.exec(source.slice(at))?.[1] ?? " "
226
+ await writeFile(path, source.slice(0, at) + entry(indent) + "\n" + source.slice(at))
227
+ return true
228
+ }
229
+
230
+ // An EMPTY object on one line. Anything else inline (`defineAgent({ a: 1 })`)
231
+ // is left alone deliberately: rewriting a populated one-liner means
232
+ // reformatting code the author wrote, and this function's contract is to
233
+ // insert a key or decline — never to reflow.
234
+ const empty = /defineAgent\s*\(\s*\{[ \t]*\}/.exec(source)
235
+ if (empty) {
236
+ const indent = " "
237
+ const replacement = `defineAgent({\n${entry(indent)}\n}`
238
+ await writeFile(
239
+ path,
240
+ source.slice(0, empty.index) + replacement + source.slice(empty.index + empty[0].length),
241
+ )
242
+ return true
243
+ }
244
+
245
+ return false
246
+ }
@@ -0,0 +1,184 @@
1
+ import { writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { err } from "@arcforge/err"
4
+ import { fsx } from "../../../utils/fs"
5
+
6
+ /** Framework-owned variables the runtime sets. A project's .env cannot override these. */
7
+ const RESERVED = new Set([
8
+ "AGENT_ID",
9
+ "DEPLOYMENT_ID",
10
+ "OWNER_USER_ID",
11
+ "AXON_TIER",
12
+ "AXON_WARMTH",
13
+ "GCP_PROJECT_ID",
14
+ "GCP_REGION",
15
+ "AXON_SOURCE",
16
+ "AGENT_ROOT",
17
+ "AXON_API_BASE",
18
+ "AXON_JWT_PUBLIC_KEY",
19
+ "PORT",
20
+ "K_SERVICE",
21
+ "K_REVISION",
22
+ "K_CONFIGURATION",
23
+ ])
24
+
25
+ type EnvOpts = {
26
+ root: string
27
+ }
28
+
29
+ /**
30
+ * .env — the project's deployed environment.
31
+ *
32
+ * Production contract: `.env` is deployed; `.env.local` is dev-only and never
33
+ * leaves the machine.
34
+ */
35
+ export function Env(opts: EnvOpts) {
36
+ const path = join(opts.root, ".env")
37
+
38
+ return {
39
+ path,
40
+
41
+ /**
42
+ * The validated environment a deploy uploads. Throws on a malformed
43
+ * name or an attempt to override a framework-owned variable — both are
44
+ * silent-breakage shapes if allowed through.
45
+ */
46
+ async production(): Promise<Record<string, string>> {
47
+ const content = await fsx.readText(path)
48
+ if (!content) return {}
49
+
50
+ const values = parse(content)
51
+ for (const key of Object.keys(values)) {
52
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
53
+ throw err("DEPLOY_ENV_INVALID", {
54
+ detail: `.env contains invalid environment variable name "${key}"`,
55
+ context: { key },
56
+ })
57
+ }
58
+ if (RESERVED.has(key)) {
59
+ throw err("DEPLOY_ENV_RESERVED", {
60
+ detail: `.env cannot override framework-owned variable "${key}"`,
61
+ context: { key },
62
+ })
63
+ }
64
+ }
65
+ return values
66
+ },
67
+
68
+ /**
69
+ * The variable names this agent's .env defines. Names only — a caller
70
+ * listing keys must never be handed the secrets to render.
71
+ */
72
+ async keys(): Promise<string[]> {
73
+ const content = await fsx.readText(path)
74
+ return content ? Object.keys(parse(content)) : []
75
+ },
76
+
77
+ /**
78
+ * Set one variable, creating .env if absent.
79
+ *
80
+ * ── Why a line edit, not a re-serialise ─────────────────────────────
81
+ *
82
+ * The file is the user's: comments, grouping and blank lines are how
83
+ * they navigate it. Parsing to an object and writing it back would
84
+ * silently discard all of that on the first `:key set`. So an existing
85
+ * key is replaced IN PLACE, keeping its position, and a new one is
86
+ * appended.
87
+ *
88
+ * ── Validated here, not at deploy ───────────────────────────────────
89
+ *
90
+ * `production()` already refuses malformed names and framework-owned
91
+ * variables — but it refuses them at DEPLOY time, which is the worst
92
+ * moment to discover a key you set days ago was never going to work.
93
+ * The same two rules run here so the write fails at the keystroke that
94
+ * caused it.
95
+ */
96
+ async set(key: string, value: string): Promise<void> {
97
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
98
+ throw err("DEPLOY_ENV_INVALID", {
99
+ detail: `"${key}" is not a valid environment variable name`,
100
+ context: { key },
101
+ })
102
+ }
103
+ if (RESERVED.has(key)) {
104
+ throw err("DEPLOY_ENV_RESERVED", {
105
+ detail: `"${key}" is framework-owned and set by the runtime — an agent's .env cannot override it`,
106
+ context: { key },
107
+ })
108
+ }
109
+
110
+ // Quoted whenever the value could not survive a round trip bare:
111
+ // anything with whitespace (trimmed on read), a `#` (read as a
112
+ // trailing comment), or a newline.
113
+ const needsQuotes = /[\s#"']/.test(value) || value === ""
114
+ const line = needsQuotes
115
+ ? `${key}="${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`
116
+ : `${key}=${value}`
117
+
118
+ const content = await fsx.readText(path) ?? ""
119
+ // Same shape the parser accepts, so an `export `-prefixed line is
120
+ // found rather than duplicated below itself.
121
+ const existing = new RegExp(`^[ \\t]*(?:export[ \\t]+)?${key}[ \\t]*=.*$`, "m")
122
+
123
+ if (existing.test(content)) {
124
+ await writeFile(path, content.replace(existing, line))
125
+ return
126
+ }
127
+
128
+ const separator = content === "" || content.endsWith("\n") ? "" : "\n"
129
+ await writeFile(path, `${content}${separator}${line}\n`)
130
+ },
131
+
132
+ /**
133
+ * Remove a variable from the agent's .env.
134
+ *
135
+ * The inverse of `set`, and it exists for the same reason `set` does:
136
+ * disconnecting a channel has to leave the agent as it was BEFORE it was
137
+ * connected, and a credential left behind means "disconnected" is not
138
+ * true. Nothing else in the file is touched — comments, ordering and
139
+ * unrelated keys survive, because a user's .env is theirs.
140
+ *
141
+ * A key that is not present is not an error: the caller wanted it gone,
142
+ * and it is gone.
143
+ */
144
+ async unset(key: string): Promise<void> {
145
+ const content = await fsx.readText(path)
146
+ if (content === null) return
147
+
148
+ // Same shape `set` matches, including an `export ` prefix, plus its
149
+ // trailing newline so removing a line does not leave a blank one.
150
+ const existing = new RegExp(`^[ \\t]*(?:export[ \\t]+)?${key}[ \\t]*=.*$\\n?`, "m")
151
+ if (!existing.test(content)) return
152
+
153
+ await writeFile(path, content.replace(existing, ""))
154
+ },
155
+
156
+ parse: parse,
157
+ }
158
+ }
159
+
160
+ export type EnvT = ReturnType<typeof Env>
161
+
162
+ /** Parse dotenv syntax: `export` prefixes, quoted values, trailing comments. */
163
+ function parse(content: string): Record<string, string> {
164
+ const result: Record<string, string> = {}
165
+ for (const line of content.split(/\r?\n/)) {
166
+ const trimmed = line.trim()
167
+ if (!trimmed || trimmed.startsWith("#")) continue
168
+ const assignment = trimmed.startsWith("export ") ? trimmed.slice(7).trim() : trimmed
169
+ const equals = assignment.indexOf("=")
170
+ if (equals < 1) continue
171
+
172
+ const key = assignment.slice(0, equals).trim()
173
+ let value = assignment.slice(equals + 1).trim()
174
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
175
+ const quote = value[0]
176
+ value = value.slice(1, -1)
177
+ if (quote === '"') value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, "\t")
178
+ } else {
179
+ value = value.replace(/\s+#.*$/, "").trim()
180
+ }
181
+ result[key] = value
182
+ }
183
+ return result
184
+ }
@@ -0,0 +1,9 @@
1
+ // manifest — the project's declaration files on disk.
2
+ // Manifest() is the module's single entry point.
3
+
4
+ export { Manifest, type ManifestT } from "./manifest"
5
+ export type { PackageJson, PackageT } from "./package"
6
+ export type { ConfigArray, ConfigT } from "./config"
7
+ export type { ModelT, ModelSetResult } from "./model"
8
+ export type { BunfigT } from "./bunfig"
9
+ export type { EnvT } from "./env"
@@ -0,0 +1,49 @@
1
+ import { Bunfig } from "./bunfig"
2
+ import { Config } from "./config"
3
+ import { Model } from "./model"
4
+ import { Env } from "./env"
5
+ import { Package } from "./package"
6
+
7
+ type ManifestOpts = {
8
+ root: string
9
+ }
10
+
11
+ /**
12
+ * Manifest — the project's declaration files on disk.
13
+ *
14
+ * Every file that records what a project IS rather than what it has installed:
15
+ *
16
+ * package.json identity, version, declared dependencies
17
+ * axon.config.ts which modules and prompts are activated
18
+ * bunfig.toml which scopes resolve against the Axon registry
19
+ * .env the environment a deploy carries
20
+ *
21
+ * All four are files a HUMAN owns and reads, which is what unites them: every
22
+ * edit is surgical and preserves the author's formatting and comments. That is
23
+ * also the boundary — materializing node_modules is a different concern
24
+ * entirely (it shells out to Bun and moves trees around) and lives on
25
+ * Installer, which owns the installed tree.
26
+ *
27
+ * This replaced six flat files of orphan operations (dependencies, version,
28
+ * config, bunfig, env, plus a duplicated regex escape) that between them held
29
+ * four separate implementations of "read the project's package.json".
30
+ */
31
+ export function Manifest(opts: ManifestOpts) {
32
+ const root = opts.root
33
+ const pckg = Package({ root })
34
+ const config = Config({ root })
35
+ const model = Model({ root })
36
+ const bunfig = Bunfig({ root })
37
+ const env = Env({ root })
38
+
39
+ return {
40
+ root: root,
41
+ package: pckg,
42
+ config: config,
43
+ model: model,
44
+ bunfig: bunfig,
45
+ env: env,
46
+ }
47
+ }
48
+
49
+ export type ManifestT = ReturnType<typeof Manifest>
@@ -0,0 +1,124 @@
1
+ import { readFile, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import ts from "typescript"
4
+ import { err } from "@arcforge/err"
5
+ import { tsast } from "../../../utils/tsast"
6
+
7
+ /**
8
+ * axon.config.ts — the agent's `model:` field.
9
+ *
10
+ * Which model drives the cortex is the one inference decision a user makes by
11
+ * hand, and the picker edits it by machine. Both write a STRING
12
+ * (`"codex:gpt-5.6-terra"`), which is why this replaced a module that located
13
+ * an `engine: Codex({ ... })` call expression and spliced its arguments: a
14
+ * string has no arguments to reconcile, no constructor to swap, and no options
15
+ * that stop being valid when the provider changes.
16
+ *
17
+ * Located by AST and edited by byte offset, the same discipline the rest of
18
+ * this directory uses. Parsing is what makes it reliable on a config that
19
+ * nests; splicing rather than reprinting is what keeps the file the author's —
20
+ * emitting from a syntax tree would reformat their code and drop their
21
+ * comments.
22
+ */
23
+
24
+ export type ModelSetResult = {
25
+ /** False when the config already declared exactly this model. */
26
+ changed: boolean
27
+ }
28
+
29
+ type ModelOpts = {
30
+ root: string
31
+ }
32
+
33
+ export function Model(opts: ModelOpts) {
34
+ const path = join(opts.root, "axon.config.ts")
35
+
36
+ /** The `defineAgent({ ... })` object literal, or null when the config is not that shape. */
37
+ function declaration(source: ts.SourceFile): ts.ObjectLiteralExpression | null {
38
+ let found: ts.ObjectLiteralExpression | null = null
39
+
40
+ tsast.visitCalls(source, "defineAgent", call => {
41
+ if (found) return
42
+ const argument = call.arguments[0]
43
+ if (argument && ts.isObjectLiteralExpression(argument)) found = argument
44
+ })
45
+
46
+ return found
47
+ }
48
+
49
+ return {
50
+ path,
51
+
52
+ /** The declared model string, or null when the agent declares none. */
53
+ async get(): Promise<string | null> {
54
+ const text = await readFile(path, "utf-8").catch(() => null)
55
+ if (text === null) return null
56
+
57
+ const source = tsast.parse(path, text)
58
+ const object = declaration(source)
59
+ if (!object) return null
60
+
61
+ for (const property of object.properties) {
62
+ if (!ts.isPropertyAssignment(property)) continue
63
+ if (property.name.getText(source) !== "model") continue
64
+ if (!ts.isStringLiteral(property.initializer)) continue
65
+ return property.initializer.text
66
+ }
67
+ return null
68
+ },
69
+
70
+ /**
71
+ * Write the model string, adding the field when it is absent.
72
+ *
73
+ * A no-op when the value already matches, so a picker re-selecting the
74
+ * current model does not dirty the file or trigger a reload — the
75
+ * caller reads `changed` to decide whether anything needs to happen.
76
+ */
77
+ async set(model: string): Promise<ModelSetResult> {
78
+ const text = await readFile(path, "utf-8")
79
+ const source = tsast.parse(path, text)
80
+ const object = declaration(source)
81
+
82
+ if (!object) {
83
+ throw err("CONFIG_INVALID", {
84
+ detail: `${path} — no defineAgent({ ... }) call to edit`,
85
+ context: { path },
86
+ })
87
+ }
88
+
89
+ for (const property of object.properties) {
90
+ if (!ts.isPropertyAssignment(property)) continue
91
+ if (property.name.getText(source) !== "model") continue
92
+
93
+ if (ts.isStringLiteral(property.initializer) && property.initializer.text === model) {
94
+ return { changed: false }
95
+ }
96
+
97
+ const start = property.initializer.getStart(source)
98
+ const end = property.initializer.getEnd()
99
+ await writeFile(path, `${text.slice(0, start)}${JSON.stringify(model)}${text.slice(end)}`, "utf-8")
100
+ return { changed: true }
101
+ }
102
+
103
+ // No `model:` yet — insert it as the FIRST property, where a reader
104
+ // looks for what an agent runs on. Indentation is copied from the
105
+ // property it sits above rather than assumed, so this lands
106
+ // correctly in a config written with any style.
107
+ const first = object.properties[0]
108
+ const insertAt = first ? first.getStart(source) : object.getStart(source) + 1
109
+ const indent = first
110
+ ? text.slice(text.lastIndexOf("\n", insertAt) + 1, insertAt)
111
+ : " "
112
+ const suffix = first ? `,\n${indent}` : "\n"
113
+
114
+ await writeFile(
115
+ path,
116
+ `${text.slice(0, insertAt)}model: ${JSON.stringify(model)}${suffix}${text.slice(insertAt)}`,
117
+ "utf-8",
118
+ )
119
+ return { changed: true }
120
+ },
121
+ }
122
+ }
123
+
124
+ export type ModelT = ReturnType<typeof Model>