mixdog 1.4.3 → 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 (281) hide show
  1. package/package.json +1 -2
  2. package/src/cli.mjs +5 -1
  3. package/src/defaults/shipped-history.json +30 -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 -229
  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 +22 -21
  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 +73 -14
  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/agent-mode/MIXY.md +5 -3
  64. package/src/rules/lead/LEAD.md +3 -1
  65. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +8 -30
  66. package/src/runtime/agent/orchestrator/agent-runtime/title-completion.mjs +5 -0
  67. package/src/runtime/agent/orchestrator/mcp/oauth-request.mjs +21 -2
  68. package/src/runtime/agent/orchestrator/providers/account-pool.mjs +3 -0
  69. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +4 -3
  70. package/src/runtime/agent/orchestrator/providers/anthropic-api-request.mjs +11 -1
  71. package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +2 -0
  72. package/src/runtime/agent/orchestrator/providers/anthropic-message-threads.mjs +583 -0
  73. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  74. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +81 -19
  75. package/src/runtime/agent/orchestrator/providers/anthropic-sse-turn/turn-events/content-block-start.mjs +4 -0
  76. package/src/runtime/agent/orchestrator/providers/anthropic-sse-turn/turn-outcome.mjs +2 -0
  77. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +180 -13
  78. package/src/runtime/agent/orchestrator/providers/anthropic-turn-result.mjs +2 -0
  79. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +58 -6
  80. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +4 -2
  81. package/src/runtime/agent/orchestrator/providers/custom-provider-config.mjs +121 -9
  82. package/src/runtime/agent/orchestrator/providers/custom-provider.mjs +4 -1
  83. package/src/runtime/agent/orchestrator/providers/gemini-error-contract.mjs +6 -6
  84. package/src/runtime/agent/orchestrator/providers/gemini-model-redirect.mjs +44 -0
  85. package/src/runtime/agent/orchestrator/providers/gemini-reasoning-relay.mjs +5 -0
  86. package/src/runtime/agent/orchestrator/providers/gemini-request-body.mjs +34 -5
  87. package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +10 -0
  88. package/src/runtime/agent/orchestrator/providers/gemini-schema.mjs +11 -6
  89. package/src/runtime/agent/orchestrator/providers/gemini-sdk-request.mjs +4 -100
  90. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +3 -227
  91. package/src/runtime/agent/orchestrator/providers/gemini.mjs +226 -118
  92. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +11 -1
  93. package/src/runtime/agent/orchestrator/providers/lib/claude-bridge-schema.mjs +15 -3
  94. package/src/runtime/agent/orchestrator/providers/lib/gemini-model-catalog.mjs +2 -1
  95. package/src/runtime/agent/orchestrator/providers/lib/generation-window.mjs +9 -0
  96. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-send.mjs +9 -1
  97. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-result.mjs +2 -0
  98. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-state.mjs +5 -0
  99. package/src/runtime/agent/orchestrator/providers/openai-compat-options.mjs +3 -0
  100. package/src/runtime/agent/orchestrator/providers/openai-compat-response-normalization.mjs +2 -0
  101. package/src/runtime/agent/orchestrator/providers/openai-compat-responses.mjs +10 -1
  102. package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +5 -28
  103. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-events.mjs +3 -0
  104. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-outcome.mjs +2 -0
  105. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +50 -28
  106. package/src/runtime/agent/orchestrator/providers/openai-ws-response-state.mjs +9 -2
  107. package/src/runtime/agent/orchestrator/providers/openai-ws-stream/socket-handlers.mjs +14 -10
  108. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +1 -3
  109. package/src/runtime/agent/orchestrator/providers/openrouter-provider-routing.mjs +28 -0
  110. package/src/runtime/agent/orchestrator/providers/openrouter.mjs +4 -1
  111. package/src/runtime/agent/orchestrator/providers/registry.mjs +30 -25
  112. package/src/runtime/agent/orchestrator/providers/stream-json-pool/worker-slots/slot-spawn.mjs +8 -3
  113. package/src/runtime/agent/orchestrator/providers/vertex-ai-maas.mjs +2 -2
  114. package/src/runtime/agent/orchestrator/runtime-core/ask-user-result.mjs +66 -0
  115. package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +4 -5
  116. package/src/runtime/agent/orchestrator/runtime-core/goal-tool-defs.mjs +2 -2
  117. package/src/runtime/agent/orchestrator/runtime-core/provider-request-tools.mjs +15 -8
  118. package/src/runtime/agent/orchestrator/runtime-core/session-title.mjs +1 -0
  119. package/src/runtime/agent/orchestrator/runtime-core/todo-list.mjs +9 -32
  120. package/src/runtime/agent/orchestrator/runtime-core/todo-tool-defs.mjs +4 -5
  121. package/src/runtime/agent/orchestrator/session/compact/summary-route.mjs +1 -3
  122. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +5 -2
  123. package/src/runtime/agent/orchestrator/session/loop/no-tool-turn/todo-check.mjs +2 -17
  124. package/src/runtime/agent/orchestrator/session/loop/usage.mjs +7 -3
  125. package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +9 -2
  126. package/src/runtime/agent/orchestrator/session/manager/runtime-liveness.mjs +8 -1
  127. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +26 -13
  128. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +4 -5
  129. package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +16 -5
  130. package/src/runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs +22 -1
  131. package/src/runtime/agent/orchestrator/session/store/live-state.mjs +4 -0
  132. package/src/runtime/agent/orchestrator/session/store.mjs +12 -6
  133. package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +11 -9
  134. package/src/runtime/agent/orchestrator/tools/builtin/grep-formatting.mjs +2 -8
  135. package/src/runtime/agent/orchestrator/tools/builtin/lib/search-input-helpers.mjs +1 -9
  136. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-output-silence.mjs +64 -0
  137. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-task-output.mjs +20 -6
  138. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +2 -2
  139. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +1 -1
  140. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +12 -3
  141. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +12 -1
  142. package/src/runtime/agent/orchestrator/tools/code-graph/ast-calls.mjs +9 -2
  143. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +137 -7
  144. package/src/runtime/agent/orchestrator/tools/code-graph/calls-cache.mjs +43 -14
  145. package/src/runtime/agent/orchestrator/tools/code-graph/calls-sidecar-worker.mjs +33 -0
  146. package/src/runtime/agent/orchestrator/tools/code-graph/disk-cache.mjs +146 -11
  147. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +31 -24
  148. package/src/runtime/agent/orchestrator/tools/code-graph/graph-binary/spawn-jsonl.mjs +172 -25
  149. package/src/runtime/agent/orchestrator/tools/code-graph/graph-model.mjs +100 -2
  150. package/src/runtime/agent/orchestrator/tools/code-graph/main-thread-slice.mjs +18 -0
  151. package/src/runtime/agent/orchestrator/tools/code-graph/mask-pool.mjs +219 -0
  152. package/src/runtime/agent/orchestrator/tools/code-graph/mask-worker.mjs +12 -0
  153. package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.mjs +6 -1
  154. package/src/runtime/agent/orchestrator/tools/code-graph/modes/calls.mjs +9 -2
  155. package/src/runtime/agent/orchestrator/tools/code-graph/modes/dependents.mjs +5 -1
  156. package/src/runtime/agent/orchestrator/tools/code-graph/modes/structure.mjs +8 -2
  157. package/src/runtime/agent/orchestrator/tools/code-graph/modes/symbols.mjs +14 -11
  158. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +41 -18
  159. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +391 -83
  160. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +109 -9
  161. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +73 -29
  162. package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +6 -5
  163. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +7 -3
  164. package/src/runtime/channels/lib/crash-log.mjs +21 -1
  165. package/src/runtime/channels/lib/routines-db.mjs +35 -0
  166. package/src/runtime/channels/lib/schedules-db.mjs +4 -0
  167. package/src/runtime/channels/lib/webhooks-db.mjs +4 -0
  168. package/src/runtime/channels/lib/worker-main.mjs +8 -25
  169. package/src/runtime/computer-bridge/action-schema.mjs +2 -2
  170. package/src/runtime/computer-bridge/core-actions.mjs +16 -2
  171. package/src/runtime/computer-bridge/result-canonical.mjs +6 -0
  172. package/src/runtime/media/jobs.mjs +5 -0
  173. package/src/runtime/media/store.mjs +146 -3
  174. package/src/runtime/memory/tool-defs.mjs +1 -1
  175. package/src/runtime/office/core/office-write-ledger.mjs +2 -2
  176. package/src/runtime/shared/agent-reap-state.mjs +19 -0
  177. package/src/runtime/shared/desktop-notice-host.d.mts +13 -0
  178. package/src/runtime/shared/desktop-notice-host.mjs +87 -0
  179. package/src/runtime/shared/file-lock.mjs +2 -2
  180. package/src/runtime/shared/heap-cap.mjs +9 -11
  181. package/src/runtime/shared/llm/http-agent.mjs +11 -1
  182. package/src/runtime/shared/llm/system-proxy.mjs +100 -25
  183. package/src/runtime/shared/llm/usage-accounting.mjs +121 -19
  184. package/src/runtime/shared/llm/usage-context.mjs +3 -3
  185. package/src/runtime/shared/llm/usage-ledger-quota.mjs +2 -0
  186. package/src/runtime/shared/llm/usage-ledger-requests.mjs +190 -0
  187. package/src/runtime/shared/llm/usage-ledger-rollup.mjs +7 -3
  188. package/src/runtime/shared/llm/usage-ledger-worker.mjs +2 -0
  189. package/src/runtime/shared/llm/usage-ledger.mjs +69 -1
  190. package/src/runtime/shared/llm/usage-request-status.mjs +48 -0
  191. package/src/runtime/shared/provider-accounts.mjs +22 -0
  192. package/src/runtime/shared/provider-auth-binding.mjs +2 -2
  193. package/src/runtime/shared/resource-admission.mjs +2 -2
  194. package/src/runtime/shared/root-async-context.mjs +51 -0
  195. package/src/runtime/shared/run-child.mjs +18 -1
  196. package/src/runtime/shared/slow-span.mjs +2 -2
  197. package/src/runtime/shared/tool-execution-owner.mjs +2 -2
  198. package/src/runtime/shared/tool-result-summary.mjs +1 -1
  199. package/src/runtime/shared/tool-work-units.mjs +2 -0
  200. package/src/runtime/shared/turn-snapshot-store.mjs +75 -18
  201. package/src/runtime/shared/turn-worktree-snapshot.mjs +38 -8
  202. package/src/runtime/shared/user-cwd.mjs +2 -2
  203. package/src/runtime/shared/worker-requests.mjs +3 -1
  204. package/src/runtime/shared/worktrees/lock.mjs +2 -2
  205. package/src/runtime/visualize-bridge/client.mjs +26 -4
  206. package/src/runtime/visualize-bridge/tool-defs.mjs +46 -5
  207. package/src/session-runtime/agent-home-delivery.mjs +76 -8
  208. package/src/session-runtime/agent-task-sessions.mjs +63 -22
  209. package/src/session-runtime/boot/apis.mjs +16 -0
  210. package/src/session-runtime/boot/begin.mjs +2 -0
  211. package/src/session-runtime/boot/tools.mjs +8 -2
  212. package/src/session-runtime/internal-tool-executor/ask-user-tool.mjs +3 -58
  213. package/src/session-runtime/media-api.mjs +15 -0
  214. package/src/session-runtime/model-route/route-persist.mjs +12 -4
  215. package/src/session-runtime/provider-models/row-hydration.mjs +2 -0
  216. package/src/session-runtime/provider-readiness.mjs +10 -2
  217. package/src/session-runtime/routine-owner.mjs +9 -3
  218. package/src/session-runtime/runtime-core.mjs +35 -8
  219. package/src/session-runtime/runtime-review-api.mjs +3 -1
  220. package/src/session-runtime/services/agent-task-status.mjs +29 -1
  221. package/src/session-runtime/services/agent-tool/close-flow.mjs +6 -1
  222. package/src/session-runtime/services/agent-tool/execute-resume.mjs +94 -0
  223. package/src/session-runtime/services/agent-tool/execute-send.mjs +77 -27
  224. package/src/session-runtime/services/agent-tool/execute-spawn.mjs +28 -7
  225. package/src/session-runtime/services/agent-tool/execute.mjs +6 -1
  226. package/src/session-runtime/services/agent-tool/helpers.mjs +11 -0
  227. package/src/session-runtime/services/agent-tool/job-views/job-render.mjs +13 -10
  228. package/src/session-runtime/services/agent-tool/job-views/session-progress.mjs +3 -0
  229. package/src/session-runtime/services/agent-tool/render.mjs +8 -1
  230. package/src/session-runtime/services/agent-tool/send-flow.mjs +1 -0
  231. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +6 -0
  232. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +2 -1
  233. package/src/session-runtime/services/agent-tool/tag-registry/reaped-sessions.mjs +82 -0
  234. package/src/session-runtime/services/agent-tool/tag-registry/record-facts-worker.mjs +36 -0
  235. package/src/session-runtime/services/agent-tool/tag-registry.mjs +4 -0
  236. package/src/session-runtime/services/agent-tool/terminal-reaper/row-helpers.mjs +29 -0
  237. package/src/session-runtime/services/agent-tool/terminal-reaper/scan-admission.mjs +11 -3
  238. package/src/session-runtime/services/agent-tool/terminal-reaper/stale-rows.mjs +19 -8
  239. package/src/session-runtime/services/agent-tool/terminal-reaper.mjs +5 -2
  240. package/src/session-runtime/services/agent-tool/worker-index.mjs +1 -0
  241. package/src/session-runtime/services/channel-admin.mjs +44 -3
  242. package/src/session-runtime/services/daemon-crash-capture/daemon-exit-record.mjs +2 -2
  243. package/src/session-runtime/services/plugin-admin.mjs +46 -7
  244. package/src/session-runtime/services/provider-admin.mjs +5 -0
  245. package/src/session-runtime/session-create.mjs +5 -0
  246. package/src/session-runtime/setup-tool/agent-settings-actions.mjs +1 -1
  247. package/src/session-runtime/setup-tool/executor.mjs +1 -1
  248. package/src/session-runtime/setup-tool/extended-actions.mjs +1 -1
  249. package/src/session-runtime/setup-tool/settings-contract.mjs +4 -2
  250. package/src/session-runtime/usage-stats-api.mjs +120 -1
  251. package/src/session-runtime/workflow-agents-api/agent-connectors.mjs +36 -29
  252. package/src/session-runtime/workflow-agents-api/agent-editor.mjs +183 -23
  253. package/src/session-runtime/workspace/admission-gate.mjs +25 -7
  254. package/src/session-runtime/workspace/transitions.mjs +4 -0
  255. package/src/standalone/daemon-log.mjs +28 -4
  256. package/src/standalone/daemon-owner.mjs +41 -7
  257. package/src/standalone/daemon-work-gate.mjs +139 -0
  258. package/src/standalone/daemon.mjs +80 -11
  259. package/src/standalone/desktop-service-registry.mjs +11 -4
  260. package/src/standalone/session-client.mjs +57 -5
  261. package/src/standalone/session-protocol.mjs +6 -0
  262. package/src/standalone/session-service/agent-tree/agent-cancel.mjs +17 -1
  263. package/src/standalone/session-service/agent-tree.mjs +7 -0
  264. package/src/standalone/session-service/retention/busy.mjs +3 -2
  265. package/src/standalone/session-service/session-calls/session-turns.mjs +12 -5
  266. package/src/standalone/session-transport/call-route.mjs +10 -4
  267. package/src/standalone/session-transport/routes.mjs +21 -0
  268. package/src/standalone/session-transport/stack.mjs +3 -1
  269. package/src/standalone/session-transport.mjs +5 -0
  270. package/src/tui/app/model-picker/model-footer.mjs +1 -1
  271. package/src/tui/app/model-picker/provider-models-list.mjs +7 -3
  272. package/src/tui/app/model-picker/route-selection/fast-parameters.mjs +23 -3
  273. package/src/tui/app/model-picker/route-selection.mjs +1 -0
  274. package/src/tui/dist/index.mjs +536 -484
  275. package/src/tui/session/session-api/integrations.mjs +3 -0
  276. package/src/tui/session/session-api/media.mjs +5 -0
  277. package/src/tui/session/tool-approval-settle.mjs +24 -4
  278. package/src/tui/session/tool-approval.mjs +35 -10
  279. package/src/tui/session/turn.mjs +13 -0
  280. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/cancellation.mjs +0 -71
  281. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/reader.mjs +0 -108
