mixdog 1.4.4 → 1.4.5

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 (218) hide show
  1. package/package.json +1 -2
  2. package/src/cli.mjs +5 -1
  3. package/src/defaults/shipped-history.json +26 -2
  4. package/src/defaults/skills/browser-use/SKILL.md +148 -273
  5. package/src/defaults/skills/browser-use/references/devtools.md +14 -0
  6. package/src/defaults/skills/browser-use/references/page-flows.md +66 -0
  7. package/src/defaults/skills/browser-use/references/sign-in.md +70 -0
  8. package/src/defaults/skills/code-tidy/SKILL.md +60 -84
  9. package/src/defaults/skills/code-tidy/references/agent-cleanup.md +27 -2
  10. package/src/defaults/skills/computer-use/SKILL.md +145 -240
  11. package/src/defaults/skills/computer-use/references/flows.md +35 -0
  12. package/src/defaults/skills/computer-use/references/operations.md +22 -0
  13. package/src/defaults/skills/computer-use/references/platforms.md +12 -0
  14. package/src/defaults/skills/docx/SKILL.md +23 -31
  15. package/src/defaults/skills/docx/references/native-authoring.md +26 -3
  16. package/src/defaults/skills/docx/references/redlining.md +15 -0
  17. package/src/defaults/skills/image/SKILL.md +37 -77
  18. package/src/defaults/skills/image/references/prompt-forms.md +51 -0
  19. package/src/defaults/skills/image/references/text.md +6 -0
  20. package/src/defaults/skills/local-provider/SKILL.md +75 -105
  21. package/src/defaults/skills/local-provider/references/lifecycle.md +14 -0
  22. package/src/defaults/skills/local-provider/references/maintenance.md +19 -0
  23. package/src/defaults/skills/local-provider/references/recovery.md +30 -0
  24. package/src/defaults/skills/memory-management/SKILL.md +16 -20
  25. package/src/defaults/skills/pdf/SKILL.md +21 -23
  26. package/src/defaults/skills/pdf/references/blocks.md +20 -0
  27. package/src/defaults/skills/pdf/references/forms.md +12 -0
  28. package/src/defaults/skills/pdf/references/html.md +2 -2
  29. package/src/defaults/skills/pdf/references/ocr.md +7 -0
  30. package/src/defaults/skills/pdf/references/security.md +8 -0
  31. package/src/defaults/skills/pptx/SKILL.md +30 -109
  32. package/src/defaults/skills/pptx/references/audit.md +45 -0
  33. package/src/defaults/skills/pptx/references/brief-critique.md +47 -0
  34. package/src/defaults/skills/pptx/references/editing.md +24 -0
  35. package/src/defaults/skills/pptx/references/html.md +1 -1
  36. package/src/defaults/skills/pptx/references/script.md +33 -0
  37. package/src/defaults/skills/setup/SKILL.md +34 -102
  38. package/src/defaults/skills/setup/references/actions.md +72 -13
  39. package/src/defaults/skills/setup/references/surfaces.md +23 -8
  40. package/src/defaults/skills/setup-guide/SKILL.md +28 -115
  41. package/src/defaults/skills/setup-guide/references/features.md +36 -0
  42. package/src/defaults/skills/setup-guide/references/glossary.md +38 -0
  43. package/src/defaults/skills/setup-guide/references/workflow-models.md +62 -0
  44. package/src/defaults/skills/test-suite/SKILL.md +15 -127
  45. package/src/defaults/skills/test-suite/references/case-management.md +17 -9
  46. package/src/defaults/skills/test-suite/references/diagnose.md +23 -0
  47. package/src/defaults/skills/test-suite/references/prune.md +27 -0
  48. package/src/defaults/skills/test-suite/references/write.md +44 -0
  49. package/src/defaults/skills/video/SKILL.md +28 -42
  50. package/src/defaults/skills/video/references/prompting.md +31 -0
  51. package/src/defaults/skills/visualize/SKILL.md +73 -107
  52. package/src/defaults/skills/visualize/references/craft.md +1 -2
  53. package/src/defaults/skills/visualize/references/feedback.md +36 -0
  54. package/src/defaults/skills/visualize/references/showing.md +13 -0
  55. package/src/defaults/skills/xlsx/SKILL.md +23 -50
  56. package/src/defaults/skills/xlsx/references/editing.md +15 -0
  57. package/src/defaults/skills/xlsx/references/model-conventions.md +1 -1
  58. package/src/defaults/skills/xlsx/references/recalculation.md +37 -0
  59. package/src/defaults/skills/xlsx/references/report-design.md +18 -2
  60. package/src/lib/keychain-cjs.cjs +22 -1
  61. package/src/lib/rules-builder.cjs +1 -1
  62. package/src/rules/agent/AGENT.md +3 -0
  63. package/src/rules/lead/LEAD.md +3 -1
  64. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +8 -30
  65. package/src/runtime/agent/orchestrator/agent-runtime/title-completion.mjs +5 -0
  66. package/src/runtime/agent/orchestrator/mcp/oauth-request.mjs +21 -2
  67. package/src/runtime/agent/orchestrator/providers/account-pool.mjs +3 -0
  68. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +2 -2
  69. package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +2 -0
  70. package/src/runtime/agent/orchestrator/providers/anthropic-message-threads.mjs +583 -0
  71. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  72. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +81 -19
  73. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +180 -13
  74. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +56 -6
  75. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +4 -2
  76. package/src/runtime/agent/orchestrator/providers/gemini-error-contract.mjs +6 -6
  77. package/src/runtime/agent/orchestrator/providers/gemini-model-redirect.mjs +44 -0
  78. package/src/runtime/agent/orchestrator/providers/gemini-reasoning-relay.mjs +5 -0
  79. package/src/runtime/agent/orchestrator/providers/gemini-request-body.mjs +34 -5
  80. package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +10 -0
  81. package/src/runtime/agent/orchestrator/providers/gemini-schema.mjs +11 -6
  82. package/src/runtime/agent/orchestrator/providers/gemini-sdk-request.mjs +4 -100
  83. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +3 -227
  84. package/src/runtime/agent/orchestrator/providers/gemini.mjs +226 -118
  85. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +11 -1
  86. package/src/runtime/agent/orchestrator/providers/lib/claude-bridge-schema.mjs +15 -3
  87. package/src/runtime/agent/orchestrator/providers/lib/gemini-model-catalog.mjs +2 -1
  88. package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +5 -28
  89. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +50 -28
  90. package/src/runtime/agent/orchestrator/providers/openai-ws-stream/socket-handlers.mjs +14 -10
  91. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +1 -3
  92. package/src/runtime/agent/orchestrator/providers/stream-json-pool/worker-slots/slot-spawn.mjs +8 -3
  93. package/src/runtime/agent/orchestrator/providers/vertex-ai-maas.mjs +2 -2
  94. package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +4 -5
  95. package/src/runtime/agent/orchestrator/runtime-core/goal-tool-defs.mjs +2 -2
  96. package/src/runtime/agent/orchestrator/runtime-core/provider-request-tools.mjs +15 -8
  97. package/src/runtime/agent/orchestrator/runtime-core/session-title.mjs +1 -0
  98. package/src/runtime/agent/orchestrator/runtime-core/todo-list.mjs +9 -32
  99. package/src/runtime/agent/orchestrator/runtime-core/todo-tool-defs.mjs +4 -5
  100. package/src/runtime/agent/orchestrator/session/compact/summary-route.mjs +1 -3
  101. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +5 -2
  102. package/src/runtime/agent/orchestrator/session/loop/no-tool-turn/todo-check.mjs +2 -17
  103. package/src/runtime/agent/orchestrator/session/loop/usage.mjs +7 -3
  104. package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +9 -2
  105. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +26 -13
  106. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +4 -5
  107. package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +16 -5
  108. package/src/runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs +22 -1
  109. package/src/runtime/agent/orchestrator/session/store/live-state.mjs +4 -0
  110. package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +11 -9
  111. package/src/runtime/agent/orchestrator/tools/builtin/grep-formatting.mjs +2 -8
  112. package/src/runtime/agent/orchestrator/tools/builtin/lib/search-input-helpers.mjs +1 -9
  113. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +2 -2
  114. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +1 -1
  115. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +12 -3
  116. package/src/runtime/agent/orchestrator/tools/code-graph/ast-calls.mjs +9 -2
  117. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +137 -7
  118. package/src/runtime/agent/orchestrator/tools/code-graph/calls-cache.mjs +43 -14
  119. package/src/runtime/agent/orchestrator/tools/code-graph/calls-sidecar-worker.mjs +33 -0
  120. package/src/runtime/agent/orchestrator/tools/code-graph/disk-cache.mjs +146 -11
  121. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +31 -24
  122. package/src/runtime/agent/orchestrator/tools/code-graph/graph-binary/spawn-jsonl.mjs +172 -25
  123. package/src/runtime/agent/orchestrator/tools/code-graph/graph-model.mjs +100 -2
  124. package/src/runtime/agent/orchestrator/tools/code-graph/main-thread-slice.mjs +18 -0
  125. package/src/runtime/agent/orchestrator/tools/code-graph/mask-pool.mjs +219 -0
  126. package/src/runtime/agent/orchestrator/tools/code-graph/mask-worker.mjs +12 -0
  127. package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.mjs +6 -1
  128. package/src/runtime/agent/orchestrator/tools/code-graph/modes/calls.mjs +9 -2
  129. package/src/runtime/agent/orchestrator/tools/code-graph/modes/dependents.mjs +5 -1
  130. package/src/runtime/agent/orchestrator/tools/code-graph/modes/structure.mjs +8 -2
  131. package/src/runtime/agent/orchestrator/tools/code-graph/modes/symbols.mjs +14 -11
  132. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +41 -18
  133. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +391 -83
  134. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +109 -9
  135. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +73 -29
  136. package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +6 -5
  137. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +7 -3
  138. package/src/runtime/channels/lib/crash-log.mjs +21 -1
  139. package/src/runtime/channels/lib/worker-main.mjs +8 -25
  140. package/src/runtime/media/jobs.mjs +5 -0
  141. package/src/runtime/media/store.mjs +146 -3
  142. package/src/runtime/office/core/office-write-ledger.mjs +2 -2
  143. package/src/runtime/shared/agent-reap-state.mjs +19 -0
  144. package/src/runtime/shared/desktop-notice-host.d.mts +13 -0
  145. package/src/runtime/shared/desktop-notice-host.mjs +87 -0
  146. package/src/runtime/shared/file-lock.mjs +2 -2
  147. package/src/runtime/shared/heap-cap.mjs +9 -11
  148. package/src/runtime/shared/llm/http-agent.mjs +11 -1
  149. package/src/runtime/shared/llm/system-proxy.mjs +100 -25
  150. package/src/runtime/shared/llm/usage-accounting.mjs +18 -7
  151. package/src/runtime/shared/llm/usage-context.mjs +2 -2
  152. package/src/runtime/shared/llm/usage-ledger-requests.mjs +10 -3
  153. package/src/runtime/shared/llm/usage-ledger.mjs +13 -1
  154. package/src/runtime/shared/provider-accounts.mjs +22 -0
  155. package/src/runtime/shared/provider-auth-binding.mjs +2 -2
  156. package/src/runtime/shared/resource-admission.mjs +2 -2
  157. package/src/runtime/shared/root-async-context.mjs +51 -0
  158. package/src/runtime/shared/run-child.mjs +18 -1
  159. package/src/runtime/shared/slow-span.mjs +2 -2
  160. package/src/runtime/shared/tool-execution-owner.mjs +2 -2
  161. package/src/runtime/shared/tool-work-units.mjs +2 -0
  162. package/src/runtime/shared/turn-snapshot-store.mjs +75 -18
  163. package/src/runtime/shared/turn-worktree-snapshot.mjs +38 -8
  164. package/src/runtime/shared/user-cwd.mjs +2 -2
  165. package/src/runtime/shared/worker-requests.mjs +3 -1
  166. package/src/runtime/shared/worktrees/lock.mjs +2 -2
  167. package/src/runtime/visualize-bridge/client.mjs +26 -4
  168. package/src/runtime/visualize-bridge/tool-defs.mjs +46 -5
  169. package/src/session-runtime/boot/apis.mjs +1 -0
  170. package/src/session-runtime/boot/begin.mjs +2 -0
  171. package/src/session-runtime/media-api.mjs +15 -0
  172. package/src/session-runtime/provider-readiness.mjs +10 -2
  173. package/src/session-runtime/runtime-core.mjs +35 -8
  174. package/src/session-runtime/runtime-review-api.mjs +3 -1
  175. package/src/session-runtime/services/agent-tool/close-flow.mjs +6 -1
  176. package/src/session-runtime/services/agent-tool/execute-resume.mjs +94 -0
  177. package/src/session-runtime/services/agent-tool/execute-send.mjs +77 -27
  178. package/src/session-runtime/services/agent-tool/execute-spawn.mjs +28 -7
  179. package/src/session-runtime/services/agent-tool/execute.mjs +6 -1
  180. package/src/session-runtime/services/agent-tool/helpers.mjs +11 -0
  181. package/src/session-runtime/services/agent-tool/job-views/job-render.mjs +13 -10
  182. package/src/session-runtime/services/agent-tool/render.mjs +2 -0
  183. package/src/session-runtime/services/agent-tool/send-flow.mjs +1 -0
  184. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +6 -0
  185. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +2 -1
  186. package/src/session-runtime/services/agent-tool/tag-registry/reaped-sessions.mjs +82 -0
  187. package/src/session-runtime/services/agent-tool/tag-registry/record-facts-worker.mjs +36 -0
  188. package/src/session-runtime/services/agent-tool/tag-registry.mjs +4 -0
  189. package/src/session-runtime/services/agent-tool/terminal-reaper/row-helpers.mjs +29 -0
  190. package/src/session-runtime/services/agent-tool/terminal-reaper/scan-admission.mjs +11 -3
  191. package/src/session-runtime/services/agent-tool/terminal-reaper/stale-rows.mjs +19 -8
  192. package/src/session-runtime/services/agent-tool/terminal-reaper.mjs +5 -2
  193. package/src/session-runtime/services/agent-tool/worker-index.mjs +1 -0
  194. package/src/session-runtime/services/daemon-crash-capture/daemon-exit-record.mjs +2 -2
  195. package/src/session-runtime/session-create.mjs +5 -0
  196. package/src/session-runtime/setup-tool/settings-contract.mjs +2 -0
  197. package/src/session-runtime/usage-stats-api.mjs +3 -0
  198. package/src/session-runtime/workspace/admission-gate.mjs +25 -7
  199. package/src/session-runtime/workspace/transitions.mjs +4 -0
  200. package/src/standalone/daemon-log.mjs +28 -4
  201. package/src/standalone/daemon-owner.mjs +41 -7
  202. package/src/standalone/daemon-work-gate.mjs +139 -0
  203. package/src/standalone/daemon.mjs +80 -11
  204. package/src/standalone/desktop-service-registry.mjs +11 -4
  205. package/src/standalone/session-client.mjs +57 -5
  206. package/src/standalone/session-protocol.mjs +5 -0
  207. package/src/standalone/session-service/agent-tree/agent-cancel.mjs +17 -1
  208. package/src/standalone/session-service/agent-tree.mjs +7 -0
  209. package/src/standalone/session-service/session-calls/session-turns.mjs +12 -5
  210. package/src/standalone/session-transport/call-route.mjs +10 -4
  211. package/src/standalone/session-transport/routes.mjs +21 -0
  212. package/src/standalone/session-transport/stack.mjs +3 -1
  213. package/src/standalone/session-transport.mjs +5 -0
  214. package/src/tui/dist/index.mjs +495 -477
  215. package/src/tui/session/session-api/media.mjs +5 -0
  216. package/src/tui/session/turn.mjs +13 -0
  217. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/cancellation.mjs +0 -71
  218. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/reader.mjs +0 -108
