@neta-art/cohub-cli 10.23.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 (369) hide show
  1. package/README.md +18 -5
  2. package/bin/cohub.js +4 -1
  3. package/dist/board-gpu/page.js +1566 -71230
  4. package/dist/bootstrap.js +67 -27
  5. package/dist/build.json +1 -1
  6. package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
  7. package/dist/chunks/about.js +102 -0
  8. package/dist/chunks/app-realtime.js +2216 -0
  9. package/dist/chunks/app-realtime2.js +2 -0
  10. package/dist/chunks/app-ref.js +88 -0
  11. package/dist/chunks/apps.js +1423 -0
  12. package/dist/chunks/auth.js +175 -0
  13. package/dist/chunks/avatar.js +146 -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 +309 -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 +2511 -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 -118
  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 -64
  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 -2139
  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 -6
  354. package/dist/session-status.js +0 -16
  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
@@ -1,2139 +0,0 @@
1
- import { readdir, stat } from "node:fs/promises";
2
- import { basename, dirname, relative, resolve, sep } from "node:path";
3
- import { APPROVAL_MODES, harnessSchema, isApprovalMode, isModelThinkingLevel, MODEL_THINKING_LEVELS, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
4
- import { uploadAvatarAsset, uploadChatImageAsset, uploadLikeStickerAsset } from "../avatar.js";
5
- import { createClient } from "../client.js";
6
- import { collectOption, readPromptContent } from "../command-input.js";
7
- import { table, json as outJson, jsonRequested, ok, error, handleHttp, formatEpochMs, truncateText } from "../output.js";
8
- import { SESSION_STATUS_COLUMN } from "../session-status.js";
9
- import { resolveSpace } from "../space.js";
10
- import { uploadLocalFiles } from "../space-files/upload.js";
11
- import { registerDecisionCommand } from "./decision.js";
12
- import { registerSpaceCommerce } from "./space-commerce.js";
13
- import { formatBytes, registerSpaceFileTransfer } from "./space-files.js";
14
- import { registerSpaceWallet } from "./space-wallet.js";
15
- import { registerSpaceActivity } from "./space-activity.js";
16
- import { registerSpaceDisplays } from "./space-displays.js";
17
- import { registerSpaceInvitations } from "./space-invitations.js";
18
- import { registerSpaceTurns } from "./space-turns.js";
19
- import { registerSpaceWebhooks } from "./space-webhooks.js";
20
- const cliEnv = resolveCohubEnvironment();
21
- const defaultIdleTtlSeconds = cliEnv === "prod" ? 60 * 60 : 5 * 60;
22
- const SPACE_ROLES = ["host", "builder", "guest"];
23
- const SANDBOX_SPEC_IDS = ["standard", "boost", "ultra"];
24
- const LABEL_RESOURCE_TYPES = ["session", "checkpoint", "file"];
25
- /** Table cell width for space descriptions; `--json` keeps the full value. */
26
- const SPACE_DESCRIPTION_COLUMN_WIDTH = 40;
27
- function parseInteger(value, name, options = {}) {
28
- if (!/^-?\d+$/.test(value.trim()))
29
- return error(`Invalid ${name}`, `${name} must be an integer`);
30
- const parsed = Number.parseInt(value, 10);
31
- if (!Number.isSafeInteger(parsed))
32
- return error(`Invalid ${name}`, `${name} must be a safe integer`);
33
- if (options.min !== undefined && parsed < options.min)
34
- return error(`Invalid ${name}`, `${name} must be at least ${options.min}`);
35
- if (options.max !== undefined && parsed > options.max)
36
- return error(`Invalid ${name}`, `${name} must be at most ${options.max}`);
37
- return parsed;
38
- }
39
- function parseEnvOptions(values) {
40
- if (!values?.length)
41
- return undefined;
42
- const env = {};
43
- for (const value of values) {
44
- const index = value.indexOf("=");
45
- if (index <= 0)
46
- return error("Invalid env", "Use --env KEY=value");
47
- const name = value.slice(0, index).trim();
48
- if (!name)
49
- return error("Invalid env", "Env name is required");
50
- env[name] = value.slice(index + 1);
51
- }
52
- return env;
53
- }
54
- function parseChoice(value, name, choices) {
55
- if (choices.includes(value))
56
- return value;
57
- return error(`Invalid ${name}`, `Use one of: ${choices.join(", ")}`);
58
- }
59
- function parseNullableRole(value, name) {
60
- if (value === undefined || value === "null")
61
- return null;
62
- return parseChoice(value, name, SPACE_ROLES);
63
- }
64
- const parseAutoDestroy = (opts) => {
65
- const mode = opts.autoDestroy ?? (opts.idleTtl ? "idle" : undefined);
66
- if (!mode)
67
- return undefined;
68
- if (mode === "never")
69
- return { mode: "never" };
70
- if (mode !== "idle")
71
- return error("Invalid auto destroy mode", "Use --auto-destroy idle or --auto-destroy never");
72
- const ttlSeconds = parseInteger(opts.idleTtl ?? String(defaultIdleTtlSeconds), "idle TTL", { min: 60, max: 30 * 24 * 60 * 60 });
73
- return { mode: "idle", ttlSeconds };
74
- };
75
- const parseSandboxSpec = (value) => value ? parseChoice(value, "sandbox spec", SANDBOX_SPEC_IDS) : undefined;
76
- async function resolveGuestApp(client, spaceId, value) {
77
- if (value === "none")
78
- return null;
79
- const { apps } = await client.apps.listBySpace(spaceId);
80
- const app = apps.find((item) => item.id === value || item.slug === value);
81
- if (!app)
82
- return error("App not found", `No App "${value}" in this Space`);
83
- return { appId: app.id };
84
- }
85
- export function buildSpaceCreateInput(opts) {
86
- const autoDestroy = parseAutoDestroy(opts);
87
- const spec = parseSandboxSpec(opts.spec);
88
- const image = opts.image ? parseChoice(opts.image, "sandbox image", ["default", "game"]) : undefined;
89
- const checkpointId = opts.checkpoint?.trim();
90
- if (opts.checkpoint !== undefined && !checkpointId) {
91
- return error("Invalid checkpoint", "Checkpoint ID is required");
92
- }
93
- return {
94
- name: opts.name,
95
- description: opts.description,
96
- ...(checkpointId
97
- ? { bootstrapSource: { type: "checkpoint", checkpointId } }
98
- : {}),
99
- ...((autoDestroy || spec || image)
100
- ? {
101
- config: {
102
- sandbox: {
103
- ...(autoDestroy ? { autoDestroy } : {}),
104
- ...(spec ? { spec } : {}),
105
- ...(image ? { image } : {}),
106
- },
107
- },
108
- }
109
- : {}),
110
- };
111
- }
112
- const formatAutoDestroy = (policy) => {
113
- if (!policy)
114
- return `${cliEnv === "prod" ? "12h" : "10m"} (default)`;
115
- if (policy.mode === "never")
116
- return "never";
117
- if (policy.ttlSeconds % 86400 === 0)
118
- return `${policy.ttlSeconds / 86400}d`;
119
- if (policy.ttlSeconds % 3600 === 0)
120
- return `${policy.ttlSeconds / 3600}h`;
121
- if (policy.ttlSeconds % 60 === 0)
122
- return `${policy.ttlSeconds / 60}m`;
123
- return `${policy.ttlSeconds}s`;
124
- };
125
- const slashPath = (value) => value.split(sep).join("/");
126
- const walkUploadPath = async (localPath, root) => {
127
- const info = await stat(localPath);
128
- const name = basename(localPath);
129
- const relativePath = slashPath(relative(root, localPath) || name);
130
- if (info.isDirectory()) {
131
- const children = await readdir(localPath);
132
- const nested = await Promise.all(children.map((child) => walkUploadPath(resolve(localPath, child), root)));
133
- return nested.flat();
134
- }
135
- if (!info.isFile())
136
- return [];
137
- return [{ localPath, relativePath, size: info.size }];
138
- };
139
- // Upload semantics: a file keeps its name, and a directory contributes its
140
- // contents directly under the target dir — like `aws s3 cp dir remote:path`
141
- // or `rclone copy`.
142
- export const planUploadInput = async (input) => {
143
- const localPath = resolve(input);
144
- const info = await stat(localPath);
145
- if (!info.isDirectory())
146
- return walkUploadPath(localPath, dirname(localPath));
147
- const children = await readdir(localPath);
148
- const nested = await Promise.all(children.map((child) => walkUploadPath(resolve(localPath, child), localPath)));
149
- return nested.flat();
150
- };
151
- export async function collectUploadFiles(paths) {
152
- if (paths.length === 0)
153
- return error("No files provided", "Pass one or more local files or directories.");
154
- const files = (await Promise.all(paths.map(planUploadInput))).flat();
155
- if (files.length === 0)
156
- return error("No regular files found");
157
- const seen = new Map();
158
- for (const file of files) {
159
- const source = seen.get(file.relativePath);
160
- if (source)
161
- throw new Error(`Duplicate upload path "${file.relativePath}" from ${source} and ${file.localPath}`);
162
- seen.set(file.relativePath, file.localPath);
163
- }
164
- return files;
165
- }
166
- async function uploadFiles(command, paths, opts) {
167
- const spaceId = await resolveSpace(command);
168
- const client = createClient();
169
- try {
170
- const files = await collectUploadFiles(paths);
171
- const { uploaded, uploadIds } = await uploadLocalFiles(client.space(spaceId).files, files, { targetDir: opts.dir });
172
- if (jsonRequested(opts))
173
- return outJson({ ok: true, uploaded, uploadId: uploadIds[0], uploadIds, files: files.length });
174
- ok(`Uploaded ${files.length} file${files.length === 1 ? "" : "s"}`);
175
- }
176
- catch (e) {
177
- handleHttp(e);
178
- }
179
- }
180
- async function confirmRestart(opts) {
181
- if (opts.yes)
182
- return;
183
- if (!process.stdin.isTTY || !process.stdout.isTTY)
184
- return error("Confirmation required", "Pass --yes to restart the sandbox automatically.");
185
- process.stdout.write("Changing mods restarts the sandbox and may interrupt running work. Continue? [y/N] ");
186
- const chunks = [];
187
- for await (const chunk of process.stdin) {
188
- chunks.push(chunk);
189
- break;
190
- }
191
- const answer = Buffer.concat(chunks).toString().trim().toLowerCase();
192
- if (answer !== "y" && answer !== "yes")
193
- return error("Cancelled");
194
- }
195
- async function sendPrompt(command, words, opts) {
196
- const content = await readPromptContent(words, { allowEmpty: Boolean(opts.image?.length) });
197
- const scheduleFlags = [opts.delayMs, opts.at, opts.cron].filter((value) => value !== undefined);
198
- if (scheduleFlags.length > 1)
199
- return error("Conflicting schedule", "Use only one of --delay-ms, --at, or --cron");
200
- if (opts.cron && !opts.timezone)
201
- return error("Missing timezone", "--timezone is required with --cron");
202
- if (opts.note) {
203
- const agentOnly = Object.entries({
204
- "--delay-ms": opts.delayMs, "--at": opts.at, "--cron": opts.cron, "--model": opts.model, "--provider": opts.provider,
205
- "--thinking-level": opts.thinkingLevel, "--context-window": opts.contextWindow, "--approval-mode": opts.approvalMode, "--service-tier": opts.serviceTier,
206
- "--read-only": opts.readOnly, "--steer": opts.steer, "--env": opts.env?.length,
207
- }).flatMap(([flag, value]) => value ? [flag] : []);
208
- if (agentOnly.length)
209
- return error("Conflicting options", `--note cannot be combined with ${agentOnly.join(", ")}`);
210
- }
211
- const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
212
- const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
213
- if (requestedThinkingLevel && !thinkingLevel) {
214
- return error("Invalid thinking level", `Use ${MODEL_THINKING_LEVELS.join("|")}`);
215
- }
216
- if (opts.approvalMode !== undefined && !isApprovalMode(opts.approvalMode))
217
- return error("Invalid approval mode", `Use ${APPROVAL_MODES.join("|")}`);
218
- const contextWindow = opts.contextWindow !== undefined ? parseInteger(opts.contextWindow, "context-window", { min: 1 }) : undefined;
219
- const spaceId = await resolveSpace(command, { home: true });
220
- const client = createClient();
221
- try {
222
- const schedule = opts.delayMs
223
- ? { mode: "delay", delayMs: parseInteger(opts.delayMs, "delay", { min: 1 }) }
224
- : opts.at
225
- ? { mode: "at", sendAt: opts.at }
226
- : opts.cron
227
- ? { mode: "repeat", cronExpression: opts.cron, timezone: opts.timezone }
228
- : undefined;
229
- const sessionId = opts.session;
230
- const imagePaths = opts.image ?? [];
231
- const imageBlocks = imagePaths.length
232
- ? await Promise.all(imagePaths.map(async (path) => {
233
- const asset = await uploadChatImageAsset({
234
- client,
235
- spaceId,
236
- sessionId,
237
- path,
238
- });
239
- return {
240
- type: "image",
241
- source: { type: "url", url: asset.publicUrl },
242
- _meta: {
243
- filename: basename(path),
244
- mediaType: "image/webp",
245
- size: asset.size,
246
- width: asset.width,
247
- height: asset.height,
248
- objectKey: asset.objectKey,
249
- },
250
- };
251
- }))
252
- : [];
253
- const promptContent = [
254
- ...(content ? [{ type: "text", text: content }] : []),
255
- ...imageBlocks,
256
- ];
257
- const result = await client.space(spaceId).prompt({
258
- ...(opts.note ? { mode: "note" } : {}),
259
- sessionId,
260
- title: sessionId === opts.session ? opts.title : undefined,
261
- content: promptContent,
262
- model: opts.model,
263
- provider: opts.provider,
264
- harness: opts.harness,
265
- thinkingLevel,
266
- ...(contextWindow ? { contextWindow } : {}),
267
- ...(isApprovalMode(opts.approvalMode) ? { approvalMode: opts.approvalMode } : {}),
268
- ...(opts.serviceTier ? { serviceTier: opts.serviceTier } : {}),
269
- accessMode: opts.readOnly ? "read_only" : "full_access",
270
- intent: opts.steer ? "steer" : undefined,
271
- env: parseEnvOptions(opts.env),
272
- schedule,
273
- labelRefs: opts.label?.length ? opts.label : undefined,
274
- });
275
- if (jsonRequested(opts))
276
- return outJson(result);
277
- if (result.mode === "immediate")
278
- return ok(`${opts.note ? "Note recorded" : "Prompt sent"} — sessionId: ${result.session.id}, turnId: ${result.turn.id}`);
279
- if (result.mode === "repeat")
280
- return ok(`Prompt scheduled — cronJobId: ${result.cronJobId}, nextRunAt: ${result.nextRunAt}`);
281
- return ok(`Prompt scheduled — taskRunId: ${result.taskRunId}, scheduledAt: ${result.scheduledAt}`);
282
- }
283
- catch (e) {
284
- handleHttp(e);
285
- }
286
- }
287
- async function runCompletionCommand(command, words, opts) {
288
- const spaceId = await resolveSpace(command, { home: true });
289
- const content = words.join(" ").trim();
290
- if (!content && process.stdin.isTTY) {
291
- return error("Message required", "Pass content args or pipe via stdin");
292
- }
293
- let text = content;
294
- if (!text && !process.stdin.isTTY) {
295
- const chunks = [];
296
- for await (const chunk of process.stdin)
297
- chunks.push(chunk);
298
- text = Buffer.concat(chunks).toString().trim();
299
- }
300
- if (!text)
301
- return error("Message required", "Pass content args or pipe via stdin");
302
- const temperature = opts.temperature !== undefined ? Number(opts.temperature) : undefined;
303
- if (temperature !== undefined && !Number.isFinite(temperature)) {
304
- return error("Invalid temperature", "--temperature must be a number");
305
- }
306
- const maxTokens = opts.maxTokens !== undefined ? Number(opts.maxTokens) : undefined;
307
- if (maxTokens !== undefined && (!Number.isFinite(maxTokens) || maxTokens <= 0)) {
308
- return error("Invalid max tokens", "--max-tokens must be a positive number");
309
- }
310
- const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
311
- const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
312
- if (requestedThinkingLevel && !thinkingLevel) {
313
- return error("Invalid thinking level", `Use ${MODEL_THINKING_LEVELS.join("|")}`);
314
- }
315
- const client = createClient();
316
- const input = {
317
- provider: opts.provider,
318
- model: opts.model,
319
- systemPromptPath: opts.systemPrompt,
320
- messages: [{ role: "user", content: [{ type: "text", text }] }],
321
- temperature,
322
- maxTokens,
323
- thinkingLevel,
324
- };
325
- try {
326
- if (opts.stream) {
327
- const iterator = client.space(spaceId).streamCompletion(input);
328
- let step = await iterator.next();
329
- let finalResult = null;
330
- while (!step.done) {
331
- const event = step.value;
332
- if (event.type === "delta") {
333
- if (!jsonRequested(opts))
334
- process.stdout.write(event.text);
335
- }
336
- else if (event.type === "thinking_delta" && !jsonRequested(opts)) {
337
- process.stderr.write(event.text);
338
- }
339
- step = await iterator.next();
340
- }
341
- finalResult = step.value;
342
- if (jsonRequested(opts))
343
- return outJson(finalResult);
344
- process.stdout.write("\n");
345
- if (finalResult.usage?.totalTokens != null) {
346
- process.stderr.write(` tokens: ${finalResult.usage.totalTokens}\n`);
347
- }
348
- return;
349
- }
350
- const result = await client.space(spaceId).completion(input);
351
- if (jsonRequested(opts))
352
- return outJson(result);
353
- const textOut = result.message.content
354
- .filter((block) => block.type === "text")
355
- .map((block) => block.text)
356
- .join("");
357
- console.log(textOut);
358
- if (result.usage?.totalTokens != null) {
359
- process.stderr.write(`\n tokens: ${result.usage.totalTokens}\n`);
360
- }
361
- }
362
- catch (e) {
363
- handleHttp(e);
364
- }
365
- }
366
- export function registerPrompt(program) {
367
- program
368
- .command("prompt [content...]")
369
- .description("Send or schedule a prompt in a space")
370
- .option("--session <id>", "Target session ID")
371
- .option("--title <title>", "Title for a newly created session or schedule")
372
- .option("-m, --model <model>", "Model name")
373
- .option("-p, --provider <provider>", "Provider name")
374
- .option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
375
- .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
376
- .option("--context-window <tokens>", "Context window for this session from this prompt on; capped at the platform value")
377
- .option("--approval-mode <mode>", `Local Harness approval mode: ${APPROVAL_MODES.join("|")}`)
378
- .option("--service-tier <tier>", "Local Harness service tier, e.g. priority for Codex Fast")
379
- .option("--read-only", "Use read-only tools")
380
- .option("--steer", "Interrupt the current turn and run immediately")
381
- .option("--delay-ms <ms>", "Delay sending by milliseconds")
382
- .option("--at <iso>", "Send once at an ISO 8601 time with timezone")
383
- .option("--cron <expression>", "Repeat using a 5-field cron expression")
384
- .option("--timezone <tz>", "IANA timezone for --cron, e.g. Asia/Shanghai")
385
- .option("--label <ref>", "Attach a label, e.g. Bug or Area/Frontend", collectOption, [])
386
- .option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
387
- .option("--image <path>", "Attach an image", collectOption, [])
388
- .option("--note", "Record the message without an AI reply")
389
- .option("--json", "Output as JSON")
390
- .action((words, opts) => sendPrompt(program, words, opts));
391
- program
392
- .command("completion [content...]")
393
- .description("Raw LLM completion with full message control")
394
- .option("-m, --model <model>", "Model name")
395
- .option("-p, --provider <provider>", "Provider name")
396
- .option("--system-prompt <path>", "Space-relative system prompt markdown path")
397
- .option("--stream", "Stream tokens via SSE")
398
- .option("--temperature <n>", "Sampling temperature")
399
- .option("--max-tokens <n>", "Maximum output tokens")
400
- .option("--thinking-level <level>", "Thinking level: off|minimal|low|medium|high|xhigh")
401
- .option("--json", "Output as JSON")
402
- .action((words, opts) => runCompletionCommand(program, words, opts));
403
- registerDecisionCommand(program);
404
- }
405
- export function registerSpaceCreate(spacesCmd, dependencies = {}) {
406
- const getClient = dependencies.createClient ?? createClient;
407
- return spacesCmd
408
- .command("create")
409
- .description("Create a new space")
410
- .requiredOption("-n, --name <name>", "Space name")
411
- .option("-d, --description <desc>", "Space description")
412
- .option("--checkpoint <id>", "Create from a checkpoint")
413
- .option("--image <image>", "Sandbox image: default or game")
414
- .option("--auto-destroy <mode>", "Sandbox auto destroy mode: idle or never")
415
- .option("--idle-ttl <seconds>", "Idle auto destroy TTL in seconds, max 2592000 (30d)")
416
- .option("--spec <spec>", "Sandbox spec: standard, boost, or ultra")
417
- .option("--json", "Output as JSON")
418
- .action(async (opts) => {
419
- const client = getClient();
420
- try {
421
- const result = await client.spaces.create(buildSpaceCreateInput(opts));
422
- if (jsonRequested(opts))
423
- return outJson(result);
424
- ok(`Space created: ${result.space.id}`);
425
- table([{ ...result.space, taskRunId: result.taskRunId }], [
426
- { key: "id", label: "ID" },
427
- { key: "name", label: "Name" },
428
- { key: "taskRunId", label: "Task" },
429
- ]);
430
- }
431
- catch (e) {
432
- handleHttp(e);
433
- }
434
- });
435
- }
436
- function registerUserLabels(program) {
437
- const labels = program.command("labels").description("Manage personal labels");
438
- labels.command("ls").description("List personal labels").option("--json", "Output as JSON").action(async (opts) => {
439
- const client = createClient();
440
- try {
441
- const result = await client.user.labels.list();
442
- const flatten = (items, parent = "") => items.flatMap((item) => [
443
- { id: item.id, ref: parent ? `${parent}/${item.name}` : item.name, source: item.source, rank: item.rank },
444
- ...flatten(item.children ?? [], parent ? `${parent}/${item.name}` : item.name),
445
- ]);
446
- const rows = flatten(result.labels);
447
- if (jsonRequested(opts))
448
- return outJson(rows);
449
- table(rows, [{ key: "ref", label: "Label" }, { key: "source", label: "Source" }, { key: "rank", label: "Rank" }]);
450
- }
451
- catch (e) {
452
- handleHttp(e);
453
- }
454
- });
455
- labels.command("create <ref>").description("Create a personal label").action(async (ref) => {
456
- try {
457
- await createClient().user.labels.create(ref);
458
- ok(`Created label: ${ref}`);
459
- }
460
- catch (e) {
461
- handleHttp(e);
462
- }
463
- });
464
- labels.command("rename <ref> <name>").description("Rename a personal label").action(async (ref, name) => {
465
- try {
466
- await createClient().user.labels.update(ref, { name });
467
- ok(`Renamed label: ${ref}`);
468
- }
469
- catch (e) {
470
- handleHttp(e);
471
- }
472
- });
473
- labels.command("rm <ref>").description("Delete a personal label").action(async (ref) => {
474
- try {
475
- await createClient().user.labels.delete(ref);
476
- ok(`Deleted label: ${ref}`);
477
- }
478
- catch (e) {
479
- handleHttp(e);
480
- }
481
- });
482
- labels.command("reorder <refs...>").description("Set personal label order").action(async (refs) => {
483
- try {
484
- await createClient().user.labels.reorder(refs);
485
- ok(`Reordered ${refs.length} label(s)`);
486
- }
487
- catch (e) {
488
- handleHttp(e);
489
- }
490
- });
491
- }
492
- export function registerSpaceSetup(spacesCmd, deps = {}) {
493
- spacesCmd
494
- .command("setup [id]")
495
- .description("Show cloud sandbox startup scripts, results, and log paths")
496
- .option("--json", "Output as JSON")
497
- .action(async (id, opts) => {
498
- try {
499
- const spaceId = id ?? await resolveSpace(spacesCmd);
500
- const { sandbox } = await (deps.createClient ?? createClient)().space(spaceId).sandbox.get();
501
- const setup = sandbox?.meta?.setup ?? null;
502
- if (jsonRequested(opts))
503
- return outJson({ provider: sandbox?.provider ?? null, setup });
504
- if (sandbox?.provider === "local")
505
- return ok("Setup is disabled for local spaces.");
506
- if (!setup)
507
- return ok("No setup report is available.");
508
- table([
509
- { key: "Status", value: setup.status ?? (setup.error || setup.exitCode ? "failed" : "succeeded") },
510
- { key: "Duration", value: setup.duration || "—" },
511
- ...(setup.error ? [{ key: "Error", value: setup.error }] : []),
512
- ], [{ key: "key", label: "Key" }, { key: "value", label: "Value" }]);
513
- if (setup.steps?.length)
514
- table(setup.steps.map((step) => ({
515
- script: step.path, status: step.status, duration: step.duration || "—", logs: step.logDir,
516
- })), [
517
- { key: "script", label: "Script" }, { key: "status", label: "Status" },
518
- { key: "duration", label: "Duration" }, { key: "logs", label: "Logs" },
519
- ]);
520
- }
521
- catch (e) {
522
- handleHttp(e);
523
- }
524
- });
525
- }
526
- export function registerSpaces(program) {
527
- const spacesCmd = program.command("spaces").description("Space management");
528
- registerSpaceInvitations(spacesCmd);
529
- registerUserLabels(program);
530
- // ── spaces ls ──
531
- spacesCmd
532
- .command("ls")
533
- .alias("list")
534
- .description("List all spaces")
535
- .option("--mine", "Only spaces you own")
536
- .option("--pinned", "Only pinned spaces")
537
- .option("--archived", "Only archived spaces")
538
- .option("--json", "Output as JSON")
539
- .action(async (opts) => {
540
- const client = createClient();
541
- try {
542
- const items = [];
543
- let cursor = null;
544
- do {
545
- const page = await client.spaces.list({
546
- limit: 100,
547
- cursor,
548
- filter: opts.archived ? "archived" : opts.pinned ? "pinned" : opts.mine ? "mine" : "all",
549
- });
550
- items.push(...page.items);
551
- cursor = page.pageInfo.nextCursor;
552
- } while (cursor);
553
- const filtered = items.filter((item) => {
554
- if (opts.pinned && !item.isPinned)
555
- return false;
556
- if (opts.archived && !item.isArchived)
557
- return false;
558
- return true;
559
- });
560
- if (jsonRequested(opts))
561
- return outJson(filtered);
562
- table(filtered, [
563
- { key: "id", label: "ID" },
564
- { key: "name", label: "Name" },
565
- { key: "description", label: "Description", format: (value) => truncateText(value, SPACE_DESCRIPTION_COLUMN_WIDTH) },
566
- { key: "isPinned", label: "Pinned" },
567
- { key: "createdAt", label: "Created" },
568
- ]);
569
- }
570
- catch (e) {
571
- handleHttp(e);
572
- }
573
- });
574
- for (const archive of [true, false]) {
575
- spacesCmd
576
- .command(archive ? "archive <ids...>" : "unarchive <ids...>")
577
- .description(archive ? "Archive spaces in your personal view" : "Restore archived spaces")
578
- .option("--json", "Output as JSON")
579
- .action(async (ids, opts) => {
580
- const client = createClient();
581
- try {
582
- const chunks = Array.from({ length: Math.ceil(ids.length / 200) }, (_, index) => ids.slice(index * 200, (index + 1) * 200));
583
- for (const chunk of chunks)
584
- await client.user.labels.patchResources(chunk, archive
585
- ? { addLabelRefs: ["Archived"], removeLabelRefs: ["Pinned"] }
586
- : { removeLabelRefs: ["Archived"] });
587
- if (jsonRequested(opts))
588
- return outJson({ ids, archived: archive });
589
- ok(`${archive ? "Archived" : "Unarchived"} ${ids.length} space(s)`);
590
- }
591
- catch (e) {
592
- handleHttp(e);
593
- }
594
- });
595
- }
596
- // ── spaces get ──
597
- spacesCmd
598
- .command("get [id]")
599
- .description("Show space details")
600
- .option("--json", "Output as JSON")
601
- .action(async (id, opts) => {
602
- const spaceId = id?.trim() || await resolveSpace(spacesCmd);
603
- const client = createClient();
604
- try {
605
- const space = await client.spaces.get(spaceId);
606
- if (jsonRequested(opts))
607
- return outJson(space);
608
- const usage = space.workspaceUsage;
609
- const storage = usage ? `${usage.bytes === null ? "-" : formatBytes(usage.bytes)} (${usage.status})` : undefined;
610
- const likeSticker = space.publicProfile?.likeSticker?.url;
611
- table([{ ...space, storage, likeSticker }], [
612
- { key: "id", label: "ID" },
613
- { key: "name", label: "Name" },
614
- { key: "slug", label: "Slug" },
615
- { key: "description", label: "Description", format: (value) => truncateText(value, SPACE_DESCRIPTION_COLUMN_WIDTH) },
616
- { key: "status", label: "Status" },
617
- { key: "createdAt", label: "Created" },
618
- ...(storage ? [{ key: "storage", label: "Storage" }] : []),
619
- ...(likeSticker ? [{ key: "likeSticker", label: "Like sticker" }] : []),
620
- ]);
621
- }
622
- catch (e) {
623
- handleHttp(e);
624
- }
625
- });
626
- // ── spaces create ──
627
- registerSpaceCreate(spacesCmd);
628
- // ── spaces update ──
629
- spacesCmd
630
- .command("update <id>")
631
- .description("Update a space")
632
- .option("--name <name>", "Space name")
633
- .option("--slug <slug>", "Public space slug")
634
- .option("--json", "Output as JSON")
635
- .action(async (id, opts) => {
636
- const input = {
637
- name: opts.name,
638
- slug: opts.slug,
639
- };
640
- if (input.name === undefined && input.slug === undefined) {
641
- return error("Nothing to update", "Pass --name or --slug.");
642
- }
643
- const client = createClient();
644
- try {
645
- const result = await client.space(id).update(input);
646
- if (jsonRequested(opts))
647
- return outJson(result);
648
- ok("Space updated");
649
- table([result.space], [
650
- { key: "id", label: "ID" },
651
- { key: "name", label: "Name" },
652
- { key: "slug", label: "Slug" },
653
- ]);
654
- }
655
- catch (e) {
656
- handleHttp(e);
657
- }
658
- });
659
- // ── spaces rename ──
660
- spacesCmd
661
- .command("rename <id> <name>")
662
- .description("Rename a space")
663
- .action(async (id, name) => {
664
- const client = createClient();
665
- try {
666
- await client.space(id).rename(name);
667
- ok(`Space renamed to "${name}"`);
668
- }
669
- catch (e) {
670
- handleHttp(e);
671
- }
672
- });
673
- // ── spaces avatar ──
674
- spacesCmd
675
- .command("avatar <path>")
676
- .description("Upload the space avatar")
677
- .option("--json", "Output as JSON")
678
- .action(async (path, opts) => {
679
- const spaceId = await resolveSpace(spacesCmd);
680
- const client = createClient();
681
- try {
682
- const asset = await uploadAvatarAsset({ client, purpose: "space_avatar", spaceId, path });
683
- const result = await client.space(spaceId).profile({ avatarUrl: asset.publicUrl });
684
- if (jsonRequested(opts))
685
- return outJson({ ...result, asset });
686
- ok("Space avatar updated");
687
- }
688
- catch (e) {
689
- handleHttp(e);
690
- }
691
- });
692
- // ── spaces like-sticker ──
693
- spacesCmd
694
- .command("like-sticker [path]")
695
- .description("Set the image that replaces the heart on the space's published Apps")
696
- .option("--clear", "Restore the default heart")
697
- .option("--json", "Output as JSON")
698
- .action(async (path, opts) => {
699
- if (Boolean(path) === Boolean(opts.clear))
700
- return error("Pass an image path or --clear");
701
- const spaceId = await resolveSpace(spacesCmd);
702
- const client = createClient();
703
- try {
704
- const asset = path ? await uploadLikeStickerAsset({ client, spaceId, path }) : null;
705
- const result = await client.space(spaceId).profile({ likeSticker: asset ? { url: asset.publicUrl } : null });
706
- if (jsonRequested(opts))
707
- return outJson({ ...result, ...(asset ? { asset } : {}) });
708
- ok(asset ? "Like sticker updated" : "Like sticker cleared");
709
- }
710
- catch (e) {
711
- handleHttp(e);
712
- }
713
- });
714
- registerSpaceSetup(spacesCmd);
715
- // ── spaces config ──
716
- spacesCmd
717
- .command("config <id>")
718
- .description("Show or update space configuration")
719
- .option("--auto-destroy <mode>", "Sandbox auto destroy mode: idle or never")
720
- .option("--idle-ttl <seconds>", "Idle auto destroy TTL in seconds, max 2592000 (30d)")
721
- .option("--spec <spec>", "Sandbox spec: standard, boost, ultra, or auto")
722
- .option("--image <image>", "Sandbox image: default, game, or auto")
723
- .option("--guest-app <app>", "Published public App shown to visitors without access: id, slug, or none")
724
- .option("--json", "Output as JSON")
725
- .action(async (id, opts) => {
726
- const client = createClient();
727
- try {
728
- const autoDestroy = parseAutoDestroy(opts);
729
- const spec = opts.spec === "auto" ? null : parseSandboxSpec(opts.spec);
730
- const image = opts.image === "auto" ? null : opts.image ? parseChoice(opts.image, "sandbox image", ["default", "game"]) : undefined;
731
- const guest = opts.guestApp === undefined ? undefined : await resolveGuestApp(client, id, opts.guestApp);
732
- const sandboxChanged = Boolean(autoDestroy) || spec !== undefined || image !== undefined;
733
- if (sandboxChanged || guest !== undefined) {
734
- const result = await client.space(id).updateConfig({
735
- ...(sandboxChanged ? { sandbox: { ...(autoDestroy ? { autoDestroy } : {}), ...(spec !== undefined ? { spec } : {}), ...(image !== undefined ? { image } : {}) } } : {}),
736
- ...(guest !== undefined ? { guest } : {}),
737
- });
738
- if (jsonRequested(opts))
739
- return outJson(result);
740
- ok(`Space config updated${autoDestroy ? ` — sandbox auto destroy: ${formatAutoDestroy(autoDestroy)}` : ""}${spec ? ` — sandbox spec: ${spec}` : ""}${result.sandbox?.pendingRestart ? " — restart the sandbox to apply" : ""}`);
741
- return;
742
- }
743
- const result = await client.space(id).getConfig();
744
- if (jsonRequested(opts))
745
- return outJson(result);
746
- table([
747
- { key: "sandbox.autoDestroy", value: formatAutoDestroy(result.config.sandbox.autoDestroy) },
748
- { key: "sandbox.image", value: result.config.sandbox.image ?? "default" },
749
- { key: "sandbox.imageSource", value: result.config.sandbox.preferences?.origins.image ?? "platform" },
750
- { key: "sandbox.specSource", value: result.config.sandbox.preferences?.origins.spec ?? "platform" },
751
- { key: "sandbox.warnings", value: result.config.sandbox.preferences?.warnings.join(", ") || "—" },
752
- { key: "sandbox.pendingRestart", value: String(result.config.sandbox.preferences?.pendingRestart ?? false) },
753
- { key: "sandbox.spec", value: result.config.sandbox.spec ?? "standard" },
754
- { key: "sandbox.appliedSpec", value: result.config.sandbox.appliedSpec ?? "—" },
755
- { key: "sandbox.allowedSpec", value: result.config.sandbox.allowedSpec ?? "standard" },
756
- { key: "guest.appId", value: result.config.guest?.appId ?? "default" },
757
- ], [
758
- { key: "key", label: "Key" },
759
- { key: "value", label: "Value" },
760
- ]);
761
- }
762
- catch (e) {
763
- handleHttp(e);
764
- }
765
- });
766
- // ── spaces prompt ──
767
- spacesCmd
768
- .command("prompt [content...]", { hidden: true })
769
- .alias("send")
770
- .description("Send or schedule a prompt in the target space")
771
- .option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
772
- .option("--session <id>", "Target session ID")
773
- .option("--title <title>", "Title for a newly created session or schedule")
774
- .option("-m, --model <model>", "Model name")
775
- .option("-p, --provider <provider>", "Provider name")
776
- .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
777
- .option("--context-window <tokens>", "Context window for this session from this prompt on; capped at the platform value")
778
- .option("--approval-mode <mode>", `Local Harness approval mode: ${APPROVAL_MODES.join("|")}`)
779
- .option("--service-tier <tier>", "Local Harness service tier, e.g. priority for Codex Fast")
780
- .option("--read-only", "Use read-only tools")
781
- .option("--steer", "Interrupt the current turn and run immediately")
782
- .option("--delay-ms <ms>", "Delay sending by milliseconds")
783
- .option("--at <iso>", "Send once at an ISO 8601 time with timezone")
784
- .option("--cron <expression>", "Repeat using a 5-field cron expression")
785
- .option("--timezone <tz>", "IANA timezone for --cron, e.g. Asia/Shanghai")
786
- .option("--label <ref>", "Attach a label, e.g. Bug or Area/Frontend", collectOption, [])
787
- .option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
788
- .option("--image <path>", "Attach an image", collectOption, [])
789
- .option("--note", "Record the message without an AI reply")
790
- .option("--json", "Output as JSON")
791
- .action((words, opts) => sendPrompt(spacesCmd, words, opts));
792
- // ── spaces completion ──
793
- spacesCmd
794
- .command("completion [content...]")
795
- .description("Raw LLM completion with full message control")
796
- .option("-m, --model <model>", "Model name")
797
- .option("-p, --provider <provider>", "Provider name")
798
- .option("--system-prompt <path>", "Space-relative system prompt markdown path")
799
- .option("--stream", "Stream tokens via SSE")
800
- .option("--temperature <n>", "Sampling temperature")
801
- .option("--max-tokens <n>", "Maximum output tokens")
802
- .option("--thinking-level <level>", "Thinking level: off|minimal|low|medium|high|xhigh")
803
- .option("--json", "Output as JSON")
804
- .action((words, opts) => runCompletionCommand(spacesCmd, words, opts));
805
- registerDecisionCommand(spacesCmd);
806
- // ── spaces files ──
807
- registerFiles(spacesCmd);
808
- registerSpaceDisplays(spacesCmd);
809
- // ── spaces sessions ──
810
- registerSessions(spacesCmd);
811
- // ── spaces turns ──
812
- registerSpaceTurns(spacesCmd);
813
- // ── spaces members ──
814
- registerMembers(spacesCmd);
815
- // ── spaces access ──
816
- registerAccess(spacesCmd);
817
- // ── spaces checkpoints ──
818
- registerCheckpoints(spacesCmd);
819
- // ── spaces mods ──
820
- registerMods(spacesCmd);
821
- // ── spaces labels ──
822
- registerLabels(spacesCmd);
823
- // ── spaces webhooks ──
824
- registerSpaceWebhooks(spacesCmd);
825
- // ── spaces pin / unpin (user-scope label convenience) ──
826
- spacesCmd
827
- .command("pin <id>")
828
- .description("Pin a space (add the Pinned user label)")
829
- .action(async (id) => {
830
- const client = createClient();
831
- try {
832
- await client.user.labels.patchResourceLabels("space", id.trim(), { addLabelRefs: ["Pinned"] });
833
- ok("Space pinned");
834
- }
835
- catch (e) {
836
- handleHttp(e);
837
- }
838
- });
839
- spacesCmd
840
- .command("unpin <id>")
841
- .description("Unpin a space (remove the Pinned user label)")
842
- .action(async (id) => {
843
- const client = createClient();
844
- try {
845
- await client.user.labels.patchResourceLabels("space", id.trim(), { removeLabelRefs: ["Pinned"] });
846
- ok("Space unpinned");
847
- }
848
- catch (e) {
849
- handleHttp(e);
850
- }
851
- });
852
- // ── spaces commerce ──
853
- registerSpaceCommerce(spacesCmd);
854
- // ── spaces activity ──
855
- registerSpaceWallet(spacesCmd);
856
- registerSpaceActivity(spacesCmd);
857
- // ── spaces usage ──
858
- spacesCmd
859
- .command("usage [days]")
860
- .description("Space usage statistics (default: 30 days)")
861
- .option("--json", "Output as JSON")
862
- .action(async (days, opts) => {
863
- const spaceId = await resolveSpace(spacesCmd);
864
- const client = createClient();
865
- try {
866
- const usage = await client.space(spaceId).usage.get(parseInteger(days ?? "30", "days", { min: 1 }));
867
- if (jsonRequested(opts))
868
- return outJson(usage);
869
- console.log("\n Summary:");
870
- table([usage.totals], [
871
- { key: "totalTokens", label: "Tokens" },
872
- ...(usage.totals.costTotal ? [{ key: "costTotal", label: "Cost ($)" }] : []),
873
- { key: "requestCount", label: "Requests" },
874
- { key: "successCount", label: "Success" },
875
- { key: "errorCount", label: "Errors" },
876
- ]);
877
- }
878
- catch (e) {
879
- handleHttp(e);
880
- }
881
- });
882
- }
883
- function flattenLabels(items, prefix = "") {
884
- return items.flatMap((label) => {
885
- const path = prefix ? `${prefix}/${label.name}` : label.name;
886
- return [{ ...label, path }, ...flattenLabels(label.children ?? [], path)];
887
- });
888
- }
889
- function parseLabelResourceType(value) {
890
- return parseChoice(value, "resource type", LABEL_RESOURCE_TYPES);
891
- }
892
- function parseLabelRefs(value) {
893
- if (!value?.trim())
894
- return [];
895
- return value.split(",").map((item) => item.trim()).filter(Boolean);
896
- }
897
- function registerLabels(spacesCmd) {
898
- const labelsCmd = spacesCmd
899
- .command("labels")
900
- .description("Manage labels")
901
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
902
- labelsCmd
903
- .command("ls")
904
- .alias("list")
905
- .description("List labels")
906
- .option("--json", "Output as JSON")
907
- .action(async (opts) => {
908
- const spaceId = await resolveSpace(spacesCmd);
909
- const client = createClient();
910
- try {
911
- const result = await client.space(spaceId).labels.list();
912
- if (jsonRequested(opts))
913
- return outJson(result);
914
- table(flattenLabels(result.labels), [
915
- { key: "path", label: "Label" },
916
- { key: "rank", label: "Rank" },
917
- ]);
918
- }
919
- catch (e) {
920
- handleHttp(e);
921
- }
922
- });
923
- labelsCmd
924
- .command("create <labelRef>")
925
- .description("Create a label")
926
- .option("--json", "Output as JSON")
927
- .action(async (labelRef, opts) => {
928
- const spaceId = await resolveSpace(spacesCmd);
929
- const client = createClient();
930
- try {
931
- const result = await client.space(spaceId).labels.create(labelRef);
932
- if (jsonRequested(opts))
933
- return outJson(result);
934
- ok("Label created");
935
- }
936
- catch (e) {
937
- handleHttp(e);
938
- }
939
- });
940
- labelsCmd
941
- .command("update <labelRef>")
942
- .description("Update a label")
943
- .option("--name <name>", "Label name")
944
- .option("--parent <ref>", "Parent label; use null for root")
945
- .option("--rank <n>", "Sort rank")
946
- .option("--json", "Output as JSON")
947
- .action(async (labelRef, opts) => {
948
- const spaceId = await resolveSpace(spacesCmd);
949
- const client = createClient();
950
- try {
951
- const result = await client.space(spaceId).labels.update(labelRef, {
952
- name: opts.name,
953
- parentRef: opts.parent === undefined ? undefined : opts.parent === "null" ? null : opts.parent,
954
- rank: opts.rank === undefined ? undefined : parseInteger(opts.rank, "rank", { min: -1_000_000, max: 1_000_000 }),
955
- });
956
- if (jsonRequested(opts))
957
- return outJson(result);
958
- ok("Label updated");
959
- }
960
- catch (e) {
961
- handleHttp(e);
962
- }
963
- });
964
- labelsCmd
965
- .command("rm <labelRef>")
966
- .alias("delete")
967
- .description("Delete a label")
968
- .action(async (labelRef) => {
969
- const spaceId = await resolveSpace(spacesCmd);
970
- const client = createClient();
971
- try {
972
- await client.space(spaceId).labels.delete(labelRef);
973
- ok("Label deleted");
974
- }
975
- catch (e) {
976
- handleHttp(e);
977
- }
978
- });
979
- labelsCmd
980
- .command("reorder <labelRefs...>")
981
- .description("Reorder labels")
982
- .option("--json", "Output as JSON")
983
- .action(async (labelRefs, opts) => {
984
- const spaceId = await resolveSpace(spacesCmd);
985
- const client = createClient();
986
- try {
987
- const result = await client.space(spaceId).labels.reorder(labelRefs);
988
- if (jsonRequested(opts))
989
- return outJson(result);
990
- ok("Labels reordered");
991
- }
992
- catch (e) {
993
- handleHttp(e);
994
- }
995
- });
996
- labelsCmd
997
- .command("items <labelRef>")
998
- .description("List label items")
999
- .option("--limit <n>", "Page size")
1000
- .option("--cursor <cursor>", "Page cursor")
1001
- .option("--json", "Output as JSON")
1002
- .action(async (labelRef, opts) => {
1003
- const spaceId = await resolveSpace(spacesCmd);
1004
- const client = createClient();
1005
- try {
1006
- const result = await client.space(spaceId).labels.listItems(labelRef, {
1007
- limit: opts.limit ? parseInteger(opts.limit, "limit", { min: 1 }) : undefined,
1008
- cursor: opts.cursor,
1009
- });
1010
- if (jsonRequested(opts))
1011
- return outJson(result);
1012
- table(result.items, [
1013
- { key: "id", label: "ID" },
1014
- { key: "resourceType", label: "Type" },
1015
- { key: "resourceRef", label: "Resource" },
1016
- { key: "rank", label: "Rank" },
1017
- ]);
1018
- }
1019
- catch (e) {
1020
- handleHttp(e);
1021
- }
1022
- });
1023
- labelsCmd
1024
- .command("attach <labelRef> <resourceType> <resourceRef>")
1025
- .description("Attach a label")
1026
- .option("--json", "Output as JSON")
1027
- .action(async (labelRef, resourceType, resourceRef, opts) => {
1028
- const spaceId = await resolveSpace(spacesCmd);
1029
- const client = createClient();
1030
- try {
1031
- const result = await client.space(spaceId).labels.attach(labelRef, { resourceType: parseLabelResourceType(resourceType), resourceRef });
1032
- if (jsonRequested(opts))
1033
- return outJson(result);
1034
- ok("Label attached");
1035
- }
1036
- catch (e) {
1037
- handleHttp(e);
1038
- }
1039
- });
1040
- labelsCmd
1041
- .command("detach <labelRef> <resourceType> <resourceRef>")
1042
- .description("Detach a label")
1043
- .action(async (labelRef, resourceType, resourceRef) => {
1044
- const spaceId = await resolveSpace(spacesCmd);
1045
- const client = createClient();
1046
- try {
1047
- await client.space(spaceId).labels.detach(labelRef, { resourceType: parseLabelResourceType(resourceType), resourceRef });
1048
- ok("Label detached");
1049
- }
1050
- catch (e) {
1051
- handleHttp(e);
1052
- }
1053
- });
1054
- labelsCmd
1055
- .command("patch <resourceType> <resourceRef>")
1056
- .description("Patch resource labels")
1057
- .option("--add <refs>", "Comma-separated label refs to add")
1058
- .option("--remove <refs>", "Comma-separated label refs to remove")
1059
- .option("--json", "Output as JSON")
1060
- .action(async (resourceType, resourceRef, opts) => {
1061
- const spaceId = await resolveSpace(spacesCmd);
1062
- const client = createClient();
1063
- try {
1064
- const result = await client.space(spaceId).labels.patchResourceLabels(parseLabelResourceType(resourceType), resourceRef, {
1065
- addLabelRefs: parseLabelRefs(opts.add),
1066
- removeLabelRefs: parseLabelRefs(opts.remove),
1067
- });
1068
- if (jsonRequested(opts))
1069
- return outJson(result);
1070
- ok("Resource labels patched");
1071
- }
1072
- catch (e) {
1073
- handleHttp(e);
1074
- }
1075
- });
1076
- labelsCmd
1077
- .command("set <resourceType> <resourceRef> [labelRefs...]")
1078
- .description("Set resource labels")
1079
- .option("--labels <refs>", "Comma-separated label refs")
1080
- .option("--json", "Output as JSON")
1081
- .action(async (resourceType, resourceRef, labelRefs, opts) => {
1082
- const spaceId = await resolveSpace(spacesCmd);
1083
- const client = createClient();
1084
- try {
1085
- const refs = [...parseLabelRefs(opts.labels), ...labelRefs];
1086
- const result = await client.space(spaceId).labels.setResourceLabels(parseLabelResourceType(resourceType), resourceRef, refs);
1087
- if (jsonRequested(opts))
1088
- return outJson(result);
1089
- ok("Resource labels updated");
1090
- }
1091
- catch (e) {
1092
- handleHttp(e);
1093
- }
1094
- });
1095
- }
1096
- function registerMods(spacesCmd) {
1097
- const modsCmd = spacesCmd
1098
- .command("mods")
1099
- .description("Manage space mods")
1100
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1101
- modsCmd
1102
- .command("ls")
1103
- .alias("list")
1104
- .description("List mods")
1105
- .option("--json", "Output as JSON")
1106
- .action(async (opts) => {
1107
- const spaceId = await resolveSpace(spacesCmd);
1108
- const client = createClient();
1109
- try {
1110
- const result = await client.space(spaceId).mods.list();
1111
- if (jsonRequested(opts))
1112
- return outJson(result.items);
1113
- table(result.items, [
1114
- { key: "id", label: "ID" },
1115
- { key: "modSpaceName", label: "Name" },
1116
- { key: "mountPath", label: "Mount" },
1117
- { key: "enabled", label: "On" },
1118
- ]);
1119
- }
1120
- catch (e) {
1121
- handleHttp(e);
1122
- }
1123
- });
1124
- modsCmd
1125
- .command("add <modSpaceId>")
1126
- .description("Add a mod")
1127
- .option("--name <name>", "Display name")
1128
- .option("--slug <slug>", "Mount slug")
1129
- .option("-y, --yes", "Confirm sandbox restart")
1130
- .option("--json", "Output as JSON")
1131
- .action(async (modSpaceId, opts) => {
1132
- await confirmRestart(opts);
1133
- const spaceId = await resolveSpace(spacesCmd);
1134
- const client = createClient();
1135
- try {
1136
- const result = await client.space(spaceId).mods.create({ modSpaceId, name: opts.name, mountSlug: opts.slug });
1137
- if (jsonRequested(opts))
1138
- return outJson(result);
1139
- ok(`Mod added — ${result.item.mountPath}; sandbox restarting`);
1140
- }
1141
- catch (e) {
1142
- handleHttp(e);
1143
- }
1144
- });
1145
- modsCmd
1146
- .command("enable <modId>")
1147
- .description("Enable a mod")
1148
- .option("-y, --yes", "Confirm sandbox restart")
1149
- .option("--json", "Output as JSON")
1150
- .action(async (modId, opts) => {
1151
- await confirmRestart(opts);
1152
- const spaceId = await resolveSpace(spacesCmd);
1153
- const client = createClient();
1154
- try {
1155
- const result = await client.space(spaceId).mods.update(modId, { enabled: true });
1156
- if (jsonRequested(opts))
1157
- return outJson(result);
1158
- ok("Mod enabled; sandbox restarting");
1159
- }
1160
- catch (e) {
1161
- handleHttp(e);
1162
- }
1163
- });
1164
- modsCmd
1165
- .command("disable <modId>")
1166
- .description("Disable a mod")
1167
- .option("-y, --yes", "Confirm sandbox restart")
1168
- .option("--json", "Output as JSON")
1169
- .action(async (modId, opts) => {
1170
- await confirmRestart(opts);
1171
- const spaceId = await resolveSpace(spacesCmd);
1172
- const client = createClient();
1173
- try {
1174
- const result = await client.space(spaceId).mods.update(modId, { enabled: false });
1175
- if (jsonRequested(opts))
1176
- return outJson(result);
1177
- ok("Mod disabled; sandbox restarting");
1178
- }
1179
- catch (e) {
1180
- handleHttp(e);
1181
- }
1182
- });
1183
- modsCmd
1184
- .command("rm <modId>")
1185
- .alias("remove")
1186
- .description("Remove a mod")
1187
- .option("-y, --yes", "Confirm sandbox restart")
1188
- .option("--json", "Output as JSON")
1189
- .action(async (modId, opts) => {
1190
- await confirmRestart(opts);
1191
- const spaceId = await resolveSpace(spacesCmd);
1192
- const client = createClient();
1193
- try {
1194
- const result = await client.space(spaceId).mods.remove(modId);
1195
- if (jsonRequested(opts))
1196
- return outJson(result);
1197
- ok("Mod removed; sandbox restarting");
1198
- }
1199
- catch (e) {
1200
- handleHttp(e);
1201
- }
1202
- });
1203
- }
1204
- function formatDiffBytes(value) {
1205
- if (value === null || value === undefined)
1206
- return "—";
1207
- if (value < 1024)
1208
- return `${value} B`;
1209
- if (value < 1024 * 1024)
1210
- return `${(value / 1024).toFixed(value >= 10 * 1024 ? 0 : 1)} KB`;
1211
- return `${(value / (1024 * 1024)).toFixed(1)} MB`;
1212
- }
1213
- function printDiffFile(file) {
1214
- if (file.kind !== "text") {
1215
- const size = file.oldSize !== undefined || file.newSize !== undefined
1216
- ? ` (${formatDiffBytes(file.oldSize)} → ${formatDiffBytes(file.newSize)})`
1217
- : "";
1218
- console.log(`${file.status ?? "?"} ${file.path} (${file.kind})${size}`);
1219
- return;
1220
- }
1221
- if (file.lines.length === 0) {
1222
- console.log(`${file.status ?? "?"} ${file.path} (no textual changes)`);
1223
- return;
1224
- }
1225
- for (const line of file.lines) {
1226
- if (line.type === "add")
1227
- console.log(`+${line.text}`);
1228
- else if (line.type === "del")
1229
- console.log(`-${line.text}`);
1230
- else if (line.type === "hunk")
1231
- console.log(line.text);
1232
- else if (line.type === "meta")
1233
- continue;
1234
- else
1235
- console.log(` ${line.text}`);
1236
- }
1237
- if (file.truncated)
1238
- console.log(" … truncated");
1239
- }
1240
- function printDiffSummary(summary, options) {
1241
- if (summary.files.length === 0) {
1242
- console.log(options?.emptyLabel ?? " (no changes)");
1243
- return;
1244
- }
1245
- if (summary.stats) {
1246
- const parts = [`${summary.stats.changedFileCount} file(s)`];
1247
- if (summary.stats.additions > 0)
1248
- parts.push(`+${summary.stats.additions}`);
1249
- if (summary.stats.deletions > 0)
1250
- parts.push(`-${summary.stats.deletions}`);
1251
- console.log(` ${parts.join(" · ")}`);
1252
- }
1253
- table(summary.files.map((file) => ({
1254
- status: file.status,
1255
- path: file.oldPath ? `${file.oldPath} → ${file.path}` : file.path,
1256
- plus: file.additions ?? (file.binary || file.asset ? "-" : "0"),
1257
- minus: file.deletions ?? (file.binary || file.asset ? "-" : "0"),
1258
- })), [
1259
- { key: "status", label: "St" },
1260
- { key: "path", label: "Path" },
1261
- { key: "plus", label: "+" },
1262
- { key: "minus", label: "-" },
1263
- ]);
1264
- if (options?.footer)
1265
- console.log(options.footer);
1266
- else if (summary.incomplete)
1267
- console.log(" … partial scan");
1268
- else if (summary.truncated)
1269
- console.log(" … truncated");
1270
- }
1271
- function registerFiles(spacesCmd) {
1272
- const filesCmd = spacesCmd
1273
- .command("files")
1274
- .description("File operations")
1275
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1276
- filesCmd
1277
- .command("ls [path]")
1278
- .alias("list")
1279
- .description("List directory tree")
1280
- .option("--json", "Output as JSON")
1281
- .action(async (path, opts) => {
1282
- const spaceId = await resolveSpace(spacesCmd);
1283
- const client = createClient();
1284
- try {
1285
- const tree = await client.space(spaceId).files.list(path ?? "");
1286
- if (jsonRequested(opts))
1287
- return outJson(tree);
1288
- if (tree.entries.length === 0) {
1289
- console.log(" (empty)");
1290
- return;
1291
- }
1292
- table(tree.entries, [
1293
- { key: "name", label: "Name" },
1294
- { key: "type", label: "Type" },
1295
- { key: "size", label: "Size" },
1296
- { key: "mtimeMs", label: "Modified", format: formatEpochMs },
1297
- ]);
1298
- }
1299
- catch (e) {
1300
- handleHttp(e);
1301
- }
1302
- });
1303
- registerSpaceFileTransfer(filesCmd, spacesCmd);
1304
- filesCmd
1305
- .command("write <path>")
1306
- .description("Write file content")
1307
- .option("-c, --content <text>", "File content")
1308
- .option("-e, --encoding <enc>", "Encoding (utf-8 or base64)", "utf-8")
1309
- .action(async (path, opts) => {
1310
- let content = opts.content ?? "";
1311
- if (!content && !process.stdin.isTTY) {
1312
- const chunks = [];
1313
- for await (const chunk of process.stdin)
1314
- chunks.push(chunk);
1315
- content = Buffer.concat(chunks).toString();
1316
- }
1317
- if (!content)
1318
- return error("No content provided", "Use -c or pipe via stdin");
1319
- const spaceId = await resolveSpace(spacesCmd);
1320
- const client = createClient();
1321
- try {
1322
- const result = await client.space(spaceId).files.write({
1323
- path,
1324
- content,
1325
- encoding: opts.encoding,
1326
- });
1327
- ok(`Written ${result.size} bytes to ${result.path}`);
1328
- }
1329
- catch (e) {
1330
- handleHttp(e);
1331
- }
1332
- });
1333
- filesCmd
1334
- .command("upload <paths...>")
1335
- .description("Upload local files; directory contents land under the target dir")
1336
- .option("--dir <path>", "Target directory in the space")
1337
- .option("--json", "Output as JSON")
1338
- .action((paths, opts) => uploadFiles(spacesCmd, paths, opts));
1339
- filesCmd
1340
- .command("mkdir <path>")
1341
- .description("Create a directory")
1342
- .action(async (path) => {
1343
- const spaceId = await resolveSpace(spacesCmd);
1344
- const client = createClient();
1345
- try {
1346
- await client.space(spaceId).files.createDir(path);
1347
- ok(`Directory created: ${path}`);
1348
- }
1349
- catch (e) {
1350
- handleHttp(e);
1351
- }
1352
- });
1353
- filesCmd
1354
- .command("rm <path>")
1355
- .description("Delete a file or directory")
1356
- .option("-r, --recursive", "Delete recursively")
1357
- .action(async (path, opts) => {
1358
- const spaceId = await resolveSpace(spacesCmd);
1359
- const client = createClient();
1360
- try {
1361
- await client.space(spaceId).files.delete(path, opts.recursive ?? false);
1362
- ok(`Deleted: ${path}`);
1363
- }
1364
- catch (e) {
1365
- handleHttp(e);
1366
- }
1367
- });
1368
- filesCmd
1369
- .command("mv <from> <to>")
1370
- .description("Move or rename")
1371
- .action(async (from, to) => {
1372
- const spaceId = await resolveSpace(spacesCmd);
1373
- const client = createClient();
1374
- try {
1375
- await client.space(spaceId).files.move({ fromPath: from, toPath: to });
1376
- ok(`Moved: ${from} → ${to}`);
1377
- }
1378
- catch (e) {
1379
- handleHttp(e);
1380
- }
1381
- });
1382
- filesCmd
1383
- .command("diff [path]")
1384
- .description("Show pending workspace changes vs last checkpoint")
1385
- .option("--json", "Output as JSON")
1386
- .action(async (path, opts) => {
1387
- const spaceId = await resolveSpace(spacesCmd);
1388
- const client = createClient();
1389
- try {
1390
- if (path) {
1391
- const file = await client.space(spaceId).files.diffFile(path);
1392
- if (jsonRequested(opts))
1393
- return outJson(file);
1394
- printDiffFile(file);
1395
- return;
1396
- }
1397
- const summary = await client.space(spaceId).files.diff();
1398
- if (jsonRequested(opts))
1399
- return outJson(summary);
1400
- printDiffSummary(summary, {
1401
- emptyLabel: " (no pending changes)",
1402
- footer: summary.incomplete
1403
- ? " … partial scan"
1404
- : summary.truncated
1405
- ? " … truncated"
1406
- : null,
1407
- });
1408
- }
1409
- catch (e) {
1410
- handleHttp(e);
1411
- }
1412
- });
1413
- }
1414
- function registerSessions(spacesCmd) {
1415
- const sessionsCmd = spacesCmd
1416
- .command("sessions")
1417
- .description("Browse sessions and turns")
1418
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1419
- sessionsCmd
1420
- .command("ls")
1421
- .alias("list")
1422
- .description("List sessions")
1423
- .option("--json", "Output as JSON")
1424
- .action(async (opts) => {
1425
- const spaceId = await resolveSpace(spacesCmd);
1426
- const client = createClient();
1427
- try {
1428
- const result = await client.space(spaceId).sessions.list();
1429
- if (jsonRequested(opts))
1430
- return outJson(result);
1431
- if (result.sessions.length === 0) {
1432
- console.log(" (empty)");
1433
- return;
1434
- }
1435
- table(result.sessions, [
1436
- { key: "id", label: "ID" },
1437
- { key: "title", label: "Title" },
1438
- SESSION_STATUS_COLUMN,
1439
- { key: "totalMessages", label: "Messages" },
1440
- { key: "createdAt", label: "Created" },
1441
- ]);
1442
- }
1443
- catch (e) {
1444
- handleHttp(e);
1445
- }
1446
- });
1447
- sessionsCmd
1448
- .command("create [title]")
1449
- .description("Create a session")
1450
- .option("--label <ref>", "Attach a label, e.g. Bug or Area/Frontend", collectOption, [])
1451
- .option("--json", "Output as JSON")
1452
- .action(async (title, opts) => {
1453
- const spaceId = await resolveSpace(spacesCmd);
1454
- const client = createClient();
1455
- try {
1456
- const result = await client.space(spaceId).sessions.create({
1457
- title,
1458
- labelRefs: opts.label?.length ? opts.label : undefined,
1459
- });
1460
- if (jsonRequested(opts))
1461
- return outJson(result);
1462
- ok(`Session created: ${result.session.id}`);
1463
- table([result.session], [
1464
- { key: "id", label: "ID" },
1465
- { key: "title", label: "Title" },
1466
- ]);
1467
- }
1468
- catch (e) {
1469
- handleHttp(e);
1470
- }
1471
- });
1472
- sessionsCmd
1473
- .command("get <id>")
1474
- .description("Session details")
1475
- .option("--json", "Output as JSON")
1476
- .action(async (id, opts) => {
1477
- const spaceId = await resolveSpace(spacesCmd);
1478
- const client = createClient();
1479
- try {
1480
- const result = await client.space(spaceId).session(id).get();
1481
- if (jsonRequested(opts))
1482
- return outJson(result);
1483
- table([result.session], [
1484
- { key: "id", label: "ID" },
1485
- { key: "title", label: "Title" },
1486
- SESSION_STATUS_COLUMN,
1487
- { key: "totalMessages", label: "Messages" },
1488
- { key: "totalToolCalls", label: "Tool Calls" },
1489
- { key: "createdAt", label: "Created" },
1490
- ]);
1491
- }
1492
- catch (e) {
1493
- handleHttp(e);
1494
- }
1495
- });
1496
- sessionsCmd
1497
- .command("stats <id>")
1498
- .description("Session statistics for settled turns (including separate inherited history)")
1499
- .option("--json", "Output as JSON")
1500
- .action(async (id, opts) => {
1501
- const spaceId = await resolveSpace(spacesCmd);
1502
- try {
1503
- const { stats } = await createClient().space(spaceId).session(id).stats();
1504
- if (jsonRequested(opts))
1505
- return outJson({ stats });
1506
- const own = stats.own;
1507
- const rows = [
1508
- { metric: "Turns", value: own.turns },
1509
- { metric: "Model calls", value: own.calls },
1510
- { metric: "Tool calls", value: own.toolCalls },
1511
- { metric: "Compactions", value: own.compactions },
1512
- { metric: "Tokens", value: own.usage?.totalTokens },
1513
- { metric: "Execution time (ms)", value: own.elapsedMs },
1514
- { metric: "Model time (ms)", value: own.modelMs == null ? null : Math.round(own.modelMs) },
1515
- { metric: "Model cost (USD)", value: own.modelCostUsd },
1516
- { metric: "Content generation cost (USD)", value: own.generationCostUsd },
1517
- { metric: "Inherited turns", value: stats.inherited.turns },
1518
- ].filter((row) => row.value != null);
1519
- table(rows, [{ key: "metric", label: "Metric" }, { key: "value", label: "Value" }]);
1520
- if (own.partial)
1521
- console.log("Some execution details were not recorded.");
1522
- }
1523
- catch (e) {
1524
- handleHttp(e);
1525
- }
1526
- });
1527
- sessionsCmd
1528
- .command("files <id>")
1529
- .description("List Space files changed by a session")
1530
- .option("--limit <n>", "Maximum files to list; the server caps it", "200")
1531
- .option("--json", "Output as JSON")
1532
- .action(async (id, opts) => {
1533
- const spaceId = await resolveSpace(spacesCmd);
1534
- const limit = Number.parseInt(opts.limit, 10);
1535
- if (!Number.isInteger(limit) || limit < 1) {
1536
- return error("Invalid limit", "--limit must be a positive integer");
1537
- }
1538
- const client = createClient();
1539
- try {
1540
- const result = await client.space(spaceId).session(id).files({ limit });
1541
- if (jsonRequested(opts))
1542
- return outJson(result);
1543
- if (result.files.length === 0) {
1544
- console.log(" (empty)");
1545
- return;
1546
- }
1547
- table(result.files.map((file) => ({
1548
- path: file.path,
1549
- change: file.lastKind,
1550
- count: file.changeCount,
1551
- turn: file.lastTurnSequence,
1552
- changedAt: file.lastChangedAt,
1553
- })), [
1554
- { key: "path", label: "Path" },
1555
- { key: "change", label: "Change" },
1556
- { key: "count", label: "Count" },
1557
- { key: "turn", label: "Turn" },
1558
- { key: "changedAt", label: "Changed" },
1559
- ]);
1560
- }
1561
- catch (e) {
1562
- handleHttp(e);
1563
- }
1564
- });
1565
- sessionsCmd
1566
- .command("rename <id> <name>")
1567
- .description("Rename a session")
1568
- .action(async (id, name) => {
1569
- const spaceId = await resolveSpace(spacesCmd);
1570
- const client = createClient();
1571
- try {
1572
- await client.space(spaceId).session(id).rename(name);
1573
- ok(`Session renamed to "${name}"`);
1574
- }
1575
- catch (e) {
1576
- handleHttp(e);
1577
- }
1578
- });
1579
- // ── sessions tail ──
1580
- sessionsCmd
1581
- .command("tail <id>")
1582
- .description("Stream realtime session events")
1583
- .option("--json", "Output as JSON")
1584
- .action(async (id, opts) => {
1585
- const spaceId = await resolveSpace(spacesCmd);
1586
- const client = createClient();
1587
- const session = client.space(spaceId).session(id);
1588
- process.stdout.write(" Listening for events...\n\n");
1589
- let lastAppendPath = null;
1590
- session.on("turn.patch", (e) => {
1591
- if (jsonRequested(opts)) {
1592
- console.log(JSON.stringify(e));
1593
- }
1594
- else {
1595
- const ops = e.payload?.ops;
1596
- for (const op of ops ?? []) {
1597
- if (op.o === "append" && typeof op.v === "string" && op.p?.endsWith("/text")) {
1598
- lastAppendPath = op.p;
1599
- process.stdout.write(op.v);
1600
- continue;
1601
- }
1602
- if (op.o === "append" && typeof op.p === "string") {
1603
- lastAppendPath = op.p;
1604
- continue;
1605
- }
1606
- if (!op.o && !op.p && typeof op.v === "string" && lastAppendPath?.endsWith("/text")) {
1607
- process.stdout.write(op.v);
1608
- }
1609
- }
1610
- }
1611
- });
1612
- session.on("turn.finalized", () => {
1613
- process.stdout.write("\n\n ✓ Done\n");
1614
- process.exit(0);
1615
- });
1616
- session.on("turn.error", (e) => {
1617
- process.stderr.write(`\n ✗ Error\n`);
1618
- if (jsonRequested(opts))
1619
- process.stderr.write(`${JSON.stringify(e)}\n`);
1620
- process.exit(1);
1621
- });
1622
- });
1623
- // ── sessions turns ──
1624
- registerTurns(sessionsCmd);
1625
- // ── sessions access ──
1626
- registerSessionAccess(sessionsCmd);
1627
- }
1628
- // ── Turn operations ──
1629
- function registerTurns(sessionsCmd) {
1630
- const turnsCmd = sessionsCmd.command("turns").description("Inspect session turns");
1631
- turnsCmd
1632
- .command("ls <sessionId>")
1633
- .alias("list")
1634
- .description("List recent turns")
1635
- .option("--cursor <sequence>", "Turn sequence cursor")
1636
- .option("--direction <older|newer>", "Page direction", "older")
1637
- .option("--limit <n>", "Page size", "30")
1638
- .option("--json", "Output as JSON")
1639
- .action(async (sessionId, opts) => {
1640
- const spaceId = await resolveSpace(sessionsCmd);
1641
- const client = createClient();
1642
- try {
1643
- const result = await client.space(spaceId).session(sessionId).turns.listPaginated({
1644
- cursor: opts.cursor === undefined ? undefined : parseInteger(opts.cursor, "cursor", { min: 0 }),
1645
- direction: parseChoice(opts.direction ?? "older", "direction", ["older", "newer"]),
1646
- limit: parseInteger(opts.limit ?? "30", "limit", { min: 1, max: 100 }),
1647
- });
1648
- if (jsonRequested(opts))
1649
- return outJson(result);
1650
- if (result.turns.length === 0)
1651
- return console.log(" No turns found");
1652
- table(result.turns, [
1653
- { key: "sequence", label: "Seq" },
1654
- { key: "id", label: "ID" },
1655
- { key: "status", label: "Status" },
1656
- { key: "userText", label: "User" },
1657
- { key: "assistantText", label: "Assistant" },
1658
- { key: "updatedAt", label: "Updated" },
1659
- ]);
1660
- if (result.hasMore)
1661
- console.log(`\n More turns available — next cursor: ${result.nextCursor}`);
1662
- }
1663
- catch (e) {
1664
- handleHttp(e);
1665
- }
1666
- });
1667
- turnsCmd
1668
- .command("get <sessionId> <turnId>")
1669
- .description("Show turn details")
1670
- .option("--json", "Output as JSON")
1671
- .action(async (sessionId, turnId, opts) => {
1672
- const spaceId = await resolveSpace(sessionsCmd);
1673
- const client = createClient();
1674
- try {
1675
- const result = await client.space(spaceId).session(sessionId).turns.get(turnId);
1676
- if (jsonRequested(opts))
1677
- return outJson(result);
1678
- table([result.turn], [
1679
- { key: "sequence", label: "Seq" },
1680
- { key: "id", label: "ID" },
1681
- { key: "status", label: "Status" },
1682
- { key: "provider", label: "Provider" },
1683
- { key: "model", label: "Model" },
1684
- { key: "stopReason", label: "Stop" },
1685
- { key: "errorMessage", label: "Error" },
1686
- ]);
1687
- if (result.turn.summary?.reason === "billing")
1688
- console.log("\nStopped: insufficient balance. Manage billing at your Cohub account settings.");
1689
- const origin = readSessionTurnOrigin(result.turn.meta, spaceId);
1690
- if (origin)
1691
- console.log(`\nOrigin (${origin.kind}): space=${origin.spaceId} session=${origin.sessionId} turn=${origin.turnId}${origin.toolCallId ? ` toolCall=${origin.toolCallId}` : ""}`);
1692
- const sent = readSentTurns(result.turn.meta);
1693
- if (sent.length > 0) {
1694
- console.log(`\nSent (${sent.length}):`);
1695
- for (const ref of sent)
1696
- console.log(` ${ref.spaceId ? `space=${ref.spaceId} ` : ""}session=${ref.sessionId} turn=${ref.turnId}${ref.toolCallId ? ` toolCall=${ref.toolCallId}` : ""}`);
1697
- }
1698
- if (result.turn.userText)
1699
- console.log(`\nUser:\n${result.turn.userText}`);
1700
- if (result.turn.assistantText)
1701
- console.log(`\nAssistant:\n${result.turn.assistantText}`);
1702
- }
1703
- catch (e) {
1704
- handleHttp(e);
1705
- }
1706
- });
1707
- turnsCmd
1708
- .command("steer <sessionId> <turnId>")
1709
- .description("Run a queued follow-up now")
1710
- .option("--json", "Output as JSON")
1711
- .action(async (sessionId, turnId, opts) => {
1712
- const spaceId = await resolveSpace(sessionsCmd);
1713
- const client = createClient();
1714
- try {
1715
- const result = await client.space(spaceId).session(sessionId).steerTurn(turnId);
1716
- if (jsonRequested(opts))
1717
- return outJson(result);
1718
- ok(`Turn steered: ${result.turn.id}`);
1719
- }
1720
- catch (e) {
1721
- handleHttp(e);
1722
- }
1723
- });
1724
- turnsCmd
1725
- .command("cancel <sessionId> <turnId>")
1726
- .description("Cancel a queued follow-up")
1727
- .option("--json", "Output as JSON")
1728
- .action(async (sessionId, turnId, opts) => {
1729
- const spaceId = await resolveSpace(sessionsCmd);
1730
- const client = createClient();
1731
- try {
1732
- const result = await client.space(spaceId).session(sessionId).cancelTurn(turnId);
1733
- if (jsonRequested(opts))
1734
- return outJson(result);
1735
- ok(`Turn cancelled: ${result.turn.id}`);
1736
- }
1737
- catch (e) {
1738
- handleHttp(e);
1739
- }
1740
- });
1741
- turnsCmd
1742
- .command("index <sessionId>", { hidden: true })
1743
- .description("List lightweight turn index")
1744
- .option("--cursor <sequence>", "Turn sequence cursor")
1745
- .option("--limit <n>", "Page size", "100")
1746
- .option("--json", "Output as JSON")
1747
- .action(async (sessionId, opts) => {
1748
- const spaceId = await resolveSpace(sessionsCmd);
1749
- const client = createClient();
1750
- try {
1751
- const result = await client.space(spaceId).session(sessionId).turns.index({
1752
- cursor: opts.cursor === undefined ? undefined : parseInteger(opts.cursor, "cursor", { min: 0 }),
1753
- limit: parseInteger(opts.limit ?? "100", "limit", { min: 1, max: 500 }),
1754
- });
1755
- if (jsonRequested(opts))
1756
- return outJson(result);
1757
- if (result.turns.length === 0)
1758
- return console.log(" No turns found");
1759
- table(result.turns, [
1760
- { key: "sequence", label: "Seq" },
1761
- { key: "id", label: "ID" },
1762
- { key: "status", label: "Status" },
1763
- { key: "userPreview", label: "User" },
1764
- { key: "assistantPreview", label: "Assistant" },
1765
- ]);
1766
- if (result.hasMore)
1767
- console.log(`\n More turns available — next cursor: ${result.nextCursor}`);
1768
- }
1769
- catch (e) {
1770
- handleHttp(e);
1771
- }
1772
- });
1773
- turnsCmd
1774
- .command("window <sessionId>", { hidden: true })
1775
- .description("Load turns around a sequence or turn ID")
1776
- .option("--sequence <n>", "Anchor turn sequence")
1777
- .option("--turn <id>", "Anchor turn ID")
1778
- .option("--before <n>", "Turns before anchor", "10")
1779
- .option("--after <n>", "Turns after anchor", "20")
1780
- .option("--json", "Output as JSON")
1781
- .action(async (sessionId, opts) => {
1782
- const spaceId = await resolveSpace(sessionsCmd);
1783
- if (!opts.sequence && !opts.turn)
1784
- return error("Missing anchor", "Use --sequence <n> or --turn <id>");
1785
- const client = createClient();
1786
- try {
1787
- const result = await client.space(spaceId).session(sessionId).turns.window({
1788
- sequence: opts.sequence === undefined ? undefined : parseInteger(opts.sequence, "sequence", { min: 0 }),
1789
- turnId: opts.turn,
1790
- before: parseInteger(opts.before ?? "10", "before", { min: 0, max: 200 }),
1791
- after: parseInteger(opts.after ?? "20", "after", { min: 0, max: 200 }),
1792
- });
1793
- if (jsonRequested(opts))
1794
- return outJson(result);
1795
- if (result.turns.length === 0)
1796
- return console.log(" No turns found");
1797
- table(result.turns, [
1798
- { key: "sequence", label: "Seq" },
1799
- { key: "id", label: "ID" },
1800
- { key: "status", label: "Status" },
1801
- { key: "userText", label: "User" },
1802
- { key: "assistantText", label: "Assistant" },
1803
- ]);
1804
- console.log(`\n Window — older: ${result.hasMoreOlder ? "yes" : "no"}, newer: ${result.hasMoreNewer ? "yes" : "no"}`);
1805
- }
1806
- catch (e) {
1807
- handleHttp(e);
1808
- }
1809
- });
1810
- }
1811
- // ── Session access operations ──
1812
- function registerSessionAccess(sessionsCmd) {
1813
- const accessCmd = sessionsCmd.command("access").description("Session access control");
1814
- accessCmd
1815
- .command("get <id>")
1816
- .description("Get session access policy")
1817
- .option("--json", "Output as JSON")
1818
- .action(async (id, opts) => {
1819
- const client = createClient();
1820
- try {
1821
- const policy = await client.sessionAccess.get(id);
1822
- if (jsonRequested(opts))
1823
- return outJson(policy);
1824
- table([policy], [
1825
- { key: "signed_in_user", label: "Signed-in" },
1826
- { key: "anonymous_user", label: "Anonymous" },
1827
- ]);
1828
- }
1829
- catch (e) {
1830
- handleHttp(e);
1831
- }
1832
- });
1833
- accessCmd
1834
- .command("set <id>")
1835
- .description("Set session anonymous access")
1836
- .option("--anonymous <role>", "Anonymous role (host|builder|guest|null)")
1837
- .option("--json", "Output as JSON")
1838
- .action(async (id, opts) => {
1839
- const client = createClient();
1840
- try {
1841
- const policy = await client.sessionAccess.set(id, {
1842
- anonymous_user: parseNullableRole(opts.anonymous, "anonymous role"),
1843
- });
1844
- if (jsonRequested(opts))
1845
- return outJson(policy);
1846
- ok("Session access updated");
1847
- table([policy], [
1848
- { key: "signed_in_user", label: "Signed-in" },
1849
- { key: "anonymous_user", label: "Anonymous" },
1850
- ]);
1851
- }
1852
- catch (e) {
1853
- handleHttp(e);
1854
- }
1855
- });
1856
- accessCmd
1857
- .command("remove <id>")
1858
- .description("Remove session access override")
1859
- .action(async (id) => {
1860
- const client = createClient();
1861
- try {
1862
- await client.sessionAccess.remove(id);
1863
- ok(`Session access override removed: ${id}`);
1864
- }
1865
- catch (e) {
1866
- handleHttp(e);
1867
- }
1868
- });
1869
- }
1870
- // ── Member operations ──
1871
- function registerMembers(spacesCmd) {
1872
- const memCmd = spacesCmd
1873
- .command("members")
1874
- .description("Member management")
1875
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1876
- memCmd
1877
- .command("ls")
1878
- .alias("list")
1879
- .description("List space members")
1880
- .option("--json", "Output as JSON")
1881
- .action(async (opts) => {
1882
- const spaceId = await resolveSpace(spacesCmd);
1883
- const client = createClient();
1884
- try {
1885
- const result = await client.space(spaceId).members.list();
1886
- if (jsonRequested(opts))
1887
- return outJson(result);
1888
- if (result.items.length === 0) {
1889
- console.log(" (empty)");
1890
- return;
1891
- }
1892
- table(result.items, [
1893
- { key: "userId", label: "User ID" },
1894
- { key: "role", label: "Role" },
1895
- { key: "createdAt", label: "Since" },
1896
- ]);
1897
- }
1898
- catch (e) {
1899
- handleHttp(e);
1900
- }
1901
- });
1902
- memCmd
1903
- .command("update <userId> <role>")
1904
- .description("Change member role (host | builder | guest)")
1905
- .action(async (userId, role) => {
1906
- const spaceId = await resolveSpace(spacesCmd);
1907
- const client = createClient();
1908
- try {
1909
- await client.space(spaceId).members.update(userId, parseChoice(role, "role", SPACE_ROLES));
1910
- ok(`${userId} → ${role}`);
1911
- }
1912
- catch (e) {
1913
- handleHttp(e);
1914
- }
1915
- });
1916
- memCmd
1917
- .command("remove <userId>")
1918
- .description("Remove a member")
1919
- .action(async (userId) => {
1920
- const spaceId = await resolveSpace(spacesCmd);
1921
- const client = createClient();
1922
- try {
1923
- await client.space(spaceId).members.remove(userId);
1924
- ok(`${userId} removed`);
1925
- }
1926
- catch (e) {
1927
- handleHttp(e);
1928
- }
1929
- });
1930
- }
1931
- // ── Access control ──
1932
- const ACCESS_COLUMNS = [
1933
- { key: "signed_in_user", label: "Signed-in" },
1934
- { key: "anonymous_user", label: "Anonymous" },
1935
- ];
1936
- function registerAccess(spacesCmd) {
1937
- const accCmd = spacesCmd
1938
- .command("access")
1939
- .description("Access control")
1940
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1941
- accCmd
1942
- .command("get")
1943
- .description("Get access policy")
1944
- .option("--json", "Output as JSON")
1945
- .action(async (opts) => {
1946
- const spaceId = await resolveSpace(spacesCmd);
1947
- const client = createClient();
1948
- try {
1949
- const policy = await client.space(spaceId).access.get();
1950
- if (jsonRequested(opts))
1951
- return outJson(policy);
1952
- table([policy], ACCESS_COLUMNS);
1953
- }
1954
- catch (e) {
1955
- handleHttp(e);
1956
- }
1957
- });
1958
- accCmd
1959
- .command("set")
1960
- .description("Set access policy; omitted options stay unchanged")
1961
- .option("--signed-in <role>", "Role for signed-in users (builder|guest|null)")
1962
- .option("--anonymous <role>", "Role for anonymous users (guest|null)")
1963
- .option("--json", "Output as JSON")
1964
- .action(async (opts) => {
1965
- const spaceId = await resolveSpace(spacesCmd);
1966
- const client = createClient();
1967
- if (opts.signedIn === undefined && opts.anonymous === undefined) {
1968
- return error("Nothing to update", "Pass --signed-in or --anonymous");
1969
- }
1970
- try {
1971
- const policy = await client.space(spaceId).access.set({
1972
- ...(opts.signedIn !== undefined ? { signed_in_user: parseNullableRole(opts.signedIn, "signed-in role") } : {}),
1973
- ...(opts.anonymous !== undefined ? { anonymous_user: parseNullableRole(opts.anonymous, "anonymous role") } : {}),
1974
- });
1975
- if (jsonRequested(opts))
1976
- return outJson(policy);
1977
- ok("Access policy updated");
1978
- table([policy], ACCESS_COLUMNS);
1979
- }
1980
- catch (e) {
1981
- handleHttp(e);
1982
- }
1983
- });
1984
- }
1985
- // ── Checkpoint operations ──
1986
- function registerCheckpoints(spacesCmd) {
1987
- const cpCmd = spacesCmd
1988
- .command("checkpoints")
1989
- .description("Checkpoint management")
1990
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1991
- cpCmd
1992
- .command("ls")
1993
- .alias("list")
1994
- .description("List checkpoints")
1995
- .option("--limit <n>", "Maximum checkpoints to return", (value) => Number(value))
1996
- .option("--cursor <cursor>", "Pagination cursor")
1997
- .option("--json", "Output as JSON")
1998
- .action(async (opts) => {
1999
- const spaceId = await resolveSpace(spacesCmd);
2000
- const client = createClient();
2001
- try {
2002
- const result = await client.space(spaceId).checkpoints.list({
2003
- limit: opts.limit,
2004
- cursor: opts.cursor,
2005
- });
2006
- if (jsonRequested(opts))
2007
- return outJson(result);
2008
- if (result.checkpoints.length === 0) {
2009
- console.log(" (empty)");
2010
- return;
2011
- }
2012
- table(result.checkpoints, [
2013
- { key: "id", label: "ID" },
2014
- { key: "commitHash", label: "Commit" },
2015
- { key: "description", label: "Description" },
2016
- { key: "createdAt", label: "Created" },
2017
- ]);
2018
- }
2019
- catch (e) {
2020
- handleHttp(e);
2021
- }
2022
- });
2023
- cpCmd
2024
- .command("get <id>")
2025
- .description("Checkpoint details")
2026
- .option("--json", "Output as JSON")
2027
- .action(async (id, opts) => {
2028
- const spaceId = await resolveSpace(spacesCmd);
2029
- const client = createClient();
2030
- try {
2031
- const result = await client.space(spaceId).checkpoints.get(id);
2032
- if (jsonRequested(opts))
2033
- return outJson(result);
2034
- table([result.checkpoint], [
2035
- { key: "id", label: "ID" },
2036
- { key: "commitHash", label: "Commit" },
2037
- { key: "description", label: "Description" },
2038
- { key: "forkCount", label: "Forks" },
2039
- { key: "createdAt", label: "Created" },
2040
- ]);
2041
- }
2042
- catch (e) {
2043
- handleHttp(e);
2044
- }
2045
- });
2046
- cpCmd
2047
- .command("create [description]")
2048
- .description("Create a checkpoint")
2049
- .option("--json", "Output as JSON")
2050
- .action(async (description, opts) => {
2051
- const spaceId = await resolveSpace(spacesCmd);
2052
- const client = createClient();
2053
- try {
2054
- const result = await client.space(spaceId).checkpoints.create(description ?? null);
2055
- if (jsonRequested(opts))
2056
- return outJson(result);
2057
- ok(`Checkpoint created — taskRunId: ${result.taskRunId}`);
2058
- }
2059
- catch (e) {
2060
- handleHttp(e);
2061
- }
2062
- });
2063
- cpCmd
2064
- .command("ls-tree <checkpointId> [path]")
2065
- .description("List checkpoint tree")
2066
- .option("--json", "Output as JSON")
2067
- .action(async (checkpointId, path, opts) => {
2068
- const spaceId = await resolveSpace(spacesCmd);
2069
- const client = createClient();
2070
- try {
2071
- const tree = await client.space(spaceId).checkpoints(checkpointId).files.list(path ?? "");
2072
- if (jsonRequested(opts))
2073
- return outJson(tree);
2074
- if (tree.entries.length === 0) {
2075
- console.log(" (empty)");
2076
- return;
2077
- }
2078
- table(tree.entries, [
2079
- { key: "name", label: "Name" },
2080
- { key: "type", label: "Type" },
2081
- { key: "size", label: "Size" },
2082
- { key: "mimeType", label: "MIME" },
2083
- { key: "mtimeMs", label: "Modified", format: formatEpochMs },
2084
- ]);
2085
- }
2086
- catch (e) {
2087
- handleHttp(e);
2088
- }
2089
- });
2090
- cpCmd
2091
- .command("show <checkpointId> <path>")
2092
- .description("Show checkpoint file content")
2093
- .option("--json", "Output as JSON")
2094
- .action(async (checkpointId, path, opts) => {
2095
- const spaceId = await resolveSpace(spacesCmd);
2096
- const client = createClient();
2097
- try {
2098
- const file = await client.space(spaceId).checkpoints(checkpointId).files.read(path);
2099
- if (jsonRequested(opts))
2100
- return outJson(file);
2101
- if (file.delivery === "url" && file.url) {
2102
- console.log(file.url);
2103
- return;
2104
- }
2105
- console.log(file.content);
2106
- }
2107
- catch (e) {
2108
- handleHttp(e);
2109
- }
2110
- });
2111
- cpCmd
2112
- .command("diff <checkpointId> [path]")
2113
- .description("Show checkpoint diff vs parent (or --base)")
2114
- .option("--base <checkpointId>", "Compare against another checkpoint")
2115
- .option("--json", "Output as JSON")
2116
- .action(async (checkpointId, path, opts) => {
2117
- const spaceId = await resolveSpace(spacesCmd);
2118
- const client = createClient();
2119
- try {
2120
- if (path) {
2121
- const file = await client.space(spaceId).checkpoints(checkpointId).diff.file(path, { base: opts.base ?? null });
2122
- if (jsonRequested(opts))
2123
- return outJson(file);
2124
- printDiffFile(file);
2125
- return;
2126
- }
2127
- const summary = await client.space(spaceId).checkpoints(checkpointId).diff.summary({ base: opts.base ?? null });
2128
- if (jsonRequested(opts))
2129
- return outJson(summary);
2130
- printDiffSummary(summary, {
2131
- emptyLabel: " (no changes)",
2132
- footer: summary.truncated ? " … truncated" : null,
2133
- });
2134
- }
2135
- catch (e) {
2136
- handleHttp(e);
2137
- }
2138
- });
2139
- }