@cortex-agent/server 2026.9.21 → 2026.9.25

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 (139) hide show
  1. package/defaults/config/thread-templates/agents/creative.json +17 -0
  2. package/defaults/prompts/systemPrompts/creative.md +13 -0
  3. package/defaults/prompts/systemPrompts/direct.md +1 -1
  4. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  5. package/dist/agent-adapter/claude/adapter.js +19 -1
  6. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  7. package/dist/agent-adapter/claude/spawn-args.js +10 -0
  8. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  9. package/dist/agent-adapter/pi/child-runner.js +5 -1
  10. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  11. package/dist/agent-adapter/pi/event-parser.js +46 -2
  12. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  13. package/dist/agent-adapter/pi/extensions.js +10 -3
  14. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  15. package/dist/agent-adapter/pi/pi-session.js +5 -0
  16. package/dist/agent-adapter/pi/runtime.js +3 -0
  17. package/dist/agent-adapter/pi/session-options.js +5 -1
  18. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  19. package/dist/agent-adapter/pi/subagent.js +18 -0
  20. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  21. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  22. package/dist/agent-adapter/types.d.ts +5 -0
  23. package/dist/core/agents/subagent/types.d.ts +3 -0
  24. package/dist/core/config-generator.js +17 -2
  25. package/dist/core/debug-mode.d.ts +11 -10
  26. package/dist/core/debug-mode.js +12 -18
  27. package/dist/core/exec-async.d.ts +26 -0
  28. package/dist/core/exec-async.js +47 -0
  29. package/dist/core/locales/en.d.ts +14 -1
  30. package/dist/core/locales/slices/commands.d.ts +12 -1
  31. package/dist/core/locales/slices/commands.js +24 -2
  32. package/dist/core/locales/slices/startup.d.ts +2 -0
  33. package/dist/core/locales/slices/startup.js +4 -0
  34. package/dist/core/rebuild-progress.d.ts +58 -0
  35. package/dist/core/rebuild-progress.js +103 -0
  36. package/dist/core/resilient-watch.js +5 -3
  37. package/dist/core/run-registry.d.ts +7 -0
  38. package/dist/core/run-registry.js +6 -0
  39. package/dist/core/types/thread-types.d.ts +23 -4
  40. package/dist/domain/agents/agent-state.d.ts +7 -0
  41. package/dist/domain/agents/agent-state.js +9 -1
  42. package/dist/domain/agents/agent-switch.d.ts +38 -0
  43. package/dist/domain/agents/agent-switch.js +106 -0
  44. package/dist/domain/agents/config.d.ts +20 -2
  45. package/dist/domain/agents/config.js +58 -4
  46. package/dist/domain/agents/index.d.ts +1 -0
  47. package/dist/domain/agents/index.js +1 -0
  48. package/dist/domain/agents/profile-manager.d.ts +6 -0
  49. package/dist/domain/agents/profile-manager.js +14 -1
  50. package/dist/domain/executions/registry.d.ts +2 -0
  51. package/dist/domain/executions/registry.js +84 -7
  52. package/dist/domain/plugins/runtime.js +1 -1
  53. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  54. package/dist/domain/plugins/skill-projection.js +76 -19
  55. package/dist/domain/remote/client-bootstrap.js +1 -1
  56. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  57. package/dist/domain/remote/client-hot-reload.js +27 -23
  58. package/dist/domain/runs/engine-spec.js +4 -0
  59. package/dist/domain/runs/request.d.ts +6 -0
  60. package/dist/domain/runs/run.js +1 -0
  61. package/dist/domain/runs/spec-loader.d.ts +4 -3
  62. package/dist/domain/runs/spec-loader.js +4 -3
  63. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  64. package/dist/domain/scheduling/scheduler.js +14 -12
  65. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  66. package/dist/domain/sessions/session-lifecycle.js +13 -1
  67. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  68. package/dist/domain/system/rebuild-hold.js +91 -0
  69. package/dist/domain/system/server-update-check.d.ts +2 -1
  70. package/dist/domain/system/server-update-check.js +15 -13
  71. package/dist/domain/tasks/archiver.js +21 -13
  72. package/dist/domain/tasks/mutator.js +60 -59
  73. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  74. package/dist/domain/tasks/system/task-completion.js +69 -6
  75. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  76. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  77. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  78. package/dist/domain/tasks/system/task-lock.js +29 -1
  79. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  80. package/dist/domain/tasks/system/task-mutations.js +25 -2
  81. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  82. package/dist/domain/tasks/system/task-state.js +19 -2
  83. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  84. package/dist/domain/threads/prompt-builder.js +28 -10
  85. package/dist/domain/threads/runner.js +7 -3
  86. package/dist/domain/threads/state-machine.js +15 -11
  87. package/dist/domain/threads/template-loader.js +6 -4
  88. package/dist/domain/threads/template-validate.d.ts +43 -6
  89. package/dist/domain/threads/template-validate.js +12 -0
  90. package/dist/domain/ui-service/app-router.d.ts +10 -0
  91. package/dist/domain/ui-service/app-router.js +2 -1
  92. package/dist/domain/ui-service/input-schemas.d.ts +11 -0
  93. package/dist/domain/ui-service/input-schemas.js +11 -0
  94. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  95. package/dist/domain/ui-service/mutate/sessions.js +40 -0
  96. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  97. package/dist/domain/ui-service/query/config.js +19 -1
  98. package/dist/domain/ui-service/query/memory.js +28 -34
  99. package/dist/domain/ui-service/query/sessions.js +89 -12
  100. package/dist/domain/ui-service/query/system.js +19 -0
  101. package/dist/domain/ui-service/query-input-schemas.d.ts +1 -0
  102. package/dist/domain/ui-service/query-input-schemas.js +2 -0
  103. package/dist/domain/ui-service/types.d.ts +97 -3
  104. package/dist/domain/ui-service/ui-service.js +2 -1
  105. package/dist/entry/app.js +23 -4
  106. package/dist/entry/daemon-notice.d.ts +10 -1
  107. package/dist/entry/daemon-notice.js +16 -1
  108. package/dist/entry/daemon.d.ts +43 -2
  109. package/dist/entry/daemon.js +163 -9
  110. package/dist/orchestration/agent-runner.js +16 -0
  111. package/dist/orchestration/conversation-request.d.ts +33 -0
  112. package/dist/orchestration/conversation-request.js +78 -16
  113. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  114. package/dist/orchestration/mid-turn-inject.js +9 -4
  115. package/dist/orchestration/resume-dispatcher.js +4 -2
  116. package/dist/orchestration/routing/commands/mode.js +114 -63
  117. package/dist/orchestration/thread-executor.js +13 -0
  118. package/dist/orchestration/turn/turn.js +1 -0
  119. package/dist/store/conversation-display-projection.d.ts +9 -1
  120. package/dist/store/conversation-display-projection.js +13 -6
  121. package/dist/store/conversation-history-reader.d.ts +19 -0
  122. package/dist/store/conversation-history-reader.js +163 -44
  123. package/dist/store/conversation-history-repo.d.ts +37 -10
  124. package/dist/store/conversation-history-repo.js +161 -139
  125. package/dist/store/session-registry-journal.d.ts +4 -0
  126. package/dist/store/session-registry-journal.js +4 -0
  127. package/dist/store/session-registry-repo.d.ts +2 -1
  128. package/dist/store/session-registry-repo.js +2 -0
  129. package/dist/store/task-repo.d.ts +6 -3
  130. package/dist/store/task-repo.js +26 -10
  131. package/package.json +2 -1
  132. package/web/dist/AGENTS.md +10 -0
  133. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  134. package/web/dist/assets/{index-DZTuqUO4.js → index-BAeLybF0.js} +1 -1
  135. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  136. package/web/dist/index.html +12 -4
  137. package/web/dist/theme.css +211 -40
  138. package/web/dist/assets/index-CwwQNMpP.css +0 -1
  139. package/web/dist/assets/index-DLSfgq3o.js +0 -444
