@chroxy/server 0.11.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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  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 +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  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 +69 -5
  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 +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,5 +1,5 @@
1
1
  import fs from 'fs'
2
- import { randomUUID } from 'crypto'
2
+ import { createHash, randomUUID } from 'crypto'
3
3
  import { dirname, resolve } from 'path'
4
4
  import { writeFileRestricted } from './platform.js'
5
5
  import { createLogger } from './logger.js'
@@ -18,6 +18,9 @@ const STORE_VERSION = 1
18
18
  // the cap are dropped on load (oldest kept) and refused on add.
19
19
  const MAX_TASKS = 500
20
20
 
21
+ /** Exported so the wire-cap parity test can pin the snapshot's `tasks` bound to it. */
22
+ export const MAX_STORED_TASKS = MAX_TASKS
23
+
21
24
  const CADENCE_KINDS = new Set(['once', 'interval', 'cron'])
22
25
 
23
26
  /**
@@ -60,11 +63,12 @@ const MAX_CRON_EXPRESSION_LENGTH = 256
60
63
  * omits it. The reachable path is therefore a hand-edited registry file.
61
64
  *
62
65
  * Since #7050 a refused entry is PRESERVED on disk rather than erased, so
63
- * refusing here does not destroy the operator's task. It does NOT yet mean they
64
- * can repair it in-product: an over-cap id is unaddressable at the wire
65
- * (`ScheduledTaskActionSchema.taskId` is capped too) and absent from
66
- * `store.list()`, so today the only remediation is hand-editing the same file.
67
- * Closing that loop is #7079.
66
+ * refusing here does not destroy the operator's task. An over-cap id is
67
+ * unaddressable at the wire (`ScheduledTaskActionSchema.taskId` is capped too)
68
+ * and absent from `store.list()`, so since #7079 the operator reaches such an
69
+ * entry through an opaque server-derived HANDLE (`listUnreadable()` /
70
+ * `discardUnreadable()`), not through its id; hand-editing the file remains a
71
+ * supported recovery path (#7077) — see the class docblock.
68
72
  */
69
73
  const MAX_WIRE_ID_LENGTH = 256
70
74
 
@@ -287,6 +291,97 @@ function normalizeLastRun(lastRun) {
287
291
  return out
288
292
  }
289
293
 
