@chroxy/server 0.10.0 → 0.11.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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -0,0 +1,775 @@
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 { CONFIG_DIR, CONFIG_FILE } from './shared.js'
43
+ import {
44
+ ScheduledTaskStore,
45
+ ScheduledTaskValidationError,
46
+ defaultScheduledTasksPath,
47
+ } from '../scheduled-task-store.js'
48
+ import { isSchedulerEnabled } from '../config.js'
49
+ import { scheduledProviderRefusalReason, resolveScheduledPermissionMode } from '../scheduler.js'
50
+ import { DEFAULT_PROVIDER } 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
+ * Deliberately rooted at `homedir()/.chroxy` (shared.js's `CONFIG_DIR`) and
68
+ * deliberately NOT at `$CHROXY_CONFIG_DIR`, because the daemon's own registry
69
+ * path is home-rooted 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 `DEFAULT_STATE_FILE` =
74
+ * `join(homedir(), '.chroxy', '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 `~/.chroxy/scheduled-tasks.json`.
78
+ *
79
+ * Neither hop consults `CHROXY_CONFIG_DIR`. Plenty of OTHER subsystems do
80
+ * (models.js, connection-info.js, doctor.js, device-preferences.js, …), so the
81
+ * convention genuinely is inconsistent — that split is tracked in #7052, and
82
+ * fixing it means moving the WRITERS, not just this reader. Honouring the env var *here*
83
+ * would point this CLI at a file the running scheduler never opens, and
84
+ * `schedule create` would print "Created scheduled task …" for a task that can
85
+ * never fire while `schedule list` showed an empty registry. That is precisely
86
+ * the report-success-while-silently-wrong failure this module's doc block
87
+ * exists to prevent, so matching the daemon beats matching the convention.
88
+ *
89
+ * The same reasoning applies to `CONFIG_FILE` below: `server-cli-child.js`
90
+ * reads `join(homedir(), '.chroxy', 'config.json')`, so reading config from the
91
+ * home-rooted path is what makes `config.provider` / `features.scheduler` here
92
+ * agree with what the daemon resolved.
93
+ *
94
+ * Pinned from both sides by tests: a spawn test asserts the registry does NOT
95
+ * follow `CHROXY_CONFIG_DIR` (tests/cli/schedule-cmd.test.js), and a drift
96
+ * guard asserts the daemon-side path this mirrors is still home-rooted
97
+ * (tests/schedule-cli.test.js). If the session-state family is ever migrated
98
+ * onto `CHROXY_CONFIG_DIR` (#7052), the drift guard goes red and this resolver
99
+ * must move with it.
100
+ */
101
+ export function defaultScheduleRegistryPath() {
102
+ return defaultScheduledTasksPath(join(CONFIG_DIR, 'session-state.json'))
103
+ }
104
+
105
+ function getDefaultStore() {
106
+ const store = new ScheduledTaskStore({ filePath: defaultScheduleRegistryPath() })
107
+ store.load()
108
+ return store
109
+ }
110
+
111
+ /**
112
+ * Build the dependency bag every exported command function runs against.
113
+ * Every dependency is overridable so tests never touch the real
114
+ * `~/.chroxy/` tree and never need a live provider registry or config file —
115
+ * see tests/schedule-cli.test.js.
116
+ */
117
+ function buildDeps(overrides = {}) {
118
+ const config = readConfigSoft(CONFIG_FILE)
119
+ return {
120
+ store: overrides.store || getDefaultStore(),
121
+ write: overrides.write || console.log,
122
+ // The provider a task would ACTUALLY run against when none is set
123
+ // explicitly — mirrors the daemon's own resolution, `config.provider ||
124
+ // DEFAULT_PROVIDER` (server-cli.js's `providerType` wiring; scheduler.js's
125
+ // live `_resolveProviderName` falls back to the wired SessionManager's
126
+ // `providerType`, which IS this same expression). Reading config.provider
127
+ // here (not just hardcoding DEFAULT_PROVIDER) matters: if the operator's
128
+ // configured default ever diverges from DEFAULT_PROVIDER, this warning
129
+ // must track what will actually run, not the out-of-the-box default.
130
+ defaultProviderName: overrides.defaultProviderName || config.provider || DEFAULT_PROVIDER,
131
+ checkProviderRefusal: overrides.checkProviderRefusal || ((name) => scheduledProviderRefusalReason(name)),
132
+ resolvePermissionMode: overrides.resolvePermissionMode || resolveScheduledPermissionMode,
133
+ checkSchedulerEnabled: overrides.checkSchedulerEnabled || (() => isSchedulerEnabled(config)),
134
+ }
135
+ }
136
+
137
+ // -- formatting helpers --------------------------------------------------
138
+
139
+ /** Deterministic UTC rendering (no locale/timezone dependence) — easy to test, unambiguous to read. */
140
+ function formatEpoch(ms) {
141
+ if (!Number.isFinite(ms)) return '—'
142
+ return new Date(ms).toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, 'Z')
143
+ }
144
+
145
+ function formatDurationMs(ms) {
146
+ if (!Number.isFinite(ms) || ms < 0) return 'unknown'
147
+ const sec = Math.floor(ms / 1000)
148
+ if (sec < 60) return `${sec}s`
149
+ const min = Math.floor(sec / 60)
150
+ if (min < 60) return `${min}m`
151
+ const hr = Math.floor(min / 60)
152
+ if (hr < 24) return `${hr}h`
153
+ return `${Math.floor(hr / 24)}d`
154
+ }
155
+
156
+ function describeCadence(cadence) {
157
+ if (!cadence || typeof cadence !== 'object') return '(invalid cadence)'
158
+ switch (cadence.kind) {
159
+ case 'once':
160
+ return `once @ ${formatEpoch(cadence.at)}`
161
+ case 'interval':
162
+ return `every ${formatDurationMs(cadence.everyMs)}`
163
+ case 'cron':
164
+ return `cron "${cadence.expression}"`
165
+ default:
166
+ return `(unknown cadence: ${cadence.kind})`
167
+ }
168
+ }
169
+
170
+ /**
171
+ * A task's honest at-a-glance health. `PAUSED` takes priority (an operator
172
+ * turned it off on purpose); otherwise a task that has never fired is always
173
+ * `NEVER RUN` — never blank, never mistaken for healthy — and every recorded
174
+ * `lastRun.status` maps to its own tag so `refused` (and a best-effort
175
+ * quarantine write, which persists as `refused`) is never confused with
176
+ * `success`, and `interrupted` (#7038 — a deliberate Stop) is never confused
177
+ * with `error`.
178
+ *
179
+ * Kept byte-for-byte in step with `deriveScheduledTaskHealthTag` in
180
+ * @chroxy/protocol; `tests/scheduled-task-health-parity.test.js` fails if a
181
+ * status the shared helper tags by name falls through to `default:` here.
182
+ */
183
+ function healthTag(task) {
184
+ if (!task.enabled) return 'PAUSED'
185
+ if (!task.lastRun) return 'NEVER RUN'
186
+ switch (task.lastRun.status) {
187
+ case 'success':
188
+ return 'OK'
189
+ case 'refused':
190
+ return 'REFUSED'
191
+ case 'skipped':
192
+ return 'SKIPPED'
193
+ case 'timeout':
194
+ return 'TIMEOUT'
195
+ case 'interrupted':
196
+ return 'INTERRUPTED'
197
+ default:
198
+ return 'ERROR'
199
+ }
200
+ }
201
+
202
+ function describeLastRun(lastRun) {
203
+ if (!lastRun) return 'never run'
204
+ let line = `${lastRun.status} @ ${formatEpoch(lastRun.at)}`
205
+ if (lastRun.sessionId) line += ` (session ${lastRun.sessionId})`
206
+ if (lastRun.error) line += ` — ${lastRun.error}`
207
+ return line
208
+ }
209
+
210
+ // -- input parsing ---------------------------------------------------------
211
+
212
+ /**
213
+ * Parse `--at` into epoch-ms: bare digits are epoch-ms, else Date.parse (ISO-8601).
214
+ *
215
+ * Timezone handling is `Date.parse`'s, unchanged and on purpose: a date-time
216
+ * string with no offset (`2026-08-01T09:00:00`) is interpreted in the HOST's
217
+ * local timezone, while everything this CLI prints is UTC (`formatEpoch`).
218
+ * Re-interpreting an offset-less string as UTC would silently move every
219
+ * already-scripted `--at` invocation by the operator's UTC offset, so the fix
220
+ * for the mismatch is to make the hint and the `--at` help text say which is
221
+ * which — not to change what a given string means. See #7015.
222
+ */
223
+ function parseAtValue(raw) {
224
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
225
+ return { error: '--at requires a value' }
226
+ }
227
+ const trimmed = raw.trim()
228
+ if (/^\d+$/.test(trimmed)) {
229
+ const ms = Number(trimmed)
230
+ return Number.isFinite(ms)
231
+ ? { at: ms }
232
+ : { error: `--at '${raw}' is not a valid epoch-ms timestamp` }
233
+ }
234
+ const parsed = Date.parse(trimmed)
235
+ if (Number.isNaN(parsed)) {
236
+ return {
237
+ error: `--at '${raw}' could not be parsed — use an ISO-8601 timestamp `
238
+ + '(e.g. 2026-08-01T09:00:00Z) or epoch milliseconds. Times are displayed in UTC; '
239
+ + 'a timestamp with no timezone is read as LOCAL time, so add a trailing Z '
240
+ + '(or a ±hh:mm offset) to say exactly which instant you mean',
241
+ }
242
+ }
243
+ return { at: parsed }
244
+ }
245
+
246
+ /** Build a brand-new cadence for `create` — exactly one of --at/--cron is required. */
247
+ function buildCadenceForCreate(options) {
248
+ const hasAt = options.at !== undefined
249
+ const hasCron = options.cron !== undefined
250
+ if (hasAt && hasCron) return { error: '--at and --cron are mutually exclusive — pick one cadence' }
251
+ if (!hasAt && !hasCron) {
252
+ return { error: 'specify a cadence: --at <when> for a one-time run, or --cron <expr> for a recurring one' }
253
+ }
254
+ if (hasCron) {
255
+ if (typeof options.cron !== 'string' || options.cron.trim().length === 0) {
256
+ return { error: '--cron requires a 5-field crontab expression' }
257
+ }
258
+ return { cadence: { kind: 'cron', expression: options.cron } }
259
+ }
260
+ const parsed = parseAtValue(options.at)
261
+ if (parsed.error) return { error: parsed.error }
262
+ return { cadence: { kind: 'once', at: parsed.at } }
263
+ }
264
+
265
+ /** Build a cadence PATCH for `edit` — absent when neither flag is given (no change). */
266
+ function buildCadencePatch(options) {
267
+ const hasAt = options.at !== undefined
268
+ const hasCron = options.cron !== undefined
269
+ if (!hasAt && !hasCron) return {}
270
+ if (hasAt && hasCron) return { error: '--at and --cron are mutually exclusive — pick one cadence' }
271
+ return buildCadenceForCreate(options)
272
+ }
273
+
274
+ /** Collect only the target fields the caller actually passed. */
275
+ function buildTargetFields(options) {
276
+ const target = {}
277
+ if (options.provider !== undefined) target.provider = options.provider
278
+ if (options.model !== undefined) target.model = options.model
279
+ if (options.cwd !== undefined) target.cwd = options.cwd
280
+ if (options.permissionMode !== undefined) target.permissionMode = options.permissionMode
281
+ return target
282
+ }
283
+
284
+ /** Resolve a caller-supplied id or unique id-prefix to a stored task. */
285
+ function resolveTaskId(store, idOrPrefix) {
286
+ if (typeof idOrPrefix !== 'string' || idOrPrefix.trim().length === 0) {
287
+ return { error: 'A task id (or unique id-prefix) is required.', errorCode: 'no-target' }
288
+ }
289
+ const target = idOrPrefix.trim()
290
+ const all = store.list()
291
+ const exact = all.find((t) => t.id === target)
292
+ if (exact) return { task: exact }
293
+ const matches = all.filter((t) => t.id.startsWith(target))
294
+ if (matches.length === 0) {
295
+ return { error: `No scheduled task matches "${target}". Run: chroxy schedule list`, errorCode: 'no-match' }
296
+ }
297
+ if (matches.length > 1) {
298
+ return {
299
+ error: `"${target}" matches ${matches.length} tasks — use a longer id prefix to disambiguate.`,
300
+ errorCode: 'ambiguous',
301
+ matches: matches.length,
302
+ }
303
+ }
304
+ return { task: matches[0] }
305
+ }
306
+
307
+ /**
308
+ * The honesty layer: warnings surfaced at create/edit time so a task's
309
+ * problems are visible up front rather than discovered later in `list`.
310
+ * Every check here reuses an engine-owned function — nothing is
311
+ * re-implemented — per the module doc above.
312
+ */
313
+ function computeWarnings(task, deps) {
314
+ const warnings = []
315
+ const providerName = task.target?.provider || deps.defaultProviderName
316
+ const refusal = deps.checkProviderRefusal(providerName)
317
+ if (refusal) {
318
+ warnings.push(`provider '${providerName}' will be REFUSED when this task is due — nothing will run: ${refusal}`)
319
+ }
320
+ const requestedMode = task.target?.permissionMode
321
+ if (requestedMode) {
322
+ const resolvedMode = deps.resolvePermissionMode(requestedMode)
323
+ if (resolvedMode !== requestedMode) {
324
+ warnings.push(
325
+ `permission mode '${requestedMode}' will be clamped to '${resolvedMode}' when this task fires `
326
+ + '— unattended runs can never use a more permissive mode',
327
+ )
328
+ }
329
+ }
330
+ if (!deps.checkSchedulerEnabled()) {
331
+ warnings.push(
332
+ 'scheduled execution is currently DISABLED on this daemon — this task is saved but will NOT fire '
333
+ + 'until enabled (set features.scheduler: true in config.json or CHROXY_ENABLE_SCHEDULER=1, then restart the daemon)',
334
+ )
335
+ }
336
+ return warnings
337
+ }
338
+
339
+ // -- command implementations (pure aside from injected deps) ---------------
340
+
341
+ /**
342
+ * `chroxy schedule create` — validates + persists via `store.add()` (which
343
+ * itself validates the cadence through schedule-parser.js), then surfaces
344
+ * the computed next-run and any create-time warnings.
345
+ * @returns {{created:boolean, task?:object, warnings?:string[], error?:string, message?:string, field?:string}}
346
+ */
347
+ export function runScheduleCreate(options = {}, depsOverride = {}) {
348
+ const deps = buildDeps(depsOverride)
349
+ const out = deps.write
350
+
351
+ if (typeof options.prompt !== 'string' || options.prompt.trim().length === 0) {
352
+ out('A --prompt is required (the instructions the scheduled run executes).')
353
+ return { created: false, error: 'missing-prompt' }
354
+ }
355
+
356
+ const cadenceResult = buildCadenceForCreate(options)
357
+ if (cadenceResult.error) {
358
+ out(cadenceResult.error)
359
+ return { created: false, error: 'invalid-cadence', message: cadenceResult.error }
360
+ }
361
+
362
+ const target = buildTargetFields(options)
363
+
364
+ let task
365
+ try {
366
+ task = deps.store.add({
367
+ name: options.name,
368
+ prompt: options.prompt,
369
+ cadence: cadenceResult.cadence,
370
+ target,
371
+ enabled: !options.paused,
372
+ })
373
+ } catch (err) {
374
+ if (err instanceof ScheduledTaskValidationError) {
375
+ out(`Invalid schedule: ${err.field ? `${err.field} — ` : ''}${err.message}`)
376
+ return { created: false, error: 'validation', field: err.field, message: err.message }
377
+ }
378
+ out(`Failed to create scheduled task: ${err?.message || err}`)
379
+ return { created: false, error: 'store-error', message: err?.message || String(err) }
380
+ }
381
+
382
+ const warnings = computeWarnings(task, deps)
383
+
384
+ if (options.json) {
385
+ out(JSON.stringify({ task, warnings }, null, 2))
386
+ } else {
387
+ out(`Created scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}`)
388
+ out(` cadence: ${describeCadence(task.cadence)}`)
389
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : `— (paused; resume with: chroxy schedule resume ${task.id})`}`)
390
+ for (const w of warnings) out(` WARNING: ${w}`)
391
+ }
392
+ return { created: true, task, warnings }
393
+ }
394
+
395
+ /**
396
+ * `chroxy schedule list` — every task with its honest health tag, next-run,
397
+ * and last-run, plus the daemon's global enable-gate state up top.
398
+ * @returns {{schedulerEnabled:boolean, tasks:Array<{task:object,health:string,providerRefusal:string|null}>}}
399
+ */
400
+ export function runScheduleList(options = {}, depsOverride = {}) {
401
+ const deps = buildDeps(depsOverride)
402
+ const out = deps.write
403
+ const tasks = deps.store.list()
404
+ const schedulerEnabled = deps.checkSchedulerEnabled()
405
+
406
+ const rows = tasks.map((task) => {
407
+ const providerName = task.target?.provider || deps.defaultProviderName
408
+ return { task, health: healthTag(task), providerRefusal: deps.checkProviderRefusal(providerName) }
409
+ })
410
+
411
+ if (options.json) {
412
+ out(JSON.stringify({
413
+ schedulerEnabled,
414
+ tasks: rows.map((r) => ({ ...r.task, health: r.health, providerRefusal: r.providerRefusal })),
415
+ }, null, 2))
416
+ return { schedulerEnabled, tasks: rows }
417
+ }
418
+
419
+ out(schedulerEnabled
420
+ ? 'Scheduled execution: ENABLED'
421
+ : 'Scheduled execution: DISABLED — tasks below are saved but will NOT fire. '
422
+ + 'Enable via features.scheduler: true in config.json or CHROXY_ENABLE_SCHEDULER=1, then restart the daemon.')
423
+ out('')
424
+
425
+ if (rows.length === 0) {
426
+ out('No scheduled tasks. Create one: chroxy schedule create --prompt "..." --cron "0 9 * * *"')
427
+ return { schedulerEnabled, tasks: [] }
428
+ }
429
+
430
+ out(`${rows.length} scheduled task(s):`)
431
+ out('')
432
+ let enabledCount = 0
433
+ let pausedCount = 0
434
+ let refusedCount = 0
435
+ let neverRunCount = 0
436
+ for (const { task, health, providerRefusal } of rows) {
437
+ if (task.enabled) enabledCount++
438
+ else pausedCount++
439
+ if (!task.lastRun) neverRunCount++
440
+ else if (task.lastRun.status === 'refused') refusedCount++
441
+
442
+ const label = task.name || '(unnamed)'
443
+ out(`[${health}] ${label} (${task.id})`)
444
+ out(` cadence: ${describeCadence(task.cadence)}`)
445
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : '— (paused)'}`)
446
+ out(` last run: ${describeLastRun(task.lastRun)}`)
447
+ if (providerRefusal) {
448
+ const providerName = task.target?.provider || deps.defaultProviderName
449
+ out(` provider check: '${providerName}' will be REFUSED when due — ${providerRefusal}`)
450
+ }
451
+ out('')
452
+ }
453
+
454
+ const bits = [`${enabledCount} enabled`, `${pausedCount} paused`]
455
+ if (refusedCount > 0) bits.push(`${refusedCount} refused`)
456
+ if (neverRunCount > 0) bits.push(`${neverRunCount} never run`)
457
+ out(`Summary: ${bits.join(', ')}.`)
458
+
459
+ return { schedulerEnabled, tasks: rows }
460
+ }
461
+
462
+ /**
463
+ * `chroxy schedule edit <id>` — patches only the fields the caller passed.
464
+ * `target` fields are merged onto the EXISTING target (store.update replaces
465
+ * the whole object, so a partial `--model` edit must not drop `--provider`).
466
+ * @returns {{updated:boolean, task?:object, warnings?:string[], error?:string, message?:string, field?:string}}
467
+ */
468
+ export function runScheduleEdit(idOrPrefix, options = {}, depsOverride = {}) {
469
+ const deps = buildDeps(depsOverride)
470
+ const out = deps.write
471
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
472
+ if (resolved.error) {
473
+ out(resolved.error)
474
+ return { updated: false, error: resolved.errorCode || 'not-found', message: resolved.error }
475
+ }
476
+ const existing = resolved.task
477
+
478
+ const patch = {}
479
+ if (options.prompt !== undefined) patch.prompt = options.prompt
480
+ if (options.name !== undefined) patch.name = options.name
481
+
482
+ const cadenceResult = buildCadencePatch(options)
483
+ if (cadenceResult.error) {
484
+ out(cadenceResult.error)
485
+ return { updated: false, error: 'invalid-cadence', message: cadenceResult.error }
486
+ }
487
+ if (cadenceResult.cadence) patch.cadence = cadenceResult.cadence
488
+
489
+ const targetFields = buildTargetFields(options)
490
+ if (Object.keys(targetFields).length > 0) {
491
+ patch.target = { ...existing.target, ...targetFields }
492
+ }
493
+
494
+ if (Object.keys(patch).length === 0) {
495
+ out('Nothing to edit — pass at least one of --prompt, --name, --at/--cron, --provider, --model, --cwd, --permission-mode.')
496
+ return { updated: false, error: 'no-changes' }
497
+ }
498
+
499
+ let task
500
+ try {
501
+ task = deps.store.update(existing.id, patch)
502
+ } catch (err) {
503
+ if (err instanceof ScheduledTaskValidationError) {
504
+ out(`Invalid schedule: ${err.field ? `${err.field} — ` : ''}${err.message}`)
505
+ return { updated: false, error: 'validation', field: err.field, message: err.message }
506
+ }
507
+ out(`Failed to update scheduled task: ${err?.message || err}`)
508
+ return { updated: false, error: 'store-error', message: err?.message || String(err) }
509
+ }
510
+ if (!task) {
511
+ out(`No scheduled task with id ${existing.id} (it may have just been deleted).`)
512
+ return { updated: false, error: 'not-found' }
513
+ }
514
+
515
+ const warnings = computeWarnings(task, deps)
516
+ if (options.json) {
517
+ out(JSON.stringify({ task, warnings }, null, 2))
518
+ } else {
519
+ out(`Updated scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}`)
520
+ out(` cadence: ${describeCadence(task.cadence)}`)
521
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : '— (paused)'}`)
522
+ for (const w of warnings) out(` WARNING: ${w}`)
523
+ }
524
+ return { updated: true, task, warnings }
525
+ }
526
+
527
+ /**
528
+ * @private — shared body for pause/resume: both are a plain `enabled` flip.
529
+ * Neither requires `--yes` (unlike `delete`): pausing is fully reversible via
530
+ * its counterpart, so the confirmation gate the repo reserves for genuinely
531
+ * destructive/irreversible actions (delete, `tokens revoke --all`, `identity
532
+ * rotate`) does not apply here.
533
+ */
534
+ function setEnabled(idOrPrefix, enabled, options, depsOverride, verb) {
535
+ const deps = buildDeps(depsOverride)
536
+ const out = deps.write
537
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
538
+ if (resolved.error) {
539
+ out(resolved.error)
540
+ return { changed: false, error: resolved.errorCode || 'not-found', message: resolved.error }
541
+ }
542
+
543
+ let task
544
+ try {
545
+ task = deps.store.update(resolved.task.id, { enabled })
546
+ } catch (err) {
547
+ out(`Failed to ${verb} scheduled task: ${err?.message || err}`)
548
+ return { changed: false, error: 'store-error', message: err?.message || String(err) }
549
+ }
550
+ if (!task) {
551
+ out(`No scheduled task with id ${resolved.task.id}.`)
552
+ return { changed: false, error: 'not-found' }
553
+ }
554
+
555
+ if (options.json) {
556
+ out(JSON.stringify({ task }, null, 2))
557
+ } else {
558
+ out(`Task ${task.id}${task.name ? ` (${task.name})` : ''} ${verb === 'pause' ? 'paused' : 'resumed'}.`)
559
+ if (enabled) {
560
+ out(` next run: ${formatEpoch(task.nextRun)}`)
561
+ for (const w of computeWarnings(task, deps)) out(` WARNING: ${w}`)
562
+ } else {
563
+ out(` will not fire again until resumed: chroxy schedule resume ${task.id}`)
564
+ }
565
+ }
566
+ return { changed: true, task }
567
+ }
568
+
569
+ /** `chroxy schedule pause <id>` */
570
+ export function runSchedulePause(idOrPrefix, options = {}, depsOverride = {}) {
571
+ return setEnabled(idOrPrefix, false, options, depsOverride, 'pause')
572
+ }
573
+
574
+ /** `chroxy schedule resume <id>` */
575
+ export function runScheduleResume(idOrPrefix, options = {}, depsOverride = {}) {
576
+ return setEnabled(idOrPrefix, true, options, depsOverride, 'resume')
577
+ }
578
+
579
+ /**
580
+ * `chroxy schedule delete <id>` — destructive and irreversible (removes the
581
+ * task definition AND its run history), so it follows the repo's `--yes`
582
+ * confirmation convention (`tokens revoke --all`, `identity rotate`):
583
+ * without `--yes` it only explains what would be removed and changes
584
+ * nothing.
585
+ * @returns {{deleted:boolean, confirmed?:boolean, task?:object, error?:string, message?:string}}
586
+ */
587
+ export function runScheduleDelete(idOrPrefix, options = {}, depsOverride = {}) {
588
+ const deps = buildDeps(depsOverride)
589
+ const out = deps.write
590
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
591
+ if (resolved.error) {
592
+ out(resolved.error)
593
+ return { deleted: false, error: resolved.errorCode || 'not-found', message: resolved.error }
594
+ }
595
+ const task = resolved.task
596
+
597
+ if (!options.yes) {
598
+ out([
599
+ `chroxy schedule delete ${task.id}${task.name ? ` (${task.name})` : ''} — this permanently removes `
600
+ + 'the task definition and its run history.',
601
+ ` cadence: ${describeCadence(task.cadence)}`,
602
+ ` prompt: ${task.prompt.length > 80 ? `${task.prompt.slice(0, 80)}…` : task.prompt}`,
603
+ '',
604
+ 'This cannot be undone — re-run with --yes to confirm:',
605
+ ` chroxy schedule delete ${task.id} --yes`,
606
+ ].join('\n'))
607
+ return { deleted: false, confirmed: false, task }
608
+ }
609
+
610
+ const removed = deps.store.remove(task.id)
611
+ if (!removed) {
612
+ out(`No scheduled task with id ${task.id} (it may have already been deleted).`)
613
+ return { deleted: false, error: 'not-found' }
614
+ }
615
+ out(`Deleted scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}.`)
616
+ return { deleted: true, confirmed: true, task }
617
+ }
618
+
619
+ /**
620
+ * `chroxy schedule last-run <id>` — the per-task detail view. A task that has
621
+ * never fired says so explicitly (`never run`, tag `[NEVER RUN]`) rather than
622
+ * showing a blank/empty field that could be mistaken for "nothing to report".
623
+ * @returns {{found:boolean, task?:object, health?:string, error?:string, message?:string}}
624
+ */
625
+ export function runScheduleLastRun(idOrPrefix, options = {}, depsOverride = {}) {
626
+ const deps = buildDeps(depsOverride)
627
+ const out = deps.write
628
+ const resolved = resolveTaskId(deps.store, idOrPrefix)
629
+ if (resolved.error) {
630
+ out(resolved.error)
631
+ return { found: false, error: resolved.errorCode || 'not-found', message: resolved.error }
632
+ }
633
+ const task = resolved.task
634
+ const health = healthTag(task)
635
+
636
+ if (options.json) {
637
+ out(JSON.stringify({ task, health }, null, 2))
638
+ return { found: true, task, health }
639
+ }
640
+
641
+ out(`${task.name ? `${task.name} ` : ''}(${task.id})`)
642
+ out(` state: ${task.enabled ? 'enabled' : 'paused'}`)
643
+ out(` cadence: ${describeCadence(task.cadence)}`)
644
+ out(` next run: ${task.enabled ? formatEpoch(task.nextRun) : '— (paused)'}`)
645
+ out(` last run: [${health}] ${describeLastRun(task.lastRun)}`)
646
+ if (!task.lastRun) {
647
+ out(` This task has never fired.${task.enabled ? '' : ' It is also currently paused.'}`)
648
+ }
649
+ if (!deps.checkSchedulerEnabled()) {
650
+ out(' NOTE: scheduled execution is DISABLED on this daemon — nothing will fire (including this task) until it is enabled.')
651
+ }
652
+ return { found: true, task, health }
653
+ }
654
+
655
+ // -- commander wiring --------------------------------------------------------
656
+
657
+ export function registerScheduleCommands(program) {
658
+ const schedule = program
659
+ .command('schedule')
660
+ .description('Manage scheduled tasks (create/list/edit/pause/resume/delete/last-run) — #6868')
661
+
662
+ schedule
663
+ .command('create')
664
+ .description('Create a scheduled task')
665
+ .requiredOption('-p, --prompt <text>', 'Instructions the scheduled run executes')
666
+ .option('-n, --name <name>', 'Optional human-readable label')
667
+ .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)')
668
+ .option('--cron <expression>', '5-field crontab expression, e.g. "0 9 * * *" (mutually exclusive with --at)')
669
+ .option('--provider <name>', 'Target provider (default: the daemon default provider)')
670
+ .option('--model <name>', 'Target model')
671
+ .option('--cwd <path>', 'Target working directory')
672
+ .option('--permission-mode <mode>', 'Target permission mode: approve, acceptEdits, auto, plan (unattended runs are always clamped to approve/plan)')
673
+ .option('--paused', 'Create the task paused (enabled: false) — will not fire until resumed')
674
+ .option('--json', 'Output machine-readable JSON')
675
+ .action((options) => {
676
+ try {
677
+ const res = runScheduleCreate(options)
678
+ if (!res.created) process.exitCode = 1
679
+ } catch (err) {
680
+ console.error(`schedule create failed: ${err.message}`)
681
+ process.exitCode = 1
682
+ }
683
+ })
684
+
685
+ schedule
686
+ .command('list')
687
+ .description('List scheduled tasks — enabled/paused state, next run, and last-run outcome')
688
+ .option('--json', 'Output machine-readable JSON')
689
+ .action((options) => {
690
+ try {
691
+ runScheduleList(options)
692
+ } catch (err) {
693
+ console.error(`schedule list failed: ${err.message}`)
694
+ process.exitCode = 1
695
+ }
696
+ })
697
+
698
+ schedule
699
+ .command('edit <id>')
700
+ .description('Edit a scheduled task (id or unique id-prefix); pass an empty string to clear an optional field')
701
+ .option('-p, --prompt <text>', 'Replace the prompt')
702
+ .option('-n, --name <name>', 'Replace the label')
703
+ .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)')
704
+ .option('--cron <expression>', 'Replace the cadence with a recurring cron expression (mutually exclusive with --at)')
705
+ .option('--provider <name>', 'Replace the target provider')
706
+ .option('--model <name>', 'Replace the target model')
707
+ .option('--cwd <path>', 'Replace the target working directory')
708
+ .option('--permission-mode <mode>', 'Replace the target permission mode')
709
+ .option('--json', 'Output machine-readable JSON')
710
+ .action((id, options) => {
711
+ try {
712
+ const res = runScheduleEdit(id, options)
713
+ if (!res.updated) process.exitCode = 1
714
+ } catch (err) {
715
+ console.error(`schedule edit failed: ${err.message}`)
716
+ process.exitCode = 1
717
+ }
718
+ })
719
+
720
+ schedule
721
+ .command('pause <id>')
722
+ .description('Pause a scheduled task (enabled: false) — reversible via `resume`')
723
+ .option('--json', 'Output machine-readable JSON')
724
+ .action((id, options) => {
725
+ try {
726
+ const res = runSchedulePause(id, options)
727
+ if (!res.changed) process.exitCode = 1
728
+ } catch (err) {
729
+ console.error(`schedule pause failed: ${err.message}`)
730
+ process.exitCode = 1
731
+ }
732
+ })
733
+
734
+ schedule
735
+ .command('resume <id>')
736
+ .description('Resume a paused scheduled task (enabled: true)')
737
+ .option('--json', 'Output machine-readable JSON')
738
+ .action((id, options) => {
739
+ try {
740
+ const res = runScheduleResume(id, options)
741
+ if (!res.changed) process.exitCode = 1
742
+ } catch (err) {
743
+ console.error(`schedule resume failed: ${err.message}`)
744
+ process.exitCode = 1
745
+ }
746
+ })
747
+
748
+ schedule
749
+ .command('delete <id>')
750
+ .description('Permanently delete a scheduled task (id or unique id-prefix)')
751
+ .option('--yes', 'Confirm the delete (without it, the command only explains what it would remove)')
752
+ .action((id, options) => {
753
+ try {
754
+ const res = runScheduleDelete(id, options)
755
+ if (res.error) process.exitCode = 1
756
+ } catch (err) {
757
+ console.error(`schedule delete failed: ${err.message}`)
758
+ process.exitCode = 1
759
+ }
760
+ })
761
+
762
+ schedule
763
+ .command('last-run <id>')
764
+ .description('View the last recorded run outcome for a scheduled task (or "never run")')
765
+ .option('--json', 'Output machine-readable JSON')
766
+ .action((id, options) => {
767
+ try {
768
+ const res = runScheduleLastRun(id, options)
769
+ if (!res.found) process.exitCode = 1
770
+ } catch (err) {
771
+ console.error(`schedule last-run failed: ${err.message}`)
772
+ process.exitCode = 1
773
+ }
774
+ })
775
+ }