@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,156 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { ControlFrame, RpcCall, RpcPath, RpcResult, RpcSubscribe, RpcUnsubscribe } from "./protocol"
3
+
4
+ type Send = (frame: ControlFrame) => void
5
+
6
+ /** Walk a property path off root, throwing with the path spelled out if any segment is missing. */
7
+ function resolve(root: unknown, path: RpcPath): unknown {
8
+ let target: unknown = root
9
+ for (const key of path) {
10
+ if (target === null || typeof target !== "object" || !(key in target)) {
11
+ throw err("CONTROL_PATH_NOT_FOUND", { detail: `no such method on the peer: ${path.join(".")}`, context: { path: path.join(".") } })
12
+ }
13
+ target = (target as Record<string, unknown>)[key]
14
+ }
15
+ return target
16
+ }
17
+
18
+ /**
19
+ * Dispatch — one end of the control channel.
20
+ *
21
+ * Symmetric by construction: it serves inbound calls against a local
22
+ * handle AND issues outbound calls to the peer, because both ends do both.
23
+ * The TUI driving the editor and the editor driving the TUI are one
24
+ * implementation used twice, not two features.
25
+ *
26
+ * Holds the channel's only state — pending outbound calls and live inbound
27
+ * subscriptions — so that `close()` can settle every promise a caller is
28
+ * still awaiting. A peer that vanishes mid-call must reject, never hang:
29
+ * this is a cross-process socket, and the caller has no other way to learn
30
+ * the TUI just died.
31
+ */
32
+ export function Dispatch(opts: { handle: unknown; send: Send }) {
33
+ /** Outbound: calls we are awaiting an answer to. */
34
+ const pending = new Map<string, { resolve: (value: unknown) => void; reject: (cause: unknown) => void }>()
35
+ /** Inbound: subscriptions the peer opened against our handle. */
36
+ const serving = new Map<string, () => void>()
37
+ /** Outbound: listeners we registered on the peer. */
38
+ const listening = new Map<string, (value: unknown) => void>()
39
+
40
+ let closed = false
41
+ let counter = 0
42
+ const nextId = (): string => `${++counter}`
43
+
44
+ /**
45
+ * Serve one inbound call. Never throws outward — a failure becomes an
46
+ * ok:false result, because the peer is across a socket and has no stack
47
+ * to catch into. The CALLER is responsible for checking `ok`; see
48
+ * `call()`, which rejects rather than returning a falsy value, so a
49
+ * failure cannot be mistaken for a result.
50
+ */
51
+ async function serveCall(frame: RpcCall): Promise<void> {
52
+ try {
53
+ const parent = resolve(opts.handle, frame.path.slice(0, -1))
54
+ const method = resolve(opts.handle, frame.path)
55
+ if (typeof method !== "function") throw err("CONTROL_PATH_NOT_CALLABLE", { detail: `not callable on the peer: ${frame.path.join(".")}`, context: { path: frame.path.join(".") } })
56
+ const value = await (method as (...args: unknown[]) => unknown).apply(parent, frame.args)
57
+ opts.send({ type: "rpc.result", id: frame.id, ok: true, value })
58
+ } catch (cause) {
59
+ opts.send({
60
+ type: "rpc.result",
61
+ id: frame.id,
62
+ ok: false,
63
+ error: cause instanceof Error ? cause.message : String(cause),
64
+ })
65
+ }
66
+ }
67
+
68
+ /** Serve one inbound subscribe, adapting the local `.watch()` into rpc.event frames. */
69
+ function serveSubscribe(frame: RpcSubscribe): void {
70
+ try {
71
+ const parent = resolve(opts.handle, frame.path.slice(0, -1))
72
+ const method = resolve(opts.handle, frame.path)
73
+ if (typeof method !== "function") throw err("CONTROL_PATH_NOT_CALLABLE", { detail: `not callable on the peer: ${frame.path.join(".")}`, context: { path: frame.path.join(".") } })
74
+ const listener = (value: unknown) => opts.send({ type: "rpc.event", id: frame.id, value })
75
+ const teardown = (method as (...args: unknown[]) => () => void).apply(parent, [...frame.args, listener])
76
+ serving.set(frame.id, teardown)
77
+ } catch (cause) {
78
+ // A subscription that failed to start still owes the caller an
79
+ // answer — otherwise it waits forever on a stream that will
80
+ // never produce a frame.
81
+ opts.send({
82
+ type: "rpc.result",
83
+ id: frame.id,
84
+ ok: false,
85
+ error: cause instanceof Error ? cause.message : String(cause),
86
+ })
87
+ }
88
+ }
89
+
90
+ function serveUnsubscribe(frame: RpcUnsubscribe): void {
91
+ serving.get(frame.id)?.()
92
+ serving.delete(frame.id)
93
+ }
94
+
95
+ function settle(frame: RpcResult): void {
96
+ const waiter = pending.get(frame.id)
97
+ if (!waiter) return
98
+ pending.delete(frame.id)
99
+ if (frame.ok) waiter.resolve(frame.value)
100
+ else waiter.reject(err("CONTROL_CALL_FAILED", { detail: frame.error, context: { error: frame.error } }))
101
+ }
102
+
103
+ return {
104
+ /** Feed one decoded frame in. The transport owns bytes; this owns meaning. */
105
+ accept(frame: ControlFrame): void {
106
+ if (frame.type === "rpc.call") return void serveCall(frame)
107
+ if (frame.type === "rpc.subscribe") return serveSubscribe(frame)
108
+ if (frame.type === "rpc.unsubscribe") return serveUnsubscribe(frame)
109
+ if (frame.type === "rpc.result") return settle(frame)
110
+ listening.get(frame.id)?.(frame.value)
111
+ },
112
+
113
+ /**
114
+ * Call a method on the PEER's handle. Rejects on failure — a remote
115
+ * error is an error here, so `await peer.call(...)` fails loudly at
116
+ * the call site instead of quietly returning undefined.
117
+ */
118
+ call(path: RpcPath, args: unknown[] = []): Promise<unknown> {
119
+ if (closed) return Promise.reject(err("CONTROL_CLOSED", { detail: `channel closed before ${path.join(".")} could be sent`, context: { path: path.join(".") } }))
120
+ const id = nextId()
121
+ return new Promise((resolve, reject) => {
122
+ pending.set(id, { resolve, reject })
123
+ opts.send({ type: "rpc.call", id, path, args })
124
+ })
125
+ },
126
+
127
+ /** Subscribe to a stream on the peer's handle. Returns the teardown. */
128
+ subscribe(path: RpcPath, args: unknown[], listener: (value: unknown) => void): () => void {
129
+ if (closed) throw err("CONTROL_CLOSED", { detail: `channel closed before ${path.join(".")} could be sent`, context: { path: path.join(".") } })
130
+ const id = nextId()
131
+ listening.set(id, listener)
132
+ opts.send({ type: "rpc.subscribe", id, path, args })
133
+ return () => {
134
+ if (!listening.delete(id)) return
135
+ if (!closed) opts.send({ type: "rpc.unsubscribe", id })
136
+ }
137
+ },
138
+
139
+ /**
140
+ * Tear down both directions. Every in-flight outbound call rejects:
141
+ * the peer is gone and no answer is coming, so leaving those
142
+ * promises pending would hang the caller forever.
143
+ */
144
+ close(cause: string): void {
145
+ if (closed) return
146
+ closed = true
147
+ for (const teardown of serving.values()) teardown()
148
+ serving.clear()
149
+ listening.clear()
150
+ for (const waiter of pending.values()) waiter.reject(err("CONTROL_CLOSED", { detail: cause, context: { error: cause } }))
151
+ pending.clear()
152
+ },
153
+ }
154
+ }
155
+
156
+ export type DispatchT = ReturnType<typeof Dispatch>
@@ -0,0 +1,17 @@
1
+ export { ControlServer, type ControlServerT } from "./server"
2
+ export { ControlClient, type ControlClientT } from "./client"
3
+ export { Dispatch, type DispatchT } from "./dispatch"
4
+ export type {
5
+ CapsuleRunOutcome,
6
+ ControlFrame,
7
+ ControlHandshake,
8
+ ControlPeer,
9
+ EditorSurface,
10
+ RpcCall,
11
+ RpcEvent,
12
+ RpcPath,
13
+ RpcResult,
14
+ RpcSubscribe,
15
+ RpcUnsubscribe,
16
+ TuiSurface,
17
+ } from "./protocol"
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The control channel's wire vocabulary — the one file both ends agree on.
3
+ *
4
+ * These frames are lifted verbatim from the Fleet webview bridge
5
+ * (`apps/fleet/shared/protocol.ts`), which already proved the shape over
6
+ * postMessage: a call carries the property PATH walked to reach a method,
7
+ * and the receiver resolves that path against whatever handle it chose to
8
+ * expose. Adding a verb to either side never touches this file — only
9
+ * domain code changes. That property is why the same frames now serve a
10
+ * second transport instead of a second vocabulary being invented for it.
11
+ *
12
+ * The channel is symmetric by construction. There is no "client frame" and
13
+ * "server frame": both ends send calls and both ends answer them, because
14
+ * the requirement is a TUI that drives the editor AND an editor that drives
15
+ * the TUI. Direction is a property of who holds which handle, not of the
16
+ * protocol.
17
+ */
18
+
19
+ /** The property path walked to reach a method on the peer's exposed handle. */
20
+ export type RpcPath = string[]
21
+
22
+ export type RpcCall = { type: "rpc.call"; id: string; path: RpcPath; args: unknown[] }
23
+
24
+ export type RpcResult =
25
+ | { type: "rpc.result"; id: string; ok: true; value: unknown }
26
+ | { type: "rpc.result"; id: string; ok: false; error: string }
27
+
28
+ /**
29
+ * Subscriptions — the counterpart for live streams (a session tail, the
30
+ * fleet list) that are not one request and one response. The resolved
31
+ * method must accept a listener and return a teardown function, which is
32
+ * the shape every platform leaf's `.watch()` already follows.
33
+ */
34
+ export type RpcSubscribe = { type: "rpc.subscribe"; id: string; path: RpcPath; args: unknown[] }
35
+ export type RpcUnsubscribe = { type: "rpc.unsubscribe"; id: string }
36
+ export type RpcEvent = { type: "rpc.event"; id: string; value: unknown }
37
+
38
+ /** Every frame that can cross the socket, in either direction. */
39
+ export type ControlFrame = RpcCall | RpcResult | RpcSubscribe | RpcUnsubscribe | RpcEvent
40
+
41
+ /**
42
+ * The handshake. Sent as the first frame by the dialling side, before any
43
+ * call. The token is read from the instance record, which lives in a 0700
44
+ * directory — the file mode guards the secret, the token guards the socket.
45
+ *
46
+ * A listening port is reachable by any local process regardless of file
47
+ * mode, which is precisely why this exists and why the file-based design
48
+ * this replaced did not need it.
49
+ */
50
+ export type ControlHello = { type: "control.hello"; token: string; peer: ControlPeer }
51
+
52
+ /** Accepted. Carries what the peer is, so each side knows what it may call. */
53
+ export type ControlWelcome = { type: "control.welcome"; peer: ControlPeer }
54
+
55
+ export type ControlPeer = "tui" | "editor"
56
+
57
+ export type ControlHandshake = ControlHello | ControlWelcome
58
+
59
+ export function isControlFrame(value: unknown): value is ControlFrame {
60
+ if (typeof value !== "object" || value === null) return false
61
+ const type = (value as { type?: unknown }).type
62
+ return (
63
+ type === "rpc.call" ||
64
+ type === "rpc.result" ||
65
+ type === "rpc.subscribe" ||
66
+ type === "rpc.unsubscribe" ||
67
+ type === "rpc.event"
68
+ )
69
+ }
70
+
71
+ /**
72
+ * What the TUI exposes to the editor, and what the editor exposes to the
73
+ * TUI. Declared here rather than inferred from either implementation
74
+ * because this is a cross-process seam: both sides compile against it, and
75
+ * a method appearing on one end that the other cannot call is a bug the
76
+ * type system should catch rather than a runtime "path not found".
77
+ *
78
+ * These are the v1 surfaces — deliberately small. The point of the first
79
+ * iteration is to prove the channel end to end with one real verb in each
80
+ * direction, not to guess the full API before either side has driven it.
81
+ */
82
+
83
+ /** Called BY the tui, implemented BY the editor extension. */
84
+ export type EditorSurface = {
85
+ /**
86
+ * Bring the Axon console panel forward, optionally landing on a
87
+ * specific instance and tab. This is the verb that motivated the whole
88
+ * channel: the agent decides something is worth watching and puts it
89
+ * in front of the human.
90
+ */
91
+ focus(target: { sessionId?: string; tab?: string }): Promise<void>
92
+ /** Open an absolute path in a real editor tab. A directory reveals in the Explorer. */
93
+ open(path: string, options?: { line?: number; beside?: boolean }): Promise<void>
94
+
95
+ /**
96
+ * Open one of the agent's runtime panes as an editor buffer, pinned to
97
+ * a run — the editor's own "pop out" gesture, invoked from the TUI.
98
+ *
99
+ * `source` is a live instance id or a session .jsonl path, the same two
100
+ * things every log-reading verb accepts, so a finished run and a
101
+ * running one open identically.
102
+ */
103
+ buffer(kind: "events" | "trace" | "engine" | "logs", source: string): Promise<void>
104
+
105
+ /**
106
+ * How good a target this window is, and how recently it was focused.
107
+ *
108
+ * Windows are NOT interchangeable: each has different folders open, so
109
+ * only some can act meaningfully on a given path. This is how the TUI
110
+ * routes without guessing — it asks every attached editor and takes
111
+ * the best answer, rather than tracking which window is "current" from
112
+ * the outside, where that truth does not live.
113
+ *
114
+ * `path` null means "not about anything in particular", and only
115
+ * recency ranks.
116
+ */
117
+ claim(path: string | null): Promise<{ contains: boolean; focusedAt: number }>
118
+ }
119
+
120
+ /**
121
+ * One capsule execution's outcome, flattened for the wire.
122
+ *
123
+ * A structural copy of the kernel's AxonRunResult minus `scope` (bindings
124
+ * are only meaningful to a caller rendering a template, which no editor
125
+ * does) — declared here rather than imported so this file stays the one
126
+ * thing both processes agree on, with no dependency on kernel internals.
127
+ */
128
+ export type CapsuleRunOutcome = {
129
+ ok: boolean
130
+ value?: unknown
131
+ stdout: string[]
132
+ error?: { kind: "timeout" | "interrupt" | "exception"; message: string }
133
+ }
134
+
135
+ /** Called BY the editor extension, implemented BY the tui. */
136
+ export type TuiSurface = {
137
+ /** Send a message to the focused agent, as if typed into the composer. */
138
+ send(content: string): Promise<void>
139
+ /** Interrupt the focused agent's current run. */
140
+ interrupt(): Promise<void>
141
+
142
+ /**
143
+ * Execute TypeScript in one agent's capsule — the developer backdoor
144
+ * behind Fleet's capsule input.
145
+ *
146
+ * PROVENANCE, NOT PRIVILEGE. This is the same verb the agent's own
147
+ * reasoning uses, through the same kernel and the same policy gate: a
148
+ * developer cannot reach anything the agent could not, and a denied
149
+ * call is denied here identically. What differs is that the command is
150
+ * stamped `origin: "host"` so the session log never claims the agent
151
+ * did it.
152
+ *
153
+ * Addressed by sessionId rather than run against "the focused agent",
154
+ * unlike send/interrupt: those are conversation gestures aimed at
155
+ * whatever the human is looking at, while this one names the machine
156
+ * whose global scope it is about to mutate. Picking the wrong one
157
+ * silently is not an acceptable failure mode for code execution.
158
+ */
159
+ capsule(sessionId: string, code: string): Promise<CapsuleRunOutcome>
160
+
161
+ /**
162
+ * Bring one agent's conversation forward in this TUI.
163
+ *
164
+ * Any TUI can view any live instance by switching, so this needs no
165
+ * routing on the caller's side beyond picking a TUI — which is what
166
+ * `lastActiveAt` below is for.
167
+ */
168
+ focus(sessionId: string): Promise<void>
169
+
170
+ /**
171
+ * When this TUI last had human input, epoch ms.
172
+ *
173
+ * The counterpart to EditorSurface.claim, and the same principle: the
174
+ * caller cannot see which terminal has focus (VS Code exposes the
175
+ * terminal, not the process inside it), so it asks each TUI about
176
+ * itself instead of inferring from the outside.
177
+ */
178
+ lastActiveAt(): Promise<number>
179
+ }
@@ -0,0 +1,241 @@
1
+ import { err } from "@arcforge/err"
2
+ import { randomBytes } from "node:crypto"
3
+ import { Dispatch, type DispatchT } from "./dispatch"
4
+ import { isControlFrame, type ControlHello, type EditorSurface } from "./protocol"
5
+
6
+ /**
7
+ * ControlServer — the TUI end of the control channel.
8
+ *
9
+ * Listens on an ephemeral port and mints a token, both of which the caller
10
+ * writes into its `AxonInstance` record. That record is the discovery
11
+ * mechanism: `Running()` already scans it, pid-checks it, GCs it and
12
+ * watches it, so the channel inherits liveness for free and needs no
13
+ * announce protocol of its own. The port dies with the process, which is
14
+ * exactly the fact the pid check already proves — so publishing it does not
15
+ * weaken the registry's invariant that every field is either true for the
16
+ * life of the process or absent.
17
+ *
18
+ * Auth is a token rather than file permissions because a listening port is
19
+ * reachable by any local process regardless of how the store is chmod'd.
20
+ * The 0700 store guards the secret; the token guards the socket.
21
+ *
22
+ * MANY editors may attach at once, and that is load-bearing rather than
23
+ * incidental. A user with two windows open has two valid targets for
24
+ * "open this session log", and they are not interchangeable — each has
25
+ * different folders open, so only one can act meaningfully on a given
26
+ * path. Holding one connection would force the TUI to guess; holding all
27
+ * of them lets it ASK (`editor.claim`) and route to the best answer.
28
+ *
29
+ * A peer that dies takes its own entry with it: the socket close handler
30
+ * is the only thing that removes one, so there is no liveness bookkeeping
31
+ * beyond what the transport already proves.
32
+ */
33
+ export function ControlServer(opts: { handle: unknown; port?: number }) {
34
+ const token = randomBytes(32).toString("hex")
35
+
36
+ let server: ReturnType<typeof Bun.serve> | null = null
37
+
38
+ /**
39
+ * Membership listeners. A UI that gates on "is an editor attached" needs to
40
+ * re-render when that flips, and polling `peerCount` would mean either a
41
+ * timer or a missed change — the socket already knows the exact moment.
42
+ */
43
+ const watchers = new Set<(count: number) => void>()
44
+ function announce(): void {
45
+ for (const watcher of watchers) watcher(peers.size)
46
+ }
47
+
48
+ /**
49
+ * Every attached editor, keyed by its socket. One dispatcher each —
50
+ * ids are per-connection, so two windows' calls can never collide.
51
+ */
52
+ type Peer = { socket: { send(data: string): void; close(): void }; dispatch: DispatchT }
53
+ const peers = new Map<unknown, Peer>()
54
+
55
+ function drop(key: unknown, cause: string): void {
56
+ const found = peers.get(key)
57
+ if (!found) return
58
+ found.dispatch.close(cause)
59
+ peers.delete(key)
60
+ announce()
61
+ }
62
+
63
+ /**
64
+ * The editor to send to. One attached peer is not a choice; several
65
+ * are polled and ranked.
66
+ *
67
+ * A peer that fails to answer is dropped from the running rather than
68
+ * failing the whole call — an editor mid-reload should not stop a
69
+ * healthy window from receiving the message.
70
+ */
71
+ async function pick(path?: string): Promise<DispatchT> {
72
+ const attached = [...peers.values()]
73
+ if (attached.length === 0) {
74
+ throw err("CONTROL_CLOSED", { detail: "no editor attached" })
75
+ }
76
+ if (attached.length === 1) return attached[0]!.dispatch
77
+
78
+ const ranked = await Promise.all(attached.map(async peer => {
79
+ try {
80
+ const claim = await peer.dispatch.call(["editor", "claim"], [path ?? null]) as {
81
+ contains?: boolean
82
+ focusedAt?: number
83
+ }
84
+ return { dispatch: peer.dispatch, contains: claim?.contains === true, focusedAt: claim?.focusedAt ?? 0 }
85
+ } catch {
86
+ return { dispatch: peer.dispatch, contains: false, focusedAt: 0 }
87
+ }
88
+ }))
89
+
90
+ // Containment first — it is the difference between useful and
91
+ // useless — then recency of focus.
92
+ ranked.sort((left, right) =>
93
+ left.contains !== right.contains ? (left.contains ? -1 : 1) : right.focusedAt - left.focusedAt,
94
+ )
95
+ return ranked[0]!.dispatch
96
+ }
97
+
98
+ return {
99
+ token,
100
+
101
+ /** The bound port. Null until listen() has run. */
102
+ get port(): number | null {
103
+ return server?.port ?? null
104
+ },
105
+
106
+ /** True while at least one editor is attached. */
107
+ get attached(): boolean {
108
+ return peers.size > 0
109
+ },
110
+
111
+ /** How many editors are attached — the count the TUI polls across. */
112
+ get peerCount(): number {
113
+ return peers.size
114
+ },
115
+
116
+ /**
117
+ * Observe attach/detach. Fires with the new count on every membership
118
+ * change; returns a teardown. Exists so a UI can GATE on whether an
119
+ * editor is reachable — a button that cannot route should not be
120
+ * rendered, and finding that out by polling would either burn a timer
121
+ * or miss the change the socket already knows about exactly.
122
+ */
123
+ watch(listener: (count: number) => void): () => void {
124
+ watchers.add(listener)
125
+ return () => { watchers.delete(listener) }
126
+ },
127
+
128
+ /**
129
+ * Start listening. Returns the bound port so the caller can put it
130
+ * on the instance record. Binds to loopback only — this channel is
131
+ * local by definition and must never be reachable off-box.
132
+ */
133
+ listen(): number {
134
+ if (server) return server.port!
135
+
136
+ server = Bun.serve({
137
+ port: opts.port ?? 0,
138
+ hostname: "127.0.0.1",
139
+ // An upgraded request must return nothing — Bun's own types
140
+ // model that as `undefined` on a union this overload can't
141
+ // narrow to, so the cast is at the framework seam, not over
142
+ // a shape of ours.
143
+ fetch(request, self): Response {
144
+ if (self.upgrade(request, { data: null })) return undefined as unknown as Response
145
+ return new Response("axon control channel", { status: 426 })
146
+ },
147
+ websocket: {
148
+ message(ws, raw) {
149
+ let frame: unknown
150
+ try {
151
+ frame = JSON.parse(String(raw))
152
+ } catch {
153
+ // Unparseable bytes on a local socket mean the
154
+ // peer is not who it claims to be. Close rather
155
+ // than continue reading.
156
+ ws.close(1003, "malformed frame")
157
+ return
158
+ }
159
+
160
+ // Handshake first: nothing is served before a valid
161
+ // token, so an unauthorised connection can never
162
+ // reach the handle.
163
+ const known = peers.get(ws)
164
+ if (!known) {
165
+ const hello = frame as ControlHello
166
+ if (hello?.type !== "control.hello" || hello.token !== token) {
167
+ ws.close(1008, "unauthorized")
168
+ return
169
+ }
170
+ const socket = { send: (data: string) => ws.send(data), close: () => ws.close() }
171
+ peers.set(ws, {
172
+ socket,
173
+ dispatch: Dispatch({ handle: opts.handle, send: f => socket.send(JSON.stringify(f)) }),
174
+ })
175
+ ws.send(JSON.stringify({ type: "control.welcome", peer: "tui" }))
176
+ announce()
177
+ return
178
+ }
179
+
180
+ if (!isControlFrame(frame)) return
181
+ known.dispatch.accept(frame)
182
+ },
183
+ close(ws) {
184
+ drop(ws, "editor disconnected")
185
+ },
186
+ },
187
+ })
188
+
189
+ return server.port!
190
+ },
191
+
192
+ /**
193
+ * Call one editor — the best target for `about`, when given.
194
+ *
195
+ * Windows are not interchangeable: each has different folders open,
196
+ * so "open this session log" is useful in the window whose
197
+ * workspace contains the path and useless in the one that does not.
198
+ * Rather than guess, every attached editor is asked `claim(path)`
199
+ * and the best answer wins — a window that contains the path beats
200
+ * one that does not, and focus breaks the tie.
201
+ *
202
+ * Without `about` the call goes to the most recently focused
203
+ * editor, which is the right default for anything not about a
204
+ * particular file.
205
+ *
206
+ * Rejects when nobody is attached rather than resolving quietly:
207
+ * "the panel did not focus because nothing is listening" is
208
+ * information the caller needs, not a no-op.
209
+ */
210
+ editor: {
211
+ async call<K extends keyof EditorSurface>(
212
+ method: K,
213
+ ...args: Parameters<EditorSurface[K]>
214
+ ): Promise<Awaited<ReturnType<EditorSurface[K]>>> {
215
+ const target = await pick()
216
+ return (await target.call(["editor", String(method)], args)) as Awaited<ReturnType<EditorSurface[K]>>
217
+ },
218
+
219
+ /** As `call`, but routed to whichever window can act on `path`. */
220
+ async about<K extends keyof EditorSurface>(
221
+ path: string,
222
+ method: K,
223
+ ...args: Parameters<EditorSurface[K]>
224
+ ): Promise<Awaited<ReturnType<EditorSurface[K]>>> {
225
+ const target = await pick(path)
226
+ return (await target.call(["editor", String(method)], args)) as Awaited<ReturnType<EditorSurface[K]>>
227
+ },
228
+ },
229
+
230
+ close(): void {
231
+ for (const [key, peer] of peers) {
232
+ drop(key, "tui shutting down")
233
+ peer.socket.close()
234
+ }
235
+ server?.stop(true)
236
+ server = null
237
+ },
238
+ }
239
+ }
240
+
241
+ export type ControlServerT = ReturnType<typeof ControlServer>
@@ -0,0 +1,81 @@
1
+ import type { AxonCloudClient, DeploymentRecord } from "@arcforge/cloud"
2
+
3
+ type DeploymentsOpts = {
4
+ cloud: AxonCloudClient
5
+ }
6
+
7
+ /** A deployment the user can actually connect to: running, with a URL. */
8
+ export type ConnectableDeployment = {
9
+ deploymentId: string
10
+ agentId: string
11
+ /** Registry name, e.g. "@cody/dave". */
12
+ name: string
13
+ url: string
14
+ tier: string
15
+ warmth: string
16
+ }
17
+
18
+ /**
19
+ * The user's deployed agents — the connectable ones, cached.
20
+ *
21
+ * Cached deliberately: the local agent list is a synchronous disk read, so a
22
+ * palette that awaited a network call to open would block on it. `list()` serves
23
+ * whatever was last fetched (empty before the first fetch) and `refresh()` is the
24
+ * only thing that touches the network. Callers refresh on boot and on demand;
25
+ * the palette never waits.
26
+ *
27
+ * Only `running` deployments with a URL are returned. A provisioning or errored
28
+ * deployment has nothing to attach to, so offering it in a palette would be
29
+ * offering an action that cannot work.
30
+ */
31
+ export function Deployments(opts: DeploymentsOpts) {
32
+ let cache: ConnectableDeployment[] = []
33
+ let lastError: Error | null = null
34
+
35
+ function connectable(rows: DeploymentRecord[]): ConnectableDeployment[] {
36
+ return rows
37
+ .filter(row => row.status === "running" && row.url !== null && row.agentName !== null)
38
+ .map(row => ({
39
+ deploymentId: row.id,
40
+ agentId: row.agentId,
41
+ name: row.agentName!,
42
+ url: row.url!,
43
+ tier: row.tier,
44
+ warmth: row.warmth,
45
+ }))
46
+ }
47
+
48
+ return {
49
+ /** Last fetched connectable deployments. Empty until refresh() has run. */
50
+ list(): ConnectableDeployment[] {
51
+ return cache
52
+ },
53
+
54
+ /** Why the last refresh failed, if it did. Surfaced, never swallowed. */
55
+ get error(): Error | null {
56
+ return lastError
57
+ },
58
+
59
+ /**
60
+ * Re-fetch from the control plane. Logged-out or offline is not a crash —
61
+ * the local agent list must still work — but the failure is recorded on
62
+ * `error` so a caller can show it rather than silently listing nothing.
63
+ */
64
+ async refresh(): Promise<ConnectableDeployment[]> {
65
+ try {
66
+ cache = connectable(await opts.cloud.user.deployments.list())
67
+ lastError = null
68
+ } catch (cause) {
69
+ lastError = cause instanceof Error ? cause : new Error(String(cause))
70
+ }
71
+ return cache
72
+ },
73
+
74
+ /** Look one up by registry name — what a palette selection resolves through. */
75
+ find(name: string): ConnectableDeployment | null {
76
+ return cache.find(item => item.name === name) ?? null
77
+ },
78
+ }
79
+ }
80
+
81
+ export type DeploymentsT = ReturnType<typeof Deployments>