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
@@ -31,6 +31,13 @@ export function killChildTree(child) {
31
31
  /** The child has exited (an exit code or the signal that ended it). */
32
32
  const childEnded = (child) => child.exitCode !== null || child.signalCode !== null;
33
33
 
34
+ // How long an exited child's pipes may stay open before its output is taken
35
+ // as complete. On Windows a process another thread of this process creates at
36
+ // the same moment (a long-lived server, say) can inherit this child's pipe
37
+ // ends and hold them open for its whole life, so 'close' would never come;
38
+ // what the child wrote before exiting is already in the pipes.
39
+ export const EXIT_DRAIN_MS = 1_000;
40
+
34
41
  /**
35
42
  * `waitForExitMs` (> 0): a timeout rejects only once the killed child has
36
43
  * exited, or after that many more ms; the error then carries `pid` and
@@ -68,10 +75,12 @@ export function runChild({
68
75
  let stdinError = null;
69
76
  let settled = false;
70
77
  let timedOut = false;
78
+ let drainTimer = null;
71
79
  const finish = (error, result) => {
72
80
  if (settled) return;
73
81
  settled = true;
74
82
  clearTimeout(timer);
83
+ clearTimeout(drainTimer);
75
84
  if (error) rejectPromise(error);
76
85
  else resolvePromise(result);
77
86
  };
@@ -129,7 +138,7 @@ export function runChild({
129
138
  // An error while a timeout terminates the child (a failed kill) is the timeout's.
130
139
  if (!timedOut) finish(error);
131
140
  });
132
- child.once('close', (code) => {
141
+ const complete = (code) => {
133
142
  // A timed-out child's close is the timeout's to report.
134
143
  if (timedOut) return;
135
144
  const result = {
@@ -144,6 +153,14 @@ export function runChild({
144
153
  return;
145
154
  }
146
155
  finish(null, result);
156
+ };
157
+ child.once('close', complete);
158
+ child.once('exit', (code) => {
159
+ drainTimer = setTimeout(() => {
160
+ child.stdout.destroy?.();
161
+ child.stderr.destroy?.();
162
+ complete(code);
163
+ }, EXIT_DRAIN_MS);
147
164
  });
148
165
  if (child.stdin) {
149
166
  // A short-lived child can close before stdin is flushed. Keep that
@@ -6,14 +6,14 @@
6
6
  // names the spans that overlapped the stall window. Spans carry labels and
7
7
  // phase durations only — never payloads.
8
8
 
9
- import { AsyncLocalStorage } from 'node:async_hooks';
10
9
  import { performance } from 'node:perf_hooks';
10
+ import { runtimeAsyncLocalStorage } from './root-async-context.mjs';
11
11
 
12
12
  export const SPAN_RING_MIN_MS = 25;
13
13
  export const SPAN_SLOW_MS = 1000;
14
14
  export const SPAN_RING_CAPACITY = 64;
15
15
 
16
- const current = new AsyncLocalStorage();
16
+ const current = runtimeAsyncLocalStorage();
17
17
 
18
18
  /** Short, log-safe id of a session id. */
19
19
  export function shortId(id) {
@@ -1,6 +1,6 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
1
+ import { runtimeAsyncLocalStorage } from './root-async-context.mjs';
2
2
 
3
- const toolExecutionOwner = new AsyncLocalStorage();
3
+ const toolExecutionOwner = runtimeAsyncLocalStorage();
4
4
 
5
5
  export function runWithToolExecutionOwner(ownerKey, run) {
6
6
  const owner =
@@ -358,6 +358,8 @@ function visualizeUnit(a) {
358
358
  return unitDescriptor('Visualize', { count: 1, active: 'Checking', done: 'Checked', noun: 'page' });
359
359
  if (action === 'inspect')
360
360
  return unitDescriptor('Visualize', { count: 1, active: 'Inspecting', done: 'Inspected', noun: 'page' });
361
+ if (action === 'act')
362
+ return unitDescriptor('Visualize', { count: 1, active: 'Operating', done: 'Operated', noun: 'page' });
361
363
  if (action === 'close')
362
364
  return unitDescriptor('Visualize', { count: 1, active: 'Closing', done: 'Closed', noun: 'tab' });
363
365
  return unitDescriptor('Visualize', { count: 1, active: 'Showing', done: 'Showed', noun: 'artifact' });
@@ -499,16 +499,30 @@ function changesPath(sessionId) {
499
499
  return join(changesRoot(), `${hash}.json`);
500
500
  }
501
501
 
502
+ /** The session's changes file; null when it is not a changes file of this
503
+ * session. An unreadable or unparsable file throws. */
504
+ async function parseChangesFile(sessionId) {
505
+ const parsed = JSON.parse(await readFile(changesPath(sessionId), 'utf8'));
506
+ if (parsed?.version !== CHANGES_VERSION || parsed.sessionId !== sessionId) return null;
507
+ return Array.isArray(parsed.records) ? parsed : null;
508
+ }
509
+
502
510
  async function readChangesFile(sessionId) {
503
511
  try {
504
- const parsed = JSON.parse(await readFile(changesPath(sessionId), 'utf8'));
505
- if (parsed?.version !== CHANGES_VERSION || parsed.sessionId !== sessionId) return null;
506
- return Array.isArray(parsed.records) ? parsed : null;
512
+ return await parseChangesFile(sessionId);
507
513
  } catch {
508
514
  return null;
509
515
  }
510
516
  }
511
517
 
518
+ function deepFreeze(value) {
519
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
520
+ Object.freeze(value);
521
+ for (const child of Object.values(value)) deepFreeze(child);
522
+ }
523
+ return value;
524
+ }
525
+
512
526
  /** Evict the oldest turns until the session fits its byte budget; a turn that
513
527
  * alone exceeds it drops its largest patches (those files stop being
514
528
  * revertable) instead of the whole record. */
@@ -558,7 +572,12 @@ async function writeChangeRecords(sessionId, records) {
558
572
  changesSweepDone = true;
559
573
  void sweepDirectory(changesRoot(), CHANGE_RECORD_TTL_MS, MAX_CHANGE_RECORD_FILES);
560
574
  }
561
- await writeJsonAtomically(changesPath(sessionId), { version: CHANGES_VERSION, sessionId, records });
575
+ try {
576
+ await writeJsonAtomically(changesPath(sessionId), { version: CHANGES_VERSION, sessionId, records });
577
+ } finally {
578
+ // A read between the drop above and the rename may have cached the old file.
579
+ changeRecordsCache.delete(sessionId);
580
+ }
562
581
  }
563
582
 
564
583
  const changeContent = (record) =>
@@ -652,39 +671,77 @@ export async function loadTurnChangeRecord(sessionId, checkpointId) {
652
671
  const id = clean(sessionId);
653
672
  const key = clean(checkpointId);
654
673
  if (!id || !key) return null;
655
- const records = (await readChangesFile(id))?.records || [];
674
+ const records = await loadTurnChangeRecords(id);
656
675
  return records.find((record) => record?.checkpointId === key) || null;
657
676
  }
658
677
 
659
678
  // Parsed change records by session, valid while the file's mtime and size are
660
- // unchanged: the session review refreshes every few seconds and must not
661
- // re-read and re-parse a multi-megabyte file each time. Callers never mutate.
679
+ // unchanged: the session review and every turn card read the same multi-
680
+ // megabyte file and must not re-read and re-parse it each time. An entry holds
681
+ // the parse's promise, so concurrent readers of one file share a single parse.
682
+ // Least recently used first; bounded by session count and by the summed file
683
+ // bytes (the newest entry always stays, however large). Records are shared and
684
+ // deep-frozen, and every write drops the entry.
662
685
  const changeRecordsCache = new Map();
663
686
  const CHANGE_RECORDS_CACHE_SESSIONS = 8;
687
+ const CHANGE_RECORDS_CACHE_BYTES = 64 * 1024 * 1024;
688
+
689
+ function trimChangeRecordsCache() {
690
+ let bytes = 0;
691
+ for (const entry of changeRecordsCache.values()) bytes += entry.bytes;
692
+ while (
693
+ changeRecordsCache.size > 1 &&
694
+ (changeRecordsCache.size > CHANGE_RECORDS_CACHE_SESSIONS || bytes > CHANGE_RECORDS_CACHE_BYTES)
695
+ ) {
696
+ const [oldest, entry] = changeRecordsCache.entries().next().value;
697
+ changeRecordsCache.delete(oldest);
698
+ bytes -= entry.bytes;
699
+ }
700
+ }
664
701
 
665
702
  /** Every retained turn's change record of a session, oldest first. */
666
703
  export async function loadTurnChangeRecords(sessionId) {
667
704
  const id = clean(sessionId);
668
705
  if (!id) return [];
669
- let signature = '';
706
+ let info;
670
707
  try {
671
- const info = await stat(changesPath(id));
672
- signature = `${info.mtimeMs}:${info.size}`;
708
+ info = await stat(changesPath(id));
673
709
  } catch {
674
710
  changeRecordsCache.delete(id);
675
711
  return [];
676
712
  }
713
+ const signature = `${info.mtimeMs}:${info.size}`;
677
714
  const cached = changeRecordsCache.get(id);
678
- if (cached?.signature === signature) return cached.records;
679
- const records = ((await readChangesFile(id))?.records || [])
680
- .filter(Boolean)
681
- .sort((left, right) => (Number(left.createdAt) || 0) - (Number(right.createdAt) || 0));
682
715
  changeRecordsCache.delete(id);
683
- changeRecordsCache.set(id, { signature, records });
684
- if (changeRecordsCache.size > CHANGE_RECORDS_CACHE_SESSIONS) {
685
- changeRecordsCache.delete(changeRecordsCache.keys().next().value);
716
+ if (cached?.signature === signature) {
717
+ changeRecordsCache.set(id, cached);
718
+ try {
719
+ return await cached.records;
720
+ } catch {
721
+ if (changeRecordsCache.get(id) === cached) changeRecordsCache.delete(id);
722
+ return [];
723
+ }
724
+ }
725
+ const entry = {
726
+ signature,
727
+ bytes: info.size,
728
+ records: parseChangesFile(id).then((file) =>
729
+ deepFreeze(
730
+ (file?.records || [])
731
+ .filter(Boolean)
732
+ .sort((left, right) => (Number(left.createdAt) || 0) - (Number(right.createdAt) || 0))
733
+ )
734
+ ),
735
+ };
736
+ changeRecordsCache.set(id, entry);
737
+ trimChangeRecordsCache();
738
+ try {
739
+ return await entry.records;
740
+ } catch {
741
+ // A failed read is not remembered: the next call reads the file again.
742
+ if (changeRecordsCache.get(id) === entry) changeRecordsCache.delete(id);
743
+ return [];
686
744
  }
687
- return records;
688
745
  }
689
746
 
690
747
  export function _setTurnChangeRecordWriteHookForTest(hook) {
@@ -161,19 +161,49 @@ function stateForRoot(root) {
161
161
  return state;
162
162
  }
163
163
 
164
+ // Platforms whose recursive watch backend reports a path as the watched
165
+ // (canonical) root plus a relative name and never descends into a link:
166
+ // ReadDirectoryChangesW on Windows watches one directory handle and its own
167
+ // subtree, and FSEvents on macOS reports resolved paths. inotify on Linux
168
+ // follows links while walking a recursive watch, so it can report an alias
169
+ // of a directory that another tracked root owns. Unlisted platforms are not
170
+ // trusted either.
171
+ const LINK_FREE_WATCH_PLATFORMS = new Set(['win32', 'darwin']);
172
+
164
173
  /** Report written paths (or `null`: anything may have changed). The next
165
- * review poll of an affected worktree captures instead of reusing. */
166
- export function noteTurnWorktreeChange(paths = null) {
174
+ * review poll of an affected worktree captures instead of reusing.
175
+ * `canonical`: the paths come from a recursive watch on canonical roots. On a
176
+ * link-free backend a path under a root by its own spelling then needs no
177
+ * filesystem call; one that is not is still canonicalised. Every other
178
+ * source, and every watcher on another platform, may name paths through
179
+ * links, so each is canonicalised. `platform` exists for tests. */
180
+ export function noteTurnWorktreeChange(paths = null, { canonical = false, platform = process.platform } = {}) {
167
181
  if (states.size === 0) return;
168
182
  const list = Array.isArray(paths) ? paths.filter((value) => clean(value)) : [];
169
- const dirs = new Map();
170
- const keys = list.map((value) => pathKey(canonicalPath(value, dirs)));
171
- for (const state of states.values()) {
172
- const root = pathKey(state.root);
173
- if (keys.length === 0 || keys.some((key) => key === root || key.startsWith(`${root}/`))) {
174
- state.changeStamp += 1;
183
+ if (list.length === 0) {
184
+ for (const state of states.values()) state.changeStamp += 1;
185
+ return;
186
+ }
187
+ const roots = [...states.values()].map((state) => ({ state, root: pathKey(state.root) }));
188
+ const stamped = new Set();
189
+ const stampMatches = (key) => {
190
+ let matched = false;
191
+ for (const { state, root } of roots) {
192
+ if (key === root || key.startsWith(`${root}/`)) {
193
+ stamped.add(state);
194
+ matched = true;
195
+ }
175
196
  }
197
+ return matched;
198
+ };
199
+ const trustSpelling = canonical && LINK_FREE_WATCH_PLATFORMS.has(platform);
200
+ const dirs = new Map();
201
+ for (const value of list) {
202
+ if (stamped.size === roots.length) break;
203
+ if (trustSpelling && stampMatches(pathKey(resolve(value)))) continue;
204
+ stampMatches(pathKey(canonicalPath(value, dirs)));
176
205
  }
206
+ for (const state of stamped) state.changeStamp += 1;
177
207
  }
178
208
 
179
209
  // A lock hold (queue wait plus work) at least this long is logged, so a slow
@@ -19,14 +19,14 @@
19
19
  * disk reads of user-cwd.txt are negligible.
20
20
  */
21
21
 
22
- import { AsyncLocalStorage } from 'node:async_hooks';
23
22
  import { readFileSync, statSync } from 'node:fs';
24
23
  import { join, resolve } from 'node:path';
25
24
  import { homedir } from 'node:os';
26
25
  import { holdsNoData, writeFileAtomicSync } from './atomic-file.mjs';
27
26
  import { resolvePluginData, mixdogRoot } from './plugin-paths.mjs';
27
+ import { runtimeAsyncLocalStorage } from './root-async-context.mjs';
28
28
 
29
- const _cwdOverride = new AsyncLocalStorage();
29
+ const _cwdOverride = runtimeAsyncLocalStorage();
30
30
 
31
31
  function _activeCwdOverride() {
32
32
  const store = _cwdOverride.getStore();
@@ -2,6 +2,7 @@
2
2
  // synchronous native work (process creation, SQLite queries) off the host
3
3
  // event loop while callers simply await the answer.
4
4
  import { parentPort, Worker } from 'node:worker_threads';
5
+ import { runInRootAsyncContext } from './root-async-context.mjs';
5
6
 
6
7
  /**
7
8
  * Returns `request(payload) → Promise<result>`. The worker starts on first use,
@@ -46,7 +47,8 @@ export function createWorkerRequestClient(url, { idleExitMs = 0, onEvent = null,
46
47
 
47
48
  function ensureWorker() {
48
49
  if (worker) return worker;
49
- const created = new Worker(url, { execArgv: [], ...workerOptions });
50
+ // Shared by every later caller: never let it retain the first caller's context.
51
+ const created = runInRootAsyncContext(() => new Worker(url, { execArgv: [], ...workerOptions }));
50
52
  const owned = pending;
51
53
  const rejectOwned = (error) => {
52
54
  const entries = [...owned.values()];
@@ -9,16 +9,16 @@
9
9
  * shared by the runtime daemon and the desktop main process.
10
10
  * Re-entrant within one async call chain.
11
11
  */
12
- import { AsyncLocalStorage } from 'node:async_hooks';
13
12
  import { join } from 'node:path';
14
13
  import { withGitRepoWriteLock } from '../../agent/orchestrator/tools/builtin/git-repo-rw-lock.mjs';
15
14
  import { withFileLock } from '../file-lock.mjs';
16
15
  import { resolvePluginData } from '../plugin-paths.mjs';
17
16
  import { repoHash, WORKTREE_STORE_DIR } from './contract.mjs';
18
17
  import { canonicalPath, pathKey } from './paths.mjs';
18
+ import { runtimeAsyncLocalStorage } from '../root-async-context.mjs';
19
19
 
20
20
  const REPO_LOCK_TIMEOUT_MS = 120_000;
21
- const heldRepoLocks = new AsyncLocalStorage();
21
+ const heldRepoLocks = runtimeAsyncLocalStorage();
22
22
 
23
23
  /** Cross-process lock file for one repository (outside the removable root). */
24
24
  function repoLockPath(repoCommonDir, { dataDir = resolvePluginData() } = {}) {
@@ -14,8 +14,13 @@ const REQUEST_TIMEOUT_MS = 30_000;
14
14
  * for it (45 s) is shorter, so a timeout is reported by the host, which then
15
15
  * writes nothing, rather than raced by this client. */
16
16
  const EXPORT_REQUEST_TIMEOUT_MS = 60_000;
17
+ /** `act` loads a page (off screen), runs up to 15 s of steps and may capture;
18
+ * the host bounds each part, so it gets the export's longer wait. */
19
+ const LONG_ACTIONS = new Set(['export', 'act']);
17
20
  const MAX_RESPONSE_BYTES = 1024 * 1024;
18
- const ACTIONS = new Set(['open', 'close', 'annotate', 'capture', 'export', 'check', 'inspect']);
21
+ const ACTIONS = new Set(['open', 'close', 'annotate', 'capture', 'export', 'check', 'inspect', 'act']);
22
+ const ACT_STEP_KINDS = new Set(['click', 'type', 'key', 'scroll', 'wait', 'evaluate']);
23
+ const MAX_ACT_STEPS = 25;
19
24
  const INLINE_KINDS = ['mermaid', 'svg', 'chart', 'html', 'markdown'];
20
25
  const MAX_INLINE_BYTES = 512 * 1024;
21
26
  const BRIDGE_UNAVAILABLE_MESSAGE = 'visualize is unavailable; the Mixdog desktop app must be running';
@@ -40,7 +45,7 @@ export function validateVisualizeArgs(args) {
40
45
  return { ok: false, error: 'visualize arguments must be an object' };
41
46
  }
42
47
  if (!ACTIONS.has(args.action))
43
- return { ok: false, error: 'action must be open, close, annotate, capture, export, check, or inspect' };
48
+ return { ok: false, error: 'action must be open, close, annotate, capture, export, check, inspect, or act' };
44
49
  const input = args.input ?? {};
45
50
  if (typeof input !== 'object' || Array.isArray(input)) return { ok: false, error: 'input must be an object' };
46
51
  if (args.action === 'open' && input.verify != null && typeof input.verify !== 'boolean') {
@@ -86,7 +91,7 @@ export function validateVisualizeArgs(args) {
86
91
  }
87
92
  }
88
93
  if (
89
- ['annotate', 'capture', 'export', 'check', 'inspect'].includes(args.action) &&
94
+ ['annotate', 'capture', 'export', 'check', 'inspect', 'act'].includes(args.action) &&
90
95
  (typeof input.tab !== 'string' || !input.tab)
91
96
  ) {
92
97
  return { ok: false, error: `${args.action} requires input.tab` };
@@ -114,6 +119,21 @@ export function validateVisualizeArgs(args) {
114
119
  if (args.action === 'capture' && !(typeof input.output === 'string' && /\.png$/i.test(input.output.trim()))) {
115
120
  return { ok: false, error: 'capture requires input.output ending in .png' };
116
121
  }
122
+ if (args.action === 'act') {
123
+ const { steps } = input;
124
+ if (!Array.isArray(steps) || steps.length < 1 || steps.length > MAX_ACT_STEPS) {
125
+ return { ok: false, error: `act requires input.steps: 1-${MAX_ACT_STEPS} steps` };
126
+ }
127
+ const bad = steps.findIndex(
128
+ (step) => !step || typeof step !== 'object' || Array.isArray(step) || !ACT_STEP_KINDS.has(step.do)
129
+ );
130
+ if (bad >= 0) {
131
+ return { ok: false, error: `act input.steps[${bad}].do must be click, type, key, scroll, wait, or evaluate` };
132
+ }
133
+ if (input.output != null && !(typeof input.output === 'string' && /\.png$/i.test(input.output.trim()))) {
134
+ return { ok: false, error: 'act input.output must end in .png' };
135
+ }
136
+ }
117
137
  if (args.action === 'export') {
118
138
  if (input.format !== 'png' && input.format !== 'pdf')
119
139
  return { ok: false, error: 'export requires input.format png or pdf' };
@@ -173,7 +193,9 @@ export async function executeVisualizeTool(args, options = {}) {
173
193
  if (!discovery) return toolError(unavailableMessage());
174
194
  let result;
175
195
  for (let attempt = 0; attempt < 2; attempt += 1) {
176
- const timeout = AbortSignal.timeout(validated.action === 'export' ? EXPORT_REQUEST_TIMEOUT_MS : REQUEST_TIMEOUT_MS);
196
+ const timeout = AbortSignal.timeout(
197
+ LONG_ACTIONS.has(validated.action) ? EXPORT_REQUEST_TIMEOUT_MS : REQUEST_TIMEOUT_MS
198
+ );
177
199
  try {
178
200
  result = await requestBridge(
179
201
  discovery,
@@ -10,24 +10,28 @@ export const TOOL_DEFS = [
10
10
  name: 'visualize',
11
11
  title: 'Mixdog Visualize',
12
12
  description:
13
- 'Show the user a finished deliverable you produced or changed (mockups, docs, decks, sheets, PDFs, images, video, local dev pages) in the desktop side panel beside the chat. A summary, plan or report of your own work is not one either: it stays in the chat. Your own check screenshots are not deliverables: look at them with read; open with verify: true only to run check/inspect/capture/export. Panel tabs auto-reload when a file changes, so re-opening after edits is unnecessary. ' +
14
- 'open: input.targets (1-3 file paths, relative to the working directory or absolute anywhere on this machine; 2-3 = side-by-side comparison; or a single http(s) URL alone, never mixed with files or other URLs), optional label, optional version (show that kept version of a file tab read-only; each open/reload that changes the files keeps a version), optional verify (true = you open only to check your own work with check/inspect/capture/export: the user is not shown the tab and it closes when the turn ends; leave it off for anything the user should see). close: optional tab (omit = all). ' +
13
+ 'Show the user a finished deliverable you produced or changed (mockups, docs, decks, sheets, PDFs, images, video, local dev pages) in the desktop side panel beside the chat. A summary, plan or report of your own work is not one either: it stays in the chat. Your own check screenshots are not deliverables: look at them with read; open with verify: true only to run check/inspect/act/capture/export. Panel tabs auto-reload when a file changes, so re-opening after edits is unnecessary. ' +
14
+ 'open: input.targets (1-3 file paths, relative to the working directory or absolute anywhere on this machine; 2-3 = side-by-side comparison; or a single http(s) URL alone, never mixed with files or other URLs), optional label, optional version (show that kept version of a file tab read-only; each open/reload that changes the files keeps a version), optional verify (true = you open only to check your own work with check/inspect/act/capture/export: the user is not shown the tab and it closes when the turn ends; leave it off for anything the user should see). close: optional tab (omit = all). ' +
15
15
  'annotate: tab + add [{selector,label?}] | remove [selector] | clear; HTML pages only, never edits the file. capture: tab + output (.png path). ' +
16
16
  'export: tab + format (png|pdf) + output (project-relative path ending .png/.pdf) + optional version (a kept version of the tab) + optional overwrite (true replaces an existing file, only under design/; otherwise an existing file is refused). Writes a record of the approved page inside the project and returns its project-relative path, size/dimensions and the page problems seen while rendering. A single HTML page (file, or inline html/chart) is rendered whole in a hidden window, so the tab need not be on screen (PDF: HTML pages only; PNG has a pixel cap, over it export pdf or shorten the page); any other tab exports as capture does (the displayed tab, PNG only). Same project containment as capture: links and paths outside the working directory are refused. ' +
17
17
  'check: tab; HTML pages only; waits briefly for the page to settle and returns only its runtime problems (uncaught errors, unhandled rejections, CSP violations, console errors/warnings, missing local assets). ' +
18
18
  'inspect: tab + optional viewport {width,height} (e.g. 375x812 to look at a mobile layout) + optional selector (scope); HTML pages with scripts/styles only (not static mermaid/svg/markdown). Returns a compact text read-out of the rendered page without a screenshot: viewport, landmarks and headings, interactive elements (role, accessible name, selector, x/y/w/h), and layout findings (horizontal overflow, clipped text, overlapping or tiny tap targets, low text contrast, images without alt, unlabeled inputs). Run it (desktop width and, for responsive designs, a mobile width) and fix the findings before reporting; `check` also says when findings exist. Secret field values are never included. ' +
19
+ 'act: tab + steps (1-25, run in order, 15 s in total) + optional pane (1-based, default the first HTML page) + optional output (.png capture of the final state); operates an HTML page (file or inline html/chart) and reads the result. Steps: {do:"click",selector} | {do:"type",selector,text} (replaces the field value, fires input/change) | {do:"key",key,selector?} (a key or chord like "Enter", "Shift+Tab", "Control+a"; to the focused element or the selector) | {do:"scroll",selector?,x?,y?} (selector alone = into view, x/y = pixels to scroll it or the page by) | {do:"wait",ms} or {do:"wait",selector,timeout?} (until it is shown; ms and timeout up to 10000) | {do:"evaluate",script} (one JS expression or IIFE run in the page, promises awaited; its JSON result is returned, cut at 4000 characters). Selectors are CSS, e.g. those inspect reports. Input is simulated in the page with synthetic DOM events (no real mouse or keyboard; Enter in a form field submits it), inside the same sandbox and network limits. Stops at the first failing step and says which and why; returns each step\'s outcome, the evaluate values and the page problems seen. On a tab shown in the panel the user sees it happen; on a verify tab or while your turn holds the panel it runs off screen in a freshly loaded page each call. ' +
19
20
  'Any result about a tab ends with a "Page problems" section when the page has problems: fix them in the file and re-check before reporting; never report a page with unresolved problems as done. ' +
20
21
  'HTML pages run their scripts, but outside network (CDNs, web fonts, APIs, any other http(s)/ws address) is blocked unless the user allows it for the tab, so mockups must be self-contained; a blocked request appears as a "blocked-network" page problem on open/check. ' +
21
22
  'Direct renderers: instead of targets, open takes input.content {kind: mermaid|svg|chart|html|markdown, source, title?} (max 512 KiB; chart = an ECharts option as JSON) and shows it with no file written. ' +
22
23
  'Prefer inline content for diagrams, charts and quick sketches; write a file for real mockups that need iteration, scripts or versioning on disk. ' +
23
24
  'mermaid, svg and markdown render as static, sanitized output (no scripts, no network). chart (ECharts option JSON, interactive: tooltips, zoom) and html (scripts run) open as in-memory pages with the same protections as HTML file pages (outside network blocked, page problems captured); html content must be self-contained. Re-open with the same title to add a version. A render error (Mermaid parse error, bad chart JSON) is returned as a page problem: fix the source and open again. ' +
24
25
  'Tweaks: an HTML page (file or inline html/chart) can declare adjustable parameters in <script type="application/json" id="mx-tweaks">[{id,label,type:color|range|select|toggle,var:"--name" or attr:"data-name",min,max,step,unit,options:[{value,label}],default}] (max 16, keep it to a few meaningful ones). The panel shows a Tweaks drawer and applies changes live to the page root (CSS variables / data attributes your CSS and script read); the chosen values come back with their next message under tweaks: to bake into the file. A malformed block is a "tweaks: <reason>" page problem. ' +
25
- 'Does not replace browser for clicking/typing. ' +
26
+ 'To check a local HTML page, open it here and operate it with act; never serve it yourself to drive it in browser (browser is for web URLs and real browser input). ' +
26
27
  TOOL_SYNC_EXECUTION_CONTRACT,
27
28
  inputSchema: {
28
29
  type: 'object',
29
30
  properties: {
30
- action: { type: 'string', enum: ['open', 'close', 'annotate', 'capture', 'export', 'check', 'inspect'] },
31
+ action: {
32
+ type: 'string',
33
+ enum: ['open', 'close', 'annotate', 'capture', 'export', 'check', 'inspect', 'act'],
34
+ },
31
35
  input: {
32
36
  type: 'object',
33
37
  properties: {
@@ -82,7 +86,44 @@ export const TOOL_DEFS = [
82
86
  output: {
83
87
  type: 'string',
84
88
  description:
85
- 'capture: project path ending .png. export: project path ending .png or .pdf (matching format).',
89
+ 'capture: project path ending .png. export: project path ending .png or .pdf (matching format). act: optional project path ending .png for a capture of the final state.',
90
+ },
91
+ steps: {
92
+ type: 'array',
93
+ minItems: 1,
94
+ maxItems: 25,
95
+ items: {
96
+ type: 'object',
97
+ properties: {
98
+ do: { type: 'string', enum: ['click', 'type', 'key', 'scroll', 'wait', 'evaluate'] },
99
+ selector: { type: 'string', maxLength: 500, description: 'CSS selector of the target element.' },
100
+ text: { type: 'string', maxLength: 10000, description: 'type: the new field value.' },
101
+ key: { type: 'string', maxLength: 40, description: 'key: a key or chord, e.g. Enter, Shift+Tab.' },
102
+ x: { type: 'integer', description: 'scroll: pixels to the right (negative = left).' },
103
+ y: { type: 'integer', description: 'scroll: pixels down (negative = up).' },
104
+ ms: { type: 'integer', minimum: 1, maximum: 10000, description: 'wait: pause length.' },
105
+ timeout: {
106
+ type: 'integer',
107
+ minimum: 1,
108
+ maximum: 10000,
109
+ description: 'wait with selector: longest wait for it to be shown (default 5000).',
110
+ },
111
+ script: {
112
+ type: 'string',
113
+ maxLength: 20000,
114
+ description: 'evaluate: one JS expression or IIFE; its JSON-serializable result is returned.',
115
+ },
116
+ },
117
+ required: ['do'],
118
+ additionalProperties: false,
119
+ },
120
+ description: 'act: the steps, run in order; the first failure stops the rest.',
121
+ },
122
+ pane: {
123
+ type: 'integer',
124
+ minimum: 1,
125
+ maximum: 6,
126
+ description: 'act: the pane (1-based position in the tab) to operate; default the first HTML page.',
86
127
  },
87
128
  format: { type: 'string', enum: ['png', 'pdf'], description: 'export: file format.' },
88
129
  overwrite: {
@@ -123,6 +123,7 @@ export function wireApis(boot) {
123
123
  if (boot.ensureConnectorAccountIds()) boot.reloadFullConfig();
124
124
  }
125
125
  boot.disposeGlobalExtensionSubscription = () => {
126
+ boot.disposeProviderReadiness();
126
127
  boot.disposeConfigSync?.();
127
128
  boot.disposeAgentProfileChanges();
128
129
  boot.resourceApi.disposeGlobalExtensionSubscription?.();
@@ -37,6 +37,7 @@ export function beginBoot(params) {
37
37
  invalidateProviderCaches,
38
38
  reinitProviders,
39
39
  ensureProvidersReady,
40
+ dispose: disposeProviderReadiness,
40
41
  modelMetaByRoute,
41
42
  providerModelCaches,
42
43
  providerUsageCaches,
@@ -57,6 +58,7 @@ export function beginBoot(params) {
57
58
  invalidateProviderCaches,
58
59
  reinitProviders,
59
60
  ensureProvidersReady,
61
+ disposeProviderReadiness,
60
62
  modelMetaByRoute,
61
63
  providerModelCaches,
62
64
  providerUsageCaches,
@@ -78,6 +78,21 @@ export function createMediaApi() {
78
78
  async listMediaAssets(options) {
79
79
  return (await store()).listMediaAssets(options || {});
80
80
  },
81
+ async listMediaBoards() {
82
+ return (await store()).listMediaBoards();
83
+ },
84
+ async createMediaBoard(name) {
85
+ return (await store()).createMediaBoard(name);
86
+ },
87
+ async renameMediaBoard(id, name) {
88
+ return (await store()).renameMediaBoard(id, name);
89
+ },
90
+ async deleteMediaBoard(id) {
91
+ return (await store()).deleteMediaBoard(id);
92
+ },
93
+ async setMediaAssetBoard(ids, boardId) {
94
+ return (await store()).setMediaAssetBoard(ids, boardId);
95
+ },
81
96
  async readMediaAsset(id, options) {
82
97
  return (await store()).readMediaAsset(id, options || {});
83
98
  },
@@ -74,8 +74,15 @@ export function createProviderReadiness({ rt, keychain, getReg, getWarmProviderM
74
74
  }
75
75
 
76
76
  // A keyring unlocked after boot: every cache built while stored keys read as
77
- // absent (provider setup, init gates) is stale.
78
- keychain.onKeychainRecovered?.(() => invalidateProviderCaches());
77
+ // absent (provider setup, init gates) is stale. The keychain module outlives
78
+ // every runtime, so the listener (which holds this runtime and its caches)
79
+ // is released by dispose().
80
+ const unsubscribeKeychainRecovered = keychain.onKeychainRecovered?.(() => invalidateProviderCaches());
81
+
82
+ /** Release the keychain subscription; the runtime's teardown calls it. Idempotent. */
83
+ function dispose() {
84
+ unsubscribeKeychainRecovered?.();
85
+ }
79
86
 
80
87
  // The one edit a caller makes to the provider config it passes is turning a
81
88
  // route's provider on (ensureProviderEnabled); those providers, judged
@@ -178,6 +185,7 @@ export function createProviderReadiness({ rt, keychain, getReg, getWarmProviderM
178
185
  invalidateProviderCaches,
179
186
  reinitProviders,
180
187
  ensureProvidersReady,
188
+ dispose,
181
189
  modelMetaByRoute,
182
190
  providerModelCaches,
183
191
  providerUsageCaches,
@@ -62,14 +62,41 @@ function bootParams({
62
62
  };
63
63
  }
64
64
 
65
+ // A boot that throws returns no runtime to close, so whatever its stages already
66
+ // subscribed to process-wide registries is released here. Each release is
67
+ // independent of the late disposeGlobalExtensionSubscription aggregate (wired by
68
+ // the last stage) and tolerates a stage that never ran.
69
+ function releaseFailedBoot(boot) {
70
+ for (const release of [
71
+ () => boot.disposeProviderReadiness(),
72
+ () => boot.disposeConfigSync?.(),
73
+ () => boot.disposeAgentProfileChanges?.(),
74
+ () => boot.resourceApi?.disposeGlobalExtensionSubscription?.(),
75
+ () => boot.setupTool?.dispose(),
76
+ () => boot.disposeInternalTools?.(),
77
+ () => boot.sessionTitles?.disposeAll(),
78
+ ]) {
79
+ try {
80
+ release();
81
+ } catch {
82
+ /* the boot error is the one to report */
83
+ }
84
+ }
85
+ }
86
+
65
87
  export async function createMixdogSessionRuntime(options = {}) {
66
88
  const boot = beginBoot(bootParams(options));
67
- await loadModules(boot);
68
- await resolveConfig(boot);
69
- wireInfrastructure(boot);
70
- wireTools(boot);
71
- wireProviders(boot);
72
- wireSessionLifecycle(boot);
73
- wireApis(boot);
74
- return buildFacade(boot);
89
+ try {
90
+ await loadModules(boot);
91
+ await resolveConfig(boot);
92
+ wireInfrastructure(boot);
93
+ wireTools(boot);
94
+ wireProviders(boot);
95
+ wireSessionLifecycle(boot);
96
+ wireApis(boot);
97
+ return buildFacade(boot);
98
+ } catch (error) {
99
+ releaseFailedBoot(boot);
100
+ throw error;
101
+ }
75
102
  }
@@ -32,7 +32,9 @@ registerSessionPurgeHook((sessionId) => {
32
32
  // reach the turn's worktree snapshot as its change signal: a session review
33
33
  // read right after them captures the worktree, an unsignaled one may reuse
34
34
  // the last capture.
35
- registerCacheInvalidationListener((paths) => noteTurnWorktreeChange(paths));
35
+ registerCacheInvalidationListener((paths, source) =>
36
+ noteTurnWorktreeChange(paths, { canonical: source?.canonical === true })
37
+ );
36
38
 
37
39
  export function createRuntimeReviewApi({ getCwd, getSessionId }) {
38
40
  return {