@neta-art/cohub-cli 10.24.0 → 10.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (368) hide show
  1. package/bin/cohub.js +4 -1
  2. package/dist/board-gpu/page.js +1566 -71230
  3. package/dist/bootstrap.js +67 -27
  4. package/dist/build.json +1 -1
  5. package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
  6. package/dist/chunks/about.js +102 -0
  7. package/dist/chunks/app-realtime.js +2216 -0
  8. package/dist/chunks/app-realtime2.js +2 -0
  9. package/dist/chunks/app-ref.js +88 -0
  10. package/dist/chunks/apps.js +1423 -0
  11. package/dist/chunks/auth.js +175 -0
  12. package/dist/chunks/avatar.js +146 -0
  13. package/dist/chunks/board-export-resources.js +232 -0
  14. package/dist/chunks/board-export.js +874 -0
  15. package/dist/chunks/board-export2.js +2 -0
  16. package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
  17. package/dist/chunks/board-kernel2.js +4 -0
  18. package/dist/chunks/board-profile.js +69 -0
  19. package/dist/chunks/board-simulate.js +315 -0
  20. package/dist/chunks/board-time.js +34 -0
  21. package/dist/chunks/boards.js +1943 -0
  22. package/dist/{board-kernel → chunks}/browserAll.js +9 -8
  23. package/dist/chunks/channels.js +64 -0
  24. package/dist/chunks/client.js +12606 -0
  25. package/dist/chunks/command-input.js +17 -0
  26. package/dist/chunks/commander.js +2962 -0
  27. package/dist/chunks/cron-jobs.js +163 -0
  28. package/dist/chunks/daemon.js +545 -0
  29. package/dist/chunks/daemon2.js +2 -0
  30. package/dist/chunks/desktop.js +172 -0
  31. package/dist/chunks/endpoint-options.js +26 -0
  32. package/dist/chunks/env-proxy.js +35 -0
  33. package/dist/chunks/environment.js +154 -0
  34. package/dist/chunks/feedback.js +120 -0
  35. package/dist/chunks/generations.js +379 -0
  36. package/dist/chunks/host.js +9 -0
  37. package/dist/chunks/http-put.js +131 -0
  38. package/dist/chunks/id.js +2416 -0
  39. package/dist/{board-kernel → chunks}/init.js +1 -1
  40. package/dist/chunks/install.js +11959 -0
  41. package/dist/chunks/launch.js +374 -0
  42. package/dist/chunks/local-media.js +47 -0
  43. package/dist/chunks/me.js +134 -0
  44. package/dist/chunks/media.js +315 -0
  45. package/dist/chunks/models.js +242 -0
  46. package/dist/chunks/operands.js +46 -0
  47. package/dist/chunks/package-paths.js +13 -0
  48. package/dist/chunks/policy.js +221 -0
  49. package/dist/chunks/preferences.js +29 -0
  50. package/dist/chunks/profile.js +64 -0
  51. package/dist/chunks/prompts.js +41 -0
  52. package/dist/chunks/public.js +2 -0
  53. package/dist/chunks/public2.js +244 -0
  54. package/dist/chunks/references.js +197 -0
  55. package/dist/chunks/referrals.js +90 -0
  56. package/dist/chunks/rolldown-runtime.js +26 -0
  57. package/dist/chunks/rooms-connect.js +2 -0
  58. package/dist/chunks/rooms-connect2.js +151 -0
  59. package/dist/chunks/rooms-rtc.js +309 -0
  60. package/dist/chunks/rooms.js +211 -0
  61. package/dist/chunks/run.js +220 -0
  62. package/dist/chunks/runtime.js +638 -0
  63. package/dist/chunks/runtime2.js +286 -0
  64. package/dist/chunks/runtimes.js +48 -0
  65. package/dist/chunks/safe-remote-image.js +198 -0
  66. package/dist/chunks/schemas.js +6017 -0
  67. package/dist/chunks/search.js +113 -0
  68. package/dist/chunks/self-update.js +238 -0
  69. package/dist/chunks/serve.js +1246 -0
  70. package/dist/chunks/session-status.js +24 -0
  71. package/dist/chunks/skills.js +35 -0
  72. package/dist/chunks/spaces.js +5080 -0
  73. package/dist/chunks/src.js +405 -0
  74. package/dist/chunks/supervisor.js +2511 -0
  75. package/dist/chunks/supervisor2.js +2 -0
  76. package/dist/chunks/tasks.js +82 -0
  77. package/dist/chunks/themes.js +2898 -0
  78. package/dist/chunks/version.js +2 -0
  79. package/dist/chunks/version2.js +22 -0
  80. package/dist/chunks/version3.js +18 -0
  81. package/dist/chunks/web.js +7 -0
  82. package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
  83. package/dist/runtime/native/pi-extension.js +174 -166
  84. package/dist/runtime/worker.js +27 -16
  85. package/package.json +8 -9
  86. package/dist/about.d.ts +0 -2
  87. package/dist/about.js +0 -71
  88. package/dist/app-download.d.ts +0 -11
  89. package/dist/app-download.js +0 -252
  90. package/dist/app-ref.d.ts +0 -5
  91. package/dist/app-ref.js +0 -8
  92. package/dist/app-target.d.ts +0 -26
  93. package/dist/app-target.js +0 -55
  94. package/dist/auth.d.ts +0 -45
  95. package/dist/auth.js +0 -307
  96. package/dist/avatar.d.ts +0 -55
  97. package/dist/avatar.js +0 -104
  98. package/dist/board-command-support.d.ts +0 -6
  99. package/dist/board-command-support.js +0 -88
  100. package/dist/board-export-resources.d.ts +0 -12
  101. package/dist/board-export-resources.js +0 -51
  102. package/dist/board-export.d.ts +0 -110
  103. package/dist/board-export.js +0 -592
  104. package/dist/board-fonts.d.ts +0 -11
  105. package/dist/board-fonts.js +0 -10
  106. package/dist/board-gpu/daemon.d.ts +0 -11
  107. package/dist/board-gpu/daemon.js +0 -295
  108. package/dist/board-gpu/index.d.ts +0 -33
  109. package/dist/board-gpu/index.js +0 -189
  110. package/dist/board-gpu/protocol.d.ts +0 -77
  111. package/dist/board-gpu/protocol.js +0 -1
  112. package/dist/board-kernel.d.ts +0 -5
  113. package/dist/board-media-export.d.ts +0 -17
  114. package/dist/board-media-export.js +0 -164
  115. package/dist/board-media.d.ts +0 -5
  116. package/dist/board-media.js +0 -66
  117. package/dist/board-profile.d.ts +0 -21
  118. package/dist/board-profile.js +0 -67
  119. package/dist/board-simulate.d.ts +0 -67
  120. package/dist/board-simulate.js +0 -259
  121. package/dist/board-time.d.ts +0 -3
  122. package/dist/board-time.js +0 -34
  123. package/dist/bootstrap.d.ts +0 -2
  124. package/dist/client.d.ts +0 -5
  125. package/dist/client.js +0 -24
  126. package/dist/command-input.d.ts +0 -4
  127. package/dist/command-input.js +0 -16
  128. package/dist/commands/app-commerce.d.ts +0 -2
  129. package/dist/commands/app-commerce.js +0 -228
  130. package/dist/commands/app-domains.d.ts +0 -2
  131. package/dist/commands/app-domains.js +0 -133
  132. package/dist/commands/apps.d.ts +0 -4
  133. package/dist/commands/apps.js +0 -827
  134. package/dist/commands/auth.d.ts +0 -2
  135. package/dist/commands/auth.js +0 -186
  136. package/dist/commands/boards/authoring.d.ts +0 -2
  137. package/dist/commands/boards/authoring.js +0 -166
  138. package/dist/commands/boards/examples.d.ts +0 -10
  139. package/dist/commands/boards/examples.js +0 -118
  140. package/dist/commands/boards.d.ts +0 -13
  141. package/dist/commands/boards.js +0 -836
  142. package/dist/commands/channels.d.ts +0 -2
  143. package/dist/commands/channels.js +0 -74
  144. package/dist/commands/cron-jobs.d.ts +0 -2
  145. package/dist/commands/cron-jobs.js +0 -155
  146. package/dist/commands/decision.d.ts +0 -4
  147. package/dist/commands/decision.js +0 -113
  148. package/dist/commands/desktop.d.ts +0 -10
  149. package/dist/commands/desktop.js +0 -233
  150. package/dist/commands/feedback.d.ts +0 -2
  151. package/dist/commands/feedback.js +0 -131
  152. package/dist/commands/generations.d.ts +0 -2
  153. package/dist/commands/generations.js +0 -427
  154. package/dist/commands/host.d.ts +0 -2
  155. package/dist/commands/host.js +0 -11
  156. package/dist/commands/me.d.ts +0 -2
  157. package/dist/commands/me.js +0 -121
  158. package/dist/commands/models.d.ts +0 -28
  159. package/dist/commands/models.js +0 -271
  160. package/dist/commands/profile.d.ts +0 -2
  161. package/dist/commands/profile.js +0 -81
  162. package/dist/commands/prompts.d.ts +0 -2
  163. package/dist/commands/prompts.js +0 -37
  164. package/dist/commands/public.d.ts +0 -20
  165. package/dist/commands/public.js +0 -291
  166. package/dist/commands/references.d.ts +0 -2
  167. package/dist/commands/references.js +0 -193
  168. package/dist/commands/referrals.d.ts +0 -2
  169. package/dist/commands/referrals.js +0 -88
  170. package/dist/commands/rooms-connect.d.ts +0 -17
  171. package/dist/commands/rooms-connect.js +0 -140
  172. package/dist/commands/rooms-rtc-binary.d.ts +0 -2
  173. package/dist/commands/rooms-rtc-binary.js +0 -107
  174. package/dist/commands/rooms-rtc.d.ts +0 -21
  175. package/dist/commands/rooms-rtc.js +0 -171
  176. package/dist/commands/rooms.d.ts +0 -3
  177. package/dist/commands/rooms.js +0 -277
  178. package/dist/commands/run.d.ts +0 -13
  179. package/dist/commands/run.js +0 -246
  180. package/dist/commands/runtime.d.ts +0 -3
  181. package/dist/commands/runtime.js +0 -320
  182. package/dist/commands/sandboxd-binary.d.ts +0 -11
  183. package/dist/commands/sandboxd-binary.js +0 -238
  184. package/dist/commands/search.d.ts +0 -2
  185. package/dist/commands/search.js +0 -114
  186. package/dist/commands/session-access.d.ts +0 -2
  187. package/dist/commands/session-access.js +0 -70
  188. package/dist/commands/skills.d.ts +0 -2
  189. package/dist/commands/skills.js +0 -34
  190. package/dist/commands/space-activity.d.ts +0 -26
  191. package/dist/commands/space-activity.js +0 -147
  192. package/dist/commands/space-commerce.d.ts +0 -2
  193. package/dist/commands/space-commerce.js +0 -514
  194. package/dist/commands/space-displays.d.ts +0 -2
  195. package/dist/commands/space-displays.js +0 -620
  196. package/dist/commands/space-files.d.ts +0 -5
  197. package/dist/commands/space-files.js +0 -215
  198. package/dist/commands/space-invitations.d.ts +0 -29
  199. package/dist/commands/space-invitations.js +0 -189
  200. package/dist/commands/space-turns.d.ts +0 -49
  201. package/dist/commands/space-turns.js +0 -205
  202. package/dist/commands/space-wallet.d.ts +0 -2
  203. package/dist/commands/space-wallet.js +0 -141
  204. package/dist/commands/space-webhooks.d.ts +0 -7
  205. package/dist/commands/space-webhooks.js +0 -73
  206. package/dist/commands/spaces.d.ts +0 -25
  207. package/dist/commands/spaces.js +0 -2170
  208. package/dist/commands/tasks.d.ts +0 -8
  209. package/dist/commands/tasks.js +0 -80
  210. package/dist/commands/version.d.ts +0 -2
  211. package/dist/commands/version.js +0 -21
  212. package/dist/endpoint-options.d.ts +0 -4
  213. package/dist/endpoint-options.js +0 -26
  214. package/dist/env-proxy.d.ts +0 -5
  215. package/dist/env-proxy.js +0 -20
  216. package/dist/help-path.d.ts +0 -18
  217. package/dist/help-path.js +0 -223
  218. package/dist/host/auth.d.ts +0 -20
  219. package/dist/host/auth.js +0 -119
  220. package/dist/host/login-env.d.ts +0 -1
  221. package/dist/host/login-env.js +0 -31
  222. package/dist/host/runtime.d.ts +0 -35
  223. package/dist/host/runtime.js +0 -395
  224. package/dist/host/runtimes.d.ts +0 -9
  225. package/dist/host/runtimes.js +0 -42
  226. package/dist/host/serve.d.ts +0 -2
  227. package/dist/host/serve.js +0 -117
  228. package/dist/host/workspaces.d.ts +0 -2
  229. package/dist/host/workspaces.js +0 -18
  230. package/dist/http-put.d.ts +0 -25
  231. package/dist/http-put.js +0 -132
  232. package/dist/index.d.ts +0 -2
  233. package/dist/index.js +0 -129
  234. package/dist/launcher.d.ts +0 -4
  235. package/dist/launcher.js +0 -38
  236. package/dist/local-media.d.ts +0 -2
  237. package/dist/local-media.js +0 -30
  238. package/dist/network-error.d.ts +0 -3
  239. package/dist/network-error.js +0 -22
  240. package/dist/output.d.ts +0 -46
  241. package/dist/output.js +0 -244
  242. package/dist/runtime/archive-store.d.ts +0 -54
  243. package/dist/runtime/archive-store.js +0 -379
  244. package/dist/runtime/cli-path.d.ts +0 -5
  245. package/dist/runtime/cli-path.js +0 -27
  246. package/dist/runtime/codex-usage.d.ts +0 -7
  247. package/dist/runtime/codex-usage.js +0 -11
  248. package/dist/runtime/connection.d.ts +0 -42
  249. package/dist/runtime/connection.js +0 -789
  250. package/dist/runtime/diagnostics.d.ts +0 -107
  251. package/dist/runtime/diagnostics.js +0 -392
  252. package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
  253. package/dist/runtime/harnesses/chained-projection.js +0 -95
  254. package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
  255. package/dist/runtime/harnesses/chained-transcript.js +0 -62
  256. package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
  257. package/dist/runtime/harnesses/claude-approval.js +0 -124
  258. package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
  259. package/dist/runtime/harnesses/claude-transcript.js +0 -138
  260. package/dist/runtime/harnesses/claude.d.ts +0 -8
  261. package/dist/runtime/harnesses/claude.js +0 -225
  262. package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
  263. package/dist/runtime/harnesses/codex-approval.js +0 -69
  264. package/dist/runtime/harnesses/codex.d.ts +0 -4
  265. package/dist/runtime/harnesses/codex.js +0 -269
  266. package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
  267. package/dist/runtime/harnesses/cursor-transcript.js +0 -183
  268. package/dist/runtime/harnesses/cursor.d.ts +0 -24
  269. package/dist/runtime/harnesses/cursor.js +0 -620
  270. package/dist/runtime/harnesses/index.d.ts +0 -16
  271. package/dist/runtime/harnesses/index.js +0 -73
  272. package/dist/runtime/harnesses/pi.d.ts +0 -4
  273. package/dist/runtime/harnesses/pi.js +0 -247
  274. package/dist/runtime/harnesses/process.d.ts +0 -31
  275. package/dist/runtime/harnesses/process.js +0 -75
  276. package/dist/runtime/harnesses/stream-json.d.ts +0 -48
  277. package/dist/runtime/harnesses/stream-json.js +0 -336
  278. package/dist/runtime/harnesses/types.d.ts +0 -117
  279. package/dist/runtime/harnesses/types.js +0 -1
  280. package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
  281. package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
  282. package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
  283. package/dist/runtime/harnesses/workbuddy.js +0 -123
  284. package/dist/runtime/instance.d.ts +0 -20
  285. package/dist/runtime/instance.js +0 -247
  286. package/dist/runtime/json-rpc.d.ts +0 -53
  287. package/dist/runtime/json-rpc.js +0 -212
  288. package/dist/runtime/launch.d.ts +0 -25
  289. package/dist/runtime/launch.js +0 -247
  290. package/dist/runtime/local-workspace.d.ts +0 -15
  291. package/dist/runtime/local-workspace.js +0 -52
  292. package/dist/runtime/model-catalog.d.ts +0 -12
  293. package/dist/runtime/model-catalog.js +0 -84
  294. package/dist/runtime/native/adapters.d.ts +0 -15
  295. package/dist/runtime/native/adapters.js +0 -11
  296. package/dist/runtime/native/approvals.d.ts +0 -18
  297. package/dist/runtime/native/approvals.js +0 -54
  298. package/dist/runtime/native/archive.d.ts +0 -19
  299. package/dist/runtime/native/archive.js +0 -142
  300. package/dist/runtime/native/attach.d.ts +0 -36
  301. package/dist/runtime/native/attach.js +0 -128
  302. package/dist/runtime/native/codex-link.d.ts +0 -60
  303. package/dist/runtime/native/codex-link.js +0 -322
  304. package/dist/runtime/native/config.d.ts +0 -16
  305. package/dist/runtime/native/config.js +0 -24
  306. package/dist/runtime/native/daemon.d.ts +0 -92
  307. package/dist/runtime/native/daemon.js +0 -380
  308. package/dist/runtime/native/execution.d.ts +0 -26
  309. package/dist/runtime/native/execution.js +0 -34
  310. package/dist/runtime/native/identity.d.ts +0 -9
  311. package/dist/runtime/native/identity.js +0 -15
  312. package/dist/runtime/native/ingest.d.ts +0 -263
  313. package/dist/runtime/native/ingest.js +0 -884
  314. package/dist/runtime/native/install.d.ts +0 -9
  315. package/dist/runtime/native/install.js +0 -113
  316. package/dist/runtime/native/paths.d.ts +0 -2
  317. package/dist/runtime/native/paths.js +0 -7
  318. package/dist/runtime/native/pi-extension.d.ts +0 -36
  319. package/dist/runtime/native/pi-link.d.ts +0 -69
  320. package/dist/runtime/native/pi-link.js +0 -269
  321. package/dist/runtime/native/results.d.ts +0 -41
  322. package/dist/runtime/native/results.js +0 -128
  323. package/dist/runtime/native/sessions.d.ts +0 -45
  324. package/dist/runtime/native/sessions.js +0 -87
  325. package/dist/runtime/native/transcript.d.ts +0 -89
  326. package/dist/runtime/native/transcript.js +0 -656
  327. package/dist/runtime/native/translate.d.ts +0 -46
  328. package/dist/runtime/native/translate.js +0 -299
  329. package/dist/runtime/native/transport.d.ts +0 -7
  330. package/dist/runtime/native/transport.js +0 -16
  331. package/dist/runtime/native/version.d.ts +0 -5
  332. package/dist/runtime/native/version.js +0 -21
  333. package/dist/runtime/preferences.d.ts +0 -7
  334. package/dist/runtime/preferences.js +0 -22
  335. package/dist/runtime/presentation.d.ts +0 -32
  336. package/dist/runtime/presentation.js +0 -124
  337. package/dist/runtime/process-group.d.ts +0 -5
  338. package/dist/runtime/process-group.js +0 -161
  339. package/dist/runtime/projection-store.d.ts +0 -27
  340. package/dist/runtime/projection-store.js +0 -30
  341. package/dist/runtime/space-binding.d.ts +0 -48
  342. package/dist/runtime/space-binding.js +0 -342
  343. package/dist/runtime/supervisor.d.ts +0 -19
  344. package/dist/runtime/supervisor.js +0 -441
  345. package/dist/runtime/turn-projection.d.ts +0 -41
  346. package/dist/runtime/turn-projection.js +0 -120
  347. package/dist/runtime/worker.d.ts +0 -1
  348. package/dist/safe-remote-image.d.ts +0 -36
  349. package/dist/safe-remote-image.js +0 -191
  350. package/dist/self-update.d.ts +0 -7
  351. package/dist/self-update.js +0 -202
  352. package/dist/session-status.d.ts +0 -10
  353. package/dist/session-status.js +0 -25
  354. package/dist/space-files/limit.d.ts +0 -2
  355. package/dist/space-files/limit.js +0 -16
  356. package/dist/space-files/operands.d.ts +0 -17
  357. package/dist/space-files/operands.js +0 -33
  358. package/dist/space-files/transfer.d.ts +0 -53
  359. package/dist/space-files/transfer.js +0 -297
  360. package/dist/space-files/upload.d.ts +0 -17
  361. package/dist/space-files/upload.js +0 -76
  362. package/dist/space.d.ts +0 -44
  363. package/dist/space.js +0 -192
  364. package/dist/version.d.ts +0 -2
  365. package/dist/version.js +0 -17
  366. package/dist/web.d.ts +0 -1
  367. package/dist/web.js +0 -4
  368. /package/dist/{board-kernel → chunks}/lexer.js +0 -0