@@ -9,6 +9,18 @@
9
9
  * { type: 'rebuild-aborted', text } — pipeline stopped early; app.ts broadcasts it as an
10
10
  * error-level system notice. The daemon has no platform adapter, so this is its only
11
11
  * way to reach the operator.
12
+ * { type: 'rebuild-hold', hold, phase, reason } — admission control for the last seconds before
13
+ * this process is replaced: while `hold` is true the app refuses to START new turns, because a
14
+ * turn spawned now is orphaned by the SIGTERM. Scope is deliberately narrow — the install and
15
+ * restart steps and a queued restart, never the build (see `rebuildHoldsTurns`). Re-sent on every
16
+ * phase change: the app's hold expires on its own, so a daemon that dies mid-pipeline fails open
17
+ * instead of muting the app forever.
18
+ *
19
+ * Rebuild progress:
20
+ * The pipeline publishes its plan and each step transition to STORE_DIR/daemon-rebuild.json
21
+ * (core/rebuild-progress.ts), which `system.daemonStatus` reads for the daemon page. It is a file
22
+ * and not in-app state on purpose: the pipeline's last act replaces the process that would have
23
+ * held it, so only a file can tell the new app what the rebuild it was born from did.
12
24
  *
13
25
  * Restart serialization:
14
26
  * Only ONE restart cycle (stop → start) runs at a time. Concurrent requests
@@ -31,9 +43,21 @@
31
43
  * types and web typechecks against ui-contract's built dist, so skipping the middle package
32
44
  * makes web fail on every newly added server DTO.
33
45
  *
46
+ * Every step is paid on every rebuild, including a web build that a server-only edit almost
47
+ * never changes, so the cost of each is kept down at the package level rather than by skipping
48
+ * steps here: both tsconfigs carry an incremental cache, and web's `build` runs its typecheck
49
+ * and its bundle concurrently. The server's cache lives inside dist/ on purpose — tsc trusts
50
+ * its buildinfo over the filesystem, so a cache that outlived its output would let a deleted
51
+ * dist file stay deleted.
52
+ *
34
53
  * Any step failing → log + notify the operator + skip (no restart), so an abort never looks