294
+ /**
295
+ * Canonical JSON: object keys sorted recursively, so two structurally-equal
296
+ * values serialise identically regardless of key order. Used for two things that
297
+ * must agree on "is this the same raw entry?": reconciling a preserved entry
298
+ * against the file (#7077) and deriving its wire handle (#7079). A raw entry may
299
+ * be any JSON value, not only an object — a hand-edited file can hold anything.
300
+ */
301
+ function canonicalJson(value) {
302
+ // ITERATIVE on purpose. A hand-edited registry can hold an entry nested
303
+ // thousands of levels deep; a recursive walk threw RangeError out of load() and
304
+ // crashed the daemon at boot, where the pre-#7077 loader read the same file
305
+ // fine. Work items are `[isLiteral, payload]` so a value that happens to look
306
+ // like a literal can never be mistaken for one.
307
+ const out = []
308
+ const work = [[false, value]]
309
+ while (work.length > 0) {
310
+ const [isLiteral, item] = work.pop()
311
+ if (isLiteral) { out.push(item); continue }
312
+ if (item === null || typeof item !== 'object') { out.push(String(JSON.stringify(item))); continue }
313
+ if (Array.isArray(item)) {
314
+ out.push('[')
315
+ work.push([true, ']'])
316
+ for (let i = item.length - 1; i >= 0; i--) {
317
+ work.push([false, item[i]])
318
+ if (i > 0) work.push([true, ','])
319
+ }
320
+ continue
321
+ }
322
+ const keys = Object.keys(item).sort()
323
+ out.push('{')
324
+ work.push([true, '}'])
325
+ for (let i = keys.length - 1; i >= 0; i--) {
326
+ work.push([false, item[keys[i]]])
327
+ work.push([true, `${JSON.stringify(keys[i])}:`])
328
+ if (i > 0) work.push([true, ','])
329
+ }
330
+ }
331
+ return out.join('')
332
+ }
333
+
334
+ /**
335
+ * A persist that did not reach disk, for the callers that must report it
336
+ * (`remove()`, `discardUnreadable()`). Deliberately generic: the cause (a path,
337
+ * an errno) is logged server-side, not sent to a client.
338
+ */
339
+ function persistFailure() {
340
+ return new Error('Could not write the scheduled-task registry; nothing was changed')
341
+ }
342
+
343
+ /**
344
+ * A preserved entry that is a well-formed task whose id a live task already
345
+ * owns. `duplicateOf` marks it so deleting that live task drops it too: left
346
+ * behind, a restart would load it as the task the operator just deleted.
347
+ */
348
+ function duplicateOfLive(entry, id) {
349
+ return {
350
+ raw: entry,
351
+ id: usableId(entry),
352
+ duplicateOf: id,
353
+ reason: `duplicates the id of a live task (${id}) — edit that task through the panel, or discard this entry`,
354
+ }
355
+ }
356
+
357
+ /** Multiset (canonical JSON -> count) of a list of raw entries. */
358
+ function countCanonical(entries) {
359
+ const counts = new Map()
360
+ for (const entry of entries) {
361
+ const key = canonicalJson(entry)
362
+ counts.set(key, (counts.get(key) ?? 0) + 1)
363
+ }
364
+ return counts
365
+ }
366
+
367
+ /** The trimmed string id of a raw entry, or null when it has no usable one. */
368
+ function usableId(raw) {
369
+ return typeof raw?.id === 'string' && raw.id.trim().length > 0 ? raw.id.trim() : null
370
+ }
371
+
372
+ /**
373
+ * #7079 — the opaque wire handle of an unreadable entry: the first 16 hex chars
374
+ * (64 bits) of the sha256 of its canonical JSON. It is the ONLY way a client
375
+ * names a preserved entry, because the entry's own id may be absent, a non-string,
376
+ * or longer than the wire's 256-char task-id cap (which is correct and must not
377
+ * be widened to carry a malformed record). Derived server-side from content, so a
378
+ * client can neither forge a handle for a live task nor address anything the
379
+ * server did not itself derive. Never contains raw contents.
380
+ */
381
+ function handleOf(canonical) {
382
+ return createHash('sha256').update(canonical).digest('hex').slice(0, 16)
383
+ }
384
+
290
385
  /**
291
386
  * The scheduled-task data model (#6862). A standing, persisted schedule for a
292
387
  * future/recurring agent run — explicitly SEPARATE from live session state and
@@ -317,6 +412,48 @@ function normalizeLastRun(lastRun) {
317
412
  * atomically (temp + rename via writeFileRestricted, mode 0600), version-gated,
318
413
  * and fail-open-empty on a corrupt/unknown-version file. Loaded once on daemon
319
414
  * start; keyed by task id.
415
+ *
416
+ * ── Unreadable (load-refused) entries (#7050, #7077, #7079, #8523) ────────────
417
+ * An entry the loader cannot read is never served as a task and never erased: it
418
+ * is kept verbatim and written back by every persist. Two ways to resolve one:
419
+ *
420
+ * 1. DISCARD (preferred) — the dashboard shows each entry with the reason it
421
+ * was refused and a Discard control; `discardUnreadable(handle)` removes it
422
+ * through the store, atomically, with no file editing.
423
+ * 2. HAND-EDIT — supported WHILE THE DAEMON RUNS.
424
+ *
425
+ * ── The hand-editing contract: the daemon only ever rewrites entries it wrote ──
426
+ * The store remembers exactly what it last wrote to the file (`_lastWritten`, a
427
+ * multiset of the canonical JSON of every entry, seeded from the raw entries as
428
+ * read at `load()`, and replaced only after an atomic write SUCCEEDS). At every
429
+ * persist it re-reads the file, and anything on disk that is not in that multiset
430
+ * is the OPERATOR's — an edit or an addition — and is never overwritten:
431
+ *
432
+ * | an entry on disk that is… | result |
433
+ * |----------------------------------------------|-------------------------------------|
434
+ * | one the daemon wrote (live or preserved) | the daemon's in-memory copy wins |
435
+ * | one the daemon wrote, now neither live nor preserved | gone on purpose (a delete or discard): NOT resurrected |
436
+ * | new, and it normalises, its id is free, cap allows | ADOPTED as a task |
437
+ * | new, and its id is a live task's (or was just adopted) | preserved as unreadable, "duplicates the id of …"; never armed |
438
+ * | new, and it does not normalise / cap reached | preserved as unreadable (reason re-derived) |
439
+ * | a preserved entry the operator edited or removed | the old capture is dropped; an edit is picked up as a new entry |
440
+ * | file missing / unparsable / wrong version or shape | no reconciliation: the in-memory set is written as before (nothing dropped) |
441
+ *
442
+ * New entries are processed in DISK ORDER, so when two share an id the first
443
+ * wins — exactly what `load()` of the same file would do. There is no identity
444
+ * inference (matching an edited entry to "the one it was" by id or position):
445
+ * each such guess had a hole that could resurrect a deleted task, arm a duplicate
446
+ * a restart would reject, or overwrite a live task. Editing a LIVE task's entry
447
+ * by hand therefore does not change the task; the edit is kept as an unreadable
448
+ * duplicate to discard or copy from. Such a duplicate is kept across restarts
449
+ * (`load()` preserves a duplicate id rather than dropping it; the first in file
450
+ * order is the task) and is dropped together with its task when that task is
451
+ * deleted, so deleting a task cannot leave a copy that a restart would arm. Edits are noticed only at a persist (any
452
+ * add/update/remove/discard or an engine run result), and an edit saved between
453
+ * that persist's read and its atomic rename is lost — the window any two writers
454
+ * of one file have. A persist that FAILS commits nothing (neither the adoption
455
+ * nor the new `_lastWritten`), and `remove()`/`discardUnreadable()` restore their
456
+ * in-memory change and throw so the caller reports the failure.
320
457
  */
