@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,398 @@
1
+ import ts from "typescript"
2
+ import { err } from "@arcforge/err"
3
+
4
+ /**
5
+ * Resolve every type an exported tool signature names, and render each one's
6
+ * declaration text for inlining into the agent's scope.
7
+ *
8
+ * THE RULE THIS IMPLEMENTS: the author's declaration is the contract. What
9
+ * they wrote in the signature is what the model is shown — this module has no
10
+ * opinion on whether a shape was a good idea, only on whether it can be
11
+ * rendered faithfully. A scan fails when a named type genuinely cannot be
12
+ * resolved, and at no other time.
13
+ *
14
+ * WHY THE CHECKER AND NOT THE EMITTED TEXT. The previous resolver collected
15
+ * declarations by walking the emitted `.d.ts` for top-level `interface`/`type`
16
+ * nodes and decided what was referenced with a `\bName\b` regex over the
17
+ * declaration string. That approach is structurally incapable of answering the
18
+ * questions authors actually ask of it, because none of them are answerable
19
+ * from declaration text:
20
+ *
21
+ * - `export type { RecallResponse } from "@vectorize-io/hindsight-client"`
22
+ * emits verbatim and declares nothing locally, so the re-export was
23
+ * invisible and the error told the author to write the line their source
24
+ * already had.
25
+ * - `Pick<Response, "items">` and `Response["items"]` keep the parent name in
26
+ * the emitted text, so narrowing an external type — the very pattern worth
27
+ * encouraging — failed.
28
+ * - An UNANNOTATED tool returning the same external type passed, because tsc
29
+ * emits `import("pkg").Response` and no bare identifier ever appears. The
30
+ * gate rewarded deleting type annotations, and the laundered form was
31
+ * strictly worse for the model: same type, now opaque.
32
+ * - A resolved type's own field types were never followed, so `type Big = {
33
+ * b: Deep }` inlined `Big` and left `Deep` dangling in the model's context.
34
+ *
35
+ * Asking the checker collapses all four into one implementation: walk the type
36
+ * the checker actually resolved, collect the declaration behind every symbol
37
+ * encountered, recurse. They stop being edge cases and become consequences.
38
+ *
39
+ * TERMINATION. Following a type graph must stop somewhere or it inlines half of
40
+ * lib.dom.d.ts. Lib types (`Date`, `Array`, `Promise`, primitives) are leaves —
41
+ * the model already knows them and their declarations are enormous. Everything
42
+ * else is followed until it bottoms out, with a seen-set carrying recursion
43
+ * (`type Node = { children: Node[] }` resolves to one declaration, not a hang).
44
+ */
45
+
46
+ /** One resolved type: its name, and the declaration text to inline. */
47
+ export type ResolvedType = {
48
+ name: string
49
+ /** Declaration text with `export`/`declare` stripped — inlined into an ambient block. */
50
+ text: string
51
+ }
52
+
53
+ export type ResolveOpts = {
54
+ checker: ts.TypeChecker
55
+ /** The tool file being declared, named in any error raised. */
56
+ fileName: string
57
+ }
58
+
59
+ /**
60
+ * Symbols whose declarations must never be inlined.
61
+ *
62
+ * These are the leaves of the walk. A lib type is one TypeScript itself
63
+ * declares — the model knows `Date` and `Array` without being told, and
64
+ * `lib.es5.d.ts`'s `Array<T>` declaration alone is several hundred lines.
65
+ */
66
+ function isLibSymbol(symbol: ts.Symbol): boolean {
67
+ const declarations = symbol.getDeclarations()
68
+ if (!declarations || declarations.length === 0) return true
69
+ // ANY declaration in a lib file makes this a leaf, not every one.
70
+ //
71
+ // `Array` is declared across lib.es5, lib.es2015.core, lib.es2015.iterable
72
+ // and more — TypeScript merges them into one symbol. An `.every()` test
73
+ // therefore answered false the moment a single declaration sat in a file
74
+ // the predicate did not recognise, and the walk inlined the entire
75
+ // `interface Array<T>` — hundreds of lines of methods — into the model's
76
+ // context. Global types are global: one lib declaration is proof enough.
77
+ return declarations.some(d => isLibFile(d.getSourceFile()))
78
+ }
79
+
80
+ /** True for one of TypeScript's own lib.*.d.ts files. */
81
+ function isLibFile(file: ts.SourceFile): boolean {
82
+ return file.hasNoDefaultLib
83
+ || /[\\/]typescript[\\/]lib[\\/]lib\.[^\\/]*\.d\.ts$/.test(file.fileName)
84
+ || /[\\/]typescript[\\/]lib[\\/]lib\.d\.ts$/.test(file.fileName)
85
+ }
86
+
87
+ /**
88
+ * Strip the module-level markers from a declaration so it can be inlined.
89
+ *
90
+ * Both consumers (the model's `<scope>` block and tool-globals.d.ts) drop these
91
+ * into an ambient `declare global` context, where `export` is meaningless and a
92
+ * nested `declare` is a syntax error (TS1038).
93
+ */
94
+ function inlineable(text: string): string {
95
+ return text.trim().replace(/^export\s+default\s+/, "").replace(/^export\s+/, "").replace(/^declare\s+/, "")
96
+ }
97
+
98
+ /**
99
+ * The declaration node to render for a symbol, following aliases.
100
+ *
101
+ * An `export { X } from "pkg"` / `import type { X }` binding resolves to an
102
+ * ALIAS symbol whose own declaration is the import statement, not the type. The
103
+ * text of that statement is useless to the model — it names a module the agent
104
+ * cannot resolve. `getAliasedSymbol` walks to the real declaration, which is
105
+ * what makes a re-exported package type render as its actual shape.
106
+ */
107
+ function targetSymbol(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol {
108
+ if ((symbol.flags & ts.SymbolFlags.Alias) === 0) return symbol
109
+ try {
110
+ const aliased = checker.getAliasedSymbol(symbol)
111
+ return aliased.getDeclarations()?.length ? aliased : symbol
112
+ } catch {
113
+ // getAliasedSymbol throws on a symbol that is not actually an alias
114
+ // target (a malformed or unresolvable import). Falling back to the
115
+ // symbol itself is correct: the caller then finds no renderable
116
+ // declaration and fails loudly, which is the right outcome for an
117
+ // import that does not resolve.
118
+ return symbol
119
+ }
120
+ }
121
+
122
+ /** The node whose text is the type's declaration, or undefined if it has none worth inlining. */
123
+ function declarationNode(symbol: ts.Symbol): ts.Declaration | undefined {
124
+ const declarations = symbol.getDeclarations() ?? []
125
+ for (const declaration of declarations) {
126
+ if (
127
+ ts.isInterfaceDeclaration(declaration)
128
+ || ts.isTypeAliasDeclaration(declaration)
129
+ || ts.isClassDeclaration(declaration)
130
+ || ts.isEnumDeclaration(declaration)
131
+ ) {
132
+ return declaration
133
+ }
134
+ }
135
+ return undefined
136
+ }
137
+
138
+ /**
139
+ * Every type-name identifier inside a declaration, as the CHECKER resolves it.
140
+ *
141
+ * This is the recursion step, and it is deliberately syntactic-walk +
142
+ * checker-lookup rather than a walk over `ts.Type`. A `ts.Type` has already
143
+ * been normalized — `Pick<R, "a">` becomes an anonymous object type and the
144
+ * name `R` is gone — but the text being inlined still SAYS `Pick<R, "a">`, so
145
+ * the model needs `R`. Walking the syntax keeps rendered text and collected
146
+ * types in agreement, which is the invariant that matters: every name in an
147
+ * inlined declaration must itself be inlined.
148
+ */
149
+ function referencedSymbols(node: ts.Node, checker: ts.TypeChecker): ts.Symbol[] {
150
+ const found: ts.Symbol[] = []
151
+
152
+ function visit(current: ts.Node): void {
153
+ // An `export { T } from "…"` specifier IS the reference — its name is a
154
+ // plain identifier, not a type-reference node, so the type-position
155
+ // cases below never see it. This is the form an author uses to say "this
156
+ // package type is part of what I expose", and honouring it is the whole
157
+ // point of accepting the re-export.
158
+ if (ts.isExportSpecifier(current)) {
159
+ const symbol = checker.getSymbolAtLocation(current.name)
160
+ if (symbol) found.push(symbol)
161
+ return
162
+ }
163
+ // The NAME of the declaration itself is not a reference to anything.
164
+ if (ts.isTypeReferenceNode(current)) {
165
+ const name = ts.isQualifiedName(current.typeName) ? current.typeName.right : current.typeName
166
+ const symbol = checker.getSymbolAtLocation(name)
167
+ if (symbol) found.push(symbol)
168
+ } else if (ts.isExpressionWithTypeArguments(current) && ts.isIdentifier(current.expression)) {
169
+ // `interface A extends B` / `class A implements B` — B is a real
170
+ // reference the model needs, and it is not a TypeReferenceNode.
171
+ const symbol = checker.getSymbolAtLocation(current.expression)
172
+ if (symbol) found.push(symbol)
173
+ } else if (ts.isTypeQueryNode(current)) {
174
+ // `typeof x` — the thing being queried is referenced.
175
+ const name = ts.isQualifiedName(current.exprName) ? current.exprName.right : current.exprName
176
+ const symbol = checker.getSymbolAtLocation(name)
177
+ if (symbol) found.push(symbol)
178
+ }
179
+ ts.forEachChild(current, visit)
180
+ }
181
+
182
+ // Skip the declaration's own name so `type Node = ...` does not resolve
183
+ // itself as a reference on the first step.
184
+ ts.forEachChild(node, child => {
185
+ if ((ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node)) && child === node.name) return
186
+ visit(child)
187
+ })
188
+
189
+ return found
190
+ }
191
+
192
+ /**
193
+ * Resolve one entry point — a type name appearing in an exported signature —
194
+ * and everything it transitively names.
195
+ *
196
+ * `seen` is shared across every entry point in a file so a type referenced by
197
+ * two tools is collected once, and so a cycle terminates.
198
+ */
199
+ function collect(symbol: ts.Symbol, opts: ResolveOpts, seen: Map<ts.Symbol, ResolvedType | null>, out: ResolvedType[]): void {
200
+ const target = targetSymbol(symbol, opts.checker)
201
+ if (seen.has(target)) return
202
+
203
+ if (isLibSymbol(target)) {
204
+ // A leaf. Recorded so a second encounter does not re-walk it.
205
+ seen.set(target, null)
206
+ return
207
+ }
208
+
209
+ const declaration = declarationNode(target)
210
+ if (!declaration) {
211
+ // Not a type the model needs (a value import, a namespace), or a type
212
+ // with no renderable declaration. Type PARAMETERS land here too and are
213
+ // correctly skipped — `T` in `id<T>(x: T): T` is bound by the signature
214
+ // that carries it, not a type to inline.
215
+ seen.set(target, null)
216
+ return
217
+ }
218
+
219
+ // Reserve the slot BEFORE recursing so a self-referential type
220
+ // (`type Node = { children: Node[] }`) terminates on its own name.
221
+ seen.set(target, null)
222
+
223
+ const source = declaration.getSourceFile()
224
+ const resolved: ResolvedType = {
225
+ name: target.getName(),
226
+ text: inlineable(declaration.getFullText(source).replace(/^\s*\/\*\*[\s\S]*?\*\/\s*/, "")),
227
+ }
228
+ seen.set(target, resolved)
229
+ out.push(resolved)
230
+
231
+ for (const referenced of referencedSymbols(declaration, opts.checker)) {
232
+ collect(referenced, opts, seen, out)
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Every type named by the given signature nodes, transitively, ready to inline.
238
+ *
239
+ * Order is first-encountered, which puts a tool's own top-level types ahead of
240
+ * the internals they reference — the order a reader (and a model) wants.
241
+ */
242
+ export function resolveSignatureTypes(nodes: ts.Node[], opts: ResolveOpts): ResolvedType[] {
243
+ const seen = new Map<ts.Symbol, ResolvedType | null>()
244
+ const out: ResolvedType[] = []
245
+
246
+ for (const node of nodes) {
247
+ // An export specifier is itself the reference; everything else is a
248
+ // container whose type positions are walked.
249
+ if (ts.isExportSpecifier(node)) {
250
+ const symbol = opts.checker.getSymbolAtLocation(node.name)
251
+ if (symbol) collect(symbol, opts, seen, out)
252
+ continue
253
+ }
254
+ for (const symbol of referencedSymbols(node, opts.checker)) {
255
+ collect(symbol, opts, seen, out)
256
+ }
257
+ }
258
+
259
+ return out
260
+ }
261
+
262
+ /**
263
+ * Fail on any type name in a rendered declaration with nothing behind it.
264
+ *
265
+ * The invariant every consumer depends on: a name the model reads in a
266
+ * signature resolves to a declaration in the same context block. A dangling
267
+ * name is the silent-wrong-output failure this whole seam exists to prevent —
268
+ * the model reads `Promise<Roll>` with no `Roll` anywhere and the editor block
269
+ * does not compile.
270
+ *
271
+ * Checked against RENDERED text rather than the symbol walk because that is
272
+ * what actually ships. If the two ever disagree, the text is the thing the
273
+ * model sees, so the text is what must be verified.
274
+ */
275
+ export function assertNoDanglingTypes(declarations: string[], resolved: ResolvedType[], fileName: string): void {
276
+ const known = new Set(resolved.map(r => r.name))
277
+
278
+ for (const declaration of declarations) {
279
+ // Parse the rendered declaration and check every type name it uses.
280
+ //
281
+ // A regex over the text cannot do this job: it cannot tell a type
282
+ // position from a parameter name or a property key, and it would reject
283
+ // `opts` as readily as `Missing`. Parsing gives exact type positions,
284
+ // which is what makes it safe to fail on what is left.
285
+ for (const name of typeNamesIn(declaration)) {
286
+ if (known.has(name) || isGlobalTypeName(name)) continue
287
+ throw err("TOOL_DECLARE_FAILED", {
288
+ detail: `type "${name}" is used in an exported signature but has no resolvable definition`
289
+ + ` — re-export it (\`export type { ${name} } from "…"\`) so the agent can read the type it is given`,
290
+ context: { file: fileName, type: name },
291
+ })
292
+ }
293
+
294
+ for (const match of declaration.matchAll(/\bimport\(["'][^"']+["']\)\s*\.\s*(\w+)/g)) {
295
+ const name = match[1] ?? ""
296
+ // An unresolved `import("pkg").Type` is the laundered-inference
297
+ // failure: the author omitted an annotation, tsc emitted a module
298
+ // path, and the model gets a name it cannot resolve. If the walk
299
+ // DID resolve it, the declaration is fine and only its spelling
300
+ // needs rewriting (see rewriteImportPaths) — this is the case where
301
+ // it did not.
302
+ if (!known.has(name)) {
303
+ throw err("TOOL_DECLARE_FAILED", {
304
+ detail: `type "${name}" is used in an exported signature but its definition does not travel with the tool`
305
+ + ` — re-export it (\`export type { ${name} } from "…"\`) so the agent can read the type it is given`,
306
+ context: { file: fileName, type: name },
307
+ })
308
+ }
309
+ }
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Rewrite `import("pkg").Type` to the bare `Type` the resolved set declares.
315
+ *
316
+ * tsc emits a module path whenever a type reaches a signature without a local
317
+ * name — most often an unannotated return whose type came from an import. The
318
+ * path is correct TypeScript and useless output: the model cannot resolve the
319
+ * specifier, and the generated tool-globals.d.ts would need the package on disk
320
+ * to compile. Since the walk has already collected the declaration and it is
321
+ * inlined alongside, the bare name is both shorter and actually resolvable.
322
+ *
323
+ * Only names present in `resolved` are rewritten. Anything else is left exactly
324
+ * as tsc wrote it so assertNoDanglingTypes can see and report it.
325
+ */
326
+ export function rewriteImportPaths(declaration: string, resolved: ResolvedType[]): string {
327
+ const known = new Set(resolved.map(r => r.name))
328
+ return declaration.replace(/\bimport\(["'][^"']+["']\)\s*\.\s*(\w+)/g, (whole, name: string) =>
329
+ known.has(name) ? name : whole,
330
+ )
331
+ }
332
+
333
+ /**
334
+ * Every identifier used in a TYPE POSITION inside a rendered declaration.
335
+ *
336
+ * Parsed, not matched. The declaration is wrapped in `declare` and read as a
337
+ * .d.ts so the compiler's own parser marks the type positions — the same
338
+ * distinction a regex cannot make, which is why the old resolver's
339
+ * `\bName\b` test could not be trusted to decide anything.
340
+ *
341
+ * Type PARAMETERS are excluded: `T` in `function id<T>(x: T): T` is bound by
342
+ * the signature carrying it, so it is resolvable without being inlined.
343
+ */
344
+ function typeNamesIn(declaration: string): string[] {
345
+ const src = ts.createSourceFile("d.d.ts", `declare ${declaration};`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
346
+ const names: string[] = []
347
+ const bound = new Set<string>()
348
+
349
+ function visit(node: ts.Node): void {
350
+ if (ts.isTypeParameterDeclaration(node)) bound.add(node.name.getText(src))
351
+ if (ts.isTypeReferenceNode(node)) {
352
+ // Only the LEFTMOST name of a qualified reference is a lookup;
353
+ // `A.B` resolves B within A, so B is not independently declared.
354
+ const root = ts.isQualifiedName(node.typeName) ? leftmost(node.typeName) : node.typeName
355
+ names.push(root.getText(src))
356
+ }
357
+ ts.forEachChild(node, visit)
358
+ }
359
+ visit(src)
360
+
361
+ return names.filter(name => !bound.has(name))
362
+ }
363
+
364
+ function leftmost(name: ts.QualifiedName): ts.Identifier {
365
+ let current: ts.EntityName = name
366
+ while (ts.isQualifiedName(current)) current = current.left
367
+ return current
368
+ }
369
+
370
+ /**
371
+ * Type names that resolve without travelling with the tool.
372
+ *
373
+ * These are the leaves isLibSymbol() refused to inline, named again on the text
374
+ * side. The two must agree: a type skipped as a lib global during the walk and
375
+ * then rejected as dangling here would fail every tool that mentions `Date`.
376
+ *
377
+ * Deliberately a fixed list rather than a checker query. This runs over
378
+ * RENDERED TEXT, which has no program behind it — and the set of globals a tool
379
+ * signature can legitimately name is small, stable, and worth stating outright
380
+ * rather than inferring.
381
+ */
382
+ const GLOBAL_TYPE_NAMES = new Set([
383
+ "Array", "ReadonlyArray", "Promise", "PromiseLike", "Date", "RegExp", "Error", "Map", "Set",
384
+ "WeakMap", "WeakSet", "Record", "Partial", "Required", "Readonly", "Pick", "Omit", "Exclude",
385
+ "Extract", "NonNullable", "ReturnType", "Parameters", "Awaited", "InstanceType", "ThisType",
386
+ "Iterable", "IterableIterator", "AsyncIterable", "AsyncIterableIterator", "Iterator",
387
+ "ArrayBuffer", "SharedArrayBuffer", "DataView", "Uint8Array", "Uint16Array", "Uint32Array",
388
+ "Int8Array", "Int16Array", "Int32Array", "Float32Array", "Float64Array", "BigInt64Array",
389
+ "BigUint64Array", "Function", "Object", "String", "Number", "Boolean", "Symbol", "BigInt",
390
+ "JSON", "Math", "Generator", "AsyncGenerator", "Buffer", "URL", "URLSearchParams", "Blob",
391
+ "File", "FormData", "Headers", "Request", "Response", "AbortSignal", "ReadableStream",
392
+ "WritableStream", "TransformStream", "Uppercase", "Lowercase", "Capitalize", "Uncapitalize",
393
+ "NoInfer", "Intl",
394
+ ])
395
+
396
+ function isGlobalTypeName(name: string): boolean {
397
+ return GLOBAL_TYPE_NAMES.has(name)
398
+ }
@@ -0,0 +1,109 @@
1
+ import { join } from "node:path"
2
+ import type { AxonRoute } from "@arcforge/types"
3
+ import { err } from "@arcforge/err"
4
+ import { fsx } from "../../../utils/fs"
5
+ import type { Scanned } from "../types"
6
+ import { installH3Globals } from "./h3-globals"
7
+
8
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const
9
+ type Method = (typeof METHODS)[number]
10
+
11
+ /**
12
+ * Routes — server/api/ of ONE root. Filename convention:
13
+ * hello.get.ts → GET /api/hello · users/[id].post.ts → POST /api/users/[id]
14
+ * chat.ws.ts → WS /api/chat · hello.ts → ANY /api/hello
15
+ * Module routes come from Modules() running this scanner per module root.
16
+ *
17
+ * This scanner IMPORTS each route file to resolve its handler — the
18
+ * blueprint contract requires resolved handlers so the runtime mounts
19
+ * as-is and never touches the filesystem. A route file that fails to
20
+ * import or lacks a default-export handler is a warning, not a route.
21
+ */
22
+ /**
23
+ * Whether a file the author wrote that cannot be READ is fatal.
24
+ *
25
+ * True for an agent's own source: the agent is defined by what its author
26
+ * wrote, so silently running a subset of it produces an agent nobody asked
27
+ * for. Invalid state, and invalid states crash.
28
+ *
29
+ * False for a MODULE's, and that is the whole distinction: an agent that
30
+ * installed a broken module is not an invalid agent — it is the agent it was
31
+ * before the install. Crashing the runtime over one dependency leaves the user
32
+ * unable to boot the terminal they need in order to remove it.
33
+ *
34
+ * Degrading was previously rejected because a warning "reached nobody at
35
+ * runtime" — true then, since build:warning classified as debug and was hidden
36
+ * at default verbosity. It is now info-level and renders as its own card, and
37
+ * a module's failure additionally reaches the MODEL through scope.unavailable.
38
+ *
39
+ * Defaults to true: a caller that has not thought about it gets the strict
40
+ * behaviour, and only the module scanner opts out.
41
+ */
42
+ export async function Routes(root: string, opts: { required?: boolean } = {}): Promise<Scanned<AxonRoute>> {
43
+ const entries: AxonRoute[] = []
44
+ const warnings: Scanned<AxonRoute>["warnings"] = []
45
+
46
+ installH3Globals()
47
+
48
+ for (const { absPath, relPath } of await fsx.walk(join(root, "server", "api"))) {
49
+ const parsed = parseRouteFile(relPath)
50
+ if (!parsed) continue
51
+
52
+ try {
53
+ const mod = (await import(absPath)) as { default?: unknown }
54
+ if (typeof mod.default !== "function") {
55
+ warnings.push({ domain: "routes", error: `${absPath} has no default-export handler — skipped` })
56
+ continue
57
+ }
58
+ entries.push({
59
+ method: parsed.method,
60
+ path: parsed.path,
61
+ handler: mod.default as AxonRoute["handler"],
62
+ file: absPath,
63
+ })
64
+ } catch (cause) {
65
+ // A route that will not import means the agent serves an endpoint
66
+ // set that is not the declared one — a caller gets a 404 for a file
67
+ // sitting in server/api/. Fatal for the agent's own routes, and a
68
+ // reported gap for a module's.
69
+ const failure = err("ROUTE_LOAD_FAILED", {
70
+ detail: `${absPath} — ${cause instanceof Error ? cause.message : String(cause)}`,
71
+ context: { file: absPath },
72
+ cause,
73
+ })
74
+ // Strict for an agent's own files, degraded for a module's.
75
+ // Per FILE: one unreadable script skips that script, never the
76
+ // rest of the directory beside it.
77
+ if (opts.required !== false) throw failure
78
+ warnings.push({ domain: "routes", error: failure.message, cause: failure })
79
+ continue
80
+ }
81
+ }
82
+
83
+ return { entries, warnings }
84
+ }
85
+
86
+ export function parseRouteFile(relPath: string): { method: Method | "ANY" | "WS"; path: string } | null {
87
+ if (!relPath.endsWith(".ts") || relPath.endsWith(".test.ts")) return null
88
+
89
+ const segments = relPath.replace(/\\/g, "/").slice(0, -3).split("/")
90
+ const last = segments[segments.length - 1]!
91
+ const dotParts = last.split(".")
92
+ const suffix = dotParts[dotParts.length - 1]!.toUpperCase()
93
+
94
+ let method: Method | "ANY" | "WS"
95
+ let base: string
96
+
97
+ if (suffix === "WS") {
98
+ method = "WS"
99
+ base = dotParts.slice(0, -1).join(".")
100
+ } else if (METHODS.includes(suffix as Method)) {
101
+ method = suffix as Method
102
+ base = dotParts.slice(0, -1).join(".")
103
+ } else {
104
+ method = "ANY"
105
+ base = last
106
+ }
107
+
108
+ return { method, path: "/api/" + [...segments.slice(0, -1), base].join("/") }
109
+ }
@@ -0,0 +1,119 @@
1
+ import { join } from "node:path"
2
+ import type { AxonScript } from "@arcforge/types"
3
+ import { err } from "@arcforge/err"
4
+ import { fsx } from "../../../utils/fs"
5
+ import type { Scanned } from "../types"
6
+
7
+ /**
8
+ * `typescript` is ~175ms of module evaluation, and importing it here made
9
+ * every consumer of the blueprint pay that at IMPORT time — before knowing
10
+ * whether the agent has a single script to analyse. Together with the Vue
11
+ * toolchain behind vstr it was the whole of a ~460ms import cost that ran
12
+ * ahead of any actual work.
13
+ *
14
+ * Loaded on first use and memoised: an agent with scripts pays it once, an
15
+ * agent without never loads the compiler at all. `tsast` rides the same gate
16
+ * because it is a thin wrapper over the same module.
17
+ */
18
+ type TsModule = typeof import("typescript")
19
+ type TsastModule = typeof import("../../../utils/tsast")
20
+
21
+ let toolchain: Promise<{ ts: TsModule; tsast: TsastModule["tsast"] }> | null = null
22
+ function loadToolchain() {
23
+ toolchain ??= Promise.all([import("typescript"), import("../../../utils/tsast")])
24
+ .then(([tsMod, tsastMod]) => ({ ts: tsMod.default, tsast: tsastMod.tsast }))
25
+ return toolchain
26
+ }
27
+
28
+ /**
29
+ * Scripts — src/scripts/*.ts. Args come from the defineArgs<{...}>() type
30
+ * argument; description from the file-leading JSDoc. Static analysis only.
31
+ */
32
+ /**
33
+ * Whether a file the author wrote that cannot be READ is fatal.
34
+ *
35
+ * True for an agent's own source: the agent is defined by what its author
36
+ * wrote, so silently running a subset of it produces an agent nobody asked
37
+ * for. Invalid state, and invalid states crash.
38
+ *
39
+ * False for a MODULE's, and that is the whole distinction: an agent that
40
+ * installed a broken module is not an invalid agent — it is the agent it was
41
+ * before the install. Crashing the runtime over one dependency leaves the user
42
+ * unable to boot the terminal they need in order to remove it.
43
+ *
44
+ * Degrading was previously rejected because a warning "reached nobody at
45
+ * runtime" — true then, since build:warning classified as debug and was hidden
46
+ * at default verbosity. It is now info-level and renders as its own card, and
47
+ * a module's failure additionally reaches the MODEL through scope.unavailable.
48
+ *
49
+ * Defaults to true: a caller that has not thought about it gets the strict
50
+ * behaviour, and only the module scanner opts out.
51
+ */
52
+ export async function Scripts(root: string, opts: { prefix?: string; required?: boolean } = {}): Promise<Scanned<AxonScript>> {
53
+ const scriptsDir = join(root, "src", "scripts")
54
+ const entries: AxonScript[] = []
55
+ const warnings: Scanned<AxonScript>["warnings"] = []
56
+
57
+ for (const file of await fsx.list(scriptsDir)) {
58
+ if (!file.endsWith(".ts") || file.endsWith(".test.ts")) continue
59
+ const filePath = join(scriptsDir, file)
60
+ const name = file.slice(0, -3)
61
+ const prefixed = opts?.prefix ? `${opts.prefix}:${name}` : name
62
+
63
+ try {
64
+ const source = (await fsx.readText(filePath)) ?? ""
65
+ const { ts, tsast } = await loadToolchain()
66
+ const args = extractDefineArgs(ts, tsast, filePath, source)
67
+ const description = tsast.leadingDescription(source)
68
+ entries.push({
69
+ name: prefixed,
70
+ filePath,
71
+ ...(description !== undefined ? { description } : {}),
72
+ ...(args.length > 0 ? { args } : {}),
73
+ })
74
+ } catch (error) {
75
+ // A script that cannot be processed means `axon run <name>` reports
76
+ // it as not found while its file sits in src/scripts/. Fatal for
77
+ // the agent's own scripts, and a reported gap for a module's.
78
+ const failure = err("SCRIPT_LOAD_FAILED", {
79
+ detail: `${filePath} — ${error instanceof Error ? error.message : String(error)}`,
80
+ context: { file: filePath },
81
+ cause: error,
82
+ })
83
+ // Strict for an agent's own files, degraded for a module's.
84
+ // Per FILE: one unreadable script skips that script, never the
85
+ // rest of the directory beside it.
86
+ if (opts.required !== false) throw failure
87
+ warnings.push({ domain: "scripts", error: failure.message, cause: failure })
88
+ continue
89
+ }
90
+ }
91
+
92
+ return { entries, warnings }
93
+ }
94
+
95
+ function extractDefineArgs(
96
+ ts: TsModule,
97
+ tsast: TsastModule["tsast"],
98
+ filePath: string,
99
+ source: string,
100
+ ): Array<{ name: string; type: string; required?: boolean }> {
101
+ const src = tsast.parse(filePath, source)
102
+ const args: Array<{ name: string; type: string; required?: boolean }> = []
103
+
104
+ tsast.visitCalls(src, "defineArgs", call => {
105
+ const typeArg = call.typeArguments?.[0]
106
+ if (!typeArg || !ts.isTypeLiteralNode(typeArg)) return
107
+ for (const member of typeArg.members) {
108
+ if (ts.isPropertySignature(member) && ts.isIdentifier(member.name)) {
109
+ args.push({
110
+ name: member.name.text,
111
+ type: member.type ? member.type.getText(src) : "unknown",
112
+ required: !member.questionToken,
113
+ })
114
+ }
115
+ }
116
+ })
117
+
118
+ return args
119
+ }