@chroxy/server 0.10.0 → 0.11.10

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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,804 @@
1
+ /**
2
+ * `chroxy schedule` — CRUD against the persisted scheduled-task registry
3
+ * (#6868, consumer slice of epic #6784).
4
+ *
5
+ * This CLI operates purely on the on-disk registry (#6862,
6
+ * `scheduled-task-store.js`) via the store's own API — it never hand-writes
7
+ * the JSON file, and it never re-implements cadence parsing: every cadence
8
+ * (`--at` / `--cron`) is validated by the store, which itself calls
9
+ * `schedule-parser.js`'s `parseCron`/`computeNextRun`. Nothing here requires
10
+ * the headless engine (#6865, `scheduler.js`) to be running — create/list/
11
+ * edit/pause/resume/delete/last-run all just read and write the registry
12
+ * file.
13
+ *
14
+ * What IS reused from the engine, deliberately (rather than re-derived), is
15
+ * its judgment about whether a task can actually fire:
16
+ * - `scheduledProviderRefusalReason` — the exact "will this provider be
17
+ * refused?" check `scheduler.js` runs before every fire. A task whose
18
+ * target provider has no in-process permission answering (including the
19
+ * daemon DEFAULT `claude-tui`) gets a clear warning at create/edit time
20
+ * instead of silently sitting dead until an operator notices `refused`
21
+ * outcomes days later.
22
+ * - `resolveScheduledPermissionMode` — the exact clamp the engine applies
23
+ * per fire. A task that asks for a permission mode above `approve`/`plan`
24
+ * is warned that it will be silently de-escalated, not rejected (the
25
+ * store itself allows any `ALLOWED_PERMISSION_MODE_IDS` value — only the
26
+ * engine's floor is stricter).
27
+ * - `isSchedulerEnabled` — the same default-off gate the daemon checks.
28
+ * `create`/`edit` still succeed with the gate closed (the task is a
29
+ * legitimate standing definition even before the operator opts in), but
30
+ * say plainly that nothing will fire yet.
31
+ *
32
+ * `list` and `last-run` render a task's `lastRun` status verbatim (never
33
+ * papered over): `refused` and a best-effort-persisted quarantine message
34
+ * both show up as an unhealthy `[REFUSED]`/`[ERROR]` tag, a deliberately
35
+ * stopped run shows `[INTERRUPTED]` rather than borrowing the crash tag
36
+ * (#7038), and a task that has never fired is always labelled `[NEVER RUN]`
37
+ * rather than left blank — nothing here is allowed to *look* healthy when it
38
+ * isn't, and nothing is allowed to look BROKEN when it merely stopped.
39
+ */
40
+ import { existsSync, readFileSync } from 'fs'
41
+ import { join } from 'path'
42
+ import { configDir, configFile } from './shared.js'
43
+ import {
44
+ ScheduledTaskStore,
45
+ ScheduledTaskValidationError,
46
+ defaultScheduledTasksPath,
47
+ } from '../scheduled-task-store.js'
48
+ import { isSchedulerEnabled, mergeConfig } from '../config.js'
49
+ import { scheduledProviderRefusalReason, resolveScheduledPermissionMode } from '../scheduler.js'
50
+ import { resolveDaemonDefaultProvider } from '../providers.js'
51
+
52
+ // -- default wiring (production) ---------------------------------------------
53
+
54
+ /** Read config.json best-effort — never throws, never exits (mirrors worktree-gc-cmd.js). */
55
+ function readConfigSoft(configPath) {
56
+ try {
57
+ if (!existsSync(configPath)) return {}
58
+ return JSON.parse(readFileSync(configPath, 'utf-8')) || {}
59
+ } catch {
60
+ return {}
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The registry file THIS DAEMON would load — a sibling of session-state.json.
66
+ *
67
+ * Rooted at `configDir()` (shared.js), which is `$CHROXY_CONFIG_DIR` when set
68
+ * and `~/.chroxy` otherwise — because that is what the daemon's own registry
69
+ * path now resolves to at every hop:
70
+ *
71
+ * 1. `server-cli.js` constructs its `SessionManager` withOUT a
72
+ * `stateFilePath` (the string does not appear in that file at all), so the
73
+ * manager falls back to `session-manager.js`'s `defaultStateFile()` =
74
+ * `configPath('session-state.json')`.
75
+ * 2. `session-manager.js` then derives `this.scheduledTaskStore` from that
76
+ * path via `defaultScheduledTasksPath()` — i.e. the live scheduler
77
+ * (#6865) reads `<config dir>/scheduled-tasks.json`.
78
+ *
79
+ * The rule this resolver actually obeys is *match the daemon*, not *match the
80
+ * convention*. Those pointed in opposite directions until #7052: the
81
+ * session-state family was hardcoded to `~/.chroxy` while models.js,
82
+ * connection-info.js and doctor.js honoured the env var, and following the
83
+ * convention here would have aimed the CLI at a file the running scheduler
84
+ * never opens — `schedule create` printing "Created scheduled task …" for a
85
+ * task that can never fire, while `schedule list` showed an empty registry.
86
+ * #7052 moved the WRITERS onto `configDir()`, so the two agree now and this
87
+ * resolver follows the daemon by following the env var. If they ever diverge
88
+ * again, the daemon wins.
89
+ *
90
+ * The same reasoning applies to `configFile()` below: `server-cli-child.js`
91
+ * reads `configPath('config.json')`, so resolving config the same way is what
92
+ * makes `config.provider` / `features.scheduler` here agree with what the
93
+ * daemon resolved.
94
+ *
95
+ * Pinned from both sides by tests: a spawn test asserts the registry follows
96
+ * `CHROXY_CONFIG_DIR` end-to-end and falls back to `$HOME/.chroxy` without it
97
+ * (tests/cli/schedule-cmd.test.js), and a drift guard asserts the CLI and
98
+ * `defaultStateFile()` land on the same registry under a relocated root
99
+ * (tests/schedule-cli.test.js). If the daemon's resolution moves again, the
100
+ * drift guard goes red and this resolver must move with it.
101
+ */
102
+ export function defaultScheduleRegistryPath() {
103
+ return defaultScheduledTasksPath(join(configDir(), 'session-state.json'))
104
+ }
105
+
106
+ function getDefaultStore() {
107
+ const store = new ScheduledTaskStore({ filePath: defaultScheduleRegistryPath() })
108
+ store.load()
109
+ return store
110
+ }
111
+
112
+ /**
113
+ * Build the dependency bag every exported command function runs against.
114
+ * Every dependency is overridable so tests never touch the real
115
+ * `~/.chroxy/` tree and never need a live provider registry or config file —
116
+ * see tests/schedule-cli.test.js.
117
+ */
118
+ function buildDeps(overrides = {}) {
119
+ const config = readConfigSoft(configFile())
120
+ return {
121
+ store: overrides.store || getDefaultStore(),
122
+ write: overrides.write || console.log,
123
+ // The provider a task would ACTUALLY run against when none is set
124
+ // explicitly — must mirror the daemon's own resolution EXACTLY, including
125
+ // the ENV tier (`CHROXY_PROVIDER`, as set by the Docker image for
126
+ // example). #8189: this used to be hand-derived as `config.provider ||
127
+ // DEFAULT_PROVIDER` over the raw `readConfigSoft` result above, which
128
+ // skipped ENV entirely — the same defect class #8177 fixed in `chroxy
129
+ // doctor` (round-2 Critical 2). Routed through the SAME shared pipeline
130
+ // `chroxy start`/`chroxy doctor` use — `mergeConfig` (config.js) resolves
131
+ // CLI > ENV > file > default (including the `legacyCli` → `claude-cli`
132
+ // mapping), then `resolveDaemonDefaultProvider` (providers.js) reads
133
+ // `merged.provider` — so this can't drift from the real daemon default
134
+ // again without touching code every one of those paths shares. `config`
135
+ // here is fed in as the FILE tier only; there is no CLI tier for this
136
+ // value (an explicit `overrides.defaultProviderName`, when present, wins
137
+ // outright and never reaches mergeConfig at all).
138
+ defaultProviderName: overrides.defaultProviderName
139
+ || resolveDaemonDefaultProvider(mergeConfig({ fileConfig: config })),
140
+ checkProviderRefusal: overrides.checkProviderRefusal || ((name) => scheduledProviderRefusalReason(name)),
141
+ resolvePermissionMode: overrides.resolvePermissionMode || resolveScheduledPermissionMode,
142
+ checkSchedulerEnabled: overrides.checkSchedulerEnabled || (() => isSchedulerEnabled(config)),
143
+ }
144
+ }
145
+
146
+ // -- formatting helpers --------------------------------------------------
147
+
148
+ /** Deterministic UTC rendering (no locale/timezone dependence) — easy to test, unambiguous to read. */
149
+ function formatEpoch(ms) {
150
+ if (!Number.isFinite(ms)) return '—'
151
+ return new Date(ms).toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, 'Z')
152
+ }
153
+
154
+ function formatDurationMs(ms) {
155
+ if (!Number.isFinite(ms) || ms < 0) return 'unknown'
156
+ const sec = Math.floor(ms / 1000)
157
+ if (sec < 60) return `${sec}s`
158
+ const min = Math.floor(sec / 60)
159
+ if (min < 60) return `${min}m`
160
+ const hr = Math.floor(min / 60)
161
+ if (hr < 24) return `${hr}h`
162
+ return `${Math.floor(hr / 24)}d`
163
+ }
164
+
165
+ function describeCadence(cadence) {
166
+ if (!cadence || typeof cadence !== 'object') return '(invalid cadence)'
167
+ switch (cadence.kind) {
168
+ case 'once':
169
+ return `once @ ${formatEpoch(cadence.at)}`
170
+ case 'interval':
171
+ return `every ${formatDurationMs(cadence.everyMs)}`
172
+ case 'cron':
173
+ return `cron "${cadence.expression}"`
174
+ default:
175
+ return `(unknown cadence: ${cadence.kind})`
176
+ }
177
+ }
178
+
179
+ /**
180
+ * A task's honest at-a-glance health. `PAUSED` takes priority (an operator
181
+ * turned it off on purpose); otherwise a task that has never fired is always
182
+ * `NEVER RUN` — never blank, never mistaken for healthy — and every recorded
183
+ * `lastRun.status` maps to its own tag so `refused` (and a best-effort
184
+ * quarantine write, which persists as `refused`) is never confused with
185
+ * `success`, and `interrupted` (#7038 — a deliberate Stop) is never confused
186
+ * with `error`.
187
+ *
188
+ * Kept byte-for-byte in step with `deriveScheduledTaskHealthTag` in
189
+ * @chroxy/protocol; `tests/scheduled-task-health-parity.test.js` fails if a
190
+ * status the shared helper tags by name falls through to `default:` here.
191
+ */
192
+ function healthTag(task) {
193
+ if (!task.enabled) return 'PAUSED'
194
+ if (!task.lastRun) return 'NEVER RUN'
195
+ switch (task.lastRun.status) {
196
+ case 'success':
197
+ return 'OK'
198
+ case 'refused':
199
+ return 'REFUSED'
200
+ case 'skipped':
201
+ return 'SKIPPED'
202
+ case 'timeout':
203
+ return 'TIMEOUT'
204
+ case 'interrupted':
205
+ return 'INTERRUPTED'
206
+ default:
207
+ return 'ERROR'
208
+ }
209
+ }
210
+
211
+ function describeLastRun(lastRun) {
212
+ if (!lastRun) return 'never run'
213
+ let line = `${lastRun.status} @ ${formatEpoch(lastRun.at)}`
214
+ if (lastRun.sessionId) line += ` (session ${lastRun.sessionId})`
215
+ if (lastRun.error) line += ` — ${lastRun.error}`
216
+ return line
217
+ }
218
+
219
+ // -- input parsing ---------------------------------------------------------
220
+
221
+ /**
222
+ * Parse `--at` into epoch-ms: bare digits are epoch-ms, else Date.parse (ISO-8601).
223
+ *
224
+ * Timezone handling is `Date.parse`'s, unchanged and on purpose: a date-time
225
+ * string with no offset (`2026-08-01T09:00:00`) is interpreted in the HOST's
226
+ * local timezone, while everything this CLI prints is UTC (`formatEpoch`).
227
+ * Re-interpreting an offset-less string as UTC would silently move every
228
+ * already-scripted `--at` invocation by the operator's UTC offset, so the fix
229
+ * for the mismatch is to make the hint and the `--at` help text say which is
230
+ * which — not to change what a given string means. See #7015.
231
+ */
232
+ function parseAtValue(raw) {
233
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
234
+ return { error: '--at requires a value' }
235
+ }
236
+ const trimmed = raw.trim()
237
+ if (/^\d+$/.test(trimmed)) {
238
+ const ms = Number(trimmed)
239
+ return Number.isFinite(ms)
240
+ ? { at: ms }
241
+ : { error: `--at '${raw}' is not a valid epoch-ms timestamp` }
242
+ }
243
+ const parsed = Date.parse(trimmed)
244
+ if (Number.isNaN(parsed)) {
245
+ return {
246
+ error: `--at '${raw}' could not be parsed — use an ISO-8601 timestamp `
247
+ + '(e.g. 2026-08-01T09:00:00Z) or epoch milliseconds. Times are displayed in UTC; '
248
+ + 'a timestamp with no timezone is read as LOCAL time, so add a trailing Z '
249
+ + '(or a ±hh:mm offset) to say exactly which instant you mean',
250
+ }
251
+ }
252
+ return { at: parsed }
253
+ }
254
+
255
+ /** Build a brand-new cadence for `create` — exactly one of --at/--cron is required. */
256
+ function buildCadenceForCreate(options) {
257
+ const hasAt = options.at !== undefined
258
+ const hasCron = options.cron !== undefined
259
+ if (hasAt && hasCron) return { error: '--at and --cron are mutually exclusive — pick one cadence' }
260
+ if (!hasAt && !hasCron) {
261
+ return { error: 'specify a cadence: --at <when> for a one-time run, or --cron <expr> for a recurring one' }
262
+ }
263
+ if (hasCron) {
264
+ if (typeof options.cron !== 'string' || options.cron.trim().length === 0) {
265
+ return { error: '--cron requires a 5-field crontab expression' }
266
+ }
267
+ return { cadence: { kind: 'cron', expression: options.cron } }
268
+ }
269
+ const parsed = parseAtValue(options.at)
270
+ if (parsed.error) return { error: parsed.error }
271
+ return { cadence: { kind: 'once', at: parsed.at } }
272
+ }
273
+
274
+ /** Build a cadence PATCH for `edit` — absent when neither flag is given (no change). */
275
+ function buildCadencePatch(options) {
276
+ const hasAt = options.at !== undefined
277
+ const hasCron = options.cron !== undefined
278
+ if (!hasAt && !hasCron) return {}
279
+ if (hasAt && hasCron) return { error: '--at and --cron are mutually exclusive — pick one cadence' }
280
+ return buildCadenceForCreate(options)
281
+ }
282
+
283
+ /** Collect only the target fields the caller actually passed. */
284
+ function buildTargetFields(options) {
285
+ const target = {}
286
+ if (options.provider !== undefined) target.provider = options.provider
287
+ if (options.model !== undefined) target.model = options.model
288
+ if (options.cwd !== undefined) target.cwd = options.cwd
289
+ if (options.permissionMode !== undefined) target.permissionMode = options.permissionMode
290
+ return target
291
+ }
292
+
293
+ /** Resolve a caller-supplied id or unique id-prefix to a stored task. */
294
+ function resolveTaskId(store, idOrPrefix) {
295
+ if (typeof idOrPrefix !== 'string' || idOrPrefix.trim().length === 0) {
296
+ return { error: 'A task id (or unique id-prefix) is required.', errorCode: 'no-target' }
297
+ }
298
+ const target = idOrPrefix.trim()
299
+ const all = store.list()
300
+ const exact = all.find((t) => t.id === target)
301
+ if (exact) return { task: exact }
302
+ const matches = all.filter((t) => t.id.startsWith(target))
303
+ if (matches.length === 0) {
304
+ return { error: `No scheduled task matches "${target}". Run: chroxy schedule list`, errorCode: 'no-match' }
305
+ }
306
+ if (matches.length > 1) {
307
+ return {
308
+ error: `"${target}" matches ${matches.length} tasks — use a longer id prefix to disambiguate.`,
309
+ errorCode: 'ambiguous',
310
+ matches: matches.length,
311
+ }
312
+ }
313
+ return { task: matches[0] }
314
+ }
315
+
316
+ /**
317
+ * The honesty layer: warnings surfaced at create/edit time so a task's
318
+ * problems are visible up front rather than discovered later in `list`.
319
+ * Every check here reuses an engine-owned function — nothing is
320
+ * re-implemented — per the module doc above.
321
+ */
322
+ function computeWarnings(task, deps) {
323
+ const warnings = []
324
+ const providerName = task.target?.provider || deps.defaultProviderName
325
+ const refusal = deps.checkProviderRefusal(providerName)
326
+ if (refusal) {
327
+ warnings.push(`provider '${providerName}' will be REFUSED when this task is due — nothing will run: ${refusal}`)
328
+ }
329
+ const requestedMode = task.target?.permissionMode
330
+ if (requestedMode) {
331
+ const resolvedMode = deps.resolvePermissionMode(requestedMode)
332
+ if (resolvedMode !== requestedMode) {
333
+ warnings.push(
334
+ `permission mode '${requestedMode}' will be clamped to '${resolvedMode}' when this task fires `
335
+ + '— unattended runs can never use a more permissive mode',
336
+ )
337
+ }
338
+ }
339
+ if (!deps.checkSchedulerEnabled()) {
340
+ warnings.push(
341
+ 'scheduled execution is currently DISABLED on this daemon — this task is saved but will NOT fire '
342
+ + 'until enabled (set features.scheduler: true in config.json or CHROXY_ENABLE_SCHEDULER=1, then restart the daemon)',
343
+ )
344
+ }
345
+ return warnings
346
+ }
347
+
348
+ // -- command implementations (pure aside from injected deps) ---------------
349
+
350
+ /**
351
+ * `chroxy schedule create` — validates + persists via `store.add()` (which
352
+ * itself validates the cadence through schedule-parser.js), then surfaces
353
+ * the computed next-run and any create-time warnings.
354
+ * @returns {{created:boolean, task?:object, warnings?:string[], error?:string, message?:string, field?:string}}
355
+ */
356
+ export function runScheduleCreate(options = {}, depsOverride = {}) {
357
+ const deps = buildDeps(depsOverride)
358
+ const out = deps.write
359
+
360
+ if (typeof options.prompt !== 'string' || options.prompt.trim().length === 0) {
361
+ out('A --prompt is required (the instructions the scheduled run executes).')
362
+ return { created: false, error: 'missing-prompt' }
363
+ }
364
+
365
+ const cadenceResult = buildCadenceForCreate(options)
366
+ if (cadenceResult.error) {
367
+ out(cadenceResult.error)
368
+ return { created: false, error: 'invalid-cadence', message: cadenceResult.error }
369
+ }
370
+
371
+ const target = buildTargetFields(options)
372
+
373
+ let task
374
+ try {
375
+ task = deps.store.add({
376
+ name: options.name,
377
+ prompt: options.prompt,
378
+ cadence: cadenceResult.cadence,
379
+ target,
380
+ enabled: !options.paused,
381
+ })
382
+ } catch (err) {
383
+ if (err instanceof ScheduledTaskValidationError) {
384
+ out(`Invalid schedule: ${err.field ? `${err.field} — ` : ''}${err.message}`)
385
+ return { created: false, error: 'validation', field: err.field, message: err.message }
386
+ }
387
+ out(`Failed to create scheduled task: ${err?.message || err}`)
388
+ return { created: false, error: 'store-error', message: err?.message || String(err) }
389
+ }
390
+
391
+ const warnings = computeWarnings(task, deps)
392
+
393
+ if (options.json) {
394
+ out(JSON.stringify({ task, warnings }, null, 2))
395
+ } else {
396
+ out(`Created scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}`)
397
+ out(` cadence: ${describeCadence(task.cadence)}`)
398
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : `— (paused; resume with: chroxy schedule resume ${task.id})`}`)
399
+ for (const w of warnings) out(` WARNING: ${w}`)
400
+ }
401
+ return { created: true, task, warnings }
402
+ }
403
+
404
+ /**
405
+ * `chroxy schedule list` — every task with its honest health tag, next-run,
406
+ * and last-run, plus the daemon's global enable-gate state up top.
407
+ * @returns {{schedulerEnabled:boolean, tasks:Array<{task:object,health:string,providerRefusal:string|null}>}}
408
+ */
409
+ export function runScheduleList(options = {}, depsOverride = {}) {
410
+ const deps = buildDeps(depsOverride)
411
+ const out = deps.write
412
+ const tasks = deps.store.list()
413
+ // #7079: stored entries the loader refused. Never printed verbatim — only the
414
+ // opaque handle (dashboard-discardable) and the loader's reason.
415
+ const unreadable = deps.store.listUnreadable()
416
+ const schedulerEnabled = deps.checkSchedulerEnabled()
417
+
418
+ const rows = tasks.map((task) => {
419
+ const providerName = task.target?.provider || deps.defaultProviderName
420
+ return { task, health: healthTag(task), providerRefusal: deps.checkProviderRefusal(providerName) }
421
+ })
422
+
423
+ if (options.json) {
424
+ out(JSON.stringify({
425
+ schedulerEnabled,
426
+ tasks: rows.map((r) => ({ ...r.task, health: r.health, providerRefusal: r.providerRefusal })),
427
+ unreadable,
428
+ }, null, 2))
429
+ return { schedulerEnabled, tasks: rows }
430
+ }
431
+
432
+ out(schedulerEnabled
433
+ ? 'Scheduled execution: ENABLED'
434
+ : 'Scheduled execution: DISABLED — tasks below are saved but will NOT fire. '
435
+ + 'Enable via features.scheduler: true in config.json or CHROXY_ENABLE_SCHEDULER=1, then restart the daemon.')
436
+ out('')
437
+
438
+ if (unreadable.length > 0) {
439
+ out(`WARNING: ${unreadable.length} stored task(s) could not be read and are NOT scheduled (kept in the registry file, not erased):`)
440
+ for (const { handle, id, reason } of unreadable) {
441
+ out(` - ${id ? `id ${id.length > 64 ? `${id.slice(0, 64)}…` : id}` : 'no usable id'} [${handle}]: ${reason}`)
442
+ }
443
+ out(' Fix the entry in the registry file, or discard it from the dashboard Scheduled tasks panel.')
444
+ out('')
445
+ }
446
+
447
+ if (rows.length === 0) {
448
+ out('No scheduled tasks. Create one: chroxy schedule create --prompt "..." --cron "0 9 * * *"')
449
+ return { schedulerEnabled, tasks: [] }
450
+ }
451
+
452
+ out(`${rows.length} scheduled task(s):`)
453
+ out('')
454
+ let enabledCount = 0
455
+ let pausedCount = 0
456
+ let refusedCount = 0
457
+ let neverRunCount = 0
458
+ for (const { task, health, providerRefusal } of rows) {
459
+ if (task.enabled) enabledCount++
460
+ else pausedCount++
461
+ if (!task.lastRun) neverRunCount++
462
+ else if (task.lastRun.status === 'refused') refusedCount++
463
+
464
+ const label = task.name || '(unnamed)'
465
+ out(`[${health}] ${label} (${task.id})`)
466
+ out(` cadence: ${describeCadence(task.cadence)}`)
467
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : '— (paused)'}`)
468
+ out(` last run: ${describeLastRun(task.lastRun)}`)
469
+ if (providerRefusal) {
470
+ const providerName = task.target?.provider || deps.defaultProviderName
471
+ out(` provider check: '${providerName}' will be REFUSED when due — ${providerRefusal}`)
472
+ }
473
+ out('')
474
+ }
475
+
476
+ const bits = [`${enabledCount} enabled`, `${pausedCount} paused`]
477
+ if (refusedCount > 0) bits.push(`${refusedCount} refused`)
478
+ if (neverRunCount > 0) bits.push(`${neverRunCount} never run`)
479
+ out(`Summary: ${bits.join(', ')}.`)
480
+
481
+ return { schedulerEnabled, tasks: rows }
482
+ }
483
+
484
+ /**
485
+ * `chroxy schedule edit <id>` — patches only the fields the caller passed.
486
+ * `target` fields are merged onto the EXISTING target (store.update replaces
487
+ * the whole object, so a partial `--model` edit must not drop `--provider`).
488
+ * @returns {{updated:boolean, task?:object, warnings?:string[], error?:string, message?:string, field?:string}}
489
+ */
490
+ export function runScheduleEdit(idOrPrefix, options = {}, depsOverride = {}) {
491
+ const deps = buildDeps(depsOverride)
492
+ const out = deps.write
493
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
494
+ if (resolved.error) {
495
+ out(resolved.error)
496
+ return { updated: false, error: resolved.errorCode || 'not-found', message: resolved.error }
497
+ }
498
+ const existing = resolved.task
499
+
500
+ const patch = {}
501
+ if (options.prompt !== undefined) patch.prompt = options.prompt
502
+ if (options.name !== undefined) patch.name = options.name
503
+
504
+ const cadenceResult = buildCadencePatch(options)
505
+ if (cadenceResult.error) {
506
+ out(cadenceResult.error)
507
+ return { updated: false, error: 'invalid-cadence', message: cadenceResult.error }
508
+ }
509
+ if (cadenceResult.cadence) patch.cadence = cadenceResult.cadence
510
+
511
+ const targetFields = buildTargetFields(options)
512
+ if (Object.keys(targetFields).length > 0) {
513
+ patch.target = { ...existing.target, ...targetFields }
514
+ }
515
+
516
+ if (Object.keys(patch).length === 0) {
517
+ out('Nothing to edit — pass at least one of --prompt, --name, --at/--cron, --provider, --model, --cwd, --permission-mode.')
518
+ return { updated: false, error: 'no-changes' }
519
+ }
520
+
521
+ let task
522
+ try {
523
+ task = deps.store.update(existing.id, patch)
524
+ } catch (err) {
525
+ if (err instanceof ScheduledTaskValidationError) {
526
+ out(`Invalid schedule: ${err.field ? `${err.field} — ` : ''}${err.message}`)
527
+ return { updated: false, error: 'validation', field: err.field, message: err.message }
528
+ }
529
+ out(`Failed to update scheduled task: ${err?.message || err}`)
530
+ return { updated: false, error: 'store-error', message: err?.message || String(err) }
531
+ }
532
+ if (!task) {
533
+ out(`No scheduled task with id ${existing.id} (it may have just been deleted).`)
534
+ return { updated: false, error: 'not-found' }
535
+ }
536
+
537
+ const warnings = computeWarnings(task, deps)
538
+ if (options.json) {
539
+ out(JSON.stringify({ task, warnings }, null, 2))
540
+ } else {
541
+ out(`Updated scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}`)
542
+ out(` cadence: ${describeCadence(task.cadence)}`)
543
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : '— (paused)'}`)
544
+ for (const w of warnings) out(` WARNING: ${w}`)
545
+ }
546
+ return { updated: true, task, warnings }
547
+ }
548
+
549
+ /**
550
+ * @private — shared body for pause/resume: both are a plain `enabled` flip.
551
+ * Neither requires `--yes` (unlike `delete`): pausing is fully reversible via
552
+ * its counterpart, so the confirmation gate the repo reserves for genuinely
553
+ * destructive/irreversible actions (delete, `tokens revoke --all`, `identity
554
+ * rotate`) does not apply here.
555
+ */
556
+ function setEnabled(idOrPrefix, enabled, options, depsOverride, verb) {
557
+ const deps = buildDeps(depsOverride)
558
+ const out = deps.write
559
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
560
+ if (resolved.error) {
561
+ out(resolved.error)
562
+ return { changed: false, error: resolved.errorCode || 'not-found', message: resolved.error }
563
+ }
564
+
565
+ let task
566
+ try {
567
+ task = deps.store.update(resolved.task.id, { enabled })
568
+ } catch (err) {
569
+ out(`Failed to ${verb} scheduled task: ${err?.message || err}`)
570
+ return { changed: false, error: 'store-error', message: err?.message || String(err) }
571
+ }
572
+ if (!task) {
573
+ out(`No scheduled task with id ${resolved.task.id}.`)
574
+ return { changed: false, error: 'not-found' }
575
+ }
576
+
577
+ if (options.json) {
578
+ out(JSON.stringify({ task }, null, 2))
579
+ } else {
580
+ out(`Task ${task.id}${task.name ? ` (${task.name})` : ''} ${verb === 'pause' ? 'paused' : 'resumed'}.`)
581
+ if (enabled) {
582
+ out(` next run: ${formatEpoch(task.nextRun)}`)
583
+ for (const w of computeWarnings(task, deps)) out(` WARNING: ${w}`)
584
+ } else {
585
+ out(` will not fire again until resumed: chroxy schedule resume ${task.id}`)
586
+ }
587
+ }
588
+ return { changed: true, task }
589
+ }
590
+
591
+ /** `chroxy schedule pause <id>` */
592
+ export function runSchedulePause(idOrPrefix, options = {}, depsOverride = {}) {
593
+ return setEnabled(idOrPrefix, false, options, depsOverride, 'pause')
594
+ }
595
+
596
+ /** `chroxy schedule resume <id>` */
597
+ export function runScheduleResume(idOrPrefix, options = {}, depsOverride = {}) {
598
+ return setEnabled(idOrPrefix, true, options, depsOverride, 'resume')
599
+ }
600
+
601
+ /**
602
+ * `chroxy schedule delete <id>` — destructive and irreversible (removes the
603
+ * task definition AND its run history), so it follows the repo's `--yes`
604
+ * confirmation convention (`tokens revoke --all`, `identity rotate`):
605
+ * without `--yes` it only explains what would be removed and changes
606
+ * nothing.
607
+ * @returns {{deleted:boolean, confirmed?:boolean, task?:object, error?:string, message?:string}}
608
+ */
609
+ export function runScheduleDelete(idOrPrefix, options = {}, depsOverride = {}) {
610
+ const deps = buildDeps(depsOverride)
611
+ const out = deps.write
612
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
613
+ if (resolved.error) {
614
+ out(resolved.error)
615
+ return { deleted: false, error: resolved.errorCode || 'not-found', message: resolved.error }
616
+ }
617
+ const task = resolved.task
618
+
619
+ if (!options.yes) {
620
+ out([
621
+ `chroxy schedule delete ${task.id}${task.name ? ` (${task.name})` : ''} — this permanently removes `
622
+ + 'the task definition and its run history.',
623
+ ` cadence: ${describeCadence(task.cadence)}`,
624
+ ` prompt: ${task.prompt.length > 80 ? `${task.prompt.slice(0, 80)}…` : task.prompt}`,
625
+ '',
626
+ 'This cannot be undone — re-run with --yes to confirm:',
627
+ ` chroxy schedule delete ${task.id} --yes`,
628
+ ].join('\n'))
629
+ return { deleted: false, confirmed: false, task }
630
+ }
631
+
632
+ let removed
633
+ try {
634
+ removed = deps.store.remove(task.id)
635
+ } catch (err) {
636
+ // #7077: a registry write that failed is reported, never shown as a delete.
637
+ out(`Could not delete scheduled task ${task.id}: ${err.message}`)
638
+ return { deleted: false, error: 'write-failed', message: err.message }
639
+ }
640
+ if (!removed) {
641
+ out(`No scheduled task with id ${task.id} (it may have already been deleted).`)
642
+ return { deleted: false, error: 'not-found' }
643
+ }
644
+ out(`Deleted scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}.`)
645
+ return { deleted: true, confirmed: true, task }
646
+ }
647
+
648
+ /**
649
+ * `chroxy schedule last-run <id>` — the per-task detail view. A task that has
650
+ * never fired says so explicitly (`never run`, tag `[NEVER RUN]`) rather than
651
+ * showing a blank/empty field that could be mistaken for "nothing to report".
652
+ * @returns {{found:boolean, task?:object, health?:string, error?:string, message?:string}}
653
+ */
654
+ export function runScheduleLastRun(idOrPrefix, options = {}, depsOverride = {}) {
655
+ const deps = buildDeps(depsOverride)
656
+ const out = deps.write
657
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
658
+ if (resolved.error) {
659
+ out(resolved.error)
660
+ return { found: false, error: resolved.errorCode || 'not-found', message: resolved.error }
661
+ }
662
+ const task = resolved.task
663
+ const health = healthTag(task)
664
+
665
+ if (options.json) {
666
+ out(JSON.stringify({ task, health }, null, 2))
667
+ return { found: true, task, health }
668
+ }
669
+
670
+ out(`${task.name ? `${task.name} ` : ''}(${task.id})`)
671
+ out(` state: ${task.enabled ? 'enabled' : 'paused'}`)
672
+ out(` cadence: ${describeCadence(task.cadence)}`)
673
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : '— (paused)'}`)
674
+ out(` last run: [${health}] ${describeLastRun(task.lastRun)}`)
675
+ if (!task.lastRun) {
676
+ out(` This task has never fired.${task.enabled ? '' : ' It is also currently paused.'}`)
677
+ }
678
+ if (!deps.checkSchedulerEnabled()) {
679
+ out(' NOTE: scheduled execution is DISABLED on this daemon — nothing will fire (including this task) until it is enabled.')
680
+ }
681
+ return { found: true, task, health }
682
+ }
683
+
684
+ // -- commander wiring --------------------------------------------------------
685
+
686
+ export function registerScheduleCommands(program) {
687
+ const schedule = program
688
+ .command('schedule')
689
+ .description('Manage scheduled tasks (create/list/edit/pause/resume/delete/last-run) — #6868')
690
+
691
+ schedule
692
+ .command('create')
693
+ .description('Create a scheduled task')
694
+ .requiredOption('-p, --prompt <text>', 'Instructions the scheduled run executes')
695
+ .option('-n, --name <name>', 'Optional human-readable label')
696
+ .option('--at <when>', 'One-time cadence: ISO-8601 timestamp (e.g. 2026-08-01T09:00:00Z — no timezone means LOCAL time; times are displayed in UTC) or epoch-ms (mutually exclusive with --cron)')
697
+ .option('--cron <expression>', '5-field crontab expression, e.g. "0 9 * * *" (mutually exclusive with --at)')
698
+ .option('--provider <name>', 'Target provider (default: the daemon default provider)')
699
+ .option('--model <name>', 'Target model')
700
+ .option('--cwd <path>', 'Target working directory')
701
+ .option('--permission-mode <mode>', 'Target permission mode: approve, acceptEdits, auto, plan (unattended runs are always clamped to approve/plan)')
702
+ .option('--paused', 'Create the task paused (enabled: false) — will not fire until resumed')
703
+ .option('--json', 'Output machine-readable JSON')
704
+ .action((options) => {
705
+ try {
706
+ const res = runScheduleCreate(options)
707
+ if (!res.created) process.exitCode = 1
708
+ } catch (err) {
709
+ console.error(`schedule create failed: ${err.message}`)
710
+ process.exitCode = 1
711
+ }
712
+ })
713
+
714
+ schedule
715
+ .command('list')
716
+ .description('List scheduled tasks — enabled/paused state, next run, and last-run outcome')
717
+ .option('--json', 'Output machine-readable JSON')
718
+ .action((options) => {
719
+ try {
720
+ runScheduleList(options)
721
+ } catch (err) {
722
+ console.error(`schedule list failed: ${err.message}`)
723
+ process.exitCode = 1
724
+ }
725
+ })
726
+
727
+ schedule
728
+ .command('edit <id>')
729
+ .description('Edit a scheduled task (id or unique id-prefix); pass an empty string to clear an optional field')
730
+ .option('-p, --prompt <text>', 'Replace the prompt')
731
+ .option('-n, --name <name>', 'Replace the label')
732
+ .option('--at <when>', 'Replace the cadence with a one-time run: ISO-8601 timestamp (add a trailing Z for UTC — no timezone means LOCAL time) or epoch-ms (mutually exclusive with --cron)')
733
+ .option('--cron <expression>', 'Replace the cadence with a recurring cron expression (mutually exclusive with --at)')
734
+ .option('--provider <name>', 'Replace the target provider')
735
+ .option('--model <name>', 'Replace the target model')
736
+ .option('--cwd <path>', 'Replace the target working directory')
737
+ .option('--permission-mode <mode>', 'Replace the target permission mode')
738
+ .option('--json', 'Output machine-readable JSON')
739
+ .action((id, options) => {
740
+ try {
741
+ const res = runScheduleEdit(id, options)
742
+ if (!res.updated) process.exitCode = 1
743
+ } catch (err) {
744
+ console.error(`schedule edit failed: ${err.message}`)
745
+ process.exitCode = 1
746
+ }
747
+ })
748
+
749
+ schedule
750
+ .command('pause <id>')
751
+ .description('Pause a scheduled task (enabled: false) — reversible via `resume`')
752
+ .option('--json', 'Output machine-readable JSON')
753
+ .action((id, options) => {
754
+ try {
755
+ const res = runSchedulePause(id, options)
756
+ if (!res.changed) process.exitCode = 1
757
+ } catch (err) {
758
+ console.error(`schedule pause failed: ${err.message}`)
759
+ process.exitCode = 1
760
+ }
761
+ })
762
+
763
+ schedule
764
+ .command('resume <id>')
765
+ .description('Resume a paused scheduled task (enabled: true)')
766
+ .option('--json', 'Output machine-readable JSON')
767
+ .action((id, options) => {
768
+ try {
769
+ const res = runScheduleResume(id, options)
770
+ if (!res.changed) process.exitCode = 1
771
+ } catch (err) {
772
+ console.error(`schedule resume failed: ${err.message}`)
773
+ process.exitCode = 1
774
+ }
775
+ })
776
+
777
+ schedule
778
+ .command('delete <id>')
779
+ .description('Permanently delete a scheduled task (id or unique id-prefix)')
780
+ .option('--yes', 'Confirm the delete (without it, the command only explains what it would remove)')
781
+ .action((id, options) => {
782
+ try {
783
+ const res = runScheduleDelete(id, options)
784
+ if (res.error) process.exitCode = 1
785
+ } catch (err) {
786
+ console.error(`schedule delete failed: ${err.message}`)
787
+ process.exitCode = 1
788
+ }
789
+ })
790
+
791
+ schedule
792
+ .command('last-run <id>')
793
+ .description('View the last recorded run outcome for a scheduled task (or "never run")')
794
+ .option('--json', 'Output machine-readable JSON')
795
+ .action((id, options) => {
796
+ try {
797
+ const res = runScheduleLastRun(id, options)
798
+ if (!res.found) process.exitCode = 1
799
+ } catch (err) {
800
+ console.error(`schedule last-run failed: ${err.message}`)
801
+ process.exitCode = 1
802
+ }
803
+ })
804
+ }