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
@@ -1,5 +1,7 @@
1
1
  // Row-level predicates shared by the terminal-reaper modules.
2
2
  import { stampMs } from '../helpers.mjs';
3
+ import { ACTIVE_STAGES } from '../tool-def.mjs';
4
+ import { resolveAgentTerminalReapMs } from '../../../../runtime/agent/orchestrator/runtime-core/config-helpers.mjs';
3
5
  import { isTerminalWorkerStatus, tagTombstoneKey } from '../worker-rows.mjs';
4
6
 
5
7
  /** Latest proof of life on the session record itself. createdAt is included
@@ -18,6 +20,33 @@ export function isTerminalRow(row) {
18
20
  return isTerminalWorkerStatus(row.status || row.stage);
19
21
  }
20
22
 
23
+ // A settled row stays indexed this long after it finished, and in any case until
24
+ // its own continuation (reap) window has ended.
25
+ export const SETTLED_ROW_RETENTION_MS = 24 * 60 * 60 * 1000;
26
+
27
+ /** Whether a settled record has aged out of the index: past the retention
28
+ * floor and past its continuation deadline (`reapAt` when stamped, else the
29
+ * provider's resolved window). `record` is a worker row or a session: both
30
+ * carry the same stamp fields, so pruning a row and admitting a session scan
31
+ * one rule over its latest activity stamp. Decided by stamps alone. */
32
+ export function pastSettledRetention(config, record, now = Date.now()) {
33
+ const settledAtMs = sessionActivityAt(record);
34
+ if (!(settledAtMs > 0) || now - settledAtMs < SETTLED_ROW_RETENTION_MS) return false;
35
+ const stamped = stampMs(record.reapAt);
36
+ return now >= (stamped > 0 ? stamped : settledAtMs + resolveAgentTerminalReapMs(config, record.provider));
37
+ }
38
+
39
+ /** In-memory proof that a session is still in use (a running or just-resumed
40
+ * turn, a queued delivery, a controller not yet aborted). Never loads a
41
+ * session record. */
42
+ export function sessionHasLiveWork(mgr, sessionId) {
43
+ if (mgr.isSessionTurnInFlight?.(sessionId) === true || mgr.hasPendingMessages?.(sessionId) === true) return true;
44
+ const runtime = mgr.getSessionRuntime?.(sessionId) || null;
45
+ if (runtime?.controller?.signal && !runtime.controller.signal.aborted) return true;
46
+ const stage = runtime?.stage;
47
+ return Boolean(stage && ACTIVE_STAGES.has(stage));
48
+ }
49
+
21
50
  export function insertTombstone(tombstonesByKey, priorityTombstoneKeys, tombstone) {
22
51
  const key = tagTombstoneKey(tombstone);
23
52
  tombstonesByKey.set(key, tombstone);
@@ -3,9 +3,9 @@
3
3
  import { clean, stampMs } from '../helpers.mjs';
4
4
  import { isTerminalWorkerStatus } from '../worker-rows.mjs';
5
5
  import { ACTIVE_STAGES } from '../tool-def.mjs';
6
- import { sessionActivityAt } from './row-helpers.mjs';
6
+ import { pastSettledRetention, sessionActivityAt } from './row-helpers.mjs';
7
7
 
8
- export function createScanAdmission({ mgr, index, tombstoneBlocksScan }) {
8
+ export function createScanAdmission({ cfgMod, mgr, index, tombstoneBlocksScan }) {
9
9
  const { readWorkerRows, upsertWorkerSessionDeferred } = index;
10
10
 
11
11
  function scanSessionIsTerminal(session) {
@@ -42,6 +42,14 @@ export function createScanAdmission({ mgr, index, tombstoneBlocksScan }) {
42
42
  };
43
43
  }
44
44
 
45
+ /** A settled session past its retention would be re-indexed with its frozen
46
+ * stamps only to be aged out again (once its tombstone expired or was
47
+ * capped), so a scan never admits it. */
48
+ function scanSessionAgedOut(session) {
49
+ if (!scanSessionIsTerminal(session)) return false;
50
+ return pastSettledRetention(cfgMod.loadConfig(), session);
51
+ }
52
+
45
53
  // Shared session-scan admission: returns false when the scan must not
46
54
  // resurrect this session, otherwise indexes it (terminal sessions with their
47
55
  // own stamps).
@@ -52,5 +60,5 @@ export function createScanAdmission({ mgr, index, tombstoneBlocksScan }) {
52
60
  return true;
53
61
  }
54
62
 
55
- return { scanUpsertSession };
63
+ return { scanUpsertSession, scanSessionAgedOut };
56
64
  }
@@ -2,35 +2,46 @@
2
2
  // last row stamp is older than the reap window becomes a tombstone so its tag is
3
3
  // freed instead of blocking spawn forever.
4
4
  import { clean, positiveInt } from '../helpers.mjs';
5
+ import { isUnnotifiedRestartFailure } from '../worker-index/row-liveness.mjs';
5
6
  import { TAG_TOMBSTONE_TTL_MS, isLeadPoolAgent, workerRowTime } from '../worker-rows.mjs';
6
7
  import { resolveAgentTerminalReapMs } from '../../../../runtime/agent/orchestrator/runtime-core/config-helpers.mjs';
7
- import { insertTombstone, isTerminalRow } from './row-helpers.mjs';
8
+ import { insertTombstone, isTerminalRow, pastSettledRetention, sessionHasLiveWork } from './row-helpers.mjs';
8
9
 
9
- export function createStaleRowTransition({ cfgMod, tagMaps, index, getLiveSession }) {
10
+ export function createStaleRowTransition({ cfgMod, mgr, tagMaps, index, getLiveSession }) {
10
11
  const { readWorkerRows, writeWorkerRows, flushWorkerIndexMutations } = index;
11
12
 
12
13
  function transitionStaleNonterminalRows(context = {}) {
14
+ const now = Date.now();
15
+ const config = cfgMod.loadConfig();
13
16
  const staleRows = readWorkerRows(context).filter((row) => {
14
17
  if (isLeadPoolAgent(row.agent)) return false;
15
- if (isTerminalRow(row)) return false;
18
+ // Settled rows age out of the index (the tombstone keeps the tag's reap
19
+ // note); an owed restart failure is the only record of that result, and
20
+ // a session still in use in this process keeps its row.
21
+ if (isTerminalRow(row)) {
22
+ if (isUnnotifiedRestartFailure(row)) return false;
23
+ if (!pastSettledRetention(config, row, now) || sessionHasLiveWork(mgr, clean(row.sessionId))) return false;
24
+ return true;
25
+ }
16
26
  if (getLiveSession(clean(row.sessionId))) return false;
17
27
  const rowTime = workerRowTime(row);
18
- const reapMs = resolveAgentTerminalReapMs(cfgMod.loadConfig(), row.provider);
28
+ const reapMs = resolveAgentTerminalReapMs(config, row.provider);
19
29
  // A row with no timestamp has no usable stamp at all. Explicitly
20
30
  // disabled terminal reaping still gets the tombstone TTL as a finite
21
31
  // staleness bound, so malformed/running index rows cannot block a
22
32
  // tag forever.
23
- return rowTime <= 0 || Date.now() - rowTime >= (reapMs ?? TAG_TOMBSTONE_TTL_MS);
33
+ return rowTime <= 0 || now - rowTime >= (reapMs ?? TAG_TOMBSTONE_TTL_MS);
24
34
  });
25
35
  if (staleRows.length === 0) return false;
26
36
  flushWorkerIndexMutations();
27
37
  const nowIso = new Date().toISOString();
38
+ const reapedIds = new Set(staleRows.map((row) => clean(row.sessionId)));
28
39
  writeWorkerRows((byKey, tombstonesByKey, priorityTombstoneKeys) => {
40
+ for (const [key, candidate] of byKey) {
41
+ if (reapedIds.has(clean(candidate.sessionId))) byKey.delete(key);
42
+ }
29
43
  for (const row of staleRows) {
30
44
  const sessionId = clean(row.sessionId);
31
- for (const [key, candidate] of [...byKey.entries()]) {
32
- if (clean(candidate.sessionId) === sessionId) byKey.delete(key);
33
- }
34
45
  const tombstone = {
35
46
  tag: clean(row.tag),
36
47
  agent: clean(row.agent) || null,
@@ -10,15 +10,18 @@ import { createStaleRowTransition } from './terminal-reaper/stale-rows.mjs';
10
10
  export function createTerminalReaper({ cfgMod, mgr, tagMaps, index, getLiveSession }) {
11
11
  const tombstones = createTagTombstones({ tagMaps, index });
12
12
  const scan = createScanAdmission({
13
+ cfgMod,
13
14
  mgr,
14
15
  index,
15
16
  tombstoneBlocksScan: tombstones.tombstoneBlocksScan,
16
17
  });
17
- const { transitionStaleNonterminalRows } = createStaleRowTransition({ cfgMod, tagMaps, index, getLiveSession });
18
+ const tombstoneBlocksScan = (session, tag, map) =>
19
+ scan.scanSessionAgedOut(session) || tombstones.tombstoneBlocksScan(session, tag, map);
20
+ const { transitionStaleNonterminalRows } = createStaleRowTransition({ cfgMod, mgr, tagMaps, index, getLiveSession });
18
21
 
19
22
  return {
20
23
  tagTombstoneIndex: tombstones.tagTombstoneIndex,
21
- tombstoneBlocksScan: tombstones.tombstoneBlocksScan,
24
+ tombstoneBlocksScan,
22
25
  scanUpsertSession: scan.scanUpsertSession,
23
26
  forgetTerminalSession: tombstones.forgetTerminalSession,
24
27
  tombstoneTerminalSession: tombstones.tombstoneTerminalSession,
@@ -110,6 +110,7 @@ export function createWorkerIndex({ dataDir, cfgMod, mgr, tags, tagAgents, tagCw
110
110
  upsertWorkerRow(rowFromSession(session, fallbackTag, extra), { defer: true }),
111
111
  removeWorkerRow,
112
112
  markReleased,
113
+ isReleased: store.isReleased,
113
114
  setAwaitingUser: awaitingUser.setAwaitingUser,
114
115
  refreshTagsFromIndex,
115
116
  flushActiveWorkerRows: settlement.flushActiveWorkerRows,
@@ -137,8 +137,8 @@ export function installDaemonExitRecorder({
137
137
  });
138
138
 
139
139
  return {
140
- setReason(reason, code = 0) {
141
- pending = { reason, code, error: null };
140
+ setReason(reason, code = 0, error = null) {
141
+ pending = { reason, code, error };
142
142
  },
143
143
  write,
144
144
  };
@@ -8,6 +8,7 @@ import { runAbortable, throwIfAborted } from '../runtime/shared/abort-race.mjs';
8
8
  import { elapsedMs, prepareRoute } from './session-create/route-prep.mjs';
9
9
  import { materializeSession, prewarmWsTransport } from './session-create/materialize.mjs';
10
10
  import { dispatchSessionStart } from './session-create/session-start-hook.mjs';
11
+ import { prewarmGitStartupProbes } from '../runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs';
11
12
  import { SessionClosedError } from '../runtime/agent/orchestrator/session/manager/session-errors.mjs';
12
13
  import {
13
14
  SessionAddressError,
@@ -67,7 +68,11 @@ export function createSessionCreator(deps, routes) {
67
68
  }
68
69
 
69
70
  async function buildSession(reason, signal, startedAt) {
71
+ // materializeSession composes the git startup line synchronously; its
72
+ // probes answer off-thread alongside route prep instead of blocking there.
73
+ const gitProbes = prewarmGitStartupProbes([rt.currentCwd]);
70
74
  const { coreMemoryContext, providerImpl } = await prepareRoute(deps, routes, signal, startedAt);
75
+ await gitProbes;
71
76
  // The fence/record may have changed during the awaits above (close during
72
77
  // reservation prewarm): re-validate synchronously right before adoption.
73
78
  assertAdmissionOpen(rt);
@@ -56,6 +56,7 @@ export const SETUP_ACTIVITY_RAIL_PIN_IDS = Object.freeze([
56
56
  'source-control',
57
57
  'search',
58
58
  'webhooks',
59
+ 'studio',
59
60
  ]);
60
61
 
61
62
  export const SETUP_EXTENDED_DOMAINS = Object.freeze([
@@ -236,6 +237,7 @@ export const SETUP_EXTENDED_PROPERTIES = Object.freeze({
236
237
  usageRailSlotsAll: boolean,
237
238
  computerObserveOnly: boolean,
238
239
  browserAutoSignIn: boolean,
240
+ browserHidDevices: boolean,
239
241
  saveChatLogins: boolean,
240
242
  notificationVolume: {
241
243
  type: 'integer',
@@ -190,6 +190,9 @@ async function describeRequestSessions(requests, sessionMetadata) {
190
190
  const id = String(sourceType || '')
191
191
  .trim()
192
192
  .toLowerCase();
193
+ // A title call is recorded under the session it titles: that session
194
+ // stays openable, so it is named like any other background request.
195
+ if (id === 'session-title') return id;
193
196
  const hidden = id && !isLeadVisibleRow({ sourceType: id, preview: id });
194
197
  return hidden && (id === 'exec' || !isConversationUsageSource(id)) ? id : '';
195
198
  };
@@ -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();