@neta-art/cohub-cli 10.24.0 → 10.25.0

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 (368) 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/board-export-resources.js +232 -0
  14. package/dist/chunks/board-export.js +874 -0
  15. package/dist/chunks/board-export2.js +2 -0
  16. package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
  17. package/dist/chunks/board-kernel2.js +4 -0
  18. package/dist/chunks/board-profile.js +69 -0
  19. package/dist/chunks/board-simulate.js +315 -0
  20. package/dist/chunks/board-time.js +34 -0
  21. package/dist/chunks/boards.js +1943 -0
  22. package/dist/{board-kernel → chunks}/browserAll.js +9 -8
  23. package/dist/chunks/channels.js +64 -0
  24. package/dist/chunks/client.js +12606 -0
  25. package/dist/chunks/command-input.js +17 -0
  26. package/dist/chunks/commander.js +2962 -0
  27. package/dist/chunks/cron-jobs.js +163 -0
  28. package/dist/chunks/daemon.js +545 -0
  29. package/dist/chunks/daemon2.js +2 -0
  30. package/dist/chunks/desktop.js +172 -0
  31. package/dist/chunks/endpoint-options.js +26 -0
  32. package/dist/chunks/env-proxy.js +35 -0
  33. package/dist/chunks/environment.js +154 -0
  34. package/dist/chunks/feedback.js +120 -0
  35. package/dist/chunks/generations.js +379 -0
  36. package/dist/chunks/host.js +9 -0
  37. package/dist/chunks/http-put.js +131 -0
  38. package/dist/chunks/id.js +2416 -0
  39. package/dist/{board-kernel → chunks}/init.js +1 -1
  40. package/dist/chunks/install.js +11959 -0
  41. package/dist/chunks/launch.js +374 -0
  42. package/dist/chunks/local-media.js +47 -0
  43. package/dist/chunks/me.js +134 -0
  44. package/dist/chunks/media.js +315 -0
  45. package/dist/chunks/models.js +242 -0
  46. package/dist/chunks/operands.js +46 -0
  47. package/dist/chunks/package-paths.js +13 -0
  48. package/dist/chunks/policy.js +221 -0
  49. package/dist/chunks/preferences.js +29 -0
  50. package/dist/chunks/profile.js +64 -0
  51. package/dist/chunks/prompts.js +41 -0
  52. package/dist/chunks/public.js +2 -0
  53. package/dist/chunks/public2.js +244 -0
  54. package/dist/chunks/references.js +197 -0
  55. package/dist/chunks/referrals.js +90 -0
  56. package/dist/chunks/rolldown-runtime.js +26 -0
  57. package/dist/chunks/rooms-connect.js +2 -0
  58. package/dist/chunks/rooms-connect2.js +151 -0
  59. package/dist/chunks/rooms-rtc.js +309 -0
  60. package/dist/chunks/rooms.js +211 -0
  61. package/dist/chunks/run.js +220 -0
  62. package/dist/chunks/runtime.js +638 -0
  63. package/dist/chunks/runtime2.js +286 -0
  64. package/dist/chunks/runtimes.js +48 -0
  65. package/dist/chunks/safe-remote-image.js +198 -0
  66. package/dist/chunks/schemas.js +6017 -0
  67. package/dist/chunks/search.js +113 -0
  68. package/dist/chunks/self-update.js +238 -0
  69. package/dist/chunks/serve.js +1246 -0
  70. package/dist/chunks/session-status.js +24 -0
  71. package/dist/chunks/skills.js +35 -0
  72. package/dist/chunks/spaces.js +5080 -0
  73. package/dist/chunks/src.js +405 -0
  74. package/dist/chunks/supervisor.js +2511 -0
  75. package/dist/chunks/supervisor2.js +2 -0
  76. package/dist/chunks/tasks.js +82 -0
  77. package/dist/chunks/themes.js +2898 -0
  78. package/dist/chunks/version.js +2 -0
  79. package/dist/chunks/version2.js +22 -0
  80. package/dist/chunks/version3.js +18 -0
  81. package/dist/chunks/web.js +7 -0
  82. package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
  83. package/dist/runtime/native/pi-extension.js +174 -166
  84. package/dist/runtime/worker.js +27 -16
  85. package/package.json +8 -9
  86. package/dist/about.d.ts +0 -2
  87. package/dist/about.js +0 -71
  88. package/dist/app-download.d.ts +0 -11
  89. package/dist/app-download.js +0 -252
  90. package/dist/app-ref.d.ts +0 -5
  91. package/dist/app-ref.js +0 -8
  92. package/dist/app-target.d.ts +0 -26
  93. package/dist/app-target.js +0 -55
  94. package/dist/auth.d.ts +0 -45
  95. package/dist/auth.js +0 -307
  96. package/dist/avatar.d.ts +0 -55
  97. package/dist/avatar.js +0 -104
  98. package/dist/board-command-support.d.ts +0 -6
  99. package/dist/board-command-support.js +0 -88
  100. package/dist/board-export-resources.d.ts +0 -12
  101. package/dist/board-export-resources.js +0 -51
  102. package/dist/board-export.d.ts +0 -110
  103. package/dist/board-export.js +0 -592
  104. package/dist/board-fonts.d.ts +0 -11
  105. package/dist/board-fonts.js +0 -10
  106. package/dist/board-gpu/daemon.d.ts +0 -11
  107. package/dist/board-gpu/daemon.js +0 -295
  108. package/dist/board-gpu/index.d.ts +0 -33
  109. package/dist/board-gpu/index.js +0 -189
  110. package/dist/board-gpu/protocol.d.ts +0 -77
  111. package/dist/board-gpu/protocol.js +0 -1
  112. package/dist/board-kernel.d.ts +0 -5
  113. package/dist/board-media-export.d.ts +0 -17
  114. package/dist/board-media-export.js +0 -164
  115. package/dist/board-media.d.ts +0 -5
  116. package/dist/board-media.js +0 -66
  117. package/dist/board-profile.d.ts +0 -21
  118. package/dist/board-profile.js +0 -67
  119. package/dist/board-simulate.d.ts +0 -67
  120. package/dist/board-simulate.js +0 -259
  121. package/dist/board-time.d.ts +0 -3
  122. package/dist/board-time.js +0 -34
  123. package/dist/bootstrap.d.ts +0 -2
  124. package/dist/client.d.ts +0 -5
  125. package/dist/client.js +0 -24
  126. package/dist/command-input.d.ts +0 -4
  127. package/dist/command-input.js +0 -16
  128. package/dist/commands/app-commerce.d.ts +0 -2
  129. package/dist/commands/app-commerce.js +0 -228
  130. package/dist/commands/app-domains.d.ts +0 -2
  131. package/dist/commands/app-domains.js +0 -133
  132. package/dist/commands/apps.d.ts +0 -4
  133. package/dist/commands/apps.js +0 -827
  134. package/dist/commands/auth.d.ts +0 -2
  135. package/dist/commands/auth.js +0 -186
  136. package/dist/commands/boards/authoring.d.ts +0 -2
  137. package/dist/commands/boards/authoring.js +0 -166
  138. package/dist/commands/boards/examples.d.ts +0 -10
  139. package/dist/commands/boards/examples.js +0 -118
  140. package/dist/commands/boards.d.ts +0 -13
  141. package/dist/commands/boards.js +0 -836
  142. package/dist/commands/channels.d.ts +0 -2
  143. package/dist/commands/channels.js +0 -74
  144. package/dist/commands/cron-jobs.d.ts +0 -2
  145. package/dist/commands/cron-jobs.js +0 -155
  146. package/dist/commands/decision.d.ts +0 -4
  147. package/dist/commands/decision.js +0 -113
  148. package/dist/commands/desktop.d.ts +0 -10
  149. package/dist/commands/desktop.js +0 -233
  150. package/dist/commands/feedback.d.ts +0 -2
  151. package/dist/commands/feedback.js +0 -131
  152. package/dist/commands/generations.d.ts +0 -2
  153. package/dist/commands/generations.js +0 -427
  154. package/dist/commands/host.d.ts +0 -2
  155. package/dist/commands/host.js +0 -11
  156. package/dist/commands/me.d.ts +0 -2
  157. package/dist/commands/me.js +0 -121
  158. package/dist/commands/models.d.ts +0 -28
  159. package/dist/commands/models.js +0 -271
  160. package/dist/commands/profile.d.ts +0 -2
  161. package/dist/commands/profile.js +0 -81
  162. package/dist/commands/prompts.d.ts +0 -2
  163. package/dist/commands/prompts.js +0 -37
  164. package/dist/commands/public.d.ts +0 -20
  165. package/dist/commands/public.js +0 -291
  166. package/dist/commands/references.d.ts +0 -2
  167. package/dist/commands/references.js +0 -193
  168. package/dist/commands/referrals.d.ts +0 -2
  169. package/dist/commands/referrals.js +0 -88
  170. package/dist/commands/rooms-connect.d.ts +0 -17
  171. package/dist/commands/rooms-connect.js +0 -140
  172. package/dist/commands/rooms-rtc-binary.d.ts +0 -2
  173. package/dist/commands/rooms-rtc-binary.js +0 -107
  174. package/dist/commands/rooms-rtc.d.ts +0 -21
  175. package/dist/commands/rooms-rtc.js +0 -171
  176. package/dist/commands/rooms.d.ts +0 -3
  177. package/dist/commands/rooms.js +0 -277
  178. package/dist/commands/run.d.ts +0 -13
  179. package/dist/commands/run.js +0 -246
  180. package/dist/commands/runtime.d.ts +0 -3
  181. package/dist/commands/runtime.js +0 -320
  182. package/dist/commands/sandboxd-binary.d.ts +0 -11
  183. package/dist/commands/sandboxd-binary.js +0 -238
  184. package/dist/commands/search.d.ts +0 -2
  185. package/dist/commands/search.js +0 -114
  186. package/dist/commands/session-access.d.ts +0 -2
  187. package/dist/commands/session-access.js +0 -70
  188. package/dist/commands/skills.d.ts +0 -2
  189. package/dist/commands/skills.js +0 -34
  190. package/dist/commands/space-activity.d.ts +0 -26
  191. package/dist/commands/space-activity.js +0 -147
  192. package/dist/commands/space-commerce.d.ts +0 -2
  193. package/dist/commands/space-commerce.js +0 -514
  194. package/dist/commands/space-displays.d.ts +0 -2
  195. package/dist/commands/space-displays.js +0 -620
  196. package/dist/commands/space-files.d.ts +0 -5
  197. package/dist/commands/space-files.js +0 -215
  198. package/dist/commands/space-invitations.d.ts +0 -29
  199. package/dist/commands/space-invitations.js +0 -189
  200. package/dist/commands/space-turns.d.ts +0 -49
  201. package/dist/commands/space-turns.js +0 -205
  202. package/dist/commands/space-wallet.d.ts +0 -2
  203. package/dist/commands/space-wallet.js +0 -141
  204. package/dist/commands/space-webhooks.d.ts +0 -7
  205. package/dist/commands/space-webhooks.js +0 -73
  206. package/dist/commands/spaces.d.ts +0 -25
  207. package/dist/commands/spaces.js +0 -2170
  208. package/dist/commands/tasks.d.ts +0 -8
  209. package/dist/commands/tasks.js +0 -80
  210. package/dist/commands/version.d.ts +0 -2
  211. package/dist/commands/version.js +0 -21
  212. package/dist/endpoint-options.d.ts +0 -4
  213. package/dist/endpoint-options.js +0 -26
  214. package/dist/env-proxy.d.ts +0 -5
  215. package/dist/env-proxy.js +0 -20
  216. package/dist/help-path.d.ts +0 -18
  217. package/dist/help-path.js +0 -223
  218. package/dist/host/auth.d.ts +0 -20
  219. package/dist/host/auth.js +0 -119
  220. package/dist/host/login-env.d.ts +0 -1
  221. package/dist/host/login-env.js +0 -31
  222. package/dist/host/runtime.d.ts +0 -35
  223. package/dist/host/runtime.js +0 -395
  224. package/dist/host/runtimes.d.ts +0 -9
  225. package/dist/host/runtimes.js +0 -42
  226. package/dist/host/serve.d.ts +0 -2
  227. package/dist/host/serve.js +0 -117
  228. package/dist/host/workspaces.d.ts +0 -2
  229. package/dist/host/workspaces.js +0 -18
  230. package/dist/http-put.d.ts +0 -25
  231. package/dist/http-put.js +0 -132
  232. package/dist/index.d.ts +0 -2
  233. package/dist/index.js +0 -129
  234. package/dist/launcher.d.ts +0 -4
  235. package/dist/launcher.js +0 -38
  236. package/dist/local-media.d.ts +0 -2
  237. package/dist/local-media.js +0 -30
  238. package/dist/network-error.d.ts +0 -3
  239. package/dist/network-error.js +0 -22
  240. package/dist/output.d.ts +0 -46
  241. package/dist/output.js +0 -244
  242. package/dist/runtime/archive-store.d.ts +0 -54
  243. package/dist/runtime/archive-store.js +0 -379
  244. package/dist/runtime/cli-path.d.ts +0 -5
  245. package/dist/runtime/cli-path.js +0 -27
  246. package/dist/runtime/codex-usage.d.ts +0 -7
  247. package/dist/runtime/codex-usage.js +0 -11
  248. package/dist/runtime/connection.d.ts +0 -42
  249. package/dist/runtime/connection.js +0 -789
  250. package/dist/runtime/diagnostics.d.ts +0 -107
  251. package/dist/runtime/diagnostics.js +0 -392
  252. package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
  253. package/dist/runtime/harnesses/chained-projection.js +0 -95
  254. package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
  255. package/dist/runtime/harnesses/chained-transcript.js +0 -62
  256. package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
  257. package/dist/runtime/harnesses/claude-approval.js +0 -124
  258. package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
  259. package/dist/runtime/harnesses/claude-transcript.js +0 -138
  260. package/dist/runtime/harnesses/claude.d.ts +0 -8
  261. package/dist/runtime/harnesses/claude.js +0 -225
  262. package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
  263. package/dist/runtime/harnesses/codex-approval.js +0 -69
  264. package/dist/runtime/harnesses/codex.d.ts +0 -4
  265. package/dist/runtime/harnesses/codex.js +0 -269
  266. package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
  267. package/dist/runtime/harnesses/cursor-transcript.js +0 -183
  268. package/dist/runtime/harnesses/cursor.d.ts +0 -24
  269. package/dist/runtime/harnesses/cursor.js +0 -620
  270. package/dist/runtime/harnesses/index.d.ts +0 -16
  271. package/dist/runtime/harnesses/index.js +0 -73
  272. package/dist/runtime/harnesses/pi.d.ts +0 -4
  273. package/dist/runtime/harnesses/pi.js +0 -247
  274. package/dist/runtime/harnesses/process.d.ts +0 -31
  275. package/dist/runtime/harnesses/process.js +0 -75
  276. package/dist/runtime/harnesses/stream-json.d.ts +0 -48
  277. package/dist/runtime/harnesses/stream-json.js +0 -336
  278. package/dist/runtime/harnesses/types.d.ts +0 -117
  279. package/dist/runtime/harnesses/types.js +0 -1
  280. package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
  281. package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
  282. package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
  283. package/dist/runtime/harnesses/workbuddy.js +0 -123
  284. package/dist/runtime/instance.d.ts +0 -20
  285. package/dist/runtime/instance.js +0 -247
  286. package/dist/runtime/json-rpc.d.ts +0 -53
  287. package/dist/runtime/json-rpc.js +0 -212
  288. package/dist/runtime/launch.d.ts +0 -25
  289. package/dist/runtime/launch.js +0 -247
  290. package/dist/runtime/local-workspace.d.ts +0 -15
  291. package/dist/runtime/local-workspace.js +0 -52
  292. package/dist/runtime/model-catalog.d.ts +0 -12
  293. package/dist/runtime/model-catalog.js +0 -84
  294. package/dist/runtime/native/adapters.d.ts +0 -15
  295. package/dist/runtime/native/adapters.js +0 -11
  296. package/dist/runtime/native/approvals.d.ts +0 -18
  297. package/dist/runtime/native/approvals.js +0 -54
  298. package/dist/runtime/native/archive.d.ts +0 -19
  299. package/dist/runtime/native/archive.js +0 -142
  300. package/dist/runtime/native/attach.d.ts +0 -36
  301. package/dist/runtime/native/attach.js +0 -128
  302. package/dist/runtime/native/codex-link.d.ts +0 -60
  303. package/dist/runtime/native/codex-link.js +0 -322
  304. package/dist/runtime/native/config.d.ts +0 -16
  305. package/dist/runtime/native/config.js +0 -24
  306. package/dist/runtime/native/daemon.d.ts +0 -92
  307. package/dist/runtime/native/daemon.js +0 -380
  308. package/dist/runtime/native/execution.d.ts +0 -26
  309. package/dist/runtime/native/execution.js +0 -34
  310. package/dist/runtime/native/identity.d.ts +0 -9
  311. package/dist/runtime/native/identity.js +0 -15
  312. package/dist/runtime/native/ingest.d.ts +0 -263
  313. package/dist/runtime/native/ingest.js +0 -884
  314. package/dist/runtime/native/install.d.ts +0 -9
  315. package/dist/runtime/native/install.js +0 -113
  316. package/dist/runtime/native/paths.d.ts +0 -2
  317. package/dist/runtime/native/paths.js +0 -7
  318. package/dist/runtime/native/pi-extension.d.ts +0 -36
  319. package/dist/runtime/native/pi-link.d.ts +0 -69
  320. package/dist/runtime/native/pi-link.js +0 -269
  321. package/dist/runtime/native/results.d.ts +0 -41
  322. package/dist/runtime/native/results.js +0 -128
  323. package/dist/runtime/native/sessions.d.ts +0 -45
  324. package/dist/runtime/native/sessions.js +0 -87
  325. package/dist/runtime/native/transcript.d.ts +0 -89
  326. package/dist/runtime/native/transcript.js +0 -656
  327. package/dist/runtime/native/translate.d.ts +0 -46
  328. package/dist/runtime/native/translate.js +0 -299
  329. package/dist/runtime/native/transport.d.ts +0 -7
  330. package/dist/runtime/native/transport.js +0 -16
  331. package/dist/runtime/native/version.d.ts +0 -5
  332. package/dist/runtime/native/version.js +0 -21
  333. package/dist/runtime/preferences.d.ts +0 -7
  334. package/dist/runtime/preferences.js +0 -22
  335. package/dist/runtime/presentation.d.ts +0 -32
  336. package/dist/runtime/presentation.js +0 -124
  337. package/dist/runtime/process-group.d.ts +0 -5
  338. package/dist/runtime/process-group.js +0 -161
  339. package/dist/runtime/projection-store.d.ts +0 -27
  340. package/dist/runtime/projection-store.js +0 -30
  341. package/dist/runtime/space-binding.d.ts +0 -48
  342. package/dist/runtime/space-binding.js +0 -342
  343. package/dist/runtime/supervisor.d.ts +0 -19
  344. package/dist/runtime/supervisor.js +0 -441
  345. package/dist/runtime/turn-projection.d.ts +0 -41
  346. package/dist/runtime/turn-projection.js +0 -120
  347. package/dist/runtime/worker.d.ts +0 -1
  348. package/dist/safe-remote-image.d.ts +0 -36
  349. package/dist/safe-remote-image.js +0 -191
  350. package/dist/self-update.d.ts +0 -7
  351. package/dist/self-update.js +0 -202
  352. package/dist/session-status.d.ts +0 -10
  353. package/dist/session-status.js +0 -25
  354. package/dist/space-files/limit.d.ts +0 -2
  355. package/dist/space-files/limit.js +0 -16
  356. package/dist/space-files/operands.d.ts +0 -17
  357. package/dist/space-files/operands.js +0 -33
  358. package/dist/space-files/transfer.d.ts +0 -53
  359. package/dist/space-files/transfer.js +0 -297
  360. package/dist/space-files/upload.d.ts +0 -17
  361. package/dist/space-files/upload.js +0 -76
  362. package/dist/space.d.ts +0 -44
  363. package/dist/space.js +0 -192
  364. package/dist/version.d.ts +0 -2
  365. package/dist/version.js +0 -17
  366. package/dist/web.d.ts +0 -1
  367. package/dist/web.js +0 -4
  368. /package/dist/{board-kernel → chunks}/lexer.js +0 -0
