@chroxy/server 0.11.10 → 0.11.11

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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
package/src/scheduler.js CHANGED
@@ -102,9 +102,11 @@
102
102
  import { EventEmitter } from 'events'
103
103
  import { createLogger } from './logger.js'
104
104
  import { isSchedulerEnabled } from './config.js'
105
+ import { RESOLVED_BY } from './permission-resolved-by.js'
105
106
  import { getProvider, listProviders, DEFAULT_PROVIDER } from './providers.js'
106
107
  import { validateCwdAllowed } from './handler-utils.js'
107
108
  import { TurnDriver, TurnError } from './orchestration/turn-driver.js'
109
+ import { busyStateOf } from './session-busy-state.js'
108
110
 
109
111
  const log = createLogger('scheduler')
110
112
 
@@ -115,6 +117,16 @@ const log = createLogger('scheduler')
115
117
  * know to poke us, and a large wall-clock jump (suspend/resume, NTP step) can
116
118
  * never park us on a stale multi-day deadline.
117
119
  */
120
+ // #9242: consecutive fires skipped because the session was mid-turn before the task
121
+ // is declared stuck (error outcome + ownership released, so the next fire mints a fresh
122
+ // session and the stuck one stays inspectable). Count-based on purpose: it needs no
123
+ // notion of how long a turn legitimately runs, and 3 slots of a stuck turn is already
124
+ // a task that has silently not run for 3 cadences. It counts SLOTS, not elapsed time: a
125
+ // task on a long cadence is declared stuck only after 3 of its own slots (accepted).
126
+ export const BUSY_SKIP_LIMIT = 3
127
+ // A one-shot task skipped for a busy session is NOT retired; it is retried after this.
128
+ const DEFAULT_BUSY_RETRY_MS = 60_000
129
+
118
130
  export const MAX_SLEEP_MS = 60 * 1000
119
131
 
120
132
  /**
@@ -123,6 +135,7 @@ export const MAX_SLEEP_MS = 60 * 1000
123
135
  * concurrency slot (and thus every other task) forever.
124
136
  */
125
137
  export const DEFAULT_RUN_TIMEOUT_MS = 15 * 60 * 1000
138
+ const MAX_TIMER_MS = 2 ** 31 - 1
126
139
 
127
140
  /**
128
141
  * How late an overdue task may still be fired. A daemon that was down (laptop
@@ -228,6 +241,21 @@ class ScheduledRunRefusedError extends Error {
228
241
  }
229
242
  }
230
243
 
244
+ /**
245
+ * Thrown internally when a fire must NOT drive its session because a person is
246
+ * using it (#9242): mid-turn, or taken over since it was resolved. The caller turns
247
+ * it into a `skipped` outcome — the slot passes, nothing is sent, and the schedule
248
+ * advances to the next slot (no retry loop, no second session minted beside a
249
+ * session that is merely busy).
250
+ */
251
+ class ScheduledRunSkippedError extends Error {
252
+ constructor(message, { busy = false } = {}) {
253
+ super(message)
254
+ this.name = 'ScheduledRunSkippedError'
255
+ this.busy = busy
256
+ }
257
+ }
258
+
231
259
  /**
232
260
  * The provider ids a scheduled task MAY currently target: every registered,
233
261
  * non-hidden provider that answers permissions in-process. Derived from the
@@ -265,9 +293,19 @@ export function listSchedulableProviders(list = listProviders) {
265
293
  *
266
294
  * @param {string} providerName - the provider the run would actually use
267
295
  * @param {(name: string) => Function} [getProviderClass=getProvider] - registry seam
296
+ * @param {string|null} daemonDefaultProvider - the daemon's RESOLVED default provider
297
+ * (`resolveDaemonDefaultProvider(config)` / the manager's `providerType`), NOT the
298
+ * compiled-in DEFAULT_PROVIDER: a daemon configured `provider: claude-tui` refuses
299
+ * provider-less tasks, and only the resolved value can say so (#8279). REQUIRED: `undefined`
300
+ * throws; `null` means no resolved default is known (no clause).
268
301
  * @returns {string|null} refusal reason, or null when the provider is supported
269
302
  */
