@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,419 @@
1
+ import { AxonCloud, HttpError, PRODUCTION_API_BASE } from "@arcforge/cloud"
2
+ import type { AxonCloudClient, AuthSession, AuthUser, DeviceAuthorization } from "@arcforge/cloud"
3
+ import { err } from "@arcforge/err"
4
+ import type { StoreT } from "./store"
5
+ import type { ProfileRecord } from "./store/types"
6
+
7
+ type CloudOpts = {
8
+ store: StoreT
9
+ /**
10
+ * Which build this is. Production is hermetic — it pins the backend so a
11
+ * project-local .env in the caller's cwd cannot redirect an installed app
12
+ * to staging, and refuses ambient AXON_* credentials. Source development
13
+ * deliberately keeps both.
14
+ *
15
+ * Taken as the input rather than as resolved flags: the composition root
16
+ * should say WHICH BUILD this is, not decide what that implies about
17
+ * credentials — that is this leaf's own policy.
18
+ */
19
+ distribution: Distribution
20
+ }
21
+
22
+ export type Distribution = "production" | "development"
23
+
24
+ /**
25
+ * What asking the backend about a credential told us.
26
+ *
27
+ * Deliberately not a boolean: "false" conflated "the server said no" with "we
28
+ * could not reach the server", and those need opposite handling — one must
29
+ * scrub the credential and force a login, the other must preserve it.
30
+ */
31
+ export type ValidationResult = "valid" | "rejected" | "unreachable"
32
+
33
+ /** A 401 — the backend actively refused this credential, as opposed to an outage. */
34
+ function isRejection(error: unknown): boolean {
35
+ return error instanceof HttpError && error.status === 401
36
+ }
37
+
38
+ /**
39
+ * Did we fail to REACH the backend, as opposed to hearing something bad from it?
40
+ *
41
+ * Recognised POSITIVELY — only a known transport failure counts. The inverse
42
+ * ("anything that isn't an HttpError") was tempting and wrong: a malformed
43
+ * payload, a parse guard, a bug in our own code all throw plain Errors, and
44
+ * calling those "unreachable" would tell the user to check their wifi while
45
+ * the real fault went unreported. Anything unrecognised throws instead, which
46
+ * is the loud failure a genuinely unexpected error deserves.
47
+ *
48
+ * `fetch` rejects with a TypeError whose `cause` carries the OS-level code on
49
+ * DNS/connection failure; an abort surfaces as an AbortError. Those are the
50
+ * only two ways the network itself fails here.
51
+ */
52
+ const TRANSPORT_CODES = new Set([
53
+ "ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN",
54
+ "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "EPIPE", "UND_ERR_SOCKET",
55
+ ])
56
+
57
+ function isUnreachable(error: unknown): boolean {
58
+ if (error instanceof HttpError) return false // the server answered
59
+ if (error instanceof Error && error.name === "AbortError") return true
60
+ if (error instanceof TypeError) return true // fetch's own connection failure
61
+ const code = (error as { cause?: { code?: unknown } } | null)?.cause?.code
62
+ return typeof code === "string" && TRANSPORT_CODES.has(code)
63
+ }
64
+
65
+ /**
66
+ * What a distribution implies. The one place the difference is written down.
67
+ *
68
+ * Credential VALIDATION is deliberately not here. It used to be
69
+ * (`validateCredentials: false` for development), which meant a source build
70
+ * accepted any credential on disk without ever asking the backend — so a
71
+ * revoked key read as authenticated, the TUI's auth gate opened, and the user
72
+ * landed in an app that could not talk to anything. It also made the failure
73
+ * impossible to reproduce locally, which is why it survived to a user report.
74
+ *
75
+ * A credential that does not work does not work in any build. Only the things
76
+ * that are genuinely a property of the DISTRIBUTION belong in this table.
77
+ */
78
+ const POLICY = {
79
+ production: { baseUrl: PRODUCTION_API_BASE, environmentCredentials: false },
80
+ development: { baseUrl: undefined, environmentCredentials: true },
81
+ } as const satisfies Record<Distribution, {
82
+ baseUrl: string | undefined
83
+ environmentCredentials: boolean
84
+ }>
85
+
86
+ /**
87
+ * TEMP: hardcoded until a real per-user setting exists. When true, logout()
88
+ * deactivates the profile but keeps its token on disk — clicking the
89
+ * profile again can silently refresh/reuse it instead of forcing a full
90
+ * device-flow login. 2026-07-08.
91
+ */
92
+ const REMEMBER_ME = true
93
+
94
+ type LoginInput = {
95
+ /** Shown the verification step (URL + user code) — TUI renders a panel, CLI prints a line. */
96
+ /** Show the user their code. May be async — awaited before polling begins, so a caller that approves inline is picked up on the first poll. */
97
+ onCode: (authorization: DeviceAuthorization) => void | Promise<void>
98
+ /** Login hint (email) forwarded to the backend. */
99
+ hint?: string
100
+ signal?: AbortSignal
101
+ }
102
+
103
+ /**
104
+ * Cloud — a real AxonCloud client for the process lifetime, plus the disk
105
+ * wiring AxonCloud itself doesn't own: which profile is active under
106
+ * ~/.axon, and provider (BYOK) credentials.
107
+ *
108
+ * No rebuild, no identity swap at this layer — login/logout/refresh
109
+ * already mutate the client's session in place (AxonCloud's own
110
+ * contract). `client` is the real client, exposed directly; consumers use
111
+ * it exactly as they would any other AxonCloud() instance.
112
+ *
113
+ * Switching to a different on-disk profile is disk-only here — it
114
+ * changes which profile is "active" for the next Cloud() construction,
115
+ * but does not change what the live `client` is authenticated as.
116
+ * Adopting another profile's session into a live client is AxonCloud's
117
+ * concern, not this wrapper's, until it exposes a way to do so.
118
+ */
119
+ export function Cloud(opts: CloudOpts) {
120
+ const store = opts.store
121
+ const policy = POLICY[opts.distribution]
122
+
123
+ /**
124
+ * Subscribers to "the session just died mid-use".
125
+ *
126
+ * A set rather than a single callback: the TUI re-gates its UI, and other
127
+ * surfaces may want to react too. Nothing here decides WHAT happens — this
128
+ * layer only knows the credential stopped working.
129
+ */
130
+ const expiredListeners = new Set<() => void>()
131
+
132
+ function build(): AxonCloudClient {
133
+ const profile = store.profiles.current()
134
+ const session = profile ? sessionFrom(profile.record) : null
135
+
136
+ return AxonCloud({
137
+ ...(policy.baseUrl ? { baseUrl: policy.baseUrl } : {}),
138
+ ...(profile?.record.auth.apiKey ? { key: profile.record.auth.apiKey } : {}),
139
+ ...(session ? { session } : {}),
140
+ environmentCredentials: policy.environmentCredentials,
141
+ onUnauthorized: () => { void onSessionExpired() },
142
+ })
143
+ }
144
+
145
+ const client = build()
146
+
147
+ /**
148
+ * Any authenticated request came back 401 — the credential died while the
149
+ * app was running.
150
+ *
151
+ * Scrubs it and tells subscribers, so the UI can re-gate immediately
152
+ * instead of leaving the user in an app where nothing works until they
153
+ * restart. Idempotent by construction: a burst of concurrent requests all
154
+ * 401 at once, and invalidate() on an already-scrubbed profile is a no-op,
155
+ * so listeners see at most one meaningful transition.
156
+ */
157
+ async function onSessionExpired(): Promise<void> {
158
+ const profile = store.profiles.current()
159
+ if (!profile) return // already scrubbed by whichever 401 got here first
160
+
161
+ await invalidate(profile.id)
162
+ for (const listener of expiredListeners) {
163
+ try {
164
+ listener()
165
+ } catch {
166
+ // One subscriber's fault must not stop the others being told
167
+ // their session is gone.
168
+ }
169
+ }
170
+ }
171
+
172
+ async function invalidate(profileId: string): Promise<void> {
173
+ const record = store.profiles.get(profileId).record.get()
174
+ if (record) store.profiles.get(profileId).record.set({ ...record, auth: {} })
175
+ if (store.profiles.active()?.id === profileId) store.profiles.deactivate()
176
+ await client.user.auth.logout()
177
+ }
178
+
179
+ /**
180
+ * Is the active profile's credential actually usable?
181
+ *
182
+ * Three outcomes, because they demand three different responses and
183
+ * collapsing them is what let an unusable credential through the TUI's
184
+ * auth gate:
185
+ *
186
+ * valid — the backend confirmed it. Proceed.
187
+ * rejected — the backend refused it (401). The credential is scrubbed
188
+ * here; the caller must send the user through login.
189
+ * unreachable — we could not ask. The credential may be perfectly good,
190
+ * so it is NEVER destroyed — but it is equally not
191
+ * verified, and entering the app on an unverified
192
+ * credential is precisely the leak. The caller decides
193
+ * (the TUI offers a retry).
194
+ *
195
+ * Self-healing comes first: a merely STALE token is refreshed and
196
+ * re-checked before anything is called rejected, so an idle session comes
197
+ * back on its own rather than demanding a device flow the user does not
198
+ * need.
199
+ */
200
+ async function validateActive(): Promise<ValidationResult> {
201
+ const profile = store.profiles.current()
202
+ if (!profile) return "rejected"
203
+
204
+ // Stale but refreshable is the common case for a session that has sat
205
+ // idle. Try to heal it before asking the backend to judge it.
206
+ if (client.user.auth.stale) {
207
+ try {
208
+ persist(await client.user.auth.refresh())
209
+ } catch (error) {
210
+ // A refusal to refresh IS a rejection — the credential is
211
+ // spent. Anything else (offline) leaves it alone; me() below
212
+ // will report unreachable on the same outage.
213
+ if (isRejection(error)) {
214
+ await invalidate(profile.id)
215
+ return "rejected"
216
+ }
217
+ }
218
+ }
219
+
220
+ try {
221
+ const user = await client.user.auth.me()
222
+ const current = store.profiles.get(profile.id).record.get()
223
+ if (current) {
224
+ store.profiles.get(profile.id).record.set({
225
+ ...current,
226
+ user: {
227
+ id: user.id,
228
+ email: user.email,
229
+ name: user.name,
230
+ memberSince: new Date(user.memberSince).toISOString(),
231
+ },
232
+ })
233
+ }
234
+ return "valid"
235
+ } catch (error) {
236
+ if (isRejection(error)) {
237
+ await invalidate(profile.id)
238
+ return "rejected"
239
+ }
240
+ // Only a TRANSPORT failure is "unreachable". A malformed response
241
+ // or a 500 means we DID reach the backend and something is broken
242
+ // — reporting that as an outage would tell the user to check their
243
+ // connection while the real fault goes unseen. It throws.
244
+ if (!isUnreachable(error)) throw error
245
+ // Never scrubbed on an outage: a working credential must survive a
246
+ // flaky network, and the honest answer is "we do not know yet".
247
+ return "unreachable"
248
+ }
249
+ }
250
+
251
+ /** Persist a live session as the active profile — merges over any existing record (keeps apiKey). */
252
+ function persist(session: AuthSession): void {
253
+ const existing = store.profiles.get(session.user.email).record.get()
254
+ store.profiles.save(session.user.email, {
255
+ ...existing,
256
+ user: {
257
+ id: session.user.id,
258
+ email: session.user.email,
259
+ name: session.user.name,
260
+ memberSince: new Date(session.user.memberSince).toISOString(),
261
+ },
262
+ auth: {
263
+ ...existing?.auth,
264
+ accessToken: session.accessToken,
265
+ expiresAt: session.expiresAt,
266
+ },
267
+ })
268
+ }
269
+
270
+ return {
271
+ /** The real AxonCloud client — no proxying, no swap. */
272
+ client: client,
273
+
274
+ /**
275
+ * A credential EXISTS on disk for the active profile.
276
+ *
277
+ * Not "the user is logged in" — this cannot tell a live session from a
278
+ * revoked key, because it never leaves the disk. Anything gating
279
+ * access (the TUI's auth route, a CLI command that needs a backend)
280
+ * must use validate() and wait for the answer; treating this as the
281
+ * gate is what let a dead credential into the app.
282
+ */
283
+ get authenticated(): boolean {
284
+ const profile = store.profiles.current()
285
+ return !!(profile?.record.auth.accessToken || profile?.record.auth.apiKey)
286
+ },
287
+
288
+ /**
289
+ * Ask the backend whether the stored credential actually works,
290
+ * refreshing a stale one first. Scrubs it on a 401. See
291
+ * ValidationResult — an outage is NOT a rejection.
292
+ */
293
+ validate: validateActive,
294
+
295
+ /**
296
+ * Called when the credential dies MID-SESSION — any authenticated
297
+ * request 401s after boot already passed its check.
298
+ *
299
+ * The credential is scrubbed before subscribers run, so a listener
300
+ * re-reading `authenticated` sees the truth. Returns an unsubscribe.
301
+ */
302
+ onSessionExpired(listener: () => void): () => void {
303
+ expiredListeners.add(listener)
304
+ return () => expiredListeners.delete(listener)
305
+ },
306
+
307
+ /**
308
+ * Device-flow login: the package runs the wire and mutates the
309
+ * client's session in place; this persists the approved session
310
+ * as the active profile.
311
+ */
312
+ async login(input: LoginInput): Promise<AuthUser> {
313
+ const session = await client.user.auth.login({
314
+ onVerification: input.onCode,
315
+ ...(input.hint !== undefined ? { hint: input.hint } : {}),
316
+ ...(input.signal !== undefined ? { signal: input.signal } : {}),
317
+ })
318
+ persist(session)
319
+ return session.user
320
+ },
321
+
322
+ /** Exchange a stale token for a fresh one and re-persist it. Call when `client.user.auth.stale`. */
323
+ async refresh(): Promise<void> {
324
+ const session = await client.user.auth.refresh()
325
+ persist(session)
326
+ },
327
+
328
+ /**
329
+ * Deactivate the profile. With REMEMBER_ME, the token stays on disk
330
+ * — switch() can silently refresh/reuse it later instead of forcing
331
+ * a full device-flow login. Without it, auth is wiped immediately.
332
+ */
333
+ async logout(): Promise<void> {
334
+ await client.user.auth.logout()
335
+
336
+ const profile = store.profiles.current()
337
+ if (profile) {
338
+ if (!REMEMBER_ME) {
339
+ const scrubbed: ProfileRecord = { ...profile.record, auth: {} }
340
+ store.profiles.get(profile.id).record.set(scrubbed)
341
+ }
342
+ store.profiles.deactivate()
343
+ }
344
+ },
345
+
346
+ /**
347
+ * Change which on-disk profile is active AND adopt its session into
348
+ * the live `client` — same client reference throughout, real
349
+ * identity swap, no rebuild. If the stored token has since expired,
350
+ * adopts it anyway and tries one refresh before giving up — the
351
+ * common case for a REMEMBER_ME profile that's been idle a while.
352
+ * Throws if the target profile has no adoptable session at all
353
+ * (never logged in), or the refresh attempt also fails (revoked —
354
+ * caller should fall back to a full login).
355
+ */
356
+ async switch(profileId: string): Promise<void> {
357
+ const record = store.profiles.get(profileId).record.get()
358
+ if (!record) {
359
+ throw err("PROFILE_UNKNOWN", {
360
+ detail: `unknown profile: ${profileId} (known: ${store.profiles.list().join(", ") || "none"})`,
361
+ context: { profileId },
362
+ })
363
+ }
364
+
365
+ const session = sessionFrom(record)
366
+ if (!session) {
367
+ throw err("PROFILE_NOT_AUTHENTICATED", { context: { profileId } })
368
+ }
369
+
370
+ store.profiles.activate(profileId)
371
+ client.user.auth.adopt(session)
372
+
373
+ // validateActive() owns the whole ladder now — refresh a stale
374
+ // token, then verify — so this no longer refreshes by hand. Two
375
+ // copies of that sequence was how they drifted: this one refreshed
376
+ // without persisting the check, and treated an outage as a dead
377
+ // profile.
378
+ const result = await validateActive()
379
+ if (result === "rejected") {
380
+ throw err("PROFILE_NOT_AUTHENTICATED", { context: { profileId } })
381
+ }
382
+ if (result === "unreachable") {
383
+ throw err("BACKEND_UNREACHABLE", {
384
+ detail: "could not reach the backend to verify this profile — check your connection and try again",
385
+ context: { profileId },
386
+ })
387
+ }
388
+ },
389
+
390
+ /**
391
+ * Provider connections — account-level BYOK credentials held by
392
+ * the backend vault. The client runs the interactive flow (OAuth
393
+ * or key paste) and uploads the credential; nothing is persisted
394
+ * on this machine. Pure delegation to AxonCloud's vault surface.
395
+ */
396
+ connections: {
397
+ openai: client.user.vault.connections.openai,
398
+ openrouter: client.user.vault.connections.openrouter,
399
+ },
400
+ }
401
+ }
402
+
403
+ export type CloudT = ReturnType<typeof Cloud>
404
+
405
+ /** A persisted record → an adoptable session. Null when no complete session was stored. */
406
+ function sessionFrom(record: ProfileRecord): AuthSession | null {
407
+ if (!record.auth.accessToken || record.auth.expiresAt === undefined) return null
408
+ return {
409
+ accessToken: record.auth.accessToken,
410
+ expiresAt: record.auth.expiresAt,
411
+ user: {
412
+ id: record.user.id,
413
+ email: record.user.email,
414
+ name: record.user.name ?? record.user.email,
415
+ isStaff: false, // not persisted — me() refreshes identity after boot
416
+ memberSince: record.user.memberSince ? Date.parse(record.user.memberSince) : 0,
417
+ },
418
+ }
419
+ }
@@ -0,0 +1,126 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonInstance } from "@arcforge/types"
3
+ import { Dispatch, type DispatchT } from "./dispatch"
4
+ import { isControlFrame, type TuiSurface } from "./protocol"
5
+
6
+ /**
7
+ * ControlClient — the editor end of the control channel.
8
+ *
9
+ * Dials a running TUI using the port and token on its instance record.
10
+ * There is no discovery here on purpose: `Running()` already answers "what
11
+ * is running right now", and the extension already watches it. This turns
12
+ * one record into one connection, nothing more.
13
+ *
14
+ * Uses the global `WebSocket` present in both Node 18+ (the extension host)
15
+ * and Bun (the TUI), so the same module serves both ends without a `ws`
16
+ * dependency in either.
17
+ *
18
+ * Reconnection is deliberately NOT here. A TUI that exits has its record
19
+ * deleted by the registry's own GC, and the extension's existing
20
+ * `fleet.watch()` fires — so "reattach when it comes back" is a
21
+ * consequence of watching the registry, not a timer this client owns.
22
+ * Adding backoff here would create a second liveness mechanism competing
23
+ * with the one that already works.
24
+ */
25
+ export function ControlClient(opts: { handle: unknown }) {
26
+ let socket: WebSocket | null = null
27
+ let dispatch: DispatchT | null = null
28
+ let sessionId: string | null = null
29
+
30
+ return {
31
+ /** The session id this client is attached to, or null. */
32
+ get attached(): string | null {
33
+ return sessionId
34
+ },
35
+
36
+ /**
37
+ * Connect to one running instance. Resolves once the TUI has
38
+ * accepted the handshake — so a caller that awaits this knows the
39
+ * channel is live, and a rejected token fails here rather than on
40
+ * the first call.
41
+ */
42
+ connect(instance: AxonInstance): Promise<void> {
43
+ if (!instance.control) {
44
+ throw err("CONTROL_CLOSED", { detail: `${instance.sessionId} exposes no control channel`, context: { sessionId: instance.sessionId } })
45
+ }
46
+ this.disconnect()
47
+
48
+ const { port, token } = instance.control
49
+ const ws = new WebSocket(`ws://127.0.0.1:${port}`)
50
+ socket = ws
51
+
52
+ return new Promise((resolve, reject) => {
53
+ let welcomed = false
54
+
55
+ ws.onopen = () => ws.send(JSON.stringify({ type: "control.hello", token, peer: "editor" }))
56
+
57
+ ws.onmessage = event => {
58
+ let frame: unknown
59
+ try {
60
+ frame = JSON.parse(String(event.data))
61
+ } catch {
62
+ return
63
+ }
64
+
65
+ if (!welcomed) {
66
+ if ((frame as { type?: string }).type !== "control.welcome") return
67
+ welcomed = true
68
+ sessionId = instance.sessionId
69
+ dispatch = Dispatch({ handle: opts.handle, send: f => ws.send(JSON.stringify(f)) })
70
+ resolve()
71
+ return
72
+ }
73
+
74
+ if (!isControlFrame(frame)) return
75
+ dispatch?.accept(frame)
76
+ }
77
+
78
+ // A close before the welcome is a rejected handshake — the
79
+ // TUI closes with 1008 on a bad token. Surfacing it here
80
+ // means a version mismatch fails at connect, loudly, rather
81
+ // than as a silent absence of a channel nobody notices.
82
+ ws.onclose = event => {
83
+ dispatch?.close(`tui closed (${event.code})`)
84
+ dispatch = null
85
+ sessionId = null
86
+ socket = null
87
+ if (!welcomed) {
88
+ reject(
89
+ event.code === 1008
90
+ ? err("CONTROL_UNAUTHORIZED", { detail: `tui ${instance.sessionId} rejected the control token`, context: { sessionId: instance.sessionId } })
91
+ : err("CONTROL_CLOSED", { detail: `handshake failed (close ${event.code})`, context: { code: event.code } }),
92
+ )
93
+ }
94
+ }
95
+
96
+ ws.onerror = () => {
97
+ if (!welcomed) reject(err("CONTROL_CLOSED", { detail: `could not reach tui on port ${port}`, context: { port } }))
98
+ }
99
+ })
100
+ },
101
+
102
+ /**
103
+ * Call the TUI. Rejects when nothing is attached — an editor
104
+ * gesture that silently does nothing is worse than one that errors.
105
+ */
106
+ tui: {
107
+ async call<K extends keyof TuiSurface>(
108
+ method: K,
109
+ ...args: Parameters<TuiSurface[K]>
110
+ ): Promise<Awaited<ReturnType<TuiSurface[K]>>> {
111
+ if (!dispatch) throw err("CONTROL_CLOSED", { detail: `no tui attached — cannot call ${String(method)}`, context: { method: String(method) } })
112
+ return (await dispatch.call(["tui", String(method)], args)) as Awaited<ReturnType<TuiSurface[K]>>
113
+ },
114
+ },
115
+
116
+ disconnect(): void {
117
+ dispatch?.close("editor disconnecting")
118
+ dispatch = null
119
+ sessionId = null
120
+ socket?.close()
121
+ socket = null
122
+ },
123
+ }
124
+ }
125
+
126
+ export type ControlClientT = ReturnType<typeof ControlClient>