@@ -16,7 +16,10 @@
16
16
  import { worktreeError, worktreeRefusal } from '../../runtime/shared/worktrees/contract.mjs';
17
17
  import { throwIfAborted } from '../../runtime/shared/worktrees/git.mjs';
18
18
  import { isWithin } from '../../runtime/shared/worktrees/paths.mjs';
19
- import { tryAdmitWorkspaceActivity } from '../../runtime/shared/worktrees/activity-gate.mjs';
19
+ import {
20
+ tryAdmitWorkspaceActivity,
21
+ tryAdmitWorkspaceActivityAsync,
22
+ } from '../../runtime/shared/worktrees/activity-gate.mjs';
20
23
  import { setTimeout as delay } from 'node:timers/promises';
21
24
 
22
25
  /** @type {Map<string, { txId: string, settled: Promise<void> }>} Lead session id → in-flight transition. */
@@ -42,10 +45,12 @@ function latch() {
42
45
 
43
46
  function once(fn) {
44
47
  let done = false;
48
+ let result;
45
49
  return () => {
46
- if (done) return;
47
- fn();
50
+ if (done) return result;
51
+ result = fn();
48
52
  done = true;
53
+ return result;
49
54
  };
50
55
  }
51
56
 
@@ -138,9 +143,13 @@ function settledOrAborted(promise, signal) {
138
143
  * Admit one turn of `sessionId`, whose live cwd is `cwd()`: waits while the
139
144
  * session itself transitions or another session holds the checkout the cwd
140
145
  * lies in, then registers the turn until the returned release is called.
141
- * An abort while waiting rejects and registers nothing.
146
+ * An abort while waiting rejects and registers nothing. The ledger grant is
147
+ * asked for without blocking this event loop, so a slow disk or a queue of
148
+ * other admissions never freezes the daemon; a change or abort that arrived
149
+ * while the answer was pending gives the grant back and is waited out.
150
+ * The release returns a promise that settles once every removal was attempted.
142
151
  * @param {{ sessionId: string, cwd: () => string, signal?: AbortSignal }} input
143
- * @returns {Promise<() => void>}
152
+ * @returns {Promise<() => Promise<void>>}
144
153
  */
145
154
  export async function admitTurn({ sessionId, cwd, signal }) {
146
155
  const id = key(sessionId);
@@ -151,25 +160,34 @@ export async function admitTurn({ sessionId, cwd, signal }) {
151
160
  await settledOrAborted(blocker, signal);
152
161
  continue;
153
162
  }
154
- const release = tryAdmitWorkspaceActivity(id, cwd());
163
+ const release = await tryAdmitWorkspaceActivityAsync(id, cwd());
155
164
  if (!release) {
156
165
  await delay(100, undefined, { signal });
157
166
  continue;
158
167
  }
168
+ if (signal?.aborted || admissionBlocker(id, cwd)) {
169
+ await release();
170
+ continue;
171
+ }
159
172
  const token = Symbol('turn');
160
173
  const leases = [release];
161
174
  turns.set(token, { sessionId: id, cwd, leases });
162
175
  return once(() => {
163
176
  const errors = [];
177
+ const pending = [];
164
178
  for (const leave of leases) {
165
179
  try {
166
- leave();
180
+ const settled = leave();
181
+ if (settled) pending.push(settled);
167
182
  } catch (error) {
168
183
  errors.push(error);
169
184
  }
170
185
  }
171
186
  turns.delete(token);
172
187
  if (errors.length) throw new AggregateError(errors, 'Workspace admission could not be released.');
188
+ const done = Promise.all(pending).then(() => {});
189
+ done.catch(() => {});
190
+ return done;
173
191
  });
174
192
  }
175
193
  }
@@ -24,6 +24,7 @@ import {
24
24
  resetReadStateAfterCompaction,
25
25
  } from '../../runtime/agent/orchestrator/session/cache/read-cache.mjs';
26
26
  import { buildWorkspacePromptContext } from '../../runtime/agent/orchestrator/session/manager/session-prompt-composition.mjs';
27
+ import { prewarmGitStartupProbes } from '../../runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs';
27
28
  import { refreshSessionWorkspaceContext } from '../../runtime/agent/orchestrator/session/manager/prompt-utils.mjs';
28
29
  import { AGENT_OWNER } from '../../runtime/agent/orchestrator/agent-owner.mjs';
29
30
  import { _liveSessions } from '../../runtime/agent/orchestrator/session/store/live-state.mjs';
@@ -71,6 +72,9 @@ export async function refreshWorkspacePrompt(
71
72
  // results. Conversation text remains historical evidence, not a file cache.
72
73
  clearReadDedupSession(session?.id);
73
74
  resetReadStateAfterCompaction(session?.id);
75
+ // The new root's git probes answer off-thread, so the synchronous prompt
76
+ // composition below finds them instead of spawning git on the event loop.
77
+ await prewarmGitStartupProbes([cwd]);
74
78
  const { environmentContext, instructionFilesContext } = buildWorkspacePromptContext(session, cwd, {
75
79
  instructionFilesMode,
76
80
  });
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import * as fs from 'node:fs/promises';
3
+ import * as fsSync from 'node:fs';
3
4
  import { inspect } from 'node:util';
4
5
  import { PLUGIN_LOG_MAX_BYTES, PLUGIN_LOG_KEEP_BYTES } from '../lib/mixdog-debug.cjs';
5
6
 
@@ -9,6 +10,7 @@ const LOG_QUEUE_MAX_BYTES = 512 * 1024;
9
10
  export function createDaemonLog({
10
11
  logPath,
11
12
  fileSystem = fs,
13
+ syncFileSystem = fsSync,
12
14
  stderr = process.stderr,
13
15
  stdout = process.stdout,
14
16
  consoleTarget = console,
@@ -36,15 +38,20 @@ export function createDaemonLog({
36
38
  }
37
39
  }
38
40
  if (fileBytes + incomingBytes <= PLUGIN_LOG_MAX_BYTES) return;
41
+ // Read-tail and rewrite run in one synchronous step: flushSync() (exit
42
+ // path) can then never land between them and be truncated away.
43
+ fileBytes = syncFileSystem.statSync(logPath).size;
39
44
  const keep = Math.min(fileBytes, PLUGIN_LOG_KEEP_BYTES);
40
45
  const tail = Buffer.allocUnsafe(keep);
41
- const handle = await fileSystem.open(logPath, 'r');
46
+ const handle = syncFileSystem.openSync(logPath, 'r');
42
47
  try {
43
- const { bytesRead } = await handle.read(tail, 0, keep, Math.max(0, fileBytes - keep));
44
- await fileSystem.writeFile(logPath, tail.subarray(0, bytesRead));
48
+ const bytesRead = syncFileSystem.readSync(handle, tail, 0, keep, Math.max(0, fileBytes - keep));
49
+ syncFileSystem.writeFileSync(logPath, tail.subarray(0, bytesRead));
45
50
  fileBytes = bytesRead;
46
51
  } finally {
47
- await handle.close().catch(() => {});
52
+ try {
53
+ syncFileSystem.closeSync(handle);
54
+ } catch {}
48
55
  }
49
56
  }
50
57
 
@@ -122,6 +129,22 @@ export function createDaemonLog({
122
129
  }
123
130
  }
124
131
 
132
+ /** Writes whatever is still queued, synchronously, for exits that never
133
+ * return to the event loop (process.exit, a fatal error). No rotation: the
134
+ * queue is bounded and the next async write rotates. */
135
+ function flushSync() {
136
+ clearFlushTimer();
137
+ const batch = takeBatch();
138
+ if (!batch) return;
139
+ try {
140
+ syncFileSystem.mkdirSync(path.dirname(logPath), { recursive: true });
141
+ syncFileSystem.appendFileSync(logPath, batch, 'utf8');
142
+ if (fileBytes !== null) fileBytes += Buffer.byteLength(batch);
143
+ } catch {
144
+ fileBytes = null;
145
+ }
146
+ }
147
+
125
148
  function log(line) {
126
149
  const text = `[daemon] ${line}`;
127
150
  // The spawner mirrors stderr before ready; after ready the daemon owns the
@@ -178,6 +201,7 @@ export function createDaemonLog({
178
201
  return {
179
202
  log,
180
203
  flush,
204
+ flushSync,
181
205
  installRedirect,
182
206
  enableFileLogging: () => {
183
207
  fileLogging = true;
@@ -266,8 +266,12 @@ export function daemonOwnerIsStale(
266
266
  * (recreating a deleted record), then calls `onBeat`.
267
267
  * - No successful refresh for `fenceMs`: fenced, never renewed (`onFenced`) —
268
268
  * unless the lease ran out inside one stall (live when the loop stopped):
269
- * then the refresh is retried every tick for `heartbeatMs` after the loop
270
- * resumes, and fenced only if none succeeds by then.
269
+ * then the refresh under the claim lock decides, however long it takes. It
270
+ * is retried every tick after the loop resumes; the record still naming
271
+ * this pid serves again, another pid's is `onSuperseded`, and fenced once a
272
+ * refresh started after the resume was refused and `heartbeatMs` of
273
+ * retries since then did not change that, or when none has answered
274
+ * `staleMs` after the resume.
271
275
  * - The record names another pid: `onSuperseded(record)`.
272
276
  * - A turn gap over `stallMs`: `admit()` refuses work until a refresh succeeds.
273
277
  * The gap is logged once, with `describeStall(fromMono, toMono)` appended.
@@ -280,6 +284,7 @@ export function createOwnerHeartbeat({
280
284
  fenceMs,
281
285
  tickMs,
282
286
  stallMs,
287
+ staleMs = daemonOwnerTimings().staleMs,
283
288
  now = Date.now,
284
289
  monoNow = () => performance.now(),
285
290
  refresh = refreshSingletonOwnerAsync,
@@ -298,6 +303,8 @@ export function createOwnerHeartbeat({
298
303
  let needsVerify = false;
299
304
  // Monotonic time the loop resumed from a stall that outlived the lease.
300
305
  let stallResumedAt = null;
306
+ // A refresh started since that resume was refused (claim lock busy, error).
307
+ let verifyDenied = false;
301
308
  // The refresh in flight: a promise of its settled status, else null.
302
309
  let pending = null;
303
310
  // When the latest stall was noticed: only a refresh started after it can
@@ -316,15 +323,32 @@ export function createOwnerHeartbeat({
316
323
  }
317
324
 
318
325
  // Expired and past re-verification: the refreshes failed while the loop
319
- // ran, or no refresh landed within `heartbeatMs` of resuming from a stall.
326
+ // ran, or a refresh started after the resume from a stall was refused and
327
+ // `heartbeatMs` of retries since then did not change that (a retry still in
328
+ // flight does not extend it). How long a verifying refresh takes proves
329
+ // nothing (the loop is often still starved right after a stall), so one not
330
+ // yet refused is waited for — but only for `staleMs` after the resume: a
331
+ // daemon that answers health probes while refusing all work would block
332
+ // every client with no one able to take over.
320
333
  function mustFence(t) {
321
- return leaseExpired(t) && !(stallResumedAt !== null && t - stallResumedAt < heartbeatMs);
334
+ if (!leaseExpired(t)) return false;
335
+ if (stallResumedAt === null) return true;
336
+ return resumeBoundPassed(t) || (verifyDenied && t - stallResumedAt >= heartbeatMs);
337
+ }
338
+
339
+ function resumeBoundPassed(t) {
340
+ return leaseExpired(t) && stallResumedAt !== null && t - stallResumedAt >= staleMs;
322
341
  }
323
342
 
324
343
  function fence(t) {
325
344
  if (state !== 'active') return;
345
+ const unanswered = stallResumedAt !== null && !verifyDenied;
326
346
  halt('fenced');
327
- log(`owner lease not refreshed for ${Math.round(t - leaseFrom)}ms (last ${lastRefreshAt}) — fencing`);
347
+ log(
348
+ unanswered
349
+ ? `owner lease verification unanswered ${Math.round(t - stallResumedAt)}ms after the loop resumed (last ${lastRefreshAt}) — fencing`
350
+ : `owner lease not refreshed for ${Math.round(t - leaseFrom)}ms (last ${lastRefreshAt}) — fencing`
351
+ );
328
352
  onFenced({ lastRefreshAt, sinceMs: Math.round(t - leaseFrom) });
329
353
  }
330
354
 
@@ -354,6 +378,12 @@ export function createOwnerHeartbeat({
354
378
  // moment the refresh started (`t`), never from when it answered.
355
379
  function settle(t, heartbeatAt, result) {
356
380
  if (state !== 'active') return result.status;
381
+ // A verification landing at or after the bound comes too late, whether or
382
+ // not a tick has fenced yet.
383
+ if (result.status === 'refreshed' && resumeBoundPassed(monoNow())) {
384
+ fence(monoNow());
385
+ return result.status;
386
+ }
357
387
  if (result.status === 'refreshed') {
358
388
  if (leaseExpired(t)) {
359
389
  log(
@@ -363,6 +393,7 @@ export function createOwnerHeartbeat({
363
393
  }
364
394
  leaseFrom = t;
365
395
  lastRefreshAt = heartbeatAt;
396
+ verifyDenied = false;
366
397
  if (t >= stallNotedAt) {
367
398
  needsVerify = false;
368
399
  stallResumedAt = null;
@@ -371,8 +402,11 @@ export function createOwnerHeartbeat({
371
402
  } else if (result.status === 'superseded') {
372
403
  halt('superseded');
373
404
  onSuperseded(result.owner);
374
- } else if (result.status === 'busy') {
375
- log('owner heartbeat skipped: claim lock busy');
405
+ } else {
406
+ if (result.status === 'busy') log('owner heartbeat skipped: claim lock busy');
407
+ // An older refresh (started before the resume) says nothing about the
408
+ // record now.
409
+ if (stallResumedAt !== null && t >= stallResumedAt) verifyDenied = true;
376
410
  }
377
411
  return result.status;
378
412
  }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * daemon-work-gate.mjs — the one admission gate for everything that starts work
3
+ * in this daemon. An update install closes it (hold) after reading the running
4
+ * count in the same step. While it is closed, HTTP session calls that start or
5
+ * change work are refused, and in-daemon starts wrapped by `deferring` (turn
6
+ * starts of scheduled, routine and channel work, memory agent dispatch) wait
7
+ * for it to reopen instead of being dropped; a waiter whose caller cancels, or
8
+ * the daemon's shutdown, rejects it. Work counts as running from the moment
9
+ * `deferring` admits it, so a hold can never slip in while a start is still
10
+ * preparing. A hold lapses by itself so an installer that died or gave up can
11
+ * never leave the daemon refusing work.
12
+ */
13
+ const HOLD_REFUSAL = 'daemon is holding new work for an update install';
14
+ const HOLD_DEFAULT_MS = 120_000;
15
+ const HOLD_MAX_MS = 5 * 60_000;
16
+
17
+ // Reads and the calls that let the user stop or answer work already running.
18
+ export const HOLD_ALLOWED_CALLS = new Set([
19
+ 'session.list',
20
+ 'session.read',
21
+ 'session.subscribe',
22
+ 'session.unsubscribe',
23
+ 'session.abort',
24
+ 'session.approve',
25
+ 'project.list',
26
+ 'project.inspect',
27
+ 'desktop.control',
28
+ 'desktop.ready',
29
+ 'desktop.init',
30
+ 'desktop.unsubscribe',
31
+ ]);
32
+
33
+ export function createWorkGate({ busy = () => 0 } = {}) {
34
+ let busySource = busy;
35
+ let held = false;
36
+ let closed = null;
37
+ let timer = null;
38
+ let starting = 0;
39
+ let waiters = new Set();
40
+ const busyNow = () => Math.max(0, Number(busySource()) || 0) + starting;
41
+
42
+ const open = () => {
43
+ held = false;
44
+ clearTimeout(timer);
45
+ timer = null;
46
+ const woken = waiters;
47
+ waiters = new Set();
48
+ for (const waiter of woken) waiter.resolve();
49
+ };
50
+
51
+ /** Resolves when the hold ends; rejects when `signal` aborts or the gate is shut down. */
52
+ const waitForOpen = (signal) =>
53
+ new Promise((resolve, reject) => {
54
+ if (closed) return reject(closed);
55
+ if (signal?.aborted) return reject(signal.reason ?? new Error('aborted'));
56
+ const waiter = {
57
+ resolve: () => {
58
+ signal?.removeEventListener('abort', onAbort);
59
+ resolve();
60
+ },
61
+ reject: (reason) => {
62
+ signal?.removeEventListener('abort', onAbort);
63
+ reject(reason);
64
+ },
65
+ };
66
+ const onAbort = () => {
67
+ waiters.delete(waiter);
68
+ waiter.reject(signal.reason ?? new Error('aborted'));
69
+ };
70
+ signal?.addEventListener('abort', onAbort, { once: true });
71
+ waiters.add(waiter);
72
+ });
73
+
74
+ return {
75
+ get held() {
76
+ return held;
77
+ },
78
+ setBusySource(source) {
79
+ busySource = source;
80
+ },
81
+ /** Why a session call may not run now, or null. */
82
+ callRefusal(name) {
83
+ return held && !HOLD_ALLOWED_CALLS.has(String(name || '')) ? HOLD_REFUSAL : null;
84
+ },
85
+ /** Running work: the embedder's count plus starts admitted and still preparing. */
86
+ busy: busyNow,
87
+ /** `start` wrapped as an admitted work start: it waits out a hold (and
88
+ * never runs if `signalOf(...args)` aborts meanwhile), then counts as
89
+ * running until it settles — which covers its preparation up to the point
90
+ * the work is registered by the embedder's own count. */
91
+ deferring:
92
+ (start, signalOf = () => undefined) =>
93
+ async (...args) => {
94
+ const signal = signalOf(...args);
95
+ // Shutdown and cancellation are judged on every pass, right before the
96
+ // count and the start with no await between: a wake-up that raced a
97
+ // shutdown or an abort must not start the work.
98
+ for (;;) {
99
+ if (closed) throw closed;
100
+ if (signal?.aborted) throw signal.reason ?? new Error('aborted');
101
+ if (!held) break;
102
+ await waitForOpen(signal);
103
+ }
104
+ starting += 1;
105
+ try {
106
+ return await start(...args);
107
+ } finally {
108
+ starting -= 1;
109
+ }
110
+ },
111
+ /** Reads the running count and closes admission with no gap between: busy
112
+ * leaves (or puts) it open, idle keeps it closed until release or lapse. */
113
+ hold(ttlMs) {
114
+ const running = busyNow();
115
+ if (running > 0) {
116
+ open();
117
+ return { held: false, busy: running };
118
+ }
119
+ clearTimeout(timer);
120
+ held = true;
121
+ timer = setTimeout(open, Math.min(HOLD_MAX_MS, Math.max(1_000, Number(ttlMs) || HOLD_DEFAULT_MS)));
122
+ timer.unref?.();
123
+ return { held: true, busy: 0 };
124
+ },
125
+ release: open,
126
+ /** The daemon is stopping: every waiter rejects and admission stays as it is. */
127
+ shutdown(reason = 'daemon is shutting down') {
128
+ closed = reason instanceof Error ? reason : new Error(String(reason));
129
+ clearTimeout(timer);
130
+ timer = null;
131
+ const woken = waiters;
132
+ waiters = new Set();
133
+ for (const waiter of woken) waiter.reject(closed);
134
+ },
135
+ };
136
+ }
137
+
138
+ /** This process's gate: the daemon wires its busy count and both front doors. */
139
+ export const daemonWorkGate = createWorkGate();
@@ -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