@neta-art/cohub-cli 10.24.0 → 10.25.1

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 (369) hide show
  1. package/bin/cohub.js +4 -1
  2. package/dist/board-gpu/page.js +1566 -71230
  3. package/dist/bootstrap.js +67 -27
  4. package/dist/build.json +1 -1
  5. package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
  6. package/dist/chunks/about.js +102 -0
  7. package/dist/chunks/app-realtime.js +2216 -0
  8. package/dist/chunks/app-realtime2.js +2 -0
  9. package/dist/chunks/app-ref.js +88 -0
  10. package/dist/chunks/apps.js +1423 -0
  11. package/dist/chunks/auth.js +175 -0
  12. package/dist/chunks/avatar.js +146 -0
  13. package/dist/chunks/binary-pins.js +5 -0
  14. package/dist/chunks/board-export-resources.js +232 -0
  15. package/dist/chunks/board-export.js +874 -0
  16. package/dist/chunks/board-export2.js +2 -0
  17. package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
  18. package/dist/chunks/board-kernel2.js +4 -0
  19. package/dist/chunks/board-profile.js +69 -0
  20. package/dist/chunks/board-simulate.js +315 -0
  21. package/dist/chunks/board-time.js +34 -0
  22. package/dist/chunks/boards.js +1943 -0
  23. package/dist/{board-kernel → chunks}/browserAll.js +9 -8
  24. package/dist/chunks/channels.js +64 -0
  25. package/dist/chunks/client.js +12606 -0
  26. package/dist/chunks/command-input.js +17 -0
  27. package/dist/chunks/commander.js +2962 -0
  28. package/dist/chunks/cron-jobs.js +163 -0
  29. package/dist/chunks/daemon.js +545 -0
  30. package/dist/chunks/daemon2.js +2 -0
  31. package/dist/chunks/desktop.js +172 -0
  32. package/dist/chunks/endpoint-options.js +26 -0
  33. package/dist/chunks/env-proxy.js +35 -0
  34. package/dist/chunks/environment.js +154 -0
  35. package/dist/chunks/feedback.js +120 -0
  36. package/dist/chunks/generations.js +379 -0
  37. package/dist/chunks/host.js +9 -0
  38. package/dist/chunks/http-put.js +131 -0
  39. package/dist/chunks/id.js +2416 -0
  40. package/dist/{board-kernel → chunks}/init.js +1 -1
  41. package/dist/chunks/install.js +11959 -0
  42. package/dist/chunks/launch.js +374 -0
  43. package/dist/chunks/local-media.js +47 -0
  44. package/dist/chunks/me.js +134 -0
  45. package/dist/chunks/media.js +315 -0
  46. package/dist/chunks/models.js +242 -0
  47. package/dist/chunks/operands.js +46 -0
  48. package/dist/chunks/package-paths.js +13 -0
  49. package/dist/chunks/policy.js +221 -0
  50. package/dist/chunks/preferences.js +29 -0
  51. package/dist/chunks/profile.js +64 -0
  52. package/dist/chunks/prompts.js +41 -0
  53. package/dist/chunks/public.js +2 -0
  54. package/dist/chunks/public2.js +244 -0
  55. package/dist/chunks/references.js +197 -0
  56. package/dist/chunks/referrals.js +90 -0
  57. package/dist/chunks/rolldown-runtime.js +26 -0
  58. package/dist/chunks/rooms-connect.js +2 -0
  59. package/dist/chunks/rooms-connect2.js +151 -0
  60. package/dist/chunks/rooms-rtc.js +311 -0
  61. package/dist/chunks/rooms.js +211 -0
  62. package/dist/chunks/run.js +220 -0
  63. package/dist/chunks/runtime.js +638 -0
  64. package/dist/chunks/runtime2.js +286 -0
  65. package/dist/chunks/runtimes.js +48 -0
  66. package/dist/chunks/safe-remote-image.js +198 -0
  67. package/dist/chunks/schemas.js +6017 -0
  68. package/dist/chunks/search.js +113 -0
  69. package/dist/chunks/self-update.js +238 -0
  70. package/dist/chunks/serve.js +1246 -0
  71. package/dist/chunks/session-status.js +24 -0
  72. package/dist/chunks/skills.js +35 -0
  73. package/dist/chunks/spaces.js +5080 -0
  74. package/dist/chunks/src.js +405 -0
  75. package/dist/chunks/supervisor.js +2513 -0
  76. package/dist/chunks/supervisor2.js +2 -0
  77. package/dist/chunks/tasks.js +82 -0
  78. package/dist/chunks/themes.js +2898 -0
  79. package/dist/chunks/version.js +2 -0
  80. package/dist/chunks/version2.js +22 -0
  81. package/dist/chunks/version3.js +18 -0
  82. package/dist/chunks/web.js +7 -0
  83. package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
  84. package/dist/runtime/native/pi-extension.js +174 -166
  85. package/dist/runtime/worker.js +27 -16
  86. package/package.json +8 -9
  87. package/dist/about.d.ts +0 -2
  88. package/dist/about.js +0 -71
  89. package/dist/app-download.d.ts +0 -11
  90. package/dist/app-download.js +0 -252
  91. package/dist/app-ref.d.ts +0 -5
  92. package/dist/app-ref.js +0 -8
  93. package/dist/app-target.d.ts +0 -26
  94. package/dist/app-target.js +0 -55
  95. package/dist/auth.d.ts +0 -45
  96. package/dist/auth.js +0 -307
  97. package/dist/avatar.d.ts +0 -55
  98. package/dist/avatar.js +0 -104
  99. package/dist/board-command-support.d.ts +0 -6
  100. package/dist/board-command-support.js +0 -88
  101. package/dist/board-export-resources.d.ts +0 -12
  102. package/dist/board-export-resources.js +0 -51
  103. package/dist/board-export.d.ts +0 -110
  104. package/dist/board-export.js +0 -592
  105. package/dist/board-fonts.d.ts +0 -11
  106. package/dist/board-fonts.js +0 -10
  107. package/dist/board-gpu/daemon.d.ts +0 -11
  108. package/dist/board-gpu/daemon.js +0 -295
  109. package/dist/board-gpu/index.d.ts +0 -33
  110. package/dist/board-gpu/index.js +0 -189
  111. package/dist/board-gpu/protocol.d.ts +0 -77
  112. package/dist/board-gpu/protocol.js +0 -1
  113. package/dist/board-kernel.d.ts +0 -5
  114. package/dist/board-media-export.d.ts +0 -17
  115. package/dist/board-media-export.js +0 -164
  116. package/dist/board-media.d.ts +0 -5
  117. package/dist/board-media.js +0 -66
  118. package/dist/board-profile.d.ts +0 -21
  119. package/dist/board-profile.js +0 -67
  120. package/dist/board-simulate.d.ts +0 -67
  121. package/dist/board-simulate.js +0 -259
  122. package/dist/board-time.d.ts +0 -3
  123. package/dist/board-time.js +0 -34
  124. package/dist/bootstrap.d.ts +0 -2
  125. package/dist/client.d.ts +0 -5
  126. package/dist/client.js +0 -24
  127. package/dist/command-input.d.ts +0 -4
  128. package/dist/command-input.js +0 -16
  129. package/dist/commands/app-commerce.d.ts +0 -2
  130. package/dist/commands/app-commerce.js +0 -228
  131. package/dist/commands/app-domains.d.ts +0 -2
  132. package/dist/commands/app-domains.js +0 -133
  133. package/dist/commands/apps.d.ts +0 -4
  134. package/dist/commands/apps.js +0 -827
  135. package/dist/commands/auth.d.ts +0 -2
  136. package/dist/commands/auth.js +0 -186
  137. package/dist/commands/boards/authoring.d.ts +0 -2
  138. package/dist/commands/boards/authoring.js +0 -166
  139. package/dist/commands/boards/examples.d.ts +0 -10
  140. package/dist/commands/boards/examples.js +0 -118
  141. package/dist/commands/boards.d.ts +0 -13
  142. package/dist/commands/boards.js +0 -836
  143. package/dist/commands/channels.d.ts +0 -2
  144. package/dist/commands/channels.js +0 -74
  145. package/dist/commands/cron-jobs.d.ts +0 -2
  146. package/dist/commands/cron-jobs.js +0 -155
  147. package/dist/commands/decision.d.ts +0 -4
  148. package/dist/commands/decision.js +0 -113
  149. package/dist/commands/desktop.d.ts +0 -10
  150. package/dist/commands/desktop.js +0 -233
  151. package/dist/commands/feedback.d.ts +0 -2
  152. package/dist/commands/feedback.js +0 -131
  153. package/dist/commands/generations.d.ts +0 -2
  154. package/dist/commands/generations.js +0 -427
  155. package/dist/commands/host.d.ts +0 -2
  156. package/dist/commands/host.js +0 -11
  157. package/dist/commands/me.d.ts +0 -2
  158. package/dist/commands/me.js +0 -121
  159. package/dist/commands/models.d.ts +0 -28
  160. package/dist/commands/models.js +0 -271
  161. package/dist/commands/profile.d.ts +0 -2
  162. package/dist/commands/profile.js +0 -81
  163. package/dist/commands/prompts.d.ts +0 -2
  164. package/dist/commands/prompts.js +0 -37
  165. package/dist/commands/public.d.ts +0 -20
  166. package/dist/commands/public.js +0 -291
  167. package/dist/commands/references.d.ts +0 -2
  168. package/dist/commands/references.js +0 -193
  169. package/dist/commands/referrals.d.ts +0 -2
  170. package/dist/commands/referrals.js +0 -88
  171. package/dist/commands/rooms-connect.d.ts +0 -17
  172. package/dist/commands/rooms-connect.js +0 -140
  173. package/dist/commands/rooms-rtc-binary.d.ts +0 -2
  174. package/dist/commands/rooms-rtc-binary.js +0 -107
  175. package/dist/commands/rooms-rtc.d.ts +0 -21
  176. package/dist/commands/rooms-rtc.js +0 -171
  177. package/dist/commands/rooms.d.ts +0 -3
  178. package/dist/commands/rooms.js +0 -277
  179. package/dist/commands/run.d.ts +0 -13
  180. package/dist/commands/run.js +0 -246
  181. package/dist/commands/runtime.d.ts +0 -3
  182. package/dist/commands/runtime.js +0 -320
  183. package/dist/commands/sandboxd-binary.d.ts +0 -11
  184. package/dist/commands/sandboxd-binary.js +0 -238
  185. package/dist/commands/search.d.ts +0 -2
  186. package/dist/commands/search.js +0 -114
  187. package/dist/commands/session-access.d.ts +0 -2
  188. package/dist/commands/session-access.js +0 -70
  189. package/dist/commands/skills.d.ts +0 -2
  190. package/dist/commands/skills.js +0 -34
  191. package/dist/commands/space-activity.d.ts +0 -26
  192. package/dist/commands/space-activity.js +0 -147
  193. package/dist/commands/space-commerce.d.ts +0 -2
  194. package/dist/commands/space-commerce.js +0 -514
  195. package/dist/commands/space-displays.d.ts +0 -2
  196. package/dist/commands/space-displays.js +0 -620
  197. package/dist/commands/space-files.d.ts +0 -5
  198. package/dist/commands/space-files.js +0 -215
  199. package/dist/commands/space-invitations.d.ts +0 -29
  200. package/dist/commands/space-invitations.js +0 -189
  201. package/dist/commands/space-turns.d.ts +0 -49
  202. package/dist/commands/space-turns.js +0 -205
  203. package/dist/commands/space-wallet.d.ts +0 -2
  204. package/dist/commands/space-wallet.js +0 -141
  205. package/dist/commands/space-webhooks.d.ts +0 -7
  206. package/dist/commands/space-webhooks.js +0 -73
  207. package/dist/commands/spaces.d.ts +0 -25
  208. package/dist/commands/spaces.js +0 -2170
  209. package/dist/commands/tasks.d.ts +0 -8
  210. package/dist/commands/tasks.js +0 -80
  211. package/dist/commands/version.d.ts +0 -2
  212. package/dist/commands/version.js +0 -21
  213. package/dist/endpoint-options.d.ts +0 -4
  214. package/dist/endpoint-options.js +0 -26
  215. package/dist/env-proxy.d.ts +0 -5
  216. package/dist/env-proxy.js +0 -20
  217. package/dist/help-path.d.ts +0 -18
  218. package/dist/help-path.js +0 -223
  219. package/dist/host/auth.d.ts +0 -20
  220. package/dist/host/auth.js +0 -119
  221. package/dist/host/login-env.d.ts +0 -1
  222. package/dist/host/login-env.js +0 -31
  223. package/dist/host/runtime.d.ts +0 -35
  224. package/dist/host/runtime.js +0 -395
  225. package/dist/host/runtimes.d.ts +0 -9
  226. package/dist/host/runtimes.js +0 -42
  227. package/dist/host/serve.d.ts +0 -2
  228. package/dist/host/serve.js +0 -117
  229. package/dist/host/workspaces.d.ts +0 -2
  230. package/dist/host/workspaces.js +0 -18
  231. package/dist/http-put.d.ts +0 -25
  232. package/dist/http-put.js +0 -132
  233. package/dist/index.d.ts +0 -2
  234. package/dist/index.js +0 -129
  235. package/dist/launcher.d.ts +0 -4
  236. package/dist/launcher.js +0 -38
  237. package/dist/local-media.d.ts +0 -2
  238. package/dist/local-media.js +0 -30
  239. package/dist/network-error.d.ts +0 -3
  240. package/dist/network-error.js +0 -22
  241. package/dist/output.d.ts +0 -46
  242. package/dist/output.js +0 -244
  243. package/dist/runtime/archive-store.d.ts +0 -54
  244. package/dist/runtime/archive-store.js +0 -379
  245. package/dist/runtime/cli-path.d.ts +0 -5
  246. package/dist/runtime/cli-path.js +0 -27
  247. package/dist/runtime/codex-usage.d.ts +0 -7
  248. package/dist/runtime/codex-usage.js +0 -11
  249. package/dist/runtime/connection.d.ts +0 -42
  250. package/dist/runtime/connection.js +0 -789
  251. package/dist/runtime/diagnostics.d.ts +0 -107
  252. package/dist/runtime/diagnostics.js +0 -392
  253. package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
  254. package/dist/runtime/harnesses/chained-projection.js +0 -95
  255. package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
  256. package/dist/runtime/harnesses/chained-transcript.js +0 -62
  257. package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
  258. package/dist/runtime/harnesses/claude-approval.js +0 -124
  259. package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
  260. package/dist/runtime/harnesses/claude-transcript.js +0 -138
  261. package/dist/runtime/harnesses/claude.d.ts +0 -8
  262. package/dist/runtime/harnesses/claude.js +0 -225
  263. package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
  264. package/dist/runtime/harnesses/codex-approval.js +0 -69
  265. package/dist/runtime/harnesses/codex.d.ts +0 -4
  266. package/dist/runtime/harnesses/codex.js +0 -269
  267. package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
  268. package/dist/runtime/harnesses/cursor-transcript.js +0 -183
  269. package/dist/runtime/harnesses/cursor.d.ts +0 -24
  270. package/dist/runtime/harnesses/cursor.js +0 -620
  271. package/dist/runtime/harnesses/index.d.ts +0 -16
  272. package/dist/runtime/harnesses/index.js +0 -73
  273. package/dist/runtime/harnesses/pi.d.ts +0 -4
  274. package/dist/runtime/harnesses/pi.js +0 -247
  275. package/dist/runtime/harnesses/process.d.ts +0 -31
  276. package/dist/runtime/harnesses/process.js +0 -75
  277. package/dist/runtime/harnesses/stream-json.d.ts +0 -48
  278. package/dist/runtime/harnesses/stream-json.js +0 -336
  279. package/dist/runtime/harnesses/types.d.ts +0 -117
  280. package/dist/runtime/harnesses/types.js +0 -1
  281. package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
  282. package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
  283. package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
  284. package/dist/runtime/harnesses/workbuddy.js +0 -123
  285. package/dist/runtime/instance.d.ts +0 -20
  286. package/dist/runtime/instance.js +0 -247
  287. package/dist/runtime/json-rpc.d.ts +0 -53
  288. package/dist/runtime/json-rpc.js +0 -212
  289. package/dist/runtime/launch.d.ts +0 -25
  290. package/dist/runtime/launch.js +0 -247
  291. package/dist/runtime/local-workspace.d.ts +0 -15
  292. package/dist/runtime/local-workspace.js +0 -52
  293. package/dist/runtime/model-catalog.d.ts +0 -12
  294. package/dist/runtime/model-catalog.js +0 -84
  295. package/dist/runtime/native/adapters.d.ts +0 -15
  296. package/dist/runtime/native/adapters.js +0 -11
  297. package/dist/runtime/native/approvals.d.ts +0 -18
  298. package/dist/runtime/native/approvals.js +0 -54
  299. package/dist/runtime/native/archive.d.ts +0 -19
  300. package/dist/runtime/native/archive.js +0 -142
  301. package/dist/runtime/native/attach.d.ts +0 -36
  302. package/dist/runtime/native/attach.js +0 -128
  303. package/dist/runtime/native/codex-link.d.ts +0 -60
  304. package/dist/runtime/native/codex-link.js +0 -322
  305. package/dist/runtime/native/config.d.ts +0 -16
  306. package/dist/runtime/native/config.js +0 -24
  307. package/dist/runtime/native/daemon.d.ts +0 -92
  308. package/dist/runtime/native/daemon.js +0 -380
  309. package/dist/runtime/native/execution.d.ts +0 -26
  310. package/dist/runtime/native/execution.js +0 -34
  311. package/dist/runtime/native/identity.d.ts +0 -9
  312. package/dist/runtime/native/identity.js +0 -15
  313. package/dist/runtime/native/ingest.d.ts +0 -263
  314. package/dist/runtime/native/ingest.js +0 -884
  315. package/dist/runtime/native/install.d.ts +0 -9
  316. package/dist/runtime/native/install.js +0 -113
  317. package/dist/runtime/native/paths.d.ts +0 -2
  318. package/dist/runtime/native/paths.js +0 -7
  319. package/dist/runtime/native/pi-extension.d.ts +0 -36
  320. package/dist/runtime/native/pi-link.d.ts +0 -69
  321. package/dist/runtime/native/pi-link.js +0 -269
  322. package/dist/runtime/native/results.d.ts +0 -41
  323. package/dist/runtime/native/results.js +0 -128
  324. package/dist/runtime/native/sessions.d.ts +0 -45
  325. package/dist/runtime/native/sessions.js +0 -87
  326. package/dist/runtime/native/transcript.d.ts +0 -89
  327. package/dist/runtime/native/transcript.js +0 -656
  328. package/dist/runtime/native/translate.d.ts +0 -46
  329. package/dist/runtime/native/translate.js +0 -299
  330. package/dist/runtime/native/transport.d.ts +0 -7
  331. package/dist/runtime/native/transport.js +0 -16
  332. package/dist/runtime/native/version.d.ts +0 -5
  333. package/dist/runtime/native/version.js +0 -21
  334. package/dist/runtime/preferences.d.ts +0 -7
  335. package/dist/runtime/preferences.js +0 -22
  336. package/dist/runtime/presentation.d.ts +0 -32
  337. package/dist/runtime/presentation.js +0 -124
  338. package/dist/runtime/process-group.d.ts +0 -5
  339. package/dist/runtime/process-group.js +0 -161
  340. package/dist/runtime/projection-store.d.ts +0 -27
  341. package/dist/runtime/projection-store.js +0 -30
  342. package/dist/runtime/space-binding.d.ts +0 -48
  343. package/dist/runtime/space-binding.js +0 -342
  344. package/dist/runtime/supervisor.d.ts +0 -19
  345. package/dist/runtime/supervisor.js +0 -441
  346. package/dist/runtime/turn-projection.d.ts +0 -41
  347. package/dist/runtime/turn-projection.js +0 -120
  348. package/dist/runtime/worker.d.ts +0 -1
  349. package/dist/safe-remote-image.d.ts +0 -36
  350. package/dist/safe-remote-image.js +0 -191
  351. package/dist/self-update.d.ts +0 -7
  352. package/dist/self-update.js +0 -202
  353. package/dist/session-status.d.ts +0 -10
  354. package/dist/session-status.js +0 -25
  355. package/dist/space-files/limit.d.ts +0 -2
  356. package/dist/space-files/limit.js +0 -16
  357. package/dist/space-files/operands.d.ts +0 -17
  358. package/dist/space-files/operands.js +0 -33
  359. package/dist/space-files/transfer.d.ts +0 -53
  360. package/dist/space-files/transfer.js +0 -297
  361. package/dist/space-files/upload.d.ts +0 -17
  362. package/dist/space-files/upload.js +0 -76
  363. package/dist/space.d.ts +0 -44
  364. package/dist/space.js +0 -192
  365. package/dist/version.d.ts +0 -2
  366. package/dist/version.js +0 -17
  367. package/dist/web.d.ts +0 -1
  368. package/dist/web.js +0 -4
  369. /package/dist/{board-kernel → chunks}/lexer.js +0 -0