@@ -1,2170 +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, sessionArchiveFilter } 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 (archived sessions are hidden by default)")
1423
- .option("--archived", "List only archived sessions")
1424
- .option("--all", "Include archived sessions")
1425
- .option("--json", "Output as JSON")
1426
- .action(async (opts) => {
1427
- const spaceId = await resolveSpace(spacesCmd);
1428
- const client = createClient();
1429
- try {
1430
- const result = await client.space(spaceId).sessions.list({ archived: sessionArchiveFilter(opts) });
1431
- if (jsonRequested(opts))
1432
- return outJson(result);
1433
- if (result.sessions.length === 0) {
1434
- console.log(" (empty)");
1435
- return;
1436
- }
1437
- table(result.sessions, [
1438
- { key: "id", label: "ID" },
1439
- { key: "title", label: "Title" },
1440
- SESSION_STATUS_COLUMN,
1441
- { key: "totalMessages", label: "Messages" },
1442
- { key: "createdAt", label: "Created" },
1443
- ]);
1444
- }
1445
- catch (e) {
1446
- handleHttp(e);
1447
- }
1448
- });
1449
- sessionsCmd
1450
- .command("create [title]")
1451
- .description("Create a session")
1452
- .option("--label <ref>", "Attach a label, e.g. Bug or Area/Frontend", collectOption, [])
1453
- .option("--json", "Output as JSON")
1454
- .action(async (title, opts) => {
1455
- const spaceId = await resolveSpace(spacesCmd);
1456
- const client = createClient();
1457
- try {
1458
- const result = await client.space(spaceId).sessions.create({
1459
- title,
1460
- labelRefs: opts.label?.length ? opts.label : undefined,
1461
- });
1462
- if (jsonRequested(opts))
1463
- return outJson(result);
1464
- ok(`Session created: ${result.session.id}`);
1465
- table([result.session], [
1466
- { key: "id", label: "ID" },
1467
- { key: "title", label: "Title" },
1468
- ]);
1469
- }
1470
- catch (e) {
1471
- handleHttp(e);
1472
- }
1473
- });
1474
- sessionsCmd
1475
- .command("get <id>")
1476
- .description("Session details")
1477
- .option("--json", "Output as JSON")
1478
- .action(async (id, opts) => {
1479
- const spaceId = await resolveSpace(spacesCmd);
1480
- const client = createClient();
1481
- try {
1482
- const result = await client.space(spaceId).session(id).get();
1483
- if (jsonRequested(opts))
1484
- return outJson(result);
1485
- table([result.session], [
1486
- { key: "id", label: "ID" },
1487
- { key: "title", label: "Title" },
1488
- SESSION_STATUS_COLUMN,
1489
- { key: "totalMessages", label: "Messages" },
1490
- { key: "totalToolCalls", label: "Tool Calls" },
1491
- { key: "createdAt", label: "Created" },
1492
- ]);
1493
- }
1494
- catch (e) {
1495
- handleHttp(e);
1496
- }
1497
- });
1498
- sessionsCmd
1499
- .command("stats <id>")
1500
- .description("Session statistics for settled turns (including separate inherited history)")
1501
- .option("--json", "Output as JSON")
1502
- .action(async (id, opts) => {
1503
- const spaceId = await resolveSpace(spacesCmd);
1504
- try {
1505
- const { stats } = await createClient().space(spaceId).session(id).stats();
1506
- if (jsonRequested(opts))
1507
- return outJson({ stats });
1508
- const own = stats.own;
1509
- const rows = [
1510
- { metric: "Turns", value: own.turns },
1511
- { metric: "Model calls", value: own.calls },
1512
- { metric: "Tool calls", value: own.toolCalls },
1513
- { metric: "Compactions", value: own.compactions },
1514
- { metric: "Tokens", value: own.usage?.totalTokens },
1515
- { metric: "Execution time (ms)", value: own.elapsedMs },
1516
- { metric: "Model time (ms)", value: own.modelMs == null ? null : Math.round(own.modelMs) },
1517
- { metric: "Model cost (USD)", value: own.modelCostUsd },
1518
- { metric: "Content generation cost (USD)", value: own.generationCostUsd },
1519
- { metric: "Inherited turns", value: stats.inherited.turns },
1520
- ].filter((row) => row.value != null);
1521
- table(rows, [{ key: "metric", label: "Metric" }, { key: "value", label: "Value" }]);
1522
- if (own.partial)
1523
- console.log("Some execution details were not recorded.");
1524
- }
1525
- catch (e) {
1526
- handleHttp(e);
1527
- }
1528
- });
1529
- sessionsCmd
1530
- .command("files <id>")
1531
- .description("List Space files changed by a session")
1532
- .option("--limit <n>", "Maximum files to list; the server caps it", "200")
1533
- .option("--json", "Output as JSON")
1534
- .action(async (id, opts) => {
1535
- const spaceId = await resolveSpace(spacesCmd);
1536
- const limit = Number.parseInt(opts.limit, 10);
1537
- if (!Number.isInteger(limit) || limit < 1) {
1538
- return error("Invalid limit", "--limit must be a positive integer");
1539
- }
1540
- const client = createClient();
1541
- try {
1542
- const result = await client.space(spaceId).session(id).files({ limit });
1543
- if (jsonRequested(opts))
1544
- return outJson(result);
1545
- if (result.files.length === 0) {
1546
- console.log(" (empty)");
1547
- return;
1548
- }
1549
- table(result.files.map((file) => ({
1550
- path: file.path,
1551
- change: file.lastKind,
1552
- count: file.changeCount,
1553
- turn: file.lastTurnSequence,
1554
- changedAt: file.lastChangedAt,
1555
- })), [
1556
- { key: "path", label: "Path" },
1557
- { key: "change", label: "Change" },
1558
- { key: "count", label: "Count" },
1559
- { key: "turn", label: "Turn" },
1560
- { key: "changedAt", label: "Changed" },
1561
- ]);
1562
- }
1563
- catch (e) {
1564
- handleHttp(e);
1565
- }
1566
- });
1567
- sessionsCmd
1568
- .command("rename <id> <name>")
1569
- .description("Rename a session")
1570
- .action(async (id, name) => {
1571
- const spaceId = await resolveSpace(spacesCmd);
1572
- const client = createClient();
1573
- try {
1574
- await client.space(spaceId).session(id).rename(name);
1575
- ok(`Session renamed to "${name}"`);
1576
- }
1577
- catch (e) {
1578
- handleHttp(e);
1579
- }
1580
- });
1581
- for (const archived of [true, false]) {
1582
- const verb = archived ? "archive" : "unarchive";
1583
- const done = archived ? "archived" : "restored";
1584
- sessionsCmd
1585
- .command(`${verb} <ids...>`)
1586
- .description(archived
1587
- ? "Archive sessions for every member; a new message restores them"
1588
- : "Restore archived sessions to the active list")
1589
- .option("--json", "Output as JSON")
1590
- .action(async (ids, opts) => {
1591
- const spaceId = await resolveSpace(spacesCmd);
1592
- const client = createClient();
1593
- const sessions = [];
1594
- for (const id of ids) {
1595
- try {
1596
- const session = client.space(spaceId).session(id.trim());
1597
- sessions.push((await (archived ? session.archive() : session.unarchive())).session);
1598
- }
1599
- catch (e) {
1600
- if (sessions.length > 0)
1601
- process.stderr.write(`\n ${sessions.length} of ${ids.length} sessions ${done} before ${id}\n`);
1602
- handleHttp(e);
1603
- }
1604
- }
1605
- if (jsonRequested(opts))
1606
- return outJson({ sessions });
1607
- ok(ids.length === 1 ? `Session ${done}` : `${ids.length} sessions ${done}`);
1608
- });
1609
- }
1610
- // ── sessions tail ──
1611
- sessionsCmd
1612
- .command("tail <id>")
1613
- .description("Stream realtime session events")
1614
- .option("--json", "Output as JSON")
1615
- .action(async (id, opts) => {
1616
- const spaceId = await resolveSpace(spacesCmd);
1617
- const client = createClient();
1618
- const session = client.space(spaceId).session(id);
1619
- process.stdout.write(" Listening for events...\n\n");
1620
- let lastAppendPath = null;
1621
- session.on("turn.patch", (e) => {
1622
- if (jsonRequested(opts)) {
1623
- console.log(JSON.stringify(e));
1624
- }
1625
- else {
1626
- const ops = e.payload?.ops;
1627
- for (const op of ops ?? []) {
1628
- if (op.o === "append" && typeof op.v === "string" && op.p?.endsWith("/text")) {
1629
- lastAppendPath = op.p;
1630
- process.stdout.write(op.v);
1631
- continue;
1632
- }
1633
- if (op.o === "append" && typeof op.p === "string") {
1634
- lastAppendPath = op.p;
1635
- continue;
1636
- }
1637
- if (!op.o && !op.p && typeof op.v === "string" && lastAppendPath?.endsWith("/text")) {
1638
- process.stdout.write(op.v);
1639
- }
1640
- }
1641
- }
1642
- });
1643
- session.on("turn.finalized", () => {
1644
- process.stdout.write("\n\n ✓ Done\n");
1645
- process.exit(0);
1646
- });
1647
- session.on("turn.error", (e) => {
1648
- process.stderr.write(`\n ✗ Error\n`);
1649
- if (jsonRequested(opts))
1650
- process.stderr.write(`${JSON.stringify(e)}\n`);
1651
- process.exit(1);
1652
- });
1653
- });
1654
- // ── sessions turns ──
1655
- registerTurns(sessionsCmd);
1656
- // ── sessions access ──
1657
- registerSessionAccess(sessionsCmd);
1658
- }
1659
- // ── Turn operations ──
1660
- function registerTurns(sessionsCmd) {
1661
- const turnsCmd = sessionsCmd.command("turns").description("Inspect session turns");
1662
- turnsCmd
1663
- .command("ls <sessionId>")
1664
- .alias("list")
1665
- .description("List recent turns")
1666
- .option("--cursor <sequence>", "Turn sequence cursor")
1667
- .option("--direction <older|newer>", "Page direction", "older")
1668
- .option("--limit <n>", "Page size", "30")
1669
- .option("--json", "Output as JSON")
1670
- .action(async (sessionId, opts) => {
1671
- const spaceId = await resolveSpace(sessionsCmd);
1672
- const client = createClient();
1673
- try {
1674
- const result = await client.space(spaceId).session(sessionId).turns.listPaginated({
1675
- cursor: opts.cursor === undefined ? undefined : parseInteger(opts.cursor, "cursor", { min: 0 }),
1676
- direction: parseChoice(opts.direction ?? "older", "direction", ["older", "newer"]),
1677
- limit: parseInteger(opts.limit ?? "30", "limit", { min: 1, max: 100 }),
1678
- });
1679
- if (jsonRequested(opts))
1680
- return outJson(result);
1681
- if (result.turns.length === 0)
1682
- return console.log(" No turns found");
1683
- table(result.turns, [
1684
- { key: "sequence", label: "Seq" },
1685
- { key: "id", label: "ID" },
1686
- { key: "status", label: "Status" },
1687
- { key: "userText", label: "User" },
1688
- { key: "assistantText", label: "Assistant" },
1689
- { key: "updatedAt", label: "Updated" },
1690
- ]);
1691
- if (result.hasMore)
1692
- console.log(`\n More turns available — next cursor: ${result.nextCursor}`);
1693
- }
1694
- catch (e) {
1695
- handleHttp(e);
1696
- }
1697
- });
1698
- turnsCmd
1699
- .command("get <sessionId> <turnId>")
1700
- .description("Show turn details")
1701
- .option("--json", "Output as JSON")
1702
- .action(async (sessionId, turnId, opts) => {
1703
- const spaceId = await resolveSpace(sessionsCmd);
1704
- const client = createClient();
1705
- try {
1706
- const result = await client.space(spaceId).session(sessionId).turns.get(turnId);
1707
- if (jsonRequested(opts))
1708
- return outJson(result);
1709
- table([result.turn], [
1710
- { key: "sequence", label: "Seq" },
1711
- { key: "id", label: "ID" },
1712
- { key: "status", label: "Status" },
1713
- { key: "provider", label: "Provider" },
1714
- { key: "model", label: "Model" },
1715
- { key: "stopReason", label: "Stop" },
1716
- { key: "errorMessage", label: "Error" },
1717
- ]);
1718
- if (result.turn.summary?.reason === "billing")
1719
- console.log("\nStopped: insufficient balance. Manage billing at your Cohub account settings.");
1720
- const origin = readSessionTurnOrigin(result.turn.meta, spaceId);
1721
- if (origin)
1722
- console.log(`\nOrigin (${origin.kind}): space=${origin.spaceId} session=${origin.sessionId} turn=${origin.turnId}${origin.toolCallId ? ` toolCall=${origin.toolCallId}` : ""}`);
1723
- const sent = readSentTurns(result.turn.meta);
1724
- if (sent.length > 0) {
1725
- console.log(`\nSent (${sent.length}):`);
1726
- for (const ref of sent)
1727
- console.log(` ${ref.spaceId ? `space=${ref.spaceId} ` : ""}session=${ref.sessionId} turn=${ref.turnId}${ref.toolCallId ? ` toolCall=${ref.toolCallId}` : ""}`);
1728
- }
1729
- if (result.turn.userText)
1730
- console.log(`\nUser:\n${result.turn.userText}`);
1731
- if (result.turn.assistantText)
1732
- console.log(`\nAssistant:\n${result.turn.assistantText}`);
1733
- }
1734
- catch (e) {
1735
- handleHttp(e);
1736
- }
1737
- });
1738
- turnsCmd
1739
- .command("steer <sessionId> <turnId>")
1740
- .description("Run a queued follow-up now")
1741
- .option("--json", "Output as JSON")
1742
- .action(async (sessionId, turnId, opts) => {
1743
- const spaceId = await resolveSpace(sessionsCmd);
1744
- const client = createClient();
1745
- try {
1746
- const result = await client.space(spaceId).session(sessionId).steerTurn(turnId);
1747
- if (jsonRequested(opts))
1748
- return outJson(result);
1749
- ok(`Turn steered: ${result.turn.id}`);
1750
- }
1751
- catch (e) {
1752
- handleHttp(e);
1753
- }
1754
- });
1755
- turnsCmd
1756
- .command("cancel <sessionId> <turnId>")
1757
- .description("Cancel a queued follow-up")
1758
- .option("--json", "Output as JSON")
1759
- .action(async (sessionId, turnId, opts) => {
1760
- const spaceId = await resolveSpace(sessionsCmd);
1761
- const client = createClient();
1762
- try {
1763
- const result = await client.space(spaceId).session(sessionId).cancelTurn(turnId);
1764
- if (jsonRequested(opts))
1765
- return outJson(result);
1766
- ok(`Turn cancelled: ${result.turn.id}`);
1767
- }
1768
- catch (e) {
1769
- handleHttp(e);
1770
- }
1771
- });
1772
- turnsCmd
1773
- .command("index <sessionId>", { hidden: true })
1774
- .description("List lightweight turn index")
1775
- .option("--cursor <sequence>", "Turn sequence cursor")
1776
- .option("--limit <n>", "Page size", "100")
1777
- .option("--json", "Output as JSON")
1778
- .action(async (sessionId, opts) => {
1779
- const spaceId = await resolveSpace(sessionsCmd);
1780
- const client = createClient();
1781
- try {
1782
- const result = await client.space(spaceId).session(sessionId).turns.index({
1783
- cursor: opts.cursor === undefined ? undefined : parseInteger(opts.cursor, "cursor", { min: 0 }),
1784
- limit: parseInteger(opts.limit ?? "100", "limit", { min: 1, max: 500 }),
1785
- });
1786
- if (jsonRequested(opts))
1787
- return outJson(result);
1788
- if (result.turns.length === 0)
1789
- return console.log(" No turns found");
1790
- table(result.turns, [
1791
- { key: "sequence", label: "Seq" },
1792
- { key: "id", label: "ID" },
1793
- { key: "status", label: "Status" },
1794
- { key: "userPreview", label: "User" },
1795
- { key: "assistantPreview", label: "Assistant" },
1796
- ]);
1797
- if (result.hasMore)
1798
- console.log(`\n More turns available — next cursor: ${result.nextCursor}`);
1799
- }
1800
- catch (e) {
1801
- handleHttp(e);
1802
- }
1803
- });
1804
- turnsCmd
1805
- .command("window <sessionId>", { hidden: true })
1806
- .description("Load turns around a sequence or turn ID")
1807
- .option("--sequence <n>", "Anchor turn sequence")
1808
- .option("--turn <id>", "Anchor turn ID")
1809
- .option("--before <n>", "Turns before anchor", "10")
1810
- .option("--after <n>", "Turns after anchor", "20")
1811
- .option("--json", "Output as JSON")
1812
- .action(async (sessionId, opts) => {
1813
- const spaceId = await resolveSpace(sessionsCmd);
1814
- if (!opts.sequence && !opts.turn)
1815
- return error("Missing anchor", "Use --sequence <n> or --turn <id>");
1816
- const client = createClient();
1817
- try {
1818
- const result = await client.space(spaceId).session(sessionId).turns.window({
1819
- sequence: opts.sequence === undefined ? undefined : parseInteger(opts.sequence, "sequence", { min: 0 }),
1820
- turnId: opts.turn,
1821
- before: parseInteger(opts.before ?? "10", "before", { min: 0, max: 200 }),
1822
- after: parseInteger(opts.after ?? "20", "after", { min: 0, max: 200 }),
1823
- });
1824
- if (jsonRequested(opts))
1825
- return outJson(result);
1826
- if (result.turns.length === 0)
1827
- return console.log(" No turns found");
1828
- table(result.turns, [
1829
- { key: "sequence", label: "Seq" },
1830
- { key: "id", label: "ID" },
1831
- { key: "status", label: "Status" },
1832
- { key: "userText", label: "User" },
1833
- { key: "assistantText", label: "Assistant" },
1834
- ]);
1835
- console.log(`\n Window — older: ${result.hasMoreOlder ? "yes" : "no"}, newer: ${result.hasMoreNewer ? "yes" : "no"}`);
1836
- }
1837
- catch (e) {
1838
- handleHttp(e);
1839
- }
1840
- });
1841
- }
1842
- // ── Session access operations ──
1843
- function registerSessionAccess(sessionsCmd) {
1844
- const accessCmd = sessionsCmd.command("access").description("Session access control");
1845
- accessCmd
1846
- .command("get <id>")
1847
- .description("Get session access policy")
1848
- .option("--json", "Output as JSON")
1849
- .action(async (id, opts) => {
1850
- const client = createClient();
1851
- try {
1852
- const policy = await client.sessionAccess.get(id);
1853
- if (jsonRequested(opts))
1854
- return outJson(policy);
1855
- table([policy], [
1856
- { key: "signed_in_user", label: "Signed-in" },
1857
- { key: "anonymous_user", label: "Anonymous" },
1858
- ]);
1859
- }
1860
- catch (e) {
1861
- handleHttp(e);
1862
- }
1863
- });
1864
- accessCmd
1865
- .command("set <id>")
1866
- .description("Set session anonymous access")
1867
- .option("--anonymous <role>", "Anonymous role (host|builder|guest|null)")
1868
- .option("--json", "Output as JSON")
1869
- .action(async (id, opts) => {
1870
- const client = createClient();
1871
- try {
1872
- const policy = await client.sessionAccess.set(id, {
1873
- anonymous_user: parseNullableRole(opts.anonymous, "anonymous role"),
1874
- });
1875
- if (jsonRequested(opts))
1876
- return outJson(policy);
1877
- ok("Session access updated");
1878
- table([policy], [
1879
- { key: "signed_in_user", label: "Signed-in" },
1880
- { key: "anonymous_user", label: "Anonymous" },
1881
- ]);
1882
- }
1883
- catch (e) {
1884
- handleHttp(e);
1885
- }
1886
- });
1887
- accessCmd
1888
- .command("remove <id>")
1889
- .description("Remove session access override")
1890
- .action(async (id) => {
1891
- const client = createClient();
1892
- try {
1893
- await client.sessionAccess.remove(id);
1894
- ok(`Session access override removed: ${id}`);
1895
- }
1896
- catch (e) {
1897
- handleHttp(e);
1898
- }
1899
- });
1900
- }
1901
- // ── Member operations ──
1902
- function registerMembers(spacesCmd) {
1903
- const memCmd = spacesCmd
1904
- .command("members")
1905
- .description("Member management")
1906
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1907
- memCmd
1908
- .command("ls")
1909
- .alias("list")
1910
- .description("List space members")
1911
- .option("--json", "Output as JSON")
1912
- .action(async (opts) => {
1913
- const spaceId = await resolveSpace(spacesCmd);
1914
- const client = createClient();
1915
- try {
1916
- const result = await client.space(spaceId).members.list();
1917
- if (jsonRequested(opts))
1918
- return outJson(result);
1919
- if (result.items.length === 0) {
1920
- console.log(" (empty)");
1921
- return;
1922
- }
1923
- table(result.items, [
1924
- { key: "userId", label: "User ID" },
1925
- { key: "role", label: "Role" },
1926
- { key: "createdAt", label: "Since" },
1927
- ]);
1928
- }
1929
- catch (e) {
1930
- handleHttp(e);
1931
- }
1932
- });
1933
- memCmd
1934
- .command("update <userId> <role>")
1935
- .description("Change member role (host | builder | guest)")
1936
- .action(async (userId, role) => {
1937
- const spaceId = await resolveSpace(spacesCmd);
1938
- const client = createClient();
1939
- try {
1940
- await client.space(spaceId).members.update(userId, parseChoice(role, "role", SPACE_ROLES));
1941
- ok(`${userId} → ${role}`);
1942
- }
1943
- catch (e) {
1944
- handleHttp(e);
1945
- }
1946
- });
1947
- memCmd
1948
- .command("remove <userId>")
1949
- .description("Remove a member")
1950
- .action(async (userId) => {
1951
- const spaceId = await resolveSpace(spacesCmd);
1952
- const client = createClient();
1953
- try {
1954
- await client.space(spaceId).members.remove(userId);
1955
- ok(`${userId} removed`);
1956
- }
1957
- catch (e) {
1958
- handleHttp(e);
1959
- }
1960
- });
1961
- }
1962
- // ── Access control ──
1963
- const ACCESS_COLUMNS = [
1964
- { key: "signed_in_user", label: "Signed-in" },
1965
- { key: "anonymous_user", label: "Anonymous" },
1966
- ];
1967
- function registerAccess(spacesCmd) {
1968
- const accCmd = spacesCmd
1969
- .command("access")
1970
- .description("Access control")
1971
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
1972
- accCmd
1973
- .command("get")
1974
- .description("Get access policy")
1975
- .option("--json", "Output as JSON")
1976
- .action(async (opts) => {
1977
- const spaceId = await resolveSpace(spacesCmd);
1978
- const client = createClient();
1979
- try {
1980
- const policy = await client.space(spaceId).access.get();
1981
- if (jsonRequested(opts))
1982
- return outJson(policy);
1983
- table([policy], ACCESS_COLUMNS);
1984
- }
1985
- catch (e) {
1986
- handleHttp(e);
1987
- }
1988
- });
1989
- accCmd
1990
- .command("set")
1991
- .description("Set access policy; omitted options stay unchanged")
1992
- .option("--signed-in <role>", "Role for signed-in users (builder|guest|null)")
1993
- .option("--anonymous <role>", "Role for anonymous users (guest|null)")
1994
- .option("--json", "Output as JSON")
1995
- .action(async (opts) => {
1996
- const spaceId = await resolveSpace(spacesCmd);
1997
- const client = createClient();
1998
- if (opts.signedIn === undefined && opts.anonymous === undefined) {
1999
- return error("Nothing to update", "Pass --signed-in or --anonymous");
2000
- }
2001
- try {
2002
- const policy = await client.space(spaceId).access.set({
2003
- ...(opts.signedIn !== undefined ? { signed_in_user: parseNullableRole(opts.signedIn, "signed-in role") } : {}),
2004
- ...(opts.anonymous !== undefined ? { anonymous_user: parseNullableRole(opts.anonymous, "anonymous role") } : {}),
2005
- });
2006
- if (jsonRequested(opts))
2007
- return outJson(policy);
2008
- ok("Access policy updated");
2009
- table([policy], ACCESS_COLUMNS);
2010
- }
2011
- catch (e) {
2012
- handleHttp(e);
2013
- }
2014
- });
2015
- }
2016
- // ── Checkpoint operations ──
2017
- function registerCheckpoints(spacesCmd) {
2018
- const cpCmd = spacesCmd
2019
- .command("checkpoints")
2020
- .description("Checkpoint management")
2021
- .hook("preAction", async () => { await resolveSpace(spacesCmd); });
2022
- cpCmd
2023
- .command("ls")
2024
- .alias("list")
2025
- .description("List checkpoints")
2026
- .option("--limit <n>", "Maximum checkpoints to return", (value) => Number(value))
2027
- .option("--cursor <cursor>", "Pagination cursor")
2028
- .option("--json", "Output as JSON")
2029
- .action(async (opts) => {
2030
- const spaceId = await resolveSpace(spacesCmd);
2031
- const client = createClient();
2032
- try {
2033
- const result = await client.space(spaceId).checkpoints.list({
2034
- limit: opts.limit,
2035
- cursor: opts.cursor,
2036
- });
2037
- if (jsonRequested(opts))
2038
- return outJson(result);
2039
- if (result.checkpoints.length === 0) {
2040
- console.log(" (empty)");
2041
- return;
2042
- }
2043
- table(result.checkpoints, [
2044
- { key: "id", label: "ID" },
2045
- { key: "commitHash", label: "Commit" },
2046
- { key: "description", label: "Description" },
2047
- { key: "createdAt", label: "Created" },
2048
- ]);
2049
- }
2050
- catch (e) {
2051
- handleHttp(e);
2052
- }
2053
- });
2054
- cpCmd
2055
- .command("get <id>")
2056
- .description("Checkpoint details")
2057
- .option("--json", "Output as JSON")
2058
- .action(async (id, opts) => {
2059
- const spaceId = await resolveSpace(spacesCmd);
2060
- const client = createClient();
2061
- try {
2062
- const result = await client.space(spaceId).checkpoints.get(id);
2063
- if (jsonRequested(opts))
2064
- return outJson(result);
2065
- table([result.checkpoint], [
2066
- { key: "id", label: "ID" },
2067
- { key: "commitHash", label: "Commit" },
2068
- { key: "description", label: "Description" },
2069
- { key: "forkCount", label: "Forks" },
2070
- { key: "createdAt", label: "Created" },
2071
- ]);
2072
- }
2073
- catch (e) {
2074
- handleHttp(e);
2075
- }
2076
- });
2077
- cpCmd
2078
- .command("create [description]")
2079
- .description("Create a checkpoint")
2080
- .option("--json", "Output as JSON")
2081
- .action(async (description, opts) => {
2082
- const spaceId = await resolveSpace(spacesCmd);
2083
- const client = createClient();
2084
- try {
2085
- const result = await client.space(spaceId).checkpoints.create(description ?? null);
2086
- if (jsonRequested(opts))
2087
- return outJson(result);
2088
- ok(`Checkpoint created — taskRunId: ${result.taskRunId}`);
2089
- }
2090
- catch (e) {
2091
- handleHttp(e);
2092
- }
2093
- });
2094
- cpCmd
2095
- .command("ls-tree <checkpointId> [path]")
2096
- .description("List checkpoint tree")
2097
- .option("--json", "Output as JSON")
2098
- .action(async (checkpointId, path, opts) => {
2099
- const spaceId = await resolveSpace(spacesCmd);
2100
- const client = createClient();
2101
- try {
2102
- const tree = await client.space(spaceId).checkpoints(checkpointId).files.list(path ?? "");
2103
- if (jsonRequested(opts))
2104
- return outJson(tree);
2105
- if (tree.entries.length === 0) {
2106
- console.log(" (empty)");
2107
- return;
2108
- }
2109
- table(tree.entries, [
2110
- { key: "name", label: "Name" },
2111
- { key: "type", label: "Type" },
2112
- { key: "size", label: "Size" },
2113
- { key: "mimeType", label: "MIME" },
2114
- { key: "mtimeMs", label: "Modified", format: formatEpochMs },
2115
- ]);
2116
- }
2117
- catch (e) {
2118
- handleHttp(e);
2119
- }
2120
- });
2121
- cpCmd
2122
- .command("show <checkpointId> <path>")
2123
- .description("Show checkpoint file content")
2124
- .option("--json", "Output as JSON")
2125
- .action(async (checkpointId, path, opts) => {
2126
- const spaceId = await resolveSpace(spacesCmd);
2127
- const client = createClient();
2128
- try {
2129
- const file = await client.space(spaceId).checkpoints(checkpointId).files.read(path);
2130
- if (jsonRequested(opts))
2131
- return outJson(file);
2132
- if (file.delivery === "url" && file.url) {
2133
- console.log(file.url);
2134
- return;
2135
- }
2136
- console.log(file.content);
2137
- }
2138
- catch (e) {
2139
- handleHttp(e);
2140
- }
2141
- });
2142
- cpCmd
2143
- .command("diff <checkpointId> [path]")
2144
- .description("Show checkpoint diff vs parent (or --base)")
2145
- .option("--base <checkpointId>", "Compare against another checkpoint")
2146
- .option("--json", "Output as JSON")
2147
- .action(async (checkpointId, path, opts) => {
2148
- const spaceId = await resolveSpace(spacesCmd);
2149
- const client = createClient();
2150
- try {
2151
- if (path) {
2152
- const file = await client.space(spaceId).checkpoints(checkpointId).diff.file(path, { base: opts.base ?? null });
2153
- if (jsonRequested(opts))
2154
- return outJson(file);
2155
- printDiffFile(file);
2156
- return;
2157
- }
2158
- const summary = await client.space(spaceId).checkpoints(checkpointId).diff.summary({ base: opts.base ?? null });
2159
- if (jsonRequested(opts))
2160
- return outJson(summary);
2161
- printDiffSummary(summary, {
2162
- emptyLabel: " (no changes)",
2163
- footer: summary.truncated ? " … truncated" : null,
2164
- });
2165
- }
2166
- catch (e) {
2167
- handleHttp(e);
2168
- }
2169
- });
2170
- }