@@ -0,0 +1,1246 @@
1
+ import { t as packagePath } from "./package-paths.js";
2
+ import { _ as union, a as array, b as uuid, c as discriminatedUnion, d as literal, f as number, h as string, i as _undefined, m as record, n as _enum, o as base64, p as object, s as boolean, v as unknown, y as url } from "./schemas.js";
3
+ import { B as readAuthSession, F as AuthRequiredError, G as revokeAndClearAuthSession, H as requestDeviceCode, I as authSessionPath, W as resolveAccessToken, Y as readRuntimeSpaceBindings, Z as runtimeSpaceBindingsPath, a as findLocalWorkspace, d as runtimeInstancesRoot, f as stopRuntimeInstance, h as currentIdentityKey, i as connectLocalWorkspace, l as requestRuntimeInstance, lt as LocalWorkspaceRpcError, m as clearHomeSpaceCache, p as watchRuntimeInstance, s as controlRuntimeInstance, u as runtimeInstanceDirectory, ut as LocalWorkspaceUnavailableError, v as jwtClaim, xt as displayIdSchema, z as pollDeviceCode } from "./client.js";
4
+ import { n as writeRuntimePreferences, t as readRuntimePreferences } from "./preferences.js";
5
+ import { t as EXPECTED_IDENTITY_ENV } from "./launch.js";
6
+ import { n as hostRuntimes, r as rememberHostRuntime, t as forgetHostRuntime } from "./runtimes.js";
7
+ import { t as describeCli } from "./about.js";
8
+ import { execFile, spawn } from "node:child_process";
9
+ import { homedir } from "node:os";
10
+ import { existsSync, mkdirSync, watch } from "node:fs";
11
+ import { basename, dirname, join, relative, sep } from "node:path";
12
+ import { randomUUID } from "node:crypto";
13
+ import { createInterface } from "node:readline";
14
+ import { opendir, readdir, realpath, stat } from "node:fs/promises";
15
+ //#region ../protocol/src/app-runtime.ts
16
+ const APP_RUNTIME_HAPTICS = [
17
+ "tick",
18
+ "confirm",
19
+ "reject",
20
+ "longPress"
21
+ ];
22
+ const hostBridgeCapabilitySchema = _enum([
23
+ "auth.token",
24
+ "auth.signIn",
25
+ "auth.session",
26
+ "notifications",
27
+ "share",
28
+ "filePicker",
29
+ "navigation",
30
+ "cache",
31
+ "runtime",
32
+ "appearance",
33
+ "launch",
34
+ "haptics",
35
+ "files",
36
+ "navigation.back",
37
+ "shortcuts",
38
+ "display",
39
+ "media.capture",
40
+ "runtime.picker",
41
+ "permissions",
42
+ "badge",
43
+ "app.launchAtLogin",
44
+ "app.globalShortcut",
45
+ "runtime.keepAwake",
46
+ "share.incoming",
47
+ "workspace",
48
+ "workspace.files",
49
+ "display.presenting",
50
+ "display.float",
51
+ "tabs",
52
+ "app.about"
53
+ ]);
54
+ const hostPlatformSchema = _enum([
55
+ "android",
56
+ "ios",
57
+ "macos",
58
+ "windows",
59
+ "linux",
60
+ "web",
61
+ "unknown"
62
+ ]);
63
+ const identifier = string().min(1).max(128);
64
+ const knownCapabilitiesSchema = array(string().min(1).max(64)).max(64).transform((names) => names.filter((name) => hostBridgeCapabilitySchema.safeParse(name).success));
65
+ const hostBridgeHelloSchema = object({
66
+ type: literal("hello"),
67
+ version: number().int().positive(),
68
+ platform: hostPlatformSchema,
69
+ hostId: identifier,
70
+ capabilities: knownCapabilitiesSchema
71
+ }).strict();
72
+ const hostDescriptionSchema = hostBridgeHelloSchema.omit({ type: true });
73
+ const hostBridgeRequestSchema = object({
74
+ type: literal("request"),
75
+ id: identifier,
76
+ method: string().min(1).max(64),
77
+ params: unknown().optional()
78
+ }).strict();
79
+ const hostBridgeResponseSchema = object({
80
+ type: literal("response"),
81
+ id: identifier,
82
+ result: unknown().optional(),
83
+ error: object({
84
+ code: string().min(1).max(64),
85
+ message: string().min(1).max(2e3)
86
+ }).strict().optional()
87
+ }).strict();
88
+ const hostBridgeEventSchema = object({
89
+ type: literal("event"),
90
+ name: string().min(1).max(64),
91
+ payload: unknown().optional()
92
+ }).strict();
93
+ discriminatedUnion("type", [
94
+ hostBridgeHelloSchema,
95
+ hostBridgeRequestSchema,
96
+ hostBridgeResponseSchema,
97
+ hostBridgeEventSchema
98
+ ]);
99
+ const accessTokenParams = object({ forceRefresh: boolean().optional() }).strict();
100
+ const sessionIdentitySchema = object({
101
+ authenticated: boolean(),
102
+ userUuid: string().min(1).max(128).nullable(),
103
+ subject: string().min(1).max(255).nullable(),
104
+ email: string().max(320).nullable()
105
+ }).strict();
106
+ const DEVICE_RUNTIME_REFUSALS = [
107
+ "space_in_use",
108
+ "folder_in_use",
109
+ "folder_unavailable",
110
+ "folder_denied"
111
+ ];
112
+ const DEVICE_RUNTIME_STOP_REFUSALS = ["unconfirmed_work"];
113
+ const devicePath = string().min(1).max(4096);
114
+ const deviceLabel = string().min(1).max(4096);
115
+ const deviceRuntimeInstanceSchema = object({
116
+ spaceId: uuid(),
117
+ root: devicePath,
118
+ label: deviceLabel,
119
+ state: _enum([
120
+ "stopped",
121
+ "connecting",
122
+ "ready",
123
+ "error"
124
+ ]),
125
+ error: string().min(1).max(64).nullable()
126
+ }).strict();
127
+ const deviceRuntimeSchema = object({ instances: array(deviceRuntimeInstanceSchema).max(256) }).strict();
128
+ const deviceFolderListingSchema = object({
129
+ path: devicePath,
130
+ label: deviceLabel,
131
+ parent: devicePath.nullable(),
132
+ spaceId: uuid().nullable(),
133
+ folders: array(object({
134
+ name: string().min(1).max(255),
135
+ path: devicePath
136
+ }).strict()).max(1e4),
137
+ volumes: array(object({
138
+ path: devicePath,
139
+ label: deviceLabel
140
+ }).strict()).max(16)
141
+ }).strict();
142
+ const deviceDisplayStatusSchema = object({
143
+ sharedWith: uuid().nullable(),
144
+ control: boolean(),
145
+ error: string().min(1).max(64).nullable(),
146
+ phoneControl: object({
147
+ stage: _enum([
148
+ "off",
149
+ "developer",
150
+ "pairing",
151
+ "code",
152
+ "starting",
153
+ "ready",
154
+ "stopped"
155
+ ]),
156
+ error: string().min(1).max(64).nullable(),
157
+ codeInput: boolean().optional(),
158
+ detail: string().max(512).optional()
159
+ }).optional()
160
+ }).strict();
161
+ const deviceDisplayRefSchema = object({
162
+ spaceId: uuid(),
163
+ display: displayIdSchema
164
+ }).strict();
165
+ const hostPermissionSchema = _enum([
166
+ "files",
167
+ "microphone",
168
+ "camera",
169
+ "notifications",
170
+ "background",
171
+ "screen",
172
+ "control"
173
+ ]);
174
+ const hostPermissionStateSchema = _enum([
175
+ "granted",
176
+ "denied",
177
+ "prompt"
178
+ ]);
179
+ const hostPermissionsSchema = object({
180
+ files: hostPermissionStateSchema.optional(),
181
+ microphone: hostPermissionStateSchema.optional(),
182
+ camera: hostPermissionStateSchema.optional(),
183
+ notifications: hostPermissionStateSchema.optional(),
184
+ background: hostPermissionStateSchema.optional()
185
+ });
186
+ const hostIncomingShareSchema = object({
187
+ id: identifier,
188
+ text: string().max(1e5).nullable(),
189
+ files: array(object({
190
+ name: string().min(1).max(255),
191
+ mimeType: string().min(1).max(255),
192
+ size: number().int().nonnegative()
193
+ }).strict()).max(16)
194
+ }).strict();
195
+ const hostColorSchema = string().regex(/^#[0-9a-f]{6}$/i);
196
+ const HOST_HAPTICS = APP_RUNTIME_HAPTICS;
197
+ const HOST_FILE_DATA_MAX_LENGTH = 16777216;
198
+ /** `id` is chosen by the web side; it correlates `files.progress` events and `files.reveal`. */
199
+ const savedFileSchema = object({
200
+ id: identifier,
201
+ name: string().min(1).max(255),
202
+ mimeType: string().min(1).max(255).optional()
203
+ });
204
+ const hostFileSaveParamsSchema = union([savedFileSchema.extend({ url: url({ protocol: /^https$/ }).max(8192) }).strict(), savedFileSchema.extend({ data: base64().max(HOST_FILE_DATA_MAX_LENGTH) }).strict()]);
205
+ /** Resolves once the file is on disk; a dismissed system sheet rejects as `canceled`. */
206
+ const hostFileSavedSchema = object({
207
+ location: _enum([
208
+ "downloads",
209
+ "pictures",
210
+ "movies",
211
+ "music",
212
+ "photos",
213
+ "files"
214
+ ]),
215
+ revealable: boolean()
216
+ }).strict();
217
+ object({
218
+ id: identifier,
219
+ received: number().int().nonnegative(),
220
+ total: number().int().positive().nullable()
221
+ }).strict();
222
+ const settingParams = object({ enabled: boolean().optional() }).strict();
223
+ const inAppPath = string().regex(/^\/(?!\/)/, "an in-app path").max(2048);
224
+ const hostShortcutSchema = object({
225
+ id: string().min(1).max(128),
226
+ label: string().min(1).max(64),
227
+ path: inAppPath
228
+ }).strict();
229
+ const hostNotificationSchema = object({
230
+ id: string().min(1).max(128),
231
+ title: string().min(1).max(256),
232
+ body: string().max(2e3).optional(),
233
+ path: inAppPath
234
+ }).strict();
235
+ /**
236
+ * What only the page knows about its own tab: `dirty` asks before the tab
237
+ * closes, `attention` marks a background tab until it is shown, and
238
+ * `captureKeys` hands the shell's tab shortcuts to the page while it forwards
239
+ * keys elsewhere, such as a remote screen.
240
+ */
241
+ const hostTabStateSchema = object({
242
+ dirty: boolean().optional(),
243
+ attention: literal(true).optional(),
244
+ captureKeys: boolean().optional()
245
+ }).strict();
246
+ const hostAuthChangedSchema = object({
247
+ authenticated: boolean(),
248
+ redirectPath: inAppPath.optional()
249
+ }).strict();
250
+ /**
251
+ * This device's Runtime answers a Space's filesystem calls directly when it
252
+ * serves that Space. Only `fs.*` crosses the bridge: process work stays on the
253
+ * Cohub pipeline. A request larger than this stays on the API: hosts read the
254
+ * bridge line by line.
255
+ */
256
+ const HOST_WORKSPACE_METHOD_PATTERN = /^fs\.[a-z]+$/;
257
+ const workspaceCallResultSchema = union([object({ result: unknown() }).strict(), object({ error: object({
258
+ code: string().min(1).max(64),
259
+ message: string().max(4e3)
260
+ }).strict() }).strict()]);
261
+ const HOST_SERVICE_WORKSPACE_ENDPOINT = "workspace.endpoint";
262
+ const HOST_SERVICE_CLI_ABOUT = "cli.about";
263
+ /**
264
+ * Methods the web surface may call. Both ends validate with these schemas, so
265
+ * a host cannot answer a shape the web side misreads.
266
+ */
267
+ const HOST_BRIDGE_METHODS = {
268
+ "host.describe": {
269
+ params: _undefined(),
270
+ result: hostDescriptionSchema
271
+ },
272
+ "auth.getAccessToken": {
273
+ params: accessTokenParams,
274
+ result: string().min(1).nullable()
275
+ },
276
+ "auth.getSessionVersion": {
277
+ params: _undefined(),
278
+ result: number().int().nonnegative()
279
+ },
280
+ "auth.getSession": {
281
+ params: _undefined(),
282
+ result: sessionIdentitySchema
283
+ },
284
+ "auth.signIn": {
285
+ params: object({ redirectPath: string().max(2048).optional() }).strict(),
286
+ result: boolean()
287
+ },
288
+ "auth.signOut": {
289
+ params: _undefined(),
290
+ result: boolean()
291
+ },
292
+ "notifications.register": {
293
+ params: _undefined(),
294
+ result: boolean()
295
+ },
296
+ "notifications.show": {
297
+ params: hostNotificationSchema,
298
+ result: boolean()
299
+ },
300
+ "share.text": {
301
+ params: object({
302
+ text: string().max(1e5),
303
+ title: string().max(512).optional()
304
+ }).strict(),
305
+ result: boolean()
306
+ },
307
+ "navigation.openPath": {
308
+ params: object({ path: string().min(1).max(2048) }).strict(),
309
+ result: boolean()
310
+ },
311
+ "cache.clear": {
312
+ params: object({ scope: _enum(["all", "user"]) }).strict(),
313
+ result: boolean()
314
+ },
315
+ "runtime.list": {
316
+ params: _undefined(),
317
+ result: deviceRuntimeSchema
318
+ },
319
+ "runtime.browse": {
320
+ params: object({ path: devicePath.optional() }).strict(),
321
+ result: deviceFolderListingSchema
322
+ },
323
+ "runtime.start": {
324
+ params: object({
325
+ spaceId: uuid(),
326
+ root: devicePath
327
+ }).strict(),
328
+ result: deviceRuntimeSchema.extend({ refused: _enum(DEVICE_RUNTIME_REFUSALS).nullable() }).strict()
329
+ },
330
+ "runtime.stop": {
331
+ params: object({
332
+ spaceId: uuid(),
333
+ force: boolean().optional()
334
+ }).strict(),
335
+ result: deviceRuntimeSchema.extend({ refused: _enum(DEVICE_RUNTIME_STOP_REFUSALS).nullable().optional() }).strict()
336
+ },
337
+ "runtime.pickFolder": {
338
+ params: object({ path: devicePath }).strict().optional(),
339
+ result: deviceFolderListingSchema
340
+ },
341
+ "runtime.keepAwake": {
342
+ params: settingParams,
343
+ result: boolean()
344
+ },
345
+ "permissions.status": {
346
+ params: _undefined(),
347
+ result: hostPermissionsSchema
348
+ },
349
+ "permissions.request": {
350
+ params: object({ kind: hostPermissionSchema }).strict(),
351
+ result: hostPermissionStateSchema
352
+ },
353
+ "permissions.openSettings": {
354
+ params: object({ kind: hostPermissionSchema }).strict(),
355
+ result: boolean()
356
+ },
357
+ "badge.set": {
358
+ params: object({ count: number().int().nonnegative() }).strict(),
359
+ result: boolean()
360
+ },
361
+ "app.launchAtLogin": {
362
+ params: settingParams,
363
+ result: boolean()
364
+ },
365
+ "app.globalShortcut": {
366
+ params: settingParams,
367
+ result: boolean()
368
+ },
369
+ "app.about": {
370
+ params: object({ web: string().min(1).max(64) }).strict(),
371
+ result: boolean()
372
+ },
373
+ "share.take": {
374
+ params: _undefined(),
375
+ result: hostIncomingShareSchema.nullable()
376
+ },
377
+ "share.readFile": {
378
+ params: object({
379
+ id: identifier,
380
+ index: number().int().nonnegative()
381
+ }).strict(),
382
+ result: object({ data: base64().max(HOST_FILE_DATA_MAX_LENGTH) }).strict()
383
+ },
384
+ "appearance.set": {
385
+ params: object({ backgroundColor: hostColorSchema }).strict(),
386
+ result: boolean()
387
+ },
388
+ "app.ready": {
389
+ params: _undefined(),
390
+ result: boolean()
391
+ },
392
+ "haptics.perform": {
393
+ params: object({ kind: _enum(HOST_HAPTICS) }).strict(),
394
+ result: boolean()
395
+ },
396
+ "files.save": {
397
+ params: hostFileSaveParamsSchema,
398
+ result: hostFileSavedSchema
399
+ },
400
+ "files.reveal": {
401
+ params: object({ id: identifier }).strict(),
402
+ result: boolean()
403
+ },
404
+ "navigation.interceptBack": {
405
+ params: object({ enabled: boolean() }).strict(),
406
+ result: boolean()
407
+ },
408
+ "shortcuts.push": {
409
+ params: hostShortcutSchema,
410
+ result: boolean()
411
+ },
412
+ "tabs.update": {
413
+ params: hostTabStateSchema,
414
+ result: boolean()
415
+ },
416
+ "display.status": {
417
+ params: _undefined(),
418
+ result: deviceDisplayStatusSchema
419
+ },
420
+ "display.share": {
421
+ params: object({ spaceId: uuid() }).strict(),
422
+ result: deviceDisplayStatusSchema
423
+ },
424
+ "display.stop": {
425
+ params: _undefined(),
426
+ result: deviceDisplayStatusSchema
427
+ },
428
+ "display.openControlSettings": {
429
+ params: _undefined(),
430
+ result: boolean()
431
+ },
432
+ "display.setup": {
433
+ params: _undefined(),
434
+ result: deviceDisplayStatusSchema
435
+ },
436
+ "display.pair": {
437
+ params: object({ code: string().regex(/^\d{6}$/) }).strict(),
438
+ result: deviceDisplayStatusSchema
439
+ },
440
+ "display.presenting": {
441
+ params: deviceDisplayRefSchema.optional(),
442
+ result: boolean()
443
+ },
444
+ "display.float": {
445
+ params: deviceDisplayRefSchema,
446
+ result: boolean()
447
+ },
448
+ "workspace.call": {
449
+ params: object({
450
+ spaceId: uuid(),
451
+ method: string().regex(HOST_WORKSPACE_METHOD_PATTERN).max(64),
452
+ params: record(string(), unknown()).optional()
453
+ }).strict(),
454
+ result: workspaceCallResultSchema
455
+ }
456
+ };
457
+ const HOST_BRIDGE_ERROR = {
458
+ unsupported: "unsupported",
459
+ unauthorized: "unauthorized",
460
+ canceled: "canceled",
461
+ failed: "failed",
462
+ denied: "denied",
463
+ unavailable: "unavailable"
464
+ };
465
+ object({
466
+ type: literal("hello"),
467
+ version: number().int().positive(),
468
+ capabilities: knownCapabilitiesSchema,
469
+ methods: array(string().min(1).max(64)).max(64)
470
+ }).strict();
471
+ const HOST_SERVICE_SHELL_EVENTS = { open: "shell.open" };
472
+ const hostShellOpenSchema = object({ url: url({ protocol: /^https?$/ }).max(8192) }).strict();
473
+ //#endregion
474
+ //#region ../sdk/src/host-bridge.ts
475
+ var HostBridgeErrorClass = class extends Error {
476
+ code;
477
+ constructor(code, message) {
478
+ super(message);
479
+ this.name = "HostBridgeError";
480
+ this.code = code;
481
+ }
482
+ get isCanceled() {
483
+ return this.code === HOST_BRIDGE_ERROR.canceled;
484
+ }
485
+ get isDenied() {
486
+ return this.code === HOST_BRIDGE_ERROR.denied;
487
+ }
488
+ get isUnsupported() {
489
+ return this.code === HOST_BRIDGE_ERROR.unsupported;
490
+ }
491
+ };
492
+ //#endregion
493
+ //#region src/host/auth.ts
494
+ const REOPEN_AFTER_MS = 1e4;
495
+ function snapshot() {
496
+ const session = readAuthSession();
497
+ if (!session) return {
498
+ subject: null,
499
+ revision: null
500
+ };
501
+ return {
502
+ subject: jwtClaim(session.idToken, "sub") ?? jwtClaim(session.accessToken, "sub"),
503
+ revision: `${session.updatedAt}:${session.refreshToken}`
504
+ };
505
+ }
506
+ var HostAuth = class {
507
+ emit;
508
+ onAccountChanged;
509
+ #current = snapshot();
510
+ #version = 0;
511
+ #watcher = null;
512
+ #debounce;
513
+ #rewatch;
514
+ #pending = null;
515
+ #requesting = null;
516
+ #redirectPath;
517
+ constructor(emit, onAccountChanged) {
518
+ this.emit = emit;
519
+ this.onAccountChanged = onAccountChanged;
520
+ }
521
+ watch() {
522
+ const path = authSessionPath();
523
+ mkdirSync(dirname(path), {
524
+ recursive: true,
525
+ mode: 448
526
+ });
527
+ this.#watcher = watch(dirname(path), (_event, name) => {
528
+ if (name && name !== basename(path)) return;
529
+ clearTimeout(this.#debounce);
530
+ this.#debounce = setTimeout(() => this.#sync(), 50);
531
+ });
532
+ this.#watcher.once("error", () => {
533
+ this.#watcher?.close();
534
+ this.#rewatch = setTimeout(() => this.watch(), 1e3).unref();
535
+ });
536
+ }
537
+ close() {
538
+ clearTimeout(this.#debounce);
539
+ clearTimeout(this.#rewatch);
540
+ this.#watcher?.close();
541
+ }
542
+ get subject() {
543
+ return this.#current.subject;
544
+ }
545
+ async accessToken(forceRefresh = false) {
546
+ try {
547
+ return await resolveAccessToken({ forceRefresh });
548
+ } catch (error) {
549
+ if (error instanceof AuthRequiredError) return null;
550
+ throw error;
551
+ }
552
+ }
553
+ sessionVersion() {
554
+ return this.#version;
555
+ }
556
+ session() {
557
+ const { subject } = snapshot();
558
+ return {
559
+ authenticated: subject !== null,
560
+ userUuid: null,
561
+ subject,
562
+ email: null
563
+ };
564
+ }
565
+ async signIn(redirectPath) {
566
+ this.#redirectPath = hostAuthChangedSchema.shape.redirectPath.safeParse(redirectPath).data;
567
+ const pending = this.#pending;
568
+ if (pending && pending.expiresAt > Date.now()) {
569
+ if (Date.now() - pending.openedAt >= REOPEN_AFTER_MS) this.#openPending(pending);
570
+ return true;
571
+ }
572
+ this.#requesting ??= this.#request().finally(() => {
573
+ this.#requesting = null;
574
+ });
575
+ await this.#requesting;
576
+ return true;
577
+ }
578
+ async #request() {
579
+ const code = await requestDeviceCode();
580
+ const pending = {
581
+ url: code.verificationUriComplete,
582
+ expiresAt: code.expiresAt,
583
+ openedAt: 0
584
+ };
585
+ this.#pending = pending;
586
+ this.#openPending(pending);
587
+ pollDeviceCode(code).then(() => this.#sync({
588
+ redirectPath: this.#redirectPath,
589
+ signedIn: true
590
+ })).catch((error) => process.stderr.write(`Sign-in did not complete: ${error instanceof Error ? error.message : String(error)}\n`)).finally(() => {
591
+ if (this.#pending === pending) this.#pending = null;
592
+ });
593
+ }
594
+ #openPending(pending) {
595
+ pending.openedAt = Date.now();
596
+ this.#open(pending.url);
597
+ }
598
+ async signOut() {
599
+ await revokeAndClearAuthSession();
600
+ clearHomeSpaceCache();
601
+ this.#sync();
602
+ this.emit("auth.signedOut");
603
+ return true;
604
+ }
605
+ #open(url) {
606
+ this.emit(HOST_SERVICE_SHELL_EVENTS.open, hostShellOpenSchema.parse({ url }));
607
+ }
608
+ #sync({ redirectPath, signedIn = false } = {}) {
609
+ const next = snapshot();
610
+ const accountChanged = next.subject !== this.#current.subject;
611
+ if (next.revision !== this.#current.revision || accountChanged) this.#version += 1;
612
+ this.#current = next;
613
+ if (accountChanged) this.onAccountChanged();
614
+ if (!accountChanged && !signedIn) return;
615
+ this.emit("auth.changed", hostAuthChangedSchema.parse({
616
+ authenticated: next.subject !== null,
617
+ ...redirectPath ? { redirectPath } : {}
618
+ }));
619
+ }
620
+ };
621
+ //#endregion
622
+ //#region src/host/login-env.ts
623
+ const TIMEOUT_MS = 1e4;
624
+ const SCOPED = /^(COHUB_.*|ENV)$/;
625
+ const quote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
626
+ async function loginShellEnv(base = process.env, platform = process.platform) {
627
+ const scoped = Object.fromEntries(Object.entries(base).filter(([key]) => SCOPED.test(key)));
628
+ if (platform === "win32") return base;
629
+ const shell = base.SHELL || (platform === "darwin" ? "/bin/zsh" : "/bin/sh");
630
+ const mark = randomUUID();
631
+ const print = `${quote(process.execPath)} -e ${quote("process.stdout.write(JSON.stringify(process.env))")}`;
632
+ const json = (await new Promise((resolve) => {
633
+ execFile(shell, [
634
+ "-l",
635
+ "-i",
636
+ "-c",
637
+ `printf %s ${mark}; ${print}; printf %s ${mark}`
638
+ ], {
639
+ encoding: "utf8",
640
+ timeout: TIMEOUT_MS,
641
+ maxBuffer: 4194304,
642
+ env: base
643
+ }, (_error, stdout) => resolve(typeof stdout === "string" ? stdout : null));
644
+ }))?.split(mark)[1];
645
+ if (!json) return base;
646
+ try {
647
+ const shellEnv = JSON.parse(json);
648
+ return {
649
+ ...Object.fromEntries(Object.entries(shellEnv).filter(([key]) => !SCOPED.test(key))),
650
+ ...scoped
651
+ };
652
+ } catch {
653
+ return base;
654
+ }
655
+ }
656
+ //#endregion
657
+ //#region src/host/runtime.ts
658
+ const MAX_FOLDERS = 1e4;
659
+ const MAX_VOLUMES = 16;
660
+ const DISPLAY_CONTROL_MS = 15e3;
661
+ const SHARED_SCREEN = "auto";
662
+ const NO_SCREEN = "";
663
+ const isRunningState = (state) => state === "connecting" || state === "ready";
664
+ const isRunning = (instance) => isRunningState(instance?.state);
665
+ const samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
666
+ function deviceState(status) {
667
+ if (!status || status.state === "stopping") return "stopped";
668
+ if (status.state === "ready") return "ready";
669
+ return status.state === "attention" ? "error" : "connecting";
670
+ }
671
+ const isDenied = (error) => ["EPERM", "EACCES"].includes(error.code ?? "");
672
+ function launchFailure(message) {
673
+ if (/non-elevated/.test(message)) return "elevated";
674
+ if (/EPERM|EACCES|permission denied|operation not permitted/i.test(message)) return "folder_denied";
675
+ if (/fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|Download of \S+ (failed|timed out)/.test(message)) return "offline";
676
+ return "failed";
677
+ }
678
+ function hasWindowsShell(env = process.env) {
679
+ if (env.COHUB_BASH) return true;
680
+ const roots = [
681
+ env.ProgramFiles,
682
+ env["ProgramFiles(x86)"],
683
+ env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Programs")
684
+ ];
685
+ const directories = (env.PATH ?? env.Path ?? "").split(";").filter((entry) => /[\\/]git[\\/]/i.test(entry));
686
+ return [
687
+ ...roots.flatMap((root) => root ? [join(root, "Git", "bin", "bash.exe")] : []),
688
+ ...directories.map((entry) => join(entry, "bash.exe")),
689
+ ...directories.map((entry) => join(dirname(entry), "bin", "bash.exe"))
690
+ ].some((path) => existsSync(path));
691
+ }
692
+ function displayPath(path, home = homedir()) {
693
+ if (process.platform === "win32") return path;
694
+ const inside = relative(home, path);
695
+ if (!inside) return "~";
696
+ return inside.startsWith("..") || inside.startsWith(sep) ? path : `~/${inside}`;
697
+ }
698
+ async function isDirectory(path) {
699
+ return stat(path).then((info) => info.isDirectory(), () => false);
700
+ }
701
+ async function volumes() {
702
+ const home = homedir();
703
+ const homeVolume = {
704
+ path: home,
705
+ label: basename(home) || home
706
+ };
707
+ if (process.platform === "win32") return [homeVolume, ...(await Promise.all([..."CDEFGHIJKLMNOPQRSTUVWXYZ"].map(async (letter) => {
708
+ const path = `${letter}:\\`;
709
+ return await isDirectory(path) ? {
710
+ path,
711
+ label: `${letter}:`
712
+ } : null;
713
+ }))).filter((drive) => drive !== null)].slice(0, MAX_VOLUMES);
714
+ if (process.platform === "darwin") {
715
+ const mounted = await readdir("/Volumes").catch(() => []);
716
+ return [homeVolume, ...(await Promise.all(mounted.map(async (name) => {
717
+ const path = await realpath(join("/Volumes", name)).catch(() => null);
718
+ return path ? {
719
+ path,
720
+ label: name
721
+ } : null;
722
+ }))).filter((volume) => volume !== null)].slice(0, MAX_VOLUMES);
723
+ }
724
+ return [homeVolume, {
725
+ path: "/",
726
+ label: "/"
727
+ }];
728
+ }
729
+ var DeviceRuntimeHost = class {
730
+ emit;
731
+ options;
732
+ #watchers = [];
733
+ #subscriptions = /* @__PURE__ */ new Map();
734
+ #debounce;
735
+ #published = "";
736
+ #restoring = Promise.resolve();
737
+ #unwatchable = /* @__PURE__ */ new Set();
738
+ #transient = /* @__PURE__ */ new Map();
739
+ #screen = {
740
+ sharedWith: null,
741
+ control: false,
742
+ error: null
743
+ };
744
+ #publishedScreen = "";
745
+ #shared = /* @__PURE__ */ new Set();
746
+ #screenWork = Promise.resolve();
747
+ constructor(emit, options) {
748
+ this.emit = emit;
749
+ this.options = options;
750
+ }
751
+ watch() {
752
+ this.#watch();
753
+ this.restore();
754
+ }
755
+ close() {
756
+ clearTimeout(this.#debounce);
757
+ for (const watcher of this.#watchers) watcher.close();
758
+ for (const subscription of this.#subscriptions.values()) subscription.abort();
759
+ }
760
+ #watch() {
761
+ const bindings = runtimeSpaceBindingsPath();
762
+ const instances = runtimeInstancesRoot();
763
+ mkdirSync(dirname(bindings), {
764
+ recursive: true,
765
+ mode: 448
766
+ });
767
+ mkdirSync(instances, {
768
+ recursive: true,
769
+ mode: 448
770
+ });
771
+ const watchers = [watch(dirname(bindings), (_event, name) => {
772
+ if (!name || name === basename(bindings)) this.changed();
773
+ }), watch(instances, { recursive: true }, () => this.changed())];
774
+ this.#watchers = watchers;
775
+ const rewatch = () => {
776
+ if (this.#watchers !== watchers) return;
777
+ this.#watchers = [];
778
+ for (const watcher of watchers) watcher.close();
779
+ setTimeout(() => {
780
+ this.#watch();
781
+ this.changed();
782
+ }, 1e3).unref();
783
+ };
784
+ for (const watcher of watchers) watcher.on("error", rewatch);
785
+ }
786
+ changed() {
787
+ clearTimeout(this.#debounce);
788
+ this.#debounce = setTimeout(() => void this.#publish().catch(() => void 0), 100);
789
+ }
790
+ async list() {
791
+ const key = this.options.account();
792
+ if (!key) return { instances: [] };
793
+ const bindings = (await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }))).bindings;
794
+ const roots = /* @__PURE__ */ new Map();
795
+ for (const binding of bindings) {
796
+ if (binding.key !== key) continue;
797
+ roots.delete(binding.spaceId);
798
+ roots.set(binding.spaceId, binding.root);
799
+ }
800
+ for (const [spaceId, { root }] of this.#transient) if (!roots.has(spaceId)) roots.set(spaceId, root);
801
+ let screen = {
802
+ sharedWith: null,
803
+ control: false,
804
+ error: null
805
+ };
806
+ const shared = /* @__PURE__ */ new Set();
807
+ const hasShell = process.platform !== "win32" || hasWindowsShell();
808
+ const instances = await Promise.all([...roots].slice(-256).map(async ([spaceId, root]) => {
809
+ const directory = runtimeInstanceDirectory(key, spaceId);
810
+ const transient = this.#transient.get(spaceId);
811
+ try {
812
+ const status = await requestRuntimeInstance(directory);
813
+ if (!status && transient) return {
814
+ spaceId,
815
+ ...transient,
816
+ label: displayPath(transient.root)
817
+ };
818
+ if (status) this.#subscribe(directory, status.pid);
819
+ if (status?.display) {
820
+ const needs = status.displayNeeds ?? [];
821
+ if (status.displayOnRequest) shared.add(spaceId);
822
+ screen = {
823
+ sharedWith: spaceId,
824
+ control: !needs.includes("accessibility"),
825
+ error: needs.includes("screenRecording") ? "screen_recording" : null
826
+ };
827
+ }
828
+ const path = status?.root ?? root;
829
+ const state = deviceState(status);
830
+ return {
831
+ spaceId,
832
+ root: path,
833
+ label: displayPath(path),
834
+ state,
835
+ error: status?.state === "attention" ? "attention" : isRunningState(state) && !hasShell ? "no_shell" : null
836
+ };
837
+ } catch {
838
+ return {
839
+ spaceId,
840
+ root,
841
+ label: displayPath(root),
842
+ state: "error",
843
+ error: "unreachable"
844
+ };
845
+ }
846
+ }));
847
+ this.#screen = screen;
848
+ this.#shared = shared;
849
+ return { instances };
850
+ }
851
+ async browse(path) {
852
+ const target = await realpath(path ?? homedir());
853
+ if (!await isDirectory(target)) throw new Error("Not a folder");
854
+ const entries = await readdir(target, { withFileTypes: true });
855
+ const folders = (await Promise.all(entries.map(async (entry) => {
856
+ if (entry.name.startsWith(".")) return null;
857
+ const folder = join(target, entry.name);
858
+ return entry.isDirectory() || entry.isSymbolicLink() && await isDirectory(folder) ? {
859
+ name: entry.name,
860
+ path: folder
861
+ } : null;
862
+ }))).filter((folder) => folder !== null).sort((a, b) => a.name.localeCompare(b.name, void 0, {
863
+ numeric: true,
864
+ sensitivity: "base"
865
+ })).slice(0, MAX_FOLDERS);
866
+ const key = this.options.account();
867
+ const bindings = key ? (await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }))).bindings : [];
868
+ const parent = dirname(target);
869
+ return {
870
+ path: target,
871
+ label: displayPath(target),
872
+ parent: parent === target ? null : parent,
873
+ spaceId: bindings.filter((binding) => binding.key === key && samePath(binding.root, target)).at(-1)?.spaceId ?? null,
874
+ folders,
875
+ volumes: await volumes()
876
+ };
877
+ }
878
+ async connect(spaceId, root) {
879
+ const key = this.options.account();
880
+ if (!key) throw new Error("Sign in first");
881
+ const folder = await realpath(root).catch(() => null);
882
+ const current = await this.list();
883
+ if (!folder || !await isDirectory(folder)) return {
884
+ ...current,
885
+ refused: "folder_unavailable"
886
+ };
887
+ const serving = current.instances.find((instance) => instance.spaceId === spaceId);
888
+ if (isRunning(serving)) return {
889
+ ...current,
890
+ refused: samePath(serving.root, folder) ? null : "space_in_use"
891
+ };
892
+ if (current.instances.some((instance) => isRunning(instance) && samePath(instance.root, folder))) return {
893
+ ...current,
894
+ refused: "folder_in_use"
895
+ };
896
+ if (await opendir(folder).then((directory) => directory.close().then(() => false), isDenied)) return {
897
+ ...current,
898
+ refused: "folder_denied"
899
+ };
900
+ this.#transient.set(spaceId, {
901
+ root: folder,
902
+ state: "connecting",
903
+ error: null
904
+ });
905
+ this.#publish().catch(() => void 0);
906
+ try {
907
+ await this.#launch(key, spaceId, folder);
908
+ await rememberHostRuntime({
909
+ key,
910
+ spaceId,
911
+ root: folder
912
+ });
913
+ this.#transient.delete(spaceId);
914
+ } catch (error) {
915
+ const message = error instanceof Error ? error.message : String(error);
916
+ process.stderr.write(`Could not connect ${folder}: ${message}\n`);
917
+ this.#transient.set(spaceId, {
918
+ root: folder,
919
+ state: "error",
920
+ error: launchFailure(message)
921
+ });
922
+ }
923
+ return {
924
+ ...await this.#publish(),
925
+ refused: null
926
+ };
927
+ }
928
+ async disconnect(spaceId, force = false) {
929
+ const key = this.options.account();
930
+ if (!key) throw new Error("Sign in first");
931
+ this.#transient.delete(spaceId);
932
+ try {
933
+ await stopRuntimeInstance(runtimeInstanceDirectory(key, spaceId), force);
934
+ } catch (error) {
935
+ if (error instanceof Error && error.message.startsWith("Unconfirmed executions remain")) return {
936
+ ...await this.list(),
937
+ refused: "unconfirmed_work"
938
+ };
939
+ throw error;
940
+ }
941
+ await forgetHostRuntime(key, spaceId);
942
+ return {
943
+ ...await this.#publish(),
944
+ refused: null
945
+ };
946
+ }
947
+ async stopAccount() {
948
+ const key = this.options.account();
949
+ if (!key) return;
950
+ const { instances } = await this.list();
951
+ await Promise.allSettled(instances.filter(isRunning).map((instance) => stopRuntimeInstance(runtimeInstanceDirectory(key, instance.spaceId), true)));
952
+ this.accountChanged();
953
+ }
954
+ accountChanged() {
955
+ this.#transient.clear();
956
+ }
957
+ async displayStatus() {
958
+ await this.list();
959
+ return this.#screen;
960
+ }
961
+ #serialScreen(work) {
962
+ const run = this.#screenWork.then(work);
963
+ this.#screenWork = run.catch(() => void 0);
964
+ return run;
965
+ }
966
+ share(spaceId) {
967
+ return this.#serialScreen(async () => {
968
+ const key = this.options.account();
969
+ if (!key) throw new Error("Sign in first");
970
+ const { instances } = await this.list();
971
+ if (!isRunning(instances.find((instance) => instance.spaceId === spaceId))) throw new Error("This device does not serve that Space");
972
+ const previous = this.#screen.sharedWith;
973
+ if (previous && previous !== spaceId) await this.#setScreen(key, previous, NO_SCREEN);
974
+ await this.#setScreen(key, spaceId, SHARED_SCREEN);
975
+ await this.#publish();
976
+ return this.#screen;
977
+ });
978
+ }
979
+ stopSharing() {
980
+ return this.#serialScreen(async () => {
981
+ const key = this.options.account();
982
+ if (!key) throw new Error("Sign in first");
983
+ await this.list();
984
+ if (this.#screen.sharedWith) await this.#setScreen(key, this.#screen.sharedWith, NO_SCREEN);
985
+ await this.#publish();
986
+ return this.#screen;
987
+ });
988
+ }
989
+ stopOwnSharing() {
990
+ return this.#serialScreen(async () => {
991
+ const key = this.options.account();
992
+ if (!key) return;
993
+ await this.list();
994
+ const results = await Promise.allSettled([...this.#shared].map((spaceId) => this.#setScreen(key, spaceId, NO_SCREEN)));
995
+ for (const result of results) if (result.status === "rejected") process.stderr.write(`Could not stop sharing the screen: ${String(result.reason)}\n`);
996
+ });
997
+ }
998
+ async keepAwake(enabled) {
999
+ if (enabled === void 0) return (await readRuntimePreferences()).keepAwake;
1000
+ await writeRuntimePreferences({ keepAwake: enabled });
1001
+ const key = this.options.account();
1002
+ if (key) {
1003
+ const { instances } = await this.list();
1004
+ await Promise.allSettled(instances.filter(isRunning).map((instance) => controlRuntimeInstance(runtimeInstanceDirectory(key, instance.spaceId), "keepAwake")));
1005
+ }
1006
+ return enabled;
1007
+ }
1008
+ async #setScreen(key, spaceId, spec) {
1009
+ await controlRuntimeInstance(runtimeInstanceDirectory(key, spaceId), "display", { spec }, DISPLAY_CONTROL_MS);
1010
+ }
1011
+ restore() {
1012
+ this.#restoring = this.#restoring.then(async () => {
1013
+ const key = this.options.account();
1014
+ if (!key) return;
1015
+ const { bindings } = await readRuntimeSpaceBindings();
1016
+ for (const item of await hostRuntimes(key)) {
1017
+ const bound = bindings.filter((binding) => binding.key === key && binding.spaceId === item.spaceId).at(-1);
1018
+ if (!bound || !samePath(bound.root, item.root)) {
1019
+ await forgetHostRuntime(key, item.spaceId);
1020
+ continue;
1021
+ }
1022
+ if (await requestRuntimeInstance(runtimeInstanceDirectory(key, item.spaceId)).catch(() => true) || !await isDirectory(item.root)) continue;
1023
+ await this.#launch(key, item.spaceId, item.root).catch((error) => {
1024
+ process.stderr.write(`Could not reconnect ${item.root}: ${error instanceof Error ? error.message : String(error)}\n`);
1025
+ });
1026
+ }
1027
+ }).catch((error) => {
1028
+ process.stderr.write(`Could not restore connected folders: ${error instanceof Error ? error.message : String(error)}\n`);
1029
+ }).finally(() => this.changed());
1030
+ return this.#restoring;
1031
+ }
1032
+ async #publish() {
1033
+ const runtime = await this.list();
1034
+ const serialized = JSON.stringify(runtime);
1035
+ if (serialized !== this.#published) {
1036
+ this.#published = serialized;
1037
+ this.emit("runtime.changed", runtime);
1038
+ }
1039
+ const screen = JSON.stringify(this.#screen);
1040
+ if (screen !== this.#publishedScreen) {
1041
+ this.#publishedScreen = screen;
1042
+ this.emit("display.changed", this.#screen);
1043
+ }
1044
+ return runtime;
1045
+ }
1046
+ #subscribe(directory, pid) {
1047
+ const instance = `${directory}:${pid}`;
1048
+ if (this.#subscriptions.has(directory) || this.#unwatchable.has(instance)) return;
1049
+ const controller = new AbortController();
1050
+ this.#subscriptions.set(directory, controller);
1051
+ watchRuntimeInstance(directory, () => this.changed(), controller.signal).then((streamed) => {
1052
+ if (!streamed) this.#unwatchable.add(instance);
1053
+ }, () => void 0).finally(() => {
1054
+ if (this.#subscriptions.get(directory) === controller) this.#subscriptions.delete(directory);
1055
+ if (!controller.signal.aborted) this.changed();
1056
+ });
1057
+ }
1058
+ async #launch(key, spaceId, root) {
1059
+ const env = await this.options.env();
1060
+ if (this.options.account() !== key) throw new Error("The signed-in account changed");
1061
+ const child = spawn(process.execPath, [
1062
+ this.options.cli,
1063
+ "runtime",
1064
+ "up",
1065
+ root,
1066
+ "--space",
1067
+ spaceId,
1068
+ "--detach",
1069
+ "--yes",
1070
+ "--no-display",
1071
+ "--json"
1072
+ ], {
1073
+ env: {
1074
+ ...env,
1075
+ [EXPECTED_IDENTITY_ENV]: key
1076
+ },
1077
+ stdio: [
1078
+ "ignore",
1079
+ "ignore",
1080
+ "pipe"
1081
+ ],
1082
+ windowsHide: true
1083
+ });
1084
+ let stderr = "";
1085
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
1086
+ stderr = `${stderr}${chunk}`.slice(-8192);
1087
+ });
1088
+ const code = await new Promise((resolve, reject) => {
1089
+ child.once("error", reject);
1090
+ child.once("close", resolve);
1091
+ });
1092
+ if (code === 0 || code === 2) return;
1093
+ const reason = stderr.trim().split("\n").at(-1)?.replace(/^Runtime failed: /, "");
1094
+ throw new Error(reason || `Runtime exited (${code})`);
1095
+ }
1096
+ };
1097
+ //#endregion
1098
+ //#region src/host/workspaces.ts
1099
+ async function callLocalWorkspace(spaceId, method, params) {
1100
+ const endpoint = await findLocalWorkspace(spaceId);
1101
+ if (endpoint) try {
1102
+ return { result: await connectLocalWorkspace(endpoint).call(method, params ?? {}) };
1103
+ } catch (error) {
1104
+ if (error instanceof LocalWorkspaceRpcError) return { error: {
1105
+ code: error.rpcErrorCode,
1106
+ message: error.message.slice(0, 4e3)
1107
+ } };
1108
+ if (!(error instanceof LocalWorkspaceUnavailableError)) throw error;
1109
+ }
1110
+ throw new HostBridgeErrorClass(HOST_BRIDGE_ERROR.unavailable, "This device does not serve that Space");
1111
+ }
1112
+ //#endregion
1113
+ //#region src/host/serve.ts
1114
+ const CAPABILITIES = [
1115
+ "auth.token",
1116
+ "auth.signIn",
1117
+ "auth.session",
1118
+ "runtime",
1119
+ "runtime.keepAwake",
1120
+ "workspace",
1121
+ ...["darwin", "win32"].includes(process.platform) ? ["display"] : []
1122
+ ];
1123
+ const SPACE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1124
+ const MAX_LINE = 8388608;
1125
+ const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
1126
+ async function serveHost(entry = packagePath("bin", "cohub.js")) {
1127
+ const emit = (name, payload) => write({
1128
+ type: "event",
1129
+ name,
1130
+ ...payload === void 0 ? {} : { payload }
1131
+ });
1132
+ let environment = null;
1133
+ const env = () => environment ??= loginShellEnv();
1134
+ const about = async () => describeCli(await env(), currentIdentityKey());
1135
+ const runtime = new DeviceRuntimeHost(emit, {
1136
+ cli: entry,
1137
+ env,
1138
+ account: currentIdentityKey
1139
+ });
1140
+ const auth = new HostAuth(emit, () => {
1141
+ runtime.accountChanged();
1142
+ runtime.changed();
1143
+ runtime.restore();
1144
+ });
1145
+ const handlers = {
1146
+ "auth.getAccessToken": (params) => auth.accessToken(params.forceRefresh === true),
1147
+ "auth.getSessionVersion": () => auth.sessionVersion(),
1148
+ "auth.getSession": () => auth.session(),
1149
+ "auth.signIn": (params) => auth.signIn(typeof params.redirectPath === "string" ? params.redirectPath : void 0),
1150
+ "auth.signOut": async () => {
1151
+ await runtime.stopAccount().catch((error) => process.stderr.write(`Could not stop Runtimes before signing out: ${error instanceof Error ? error.message : String(error)}\n`));
1152
+ return auth.signOut();
1153
+ },
1154
+ "runtime.list": () => runtime.list(),
1155
+ "runtime.browse": (params) => runtime.browse(typeof params.path === "string" ? params.path : void 0),
1156
+ "runtime.start": (params) => runtime.connect(String(params.spaceId), String(params.root)),
1157
+ "runtime.stop": (params) => runtime.disconnect(String(params.spaceId), params.force === true),
1158
+ "runtime.keepAwake": (params) => runtime.keepAwake(typeof params.enabled === "boolean" ? params.enabled : void 0),
1159
+ ...CAPABILITIES.includes("display") ? {
1160
+ "display.status": () => runtime.displayStatus(),
1161
+ "display.share": (params) => runtime.share(String(params.spaceId)),
1162
+ "display.stop": () => runtime.stopSharing()
1163
+ } : {},
1164
+ "workspace.call": (params) => callLocalWorkspace(String(params.spaceId), String(params.method), params.params)
1165
+ };
1166
+ const shellHandlers = {
1167
+ [HOST_SERVICE_CLI_ABOUT]: about,
1168
+ [HOST_SERVICE_WORKSPACE_ENDPOINT]: (params) => {
1169
+ const spaceId = String(params.spaceId ?? "");
1170
+ if (!SPACE_ID.test(spaceId)) throw new Error("A Space id is required");
1171
+ return findLocalWorkspace(spaceId);
1172
+ }
1173
+ };
1174
+ const answer = async (line) => {
1175
+ let raw;
1176
+ try {
1177
+ raw = JSON.parse(line);
1178
+ } catch {
1179
+ return;
1180
+ }
1181
+ const request = hostBridgeRequestSchema.safeParse(raw);
1182
+ if (!request.success) return;
1183
+ const { id, method } = request.data;
1184
+ const fail = (code, message) => write({
1185
+ type: "response",
1186
+ id,
1187
+ error: {
1188
+ code,
1189
+ message: message.slice(0, 2e3) || "Host call failed"
1190
+ }
1191
+ });
1192
+ const name = method;
1193
+ const shellHandler = Object.hasOwn(shellHandlers, method) ? shellHandlers[method] : void 0;
1194
+ if (shellHandler) {
1195
+ try {
1196
+ write({
1197
+ type: "response",
1198
+ id,
1199
+ result: await shellHandler(request.data.params ?? {}) ?? null
1200
+ });
1201
+ } catch (error) {
1202
+ fail(HOST_BRIDGE_ERROR.failed, error instanceof Error ? error.message : String(error));
1203
+ }
1204
+ return;
1205
+ }
1206
+ const handler = handlers[name];
1207
+ if (!handler) return fail(HOST_BRIDGE_ERROR.unsupported, `Unsupported method: ${method}`);
1208
+ const shape = HOST_BRIDGE_METHODS[name];
1209
+ const params = shape.params.safeParse(request.data.params);
1210
+ if (!params.success) return fail(HOST_BRIDGE_ERROR.failed, `Invalid params for ${method}`);
1211
+ try {
1212
+ const result = await handler(params.data ?? {});
1213
+ write({
1214
+ type: "response",
1215
+ id,
1216
+ result: shape.result.parse(result)
1217
+ });
1218
+ } catch (error) {
1219
+ const denied = ["EPERM", "EACCES"].includes(error.code ?? "");
1220
+ fail(error instanceof HostBridgeErrorClass ? error.code : denied ? HOST_BRIDGE_ERROR.denied : HOST_BRIDGE_ERROR.failed, error instanceof Error ? error.message : String(error));
1221
+ }
1222
+ };
1223
+ const hello = {
1224
+ type: "hello",
1225
+ version: 1,
1226
+ capabilities: [...CAPABILITIES],
1227
+ methods: Object.keys(handlers)
1228
+ };
1229
+ write(hello);
1230
+ auth.watch();
1231
+ runtime.watch();
1232
+ setTimeout(() => void about().catch(() => void 0), 3e3).unref();
1233
+ const input = createInterface({
1234
+ input: process.stdin,
1235
+ crlfDelay: Infinity
1236
+ });
1237
+ input.on("line", (line) => {
1238
+ if (line.length <= MAX_LINE) answer(line);
1239
+ });
1240
+ await new Promise((resolve) => input.once("close", resolve));
1241
+ auth.close();
1242
+ await runtime.stopOwnSharing();
1243
+ runtime.close();
1244
+ }
1245
+ //#endregion
1246
+ export { serveHost };