@@ -0,0 +1,2513 @@
1
+ import { t as packagePath } from "./package-paths.js";
2
+ import { t as CLI_VERSION } from "./version2.js";
3
+ import { a as runtimeCapabilitiesSchema, b as assertHarnessAccess, c as runtimeHelloCapabilities, l as runtimeReadySchema, m as runtimeNativeStopSchema, n as RUNTIME_MAX_FRAME_BYTES, o as runtimeCommandSchema, p as runtimeApprovalDecisionSchema, s as runtimeEventSchema } from "./runtime.js";
4
+ import { F as AuthRequiredError, P as describeError, W as resolveAccessToken, Y as readRuntimeSpaceBindings, c as ownRuntimeInstance, h as currentIdentityKey, o as UNCONFIRMED_WORK, t as createClient, u as runtimeInstanceDirectory } from "./client.js";
5
+ import { A as formatVersion, B as closeHost, E as CodexShared, F as piTranslator, G as RuntimeDiagnostics, H as ProcessCleanupUncertainError, I as ArchiveNotRestorableError, J as serializeDiagnosticError, L as PI_MIN_VERSION, M as SizeLimitError, N as LiveProgress, P as codexTranslator, R as PiLink, S as harnessAdapter, U as confirmQuiescentProcessGroup, V as record$1, Y as serializeProjectionRecords, a as NativeIngest, b as atomicRuntimeJson, c as runtimeStateRoot, d as createDiagnosticConsole, j as harnessVersion, k as atLeast, n as piExtensionSource, r as piExtensionState, s as readNativeConfig, v as readTranscript, w as refreshHarnesses, x as discoverHarnesses, y as RuntimeArchiveStore, z as controlSocketPath } from "./install.js";
6
+ import { d as resolveWebsocketUrl } from "./environment.js";
7
+ import "./binary-pins.js";
8
+ import { t as readRuntimePreferences } from "./preferences.js";
9
+ import { spawn } from "node:child_process";
10
+ import { homedir, tmpdir } from "node:os";
11
+ import { createReadStream, createWriteStream, mkdirSync, renameSync, writeFileSync } from "node:fs";
12
+ import { delimiter, dirname, join } from "node:path";
13
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
14
+ import { createServer } from "node:net";
15
+ import { createInterface } from "node:readline";
16
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
17
+ import { PassThrough, Readable } from "node:stream";
18
+ import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
19
+ import { pipeline } from "node:stream/promises";
20
+ import { isDeepStrictEqual } from "node:util";
21
+ //#region src/commands/sandboxd-binary.ts
22
+ const BINARY_NAME = "cohub-sandboxd";
23
+ const binaryName = (goos) => goos === "windows" ? `${BINARY_NAME}.exe` : BINARY_NAME;
24
+ const cdnBaseUrl = () => (process.env.COHUB_SANDBOXD_CDN_BASE_URL?.trim() || "https://public.cohub.live/sandboxd").replace(/\/+$/, "");
25
+ const DOWNLOAD_TIMEOUT_MS = 12e4;
26
+ const LOCK_STALE_MS = 3e5;
27
+ const GOOS_BY_PLATFORM = {
28
+ darwin: "darwin",
29
+ linux: "linux",
30
+ win32: "windows"
31
+ };
32
+ const GOARCH_BY_ARCH = {
33
+ x64: "amd64",
34
+ arm64: "arm64"
35
+ };
36
+ var SandboxdDownloadError = class extends Error {
37
+ name = "SandboxdDownloadError";
38
+ };
39
+ const resolveTarget = () => {
40
+ const goos = GOOS_BY_PLATFORM[process.platform];
41
+ const goarch = GOARCH_BY_ARCH[process.arch];
42
+ if (!goos || !goarch) throw new SandboxdDownloadError(`Unsupported platform ${process.platform}/${process.arch}. Set COHUB_SANDBOXD_BIN to a locally built binary.`);
43
+ return {
44
+ goos,
45
+ goarch
46
+ };
47
+ };
48
+ const cacheDir = (version) => join(homedir(), ".cache", "cohub", "sandboxd", version);
49
+ const cachedBinaryPath = (version, target) => join(cacheDir(version), binaryName(target.goos));
50
+ const archiveName = (version, target) => `${BINARY_NAME}_${version}_${target.goos}_${target.goarch}.tar.gz`;
51
+ const isExecutableFile = async (path) => {
52
+ const info = await lstat(path).catch(() => null);
53
+ return Boolean(info?.isFile());
54
+ };
55
+ const isSafeArchiveFile = async (path) => {
56
+ const info = await lstat(path).catch(() => null);
57
+ return Boolean(info?.isFile() && info.nlink === 1);
58
+ };
59
+ const sha256File = async (path) => {
60
+ const hash = createHash("sha256");
61
+ await pipeline(createReadStream(path), hash);
62
+ return hash.digest("hex");
63
+ };
64
+ const withTimeout = async (what, fn) => {
65
+ const controller = new AbortController();
66
+ const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS);
67
+ try {
68
+ return await fn(controller.signal);
69
+ } catch (err) {
70
+ if (err instanceof SandboxdDownloadError) throw err;
71
+ if (controller.signal.aborted) throw new SandboxdDownloadError(`${what} timed out after ${DOWNLOAD_TIMEOUT_MS / 1e3}s`);
72
+ throw new SandboxdDownloadError(`${what} failed: ${err instanceof Error ? err.message : String(err)}`);
73
+ } finally {
74
+ clearTimeout(timer);
75
+ }
76
+ };
77
+ const downloadToFile = (url, accept, destPath) => withTimeout(`Download of ${url}`, async (signal) => {
78
+ const response = await fetch(url, {
79
+ signal,
80
+ headers: { accept }
81
+ });
82
+ if (!response.ok) throw new SandboxdDownloadError(`Download failed (${response.status}) for ${url}`);
83
+ if (!response.body) throw new SandboxdDownloadError(`Empty response body for ${url}`);
84
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(destPath));
85
+ });
86
+ const fetchText = (url, accept) => withTimeout(`Download of ${url}`, async (signal) => {
87
+ const response = await fetch(url, {
88
+ signal,
89
+ headers: { accept }
90
+ });
91
+ if (!response.ok) throw new SandboxdDownloadError(`Download failed (${response.status}) for ${url}`);
92
+ return (await response.text()).trim();
93
+ });
94
+ function validSandboxdArchiveEntries(entries, goos) {
95
+ const expected = [
96
+ binaryName(goos),
97
+ "LICENSE",
98
+ "NOTICE"
99
+ ];
100
+ return entries.length === expected.length && expected.every((entry) => entries.includes(entry));
101
+ }
102
+ const tarCommand = () => {
103
+ if (process.platform !== "win32") return "tar";
104
+ if (!process.env.SystemRoot) throw new SandboxdDownloadError("SystemRoot is not set; cannot locate tar.exe");
105
+ return join(process.env.SystemRoot, "System32", "tar.exe");
106
+ };
107
+ const listTarGz = (archivePath, verbose = false) => new Promise((res, rej) => {
108
+ const child = spawn(tarCommand(), [verbose ? "-tvzf" : "-tzf", archivePath], { stdio: [
109
+ "ignore",
110
+ "pipe",
111
+ "pipe"
112
+ ] });
113
+ let stdout = "";
114
+ let stderr = "";
115
+ child.stdout.on("data", (chunk) => {
116
+ stdout += chunk.toString();
117
+ });
118
+ child.stderr.on("data", (chunk) => {
119
+ stderr += chunk.toString();
120
+ });
121
+ child.on("error", rej);
122
+ child.on("close", (code) => code === 0 ? res(stdout.split("\n").map((line) => line.trim()).filter(Boolean)) : rej(new SandboxdDownloadError(`tar listing failed: ${stderr.trim() || `exit ${code}`}`)));
123
+ });
124
+ async function validateSandboxdArchive(archivePath, goos) {
125
+ const entries = await listTarGz(archivePath);
126
+ if (!validSandboxdArchiveEntries(entries, goos)) throw new SandboxdDownloadError(`Unexpected sandbox archive contents: ${entries.join(", ") || "(empty)"}`);
127
+ const details = await listTarGz(archivePath, true);
128
+ if (details.length !== entries.length || details.some((line) => !line.startsWith("-") || /(?: link to | -> | == )/.test(line))) throw new SandboxdDownloadError("Sandbox archive must contain only regular files");
129
+ return entries;
130
+ }
131
+ const extractTarGz = (archivePath, cwd) => new Promise((res, rej) => {
132
+ const child = spawn(tarCommand(), [
133
+ "-xzf",
134
+ archivePath,
135
+ "-C",
136
+ cwd
137
+ ], { stdio: [
138
+ "ignore",
139
+ "ignore",
140
+ "pipe"
141
+ ] });
142
+ let stderr = "";
143
+ child.stderr.on("data", (chunk) => {
144
+ stderr += chunk.toString();
145
+ });
146
+ child.on("error", rej);
147
+ child.on("close", (code) => code === 0 ? res() : rej(new SandboxdDownloadError(`tar extraction failed: ${stderr.trim() || `exit ${code}`}`)));
148
+ });
149
+ const withLock = async (version, fn) => {
150
+ const lockPath = join(cacheDir(version), ".download.lock");
151
+ await mkdir(dirname(lockPath), { recursive: true });
152
+ for (let attempt = 0; attempt < 600; attempt += 1) try {
153
+ await mkdir(lockPath);
154
+ try {
155
+ return await fn();
156
+ } finally {
157
+ await rm(lockPath, {
158
+ recursive: true,
159
+ force: true
160
+ });
161
+ }
162
+ } catch (err) {
163
+ if (err.code !== "EEXIST") throw err;
164
+ const info = await stat(lockPath).catch(() => null);
165
+ if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
166
+ await rm(lockPath, {
167
+ recursive: true,
168
+ force: true
169
+ }).catch(() => void 0);
170
+ continue;
171
+ }
172
+ await new Promise((r) => setTimeout(r, 500));
173
+ }
174
+ throw new SandboxdDownloadError("Timed out waiting for the sandboxd download lock");
175
+ };
176
+ const downloadAndVerify = async (version, target) => {
177
+ const name = archiveName(version, target);
178
+ const archiveUrl = `${cdnBaseUrl()}/${version}/${name}`;
179
+ const checksumUrl = `${archiveUrl}.sha256`;
180
+ const tempDir = await mkdtemp(join(tmpdir(), "cohub-sandboxd-"));
181
+ try {
182
+ const archivePath = join(tempDir, name);
183
+ await downloadToFile(archiveUrl, "application/gzip", archivePath);
184
+ const expected = (await fetchText(checksumUrl, "text/plain")).split(/\s+/)[0]?.toLowerCase();
185
+ if (!expected || !/^[0-9a-f]{64}$/.test(expected)) throw new SandboxdDownloadError(`Invalid checksum manifest for ${name}`);
186
+ const actual = (await sha256File(archivePath)).toLowerCase();
187
+ if (actual !== expected) throw new SandboxdDownloadError(`Checksum mismatch for ${name} (expected ${expected}, got ${actual})`);
188
+ const entries = await validateSandboxdArchive(archivePath, target.goos);
189
+ await extractTarGz(archivePath, tempDir);
190
+ for (const entry of entries) if (!await isSafeArchiveFile(join(tempDir, entry))) throw new SandboxdDownloadError(`Unsafe sandbox archive entry: ${entry}`);
191
+ const extractedBinary = join(tempDir, binaryName(target.goos));
192
+ if (!await isSafeArchiveFile(extractedBinary)) throw new SandboxdDownloadError(`Archive ${name} did not contain ${binaryName(target.goos)}`);
193
+ const dest = cachedBinaryPath(version, target);
194
+ await mkdir(dirname(dest), { recursive: true });
195
+ await rename(extractedBinary, dest).catch(async (err) => {
196
+ if (err.code !== "EXDEV") throw err;
197
+ await copyFile(extractedBinary, dest);
198
+ });
199
+ await chmod(dest, 493);
200
+ return dest;
201
+ } finally {
202
+ await rm(tempDir, {
203
+ recursive: true,
204
+ force: true
205
+ }).catch(() => void 0);
206
+ }
207
+ };
208
+ const ensureSandboxdBinary = async (options = {}) => {
209
+ const override = process.env.COHUB_SANDBOXD_BIN?.trim();
210
+ if (override) {
211
+ if (!await isExecutableFile(override)) throw new SandboxdDownloadError(`COHUB_SANDBOXD_BIN=${override} is not a file`);
212
+ return override;
213
+ }
214
+ const version = options.version?.trim() || "v2.96.0";
215
+ const target = resolveTarget();
216
+ const cached = cachedBinaryPath(version, target);
217
+ if (await isExecutableFile(cached)) return cached;
218
+ return withLock(version, async () => {
219
+ if (await isExecutableFile(cached)) return cached;
220
+ options.onStatus?.(`Downloading sandbox runtime ${version} (${target.goos}/${target.goarch})`);
221
+ const path = await downloadAndVerify(version, target);
222
+ options.onStatus?.("Sandbox runtime ready");
223
+ return path;
224
+ });
225
+ };
226
+ //#endregion
227
+ //#region src/runtime/native/execution.ts
228
+ /** Run one Cohub Turn in a local harness through its adapter. */
229
+ async function executeTurn(executor, input, emit, signal, requestId, context) {
230
+ signal.throwIfAborted();
231
+ assertHarnessAccess(input.harness, input.accessMode);
232
+ const diverged = await executor.results.admit(input);
233
+ const started = async (session) => {
234
+ await executor.results.start(session, input, requestId);
235
+ executor.ingest.begin(session, input.sessionId, input.turnId);
236
+ };
237
+ const turn = {
238
+ input,
239
+ emit,
240
+ signal,
241
+ diverged,
242
+ started,
243
+ context
244
+ };
245
+ let run;
246
+ try {
247
+ run = await harnessAdapter(input.harness).run(executor, turn);
248
+ } catch (error) {
249
+ executor.ingest.end(input.turnId);
250
+ throw error;
251
+ }
252
+ let uncertainCleanup;
253
+ if (run.host) uncertainCleanup = await closeHost(run.host, run.message.errorMessage);
254
+ const message = signal.aborted ? {
255
+ ...run.message,
256
+ stopReason: "aborted"
257
+ } : run.message;
258
+ const archive = !harnessAdapter(input.harness).session.archive ? null : await executor.archives.stage({
259
+ sessionId: input.sessionId,
260
+ harness: input.harness,
261
+ nativeSessionId: run.session.nativeSessionId,
262
+ path: run.session.path
263
+ }, input.turnId).catch((error) => {
264
+ executor.diagnostics?.log("warn", "archive.capture_failed", { error: serializeDiagnosticError(error) }, {
265
+ ...context,
266
+ component: "archive"
267
+ });
268
+ return null;
269
+ });
270
+ executor.ingest.advance(run.session.path, input.turnId);
271
+ return {
272
+ session: run.session,
273
+ event: {
274
+ type: "turn.end",
275
+ message,
276
+ resume: run.resume,
277
+ archive
278
+ },
279
+ ...uncertainCleanup ? { uncertainCleanup } : {}
280
+ };
281
+ }
282
+ //#endregion
283
+ //#region src/runtime/native/results.ts
284
+ var ContextRequiredError = class extends Error {};
285
+ const missing = (error) => error?.code === "ENOENT";
286
+ /** One small receipt per Cohub-executed Turn until the server acknowledges its result. */
287
+ var ExecutionResults = class {
288
+ root;
289
+ constructor(root) {
290
+ this.root = root;
291
+ }
292
+ path(sessionId) {
293
+ return join(this.root, "executions", `${sessionId}.json`);
294
+ }
295
+ async read(sessionId) {
296
+ try {
297
+ const receipt = JSON.parse(await readFile(this.path(sessionId), "utf8"));
298
+ if (receipt.version !== 2 || receipt.sessionId !== sessionId) throw new Error("Invalid execution receipt");
299
+ return receipt;
300
+ } catch (error) {
301
+ if (missing(error)) return null;
302
+ throw error;
303
+ }
304
+ }
305
+ /**
306
+ * Admit a new Turn. An unacknowledged earlier Turn is released once the server has settled it;
307
+ * otherwise the server must decide first, so a result is never overwritten unseen.
308
+ */
309
+ async admit(input) {
310
+ const receipt = await this.read(input.sessionId);
311
+ if (!receipt || receipt.turnId === input.turnId) return null;
312
+ const { resolvedTurnIds, settledTurnIds, complete } = input.context;
313
+ const resolved = resolvedTurnIds?.includes(receipt.turnId) === true;
314
+ if (resolved || settledTurnIds?.includes(receipt.turnId)) {
315
+ await rm(this.path(input.sessionId), { force: true });
316
+ return resolved ? receipt.session.path : null;
317
+ }
318
+ if (complete === false) throw new ContextRequiredError("Server resolution is required for the pending native execution");
319
+ throw new Error(`Local turn ${receipt.turnId} has unconfirmed results; reconcile it before continuing`);
320
+ }
321
+ async start(session, input, requestId) {
322
+ await atomicRuntimeJson(this.path(input.sessionId), {
323
+ version: 2,
324
+ requestId,
325
+ sessionId: input.sessionId,
326
+ turnId: input.turnId,
327
+ session
328
+ });
329
+ }
330
+ async record(session, input, requestId, events, uncertainCleanup) {
331
+ await atomicRuntimeJson(this.path(input.sessionId), {
332
+ version: 2,
333
+ requestId,
334
+ sessionId: input.sessionId,
335
+ turnId: input.turnId,
336
+ session,
337
+ events,
338
+ ...uncertainCleanup ? { uncertainCleanup } : {}
339
+ });
340
+ }
341
+ async recover(input, requestId) {
342
+ const receipt = await this.read(input.sessionId);
343
+ if (!receipt || receipt.turnId !== input.turnId || receipt.session.harness !== input.harness) return null;
344
+ if (requestId && receipt.requestId != null && receipt.requestId !== requestId) throw new Error("Runtime result execution identity mismatch");
345
+ if (receipt.events) {
346
+ if (receipt.uncertainCleanup && !receipt.uncertainCleanup.confirmedAt) {
347
+ if (!await confirmQuiescentProcessGroup(receipt.uncertainCleanup.processGroupId)) return null;
348
+ receipt.uncertainCleanup.confirmedAt = (/* @__PURE__ */ new Date()).toISOString();
349
+ await atomicRuntimeJson(this.path(input.sessionId), receipt);
350
+ }
351
+ return {
352
+ session: receipt.session,
353
+ events: receipt.events.map((event) => runtimeEventSchema.parse(event))
354
+ };
355
+ }
356
+ const events = await this.fromTranscript(receipt);
357
+ if (!events) return null;
358
+ await this.record(receipt.session, receipt, receipt.requestId, events);
359
+ return {
360
+ session: receipt.session,
361
+ events
362
+ };
363
+ }
364
+ async acknowledge(sessionId, turnId) {
365
+ if ((await this.read(sessionId))?.turnId !== turnId) throw new Error("Runtime acknowledgement identity mismatch");
366
+ await rm(this.path(sessionId), { force: true });
367
+ }
368
+ async pendingTurnIds(sessionId) {
369
+ const receipt = await this.read(sessionId);
370
+ return receipt ? [receipt.turnId] : [];
371
+ }
372
+ async *pendingBatches() {
373
+ const names = await readdir(join(this.root, "executions")).catch((error) => {
374
+ if (missing(error)) return [];
375
+ throw error;
376
+ });
377
+ let batch = [];
378
+ for (const name of names) {
379
+ if (!name.endsWith(".json")) continue;
380
+ const receipt = await this.read(name.slice(0, -5)).catch(() => null);
381
+ if (!receipt) continue;
382
+ batch.push({
383
+ sessionId: receipt.sessionId,
384
+ turnId: receipt.turnId,
385
+ harness: receipt.session.harness
386
+ });
387
+ if (batch.length >= 64) {
388
+ yield batch;
389
+ batch = [];
390
+ }
391
+ }
392
+ if (batch.length) yield batch;
393
+ }
394
+ async fromTranscript(receipt) {
395
+ const transcript = await readTranscript(receipt.session.path, receipt.session.harness).catch(() => null);
396
+ const turn = transcript?.turns.find((entry) => entry.cloudTurnId === receipt.turnId);
397
+ const result = turn?.result;
398
+ if (!result || result.status === "interrupted" || turn !== transcript?.turns.at(-1)) return null;
399
+ const messages = result.messages.filter((message) => message.content.length);
400
+ if (!messages.length) return null;
401
+ const message = (entry, ordinal) => ({
402
+ ordinal,
403
+ content: entry.content,
404
+ provider: entry.provider ?? null,
405
+ model: entry.model ?? null,
406
+ usage: entry.usage ?? null,
407
+ stopReason: entry.stopReason ?? "stop",
408
+ errorMessage: entry.errorMessage ?? null
409
+ });
410
+ return [...messages.slice(0, -1).map((entry, index) => ({
411
+ type: "message.commit",
412
+ message: message(entry, index)
413
+ })), {
414
+ type: "turn.end",
415
+ message: message(messages.at(-1), messages.length - 1),
416
+ resume: "native",
417
+ archive: null
418
+ }];
419
+ }
420
+ };
421
+ //#endregion
422
+ //#region src/runtime/connection.ts
423
+ async function serveRuntime(options) {
424
+ const runtimeId = options.runtimeId ?? options.diagnostics?.runtimeId ?? randomUUID();
425
+ let backoff = 500;
426
+ let attempt = 0;
427
+ let conflictSince = null;
428
+ const executions = options.executions ?? /* @__PURE__ */ new Map();
429
+ const seen = /* @__PURE__ */ new Set();
430
+ const announce = { current: null };
431
+ const catalog = {
432
+ current: options.capabilities,
433
+ publish: null
434
+ };
435
+ const uploads = new AbortController();
436
+ const uploadSignal = AbortSignal.any([options.signal, uploads.signal]);
437
+ const log = (level, event, data, context) => options.diagnostics?.log(level, event, data, context);
438
+ const flush = () => options.executor.archives.flush(uploadSignal).catch((error) => {
439
+ if (!uploadSignal.aborted) log("warn", "archive.flush_failed", { error: serializeDiagnosticError(error) });
440
+ });
441
+ const timer = setInterval(() => {
442
+ flush();
443
+ }, 1e4);
444
+ let refreshing = false;
445
+ const refreshCatalog = async () => {
446
+ if (!options.refreshCapabilities || refreshing || options.signal.aborted) return;
447
+ refreshing = true;
448
+ try {
449
+ const next = await options.refreshCapabilities(catalog.current);
450
+ runtimeCapabilitiesSchema.parse(next);
451
+ if (options.signal.aborted || isDeepStrictEqual(next, catalog.current)) return;
452
+ catalog.current = next;
453
+ log("info", "runtime.catalog_changed", {
454
+ harnesses: next.harnesses,
455
+ modelCount: next.models.length
456
+ });
457
+ catalog.publish?.();
458
+ } catch (error) {
459
+ log("warn", "runtime.catalog_refresh_failed", { error: serializeDiagnosticError(error) });
460
+ } finally {
461
+ refreshing = false;
462
+ }
463
+ };
464
+ const catalogTimer = options.refreshCapabilities ? setInterval(() => {
465
+ refreshCatalog();
466
+ }, options.capabilitiesRefreshMs ?? 36e5) : void 0;
467
+ flush();
468
+ log("info", "runtime.started", {
469
+ runtimeId,
470
+ workspace: options.cwd,
471
+ harnesses: options.capabilities.harnesses
472
+ });
473
+ try {
474
+ while (!options.signal.aborted) {
475
+ attempt += 1;
476
+ let readyAt = 0;
477
+ const connectStartedAt = Date.now();
478
+ let outcome;
479
+ try {
480
+ outcome = await connect({
481
+ ...options,
482
+ runtimeId,
483
+ attempt,
484
+ executions,
485
+ seen,
486
+ announce,
487
+ catalog,
488
+ onReady: () => {
489
+ readyAt = Date.now();
490
+ conflictSince = null;
491
+ options.onReady();
492
+ flush();
493
+ }
494
+ });
495
+ } catch (error) {
496
+ if (options.signal.aborted) return;
497
+ log("warn", "runtime.connection_failed", { error: serializeDiagnosticError(error) });
498
+ outcome = { kind: "retry" };
499
+ }
500
+ options.onDisconnected?.();
501
+ if (options.signal.aborted) return;
502
+ if (outcome.kind === "fatal") throw new Error(`Runtime connection rejected (${[outcome.code, outcome.reason].filter(Boolean).join(" ")}); ${outcome.code === 4403 ? "check Space permissions" : "upgrade the CLI"}`);
503
+ if (readyAt && Date.now() - readyAt >= 6e4) {
504
+ backoff = 500;
505
+ attempt = 0;
506
+ }
507
+ if (outcome.kind === "conflict") {
508
+ conflictSince ??= Date.now();
509
+ if (Date.now() - conflictSince >= (options.leaseConflictTimeoutMs ?? 9e4)) throw new Error("Space is already connected to another Runtime");
510
+ }
511
+ log("debug", "runtime.reconnect_scheduled", {
512
+ attempt: attempt || 1,
513
+ delayMs: backoff,
514
+ outcome: outcome.kind,
515
+ connectedMs: Date.now() - connectStartedAt,
516
+ readyMs: readyAt ? Date.now() - readyAt : null,
517
+ activeExecutions: executions.size
518
+ });
519
+ await setTimeout$1(backoff / 2 + Math.random() * backoff / 2, void 0, { signal: options.signal }).catch(() => void 0);
520
+ backoff = Math.min(3e4, backoff * 2);
521
+ }
522
+ } finally {
523
+ clearInterval(catalogTimer);
524
+ for (const execution of executions.values()) execution.controller.abort();
525
+ await Promise.allSettled([...executions.values()].map((entry) => entry.promise));
526
+ clearInterval(timer);
527
+ uploads.abort();
528
+ await flush();
529
+ log("info", "runtime.stopped", { runtimeId });
530
+ }
531
+ }
532
+ function frameIdentity(frame) {
533
+ const value = frame;
534
+ const event = value?.event;
535
+ const pick = (input) => typeof input === "string" ? input : void 0;
536
+ return {
537
+ frameType: pick(value?.type),
538
+ requestId: pick(value?.requestId),
539
+ eventType: pick(event?.type),
540
+ sessionId: pick(event?.sessionId) ?? pick(event?.input?.sessionId),
541
+ turnId: pick(event?.turnId) ?? pick(event?.input?.turnId),
542
+ harness: pick(event?.input?.harness),
543
+ nativeSessionId: pick(event?.input?.nativeSessionId),
544
+ turnCount: Array.isArray(event?.input?.turns) ? event.input.turns.length : void 0,
545
+ turnIds: Array.isArray(event?.input?.turns) ? event.input.turns.slice(0, 10).map((turn) => pick(turn?.turnId)).filter(Boolean) : void 0
546
+ };
547
+ }
548
+ function executionContext(connectionId, input) {
549
+ return {
550
+ connectionId,
551
+ sessionId: input.sessionId,
552
+ turnId: input.turnId,
553
+ harness: input.harness,
554
+ requestId: input.traceContext?.requestId ?? input.requestId ?? null,
555
+ traceContext: input.traceContext
556
+ };
557
+ }
558
+ async function connect(options) {
559
+ const log = (level, event, data, context) => options.diagnostics?.log(level, event, data, context);
560
+ const connectedAt = Date.now();
561
+ log("debug", "runtime.websocket.connecting", {
562
+ attempt: options.attempt,
563
+ url: options.url
564
+ });
565
+ let currentToken;
566
+ try {
567
+ currentToken = await options.token();
568
+ } catch (error) {
569
+ log("warn", error instanceof Error && error.name === "AuthRequiredError" ? "runtime.auth_required" : "runtime.auth_token_failed", { error: serializeDiagnosticError(error) });
570
+ throw error;
571
+ }
572
+ const runtimeUrl = new URL(options.url);
573
+ runtimeUrl.searchParams.set("runtimeId", options.runtimeId);
574
+ const socket = new WebSocket(runtimeUrl.toString());
575
+ const active = options.executions;
576
+ const seen = options.seen;
577
+ const disconnected = new AbortController();
578
+ const contexts = /* @__PURE__ */ new Map();
579
+ let lastHeartbeat = Date.now();
580
+ let openedAt = 0;
581
+ let readyAt = 0;
582
+ let connectionId = null;
583
+ let fatal = false;
584
+ let fatalCode = 0;
585
+ let fatalReason = "";
586
+ let conflict = false;
587
+ let unauthorized = false;
588
+ let readyTimer;
589
+ const nativePending = /* @__PURE__ */ new Map();
590
+ let nativeChannelReady = false;
591
+ const send = (frame) => {
592
+ if (socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > 33554432) {
593
+ log("warn", "runtime.frame_send_unavailable", {
594
+ readyState: socket.readyState,
595
+ bufferedBytes: socket.bufferedAmount
596
+ }, { connectionId });
597
+ throw new Error("Runtime connection unavailable");
598
+ }
599
+ const data = JSON.stringify(frame);
600
+ const bytes = Buffer.byteLength(data);
601
+ if (bytes > 33554432) {
602
+ const identity = frameIdentity(frame);
603
+ const execution = identity.requestId ? active.get(identity.requestId) : void 0;
604
+ log("error", "runtime.frame_too_large", {
605
+ bytes,
606
+ maxBytes: RUNTIME_MAX_FRAME_BYTES,
607
+ ...identity
608
+ }, execution ? executionContext(connectionId, execution) : { connectionId });
609
+ throw new SizeLimitError("Runtime frame exceeds transfer limit");
610
+ }
611
+ socket.send(data);
612
+ };
613
+ const closeTransport = () => socket.close();
614
+ /** What the Gateway holds for this connection. */
615
+ let registered = null;
616
+ let capabilitiesFrame = false;
617
+ const publishCatalog = () => {
618
+ const current = options.catalog.current;
619
+ if (!connectionId || isDeepStrictEqual(registered, capabilitiesFrame ? current : runtimeHelloCapabilities(current))) return;
620
+ if (!capabilitiesFrame) {
621
+ log("info", "runtime.catalog_reconnect", void 0, { connectionId });
622
+ closeTransport();
623
+ return;
624
+ }
625
+ try {
626
+ send({
627
+ type: "runtime.capabilities",
628
+ capabilities: current
629
+ });
630
+ registered = current;
631
+ log("info", "runtime.catalog_published", { modelCount: current.models.length }, { connectionId });
632
+ } catch (error) {
633
+ log("warn", "runtime.catalog_publish_failed", { error: serializeDiagnosticError(error) }, { connectionId });
634
+ closeTransport();
635
+ }
636
+ };
637
+ const shutdown = () => {
638
+ for (const execution of active.values()) execution.controller.abort();
639
+ closeTransport();
640
+ };
641
+ const sendNative = (event) => new Promise((resolve, reject) => {
642
+ if (!nativeChannelReady || !connectionId) {
643
+ reject(/* @__PURE__ */ new Error("Runtime native channel is unavailable"));
644
+ return;
645
+ }
646
+ const requestId = randomUUID();
647
+ const timer = setTimeout(() => {
648
+ nativePending.delete(requestId);
649
+ reject(/* @__PURE__ */ new Error("Native Runtime event timed out"));
650
+ }, event.type === "ingest" ? 12e4 : 3e4);
651
+ nativePending.set(requestId, {
652
+ resolve,
653
+ reject,
654
+ timer
655
+ });
656
+ try {
657
+ send({
658
+ type: "runtime.native",
659
+ requestId,
660
+ event
661
+ });
662
+ } catch (error) {
663
+ clearTimeout(timer);
664
+ nativePending.delete(requestId);
665
+ reject(error instanceof Error ? error : new Error(String(error)));
666
+ }
667
+ });
668
+ options.signal.addEventListener("abort", shutdown, { once: true });
669
+ const heartbeat = setInterval(() => {
670
+ const heartbeatAgeMs = Date.now() - lastHeartbeat;
671
+ if (heartbeatAgeMs > 3e4) {
672
+ log("error", "runtime.heartbeat_timeout", {
673
+ ageMs: heartbeatAgeMs,
674
+ activeExecutions: active.size,
675
+ readyState: socket.readyState,
676
+ bufferedBytes: socket.bufferedAmount
677
+ }, { connectionId });
678
+ closeTransport();
679
+ if (heartbeatAgeMs > 45e3) handleClose({
680
+ code: 1006,
681
+ reason: "Runtime heartbeat timed out",
682
+ wasClean: false
683
+ }, true);
684
+ } else if (connectionId) {
685
+ try {
686
+ send({ type: "runtime.heartbeat" });
687
+ } catch (error) {
688
+ log("warn", "runtime.heartbeat_send_failed", { error: serializeDiagnosticError(error) }, { connectionId });
689
+ closeTransport();
690
+ }
691
+ options.token().then((next) => {
692
+ if (next !== currentToken) try {
693
+ send({
694
+ type: "runtime.auth",
695
+ token: next
696
+ });
697
+ currentToken = next;
698
+ log("debug", "runtime.auth_refreshed", void 0, { connectionId });
699
+ } catch (error) {
700
+ log("warn", "runtime.auth_refresh_send_failed", { error: serializeDiagnosticError(error) }, { connectionId });
701
+ closeTransport();
702
+ }
703
+ }).catch((error) => {
704
+ log("warn", "runtime.auth_refresh_failed", { error: serializeDiagnosticError(error) }, { connectionId });
705
+ closeTransport();
706
+ });
707
+ }
708
+ }, 1e4);
709
+ const announceHere = (execution) => {
710
+ try {
711
+ send({
712
+ type: "runtime.recovery",
713
+ executions: [execution]
714
+ });
715
+ log("info", "runtime.detached_result_announced", void 0, executionContext(connectionId, execution));
716
+ } catch {}
717
+ };
718
+ /** Replays a saved result, or answers explicitly that none is available; never leaves the server waiting. */
719
+ const replaySaved = async (requestId, input, context, executionRequestId) => {
720
+ let saved = null;
721
+ try {
722
+ saved = await options.executor.results.recover(input, executionRequestId);
723
+ } catch (error) {
724
+ log("error", "runtime.recovery_failed", { error: serializeDiagnosticError(error) }, context);
725
+ }
726
+ if (saved) for (const event of saved.events) send({
727
+ type: "runtime.event",
728
+ requestId,
729
+ event
730
+ });
731
+ else send({
732
+ type: "runtime.event",
733
+ requestId,
734
+ event: {
735
+ type: "turn.error",
736
+ uncertain: true,
737
+ message: "Result unavailable; files retained"
738
+ }
739
+ });
740
+ };
741
+ let closeHandled = false;
742
+ let resolveClosed = () => {};
743
+ const closed = new Promise((resolve) => {
744
+ resolveClosed = resolve;
745
+ });
746
+ const handleClose = (event, forced = false) => {
747
+ if (closeHandled) return;
748
+ closeHandled = true;
749
+ unauthorized = event.code === 4401;
750
+ fatal = [4400, 4403].includes(event.code);
751
+ if (fatal) {
752
+ fatalCode = event.code;
753
+ fatalReason = event.reason;
754
+ }
755
+ conflict = event.code === 4409;
756
+ disconnected.abort();
757
+ const now = Date.now();
758
+ log(options.signal.aborted ? "debug" : fatal || conflict ? "error" : "warn", fatal ? "runtime.websocket.rejected" : "runtime.websocket.closed", {
759
+ code: event.code,
760
+ reason: event.reason,
761
+ wasClean: event.wasClean,
762
+ forced,
763
+ durationMs: now - connectedAt,
764
+ openMs: openedAt ? now - openedAt : null,
765
+ readyMs: readyAt ? now - readyAt : null,
766
+ lastInboundAgeMs: now - lastHeartbeat,
767
+ bufferedBytes: socket.bufferedAmount,
768
+ activeExecutions: active.size,
769
+ fatal,
770
+ conflict
771
+ }, { connectionId });
772
+ nativeChannelReady = false;
773
+ for (const pending of nativePending.values()) {
774
+ clearTimeout(pending.timer);
775
+ pending.reject(/* @__PURE__ */ new Error("Runtime native channel disconnected"));
776
+ }
777
+ nativePending.clear();
778
+ options.onDisconnected?.();
779
+ const executionMustStop = options.signal.aborted || fatal || conflict;
780
+ if (options.announce.current === announceHere) options.announce.current = null;
781
+ if (options.catalog.publish === publishCatalog) options.catalog.publish = null;
782
+ for (const [requestId, execution] of active) if (executionMustStop) {
783
+ log("error", "runtime.execution_transport_invalidated", {
784
+ code: event.code,
785
+ reason: event.reason
786
+ }, executionContext(connectionId, execution));
787
+ execution.controller.abort();
788
+ } else if (execution.recovery) execution.controller.abort();
789
+ else if (!execution.detached) {
790
+ execution.detached = true;
791
+ log("warn", "runtime.execution_transport_detached", {
792
+ code: event.code,
793
+ reason: event.reason
794
+ }, executionContext(connectionId, execution));
795
+ execution.promise.finally(() => {
796
+ if (!execution.result || active.get(requestId) !== execution) return;
797
+ options.announce.current?.({
798
+ sessionId: execution.sessionId,
799
+ turnId: execution.turnId,
800
+ harness: execution.harness
801
+ });
802
+ });
803
+ }
804
+ resolveClosed();
805
+ };
806
+ socket.addEventListener("close", (event) => handleClose(event), { once: true });
807
+ socket.addEventListener("error", (event) => {
808
+ const detail = event;
809
+ log("warn", "runtime.websocket.error", {
810
+ type: event.type,
811
+ message: typeof detail.message === "string" && detail.message ? detail.message : void 0,
812
+ readyState: socket.readyState,
813
+ opened: openedAt > 0,
814
+ ready: readyAt > 0,
815
+ lastInboundAgeMs: Date.now() - lastHeartbeat,
816
+ error: serializeDiagnosticError(detail.error ?? /* @__PURE__ */ new Error("WebSocket error"))
817
+ }, { connectionId });
818
+ socket.close();
819
+ });
820
+ socket.addEventListener("open", () => {
821
+ openedAt = Date.now();
822
+ try {
823
+ log("info", "runtime.websocket.open", {
824
+ attempt: options.attempt,
825
+ durationMs: Date.now() - connectedAt
826
+ });
827
+ registered = runtimeHelloCapabilities(options.catalog.current);
828
+ send({
829
+ type: "runtime.hello",
830
+ version: 1,
831
+ spaceId: options.spaceId,
832
+ token: currentToken,
833
+ capabilities: registered,
834
+ client: {
835
+ name: "cli",
836
+ version: CLI_VERSION
837
+ }
838
+ });
839
+ } catch (error) {
840
+ log("error", "runtime.hello_failed", { error: serializeDiagnosticError(error) });
841
+ closeTransport();
842
+ }
843
+ });
844
+ socket.addEventListener("message", (event) => {
845
+ (async () => {
846
+ let raw;
847
+ try {
848
+ raw = JSON.parse(String(event.data));
849
+ } catch (error) {
850
+ log("error", "runtime.protocol.invalid_json", { error: serializeDiagnosticError(error) }, { connectionId });
851
+ throw error;
852
+ }
853
+ lastHeartbeat = Date.now();
854
+ if (raw.type === "runtime.ready") {
855
+ const frame = runtimeReadySchema.parse(raw);
856
+ if (connectionId === frame.connectionId) return;
857
+ if (connectionId) throw new Error("Runtime connection identity changed");
858
+ connectionId = frame.connectionId;
859
+ readyAt = Date.now();
860
+ clearTimeout(readyTimer);
861
+ log("info", "runtime.ready", {
862
+ connectionId,
863
+ durationMs: readyAt - connectedAt,
864
+ detachedExecutions: [...active.values()].filter((entry) => entry.detached).length
865
+ }, { connectionId });
866
+ nativeChannelReady = true;
867
+ capabilitiesFrame = frame.features?.includes("capabilities") === true;
868
+ options.onNativeChannel?.(sendNative, { approvals: frame.features?.includes("approvals") === true });
869
+ options.onReady();
870
+ options.announce.current = announceHere;
871
+ options.catalog.publish = publishCatalog;
872
+ publishCatalog();
873
+ let recoveryBatch = 0;
874
+ for await (const executions of options.executor.results.pendingBatches()) {
875
+ recoveryBatch += 1;
876
+ log("info", "runtime.recovery_batch_sent", {
877
+ batch: recoveryBatch,
878
+ count: executions.length
879
+ }, { connectionId });
880
+ send({
881
+ type: "runtime.recovery",
882
+ executions
883
+ });
884
+ }
885
+ return;
886
+ }
887
+ if (!connectionId) throw new Error("Runtime handshake is incomplete");
888
+ if (raw.type === "runtime.heartbeat") return;
889
+ if (raw.type === "runtime.native.stop") {
890
+ const stop = runtimeNativeStopSchema.safeParse(raw);
891
+ if (!stop.success) {
892
+ log("warn", "runtime.protocol.invalid_native_stop", { error: stop.error.message }, { connectionId });
893
+ return;
894
+ }
895
+ if (stop.data.spaceId === options.spaceId) options.onNativeStop?.(stop.data);
896
+ return;
897
+ }
898
+ if (raw.type === "runtime.approval.decision") {
899
+ const decision = runtimeApprovalDecisionSchema.safeParse(raw);
900
+ if (!decision.success) {
901
+ log("warn", "runtime.protocol.invalid_approval_decision", { error: decision.error.message }, { connectionId });
902
+ return;
903
+ }
904
+ if (decision.data.spaceId === options.spaceId) options.onApprovalDecision?.(decision.data);
905
+ return;
906
+ }
907
+ if (raw.type === "runtime.native.result") {
908
+ const result = raw;
909
+ const pending = result.requestId ? nativePending.get(result.requestId) : null;
910
+ if (!pending) return;
911
+ clearTimeout(pending.timer);
912
+ nativePending.delete(result.requestId ?? "");
913
+ if (result.error) pending.reject(new Error(result.error));
914
+ else pending.resolve(result.result);
915
+ return;
916
+ }
917
+ const frame = runtimeCommandSchema.parse(raw);
918
+ if (frame.type === "session.context") {
919
+ log("debug", "runtime.context_received", { messageCount: frame.context.messages.length }, { connectionId });
920
+ contexts.get(frame.requestId)?.(frame.context);
921
+ contexts.delete(frame.requestId);
922
+ return;
923
+ }
924
+ if (frame.type === "turn.abort") {
925
+ log("info", "runtime.turn_abort_received", void 0, {
926
+ connectionId,
927
+ requestId: frame.requestId
928
+ });
929
+ active.get(frame.requestId)?.controller.abort();
930
+ return;
931
+ }
932
+ if (frame.type === "turn.ack") {
933
+ const execution = active.get(frame.requestId);
934
+ if (!execution) return;
935
+ const context = executionContext(connectionId, execution);
936
+ try {
937
+ await execution.promise;
938
+ if (!execution.result) throw new Error("Runtime result is not available");
939
+ await options.executor.results.acknowledge(execution.sessionId, frame.turnId);
940
+ } catch (error) {
941
+ log("error", "runtime.turn_ack_failed", {
942
+ revision: frame.revision,
943
+ error: serializeDiagnosticError(error)
944
+ }, context);
945
+ active.delete(frame.requestId);
946
+ send({
947
+ type: "runtime.event",
948
+ requestId: frame.requestId,
949
+ event: {
950
+ type: "turn.error",
951
+ message: "Local acknowledgement failed; result retained"
952
+ }
953
+ });
954
+ return;
955
+ }
956
+ log("info", "runtime.turn_acknowledged", { revision: frame.revision }, context);
957
+ active.delete(frame.requestId);
958
+ send({
959
+ type: "runtime.event",
960
+ requestId: frame.requestId,
961
+ event: { type: "turn.acknowledged" }
962
+ });
963
+ return;
964
+ }
965
+ if (frame.type === "turn.recover") {
966
+ const identity = frame.execution;
967
+ if (identity.spaceId !== options.spaceId) throw new Error("Invalid Runtime target");
968
+ const context = executionContext(connectionId, {
969
+ ...identity,
970
+ requestId: frame.traceContext?.requestId,
971
+ traceContext: frame.traceContext
972
+ });
973
+ log("info", "runtime.recovery_requested", void 0, context);
974
+ const previous = active.get(frame.requestId);
975
+ if (previous) {
976
+ if (previous.sessionId !== identity.sessionId || previous.turnId !== identity.turnId || previous.harness !== identity.harness) throw new Error("Runtime recovery identity changed");
977
+ await previous.promise;
978
+ await replaySaved(frame.requestId, identity, context);
979
+ return;
980
+ }
981
+ const running = [...active].find(([, entry]) => entry.turnId === identity.turnId && entry.sessionId === identity.sessionId && entry.harness === identity.harness);
982
+ const recovery = {
983
+ ...identity,
984
+ requestId: frame.traceContext?.requestId,
985
+ traceContext: frame.traceContext,
986
+ controller: new AbortController(),
987
+ promise: Promise.resolve(),
988
+ recovery: true
989
+ };
990
+ active.set(frame.requestId, recovery);
991
+ recovery.promise = (async () => {
992
+ try {
993
+ if (running) {
994
+ if (running[1].detached) {
995
+ log("info", "runtime.recovery_waiting_detached", { runningRequestId: running[0] }, context);
996
+ const stopped = recovery.controller.signal;
997
+ await Promise.race([running[1].promise, new Promise((resolve) => stopped.addEventListener("abort", () => resolve(), { once: true }))]);
998
+ stopped.throwIfAborted();
999
+ } else {
1000
+ running[1].controller.abort();
1001
+ await running[1].promise;
1002
+ }
1003
+ if (active.get(running[0]) === running[1]) active.delete(running[0]);
1004
+ }
1005
+ const saved = await options.executor.results.recover(identity);
1006
+ recovery.controller.signal.throwIfAborted();
1007
+ const last = saved?.events.at(-1);
1008
+ if (!saved || last?.type !== "turn.end") throw new Error("No confirmed result");
1009
+ recovery.result = {
1010
+ session: saved.session,
1011
+ event: last
1012
+ };
1013
+ for (const event of saved.events) send({
1014
+ type: "runtime.event",
1015
+ requestId: frame.requestId,
1016
+ event
1017
+ });
1018
+ } catch (error) {
1019
+ if (!recovery.controller.signal.aborted) {
1020
+ log("error", "runtime.recovery_failed", { error: serializeDiagnosticError(error) }, context);
1021
+ try {
1022
+ send({
1023
+ type: "runtime.event",
1024
+ requestId: frame.requestId,
1025
+ event: {
1026
+ type: "turn.error",
1027
+ uncertain: true,
1028
+ message: "Result unavailable; files retained"
1029
+ }
1030
+ });
1031
+ } catch {}
1032
+ }
1033
+ if (active.get(frame.requestId) === recovery) active.delete(frame.requestId);
1034
+ }
1035
+ })();
1036
+ return;
1037
+ }
1038
+ if (frame.input.spaceId !== options.spaceId || !options.catalog.current.harnesses.includes(frame.input.harness)) throw new Error("Invalid Runtime target");
1039
+ const context = executionContext(connectionId, frame.input);
1040
+ log("info", "runtime.turn_received", {
1041
+ requestId: frame.requestId,
1042
+ resumeOnly: frame.resumeOnly === true
1043
+ }, context);
1044
+ const previous = active.get(frame.requestId);
1045
+ if (previous) {
1046
+ if (previous.sessionId !== frame.input.sessionId || previous.turnId !== frame.input.turnId || previous.harness !== frame.input.harness) throw new Error("Runtime execution identity changed");
1047
+ log("info", "runtime.execution_resumed", {
1048
+ detached: previous.detached === true,
1049
+ settled: Boolean(previous.result)
1050
+ }, executionContext(connectionId, frame.input));
1051
+ await previous.promise;
1052
+ await replaySaved(frame.requestId, frame.input, context, frame.requestId);
1053
+ return;
1054
+ }
1055
+ const requestContext = async (executionSignal) => {
1056
+ const signal = AbortSignal.any([executionSignal, disconnected.signal]);
1057
+ signal.throwIfAborted();
1058
+ const pendingTurnIds = await options.executor.results.pendingTurnIds(frame.input.sessionId);
1059
+ log("debug", "runtime.context_requested", { pendingTurnCount: pendingTurnIds.length }, context);
1060
+ return new Promise((resolve, reject) => {
1061
+ const abort = () => {
1062
+ clearTimeout(timeout);
1063
+ contexts.delete(frame.requestId);
1064
+ signal.removeEventListener("abort", abort);
1065
+ reject(/* @__PURE__ */ new Error("Runtime context request aborted"));
1066
+ };
1067
+ const timeout = setTimeout(abort, 6e4);
1068
+ signal.addEventListener("abort", abort, { once: true });
1069
+ contexts.set(frame.requestId, (nextContext) => {
1070
+ clearTimeout(timeout);
1071
+ signal.removeEventListener("abort", abort);
1072
+ resolve(nextContext);
1073
+ });
1074
+ try {
1075
+ send({
1076
+ type: "runtime.event",
1077
+ requestId: frame.requestId,
1078
+ event: {
1079
+ type: "context.required",
1080
+ pendingTurnIds
1081
+ }
1082
+ });
1083
+ } catch {
1084
+ abort();
1085
+ }
1086
+ if (signal.aborted) abort();
1087
+ });
1088
+ };
1089
+ if ([...active.values()].some((entry) => entry.sessionId === frame.input.sessionId) && !frame.input.context.complete) frame.input.context = await requestContext(options.signal);
1090
+ const repeated = seen.has(frame.requestId);
1091
+ for (const [requestId, entry] of active) {
1092
+ if (entry.sessionId !== frame.input.sessionId) continue;
1093
+ const resolved = frame.input.context.resolvedTurnIds?.includes(entry.turnId);
1094
+ const settled = entry.result && frame.input.context.settledTurnIds?.includes(entry.turnId);
1095
+ if (!resolved && !settled) continue;
1096
+ entry.controller.abort();
1097
+ await entry.promise;
1098
+ active.delete(requestId);
1099
+ }
1100
+ if ([...active.values()].some((entry) => entry.sessionId === frame.input.sessionId) || active.size >= 8) {
1101
+ log("warn", "runtime.turn_rejected_busy", { activeExecutions: active.size }, context);
1102
+ send({
1103
+ type: "runtime.event",
1104
+ requestId: frame.requestId,
1105
+ event: {
1106
+ type: "turn.error",
1107
+ message: "Local Runtime is busy"
1108
+ }
1109
+ });
1110
+ return;
1111
+ }
1112
+ seen.add(frame.requestId);
1113
+ if (seen.size > 4096) {
1114
+ const oldest = seen.values().next().value;
1115
+ if (oldest) seen.delete(oldest);
1116
+ }
1117
+ const controller = new AbortController();
1118
+ const execution = {
1119
+ controller,
1120
+ sessionId: frame.input.sessionId,
1121
+ turnId: frame.input.turnId,
1122
+ harness: frame.input.harness,
1123
+ requestId: frame.input.requestId,
1124
+ traceContext: frame.input.traceContext,
1125
+ promise: Promise.resolve()
1126
+ };
1127
+ active.set(frame.requestId, execution);
1128
+ const durableEvents = [];
1129
+ const emit = (value) => {
1130
+ if (value.type === "message.commit") durableEvents.push(value);
1131
+ if (disconnected.signal.aborted || socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > 33554432) return;
1132
+ try {
1133
+ send({
1134
+ type: "runtime.event",
1135
+ requestId: frame.requestId,
1136
+ event: value
1137
+ });
1138
+ } catch (error) {
1139
+ if (!disconnected.signal.aborted && socket.readyState === WebSocket.OPEN) throw error;
1140
+ }
1141
+ };
1142
+ execution.promise = (async () => {
1143
+ try {
1144
+ const saved = await options.executor.results.recover(frame.input, frame.requestId);
1145
+ if (saved) {
1146
+ const last = saved.events.at(-1);
1147
+ if (last?.type !== "turn.end") throw new Error("Incomplete saved Runtime result");
1148
+ execution.result = {
1149
+ session: saved.session,
1150
+ event: last
1151
+ };
1152
+ for (const event of saved.events) emit(event);
1153
+ return;
1154
+ }
1155
+ if (frame.resumeOnly || repeated) {
1156
+ emit({
1157
+ type: "turn.error",
1158
+ message: "Execution outcome is unknown; native files retained, no replay",
1159
+ uncertain: true
1160
+ });
1161
+ active.delete(frame.requestId);
1162
+ return;
1163
+ }
1164
+ const run = () => executeTurn(options.executor, frame.input, emit, controller.signal, frame.requestId, context);
1165
+ for (let retry = 0;; retry += 1) try {
1166
+ execution.result = await run();
1167
+ break;
1168
+ } catch (error) {
1169
+ if (!(error instanceof ContextRequiredError) || retry >= 2) throw error;
1170
+ frame.input.context = await requestContext(controller.signal);
1171
+ }
1172
+ await options.executor.results.record(execution.result.session, frame.input, frame.requestId, [...durableEvents, execution.result.event], execution.result.uncertainCleanup);
1173
+ if (execution.result.uncertainCleanup) log("warn", "runtime.turn_cleanup_pending", { cleanup: execution.result.uncertainCleanup.error }, context);
1174
+ emit(execution.result.event);
1175
+ } catch (error) {
1176
+ log("error", "runtime.turn_failed", {
1177
+ uncertain: Boolean(execution.result) || frame.resumeOnly === true || error instanceof ProcessCleanupUncertainError,
1178
+ error: serializeDiagnosticError(error)
1179
+ }, context);
1180
+ try {
1181
+ emit({
1182
+ type: "turn.error",
1183
+ message: describeError(error),
1184
+ uncertain: !!execution.result || frame.resumeOnly === true || error instanceof ProcessCleanupUncertainError
1185
+ });
1186
+ } catch {}
1187
+ active.delete(frame.requestId);
1188
+ }
1189
+ })();
1190
+ })().catch((error) => {
1191
+ log("error", "runtime.protocol_error", { error: serializeDiagnosticError(error) }, { connectionId });
1192
+ closeTransport();
1193
+ });
1194
+ });
1195
+ readyTimer = setTimeout(() => {
1196
+ log("error", "runtime.handshake_timeout", { timeoutMs: 15e3 }, { connectionId });
1197
+ socket.close(4408, "Runtime handshake timed out");
1198
+ }, 15e3);
1199
+ if (options.signal.aborted) shutdown();
1200
+ try {
1201
+ await closed;
1202
+ } finally {
1203
+ clearTimeout(readyTimer);
1204
+ clearInterval(heartbeat);
1205
+ options.signal.removeEventListener("abort", shutdown);
1206
+ }
1207
+ if (unauthorized && !options.signal.aborted) await options.token(true);
1208
+ return fatal ? {
1209
+ kind: "fatal",
1210
+ code: fatalCode,
1211
+ reason: fatalReason
1212
+ } : conflict ? { kind: "conflict" } : { kind: "retry" };
1213
+ }
1214
+ //#endregion
1215
+ //#region src/runtime/cli-path.ts
1216
+ const ENTRY = packagePath("bin", "cohub.js");
1217
+ /**
1218
+ * Puts this Runtime's own `cohub` last on PATH, so what it runs can always call the CLI while a
1219
+ * `cohub` already on PATH (a global install that updates itself) still comes first.
1220
+ */
1221
+ function appendCliToPath(env = process.env, node = process.execPath, entry = ENTRY) {
1222
+ const dir = join(homedir(), ".cache", "cohub", "cli", createHash("sha256").update(`${node}\0${entry}`).digest("hex").slice(0, 12));
1223
+ const windows = process.platform === "win32";
1224
+ const script = windows ? `@"${node}" "${entry}" %*\r\n` : `#!/bin/sh\nexec ${quote(node)} ${quote(entry)} "$@"\n`;
1225
+ mkdirSync(dir, { recursive: true });
1226
+ const file = join(dir, windows ? "cohub.cmd" : "cohub");
1227
+ const temporary = `${file}.${process.pid}`;
1228
+ writeFileSync(temporary, script, { mode: 493 });
1229
+ renameSync(temporary, file);
1230
+ const path = env.PATH?.split(delimiter).filter(Boolean) ?? [];
1231
+ if (!path.includes(dir)) env.PATH = [...path, dir].join(delimiter);
1232
+ return dir;
1233
+ }
1234
+ const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
1235
+ //#endregion
1236
+ //#region src/runtime/native/approvals.ts
1237
+ /** How long a card waits for a person; unanswered, the request is declined. */
1238
+ const APPROVAL_TIMEOUT_MS = 18e5;
1239
+ /** Asks the web for a decision over the control connection; without one, it declines. */
1240
+ var ApprovalBroker = class {
1241
+ timeoutMs;
1242
+ send = null;
1243
+ pending = /* @__PURE__ */ new Map();
1244
+ constructor(timeoutMs = APPROVAL_TIMEOUT_MS) {
1245
+ this.timeoutMs = timeoutMs;
1246
+ }
1247
+ /** `null` when the Gateway cannot relay decisions; open cards are then declined. */
1248
+ connect(send) {
1249
+ this.send = send;
1250
+ if (!send) for (const entry of this.pending.values()) entry.resolve("decline");
1251
+ }
1252
+ get available() {
1253
+ return this.send !== null;
1254
+ }
1255
+ async request(sessionId, turnId, request, signal) {
1256
+ const send = this.send;
1257
+ if (!send || signal.aborted) return "decline";
1258
+ const id = randomUUID();
1259
+ const now = Date.now();
1260
+ let timer;
1261
+ let onAbort = () => {};
1262
+ const decided = new Promise((resolve) => {
1263
+ this.pending.set(id, {
1264
+ sessionId,
1265
+ turnId,
1266
+ resolve
1267
+ });
1268
+ timer = setTimeout(() => resolve("decline"), this.timeoutMs);
1269
+ onAbort = () => resolve("decline");
1270
+ signal.addEventListener("abort", onAbort, { once: true });
1271
+ });
1272
+ try {
1273
+ await send({
1274
+ type: "approval",
1275
+ sessionId,
1276
+ turnId,
1277
+ approval: {
1278
+ ...request,
1279
+ id,
1280
+ requestedAt: new Date(now).toISOString(),
1281
+ expiresAt: new Date(now + this.timeoutMs).toISOString()
1282
+ }
1283
+ });
1284
+ return await decided;
1285
+ } catch {
1286
+ return "decline";
1287
+ } finally {
1288
+ clearTimeout(timer);
1289
+ signal.removeEventListener("abort", onAbort);
1290
+ this.pending.delete(id);
1291
+ this.send?.({
1292
+ type: "approval.closed",
1293
+ sessionId,
1294
+ turnId,
1295
+ approvalId: id
1296
+ }).catch(() => void 0);
1297
+ }
1298
+ }
1299
+ decide(input) {
1300
+ const entry = this.pending.get(input.approvalId);
1301
+ if (entry && entry.sessionId === input.sessionId && entry.turnId === input.turnId) entry.resolve(input.decision);
1302
+ }
1303
+ };
1304
+ //#endregion
1305
+ //#region src/runtime/turn-projection.ts
1306
+ const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
1307
+ const iso = (value) => value ?? (/* @__PURE__ */ new Date(0)).toISOString();
1308
+ const sourceSessionId = (turn) => turn.sourceSessionId ?? turn.sessionId;
1309
+ const sourceTurnId = (turn) => turn.sourceTurnId ?? turn.id;
1310
+ const userMessageId = (turn) => {
1311
+ const value = record(turn.meta).userMessageId;
1312
+ return typeof value === "string" && value ? value : `${turn.id}:user`;
1313
+ };
1314
+ function hydrateToolDetails(content, calls) {
1315
+ const byId = new Map(calls.map((call) => [call.id, call]));
1316
+ return content.map((block) => {
1317
+ if (block.type === "tool_use") {
1318
+ const call = byId.get(block.id);
1319
+ return call ? {
1320
+ ...block,
1321
+ input: call.input
1322
+ } : block;
1323
+ }
1324
+ if (block.type === "tool_result") {
1325
+ const call = byId.get(block.tool_use_id);
1326
+ return call?.result ? {
1327
+ ...block,
1328
+ content: call.result.content ?? block.content,
1329
+ is_error: call.result.isError
1330
+ } : block;
1331
+ }
1332
+ return block;
1333
+ });
1334
+ }
1335
+ async function hydrateIntermediateMessage(turn, message, client, signal) {
1336
+ signal?.throwIfAborted();
1337
+ const toolCalls = await client.turns.intermediate.getToolCalls(turn.id, message, { signal });
1338
+ return {
1339
+ id: message.id,
1340
+ turnId: turn.id,
1341
+ role: message.role,
1342
+ content: hydrateToolDetails(message.content, toolCalls?.toolCalls ?? []),
1343
+ provider: message.provider,
1344
+ model: message.model,
1345
+ usage: message.usage,
1346
+ stopReason: message.stopReason,
1347
+ errorMessage: message.errorMessage,
1348
+ meta: message.meta,
1349
+ sourceSessionId: message.sessionId,
1350
+ sequence: message.sequence ?? 0,
1351
+ createdAt: iso(message.createdAt)
1352
+ };
1353
+ }
1354
+ async function mapWithConcurrency(items, concurrency, mapper) {
1355
+ const results = new Array(items.length);
1356
+ let next = 0;
1357
+ const worker = async () => {
1358
+ for (;;) {
1359
+ const index = next++;
1360
+ if (index >= items.length) return;
1361
+ const item = items[index];
1362
+ if (item === void 0) return;
1363
+ results[index] = await mapper(item);
1364
+ }
1365
+ };
1366
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
1367
+ return results;
1368
+ }
1369
+ async function hydrateSessionTurn(turn, client, signal) {
1370
+ const sourceId = sourceSessionId(turn);
1371
+ const messages = [];
1372
+ if (turn.userContent.length) messages.push({
1373
+ id: userMessageId(turn),
1374
+ turnId: turn.id,
1375
+ role: "user",
1376
+ content: turn.userContent,
1377
+ meta: {
1378
+ userMessageId: userMessageId(turn),
1379
+ turnId: turn.id
1380
+ },
1381
+ sourceSessionId: sourceId,
1382
+ sequence: turn.sequence * 1e6,
1383
+ createdAt: iso(turn.createdAt)
1384
+ });
1385
+ const objectKey = turn.intermediateIndex?.messagesObjectKey;
1386
+ if (!objectKey && (turn.intermediateSummary?.messageCount ?? 0) > 0) throw new Error(`Intermediate message index is unavailable for Turn ${turn.id}`);
1387
+ if (objectKey) {
1388
+ const archive = await client.turns.intermediate.get(turn.id, objectKey, { signal });
1389
+ if (!archive) throw new Error(`Intermediate messages are unavailable for Turn ${turn.id}`);
1390
+ const intermediate = await mapWithConcurrency(archive.messages, 8, (message) => hydrateIntermediateMessage(turn, message, client, signal));
1391
+ messages.push(...intermediate.map((message) => ({
1392
+ ...message,
1393
+ sequence: turn.sequence * 1e6 + 1e5 + message.sequence
1394
+ })));
1395
+ }
1396
+ const hasFinalGenerationResult = messages.some((message) => message.role === "assistant" && message.meta?.messageKind === "generation_result" && ["completed", "failed"].includes(String(message.meta.generationStatus)));
1397
+ if (turn.assistantContent?.length && !hasFinalGenerationResult) messages.push({
1398
+ id: `${turn.id}:assistant`,
1399
+ turnId: turn.id,
1400
+ role: turn.intent === "compact" ? "system" : "assistant",
1401
+ content: turn.assistantContent,
1402
+ provider: turn.provider,
1403
+ model: turn.model,
1404
+ usage: turn.finalUsage,
1405
+ stopReason: turn.stopReason,
1406
+ errorMessage: turn.errorMessage,
1407
+ meta: {
1408
+ ...turn.meta ?? {},
1409
+ turnId: turn.id,
1410
+ createdAt: turn.createdAt
1411
+ },
1412
+ sourceSessionId: sourceId,
1413
+ sequence: turn.sequence * 1e6 + 9e5,
1414
+ createdAt: iso(turn.createdAt)
1415
+ });
1416
+ messages.sort((left, right) => left.sequence - right.sequence || left.id.localeCompare(right.id));
1417
+ return {
1418
+ id: turn.id,
1419
+ sourceSessionId: sourceId,
1420
+ sourceTurnId: sourceTurnId(turn),
1421
+ sequence: turn.sequence,
1422
+ status: turn.status,
1423
+ intent: turn.intent,
1424
+ provider: turn.provider,
1425
+ model: turn.model,
1426
+ userContent: turn.userContent,
1427
+ assistantContent: turn.assistantContent,
1428
+ meta: turn.meta,
1429
+ createdAt: iso(turn.createdAt),
1430
+ startedAt: turn.startedAt,
1431
+ completedAt: turn.completedAt,
1432
+ durationMs: turn.durationMs,
1433
+ messages
1434
+ };
1435
+ }
1436
+ async function listSessionProjectionTurns(source, sessionId, options = {}) {
1437
+ const client = source.session(sessionId);
1438
+ const turns = [];
1439
+ const throughSequence = options.throughSequence ?? null;
1440
+ let cursor = options.afterSequence && options.afterSequence > 0 ? options.afterSequence : void 0;
1441
+ for (;;) {
1442
+ options.signal?.throwIfAborted();
1443
+ const page = await client.turns.listPaginated({
1444
+ cursor,
1445
+ limit: 100,
1446
+ direction: "newer"
1447
+ }, { signal: options.signal });
1448
+ const visible = page.turns.filter((turn) => (throughSequence == null || turn.sequence <= throughSequence) && turn.id !== options.excludeTurnId && ![
1449
+ "queued",
1450
+ "running",
1451
+ "abort_requested"
1452
+ ].includes(turn.status));
1453
+ turns.push(...visible);
1454
+ if (throughSequence != null && page.turns.some((turn) => turn.sequence >= throughSequence)) break;
1455
+ if (!page.hasMore) break;
1456
+ if (page.nextCursor === void 0 || page.nextCursor === cursor) throw new Error("Session Turn pagination did not advance");
1457
+ cursor = page.nextCursor;
1458
+ }
1459
+ return mapWithConcurrency(turns, 4, (turn) => hydrateSessionTurn(turn, client, options.signal));
1460
+ }
1461
+ function projectTurnBatch(input, target) {
1462
+ return harnessAdapter(target).session.project(input);
1463
+ }
1464
+ //#endregion
1465
+ //#region src/runtime/projection-store.ts
1466
+ /** Give the projection's own records (the native header) the identity of the file it becomes. */
1467
+ function rebindProjectionNativeSession(result, nativeSessionId) {
1468
+ const records = harnessAdapter(result.projection.target).session.rebind(result.projection.records, nativeSessionId);
1469
+ return {
1470
+ ...result,
1471
+ projection: {
1472
+ ...result.projection,
1473
+ records
1474
+ }
1475
+ };
1476
+ }
1477
+ /**
1478
+ * Materializes a Session's durable Turns into one harness-specific native file. Cohub never appends
1479
+ * to a native file it did not just write, so every projection is complete up to the Session head.
1480
+ */
1481
+ var ProjectionStore = class {
1482
+ source;
1483
+ constructor(source) {
1484
+ this.source = source;
1485
+ }
1486
+ async project(input, signal) {
1487
+ const throughSequence = input.throughTurnId ? (await this.source.session(input.sessionId).turns.get(input.throughTurnId, { signal })).turn.sequence : 0;
1488
+ const turns = await listSessionProjectionTurns(this.source, input.sessionId, {
1489
+ throughSequence,
1490
+ excludeTurnId: input.turnId,
1491
+ signal
1492
+ });
1493
+ return {
1494
+ projection: projectTurnBatch({
1495
+ spaceId: input.spaceId,
1496
+ sessionId: input.sessionId,
1497
+ nativeSessionId: input.nativeSessionId,
1498
+ cwd: input.cwd,
1499
+ provider: input.provider,
1500
+ turns
1501
+ }, input.target),
1502
+ turns
1503
+ };
1504
+ }
1505
+ };
1506
+ //#endregion
1507
+ //#region src/runtime/native/sessions.ts
1508
+ /** Chooses the native file a Turn runs in. 1. */
1509
+ var NativeSessions = class {
1510
+ options;
1511
+ projections;
1512
+ constructor(options) {
1513
+ this.options = options;
1514
+ this.projections = new ProjectionStore(options.projectionSource);
1515
+ }
1516
+ async prepare(input) {
1517
+ const existing = this.options.ingest.transcriptFor(input.sessionId, input.harness, input.context.throughTurnId);
1518
+ if (existing && input.resumable(existing)) return {
1519
+ session: {
1520
+ harness: existing.harness,
1521
+ nativeSessionId: existing.nativeSessionId,
1522
+ path: existing.path,
1523
+ cwd: existing.cwd
1524
+ },
1525
+ resume: "native"
1526
+ };
1527
+ const archive = input.context.archive;
1528
+ if (archive && archive.harness === input.harness && archive.sessionId === input.sessionId && archive.turnId === input.context.throughTurnId) {
1529
+ const restored = await this.restore(input, archive, input.signal).catch((error) => {
1530
+ input.signal?.throwIfAborted();
1531
+ this.options.onRestoreFailed?.(error, {
1532
+ sessionId: input.sessionId,
1533
+ harness: input.harness,
1534
+ unrestorable: error instanceof ArchiveNotRestorableError
1535
+ });
1536
+ return null;
1537
+ });
1538
+ if (restored) {
1539
+ const through = (await readTranscript(restored.path, restored.harness).catch(() => null))?.turns.at(-1)?.key ?? null;
1540
+ if (through) this.options.ingest.adopt(restored, input.sessionId, {
1541
+ turnKey: through,
1542
+ turnId: input.context.throughTurnId
1543
+ });
1544
+ else this.options.ingest.adopt(restored, input.sessionId);
1545
+ return {
1546
+ session: restored,
1547
+ resume: "restored"
1548
+ };
1549
+ }
1550
+ }
1551
+ const projected = await this.project(input);
1552
+ if (projected.resume !== "new" || !harnessAdapter(input.harness).session.startsWithoutFile) this.options.ingest.adopt(projected.session, input.sessionId);
1553
+ return projected;
1554
+ }
1555
+ async restore(input, archive, signal) {
1556
+ const id = randomUUID();
1557
+ const raw = join(this.options.root, "native", "restored", `${id}.jsonl`);
1558
+ const format = harnessAdapter(input.harness).session.archive;
1559
+ if (!format) throw new ArchiveNotRestorableError(`${input.harness} archives are not restorable`);
1560
+ try {
1561
+ const restored = await this.options.archives.restore(archive, raw, signal);
1562
+ const path = format.target({
1563
+ id,
1564
+ nativeSessionId: restored.nativeSessionId,
1565
+ cwd: input.cwd
1566
+ });
1567
+ const imported = await format.import({
1568
+ source: raw,
1569
+ target: path,
1570
+ nativeSessionId: restored.nativeSessionId,
1571
+ id,
1572
+ cwd: input.cwd,
1573
+ signal
1574
+ });
1575
+ return {
1576
+ harness: input.harness,
1577
+ nativeSessionId: imported.nativeSessionId,
1578
+ path,
1579
+ cwd: input.cwd
1580
+ };
1581
+ } finally {
1582
+ await rm(raw, { force: true }).catch(() => void 0);
1583
+ }
1584
+ }
1585
+ async project(input) {
1586
+ const format = harnessAdapter(input.harness).session;
1587
+ const nativeSessionId = randomUUID();
1588
+ const path = format.path(nativeSessionId, input.cwd);
1589
+ const projection = rebindProjectionNativeSession(await this.projections.project({
1590
+ spaceId: this.options.spaceId,
1591
+ sessionId: input.sessionId,
1592
+ turnId: input.turnId,
1593
+ nativeSessionId,
1594
+ cwd: input.cwd,
1595
+ provider: input.provider,
1596
+ target: input.harness,
1597
+ throughTurnId: input.context.throughTurnId
1598
+ }, input.signal), nativeSessionId);
1599
+ const session = {
1600
+ harness: input.harness,
1601
+ nativeSessionId,
1602
+ path,
1603
+ cwd: input.cwd
1604
+ };
1605
+ if ((!projection.turns.length || !projection.projection.records.length) && format.startsWithoutFile) return {
1606
+ session,
1607
+ resume: "new"
1608
+ };
1609
+ await mkdir(dirname(path), {
1610
+ recursive: true,
1611
+ mode: 448
1612
+ });
1613
+ const temporary = `${path}.${randomUUID()}.projection`;
1614
+ await writeFile(temporary, serializeProjectionRecords(projection.projection.records), { mode: 384 });
1615
+ await rename(temporary, path);
1616
+ return {
1617
+ session,
1618
+ resume: projection.turns.length ? "handoff" : "new"
1619
+ };
1620
+ }
1621
+ };
1622
+ //#endregion
1623
+ //#region src/runtime/native/transport.ts
1624
+ /**
1625
+ * Transcript ingest travels over the existing Runtime WebSocket: one connection, one credential, no
1626
+ * second channel and no local receipts.
1627
+ */
1628
+ function nativeWebSocketTransport(send) {
1629
+ const call = async (event, options) => {
1630
+ options?.signal?.throwIfAborted();
1631
+ return await send(event);
1632
+ };
1633
+ return {
1634
+ ingest: (event, options) => call(event, options),
1635
+ known: async (turnIds, options) => (await call({
1636
+ type: "known",
1637
+ input: { turnIds }
1638
+ }, options)).turns,
1639
+ progress: (event, options) => call(event, options),
1640
+ status: (sessionId, turnId, controllable, options) => call({
1641
+ type: "status",
1642
+ sessionId,
1643
+ turnId,
1644
+ ...controllable === void 0 ? {} : { controllable }
1645
+ }, options)
1646
+ };
1647
+ }
1648
+ //#endregion
1649
+ //#region src/runtime/native/daemon.ts
1650
+ const text = (value) => typeof value === "string" ? value : "";
1651
+ /** Streamed previews reach the web at most this often. */
1652
+ const STREAM_INTERVAL_MS = 250;
1653
+ /** A client Cohub cannot stream is previewed from its file, at most this often. */
1654
+ const FILE_PREVIEW_INTERVAL_MS = 2e3;
1655
+ /** A file preview waits at least this many times as long as its last read took. */
1656
+ const FILE_PREVIEW_COST_FACTOR = 20;
1657
+ /**
1658
+ * Everything the Runtime does with native sessions: the ingest engine (data plane), the Pi and
1659
+ * Codex links (control plane), and the executor that runs Cohub Turns through them.
1660
+ */
1661
+ var NativeRuntime = class {
1662
+ options;
1663
+ ingest;
1664
+ executor;
1665
+ pi;
1666
+ codex;
1667
+ streams = /* @__PURE__ */ new Map();
1668
+ filePreviews = /* @__PURE__ */ new Map();
1669
+ watched = /* @__PURE__ */ new Map();
1670
+ active = /* @__PURE__ */ new Set();
1671
+ send = null;
1672
+ approvals = new ApprovalBroker();
1673
+ extension = "missing";
1674
+ constructor(options) {
1675
+ this.options = options;
1676
+ this.pi = new PiLink({
1677
+ socketPath: controlSocketPath(options.root),
1678
+ owns: (cwd) => this.ingest.owns(cwd),
1679
+ onEvent: (link, event) => this.onPiEvent(link, event),
1680
+ onConnect: (link) => this.ingest.controlChanged("pi", link.sessionId),
1681
+ onDisconnect: (link) => {
1682
+ this.endStream(`pi:${link.sessionId}`);
1683
+ this.ingest.controlChanged("pi", link.sessionId);
1684
+ if (link.sessionFile) this.ingest.touch(link.sessionFile);
1685
+ },
1686
+ onDroppedLine: (nativeSessionId, bytes) => options.diagnostics.log("warn", "native.pi_line_dropped", {
1687
+ nativeSessionId,
1688
+ bytes
1689
+ }, {
1690
+ component: "native",
1691
+ harness: "pi"
1692
+ })
1693
+ });
1694
+ this.codex = new CodexShared(options.executables.codex || "codex", options.root, Boolean(options.config?.codexShared) && options.harnesses.includes("codex"));
1695
+ this.codex.onConnect((channel) => this.observeCodex(channel));
1696
+ this.codex.onRelease((threadId) => {
1697
+ this.watched.delete(threadId);
1698
+ this.endStream(`codex:${threadId}`);
1699
+ });
1700
+ this.ingest = new NativeIngest({
1701
+ spaceId: options.spaceId,
1702
+ cwd: options.root,
1703
+ harnesses: this.synced,
1704
+ enabledAt: options.config?.enabledAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1705
+ root: options.stateRoot,
1706
+ archives: options.archives,
1707
+ hooks: {
1708
+ settled: (state, mtimeMs) => {
1709
+ const link = state.harness === "pi" ? this.pi.find(state.nativeSessionId) : null;
1710
+ if (!link) return null;
1711
+ if (!link.idle) return false;
1712
+ return link.settledAt >= mtimeMs ? true : null;
1713
+ },
1714
+ controllable: (state) => state.harness === "pi" ? this.pi.find(state.nativeSessionId) !== null : state.harness === "codex" && this.codex.enabled && (this.active.has(state.nativeSessionId) || this.watched.has(state.nativeSessionId) || this.codex.driving.has(state.nativeSessionId)),
1715
+ abortTurn: (state) => {
1716
+ (state.harness === "pi" ? this.pi.abort(state.nativeSessionId) : state.harness === "codex" && state.runningTurnKey ? this.codex.interrupt(state.nativeSessionId, state.runningTurnKey) : Promise.resolve(false)).catch((error) => options.diagnostics.log("warn", "native.stop_failed", { error: serializeDiagnosticError(error) }, {
1717
+ harness: state.harness,
1718
+ sessionId: state.sessionId ?? void 0
1719
+ }));
1720
+ },
1721
+ onGrowth: (state) => this.onGrowth(state),
1722
+ onRunning: (state, turnId) => this.onRunning(state, turnId),
1723
+ onError: (error, context) => options.diagnostics.log("warn", "native.sync_pending", {
1724
+ path: context.path,
1725
+ error: serializeDiagnosticError(error)
1726
+ }, {
1727
+ component: "native",
1728
+ harness: context.harness
1729
+ })
1730
+ }
1731
+ });
1732
+ const results = new ExecutionResults(options.stateRoot);
1733
+ this.executor = {
1734
+ cwd: options.root,
1735
+ executables: options.executables,
1736
+ sessions: new NativeSessions({
1737
+ root: options.stateRoot,
1738
+ spaceId: options.spaceId,
1739
+ projectionSource: options.projectionSource,
1740
+ archives: options.archives,
1741
+ ingest: this.ingest,
1742
+ onRestoreFailed: (error, context) => options.diagnostics.log("warn", "native.restore_failed", {
1743
+ error: serializeDiagnosticError(error),
1744
+ unrestorable: context.unrestorable
1745
+ }, {
1746
+ component: "archive",
1747
+ harness: context.harness,
1748
+ sessionId: context.sessionId
1749
+ })
1750
+ }),
1751
+ results,
1752
+ ingest: this.ingest,
1753
+ archives: options.archives,
1754
+ pi: this.pi,
1755
+ codex: this.codex,
1756
+ approvals: this.approvals,
1757
+ piExtension: piExtensionSource(),
1758
+ diagnostics: options.diagnostics
1759
+ };
1760
+ }
1761
+ get synced() {
1762
+ const { config, root, harnesses } = this.options;
1763
+ return config?.root === root ? config.harnesses.filter((harness) => harnesses.includes(harness)) : [];
1764
+ }
1765
+ async start(signal) {
1766
+ const degraded = (event) => (error) => this.options.diagnostics.log("warn", event, { error: serializeDiagnosticError(error) }, { component: "native" });
1767
+ await this.ingest.load().catch(degraded("native.ledger_unreadable"));
1768
+ await this.refreshScope();
1769
+ if (this.options.harnesses.includes("pi")) {
1770
+ const version = await harnessVersion(this.options.executables.pi || "pi");
1771
+ if (!atLeast(version, PI_MIN_VERSION)) this.pi.unavailable = `Pi ${formatVersion(version)} predates the Cohub extension (${PI_MIN_VERSION.join(".")}+); upgrade Pi, then restart the Runtime`;
1772
+ else await this.pi.listen(signal).catch((error) => {
1773
+ this.pi.unavailable = `Pi control socket unavailable (${serializeDiagnosticError(error).message}); restart the Runtime`;
1774
+ degraded("native.pi_socket_unavailable")(error);
1775
+ });
1776
+ this.extension = await piExtensionState().catch(() => "missing");
1777
+ }
1778
+ await this.ingest.watch(signal).catch(degraded("native.watch_unavailable"));
1779
+ if (this.codex.enabled) this.codex.get();
1780
+ }
1781
+ /** `approvals`: the Gateway relays approval decisions back. */
1782
+ connect(send, features = {}) {
1783
+ this.send = send;
1784
+ this.ingest.connect(send ? nativeWebSocketTransport(send) : null);
1785
+ this.approvals.connect(send && features.approvals ? send : null);
1786
+ }
1787
+ stop(sessionId, turnId) {
1788
+ return this.ingest.stop(sessionId, turnId);
1789
+ }
1790
+ status() {
1791
+ const ingest = this.ingest.status();
1792
+ return {
1793
+ synced: this.synced,
1794
+ transcripts: ingest.transcripts,
1795
+ running: ingest.running,
1796
+ pi: this.options.harnesses.includes("pi") ? {
1797
+ extension: this.extension,
1798
+ connected: this.pi.list().length,
1799
+ unavailable: this.pi.unavailable
1800
+ } : null,
1801
+ codex: this.options.harnesses.includes("codex") ? {
1802
+ control: this.codex.enabled ? "shared" : "private",
1803
+ watching: this.watched.size
1804
+ } : null,
1805
+ import: ingest.import
1806
+ };
1807
+ }
1808
+ async control(action, message) {
1809
+ if (action === "reload") return await this.reload();
1810
+ if (action !== "import") throw new Error("Unknown Runtime control request");
1811
+ if (!this.synced.length) throw new Error("Native sync is not enabled for this directory; run cohub runtime up");
1812
+ const filter = {
1813
+ ...Array.isArray(message.harnesses) && message.harnesses.length ? { harnesses: message.harnesses } : {},
1814
+ ...typeof message.nativeSessionId === "string" && message.nativeSessionId ? { nativeSessionId: message.nativeSessionId } : {}
1815
+ };
1816
+ if (message.command === "pause") return this.ingest.pauseImport();
1817
+ if (message.command === "start") return await this.ingest.startImport(filter, typeof message.concurrency === "number" ? message.concurrency : 4);
1818
+ const plan = await this.ingest.plan(filter);
1819
+ return {
1820
+ files: plan.length,
1821
+ bytes: plan.reduce((sum, candidate) => sum + candidate.size, 0),
1822
+ sample: plan.slice(0, 20).map(({ harness, path, nativeSessionId, mtimeMs, size }) => ({
1823
+ harness,
1824
+ path,
1825
+ nativeSessionId,
1826
+ mtimeMs,
1827
+ size
1828
+ }))
1829
+ };
1830
+ }
1831
+ async reload() {
1832
+ await this.refreshScope();
1833
+ this.options.config = await readNativeConfig(this.options.stateRoot, this.options.identity);
1834
+ this.ingest.configure(this.synced, this.options.config?.enabledAt ?? (/* @__PURE__ */ new Date()).toISOString());
1835
+ this.codex.enabled = Boolean(this.options.config?.codexShared) && this.options.harnesses.includes("codex");
1836
+ if (this.codex.enabled) this.codex.get();
1837
+ if (this.options.harnesses.includes("pi")) this.extension = await piExtensionState().catch(() => "missing");
1838
+ return this.status();
1839
+ }
1840
+ async refreshScope() {
1841
+ const { bindings } = await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }));
1842
+ this.ingest.exclude(bindings.filter((binding) => binding.key === this.options.identity && binding.spaceId !== this.options.spaceId).map((binding) => binding.root));
1843
+ }
1844
+ async close(signal) {
1845
+ for (const stream of this.streams.values()) stream.progress.dispose();
1846
+ for (const preview of this.filePreviews.values()) {
1847
+ preview.progress.dispose();
1848
+ if (preview.timer) clearTimeout(preview.timer);
1849
+ }
1850
+ await Promise.allSettled([
1851
+ this.pi.close(),
1852
+ this.codex.close(),
1853
+ this.ingest.close(signal)
1854
+ ]);
1855
+ }
1856
+ sink(harness, nativeSessionId) {
1857
+ return (progress) => {
1858
+ const running = this.ingest.running(harness, nativeSessionId);
1859
+ if (!running?.sessionId || !running.runningTurnId || !this.send) return null;
1860
+ return this.send({
1861
+ type: "progress",
1862
+ sessionId: running.sessionId,
1863
+ turnId: running.runningTurnId,
1864
+ progress
1865
+ }).catch(() => ({ accepted: false }));
1866
+ };
1867
+ }
1868
+ /**
1869
+ * A connected Pi. A user prompt starting and the agent settling are the two moments its file has
1870
+ * something to persist; everything between streams as a preview of a Turn someone runs there.
1871
+ */
1872
+ onPiEvent(link, event) {
1873
+ const key = `pi:${link.sessionId}`;
1874
+ const type = text(event.type);
1875
+ const userPrompt = type === "message_end" && record$1(event.message).role === "user";
1876
+ if (userPrompt || type === "agent_settled") {
1877
+ if (link.sessionFile) this.ingest.touch(link.sessionFile);
1878
+ }
1879
+ if (type === "agent_start") this.endStream(key);
1880
+ if (type === "agent_settled") {
1881
+ this.endStream(key);
1882
+ return;
1883
+ }
1884
+ this.ingest.alive("pi", link.sessionId);
1885
+ if (!this.ingest.running("pi", link.sessionId) && !userPrompt && !this.streams.has(key)) return;
1886
+ this.stream(key, "pi", link.sessionId).translator.push(event);
1887
+ }
1888
+ stream(key, harness, nativeSessionId) {
1889
+ let stream = this.streams.get(key);
1890
+ if (!stream) {
1891
+ const progress = new LiveProgress(this.sink(harness, nativeSessionId), STREAM_INTERVAL_MS);
1892
+ const emit = (update) => progress.apply(update);
1893
+ stream = {
1894
+ progress,
1895
+ translator: harness === "pi" ? piTranslator(emit) : codexTranslator(emit, {
1896
+ provider: null,
1897
+ model: null
1898
+ })
1899
+ };
1900
+ this.streams.set(key, stream);
1901
+ }
1902
+ return stream;
1903
+ }
1904
+ endStream(key) {
1905
+ this.streams.get(key)?.progress.dispose();
1906
+ this.streams.delete(key);
1907
+ }
1908
+ endFilePreview(path) {
1909
+ const preview = this.filePreviews.get(path);
1910
+ if (!preview) return;
1911
+ preview.progress.dispose();
1912
+ if (preview.timer) clearTimeout(preview.timer);
1913
+ this.filePreviews.delete(path);
1914
+ }
1915
+ observeCodex(channel) {
1916
+ const offEvent = channel.onEvent((event) => this.onCodexEvent(event));
1917
+ const offClose = channel.onClose(() => {
1918
+ offEvent();
1919
+ offClose();
1920
+ const lost = /* @__PURE__ */ new Set([...this.watched.keys(), ...this.active]);
1921
+ this.watched.clear();
1922
+ this.active.clear();
1923
+ for (const key of [...this.streams.keys()]) if (key.startsWith("codex:")) this.endStream(key);
1924
+ for (const threadId of lost) this.ingest.controlChanged("codex", threadId);
1925
+ });
1926
+ channel.request("thread/loaded/list", {}).then((result) => {
1927
+ for (const threadId of Array.isArray(result.data) ? result.data : []) if (typeof threadId === "string") this.watchCodexThread(channel, threadId, false);
1928
+ }).catch(() => void 0);
1929
+ }
1930
+ async watchCodexThread(channel, threadId, busy) {
1931
+ if (this.watched.has(threadId)) return;
1932
+ const read = await channel.request("thread/read", { threadId }).catch(() => null);
1933
+ const thread = record$1(read?.thread);
1934
+ if (!busy && record$1(thread.status).type !== "active") return;
1935
+ if (!this.ingest.owns(text(thread.cwd)) || thread.parentThreadId || thread.ephemeral === true) return;
1936
+ this.active.add(threadId);
1937
+ if (this.codex.driving.has(threadId)) return;
1938
+ this.watched.set(threadId, { path: text(thread.path) || null });
1939
+ this.ingest.controlChanged("codex", threadId);
1940
+ await this.codex.join(threadId).catch((error) => {
1941
+ this.watched.delete(threadId);
1942
+ this.options.diagnostics.log("debug", "native.codex_join_failed", { error: serializeDiagnosticError(error) }, { harness: "codex" });
1943
+ });
1944
+ }
1945
+ onCodexEvent(event) {
1946
+ if (event.id != null) return;
1947
+ const threadId = text(event.params.threadId);
1948
+ if (!threadId) return;
1949
+ if (event.method === "thread/status/changed") {
1950
+ if (record$1(event.params.status).type === "active") this.codex.get().then((channel) => channel && this.watchCodexThread(channel, threadId, true));
1951
+ return;
1952
+ }
1953
+ const watched = this.watched.get(threadId);
1954
+ if (!watched || this.codex.driving.has(threadId)) return;
1955
+ this.ingest.alive("codex", threadId);
1956
+ const key = `codex:${threadId}`;
1957
+ if (event.method === "turn/started") this.endStream(key);
1958
+ if (event.method === "turn/completed") {
1959
+ this.endStream(key);
1960
+ if (watched.path) this.ingest.touch(watched.path);
1961
+ this.codex.release(threadId);
1962
+ return;
1963
+ }
1964
+ this.stream(key, "codex", threadId).translator.push(event);
1965
+ }
1966
+ /**
1967
+ * A terminal Pi runs many Turns in one process; once the ledger knows which one is running, its
1968
+ * tools are told, so a `cohub` call from a tool names the right Space, Session and Turn.
1969
+ */
1970
+ onRunning(state, turnId) {
1971
+ if (!turnId) this.endFilePreview(state.path);
1972
+ if (state.harness !== "pi" || !state.sessionId || !this.pi.find(state.nativeSessionId)) return;
1973
+ this.pi.context(state.nativeSessionId, {
1974
+ COHUB_SPACE_ID: this.options.spaceId,
1975
+ COHUB_SESSION_ID: state.sessionId,
1976
+ COHUB_TURN_ID: turnId
1977
+ }).catch(() => void 0);
1978
+ }
1979
+ /**
1980
+ * A running Turn's file grew. A connected client streams it already; otherwise the preview is
1981
+ * read from the file, at a pace set by a timer, not by every write.
1982
+ */
1983
+ onGrowth(state) {
1984
+ this.ingest.alive(state.harness, state.nativeSessionId);
1985
+ if (state.harness === "codex" && this.codex.enabled && !this.watched.has(state.nativeSessionId)) this.codex.get();
1986
+ if (state.harness === "pi" ? this.pi.find(state.nativeSessionId) !== null : this.watched.has(state.nativeSessionId)) return;
1987
+ let preview = this.filePreviews.get(state.path);
1988
+ if (!preview) {
1989
+ preview = {
1990
+ progress: new LiveProgress(this.sink(state.harness, state.nativeSessionId), 0),
1991
+ timer: null,
1992
+ readMs: 0
1993
+ };
1994
+ this.filePreviews.set(state.path, preview);
1995
+ }
1996
+ const entry = preview;
1997
+ entry.timer ??= setTimeout(() => {
1998
+ if (!state.runningTurnId) {
1999
+ this.endFilePreview(state.path);
2000
+ return;
2001
+ }
2002
+ const startedAt = performance.now();
2003
+ readTranscript(state.path, state.harness).then((transcript) => {
2004
+ if (!state.runningTurnId) {
2005
+ this.endFilePreview(state.path);
2006
+ return;
2007
+ }
2008
+ const tail = transcript.turns.at(-1);
2009
+ entry.progress.replace((tail?.messages ?? []).map((message) => ({
2010
+ content: message.content,
2011
+ provider: message.provider ?? null,
2012
+ model: message.model ?? null
2013
+ })));
2014
+ }).catch(() => void 0).finally(() => {
2015
+ entry.readMs = performance.now() - startedAt;
2016
+ entry.timer = null;
2017
+ });
2018
+ }, Math.max(FILE_PREVIEW_INTERVAL_MS, FILE_PREVIEW_COST_FACTOR * entry.readMs));
2019
+ entry.timer.unref?.();
2020
+ }
2021
+ };
2022
+ //#endregion
2023
+ //#region src/runtime/supervisor.ts
2024
+ const DISPLAY_ANSWER_MS = 1e4;
2025
+ const ACTIVITY_MS = 6e4;
2026
+ function sandboxOutputLevel(value, stream) {
2027
+ const level = typeof value === "string" ? value.toLowerCase() : "";
2028
+ if ([
2029
+ "debug",
2030
+ "info",
2031
+ "warn",
2032
+ "error"
2033
+ ].includes(level)) return level;
2034
+ return stream === "stderr" ? "warn" : "debug";
2035
+ }
2036
+ /**
2037
+ * Windows cannot hand sandboxd an extra inherited pipe, so control frames use a
2038
+ * named pipe instead. Only the first client is accepted; the name is unguessable.
2039
+ */
2040
+ async function listenWindowsControlPipe() {
2041
+ const path = `\\\\.\\pipe\\cohub-sandboxd-${randomUUID()}`;
2042
+ const stream = new PassThrough();
2043
+ const server = createServer((socket) => {
2044
+ server.close();
2045
+ socket.on("error", () => stream.end());
2046
+ socket.pipe(stream);
2047
+ });
2048
+ await new Promise((resolve, reject) => {
2049
+ server.once("error", reject);
2050
+ server.listen(path, () => {
2051
+ server.removeListener("error", reject);
2052
+ resolve();
2053
+ });
2054
+ });
2055
+ return {
2056
+ path,
2057
+ stream,
2058
+ close: () => {
2059
+ server.close();
2060
+ stream.end();
2061
+ }
2062
+ };
2063
+ }
2064
+ async function runRuntime(config, onState, externalSignal, onDiagnostic) {
2065
+ const controller = new AbortController();
2066
+ const signal = externalSignal ? AbortSignal.any([externalSignal, controller.signal]) : controller.signal;
2067
+ const stop = () => controller.abort();
2068
+ process.once("SIGINT", stop);
2069
+ process.once("SIGTERM", stop);
2070
+ appendCliToPath();
2071
+ const space = createClient().space(config.spaceId);
2072
+ const stateRoot = runtimeStateRoot(config.spaceId);
2073
+ const archives = new RuntimeArchiveStore(join(stateRoot, "archives"), space);
2074
+ const consoleSink = config.background ? void 0 : createDiagnosticConsole(config.verbose);
2075
+ const diagnostics = new RuntimeDiagnostics({
2076
+ root: stateRoot,
2077
+ spaceId: config.spaceId,
2078
+ runtimeId: randomUUID(),
2079
+ onEvent: (event) => {
2080
+ consoleSink?.(event);
2081
+ onDiagnostic?.(event);
2082
+ }
2083
+ });
2084
+ archives.setErrorReporter((error, index) => diagnostics.log("warn", "archive.upload_pending", { error: serializeDiagnosticError(error) }, {
2085
+ component: "archive",
2086
+ sessionId: index?.sessionId,
2087
+ turnId: index?.turnId,
2088
+ harness: index?.harness
2089
+ }));
2090
+ const native = new NativeRuntime({
2091
+ spaceId: config.spaceId,
2092
+ root: config.root,
2093
+ stateRoot,
2094
+ harnesses: config.harnesses,
2095
+ executables: config.executables,
2096
+ identity: config.identity,
2097
+ config: await readNativeConfig(stateRoot, config.identity).catch(() => null),
2098
+ archives,
2099
+ projectionSource: space,
2100
+ diagnostics
2101
+ });
2102
+ let status = {
2103
+ spaceId: config.spaceId,
2104
+ root: config.root,
2105
+ runtimeId: diagnostics.runtimeId,
2106
+ pid: process.pid,
2107
+ version: CLI_VERSION,
2108
+ harnesses: config.harnesses,
2109
+ background: config.background,
2110
+ ...config.display ? { display: config.display } : {},
2111
+ state: "starting",
2112
+ harnessConnected: false,
2113
+ workspaceConnected: false,
2114
+ diagnosticsPath: diagnostics.directory
2115
+ };
2116
+ const summary = () => ({
2117
+ ...status,
2118
+ native: native.status()
2119
+ });
2120
+ let instance;
2121
+ let hasBeenReady = false;
2122
+ const update = (patch) => {
2123
+ const next = {
2124
+ ...status,
2125
+ ...patch
2126
+ };
2127
+ if (next.state !== "stopping" && next.state !== "attention") next.state = next.harnessConnected && next.workspaceConnected ? "ready" : hasBeenReady ? "reconnecting" : "starting";
2128
+ if (JSON.stringify(status) === JSON.stringify(next)) return;
2129
+ const becameReady = next.state === "ready" && status.state !== "ready";
2130
+ status = next;
2131
+ if (becameReady) {
2132
+ hasBeenReady = true;
2133
+ diagnostics.log("info", "runtime.available");
2134
+ }
2135
+ onState({ ...status });
2136
+ instance?.changed();
2137
+ };
2138
+ let bridgeTask;
2139
+ let retryDisconnectedBridge;
2140
+ let nativeStarted = false;
2141
+ let tokenInFlight = null;
2142
+ const executions = /* @__PURE__ */ new Map();
2143
+ let bridgeControl = null;
2144
+ let workspace = null;
2145
+ let displayAnswer = null;
2146
+ const applyKeepAwake = async () => {
2147
+ if (bridgeControl?.features.includes("keepAwake")) bridgeControl.send({
2148
+ type: "keepAwake",
2149
+ enabled: (await readRuntimePreferences()).keepAwake
2150
+ });
2151
+ };
2152
+ const setDisplay = async (spec) => {
2153
+ if (bridgeControl && !bridgeControl.features.includes("display")) throw new Error("This Runtime cannot change its screen while running; reconnect it");
2154
+ if (!spec) update({
2155
+ display: void 0,
2156
+ displayOnRequest: void 0,
2157
+ displayNeeds: void 0
2158
+ });
2159
+ if (!bridgeControl) {
2160
+ if (!spec) return summary();
2161
+ throw new Error("The file bridge is restarting; try again");
2162
+ }
2163
+ const { send } = bridgeControl;
2164
+ const before = status.displayOnRequest;
2165
+ if (spec) update({ displayOnRequest: true });
2166
+ const frame = await new Promise((resolve, reject) => {
2167
+ const timer = setTimeout(() => {
2168
+ displayAnswer = null;
2169
+ if (spec) send({
2170
+ type: "display",
2171
+ spec: ""
2172
+ });
2173
+ update({
2174
+ display: void 0,
2175
+ displayOnRequest: void 0,
2176
+ displayNeeds: void 0
2177
+ });
2178
+ reject(/* @__PURE__ */ new Error("The file bridge did not answer"));
2179
+ }, DISPLAY_ANSWER_MS);
2180
+ displayAnswer = (answer) => {
2181
+ if (!answer.error && answer.spec !== spec) return;
2182
+ clearTimeout(timer);
2183
+ displayAnswer = null;
2184
+ resolve(answer);
2185
+ };
2186
+ send({
2187
+ type: "display",
2188
+ spec
2189
+ });
2190
+ });
2191
+ if (frame.error) {
2192
+ update({ displayOnRequest: before });
2193
+ throw new Error(frame.error);
2194
+ }
2195
+ return summary();
2196
+ };
2197
+ const token = (forceRefresh = false) => {
2198
+ tokenInFlight ??= (async () => {
2199
+ if (currentIdentityKey() !== config.identity) throw new AuthRequiredError("Runtime account changed; sign in to the original account");
2200
+ const value = await resolveAccessToken({ forceRefresh });
2201
+ if (!value) throw new AuthRequiredError();
2202
+ if (currentIdentityKey() !== config.identity) throw new AuthRequiredError("Runtime account changed");
2203
+ return value;
2204
+ })().finally(() => {
2205
+ tokenInFlight = null;
2206
+ });
2207
+ return tokenInFlight;
2208
+ };
2209
+ try {
2210
+ instance = await ownRuntimeInstance(runtimeInstanceDirectory(config.identity, config.spaceId), summary, async (force) => {
2211
+ if (!force) {
2212
+ for await (const batch of native.executor.results.pendingBatches()) if (batch.length) throw new Error(`${UNCONFIRMED_WORK}. Use down --yes to stop; results and files are retained`);
2213
+ }
2214
+ update({ state: "stopping" });
2215
+ setTimeout(stop, 30);
2216
+ }, (action, message) => {
2217
+ if (action === "display") return setDisplay(String(message.spec ?? ""));
2218
+ if (action === "keepAwake") return applyKeepAwake();
2219
+ if (action === "workspace") return Promise.resolve(status.state === "ready" ? workspace : null);
2220
+ return native.control(action, message);
2221
+ });
2222
+ onState({ ...status });
2223
+ diagnostics.log("info", "runtime.cli_started", {
2224
+ platform: process.platform,
2225
+ node: process.versions.node,
2226
+ harnesses: config.harnesses
2227
+ });
2228
+ const [binary, capabilities] = await Promise.all([ensureSandboxdBinary({ onStatus: (message) => diagnostics.log("info", "sandboxd.download", { message }) }), config.capabilities ?? discoverHarnesses(config.harnesses, config.executables, config.root)]);
2229
+ signal.throwIfAborted();
2230
+ const url = new URL(resolveWebsocketUrl());
2231
+ url.pathname = url.pathname.replace(/\/ws$/, "/runtime/relay");
2232
+ const relay = new URL(url);
2233
+ relay.pathname = relay.pathname.replace(/\/runtime\/relay$/, "/sandbox/relay");
2234
+ const runBridge = async () => {
2235
+ let attempts = 0;
2236
+ while (!signal.aborted) {
2237
+ if (!status.harnessConnected) {
2238
+ await setTimeout$1(500, void 0, { signal }).catch(() => void 0);
2239
+ continue;
2240
+ }
2241
+ const startedAt = Date.now();
2242
+ let refreshTimer;
2243
+ let probeTimer;
2244
+ let managed = false;
2245
+ let childStopped = false;
2246
+ let bridgeDisconnected = false;
2247
+ let terminating = false;
2248
+ let recoveryTimer;
2249
+ let controlPipe = null;
2250
+ try {
2251
+ const initialToken = await token();
2252
+ signal.throwIfAborted();
2253
+ if (process.platform === "win32") controlPipe = await listenWindowsControlPipe();
2254
+ const spawnedScreen = status.display ?? "";
2255
+ const localToken = randomBytes(32).toString("base64url");
2256
+ const bridge = spawn(binary, [
2257
+ "--local",
2258
+ "--space",
2259
+ config.spaceId,
2260
+ "--root",
2261
+ config.root,
2262
+ "--relay",
2263
+ process.env.COHUB_RELAY_URL?.trim() || relay.toString()
2264
+ ], {
2265
+ stdio: controlPipe ? [
2266
+ "pipe",
2267
+ "pipe",
2268
+ "pipe"
2269
+ ] : [
2270
+ "pipe",
2271
+ "pipe",
2272
+ "pipe",
2273
+ "pipe"
2274
+ ],
2275
+ windowsHide: true,
2276
+ env: {
2277
+ ...process.env,
2278
+ COHUB_RELAY_TOKEN: initialToken,
2279
+ COHUB_LOCAL_TOKEN: localToken,
2280
+ COHUB_RUNTIME_ID: status.runtimeId,
2281
+ COHUB_LOG_FORMAT: "json",
2282
+ COHUB_RUNTIME_MANAGED: "1",
2283
+ COHUB_DISPLAY: spawnedScreen,
2284
+ ...controlPipe ? { COHUB_RUNTIME_CONTROL_PIPE: controlPipe.path } : {}
2285
+ }
2286
+ });
2287
+ bridge.stdin?.on("error", () => void 0);
2288
+ const closed = new Promise((resolve) => {
2289
+ let drainTimer;
2290
+ bridge.once("error", (error) => diagnostics.log("error", "sandboxd.process_error", { error: serializeDiagnosticError(error) }));
2291
+ bridge.once("exit", (code, exitSignal) => {
2292
+ childStopped = true;
2293
+ clearTimeout(recoveryTimer);
2294
+ recoveryTimer = void 0;
2295
+ if (!signal.aborted) diagnostics.log("warn", "sandboxd.process_exit", {
2296
+ code,
2297
+ signal: exitSignal
2298
+ });
2299
+ drainTimer = setTimeout(() => {
2300
+ diagnostics.log("warn", "sandboxd.stdio_drain_timeout");
2301
+ for (const stream of bridge.stdio) stream?.destroy();
2302
+ }, 1e3);
2303
+ });
2304
+ bridge.once("close", () => {
2305
+ childStopped = true;
2306
+ clearTimeout(drainTimer);
2307
+ resolve();
2308
+ });
2309
+ });
2310
+ for (const streamName of ["stdout", "stderr"]) {
2311
+ const stream = bridge[streamName];
2312
+ if (!stream) continue;
2313
+ createInterface({ input: stream }).on("line", (line) => {
2314
+ let parsed = null;
2315
+ try {
2316
+ const value = JSON.parse(line);
2317
+ if (value && typeof value === "object" && !Array.isArray(value)) parsed = value;
2318
+ } catch {}
2319
+ const data = parsed ? Object.fromEntries(Object.entries(parsed).filter(([key]) => ![
2320
+ "msg",
2321
+ "level",
2322
+ "time"
2323
+ ].includes(key))) : {};
2324
+ diagnostics.log(sandboxOutputLevel(parsed?.level, streamName), "sandboxd.log", {
2325
+ ...data,
2326
+ message: parsed?.msg ?? line
2327
+ }, { component: "sandboxd" });
2328
+ });
2329
+ }
2330
+ const control = controlPipe ? controlPipe.stream : bridge.stdio[3];
2331
+ createInterface({ input: control }).on("line", (line) => {
2332
+ try {
2333
+ const event = JSON.parse(line);
2334
+ if (event.type === "hello") managed = true;
2335
+ if (event.type === "features") {
2336
+ bridgeControl = {
2337
+ features: event.features,
2338
+ send: (frame) => bridge.stdin?.write(`${JSON.stringify(frame)}\n`)
2339
+ };
2340
+ applyKeepAwake().catch(() => void 0);
2341
+ if ((status.display ?? "") !== spawnedScreen) bridgeControl.send({
2342
+ type: "display",
2343
+ spec: status.display ?? ""
2344
+ });
2345
+ }
2346
+ if (event.type === "local" && Number.isInteger(event.port)) {
2347
+ workspace = {
2348
+ url: `http://127.0.0.1:${event.port}`,
2349
+ token: localToken
2350
+ };
2351
+ update({ direct: true });
2352
+ }
2353
+ if (event.type === "display") {
2354
+ update({
2355
+ display: event.spec || void 0,
2356
+ displayNeeds: event.needs?.length ? event.needs : void 0
2357
+ });
2358
+ displayAnswer?.(event);
2359
+ }
2360
+ if (event.type === "connected" || event.type === "disconnected") {
2361
+ const connected = event.type === "connected";
2362
+ bridgeDisconnected = !connected;
2363
+ update({ workspaceConnected: connected });
2364
+ diagnostics.log(connected ? "info" : "warn", `sandboxd.${event.type}`);
2365
+ retryDisconnectedBridge?.();
2366
+ }
2367
+ } catch {
2368
+ diagnostics.log("warn", "sandboxd.control_invalid");
2369
+ }
2370
+ });
2371
+ const refresh = async () => {
2372
+ try {
2373
+ const next = await token();
2374
+ if (!childStopped && managed && !signal.aborted) bridge.stdin?.write(`${JSON.stringify({
2375
+ type: "auth",
2376
+ token: next
2377
+ })}\n`);
2378
+ } catch (error) {
2379
+ diagnostics.log("warn", error instanceof AuthRequiredError ? "runtime.auth_required" : "runtime.auth_token_failed", { error: serializeDiagnosticError(error) });
2380
+ }
2381
+ if (!childStopped && !signal.aborted) refreshTimer = setTimeout(() => void refresh(), 1e4);
2382
+ };
2383
+ refresh();
2384
+ const probe = async () => {
2385
+ if (!managed && !childStopped && !signal.aborted) try {
2386
+ const remote = await space.getRuntime(void 0, { signal: AbortSignal.any([signal, AbortSignal.timeout(5e3)]) });
2387
+ if (!childStopped && !managed) update({ workspaceConnected: remote.runtimeId === status.runtimeId && remote.workspace?.online === true });
2388
+ } catch {
2389
+ if (!childStopped && !managed) update({ workspaceConnected: false });
2390
+ }
2391
+ if (!childStopped && !signal.aborted && !managed) probeTimer = setTimeout(() => void probe(), 5e3);
2392
+ };
2393
+ probeTimer = setTimeout(() => void probe(), 1e3);
2394
+ const terminate = () => {
2395
+ if (terminating || childStopped) return;
2396
+ terminating = true;
2397
+ clearTimeout(recoveryTimer);
2398
+ recoveryTimer = void 0;
2399
+ if (process.platform === "win32") bridge.stdin?.end();
2400
+ else bridge.kill("SIGTERM");
2401
+ const timeout = setTimeout(() => bridge.kill("SIGKILL"), 3e3);
2402
+ closed.finally(() => clearTimeout(timeout));
2403
+ };
2404
+ retryDisconnectedBridge = () => {
2405
+ if (signal.aborted || !status.harnessConnected || !bridgeDisconnected || terminating || childStopped) {
2406
+ clearTimeout(recoveryTimer);
2407
+ recoveryTimer = void 0;
2408
+ } else if (!recoveryTimer) recoveryTimer = setTimeout(() => {
2409
+ recoveryTimer = void 0;
2410
+ if (!signal.aborted && status.harnessConnected && bridgeDisconnected && !terminating && !childStopped) {
2411
+ diagnostics.log("info", "sandboxd.lease_recovery");
2412
+ terminate();
2413
+ }
2414
+ }, 3e4);
2415
+ };
2416
+ signal.addEventListener("abort", terminate, { once: true });
2417
+ if (signal.aborted) terminate();
2418
+ await closed;
2419
+ signal.removeEventListener("abort", terminate);
2420
+ } catch (error) {
2421
+ if (!signal.aborted) diagnostics.log("warn", "sandboxd.restart_failed", { error: serializeDiagnosticError(error) });
2422
+ } finally {
2423
+ retryDisconnectedBridge = void 0;
2424
+ bridgeControl = null;
2425
+ workspace = null;
2426
+ childStopped = true;
2427
+ controlPipe?.close();
2428
+ clearTimeout(refreshTimer);
2429
+ clearTimeout(probeTimer);
2430
+ clearTimeout(recoveryTimer);
2431
+ update({
2432
+ workspaceConnected: false,
2433
+ direct: void 0
2434
+ });
2435
+ }
2436
+ if (Date.now() - startedAt > 6e4) attempts = 0;
2437
+ const backoff = Math.min(3e4, 500 * 2 ** Math.min(attempts++, 6));
2438
+ await setTimeout$1(backoff / 2 + Math.random() * backoff / 2, void 0, { signal }).catch(() => void 0);
2439
+ }
2440
+ };
2441
+ bridgeTask = runBridge();
2442
+ const activity = setInterval(() => {
2443
+ if (executions.size || native.status().running) bridgeControl?.send({ type: "activity" });
2444
+ }, ACTIVITY_MS);
2445
+ activity.unref();
2446
+ signal.addEventListener("abort", () => clearInterval(activity), { once: true });
2447
+ await native.start(signal);
2448
+ nativeStarted = true;
2449
+ let importRequested = Boolean(config.importHistory);
2450
+ await serveRuntime({
2451
+ spaceId: config.spaceId,
2452
+ cwd: config.root,
2453
+ url: url.toString(),
2454
+ capabilities,
2455
+ refreshCapabilities: (current) => refreshHarnesses(current, config.executables, config.root, (harness, error) => diagnostics.log("warn", "runtime.harness_catalog_failed", {
2456
+ harness,
2457
+ error: serializeDiagnosticError(error)
2458
+ })),
2459
+ runtimeId: status.runtimeId,
2460
+ diagnostics,
2461
+ token,
2462
+ signal,
2463
+ executor: native.executor,
2464
+ executions,
2465
+ onReady: () => {
2466
+ update({ harnessConnected: true });
2467
+ retryDisconnectedBridge?.();
2468
+ },
2469
+ onDisconnected: () => {
2470
+ native.connect(null);
2471
+ update({ harnessConnected: false });
2472
+ retryDisconnectedBridge?.();
2473
+ },
2474
+ onNativeStop: (stop) => {
2475
+ native.stop(stop.sessionId, stop.turnId);
2476
+ },
2477
+ onApprovalDecision: (decision) => {
2478
+ native.executor.approvals.decide(decision);
2479
+ },
2480
+ onNativeChannel: (send, features) => {
2481
+ native.connect(send, features);
2482
+ if (!importRequested) return;
2483
+ importRequested = false;
2484
+ native.control("import", { command: "start" }).catch((error) => diagnostics.log("warn", "native.import_failed", { error: serializeDiagnosticError(error) }));
2485
+ }
2486
+ });
2487
+ } catch (error) {
2488
+ if (!signal.aborted) {
2489
+ update({ state: "attention" });
2490
+ diagnostics.log("error", "runtime.failed", { error: serializeDiagnosticError(error) });
2491
+ throw error;
2492
+ }
2493
+ } finally {
2494
+ controller.abort();
2495
+ try {
2496
+ await bridgeTask;
2497
+ if (nativeStarted) await native.close(AbortSignal.timeout(5e3));
2498
+ } finally {
2499
+ try {
2500
+ await diagnostics.close();
2501
+ } finally {
2502
+ try {
2503
+ await instance?.close();
2504
+ } finally {
2505
+ process.removeListener("SIGINT", stop);
2506
+ process.removeListener("SIGTERM", stop);
2507
+ }
2508
+ }
2509
+ }
2510
+ }
2511
+ }
2512
+ //#endregion
2513
+ export { sandboxOutputLevel as n, runRuntime as t };