35
- * like a no-op restart. busy/idle gating is reused: a rebuild during an in-flight Slack
36
- * request defers the final restart() step until the child reports idle.
54
+ * like a no-op restart.
55
+ *
56
+ * busy/idle gating is checked twice, because only the tail of the pipeline is dangerous to a live
57
+ * turn. Once before the build, and again after it: the build takes minutes, so a turn can have
58
+ * started meanwhile, and everything past that point replaces the files app.js is running from and
59
+ * then kills it. A busy child there parks the reason in `pendingRebuild` and the whole pipeline
60
+ * runs again on the idle transition — waiting for real work to finish, rather than refusing it.
37
61
  *
38
62
  * Manual upgrade workflow (still supported):
39
63
  * npm run build && npm pack && npm install -g ./cortex-agent-server-X.Y.Z.tgz (package: @cortex-agent/server)
@@ -50,6 +74,7 @@ import { createResilientWatchMonitor } from '../core/resilient-watch.js';
50
74
  import { isMainModule, moduleDir, DATA_DIR, CONFIG_DIR, STORE_DIR, INSTALL_ROOT } from '../core/utils.js';
51
75
  import { planFastInstall, applyFastInstall } from './fast-install.js';
52
76
  import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
77
+ import { finishRebuildStep, planRebuildProgress, settleRebuildProgress, startRebuildStep, writeRebuildProgress, } from '../core/rebuild-progress.js';
53
78
  // Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
54
79
  // daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
55
80
  // the OS shell env. Must be sync and before the `CORTEX_REPO` constant below.
@@ -98,6 +123,7 @@ let restarting = false; // true while restart() stop→start cycle is in progres
98
123
  let rebuilding = false; // true while runRebuildPipeline() is running
99
124
  let nextRestartReason = null; // forwarded to next child via CORTEX_RESTART_REASON
100
125
  let watchMonitors = [];
126
+ let rebuildProgress = null; // published pipeline state (file + child IPC)
101
127
  // Daemon logs are written by the centralized logger (src/core/log.ts)
102
128
  // — console + daily-rotating file output in DATA_DIR/logs/.
103
129
  // --- Cancel all pending restart timers ---
@@ -239,23 +265,39 @@ function stopChild() {
239
265
  c.kill('SIGTERM');
240
266
  });
241
267
  }
268
+ /**
269
+ * Stop the child and start a fresh one. Resolves once the replacement has been forked.
270
+ *
271
+ * Returns 'deferred' when the cycle did not run: the child was mid-request, or another cycle owns
272
+ * the stop→start, and `pendingRestart` now carries the reason to the next idle transition. Callers
273
+ * that report progress need that distinction — a deferred restart leaves the OLD process serving.
274
+ *
275
+ * The child is told to hold new turns before anything else happens, including on the deferred
276
+ * paths: a restart that is waiting for idle wants the child to drain, not to take more work.
277
+ */
242
278
  async function restart(reason) {
243
279
  // Defer if child is busy processing a request
244
280
  if (childBusy) {
245
281
  log.info(`Restart deferred (app.ts is busy): ${reason}`);
246
282
  pendingRestart = reason;
247
- return;
283
+ holdChildTurns(true, 'restart', reason);
284
+ return 'deferred';
248
285
  }
249
286
  // Serialize: only one stop→start cycle at a time
250
287
  if (restarting) {
251
288
  log.info(`Restart deferred (already restarting): ${reason}`);
252
289
  pendingRestart = reason;
253
- return;
290
+ holdChildTurns(true, 'restart', reason);
291
+ return 'deferred';
254
292
  }
255
293
  cancelPendingTimers();
256
294
  log.info(`Restarting: ${reason}`);
257
295
  backoff = BACKOFF_INITIAL;
258
296
  restarting = true;
297
+ // The window this closes is the one that orphaned a turn on 2026-09-21: app.ts reported idle, the
298
+ // daemon began the stop, and a message landing in the same tick spawned a CLI whose stdout owner
299
+ // died a moment later. Between this line and SIGTERM the child admits nothing new.
300
+ holdChildTurns(true, 'restart', reason);
259
301
  await stopChild();
260
302
  restarting = false;
261
303
  // Absorb any restarts requested during the stop phase —
@@ -266,6 +308,7 @@ async function restart(reason) {
266
308
  }
267
309
  nextRestartReason = reason;
268
310
  startChild();
311
+ return 'restarted';
269
312
  }
270
313
  // --- File Watching ---
271
314
  function closeWatchers(watchers) {
@@ -496,10 +539,84 @@ function notifyChild(msg) {
496
539
  }
497
540
  catch { /* child went away — the log line still records it */ }
498
541
  }
