@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,10 @@
1
+ // extensions — the user's TUI config: their own main.ts and plugins/, plus
2
+ // every extension profile.config.ts enables.
3
+ //
4
+ // Extensions() is the module's single entry point.
5
+
6
+ export { Extensions, type ExtensionsT, type ExtensionsResult, type ExtensionUpdate } from "./extensions"
7
+ export { ProfileConfigFile, resolveEntry, type ResolvedEntry, type ProfileConfigResult } from "./config"
8
+ export { addEntry, addProvider, readEntries, readPolicy, readProviders, readSettings, removeEntry, removeProvider, setSetting, type EditResult } from "./edit"
9
+ export { DisposerSink, type LoadedSource, type LoadedFile } from "./load"
10
+ export { ExtensionStore, formatRef, parseRef, type ExtensionStoreT, type StoredExtension } from "./store"
@@ -0,0 +1,350 @@
1
+ import { copyFile, rm } from "node:fs/promises"
2
+ import { pathToFileURL } from "node:url"
3
+ import { dirname, extname, join } from "node:path"
4
+ import { err } from "@arcforge/err"
5
+ import type { Disposer } from "@arcforge/types"
6
+ import { fsx } from "../../utils/fs"
7
+
8
+ /**
9
+ * Filename prefix for the transient copies `importFile` evaluates.
10
+ *
11
+ * Exported because the config WATCHER must ignore them: writing one is part of
12
+ * performing a reload, so reacting to it would make every reload trigger the
13
+ * next one. Named in one place so the two cannot disagree — a rename here that
14
+ * the watcher did not learn about is an infinite reload loop.
15
+ */
16
+ export const RELOAD_PREFIX = ".axon-reload-"
17
+
18
+ /**
19
+ * How long one config file may take to evaluate before the load moves on.
20
+ *
21
+ * ── What this can and cannot do ─────────────────────────────────────────────
22
+ *
23
+ * It bounds how long a slow or hung file delays BOOT. It does not stop the
24
+ * file: JavaScript cannot interrupt code mid-execution, so a synchronous
25
+ * `while (true) {}` at module scope still owns the thread and no timer of any
26
+ * kind will fire. Nothing here pretends otherwise — the error says the load
27
+ * continued without it, not that it was cancelled.
28
+ *
29
+ * What it genuinely rescues is the common shape: a file awaiting something
30
+ * that never resolves (a fetch with no timeout, a lock, a prompt on a stream
31
+ * nobody is writing to). That yields to the event loop, so the budget fires,
32
+ * the user gets a named error pointing at the file, and the terminal boots.
33
+ *
34
+ * Generous on purpose. A config that legitimately reads a file or resolves a
35
+ * small import chain is well inside this; anything past it is not "slow", it
36
+ * is stuck, and a user waiting on a black terminal has no way to learn why.
37
+ */
38
+ const LOAD_BUDGET_MS = 10_000
39
+
40
+ /**
41
+ * Loading one source — a profile, or one extension.
42
+ *
43
+ * A "source" is a directory containing a `main.ts` and/or a `plugins/` folder.
44
+ * A profile and an extension are the same shape, which is the whole design:
45
+ * an extension is a profile's config, packaged. So one loader serves both and
46
+ * neither gets a capability the other lacks.
47
+ *
48
+ * ── Registration is a side effect of importing ──────────────────────────────
49
+ *
50
+ * There is no `setup()` and no default export to call. `commands.register(...)`
51
+ * at module scope runs as the module body evaluates, so importing the file IS
52
+ * loading it. That is what makes `main.ts` and a `plugins/` file identical to
53
+ * write, and what makes a user's own config publishable unchanged.
54
+ *
55
+ * The cost is that a file which registers nothing is indistinguishable from one
56
+ * that crashed before registering — so every failure is caught and reported per
57
+ * file rather than being allowed to look like silence.
58
+ */
59
+
60
+ /** What one file's load produced, or why it did not. */
61
+ export type LoadedFile = {
62
+ /** Absolute path to the file. */
63
+ path: string
64
+ /** Null when it loaded. An AxonError describing the failure otherwise. */
65
+ error: unknown | null
66
+ }
67
+
68
+ export type LoadedSource = {
69
+ /** Absolute directory. */
70
+ root: string
71
+ /** How this source is named in errors — a profile says "profile", an extension says its entry. */
72
+ label: string
73
+ /** Every file this source contributed, in load order. */
74
+ files: LoadedFile[]
75
+ /** Disposers registered while this source was loading, in registration order. */
76
+ disposers: Disposer[]
77
+ }
78
+
79
+ /**
80
+ * Collects the disposers a source registers while it loads.
81
+ *
82
+ * The API implementation calls `track()` from inside every `register`/`create`,
83
+ * so nothing in the contract has to be reshaped to make teardown work — a
84
+ * global `commands.register(...)` returns its disposer to the user AND hands a
85
+ * copy here, and the loader knows which source it belongs to because only one
86
+ * loads at a time.
87
+ */
88
+ export type DisposerSink = {
89
+ /** Begin attributing disposers to this source. */
90
+ open(): void
91
+ /** Stop attributing, returning everything registered since open(). */
92
+ close(): Disposer[]
93
+ /** Called by the API implementation on every registration. */
94
+ track(dispose: Disposer): void
95
+ }
96
+
97
+ export function DisposerSink(): DisposerSink {
98
+ let current: Disposer[] | null = null
99
+
100
+ return {
101
+ open(): void {
102
+ current = []
103
+ },
104
+ close(): Disposer[] {
105
+ const collected = current ?? []
106
+ current = null
107
+ return collected
108
+ },
109
+ track(dispose: Disposer): void {
110
+ // Outside a load — a registration made later from a hook or a
111
+ // command. Nothing owns it, so nothing disposes it; the caller
112
+ // holds the disposer it was returned.
113
+ current?.push(dispose)
114
+ },
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Import one file for its side effects, re-evaluating it every time.
120
+ *
121
+ * ── Why this is not `import(path + "?t=" + uuid)` ───────────────────────────
122
+ *
123
+ * That is the Node idiom, it was what this did, and under Bun it does
124
+ * NOTHING. Bun keys its ESM cache on the resolved file path and discards the
125
+ * query string, so every reload after the first was served the cached module
126
+ * and no top-level registration re-ran.
127
+ *
128
+ * The failure was silent and total: `reload()` is unload-then-load, the unload
129
+ * half worked perfectly, and the load half re-imported nothing. So a reload
130
+ * DESTROYED the user's commands, keybinds, status lines and themes and never
131
+ * brought them back — with an empty error list, because nothing threw. On a
132
+ * real profile: 11 themes registered on load, 0 on reload.
133
+ *
134
+ * A symlink does not work either — Bun resolves it with realpath, arriving at
135
+ * the same cache key. What does work is a real copy at a path nothing has
136
+ * imported before.
137
+ *
138
+ * ── Why the copy sits BESIDE the original ───────────────────────────────────
139
+ *
140
+ * The user's file may import its own siblings (`./lib`, `../shared`), and a
141
+ * relative specifier resolves against the importing file's directory. Copying
142
+ * to a temp dir would break every one of them. A dotted, uuid-named neighbour
143
+ * resolves identically to the original and is removed immediately after.
144
+ *
145
+ * `.axon-reload-*` is in the config watcher's ignore list, so writing it here
146
+ * cannot trigger the reload that is already running.
147
+ */
148
+ async function importFile(path: string): Promise<void> {
149
+ const copy = join(dirname(path), `${RELOAD_PREFIX}${crypto.randomUUID()}${extname(path)}`)
150
+ await copyFile(path, copy)
151
+ try {
152
+ await import(pathToFileURL(copy).href)
153
+ } catch (cause) {
154
+ // The copy's path is an implementation detail of reloading, and it is
155
+ // DELETED a moment later — so a stack naming it points the user at a
156
+ // file that does not exist, for an error in a file that does. Rewritten
157
+ // back to the real path, because "where is my mistake" is the entire
158
+ // value of this error.
159
+ throw restack(cause, copy, path)
160
+ } finally {
161
+ // Best-effort: a leftover copy is inert (it is ignored by the watcher
162
+ // and imported by nothing), and failing a config load over a temp file
163
+ // that would not delete is the wrong trade.
164
+ await rm(copy, { force: true }).catch(() => {})
165
+ }
166
+ }
167
+
168
+ /** What `withBudget` throws when a file outlives the budget. */
169
+ type Timeout = { axonLoadTimeout: true; error: unknown }
170
+
171
+ function isTimeout(value: unknown): value is Timeout {
172
+ return typeof value === "object" && value !== null && "axonLoadTimeout" in value
173
+ }
174
+
175
+ /**
176
+ * Run one file's import against the load budget.
177
+ *
178
+ * The import is NOT cancelled when the budget expires — it cannot be, and the
179
+ * module may still register things afterwards. What is bounded is how long the
180
+ * loader waits before reporting and moving on, which is the difference between
181
+ * a terminal that boots degraded with a named error and one that never boots
182
+ * at all.
183
+ *
184
+ * A late rejection from an abandoned import is swallowed deliberately: the
185
+ * file has already been reported as timed out, and a second error about the
186
+ * same file — arriving after the load finished, as an unhandled rejection —
187
+ * would be noise at best and a crash at worst.
188
+ */
189
+ async function withBudget<T>(path: string, run: () => Promise<T>): Promise<T> {
190
+ let timer: ReturnType<typeof setTimeout> | undefined
191
+ const budget = new Promise<never>((_, reject) => {
192
+ timer = setTimeout(() => {
193
+ reject({
194
+ axonLoadTimeout: true,
195
+ error: err("EXTENSION_LOAD_TIMEOUT", {
196
+ detail: `${path} did not finish loading within ${LOAD_BUDGET_MS / 1000}s`,
197
+ context: { path, budgetMs: LOAD_BUDGET_MS },
198
+ }),
199
+ } satisfies Timeout)
200
+ }, LOAD_BUDGET_MS)
201
+ })
202
+
203
+ const attempt = run()
204
+ // Attached before the race so an import that rejects AFTER losing it does
205
+ // not surface as an unhandled rejection.
206
+ attempt.catch(() => {})
207
+
208
+ try {
209
+ return await Promise.race([attempt, budget])
210
+ } finally {
211
+ clearTimeout(timer)
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Point an error's message and stack back at the file the user actually wrote.
217
+ *
218
+ * Mutates rather than wrapping: the cause is handed to the caller as-is and
219
+ * rendered by whoever reports it, so a wrapper would have to be unwrapped by
220
+ * every reader to find the real message. Both fields are rewritten because
221
+ * Bun puts the path in each, and a message still naming the temp copy is the
222
+ * half a user reads first.
223
+ */
224
+ function restack(cause: unknown, from: string, to: string): unknown {
225
+ if (typeof cause !== "object" || cause === null) return cause
226
+ const swap = (text: string): string => text.split(from).join(to)
227
+
228
+ // Bun reports an unresolvable import as a `ResolveMessage`, which is NOT
229
+ // an Error and whose text comes from engine-internal state: assigning
230
+ // `.message` appears to succeed and changes nothing that any reader sees
231
+ // (`String(e)` still names the copy), and it carries the path a second
232
+ // time in `.referrer`. A typo'd `./sibling` is the most common config
233
+ // mistake there is, so this cannot be left pointing at a deleted file.
234
+ //
235
+ // Converted to a real Error rather than patched: it is the only way the
236
+ // corrected text survives every way a caller might render it.
237
+ const named = cause as { name?: unknown; message?: unknown; stack?: unknown }
238
+ if (named.name === "ResolveMessage") {
239
+ const rebuilt = new Error(swap(String(cause)))
240
+ rebuilt.name = "ResolveMessage"
241
+ // The original stays reachable for anything that wants the structured
242
+ // fields (`specifier`, `importKind`) — nothing is discarded, only the
243
+ // rendering is corrected.
244
+ rebuilt.cause = cause
245
+ return rebuilt
246
+ }
247
+
248
+ try {
249
+ if (typeof named.message === "string") named.message = swap(named.message)
250
+ if (typeof named.stack === "string") named.stack = swap(named.stack)
251
+ } catch {
252
+ // A frozen or getter-only value — nothing to rewrite, and the original
253
+ // is still more useful than failing here. Rethrown unchanged.
254
+ }
255
+ return cause
256
+ }
257
+
258
+ /** Every `.ts` in `plugins/`, alphabetical. Missing folder → nothing. */
259
+ async function pluginFiles(root: string): Promise<string[]> {
260
+ const dir = join(root, "plugins")
261
+ if (!fsx.exists(dir)) return []
262
+
263
+ const names = await fsx.list(dir)
264
+ return names
265
+ .filter(name => name.endsWith(".ts"))
266
+ .sort()
267
+ .map(name => join(dir, name))
268
+ }
269
+
270
+ type LoadSourceOpts = {
271
+ root: string
272
+ label: string
273
+ sink: DisposerSink
274
+ /** Which error names a failing main.ts — a profile's and an extension's differ. */
275
+ mainError: "PROFILE_MAIN_FAILED" | "EXTENSION_LOAD_FAILED"
276
+ }
277
+
278
+ /**
279
+ * Load one source: `main.ts`, then every file in `plugins/` alphabetically.
280
+ *
281
+ * ── Per-file containment ────────────────────────────────────────────────────
282
+ *
283
+ * A throwing file disables ITSELF and nothing else. Its siblings still load,
284
+ * and whatever it registered before throwing stays registered — a partially
285
+ * loaded file is not rolled back, because the registrations that succeeded are
286
+ * real and removing them would surprise a user whose command exists in a file
287
+ * that later has a typo.
288
+ *
289
+ * The alternative — failing the whole source — is more predictable but punishes
290
+ * far more: one bad plugin would cost a user every command in their config, at
291
+ * the exact moment they need the terminal to go fix it.
292
+ *
293
+ * ORDER is main.ts first, deliberately. It is the file a user thinks of as
294
+ * their config, and the one that may `import "./keybindings"` — so anything it
295
+ * pulls in is registered before any plugin hook can fire.
296
+ */
297
+ export async function loadSource(opts: LoadSourceOpts): Promise<LoadedSource> {
298
+ const { root, label, sink, mainError } = opts
299
+
300
+ sink.open()
301
+ const files: LoadedFile[] = []
302
+
303
+ /** Import one file under the budget, recording success or the reason not. */
304
+ async function loadFile(path: string, failure: "PROFILE_MAIN_FAILED" | "EXTENSION_LOAD_FAILED" | "PLUGIN_FAILED"): Promise<void> {
305
+ try {
306
+ await withBudget(path, () => importFile(path))
307
+ files.push({ path, error: null })
308
+ } catch (cause) {
309
+ if (isTimeout(cause)) {
310
+ files.push({ path, error: cause.error })
311
+ return
312
+ }
313
+ files.push({
314
+ path,
315
+ error: err(failure, {
316
+ detail: `${path} — ${cause instanceof Error ? cause.message : String(cause)}`,
317
+ context: { path, source: label },
318
+ cause,
319
+ }),
320
+ })
321
+ }
322
+ }
323
+
324
+ const main = join(root, "main.ts")
325
+ if (fsx.exists(main)) await loadFile(main, mainError)
326
+
327
+ for (const path of await pluginFiles(root)) await loadFile(path, "PLUGIN_FAILED")
328
+
329
+ return { root, label, files, disposers: sink.close() }
330
+ }
331
+
332
+ /**
333
+ * Undo one source's registrations.
334
+ *
335
+ * Reverse order, so a disposer registered later cannot depend on state a
336
+ * disposer registered earlier has already torn down. A throwing disposer must
337
+ * not strand the rest — teardown runs to completion and reports nothing, since
338
+ * there is no user action to take about a failed unregistration.
339
+ */
340
+ export function disposeSource(source: LoadedSource): void {
341
+ for (const dispose of [...source.disposers].reverse()) {
342
+ try {
343
+ dispose()
344
+ } catch {
345
+ // Deliberately swallowed. Teardown is bookkeeping the user did not
346
+ // ask for; a failure here is ours, and reporting it during a reload
347
+ // would blame them for it. The remaining disposers still run.
348
+ }
349
+ }
350
+ }
@@ -0,0 +1,189 @@
1
+ import ts from "typescript"
2
+ import { join } from "node:path"
3
+ import { readFileSync, readdirSync } from "node:fs"
4
+ import { fsx } from "../../utils/fs"
5
+ import { tsast } from "../../utils/tsast"
6
+
7
+ /**
8
+ * What a config REGISTERS, read from its source without running it.
9
+ *
10
+ * ── Why static analysis rather than asking the runtime ──────────────────────
11
+ *
12
+ * Types are generated on disk, before a terminal boots — and the whole point
13
+ * is that an editor completes `components.create("me:uptime")` while you are
14
+ * writing the line that uses it. Asking the live TUI what it registered would
15
+ * mean types that only exist once the thing is running, which is exactly
16
+ * backwards.
17
+ *
18
+ * ── Literal arguments only, deliberately ────────────────────────────────────
19
+ *
20
+ * `components.create(name, …)` where `name` is a variable cannot be seen, and
21
+ * that is fine: the name it resolves to is not knowable at generation time
22
+ * either. Every union this feeds keeps a `(string & {})` arm for exactly that
23
+ * case, so a computed name still typechecks — it simply does not complete.
24
+ *
25
+ * A parse, not a program: only the shape of the call site matters, so there is
26
+ * no need for `ts.createProgram` and its type checker. That keeps this fast
27
+ * enough to run on every config reload rather than only on prepare.
28
+ */
29
+
30
+ /** One registered name, with whatever documentation sat above the call. */
31
+ export type Registration = {
32
+ name: string
33
+ /** JSDoc from immediately above the call site, if any. */
34
+ description?: string
35
+ }
36
+
37
+ /** Everything one source contributes to the ambient surface. */
38
+ export type Registrations = {
39
+ components: Registration[]
40
+ lines: Registration[]
41
+ palettes: Registration[]
42
+ /** Command paths, space-joined — `["git", "push"]` reads as "git push". */
43
+ commands: Registration[]
44
+ }
45
+
46
+ export function emptyRegistrations(): Registrations {
47
+ return { components: [], lines: [], palettes: [], commands: [] }
48
+ }
49
+
50
+ /**
51
+ * The call sites worth reading, as `object.method` → which bucket it fills.
52
+ *
53
+ * A table rather than a chain of conditionals: adding a surface is adding a
54
+ * row, and the walker below never grows.
55
+ */
56
+ const CALLS: Record<string, keyof Registrations> = {
57
+ "components.create": "components",
58
+ "lines.create": "lines",
59
+ "palette.create": "palettes",
60
+ "commands.register": "commands",
61
+ }
62
+
63
+ /**
64
+ * A call's first argument as a name, or null when it is not a literal.
65
+ *
66
+ * `commands.register` takes a path that may be an array — `["git", "push"]` is
67
+ * one command called "git push", which is how the tree renders it and how
68
+ * `commands.run()` addresses it.
69
+ */
70
+ function nameOf(arg: ts.Expression): string | null {
71
+ if (ts.isStringLiteralLike(arg)) return arg.text
72
+
73
+ if (ts.isArrayLiteralExpression(arg)) {
74
+ const parts: string[] = []
75
+ for (const element of arg.elements) {
76
+ if (!ts.isStringLiteralLike(element)) return null
77
+ parts.push(element.text)
78
+ }
79
+ return parts.length > 0 ? parts.join(" ") : null
80
+ }
81
+
82
+ return null
83
+ }
84
+
85
+ /** Read one file's registrations. Unreadable or unparseable files contribute nothing. */
86
+ export function readRegistrations(filePath: string): Registrations {
87
+ const out = emptyRegistrations()
88
+
89
+ let source: string
90
+ try {
91
+ source = readFileSync(filePath, "utf-8")
92
+ } catch {
93
+ // A file that cannot be read is a file that registers nothing. The
94
+ // loader reports its own failures; this is not the place to duplicate
95
+ // that, and throwing here would cost every OTHER source its types.
96
+ return out
97
+ }
98
+
99
+ const file = tsast.parse(filePath, source)
100
+
101
+ const visit = (node: ts.Node): void => {
102
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
103
+ const target = `${node.expression.expression.getText(file)}.${node.expression.name.getText(file)}`
104
+ const bucket = CALLS[target]
105
+ const first = node.arguments[0]
106
+
107
+ if (bucket && first) {
108
+ const name = nameOf(first)
109
+ if (name !== null) {
110
+ // The JSDoc is read from the STATEMENT, not the call: a
111
+ // comment sits above `components.create(...)` as a whole,
112
+ // and asking the call node returns nothing.
113
+ const statement = findStatement(node)
114
+ // Trimmed: tsast.jsdoc preserves the leading space after
115
+ // the `*`, which would land inside the generated `/** */`
116
+ // and read as an indent nobody wrote.
117
+ const description = statement ? tsast.jsdoc(statement, file)?.trim() : undefined
118
+ out[bucket].push({ name, ...(description ? { description } : {}) })
119
+ }
120
+ }
121
+ }
122
+ ts.forEachChild(node, visit)
123
+ }
124
+
125
+ visit(file)
126
+ return out
127
+ }
128
+
129
+ /** Walk up to the statement a call belongs to — where its JSDoc lives. */
130
+ function findStatement(node: ts.Node): ts.Node | undefined {
131
+ let current: ts.Node | undefined = node
132
+ while (current && !ts.isSourceFile(current.parent)) current = current.parent
133
+ return current
134
+ }
135
+
136
+ /**
137
+ * Every registration under one source root — `main.ts` plus `plugins/*.ts`.
138
+ *
139
+ * The same files the loader imports, and in the same order, so what an editor
140
+ * completes matches what actually registers. A source with neither is not an
141
+ * error: an extension may be all config and no code.
142
+ */
143
+ export function scanSource(root: string): Registrations {
144
+ const out = emptyRegistrations()
145
+
146
+ const files: string[] = []
147
+ const main = join(root, "main.ts")
148
+ if (fsx.exists(main)) files.push(main)
149
+
150
+ // Sync, because typegen is: the generator writes files inline and an async
151
+ // hop here would make every caller await for one directory read.
152
+ const pluginsDir = join(root, "plugins")
153
+ if (fsx.exists(pluginsDir)) {
154
+ for (const entry of readdirSync(pluginsDir).sort()) {
155
+ if (entry.endsWith(".ts") && !entry.endsWith(".d.ts")) files.push(join(pluginsDir, entry))
156
+ }
157
+ }
158
+
159
+ for (const file of files) {
160
+ const found = readRegistrations(file)
161
+ out.components.push(...found.components)
162
+ out.lines.push(...found.lines)
163
+ out.palettes.push(...found.palettes)
164
+ out.commands.push(...found.commands)
165
+ }
166
+
167
+ return out
168
+ }
169
+
170
+ /** Merge several sources' registrations into one, first-registered wins on a duplicate name. */
171
+ export function mergeRegistrations(all: readonly Registrations[]): Registrations {
172
+ const out = emptyRegistrations()
173
+
174
+ for (const key of ["components", "lines", "palettes", "commands"] as const) {
175
+ const seen = new Set<string>()
176
+ for (const source of all) {
177
+ for (const entry of source[key]) {
178
+ // First wins, matching the loader: a user's own config loads
179
+ // before extensions, and between extensions the earlier one in
180
+ // profile.config.ts keeps the name.
181
+ if (seen.has(entry.name)) continue
182
+ seen.add(entry.name)
183
+ out[key].push(entry)
184
+ }
185
+ }
186
+ }
187
+
188
+ return out
189
+ }