321
458
  export class ScheduledTaskStore {
322
459
  /**
@@ -337,6 +474,9 @@ export class ScheduledTaskStore {
337
474
  // tasks; they exist so an operator's unreadable task survives the next
338
475
  // unrelated mutation instead of being silently deleted from disk.
339
476
  this._unreadable = []
477
+ // #7077: canonical JSON -> count of every entry in the last SUCCESSFUL write
478
+ // (seeded at load()). What is on disk and NOT in here is the operator's.
479
+ this._lastWritten = new Map()
340
480
  this._loaded = false
341
481
  }
342
482
 
@@ -365,6 +505,7 @@ export class ScheduledTaskStore {
365
505
  // and `_persist()` would write them back into a file that no longer has them,
366
506
  // resurrecting records the operator deleted.
367
507
  this._unreadable = []
508
+ this._lastWritten = new Map()
368
509
  let raw
369
510
  try {
370
511
  raw = fs.readFileSync(this._filePath, 'utf-8')
@@ -390,6 +531,10 @@ export class ScheduledTaskStore {
390
531
  }
391
532
  const tasks = parsed.tasks
392
533
  if (!Array.isArray(tasks)) return this
534
+ // #7077: everything in the file as read is, by definition, already known — the
535
+ // daemon is about to own it. Seeded BEFORE the loop so a refused or dropped
536
+ // entry is known too.
537
+ this._lastWritten = countCanonical(tasks)
393
538
  for (const [i, entry] of tasks.entries()) {
394
539
  if (this._tasks.size >= MAX_TASKS) {
395
540
  // #7050: the remainder is never even examined, so it would be erased on
@@ -409,7 +554,11 @@ export class ScheduledTaskStore {
409
554
  continue
410
555
  }
411
556
  if (this._tasks.has(record.id)) {
412
- this._log.warn(`Dropping duplicate scheduled-task id ${record.id} on load`)
557
+ // Kept, not dropped: a duplicate may be an operator's edit that a running
558
+ // daemon preserved (see `_reconcile`), and dropping it here would erase
559
+ // it at the next write after a restart. First in file order wins, as ever.
560
+ this._log.warn(`Scheduled-task id ${record.id} appears more than once — keeping the first, preserving the duplicate (not scheduled)`)
561
+ this._unreadable.push(duplicateOfLive(entry, record.id))
413
562
  continue
414
563
  }
415
564
  this._tasks.set(record.id, record)
@@ -522,8 +671,17 @@ export class ScheduledTaskStore {
522
671
  */
523
672
  remove(id) {
524
673
  if (this._tasks.has(id)) {
674
+ const before = new Map(this._tasks)
675
+ const beforeUnreadable = this._unreadable
525
676
  this._tasks.delete(id)
526
- this._persist()
677
+ // The duplicates kept for this id go with it: otherwise a restart loads one
678
+ // as the very task that was just deleted.
679
+ this._unreadable = beforeUnreadable.filter((u) => u.duplicateOf !== id)
680
+ if (!this._persist()) {
681
+ this._tasks = before
682
+ this._unreadable = beforeUnreadable
683
+ throw persistFailure()
684
+ }
527
685
  return true
528
686
  }
529
687
  // #7050: a preserved (unreadable) entry must stay deletable — otherwise
@@ -535,10 +693,13 @@ export class ScheduledTaskStore {
535
693
  // once and report success. `listUnreadable()` publicly emits those null rows,
536
694
  // so this is reachable the moment a caller forwards one back.
537
695
  if (typeof id !== 'string' || id.length === 0) return false
538
- const before = this._unreadable.length
539
- this._unreadable = this._unreadable.filter((u) => u.id !== id)
540
- if (this._unreadable.length === before) return false
541
- this._persist()
696
+ const before = this._unreadable
697
+ this._unreadable = before.filter((u) => u.id !== id)
698
+ if (this._unreadable.length === before.length) return false
699
+ if (!this._persist()) {
700
+ this._unreadable = before
701
+ throw persistFailure()
702
+ }
542
703
  return true
543
704
  }
544
705
 
@@ -553,17 +714,125 @@ export class ScheduledTaskStore {
553
714
  }
554
715
 
555
716
  /**
556
- * #7050 — the refused entries' ids and reasons (never their raw contents, which
557
- * may be any shape). `id` is null when the entry had no usable string id.
558
- * @returns {{ id: string|null, reason: string }[]}
717
+ * #7050 / #7079 — the refused entries' handles, ids and reasons (never their
718
+ * raw contents, which may be any shape). `id` is null when the entry had no
719
+ * usable string id. `handle` is the opaque, wire-legal token a client uses to
720
+ * name the entry (see {@link handleOf}); byte-identical entries get a `-<n>`
721
+ * suffix so each stays individually addressable.
722
+ *
723
+ * This reflects the daemon's view as of the last load or persist; it does not
724
+ * re-read the file (a read must not change what is armed to fire).
725
+ * @returns {{ handle: string, id: string|null, reason: string }[]}
559
726
  */
560
727
  listUnreadable() {
561
- return this._unreadable.map(({ id, reason }) => ({ id, reason }))
728
+ const seen = new Map()
729
+ return this._unreadable.map(({ raw, id, reason }) => {
730
+ const base = handleOf(canonicalJson(raw))
731
+ const n = (seen.get(base) ?? 0) + 1
732
+ seen.set(base, n)
733
+ return { handle: n === 1 ? base : `${base}-${n}`, id, reason }
734
+ })
735
+ }
736
+
737
+ /**
738
+ * #7079 — discard ONE unreadable entry by the handle `listUnreadable()` derived
739
+ * for it, and persist. Returns false (changing nothing) for an unknown, stale or
740
+ * non-string handle. Re-derives handles server-side after refreshing the
741
+ * preserved set from disk, so a handle the operator saw before hand-editing the
742
+ * file no longer matches: their newer edit is never discarded blind.
743
+ * @param {string} handle
744
+ * @returns {boolean}
745
+ */
746
+ discardUnreadable(handle) {
747
+ if (typeof handle !== 'string' || handle.length === 0) return false
748
+ const index = this.listUnreadable().findIndex((u) => u.handle === handle)
749
+ if (index === -1) return false
750
+ // A handle derives from the daemon's in-memory capture. If the operator has
751
+ // since edited or removed that entry in the file, the capture is stale and
752
+ // the handle no longer names what is on disk: refuse, and refresh (a persist
753
+ // reconciles) so the next listing carries the entry as it is now.
754
+ const disk = this._readDiskEntries()
755
+ const key = canonicalJson(this._unreadable[index].raw)
756
+ if (disk !== null && !disk.some((entry) => canonicalJson(entry) === key)) {
757
+ this._persist()
758
+ return false
759
+ }
760
+ const before = this._unreadable
761
+ this._unreadable = before.filter((_, i) => i !== index)
762
+ if (!this._persist()) {
763
+ this._unreadable = before
764
+ throw persistFailure()
765
+ }
766
+ return true
767
+ }
768
+
769
+ /**
770
+ * @private — #7077: read the file's task entries for reconciliation, or null
771
+ * when they cannot be trusted (missing / unreadable / unparsable / wrong
772
+ * version / `tasks` not an array). Null means "fall back to the captured raw
773
+ * entries", never "there are none".
774
+ */
775
+ _readDiskEntries() {
776
+ try {
777
+ const parsed = JSON.parse(fs.readFileSync(this._filePath, 'utf-8'))
778
+ if (!parsed || typeof parsed !== 'object' || parsed.version !== STORE_VERSION) return null
779
+ return Array.isArray(parsed.tasks) ? parsed.tasks : null
780
+ } catch {
781
+ return null
782
+ }
783
+ }
784
+
785
+ /**
786
+ * @private — #7077/#8523: classify what is on disk against what the daemon last
787
+ * wrote. PURE — returns the result; `_persist()` commits it only if the write
788
+ * succeeds. See the class docblock for the table. `disk` is trusted.
789
+ * @returns {{ adopted: object[], unreadable: object[] }}
790
+ */
791
+ _reconcile(disk) {
792
+ const diskKeys = disk.map(canonicalJson)
793
+ // A preserved entry the file still holds verbatim stays; one it does not was
794
+ // edited or removed by the operator, so the capture is dropped (an edit
795
+ // reappears below as a new entry).
796
+ const onDisk = countCanonical(disk)
797
+ const unreadable = []
798
+ for (const p of this._unreadable) {
799
+ const key = canonicalJson(p.raw)
800
+ const n = onDisk.get(key) ?? 0
801
+ if (n > 0) {
802
+ onDisk.set(key, n - 1)
803
+ unreadable.push(p)
804
+ } else {
805
+ this._log.info('A preserved unreadable scheduled-task entry was edited or removed in the registry file — dropping the stale copy')
806
+ }
807
+ }
808
+ // Everything the daemon did not write is the operator's, in DISK ORDER.
809
+ const known = new Map(this._lastWritten)
810
+ const taken = new Set(this._tasks.keys())
811
+ const adopted = []
812
+ disk.forEach((entry, i) => {
813
+ const n = known.get(diskKeys[i]) ?? 0
814
+ if (n > 0) { known.set(diskKeys[i], n - 1); return }
815
+ try {
816
+ const record = this._normalizeStoredTask(entry)
817
+ if (taken.has(record.id)) {
818
+ unreadable.push(duplicateOfLive(entry, record.id))
819
+ } else if (taken.size >= MAX_TASKS) {
820
+ unreadable.push({ raw: entry, id: usableId(entry), reason: `store cap (${MAX_TASKS}) reached` })
821
+ } else {
822
+ taken.add(record.id)
823
+ adopted.push(record)
824
+ this._log.info(`Adopted scheduled task ${record.id}: it was added or repaired in the registry file`)
825
+ }
826
+ } catch (err) {
827
+ unreadable.push({ raw: entry, id: usableId(entry), reason: String(err.message) })
828
+ }
829
+ })
830
+ return { adopted, unreadable }
562
831
  }
563
832
 
564
833
  /** @private — keep a refused raw entry so `_persist()` cannot erase it (#7050). */
565
834
  _preserveUnreadable(raw, reason) {
566
- const id = typeof raw?.id === 'string' && raw.id.trim().length > 0 ? raw.id.trim() : null
835
+ const id = usableId(raw)
567
836
  this._unreadable.push({ raw, id, reason: String(reason) })
568
837
  }
569
838
 
@@ -618,25 +887,48 @@ export class ScheduledTaskStore {
618
887
  }
619
888
  }
620
889
 
621
- /** @private — atomic write of the whole store. */
890
+ /**
891
+ * @private — atomic write of the whole store. Returns true when the file was
892
+ * written, false when it was not (the failure is logged; nothing is committed).
893
+ * add()/update() keep their long-standing best-effort contract and ignore it;
894
+ * remove()/discardUnreadable() report it.
895
+ */
622
896
  _persist() {
623
897
  try {
624
898
  const dir = dirname(this._filePath)
625
899
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
626
- // #7050: the preserved raw entries ride along so an unrelated mutation
627
- // cannot erase a task the loader merely could not READ. They are appended
628
- // (never re-serialized from a normalized record) so nothing is lost in a
629
- // round trip through a shape this version does not understand.
630
- const state = {
631
- version: STORE_VERSION,
632
- tasks: [...this._tasks.values(), ...this._unreadable.map((u) => u.raw)],
900
+ // #7077/#8523: pick up the operator's edits and additions BEFORE writing, so
901
+ // the daemon only ever rewrites entries it wrote itself. A store that never
902
+ // loaded has no baseline to compare against and writes as before; so does a
903
+ // file that is missing / unparsable / the wrong shape (nothing is dropped).
904
+ let adopted = []
905
+ let unreadable = this._unreadable
906
+ if (this._loaded) {
907
+ const disk = this._readDiskEntries()
908
+ if (disk !== null) ({ adopted, unreadable } = this._reconcile(disk))
633
909
  }
634
- writeFileRestricted(this._filePath, JSON.stringify(state, null, 2), { tmpSuffix: `.tmp-${process.pid}` })
910
+ // The preserved raw entries ride along so an unrelated mutation cannot erase
911
+ // a task the loader merely could not READ. They are appended (never
912
+ // re-serialized from a normalized record) so nothing is lost in a round trip
913
+ // through a shape this version does not understand.
914
+ const text = JSON.stringify({
915
+ version: STORE_VERSION,
916
+ tasks: [...this._tasks.values(), ...adopted, ...unreadable.map((u) => u.raw)],
917
+ }, null, 2)
918
+ writeFileRestricted(this._filePath, text, { tmpSuffix: `.tmp-${process.pid}` })
919
+ // Committed only now that the file really holds it. A failed write leaves the
920
+ // baseline and the preserved set as they were, so the next persist reconciles
921
+ // against the truth instead of against something that never reached disk.
922
+ for (const record of adopted) this._tasks.set(record.id, record)
923
+ this._unreadable = unreadable
924
+ this._lastWritten = countCanonical(JSON.parse(text).tasks)
925
+ return true
635
926
  } catch (err) {
636
927
  // Best-effort: a failed persist leaves the in-memory set intact for this
637
928
  // process; the prior good file (if any) survives (atomic write). Surface
638
929
  // it so an operator can see the schedule won't survive a restart.
639
930
  this._log.error(`Failed to persist scheduled tasks to ${this._filePath}: ${err?.stack || err}`)
931
+ return false
640
932
  }
641
933
  }
642
934
  }
package/src/scheduler.js CHANGED
@@ -388,6 +388,7 @@ export class SchedulerEngine extends EventEmitter {
388
388
  this._running = new Set()
389
389
  /** @type {Map<string,string>} taskId -> sessionId, so a recurring task RESUMES its session. */
390
390
  this._sessionByTask = new Map()
391
+ this._staleModelWarned = new Set()
391
392
  /**
392
393
  * @type {Set<string>} task ids whose outcome could not be persisted. Recording
393
394
  * the run is what advances nextRun, so a task we cannot record would stay
@@ -416,6 +417,11 @@ export class SchedulerEngine extends EventEmitter {
416
417
  return new Set(this._running)
417
418
  }
418
419
 
420
+ /** taskId -> sessionId for every task whose session is currently cached (test/observability aid). */
421
+ get scheduledSessionIds() {
422
+ return new Map(this._sessionByTask)
423
+ }
424
+
419
425
  /**
420
426
  * Task ids this process has quarantined (their outcome could not be persisted,
421
427
  * so they have STOPPED firing until the daemon restarts). Part of the engine's
@@ -499,6 +505,9 @@ export class SchedulerEngine extends EventEmitter {
499
505
  _armNextTick() {
500
506
  if (this._destroyed || !this._started) return
501
507
  this._clearArmedTimer()
508
+ // Every registry change and every settled run funnels through here, so this
509
+ // is the one place that notices a task has gone away (#7006).
510
+ this._releaseSessions()
502
511
  const now = this._now()
503
512
  let earliest = null
504
513
  // At capacity nothing new can start, and a shed task stays due — computing a
@@ -519,6 +528,56 @@ export class SchedulerEngine extends EventEmitter {
519
528
  this._timer = this._setTimer(() => this._tick(), delay)
520
529
  }
521
530
 
531
+ /**
532
+ * @private — end the session lifecycle of tasks that no longer exist (#7006).
533
+ * A recurring task keeps exactly ONE session between fires (see
534
+ * _runViaSessionManager); this is the other half — what happens when the task
535
+ * is deleted.
536
+ *
537
+ * Only REMOVAL (the task is gone from the store) ends the session: it is
538
+ * destroyed and the mapping dropped, so a deleted task no longer leaves a
539
+ * provider session running until the daemon exits. Never while the task's run
540
+ * is in flight — the turn is still using it — so it is skipped here and
541
+ * released by the pass that follows the run settling (_fire re-arms after every
542
+ * run).
543
+ *
544
+ * A task that is merely DISABLED, or a `once` task that retired (nextRun null),
545
+ * keeps its mapping and its session. Resume reuses the same session (dropping
546
+ * the mapping on pause would strand one session per pause/resume cycle), and
547
+ * the session still holds what the last run did. If such a task is deleted
548
+ * later, the pass above destroys its session.
549
+ *
550
+ * The mapping is in-memory only, so a restart forgets every task->session link
551
+ * without destroying anything. Never throws: a failing destroy must not take
552
+ * the scheduling tick down.
553
+ */
554
+ _releaseSessions() {
555
+ for (const [taskId, sessionId] of [...this._sessionByTask]) {
556
+ if (this._store.get(taskId)) continue
557
+ if (this._running.has(taskId)) continue
558
+ this._sessionByTask.delete(taskId)
559
+ this._destroyTaskSession(taskId, sessionId)
560
+ }
561
+ }
562
+
563
+ /** @private — destroy a removed task's session if it is still alive; never throws. */
564
+ _destroyTaskSession(taskId, sessionId) {
565
+ const warn = (err) => {
566
+ this._log.warn(`Could not destroy the session of removed scheduled task ${taskId}: ${err?.message || err}`)
567
+ }
568
+ try {
569
+ // Already gone (the operator closed it, or a teardown is in progress).
570
+ if (!this._sm?.getSession?.(sessionId)) return
571
+ this._log.info(`Scheduled task ${taskId} was removed — closing its session ${sessionId}`)
572
+ const pending = typeof this._sm.destroySessionLocked === 'function'
573
+ ? this._sm.destroySessionLocked(sessionId)
574
+ : this._sm.destroySession?.(sessionId)
575
+ if (pending && typeof pending.catch === 'function') pending.catch(warn)
576
+ } catch (err) {
577
+ warn(err)
578
+ }
579
+ }
580
+
522
581
  /**
523
582
  * @private — one evaluation pass: fire everything due (under the concurrency
524
583
  * cap), then re-arm. Never throws; a per-task failure is recorded and the pass
@@ -762,8 +821,12 @@ export class SchedulerEngine extends EventEmitter {
762
821
  * task to ONE session instead of one per fire, keeps the recorded `sessionId`
763
822
  * meaningful (the operator can open it and read what the run actually did), and
764
823
  * gives a recurring task continuity across runs. Sessions are NOT auto-destroyed
765
- * afterwards — they are ordinary sessions the operator can inspect and close
766
- * (never reaping them is tracked in #7006).
824
+ * after a run — they are ordinary sessions the operator can inspect and close.
825
+ * A recurring task therefore keeps exactly one session between fires, so within
826
+ * one daemon process the cache is bounded by the number of tasks in the registry;
827
+ * there is no idle reap and no cap. (A restart restores old sessions without
828
+ * their task link.) The session ends when the task is DELETED: see
829
+ * _releaseSessions (#7006). Pausing, resuming or retiring a task leaves it be.
767
830
  *
768
831
  * Because they are ordinary sessions, the operator can also change their
769
832
  * permission mode. That makes reuse an escalation vector, so the clamped mode is
@@ -870,7 +933,7 @@ export class SchedulerEngine extends EventEmitter {
870
933
  name: task.name || `Scheduled: ${task.id.slice(0, 8)}`,
871
934
  ...(target.cwd ? { cwd: target.cwd } : {}),
872
935
  ...(target.provider ? { provider: target.provider } : {}),
873
- ...(target.model ? { model: target.model } : {}),
936
+ ...(target.model ? { model: target.model, modelSource: 'replay' } : {}),
874
937
  // The clamped floor — never the task's raw value (see resolveScheduledPermissionMode).
875
938
  permissionMode: ctx.permissionMode,
876
939
  // EXPLICIT false so an unattended run can never inherit the server-wide
@@ -881,6 +944,13 @@ export class SchedulerEngine extends EventEmitter {
881
944
  // Trust nothing: verify the freshly-created session really came up at the
882
945
  // clamped mode rather than assuming createSession honoured the option.
883
946
  const created = this._sm.getSession?.(sessionId)
947
+ // #7855: a saved model id that is no longer usable runs on the default instead of
948
+ // failing every fire; say so once per task, naming it, so the owner can fix it.
949
+ if (target.model && created?.session && (created.session.model ?? null) !== target.model
950
+ && !this._staleModelWarned.has(task.id)) {
951
+ this._staleModelWarned.add(task.id)
952
+ this._log.warn(`Scheduled task ${task.id}${task.name ? ` (${task.name})` : ''}: saved model '${target.model}' is not usable; running on the provider default. Edit the task's model to fix.`)
953
+ }
884
954
  if (created?.session) this._assertPermissionMode(created.session, ctx.permissionMode, sessionId)
885
955
  this._sessionByTask.set(task.id, sessionId)
886
956
  return sessionId