499
- /** Single exit point for every pipeline abort: log it AND tell the operator. */
542
+ /** Tell the child to stop admitting new turns (or to resume). Sent on every phase change so the
543
+ * child's hold, which expires on its own, keeps being renewed for as long as the pipeline runs.
544
+ * A turn admitted after this point would be spawned into a process that is about to be SIGTERMed:
545
+ * its CLI child outlives the app that owns its stdout, so the answer is written to a pipe nobody
546
+ * is reading and the turn never completes. */
547
+ function holdChildTurns(hold, phase, reason) {
548
+ notifyChild({ type: 'rebuild-hold', hold, phase, reason });
549
+ }
550
+ /** Which published states close the child's turn gate.
551
+ *
552
+ * Only the two steps that touch the running process: `install` overwrites the files app.js loaded,
553
+ * `restart` kills it. The build steps before them read the repo and write `dist/` — a turn running
554
+ * during those is in no danger, and refusing it would be worse than useless: a refused waitpoint
555
+ * wake or background-agent result is dropped work, not delayed work (2026-09-21). Those two steps
556
+ * are only entered when app.ts is idle anyway, so the gate exists for the tick-level race — a
557
+ * message landing between the idle check and the SIGTERM.
558
+ *
559
+ * A queued restart (`pendingRestart`) holds regardless of the record: the build is over, but the
560
+ * process a turn would run in is still going to be replaced. */
561
+ export function rebuildHoldsTurns(progress, queuedRestart) {
562
+ if (queuedRestart)
563
+ return true;
564
+ if (!progress || progress.status !== 'running')
565
+ return false;
566
+ return progress.current === 'install' || progress.current === 'restart';
567
+ }
568
+ /** Publish pipeline state: keep it in memory, on disk for `system.daemonStatus`, and in the child's
569
+ * turn gate. One function so a phase can never reach one reader and not the others. */
570
+ function setRebuildProgress(next) {
571
+ rebuildProgress = next;
572
+ writeRebuildProgress(next);
573
+ const queuedRestart = pendingRestart !== null;
574
+ holdChildTurns(rebuildHoldsTurns(next, queuedRestart), next.current ?? (queuedRestart ? 'restart' : null), next.reason);
575
+ }
576
+ /** The steps a checkout will actually run, in order. Derived from `planRebuildSteps` so the build
577
+ * half cannot drift — a package that is absent is never published as pending — plus the two phases
578
+ * the build planner does not own. */
579
+ export function planRebuildStepNames(dirs) {
580
+ const names = planRebuildSteps(dirs).map((step) => step.label);
581
+ return [...names, 'install', 'restart'];
582
+ }
583
+ /** `planRebuildStepNames` for this process's checkout. */
584
+ function plannedProgressSteps() {
585
+ return planRebuildStepNames({
586
+ repoDir: CORTEX_REPO,
587
+ uiContractDir: UI_CONTRACT_DIR && existsSync(UI_CONTRACT_DIR) ? UI_CONTRACT_DIR : null,
588
+ webDir: WEB_DIR && existsSync(WEB_DIR) ? WEB_DIR : null,
589
+ });
590
+ }
591
+ /** The pipeline's last step, with the progress record closed out according to what restart() did. */
592
+ async function restartForRebuild(reason) {
593
+ updateRebuildProgress((progress) => startRebuildStep(progress, 'restart'));
594
+ const outcome = await restart(`src rebuild: ${reason}`);
595
+ updateRebuildProgress((progress) => (outcome === 'restarted'
596
+ ? settleRebuildProgress(finishRebuildStep(progress, 'restart', 'done'), 'succeeded')
597
+ : settleRebuildProgress(finishRebuildStep(progress, 'restart', 'skipped', 'app.ts busy'), 'deferred', 'Build and install succeeded; the restart is queued until app.ts goes idle.')));
598
+ }
599
+ /** Advance the published progress, if a pipeline is being tracked at all. */
600
+ function updateRebuildProgress(patch) {
601
+ if (!rebuildProgress)
602
+ return;
603
+ setRebuildProgress(patch(rebuildProgress));
604
+ }
605
+ /** Map an abort's step label onto the published step vocabulary. `tgz cleanup` and `pack` are
606
+ * phases of the same install step from the reader's point of view. */
607
+ function progressStepFor(label) {
608
+ if (label === 'server' || label === 'ui-contract' || label === 'web' || label === 'install')
609
+ return label;
610
+ if (label === 'pack' || label === 'tgz cleanup')
611
+ return 'install';
612
+ return null;
613
+ }
614
+ /** Single exit point for every pipeline abort: log it, mark the step failed, tell the operator. */
500
615
  function abortRebuild(step, detail, reason) {
501
616
  const text = buildRebuildAbortNotice({ step, detail, reason });
502
617
  log.error(text);
618
+ const failed = progressStepFor(step);
619
+ updateRebuildProgress((progress) => settleRebuildProgress(failed ? finishRebuildStep(progress, failed, 'failed', detail) : progress, 'aborted', text));
503
620
  notifyChild({ type: 'rebuild-aborted', text });
504
621
  }
505
622
  /** Run the ordered build steps. Returns false once any step fails (already reported). */
@@ -513,11 +630,16 @@ async function runBuildSteps(reason) {
513
630
  log.warn('WEB_DIR not found — skipping web build, pack will use stale web/dist if present');
514
631
  }
515
632
  for (const step of steps) {
633
+ const tracked = progressStepFor(step.label);
634
+ if (tracked)
635
+ updateRebuildProgress((progress) => startRebuildStep(progress, tracked));
516
636
  const code = await spawnAsync(step.cmd, step.args, { cwd: step.cwd });
517
637
  if (code !== 0) {
518
638
  abortRebuild(step.label, `exit ${code}`, reason);
519
639
  return false;
520
640
  }
641
+ if (tracked)
642
+ updateRebuildProgress((progress) => finishRebuildStep(progress, tracked, 'done'));
521
643
  }
522
644
  return true;
523
645
  }
@@ -601,19 +723,42 @@ async function runRebuildPipeline(reason) {
601
723
  return;
602
724
  }