@@ -14,6 +14,8 @@
14
14
  //
15
15
  // The unified host identity is set before the channels runtime is loaded so
16
16
  // worker-main skips its parent-IPC loop and this entry owns start()/stop().
17
+ // Before any request context exists: long-lived handles are created in this one.
18
+ initRootAsyncContext();
17
19
  process.env.MIXDOG_WORKER_MODE = process.env.MIXDOG_WORKER_MODE || '1';
18
20
  // This process owns session runtimes and must never proxy back into itself.
19
21
  process.env.MIXDOG_DAEMON_HOST = '1';
@@ -27,7 +29,7 @@ await import('../runtime/shared/sharp-electron-linux.mjs');
27
29
  // (handed over by the CLI or desktop that started this daemon, or read on
28
30
  // Windows when started alone) is applied to this process's fetch only; its
29
31
  // handoff variable is removed here so no child inherits it.
30
- (await import('../runtime/shared/llm/system-proxy.mjs')).adoptSystemProxy();
32
+ await (await import('../runtime/shared/llm/system-proxy.mjs')).adoptSystemProxyAsync();
31
33
  (await import('../runtime/shared/llm/http-agent.mjs')).adoptEnvProxy();
32
34
 
33
35
  // No V8 compile cache here, on purpose. Measured on this runtime: a cache hit