270
- export function scheduledProviderRefusalReason(providerName, getProviderClass = getProvider) {
303
+ export function scheduledProviderRefusalReason(providerName, getProviderClass = getProvider, daemonDefaultProvider) {
304
+ // REQUIRED (null = "no resolved default known", no clause): an optional
305
+ // argument lets a caller silently lose the clause (#8279).
306
+ if (daemonDefaultProvider === undefined) {
307
+ throw new TypeError('scheduledProviderRefusalReason: daemonDefaultProvider is required (pass null when no resolved default is known)')
308
+ }
271
309
  if (typeof providerName !== 'string' || providerName.length === 0) {
272
310
  return 'no provider could be resolved for this scheduled task — refusing to fire an unattended run at an unknown provider'
273
311
  }
@@ -281,7 +319,7 @@ export function scheduledProviderRefusalReason(providerName, getProviderClass =
281
319
  // Kept under the 500-char cap _recordRefusal applies, so the #7003 pointer and
282
320
  // the supported-provider list survive into the registry rather than being cut.
283
321
  const supported = listSchedulableProviders()
284
- const isDefault = providerName === DEFAULT_PROVIDER
322
+ const isDefault = typeof daemonDefaultProvider === 'string' && providerName === daemonDefaultProvider
285
323
  return `provider '${providerName}' routes permission prompts through the permission hook (POST /permission), which the scheduler cannot answer — an unattended run would stall on every gated tool call until the 300s auto-deny, then report a turn whose tool calls were all silently refused.${isDefault ? ` It is also the daemon DEFAULT, so a task with no target.provider lands here.` : ''} Set target.provider to one of: ${supported.length ? supported.join(', ') : '(none)'}. Hook-routed support: #7003.`
286
324
  }
287
325
 
@@ -356,6 +394,7 @@ export class SchedulerEngine extends EventEmitter {
356
394
  runTimeoutMs = DEFAULT_RUN_TIMEOUT_MS,
357
395
  overdueGraceMs = DEFAULT_OVERDUE_GRACE_MS,
358
396
  maxSleepMs = MAX_SLEEP_MS,
397
+ busyRetryMs = DEFAULT_BUSY_RETRY_MS,
359
398
  logger = log,
360
399
  } = {}) {
361
400
  super()
@@ -376,10 +415,21 @@ export class SchedulerEngine extends EventEmitter {
376
415
  this._setTimer = setTimer
377
416
  this._clearTimer = clearTimer
378
417
  this._maxConcurrentRuns = Math.max(1, Math.floor(maxConcurrentRuns) || 1)
379
- this._runTimeoutMs = runTimeoutMs
418
+ // Normalised: the value reaches setTimeout (the start wait, and TurnDriver's
419
+ // turn timer). null / 0 / NaN / negative would fire at once (TurnDriver treats
420
+ // a non-finite value as ITS default, never as "no timeout", and 0 as an
421
+ // immediate timeout), and > 2^31-1 overflows to ~0ms. Fall back to the default.
422
+ this._runTimeoutMs = (Number.isFinite(runTimeoutMs) && runTimeoutMs > 0 && runTimeoutMs <= MAX_TIMER_MS)
423
+ ? runTimeoutMs
424
+ : DEFAULT_RUN_TIMEOUT_MS
380
425
  this._overdueGraceMs = overdueGraceMs
381
426
  this._maxSleepMs = Math.max(1, Math.floor(maxSleepMs) || MAX_SLEEP_MS)
427
+ this._busyRetryMs = Number.isFinite(busyRetryMs) && busyRetryMs >= 0 ? busyRetryMs : DEFAULT_BUSY_RETRY_MS
382
428
  this._log = logger
429
+ /** @type {Map<string,number>} taskId -> consecutive busy-skips (#9242). */
430
+ this._busySkips = new Map()
431
+ /** @type {Map<string,number>} taskId -> epoch ms before which a busy-skipped one-shot is not retried. */
432
+ this._retryAt = new Map()
383
433
 
384
434
  this._timer = null
385
435
  this._started = false
@@ -388,6 +438,8 @@ export class SchedulerEngine extends EventEmitter {
388
438
  this._running = new Set()
389
439
  /** @type {Map<string,string>} taskId -> sessionId, so a recurring task RESUMES its session. */
390
440
  this._sessionByTask = new Map()
441
+ // #9286: last-seen task names, so the notice can name a task that is already deleted.
442
+ this._taskNames = new Map()
391
443
  this._staleModelWarned = new Set()
392
444
  /**
393
445
  * @type {Set<string>} task ids whose outcome could not be persisted. Recording
@@ -452,6 +504,7 @@ export class SchedulerEngine extends EventEmitter {
452
504
  }
453
505
  this._started = true
454
506
  this._log.info('Scheduled execution ENABLED — arming headless scheduler')
507
+ this._adoptLinkedSessions()
455
508
  this._armNextTick()
456
509
  return true
457
510
  }
@@ -507,6 +560,7 @@ export class SchedulerEngine extends EventEmitter {
507
560
  this._clearArmedTimer()
508
561
  // Every registry change and every settled run funnels through here, so this
509
562
  // is the one place that notices a task has gone away (#7006).
563
+ this._adoptLinkedSessions()
510
564
  this._releaseSessions()
511
565
  const now = this._now()
512
566
  let earliest = null
@@ -517,7 +571,8 @@ export class SchedulerEngine extends EventEmitter {
517
571
  for (const task of this._store.list()) {
518
572
  if (!task.enabled || !Number.isFinite(task.nextRun)) continue
519
573
  if (this._running.has(task.id) || this._quarantined.has(task.id)) continue
520
- if (earliest === null || task.nextRun < earliest) earliest = task.nextRun
574
+ const due = Math.max(task.nextRun, this._retryAt.get(task.id) ?? 0)
575
+ if (earliest === null || due < earliest) earliest = due
521
576
  }
522
577
  }
523
578
  // Even with nothing scheduled we re-check on the max-sleep cadence, so a task
@@ -547,8 +602,11 @@ export class SchedulerEngine extends EventEmitter {
547
602
  * the session still holds what the last run did. If such a task is deleted
548
603
  * later, the pass above destroys its session.
549
604
  *
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
605
+ * The mapping itself is in-memory, but the session's `scheduledTaskId` is
606
+ * persisted as a restore hint, so a restart re-adopts it (_adoptLinkedSessions,
607
+ * #8571) and a task deleted afterwards is released here like any other. Only an
608
+ * ADOPTED (mapped) session is closed; a task deleted while the daemon was down
609
+ * leaves its session as an ordinary one. Never throws: a failing destroy must not take
552
610
  * the scheduling tick down.
553
611
  */
554
612
  _releaseSessions() {
@@ -556,18 +614,115 @@ export class SchedulerEngine extends EventEmitter {
556
614
  if (this._store.get(taskId)) continue
557
615
  if (this._running.has(taskId)) continue
558
616
  this._sessionByTask.delete(taskId)
559
- this._destroyTaskSession(taskId, sessionId)
617
+ const taskName = this._taskNames.get(taskId)
618
+ this._taskNames.delete(taskId)
619
+ this._destroyTaskSession(taskId, sessionId, taskName)
620
+ }
621
+ for (const map of [this._busySkips, this._retryAt]) {
622
+ for (const id of [...map.keys()]) if (!this._store.get(id)) map.delete(id)
623
+ }
624
+ }
625
+
626
+ /**
627
+ * @private (#8571) — adopt restored sessions into the task->session map. The
628
+ * persisted `scheduledTaskId` is only a restore HINT: the SessionManager holds it
629
+ * inert until this pass takes ownership of the session (which is what makes it
630
+ * `automation_owned`). For every task in the store with no LIVE mapped session, the
631
+ * most recently active live session linked to it (owned or hinted; ties: highest
632
+ * session id) is adopted and mapped. Run on start, on every re-arm (so a session
633
+ * that came back late — retryFailedRestore, an archive restore — is picked up)
634
+ * and before a fire creates a session. Idempotent and cheap; never throws.
635
+ *
636
+ * It NEVER unlinks or destroys. A task absent from the store is not evidence of a
637
+ * deletion (the store loads EMPTY when its file is unreadable), so sessions linked
638
+ * to an absent task, and non-chosen duplicates, keep their inert hint. A task
639
+ * deleted while the daemon was down therefore leaves its session as an ordinary
640
+ * one; only a session adopted in this process is closed on deletion
641
+ * (_releaseSessions): an adopted session belongs to its task, so deleting the task
642
+ * closes it and its worktree. A person typing into a session that still carries only
643
+ * a hint releases the hint (SessionManager.releaseRestoreHint), so a duplicate the
644
+ * user took over is never adopted later. An archive restore of a scheduled session
645
+ * comes back through restore and is re-adopted the same way.
646
+ * Sessions dropped by restore's staleness filter cannot be
647
+ * re-adopted, so a long-cadence task may still get a fresh session.
648
+ *
649
+ * @param {string} [onlyTaskId] - restrict the pass to one task
650
+ */
651
+ _adoptLinkedSessions(onlyTaskId) {
652
+ try {
653
+ if (typeof this._sm?.listScheduledTaskSessions !== 'function') return
654
+ const linked = this._sm.listScheduledTaskSessions()
655
+ const tasks = onlyTaskId !== undefined
656
+ ? [this._store.get(onlyTaskId)].filter(Boolean)
657
+ : this._store.list()
658
+ for (const task of tasks) {
659
+ if (typeof task.name === 'string' && task.name) this._taskNames.set(task.id, task.name)
660
+ const mapped = this._sessionByTask.get(task.id)
661
+ if (mapped) {
662
+ if (this._sm.getSession?.(mapped)?.session) {
663
+ // Live. Reassert OWNERSHIP: a session retried after a start failure comes
664
+ // back on the same id carrying only the hint, and the map alone would
665
+ // leave it driven without the `automation_owned` blocker. A session that
666
+ // is neither owned nor hinted any more (a person used it) cannot be
667
+ // reasserted, so it is dropped rather than driven.
668
+ if (typeof this._sm.adoptScheduledTask !== 'function' || this._sm.adoptScheduledTask(mapped, task.id)) continue
669
+ }
670
+ this._sessionByTask.delete(task.id)
671
+ }
672
+ // Owned beats hinted, then most recent activity, then highest id.
673
+ let best = null
674
+ for (const s of linked) {
675
+ if (s.taskId !== task.id) continue
676
+ if (!best
677
+ || (s.owned !== best.owned ? s.owned
678
+ : s.lastActivityAt !== best.lastActivityAt ? s.lastActivityAt > best.lastActivityAt
679
+ : s.sessionId > best.sessionId)) {
680
+ best = s
681
+ }
682
+ }
683
+ if (!best) continue
684
+ if (this._sm.adoptScheduledTask?.(best.sessionId, task.id)) {
685
+ this._sessionByTask.set(task.id, best.sessionId)
686
+ this._log.info(`Adopted session ${best.sessionId} as the session of scheduled task ${task.id}`)
687
+ }
688
+ }
689
+ } catch (err) {
690
+ this._log.warn(`Could not adopt restored scheduled sessions: ${err?.message || err}`)
560
691
  }
561
692
  }
562
693
 
563
694
  /** @private — destroy a removed task's session if it is still alive; never throws. */
564
- _destroyTaskSession(taskId, sessionId) {
695
+ _destroyTaskSession(taskId, sessionId, taskName) {
565
696
  const warn = (err) => {
566
697
  this._log.warn(`Could not destroy the session of removed scheduled task ${taskId}: ${err?.message || err}`)
567
698
  }
568
699
  try {
569
700
  // Already gone (the operator closed it, or a teardown is in progress).
570
701
  if (!this._sm?.getSession?.(sessionId)) return
702
+ // #9242: only a session this task STILL owns is the task's to close. One a
703
+ // person took over (ownership released) is an ordinary session now, whether
704
+ // or not the adoption pass has noticed yet.
705
+ if (typeof this._sm.ownsScheduledTask === 'function' && !this._sm.ownsScheduledTask(sessionId, taskId)) {
706
+ this._log.info(`Scheduled task ${taskId} was removed — leaving its session ${sessionId} open (no longer owned by the task)`)
707
+ return
708
+ }
709
+ // #9242: and never take work with it. A worktree with uncommitted changes (or
710
+ // commits nothing else reaches), or one whose state cannot be read, is KEPT:
711
+ // the session is released to an ordinary one and the person decides.
712
+ const unsaved = typeof this._sm.unsavedWorktreeWork === 'function'
713
+ ? this._sm.unsavedWorktreeWork(sessionId)
714
+ : (typeof this._sm.hasUnsavedWorktreeWork === 'function' && this._sm.hasUnsavedWorktreeWork(sessionId)
715
+ ? { has: true, kinds: [], samples: {} }
716
+ : null)
717
+ if (unsaved?.has) {
718
+ this._sm.releaseScheduledOwnership?.(sessionId, taskId)
719
+ // #9286: say so in the session itself; the log line alone is invisible to the person.
720
+ // The release and the note are two flushes: a crash between them keeps the session
721
+ // without a note (cosmetic), and a retry cannot duplicate the note.
722
+ this._sm.noteScheduledSessionKept?.(sessionId, taskId, unsaved, taskName)
723
+ this._log.warn(`Scheduled task ${taskId} was removed — keeping its session ${sessionId} open: its worktree has unsaved work (uncommitted changes, unreachable commits, or an unreadable status). It is an ordinary session now; close it yourself once the work is safe.`)
724
+ return
725
+ }
571
726
  this._log.info(`Scheduled task ${taskId} was removed — closing its session ${sessionId}`)
572
727
  const pending = typeof this._sm.destroySessionLocked === 'function'
573
728
  ? this._sm.destroySessionLocked(sessionId)
@@ -622,7 +777,8 @@ export class SchedulerEngine extends EventEmitter {
622
777
  return this._store
623
778
  .list()
624
779
  .filter((t) => t.enabled && Number.isFinite(t.nextRun) && t.nextRun <= now
625
- && !this._running.has(t.id) && !this._quarantined.has(t.id))
780
+ && !this._running.has(t.id) && !this._quarantined.has(t.id)
781
+ && !((this._retryAt.get(t.id) ?? 0) > now))
626
782
  .sort((a, b) => a.nextRun - b.nextRun)
627
783
  }
628
784
 
@@ -678,6 +834,17 @@ export class SchedulerEngine extends EventEmitter {
678
834
  }
679
835
 
680
836
  const status = outcome?.status
837
+ // #9242: a one-shot task skipped because its session was busy has not run, and
838
+ // recording the skip would retire it. Leave it unrecorded (still due) and retry
839
+ // after a delay so it cannot spin; the overdue grace bounds how long it keeps trying.
840
+ if (outcome?.busy === true && status === 'skipped' && task.cadence?.kind === 'once') {
841
+ const delay = outcome.retryNow === true ? 0 : this._busyRetryMs
842
+ this._retryAt.set(task.id, this._now() + delay)
843
+ this._log.warn(`Scheduled one-shot task ${task.id} not run: ${outcome.error} — retrying in ${delay}ms`)
844
+ this.emit('run-end', { taskId: task.id, at, status: 'skipped', ...(outcome.sessionId ? { sessionId: outcome.sessionId } : {}), error: String(outcome.error).slice(0, 500) })
845
+ this._armNextTick()
846
+ return
847
+ }
681
848
  const result = {
682
849
  at,
683
850
  status: PASSTHROUGH_STATUSES.has(status) ? status : 'error',
@@ -685,6 +852,7 @@ export class SchedulerEngine extends EventEmitter {
685
852
  ...(outcome?.error ? { error: String(outcome.error).slice(0, 500) } : {}),
686
853
  }
687
854
  this._recordRun(task, result)
855
+ this._retryAt.delete(task.id) // an outcome is recorded: any busy-retry hold is over
688
856
  this.emit('run-end', { taskId: task.id, ...result })
689
857
  if (result.status === 'success') {
690
858
  this._log.info(`Scheduled task ${task.id} completed`)
@@ -703,7 +871,11 @@ export class SchedulerEngine extends EventEmitter {
703
871
  */
704
872
  _preflightRefusal(task) {
705
873
  // (a) Can we actually govern this provider's permission prompts? (#7003)
706
- const providerRefusal = scheduledProviderRefusalReason(this._resolveProviderName(task), this._getProviderClass)
874
+ const providerRefusal = scheduledProviderRefusalReason(
875
+ this._resolveProviderName(task),
876
+ this._getProviderClass,
877
+ this._resolveProviderName({}),
878
+ )
707
879
  if (providerRefusal) return providerRefusal
708
880
 
709
881
  // (b) Is the cwd one a session may be created in at all? The registry is a
@@ -822,11 +994,15 @@ export class SchedulerEngine extends EventEmitter {
822
994
  * meaningful (the operator can open it and read what the run actually did), and
823
995
  * gives a recurring task continuity across runs. Sessions are NOT auto-destroyed
824
996
  * 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.
997
+ * A task keeps one session between fires while NOBODY ELSE uses it. The mapping
998
+ * is bounded by the number of tasks, but the SESSIONS are not: a person using the
999
+ * task's session (typing, answering a question, restoring files) releases it to an
1000
+ * ordinary session, and a stuck-busy one is released after BUSY_SKIP_LIMIT skips
1001
+ * (#9242); the next fire then mints a fresh session, so one task can leave one
1002
+ * ordinary session per takeover. There is no idle reap and no cap. (A restart
1003
+ * re-adopts the owned session, #8571.) The session ends when the task is DELETED
1004
+ * and still owns it with no unsaved worktree work: see _releaseSessions (#7006).
1005
+ * Pausing, resuming or retiring a task leaves it be.
830
1006
  *
831
1007
  * Because they are ordinary sessions, the operator can also change their
832
1008
  * permission mode. That makes reuse an escalation vector, so the clamped mode is
@@ -843,10 +1019,21 @@ export class SchedulerEngine extends EventEmitter {
843
1019
  sessionId = this._resolveSession(task, ctx)
844
1020
  } catch (err) {
845
1021
  if (err instanceof ScheduledRunRefusedError) return { status: REFUSED_STATUS, error: err.message }
1022
+ if (err instanceof ScheduledRunSkippedError) return this._skipOutcome(task, err, undefined)
846
1023
  return { status: 'error', error: `session create failed: ${err?.message || err}` }
847
1024
  }
848
1025
  if (!sessionId) return { status: 'error', error: 'session create failed (no sessionId)' }
849
1026
 
1027
+ // #9245: a session whose provider start() is still in flight (a fresh one, or
1028
+ // a restored one) is not ready for input yet — BYOK's sendMessage rejects
1029
+ // 'Session not ready' until start() resolves (it sets _processReady and emits
1030
+ // 'ready' before resolving, byok-session.js start()). Take the settle handle
1031
+ // SYNCHRONOUSLY, before any await (the manager drops a failed start from
1032
+ // _sessions), and await it below. A settled or sync-start session resolves
1033
+ // immediately, so a reused session is never delayed.
1034
+ const waitStartedAt = Date.now()
1035
+ const startWait = this._sm.awaitSessionStart?.(sessionId, ctx.runTimeoutMs)
1036
+
850
1037
  // Register as an OWNED run before the turn starts, so the permission answerer
851
1038
  // is armed for the very first tool call.
852
1039
  const runState = { taskId: task.id, blocked: null }
@@ -854,10 +1041,33 @@ export class SchedulerEngine extends EventEmitter {
854
1041
  this._attachPermissionListener()
855
1042
 
856
1043
  try {
1044
+ if (startWait) {
1045
+ // Bound: runTimeoutMs, the run's own budget. The manager already fails a
1046
+ // start at its provider deadline (60s default, START_TIMEOUT), so this
1047
+ // bound only matters for providers that declare no start deadline; it
1048
+ // is never longer than the run is allowed to take.
1049
+ const started = await startWait
1050
+ if (!started.ok) {
1051
+ return { status: 'error', sessionId, error: `session ${sessionId} did not finish starting: ${started.error?.message || started.error || 'start failed'}` }
1052
+ }
1053
+ if (started.pending) {
1054
+ return { status: 'error', sessionId, error: `session ${sessionId} did not finish starting within ${ctx.runTimeoutMs}ms` }
1055
+ }
1056
+ }
1057
+ // #9242: the start wait is an await — a person may have taken the session over
1058
+ // (or started a turn in it) meanwhile. Judge again, right before the send.
1059
+ this._assertDrivable(task, sessionId)
1060
+ this._busySkips.delete(task.id) // reached dispatch: not stuck
857
1061
  const driver = this._ensureTurnDriver()
1062
+ // The start wait spends part of the run budget: the turn gets the REMAINDER,
1063
+ // so `timeout` keeps meaning total run time (floored so it stays a valid timer).
1064
+ const remainingMs = Math.max(1, ctx.runTimeoutMs - (Date.now() - waitStartedAt))
858
1065
  await driver.driveTurn(sessionId, task.prompt, {
859
1066
  label: `scheduled:${task.id}`,
860
- timeoutMs: ctx.runTimeoutMs,
1067
+ timeoutMs: remainingMs,
1068
+ // #9242: asked again at dispatch (after the mutex, and at a provider's queue
1069
+ // flush): the person may have taken the session over since the check above.
1070
+ admit: () => !(typeof this._sm.ownsScheduledTask === 'function') || this._sm.ownsScheduledTask(sessionId, task.id),
861
1071
  })
862
1072
  // `success` is the NARROWEST outcome, asserted positively: the turn
863
1073
  // completed AND no permission prompt was ever raised on this run. Any
@@ -871,6 +1081,7 @@ export class SchedulerEngine extends EventEmitter {
871
1081
  if (runState.blocked) return this._blockedOutcome(runState, sessionId)
872
1082
  return { status: 'success', sessionId }
873
1083
  } catch (err) {
1084
+ if (err instanceof ScheduledRunSkippedError) return this._skipOutcome(task, err, sessionId)
874
1085
  // ORDER IS LOAD-BEARING. `runState.blocked` is checked FIRST, ahead of the
875
1086
  // TURN_STOPPED arm below, because the engine's own deny path reaches this
876
1087
  // catch through exactly the same rejection: it answers `deny`, interrupts
@@ -879,6 +1090,9 @@ export class SchedulerEngine extends EventEmitter {
879
1090
  // keep the `error` status it has always had. Only an interrupt with NO
880
1091
  // permission activity is the benign operator Stop.
881
1092
  if (runState.blocked) return this._blockedOutcome(runState, sessionId)
1093
+ if (err instanceof TurnError && err.code === 'NOT_ADMITTED') {
1094
+ return { status: 'skipped', sessionId, error: `session ${sessionId} was taken over before the scheduled prompt was dispatched — it was not sent` }
1095
+ }
882
1096
  if (err instanceof TurnError && err.code === 'TURN_TIMEOUT') {
883
1097
  return { status: 'timeout', sessionId, error: `run exceeded ${ctx.runTimeoutMs}ms` }
884
1098
  }
@@ -895,6 +1109,46 @@ export class SchedulerEngine extends EventEmitter {
895
1109
  }
896
1110
  }
897
1111
 
1112
+ /**
1113
+ * @private (#9242) — the outcome of a fire that declined to drive its session. A
1114
+ * takeover is a plain `skipped`. A BUSY session is `skipped` too, up to
1115
+ * BUSY_SKIP_LIMIT fires in a row; past that the task is stuck behind a session that
1116
+ * never goes idle, so the outcome becomes a visible `error` and the session is
1117
+ * released to an ordinary one (still there to inspect) so the next fire mints a fresh
1118
+ * session instead of being skipped forever.
1119
+ */
1120
+ _skipOutcome(task, err, sessionId) {
1121
+ if (!err.busy) {
1122
+ this._busySkips.delete(task.id)
1123
+ return { status: 'skipped', ...(sessionId ? { sessionId } : {}), error: err.message }
1124
+ }
1125
+ const n = (this._busySkips.get(task.id) ?? 0) + 1
1126
+ if (n < BUSY_SKIP_LIMIT) {
1127
+ this._busySkips.set(task.id, n)
1128
+ return { status: 'skipped', busy: true, ...(sessionId ? { sessionId } : {}), error: err.message }
1129
+ }
1130
+ this._busySkips.delete(task.id)
1131
+ const stuck = this._sessionByTask.get(task.id)
1132
+ if (stuck) {
1133
+ this._sm.releaseScheduledOwnership?.(stuck, task.id)
1134
+ this._sessionByTask.delete(task.id)
1135
+ }
1136
+ // A one-shot task has no later slot: recording an error would retire it unrun. The
1137
+ // stuck session is released as above and the task runs in a FRESH one at the next tick.
1138
+ if (task.cadence?.kind === 'once') {
1139
+ return {
1140
+ status: 'skipped', busy: true, retryNow: true,
1141
+ ...(stuck ? { sessionId: stuck } : {}),
1142
+ error: `session ${stuck ?? ''} has been busy for ${n} consecutive attempts — it was released (it stays open to inspect) and this one-shot task will run in a fresh session`,
1143
+ }
1144
+ }
1145
+ return {
1146
+ status: 'error',
1147
+ ...(stuck ? { sessionId: stuck } : {}),
1148
+ error: `session ${stuck ?? ''} has been busy for ${n} consecutive scheduled fires — the task has not run; the session was released (it stays open to inspect) and the next fire starts a fresh one`,
1149
+ }
1150
+ }
1151
+
898
1152
  /** @private — the permission-blocked outcome (a visible failure, never silent). */
899
1153
  _blockedOutcome(runState, sessionId) {
900
1154
  return {
@@ -911,10 +1165,18 @@ export class SchedulerEngine extends EventEmitter {
911
1165
  * verified. A session that cannot be brought to the clamped mode is refused.
912
1166
  */
913
1167
  _resolveSession(task, ctx) {
1168
+ // Adopt (or reassert ownership of) a linked session before minting a fresh one:
1169
+ // it may have been restored late, or come back on its id after a start failure.
1170
+ // Idempotent; drops a dead or no-longer-owned mapping (#8571).
1171
+ this._adoptLinkedSessions(task.id)
914
1172
  const existing = this._sessionByTask.get(task.id)
915
1173
  if (existing) {
916
1174
  const entry = this._sm.getSession?.(existing)
917
1175
  if (entry?.session) {
1176
+ // #9242: never drive into a session a person is in the middle of using.
1177
+ // BEFORE the mode assert, which would otherwise mutate (or refuse) a busy
1178
+ // session's permission mode for a run that is not going to happen.
1179
+ this._assertDrivable(task, existing)
918
1180
  // THE ESCALATION VECTOR (#6997 review C3): scheduled sessions are kept
919
1181
  // alive and reused, and an operator can flip any session to `auto` from
920
1182
  // the dashboard — even mid-turn. Without re-asserting here, one manual
@@ -953,9 +1215,33 @@ export class SchedulerEngine extends EventEmitter {
953
1215
  }
954
1216
  if (created?.session) this._assertPermissionMode(created.session, ctx.permissionMode, sessionId)
955
1217
  this._sessionByTask.set(task.id, sessionId)
1218
+ if (typeof task.name === 'string' && task.name) this._taskNames.set(task.id, task.name)
956
1219
  return sessionId
957
1220
  }
958
1221
 
1222
+ /**
1223
+ * @private (#9242) — a scheduled run only ever drives a session that is STILL the
1224
+ * task's and is NOT mid-turn. Ownership is released the moment a person sends
1225
+ * input (SessionManager.recordUserIntent), so a released session is never
1226
+ * driven; a mid-turn one (a person's turn, or the task's own previous run still
1227
+ * going after a timeout) would interleave the prompt with that turn, so the fire
1228
+ * is skipped instead. Only a mid-turn session blocks: one idle but held busy by
1229
+ * background shells is not in the middle of anything (busyReason 'turn').
1230
+ * A manager without the ownership API (a stub) is trusted as before.
1231
+ *
1232
+ * @throws {ScheduledRunSkippedError}
1233
+ */
1234
+ _assertDrivable(task, sessionId) {
1235
+ if (typeof this._sm.ownsScheduledTask === 'function' && !this._sm.ownsScheduledTask(sessionId, task.id)) {
1236
+ this._sessionByTask.delete(task.id)
1237
+ throw new ScheduledRunSkippedError(`session ${sessionId} is no longer owned by this task (a person took it over) — not driving it`)
1238
+ }
1239
+ const session = this._sm.getSession?.(sessionId)?.session
1240
+ if (session && busyStateOf(session).busyReason === 'turn') {
1241
+ throw new ScheduledRunSkippedError(`session ${sessionId} is busy (a turn is in progress) — not driving a scheduled prompt into it; the next slot will run`, { busy: true })
1242
+ }
1243
+ }
1244
+
959
1245
  /**
960
1246
  * @private — force `mode` onto a session and PROVE it took, or throw. The
961
1247
  * invariant this exists to hold: **a scheduled fire runs at the clamped mode,
@@ -1053,7 +1339,8 @@ export class SchedulerEngine extends EventEmitter {
1053
1339
  if (!session) return
1054
1340
  if (typeof session.respondToPermission === 'function') {
1055
1341
  try {
1056
- session.respondToPermission(requestId, 'deny')
1342
+ // #9119: nobody was there to ask; the daemon cleared it. Never a person.
1343
+ session.respondToPermission(requestId, 'deny', undefined, undefined, undefined, RESOLVED_BY.cleared)
1057
1344
  } catch (err) {
1058
1345
  this._log.warn(`Scheduler permission deny failed for ${sessionId}: ${err?.message || err}`)
1059
1346
  }