603
725
  rebuilding = true;
726
+ let awaitingIdle = false;
604
727
  try {
605
728
  log.info(`Rebuild pipeline starting: ${reason}`);
729
+ // Publishing the plan before the first step is what makes the progress honest: the reader gets
730
+ // the total up front, including the steps that have not started.
731
+ setRebuildProgress(planRebuildProgress({
732
+ reason,
733
+ names: plannedProgressSteps(),
734
+ daemonPid: process.pid,
735
+ }));
606
736
  // Step 1: build the workspace packages in dependency order (server → ui-contract → web).
607
737
  if (!await runBuildSteps(reason))
608
738
  return;
739
+ // Second busy gate. The build above is minutes long and touches nothing the running child
740
+ // reads, so a turn can legitimately have started during it — and everything below does touch
741
+ // it: the install overwrites the files app.js loaded, the restart kills it. Rather than refuse
742
+ // that turn (a refused waitpoint wake or background-agent result is dropped work, not delayed
743
+ // work), abandon the install and let the idle transition run the whole pipeline again. The
744
+ // build outputs stay on disk, so the retry is the incremental cost of a second `npm run build`.
745
+ if (childBusy) {
746
+ log.info(`Rebuild install deferred (app.ts busy): ${reason} — retrying when app.ts goes idle`);
747
+ pendingRebuild = reason;
748
+ awaitingIdle = true;
749
+ updateRebuildProgress((progress) => settleRebuildProgress(progress, 'deferred', 'Build finished; install and restart wait for app.ts to go idle.'));
750
+ return;
751
+ }
609
752
  // Step 2: fast install. A src edit changes only the compiled output, so copying it into the
610
753
  // install root is equivalent to reinstalling — and skips rewriting the ~40k-file vendored
611
754
  // closure that `npm install -g` rm -rf's and re-extracts on every rebuild.
612
755
  const started = Date.now();
756
+ updateRebuildProgress((progress) => startRebuildStep(progress, 'install'));
613
757
  const synced = tryFastInstall();
614
758
  if (synced) {
615
759
  log.info(`Fast install: ${synced.join(', ')} in ${Date.now() - started}ms — restarting app.ts`);
616
- restart(`src rebuild: ${reason}`);
760
+ updateRebuildProgress((progress) => finishRebuildStep(progress, 'install', 'done', 'fast'));
761
+ await restartForRebuild(reason);
617
762
  return;
618
763
  }
619
764
  // Step 3: pack (clean old tgz first, otherwise readdir picks up a stale one)
@@ -628,17 +773,26 @@ async function runRebuildPipeline(reason) {
628
773
  abortRebuild('install', `exit ${installCode}`, reason);
629
774
  return;
630
775
  }
776
+ updateRebuildProgress((progress) => finishRebuildStep(progress, 'install', 'done', 'pack + install -g'));
631
777
  // Step 5: restart app.ts. This reuses the busy/idle gate inside restart() —
632
778
  // if a request snuck in between the busy-check above and now, restart() will
633
779
  // re-defer to pendingRestart. Either way, the new app.js boots from the freshly
634
780
  // installed dist/.
635
781
  log.info(`Rebuild succeeded — restarting app.ts`);
636
- restart(`src rebuild: ${reason}`);
782
+ await restartForRebuild(reason);
637
783
  }