@@ -37,6 +39,7 @@ await import('../runtime/shared/sharp-electron-linux.mjs');
37
39
  // serialize it, turning a 110ms module graph into ~1.2s and taxing the ~900
38
40
  // lazily imported modules the same way.
39
41
 
42
+ import { initRootAsyncContext } from '../runtime/shared/root-async-context.mjs';
40
43
  import os from 'node:os';
41
44
  import path from 'node:path';
42
45
  import { rmSync } from 'node:fs';
@@ -75,6 +78,7 @@ import {
75
78
  import { createAgentDispatchBroker } from './agent-dispatch-broker.mjs';
76
79
  import { createChannelTransport } from './channel-transport.mjs';
77
80
  import { drainDeferral, idleGcEligible } from './daemon-drain-policy.mjs';
81
+ import { daemonWorkGate } from './daemon-work-gate.mjs';
78
82
  import { createDaemonPgStop } from './daemon-pg-stop.mjs';
79
83
  import { createChannelSessionRouter } from '../session-runtime/services/channel-session-router.mjs';
80
84
  import { createSessionTransport } from './session-transport.mjs';
@@ -96,6 +100,7 @@ import { registerTranscriptPurgeHook } from '../session-runtime/session-transcri
96
100
  import { createBootPhaseProfiler } from './boot-phase-profiler.mjs';
97
101
  import { createDaemonBootCoordinator } from './daemon-boot-coordinator.mjs';
98
102
  import { createDaemonLog } from './daemon-log.mjs';
103
+ import { crashEndsProcess } from '../runtime/channels/lib/crash-log.mjs';
99
104
  import { daemonCrashCaptureDir } from '../session-runtime/services/daemon-crash-capture/paths.mjs';
100
105
  import {
101
106
  installDaemonExitRecorder,
@@ -139,9 +144,13 @@ const LOG_PATH = path.join(DATA_DIR, 'daemon.log');
139
144
  const {
140
145
  log,
141
146
  flush: flushDaemonLogs,
147
+ flushSync: flushDaemonLogsSync,
142
148
  enableFileLogging,
143
149
  installRedirect: installDaemonLogRedirect,
144
150
  } = createDaemonLog({ logPath: LOG_PATH });
151
+ // Every synchronous exit (process.exit in a backstop or a lost claim, a fatal
152
+ // error) skips the async flush in shutdown(); keep the queued tail.
153
+ process.on('exit', flushDaemonLogsSync);
145
154
 
146
155
  // Every way this process ends leaves a reason + exit code in its crash-capture
147
156
  // sidecar (the launcher usually cannot: it is often gone before the daemon).
@@ -234,11 +243,26 @@ const SHUTDOWN_BUDGET_MS = 15_000;
234
243
  /** Graceful PostgreSQL stop bound inside that budget (pg_ctl stop -m fast). */
235
244
  const PG_STOP_TIMEOUT_MS = 6_000;
236
245
 
237
- async function shutdown(reason, code = 0) {
246
+ // A fatal error seen at any point (also while a teardown is already running)
247
+ // decides the exit status; both exit paths of shutdown() read it.
248
+ let fatalExit = null;
249
+
250
+ /** Records how this shutdown ends and returns the code to exit with. */
251
+ function settleExit(reason, code, error) {
252
+ if (fatalExit) {
253
+ exitRecorder.setReason(`shutdown: ${reason} (fatal ${fatalExit.label})`, 1, fatalExit.detail);
254
+ return 1;
255
+ }
256
+ exitRecorder.setReason(`shutdown: ${reason}`, code, error);
257
+ return code;
258
+ }
259
+
260
+ async function shutdown(reason, code = 0, error = null) {
238
261
  if (shuttingDown) return;
239
262
  shuttingDown = true;
263
+ daemonWorkGate.shutdown();
240
264
  ownerHeartbeat?.stop();
241
- exitRecorder.setReason(`shutdown: ${reason}`, code);
265
+ settleExit(reason, code, error);
242
266
  if (shutdownRecheckTimer) {
243
267
  clearTimeout(shutdownRecheckTimer);
244
268
  shutdownRecheckTimer = null;
@@ -249,8 +273,7 @@ async function shutdown(reason, code = 0) {
249
273
  // clean path still exits the moment teardown finishes.
250
274
  const forcedExit = setTimeout(() => {
251
275
  log('shutdown budget exceeded, forcing exit');
252
- exitRecorder.setReason(`shutdown: ${reason} (budget exceeded, forced exit)`, code);
253
- process.exit(code);
276
+ process.exit(settleExit(`${reason} (budget exceeded, forced exit)`, code, error));
254
277
  }, SHUTDOWN_BUDGET_MS);
255
278
  forcedExit.unref?.();
256
279
  // PostgreSQL stops after its users below (durable writes drained first), or
@@ -347,9 +370,16 @@ async function shutdown(reason, code = 0) {
347
370
  releaseSingletonOwner(OWNER_PATH, process.pid);
348
371
  } catch {}
349
372
  await flushDaemonLogs();
350
- process.exit(code);
373
+ process.exit(settleExit(reason, code, error));
351
374
  }
352
375
 
376
+ // An update install's hold counts what dies with this process: running
377
+ // sessions (turns, scheduled and routine runs, agents) and memory agents.
378
+ daemonWorkGate.setBusySource(() => {
379
+ const { busySessions, busyMemoryAgents } = inFlightWork();
380
+ return busySessions + busyMemoryAgents;
381
+ });
382
+
353
383
  /** Work actually running right now, across both front doors. Self-shutdown
354
384
  * asks whether this process may exit; idle GC asks whether a pause is safe. */
355
385
  function inFlightWork() {
@@ -415,6 +445,7 @@ daemonTelemetry = createDaemonTelemetry({
415
445
  * evict a busy one, so every self-shutdown trigger checks BOTH registries. */
416
446
  let _lastDeferredLog = { key: '', at: 0, suppressed: 0 };
417
447
  function maybeSelfShutdown(reason) {
448
+ if (shuttingDown) return;
418
449
  const channelClients = transport?.clientCount ?? 0;
419
450
  const sessionClients = sessionTransport?.clientCount ?? 0;
420
451
  const remoteClients = sessionService?.externalClientCount ?? 0;
@@ -913,7 +944,8 @@ async function main() {
913
944
  if (changed || incomplete || report.errors.length) {
914
945
  log(
915
946
  `worktree reconcile: removed ${report.removed.length}, recovered ${report.recovered.length}, ` +
916
- `pruned ${report.pruned.length}, incomplete ${incomplete}, errors ${report.errors.length}`
947
+ `pruned ${report.pruned.length}, incomplete ${incomplete}, errors ${report.errors.length}` +
948
+ (report.errors.length ? ` ${JSON.stringify(report.errors).slice(0, 2000)}` : '')
917
949
  );
918
950
  }
919
951
  })
@@ -952,10 +984,15 @@ async function main() {
952
984
  agentDispatchBroker = createAgentDispatchBroker({
953
985
  // Memory-cycle agents use the same lazy provider/orchestrator graph as
954
986
  // session actors; it stays unloaded until a real cycle requests it.
955
- dispatchAgent: (payload, options) => {
956
- if (!sessionRuntimeHost) throw new Error('session runtime host is not ready');
957
- return sessionRuntimeHost.agentDispatch(payload, options);
958
- },
987
+ // A memory cycle that comes due during an update install's hold waits for
988
+ // it instead of starting work the shutdown would abort.
989
+ dispatchAgent: daemonWorkGate.deferring(
990
+ (payload, options) => {
991
+ if (!sessionRuntimeHost) throw new Error('session runtime host is not ready');
992
+ return sessionRuntimeHost.agentDispatch(payload, options);
993
+ },
994
+ (_payload, options) => options?.signal
995
+ ),
959
996
  log,
960
997
  onActivityChanged: () => {
961
998
  maybeSelfShutdown('memory agent activity changed');
@@ -1140,6 +1177,7 @@ async function main() {
1140
1177
  } catch {}
1141
1178
  },
1142
1179
  onUpgradeRequested: requestDaemonReplacement,
1180
+ workGate: daemonWorkGate,
1143
1181
  admitWork: admitOwnerWorkAsync,
1144
1182
  });
1145
1183
  const sessionEndpoint = await bootPhases.measure('session-transport-start', () => sessionTransport.start());
@@ -1207,6 +1245,37 @@ process.on('message', (msg) => {
1207
1245
  if (msg && msg.type === 'shutdown') void shutdown('IPC shutdown');
1208
1246
  });
1209
1247
 
1248
+ // The daemon, not the channels runtime it hosts, ends the process on a fatal
1249
+ // error, so teardown (session stop, PG stop, log flush) always runs. Benign
1250
+ // transport errors stay survivable exactly as the channels runtime treats them.
1251
+ function onFatalError(label, err) {
1252
+ // 1. Diagnostics first, synchronously: crash.log (inside crashEndsProcess),
1253
+ // the exit record and the daemon log never wait on teardown.
1254
+ if (!crashEndsProcess(label, err)) return;
1255
+ const detail = err?.stack || err?.message || String(err);
1256
+ process.exitCode = 1;
1257
+ fatalExit ||= { label, detail };
1258
+ log(`${label}: ${err?.message || err}`);
1259
+ flushDaemonLogsSync();
1260
+ if (shuttingDown) {
1261
+ // A teardown already running (second fatal, or a signal) keeps its own
1262
+ // budget and is not restarted, but it now ends nonzero with this error.
1263
+ exitRecorder.setReason(`fatal ${label} during shutdown`, 1, detail);
1264
+ exitRecorder.write({ reason: `fatal ${label} during shutdown`, code: 1, error: detail });
1265
+ return;
1266
+ }
1267
+ exitRecorder.write({ reason: `fatal ${label}`, code: 1, error: detail });
1268
+ // 2./3. shutdown() flips shuttingDown synchronously (admission closes) and
1269
+ // carries its own bounded budget with a forced exit. A second fatal error
1270
+ // during teardown returns early there instead of re-entering.
1271
+ // 4. Whatever teardown does, the process ends nonzero.
1272
+ shutdown(`fatal ${label}`, 1, detail)
1273
+ .catch((e) => log(`fatal shutdown failed: ${e?.message || e}`))
1274
+ .finally(() => process.exit(1));
1275
+ }
1276
+ process.on('unhandledRejection', (err) => onFatalError('unhandled rejection', err));
1277
+ process.on('uncaughtException', (err) => onFatalError('uncaught exception', err));
1278
+
1210
1279
  main().catch((err) => {
1211
1280
  log(`fatal boot error: ${err?.stack || err?.message || err}`);
1212
1281
  void shutdown('fatal boot error', 2);
@@ -75,10 +75,11 @@ export class DesktopServiceRegistry {
75
75
  this.#onReady = onReady;
76
76
  }
77
77
 
78
+ /** Whether a desktop client is subscribed to receive `message`. */
78
79
  #publish(desktopId, message) {
79
80
  const wire = sanitizeForWire(message);
80
81
  const service = this.#servicesById.get(desktopId);
81
- if (!wire || !service) return;
82
+ if (!wire || !service) return false;
82
83
  this.#onFrame(
83
84
  {
84
85
  type: 'desktop-event',
@@ -88,6 +89,7 @@ export class DesktopServiceRegistry {
88
89
  },
89
90
  service.subscribers
90
91
  );
92
+ return service.subscribers.size > 0;
91
93
  }
92
94
 
93
95
  #require(desktopId) {
@@ -145,9 +147,8 @@ export class DesktopServiceRegistry {
145
147
  const instance = await loaded.createDesktopService({
146
148
  options: sanitizeForWire(options) || {},
147
149
  runtime: this.#runtime,
148
- emit: (message) => {
149
- if (ownsRecord()) this.#publish(requestedId, message);
150
- },
150
+ // Answers whether a desktop client was subscribed to receive it.
151
+ emit: (message) => ownsRecord() && this.#publish(requestedId, message),
151
152
  onClientCountChanged: () => {
152
153
  if (!ownsRecord()) return;
153
154
  try {
@@ -262,6 +263,12 @@ export class DesktopServiceRegistry {
262
263
  const { service, token } = this.#requireSubscribed(desktopId, ctx);
263
264
  this.#syncModelProxyPresence();
264
265
  this.#onReady({ desktopId: service.desktopId, clientToken: token || null });
266
+ // What the service could not deliver while nobody was attached goes now.
267
+ try {
268
+ service.instance.clientReady?.();
269
+ } catch (error) {
270
+ this.#log(`desktop service clientReady failed: ${error?.message || error}`);
271
+ }
265
272
  return { ok: true };
266
273
  }
267
274
 
@@ -662,14 +662,31 @@ export async function shutdownDaemon(
662
662
  * with it, so ask the serving one to stop (forced — its work cannot outlive
663
663
  * this tree anyway) and wait, bounded, for every such child's graceful exit.
664
664
  * One that already unpublished its endpoint is mid-teardown: only waited on.
665
- * False when no such child is alive (detached, or another launcher's). */
665
+ * The outcome says what happened, so a quit that ends in the tree kill can
666
+ * be told apart: `stopped` is false when no such child is alive (detached,
667
+ * or another launcher's) or one outlived the wait; `request` is `sent`,
668
+ * `failed` (with `error`), `no-discovery`, `not-in-tree` (daemon.json names
669
+ * another pid) or `none` (nothing in the tree). */
666
670
  export async function stopInTreeDaemon({
667
671
  timeoutMs = IN_TREE_DAEMON_STOP_GRACE_MS,
668
672
  discovery = readSessionDiscovery(),
669
673
  } = {}) {
674
+ const startedAt = Date.now();
670
675
  const pids = [...inTreeDaemons.keys()].filter((pid) => isPidAlive(pid));
671
- if (!pids.length) return false;
672
- if (discovery?.port && pids.includes(Number(discovery.pid))) {
676
+ const outcome = {
677
+ stopped: false,
678
+ inTree: pids,
679
+ discoveryPid: Number(discovery?.pid) || null,
680
+ request: 'none',
681
+ error: null,
682
+ elapsedMs: 0,
683
+ };
684
+ if (!pids.length) return outcome;
685
+ if (!discovery?.port) {
686
+ outcome.request = 'no-discovery';
687
+ } else if (!pids.includes(Number(discovery.pid))) {
688
+ outcome.request = 'not-in-tree';
689
+ } else {
673
690
  try {
674
691
  await request({
675
692
  port: discovery.port,
@@ -680,13 +697,48 @@ export async function stopInTreeDaemon({
680
697
  timeoutMs: 3000,
681
698
  control: true,
682
699
  });
683
- } catch {
700
+ outcome.request = 'sent';
701
+ } catch (error) {
684
702
  // Past its front door already: only the wait remains.
703
+ outcome.request = 'failed';
704
+ outcome.error = String(error?.message || error);
685
705
  }
686
706
  }
687
707
  const deadline = Date.now() + Math.max(1, Number(timeoutMs) || IN_TREE_DAEMON_STOP_GRACE_MS);
688
708
  while (pids.some((pid) => isPidAlive(pid)) && Date.now() < deadline) await delay(50);
689
- return !pids.some((pid) => isPidAlive(pid));
709
+ outcome.stopped = !pids.some((pid) => isPidAlive(pid));
710
+ outcome.elapsedMs = Date.now() - startedAt;
711
+ return outcome;
712
+ }
713
+
714
+ /** Before an update install tears the app down: close new-work admission on
715
+ * the in-tree daemon and read its running count in one daemon-side step.
716
+ * `held` — idle, admission stays closed until release (or the hold lapses);
717
+ * `busy` — turns run, admission was left open, `busy` is the count;
718
+ * `none` — no in-tree daemon serves, so the install kills nothing;
719
+ * `unknown` — the daemon could not be asked. `release` reopens admission. */
720
+ export async function holdInTreeDaemon({ release = false, ttlMs, discovery = readSessionDiscovery() } = {}) {
721
+ const pids = [...inTreeDaemons.keys()].filter((pid) => isPidAlive(pid));
722
+ if (!pids.length) return { status: 'none', busy: 0, error: null };
723
+ if (discovery?.port && !pids.includes(Number(discovery.pid))) return { status: 'none', busy: 0, error: null };
724
+ if (!discovery?.port) return { status: 'unknown', busy: 0, error: 'no daemon discovery' };
725
+ try {
726
+ const answer = await request({
727
+ port: discovery.port,
728
+ token: discovery.token,
729
+ method: 'POST',
730
+ path: '/install-hold',
731
+ body: release ? { action: 'release' } : { action: 'close', ttlMs },
732
+ timeoutMs: 3000,
733
+ control: true,
734
+ });
735
+ if (release) return { status: 'released', busy: 0, error: null };
736
+ if (answer?.held === true) return { status: 'held', busy: 0, error: null };
737
+ if (Number(answer?.busy) > 0) return { status: 'busy', busy: Number(answer.busy), error: null };
738
+ return { status: 'unknown', busy: 0, error: 'unexpected hold answer' };
739
+ } catch (error) {
740
+ return { status: 'unknown', busy: 0, error: String(error?.message || error) };
741
+ }
690
742
  }
691
743
 
692
744
  export async function shutdownDaemonForRuntimeRoot(root, options = {}) {
@@ -92,6 +92,7 @@ export const SESSION_READ_ACTIONS = Object.freeze([
92
92
  'listAgents',
93
93
  'listImportableConversations',
94
94
  'listMediaAssets',
95
+ 'listMediaBoards',
95
96
  'listMediaLanes',
96
97
  'listOutputStyles',
97
98
  'listPresets',
@@ -146,6 +147,10 @@ export const SESSION_CONFIGURE_ACTIONS = Object.freeze([
146
147
  'deleteHookRule',
147
148
  'deleteMediaAsset',
148
149
  'deleteMediaAssets',
150
+ 'createMediaBoard',
151
+ 'renameMediaBoard',
152
+ 'deleteMediaBoard',
153
+ 'setMediaAssetBoard',
149
154
  'deleteSchedule',
150
155
  'saveCustomProvider',
151
156
  'saveCustomProviderKey',
@@ -23,9 +23,25 @@ export function createAgentCancellation({
23
23
  entryForSession,
24
24
  log,
25
25
  rememberCancelTranscript,
26
+ markOwnerClosed,
26
27
  }) {
27
28
  const agentCloseRuns = new Map();
28
29
 
30
+ // The agent's owner closed it (options.ownerClose): recorded on the stored
31
+ // record itself once the runtime is closed, whichever close got it there —
32
+ // this one, an earlier one for another reason, or one already in progress.
33
+ async function closeOne(id, reason, options) {
34
+ const closed = await closeRuntime(id, reason, options);
35
+ if (closed && options.ownerClose === true) {
36
+ const outcome = { absent: false };
37
+ const generation = await markOwnerClosed(id, reason, { outcome });
38
+ if (typeof generation !== 'number' && outcome.absent !== true) {
39
+ throw new Error(`agent session ${id}: the owner close could not be recorded`);
40
+ }
41
+ }
42
+ return closed;
43
+ }
44
+
29
45
  /** The runtime entry that can close this descriptor: the live owner, else a
30
46
  * freshly loaded one (null when loading fails, which is logged). */
31
47
  const closableEntry = async (id, descriptor) => {
@@ -44,7 +60,7 @@ export function createAgentCancellation({
44
60
  }
45
61
  };
46
62
 
47
- function closeOne(id, reason, options) {
63
+ function closeRuntime(id, reason, options) {
48
64
  const active = agentCloseRuns.get(id);
49
65
  if (active) return active;
50
66
  let run;
@@ -24,6 +24,12 @@ export function createAgentTree({
24
24
  entryForSession,
25
25
  retainUnwatched,
26
26
  createSession,
27
+ // Sessions run inline in this daemon, so its own store records the owner
28
+ // close; loaded on first use only.
29
+ markOwnerClosed = async (...args) =>
30
+ (await import('../../runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs')).markSessionOwnerClosedAsync(
31
+ ...args
32
+ ),
27
33
  } = {}) {
28
34
  const registry = createAgentRegistry();
29
35
  const progress = new Map();
@@ -110,6 +116,7 @@ export function createAgentTree({
110
116
  entryForSession,
111
117
  log,
112
118
  rememberCancelTranscript,
119
+ markOwnerClosed,
113
120
  });
114
121
 
115
122
  /** The descriptor as callers see it: status from the live runtime when one
@@ -5,6 +5,7 @@
5
5
  // ./goal-recovery.mjs.
6
6
  import { createGoalRecovery } from './goal-recovery.mjs';
7
7
  import { createSessionTurnGate } from './turn-gate.mjs';
8
+ import { daemonWorkGate } from '../../daemon-work-gate.mjs';
8
9
  import {
9
10
  attachmentsForIntake,
10
11
  materializePromptSubmission,
@@ -79,11 +80,17 @@ export function createSessionTurnCalls(ctx) {
79
80
  }
80
81
  }
81
82
 
82
- async function submitSession(params = {}) {
83
- const id = String(params?.sessionId || '');
84
- if (!id) throw new TypeError('sessionId is required');
85
- return admitted(id, () => submitAdmitted(id, params));
86
- }
83
+ // Every in-daemon turn start (scheduled fires, routines, channel and
84
+ // agent-report turns) waits out an update install's hold rather than
85
+ // starting during the teardown; it is deferred, not dropped.
86
+ const submitSession = daemonWorkGate.deferring(
87
+ async (params = {}) => {
88
+ const id = String(params?.sessionId || '');
89
+ if (!id) throw new TypeError('sessionId is required');
90
+ return admitted(id, () => submitAdmitted(id, params));
91
+ },
92
+ (params) => params?.signal
93
+ );
87
94
 
88
95
  async function submitAdmitted(
89
96
  id,
@@ -7,6 +7,7 @@
7
7
  import { sendJson, sendError } from '../../runtime/memory/lib/http-wire.mjs';
8
8
  import { callSignature, callIdConflict, clientCallOwner } from '../rpc-call-identity.mjs';
9
9
  import { callLane } from './call-lanes.mjs';
10
+ import { createWorkGate } from '../daemon-work-gate.mjs';
10
11
 
11
12
  // These routes are safe to replay and can return large snapshots. Keeping
12
13
  // them in the mutation-dedup cache retained multiple transcript copies for a
@@ -44,7 +45,7 @@ function cachedDispatch(cached, callId, signature) {
44
45
  return cached.promise;
45
46
  }
46
47
 
47
- export function createCallRoute({ handleCall, clients, lanes, callCache, nowMs }) {
48
+ export function createCallRoute({ handleCall, clients, lanes, callCache, nowMs, workGate = createWorkGate() }) {
48
49
  return async function handleCallRequest(body, res) {
49
50
  const clientToken = body.token ? String(body.token) : null;
50
51
  const c = clientToken ? clients.get(clientToken) : null;
@@ -72,13 +73,18 @@ export function createCallRoute({ handleCall, clients, lanes, callCache, nowMs }
72
73
  } else {
73
74
  dispatch = lanes.dispatch(
74
75
  ownerKeyFor(clientToken, c, body.args),
75
- () =>
76
- handleCall(name, args, {
76
+ () => {
77
+ // The gate is asked again where the call actually starts: one that
78
+ // queued before a hold must not begin during the teardown.
79
+ const refusal = workGate.callRefusal(name);
80
+ if (refusal) throw Object.assign(new Error(refusal), { code: 'EINSTALLHOLD' });
81
+ return handleCall(name, args, {
77
82
  clientToken,
78
83
  leadPid: c.leadPid ?? null,
79
84
  cwd: c.cwd ?? null,
80
85
  revision: c.revision ?? 0,
81
- }),
86
+ });
87
+ },
82
88
  { lane: callLane(name, args) }
83
89
  );
84
90
  if (cacheKey) callCache.track(cacheKey, dispatch, signature);
@@ -53,6 +53,7 @@ export function createTransportRoutes({
53
53
  transportMemory,
54
54
  onClientsEmpty,
55
55
  onUpgradeRequested,
56
+ workGate,
56
57
  admitWork = () => true,
57
58
  }) {
58
59
  // Checked on every register/call, last right before the work is handed on
@@ -82,6 +83,7 @@ export function createTransportRoutes({
82
83
  modelProxy: modelProxyClientMode() ? 'client' : null,
83
84
  draining: drain.reason || null,
84
85
  drainCommitted: drain.committed,
86
+ installHold: workGate.held,
85
87
  version: runtimeVersion(),
86
88
  packageVersion: runtimeVersion(),
87
89
  buildHash: remoteInstallBuildHash(),
@@ -160,9 +162,27 @@ export function createTransportRoutes({
160
162
  // Again right before dispatch: the lease may have been fenced while the
161
163
  // body was still arriving.
162
164
  if (await refuseUnadmitted(res)) return;
165
+ const refusal = workGate.callRefusal(body.name);
166
+ if (refusal) {
167
+ sendError(res, refusal, 503);
168
+ return;
169
+ }
163
170
  await callRoute(body, res);
164
171
  };
165
172
 
173
+ // The desktop's update install asks to close the daemon's admission gate and
174
+ // read the running count in one step (daemon-work-gate.mjs): busy leaves it
175
+ // open, idle keeps it closed until `release`, shutdown, or the lease lapses.
176
+ const installHold = async (req, res) => {
177
+ const body = await readBody(req);
178
+ if (body.action === 'release') {
179
+ workGate.release();
180
+ sendJson(res, { ok: true, held: false });
181
+ return;
182
+ }
183
+ sendJson(res, { ok: true, ...workGate.hold(body.ttlMs) });
184
+ };
185
+
166
186
  const shutdown = (res) => {
167
187
  sendJson(res, { ok: true });
168
188
  if (typeof onClientsEmpty === 'function') {
@@ -230,6 +250,7 @@ export function createTransportRoutes({
230
250
  'POST /call': call,
231
251
  'POST /shutdown': (_req, res) => shutdown(res),
232
252
  'POST /stop': stop,
253
+ 'POST /install-hold': installHold,
233
254
  'POST /upgrade': upgrade,
234
255
  };
235
256
 
@@ -76,6 +76,7 @@ export function createTransportStack({
76
76
  onClientDropped,
77
77
  onUpgradeRequested,
78
78
  getStatus,
79
+ workGate,
79
80
  admitWork,
80
81
  }) {
81
82
  const body = createBodyReader();
@@ -113,7 +114,8 @@ export function createTransportStack({
113
114
  readBody: body.readBody,
114
115
  registry,
115
116
  lanes,
116
- callRoute: createCallRoute({ handleCall, clients, lanes, callCache, nowMs }),
117
+ callRoute: createCallRoute({ handleCall, clients, lanes, callCache, nowMs, workGate }),
118
+ workGate,
117
119
  attachSse,
118
120
  getStatus,
119
121
  transportMemory: () => ({
@@ -20,6 +20,7 @@ import http from 'node:http';
20
20
  import { randomUUID } from 'node:crypto';
21
21
  import { createLoopbackListener } from '../runtime/shared/loopback-listener.mjs';
22
22
  import { createTransportStack } from './session-transport/stack.mjs';
23
+ import { createWorkGate } from './daemon-work-gate.mjs';
23
24
 
24
25
  export function createSessionTransport({
25
26
  handleCall,
@@ -35,6 +36,9 @@ export function createSessionTransport({
35
36
  // Asked before every register/call; false answers 503 (the daemon's owner
36
37
  // lease is not held — daemon-owner.mjs).
37
38
  admitWork = () => true,
39
+ // The daemon's one admission gate; an embedder without one gets its own,
40
+ // counting the status' busy sessions.
41
+ workGate = createWorkGate({ busy: () => Number(getStatus()?.busy) || 0 }),
38
42
  } = {}) {
39
43
  if (typeof handleCall !== 'function') throw new Error('handleCall is required');
40
44
 
@@ -55,6 +59,7 @@ export function createSessionTransport({
55
59
  onClientDropped,
56
60
  onUpgradeRequested,
57
61
  getStatus,
62
+ workGate,
58
63
  admitWork,
59
64
  });
60
65