638
784
  finally {
785
+ // An aborted pipeline already settled its own record; a run that reached here still `running`
786
+ // never restarted the child either, so releasing the hold is the honest close.
787
+ if (rebuildProgress?.status === 'running') {
788
+ setRebuildProgress(settleRebuildProgress(rebuildProgress, 'aborted', 'pipeline ended without restarting app.ts'));
789
+ }
790
+ rebuildProgress = null;
639
791
  rebuilding = false;
640
- // If src changed again while we were rebuilding, pick that up now.
641
- if (pendingRebuild) {
792
+ // If src changed again while we were rebuilding, pick that up now. A pipeline that deferred its
793
+ // own install is the one exception: its reason stays queued for the idle transition, because
794
+ // re-triggering here would rebuild every couple of seconds for as long as the turn lasts.
795
+ if (pendingRebuild && !awaitingIdle) {
642
796
  const next = pendingRebuild;
643
797
  pendingRebuild = null;
644
798
  log.info(`Consuming queued rebuild: ${next}`);
@@ -22,6 +22,7 @@ import { acquireSessionUseLease, acquireTurnBrowser, collectTurnFiles, releaseTu
22
22
  import { tryConsume as tryHumanAnswerBackstop } from './human-answer-backstop.js';
23
23
  import { downloadFiles as downloadPlatformFiles, inboundAttachmentKey, } from './routing/file-handler.js';
24
24
  import { acquireTurnMutationLock } from './turn-mutation-lock.js';
25
+ import { isRebuildHeld, refuseTurnForRebuild } from '../domain/system/rebuild-hold.js';
25
26
  const log = createLogger('agent-runner');
26
27
  export class AgentRunner {
27
28
  _enqueue;
@@ -49,6 +50,21 @@ export class AgentRunner {
49
50
  }
50
51
  async _routeWithAdmission(ctx, mutationRelease, loadPlatformFiles) {
51
52
  const { message, channel, adapter } = ctx;
53
+ // The supervisor is rebuilding or replacing this process (entry/daemon-notice.ts pushes the
54
+ // hold). A turn admitted now spawns a backend CLI whose stdout owner is about to be SIGTERMed:
55
+ // the CLI finishes, writes into a pipe nobody reads, and the turn hangs at "processing" forever
56
+ // (2026-09-21). Refused first, before anything is tracked, marked, leased or injected — a
57
+ // message folded into a turn that is about to die is lost just as thoroughly.
58
+ if (isRebuildHeld()) {
59
+ log.info(`Refusing turn on ${channel}: supervisor rebuild in progress`);
60
+ await refuseTurnForRebuild({
61
+ adapter,
62
+ channel,
63
+ text: ctx.userMessage || '',
64
+ interactive: message.senderId !== SYNTHETIC_CALLBACK_SENDER && !message.systemOrigin,
65
+ });
66
+ return false;
67
+ }
52
68
  // DR-0016 top-level fallback: if this channel has a pending human-escalated subtask question,
53
69
  // consume this message as the answer and short-circuit normal turn handling. Scope is narrow —
54
70
  // the backstop is disarmed unless this exact channel is awaiting a human reply, and it is armed
@@ -3,6 +3,7 @@ import type { AttachmentFailure } from './routing/file-handler.js';
3
3
  import { projectStore } from '../domain/projects/index.js';
4
4
  import { loadCommissionDraftContext, loadCommissionPromptContext, type CommissionPromptContext } from '../domain/commissions/commission-context.js';
5
5
  import type { RunRequest } from '../domain/runs/request.js';
6
+ import type { AgentSlotConfig } from '../core/types/thread-types.js';
6
7
  /** The ids the caller has already resolved for this turn. Mirrors the plan's `prepareRequest(ids)`
7
8
  * shape: everything else on {@link PrepareConversationRequestOptions} is per-surface turn input. */
8
9
  export interface ConversationSessionIds {
@@ -49,16 +50,48 @@ export interface PreparedRequest {
49
50
  * in history) of a Web UI direct session (`web:` channel — the only path where the user explicitly
50
51
  * binds the session to a project at create time), and only for real user projects (the `general`
51
52
  * umbrella carries no signal). Unknown/deleted project ids inject nothing rather than a dead path.
53
+ * An agent with `projectContext: false` opts out of the block entirely — "record your findings in
54
+ * the project" is operational noise in an environment built for something else.
52
55
  */
53
56
  export declare function resolveConversationProject(args: {
54
57
  channel: string;
55
58
  projectId: string;
56
59
  isFreshSession: boolean;
60
+ projectContext?: boolean;
57
61
  store?: Pick<typeof projectStore, 'get'>;
58
62
  }): {
59
63
  id: string;
60
64
  contextDir: string;
61
65
  } | null;
66
+ /**
67
+ * The policy one conversation turn opens under: the shared direct-run policy, the surface's own
68
+ * background intent, and the execution-environment fields the agent template declares.
69
+ *
70
+ * Every environment default equals what {@link DIRECT_RUN_POLICY} already said, so an agent that
71
+ * declares none of them produces that constant field for field — which is why adding the fields
72
+ * changed no existing session. `skills` and `settingSources` stay `undefined` rather than being
73
+ * defaulted here: absent means "whatever the backend loads on its own", and only the agent that
74
+ * opts out has an opinion.
75
+ */
76
+ export declare function conversationRunPolicy(agentConfig: AgentSlotConfig, opts: {
77
+ channel: string;
78
+ browserCdpEndpoint?: string | null;
79
+ }): RunRequest['policy'];
80
+ /**
81
+ * Which agent — which execution environment — a conversation turn opens under.
82
+ *
83
+ * The chain is the profile chain's twin: the session's own choice (what the composer set, or what
84
+ * `!agent` recorded on the session), then the channel's selection, then the global default, then
85
+ * `main`. `getDefaultAgent(channel)` already folds the middle two together.
86
+ *
87
+ * A candidate that no longer resolves is SKIPPED rather than fatal: an agent renamed or deleted
88
+ * since it was persisted must not kill every turn of the session that named it, exactly as an
89
+ * unknown channel profile falls back instead of throwing (see the run-config resolution below).
90
+ */
91
+ export declare function resolveConversationAgent(candidates: ReadonlyArray<string | null | undefined>, resolve?: (name: string) => AgentSlotConfig | null): {
92
+ agentName: string;
93
+ agentConfig: AgentSlotConfig;
94
+ };
62
95
  /** The delivery key for a session's current commission binding, or null outside the mode. Bound
63
96
  * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
64
97
  export declare function commissionBindingKey(session: {
@@ -46,9 +46,13 @@ function conversationBackgroundPolicy(channel) {
46
46
  * in history) of a Web UI direct session (`web:` channel — the only path where the user explicitly
47
47
  * binds the session to a project at create time), and only for real user projects (the `general`
48
48
  * umbrella carries no signal). Unknown/deleted project ids inject nothing rather than a dead path.
49
+ * An agent with `projectContext: false` opts out of the block entirely — "record your findings in
50
+ * the project" is operational noise in an environment built for something else.
49
51
  */
50
52
  export function resolveConversationProject(args) {
51
53
  const store = args.store ?? projectStore;
54
+ if (args.projectContext === false)
55
+ return null;
52
56
  if (!args.isFreshSession)
53
57
  return null;
54
58
  if (!args.channel.startsWith('web:'))
@@ -58,6 +62,63 @@ export function resolveConversationProject(args) {
58
62
  return null;
59
63
  return { id: project.id, contextDir: project.contextDir };
60
64
  }
65
+ /**
66
+ * The policy one conversation turn opens under: the shared direct-run policy, the surface's own
67
+ * background intent, and the execution-environment fields the agent template declares.
68
+ *
69
+ * Every environment default equals what {@link DIRECT_RUN_POLICY} already said, so an agent that
70
+ * declares none of them produces that constant field for field — which is why adding the fields
71
+ * changed no existing session. `skills` and `settingSources` stay `undefined` rather than being
72
+ * defaulted here: absent means "whatever the backend loads on its own", and only the agent that
73
+ * opts out has an opinion.
74
+ */
75
+ export function conversationRunPolicy(agentConfig, opts) {
76
+ return {
77
+ ...DIRECT_RUN_POLICY,
78
+ background: conversationBackgroundPolicy(opts.channel),
79
+ hooks: agentConfig.disableHooks !== true,
80
+ loadRules: agentConfig.loadRules !== false,
81
+ skills: agentConfig.skills,
82
+ settingSources: agentConfig.settingSources,
83
+ mcpComposition: agentConfig.mcpComposition ?? 'direct',
84
+ mcpToolAllowlist: agentConfig.mcpToolAllowlist,
85
+ browserCdpEndpoint: opts.browserCdpEndpoint ?? null,
86
+ };
87
+ }
88
+ /** The agent a conversation falls back to when nothing anywhere names one. */
89
+ const FALLBACK_AGENT = 'main';
90
+ /**
91
+ * Which agent — which execution environment — a conversation turn opens under.
92
+ *
93
+ * The chain is the profile chain's twin: the session's own choice (what the composer set, or what
94
+ * `!agent` recorded on the session), then the channel's selection, then the global default, then
95
+ * `main`. `getDefaultAgent(channel)` already folds the middle two together.
96
+ *
97
+ * A candidate that no longer resolves is SKIPPED rather than fatal: an agent renamed or deleted
98
+ * since it was persisted must not kill every turn of the session that named it, exactly as an
99
+ * unknown channel profile falls back instead of throwing (see the run-config resolution below).
100
+ */
101
+ export function resolveConversationAgent(candidates, resolve = resolveAgentSlotConfigByName) {
102
+ for (const name of [...candidates, FALLBACK_AGENT]) {
103
+ if (!name)
104
+ continue;
105
+ const agentConfig = resolve(name);
106
+ if (agentConfig)
107
+ return { agentName: name, agentConfig };
108
+ }
109
+ throw new Error(`Unknown default agent: ${FALLBACK_AGENT}`);
110
+ }
111
+ /** The agent recorded on the session record, if any. Best-effort: a registry read that fails leaves
112
+ * the channel's selection to answer, which is the same thing a session with no choice of its own
113
+ * would produce. */
114
+ async function sessionAgentName(sessionId) {
115
+ try {
116
+ return (await sessionStore.getById(sessionId))?.agentName ?? null;
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
61
122
  /** The delivery key for a session's current commission binding, or null outside the mode. Bound
62
123
  * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
63
124
  export function commissionBindingKey(session) {
@@ -124,15 +185,19 @@ export async function resolveConversationCommission(trackSessionId, args = {}, d
124
185
  */
125
186
  export async function prepareConversationRequest(opts) {
126
187
  const { sessionId, backendSessionId, sessionName, projectId } = opts.ids;
127
- const defaultAgentName = getDefaultAgent() || 'main';
128
- const agentConfig = resolveAgentSlotConfigByName(defaultAgentName);
129
- if (!agentConfig)
130
- throw new Error(`Unknown default agent: ${defaultAgentName}`);
188
+ const { agentConfig } = resolveConversationAgent([
189
+ await sessionAgentName(sessionId),
190
+ getDefaultAgent(opts.channel),
191
+ ]);
131
192
  // USER.md profile is injected only on a session's FIRST turn (no backend session yet).
132
193
  // Session resume keeps it in history thereafter, so re-sending it every turn just wastes tokens.
133
194
  const isFreshSession = backendSessionId === null;
134
- // A thread-free conversation runs on the direct MCP surface — there is no thread to control.
135
- const spec = fromAgentSlot(agentConfig, { mcpComposition: 'direct' });
195
+ // A thread-free conversation runs on the direct MCP surface — there is no thread to control —
196
+ // unless the agent declared a narrower one, which it owns on every path it runs.
197
+ const policy = conversationRunPolicy(agentConfig, {
198
+ channel: opts.channel, browserCdpEndpoint: opts.browserCdpEndpoint,
199
+ });
200
+ const spec = fromAgentSlot(agentConfig, { mcpComposition: policy.mcpComposition });
136
201
  // A plain conversation turn is thread-free: no artifact, no previous step, no control-plane
137
202
  // preamble. Everything it does carry is a first-turn ambient block, and the two prompt-shaping
138
203
  // fields come from the very spec the run is opened with — one description of the agent, not two.
@@ -140,7 +205,12 @@ export async function prepareConversationRequest(opts) {
140
205
  userContext: userProfileBlock(isFreshSession),
141
206
  // Web UI direct sessions are bound to a project at create time; tell the agent which one
142
207
  // on the session's first turn (see resolveConversationProject for the exact gating).
143
- project: resolveConversationProject({ channel: opts.channel, projectId, isFreshSession }),
208
+ project: resolveConversationProject({
209
+ channel: opts.channel,
210
+ projectId,
211
+ isFreshSession,
212
+ projectContext: agentConfig.projectContext,
213
+ }),
144
214
  // Commission sessions additionally get the contract + ledger index + protocol block, once per
145
215
  // binding rather than once per session (see resolveConversationCommission).
146
216
  commission: await resolveConversationCommission(sessionId, { isFreshSession }),
@@ -197,15 +267,7 @@ export async function prepareConversationRequest(opts) {
197
267
  commissionMode: opts.commissionMode ?? false,
198
268
  scheduleTaskId: opts.scheduleTaskId ?? null,
199
269
  },
200
- // The three fields that differ from the shared direct-run policy; every field NOT named here
201
- // is provably the `DIRECT_RUN_POLICY` value (background:'none' → this path's surface intent,
202
- // and browserCdpEndpoint:null → the session's opted-in Chrome, are the two it overrides).
203
- policy: {
204
- ...DIRECT_RUN_POLICY,
205
- background: conversationBackgroundPolicy(opts.channel),
206
- mcpToolAllowlist: agentConfig.mcpToolAllowlist,
207
- browserCdpEndpoint: opts.browserCdpEndpoint ?? null,
208
- },
270
+ policy,
209
271
  };
210
272
  return { request, backendPrompt };
211
273
  }
@@ -17,6 +17,9 @@ import { type InjectionLedgerDeps } from './transcript-sink.js';
17
17
  export interface LiveExecutionLike {
18
18
  backend: string;
19
19
  run?: AgentRun;
20
+ /** Stable Cortex session the run belongs to. A subagent child registers on its parent's channel
21
+ * with a null session, so this is what tells the conversation's own run apart from it. */
22
+ trackSessionId?: string | null;
20
23
  }
21
24
  /** Everything the injection ledger and the router need, bound by `buildInjectDeps`. */
22
25
  export interface MidTurnInjectDeps extends InjectionLedgerDeps {
@@ -30,11 +30,16 @@ export function isInjectableMessage(opts) {
30
30
  export function backendSupportsInject(backend) {
31
31
  return !!CAPABILITIES_BY_BACKEND[backend]?.has(Capability.MidTurnInject);
32
32
  }
33
- /** The newest live run on the channel. Capability is enforced by `run.steer()`, not inspected here. */
34
- function selectInjectRun(execs) {
33
+ /**
34
+ * The newest live run on the channel that belongs to the channel's own session. Background subagent
35
+ * children share the parent's channel and outlive the parent's turn; picking one of them sent the
36
+ * user's message into the child's stdin, where it was swallowed and the conversation never answered.
37
+ * Capability is enforced by `run.steer()`, not inspected here.
38
+ */
39
+ function selectInjectRun(execs, sessionId) {
35
40
  let best = null;
36
41
  for (const exec of execs) {
37
- if (exec.run)
42
+ if (exec.run && exec.trackSessionId === sessionId)
38
43
  best = { run: exec.run, backend: exec.backend };
39
44
  }
40
45
  return best;
@@ -65,7 +70,7 @@ function buildPendingRecord(deps, ctx, message, sessionId, backend, ts) {
65
70
  export async function tryInjectIntoLiveTurn(deps, ctx) {
66
71
  if (!isInjectableMessage(ctx) || !ctx.sessionId)
67
72
  return false;
68
- const target = selectInjectRun(deps.getLiveExecutions(ctx.channel));
73
+ const target = selectInjectRun(deps.getLiveExecutions(ctx.channel), ctx.sessionId);
69
74
  if (!target)
70
75
  return false;
71
76
  const platformAttachments = ctx.prepareBackendAttachments
@@ -31,8 +31,10 @@ function defaultDeps() {
31
31
  requeue: recordResume,
32
32
  buildResumeInput: (thread) => resumeThreadRunInput(thread, 'resume-rate-limited'),
33
33
  getThread: (id) => threadStore.get(id),
34
- channelBusy: (ch) => runRegistry.hasChannel(ch),
35
- directSessionBusy: (ch) => runRegistry.getByChannel(ch).some(e => !e.threadId),
34
+ // Subagent children ride on their parent's channel and outlive its turn; counting them read an
35
+ // idle conversation as busy, which dropped its direct resume and stalled threads behind it.
36
+ channelBusy: (ch) => runRegistry.getOwnByChannel(ch).length > 0,
37
+ directSessionBusy: (ch) => runRegistry.getOwnByChannel(ch).some(e => !e.threadId),
36
38
  acquireSessionUse: (sessionId) => acquireSessionUse(sessionId),
37
39
  track: trackPendingTask,
38
40
  delay: (ms) => new Promise((r) => setTimeout(r, ms)),