mixdog 0.9.147 → 0.9.148

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 (255) hide show
  1. package/package.json +23 -3
  2. package/scripts/build-voice-runtime-unix.sh +101 -0
  3. package/scripts/embedding-quality-probe.mjs +96 -0
  4. package/scripts/generate-voice-runtime-manifest.mjs +300 -0
  5. package/scripts/generate-voice-runtime-manifest.test.mjs +135 -0
  6. package/scripts/native-binary-arch.mjs +30 -13
  7. package/scripts/native-binary-arch.test.mjs +40 -4
  8. package/scripts/plan-voice-runtime-release.mjs +73 -0
  9. package/scripts/prepare-native-assets.mjs +50 -9
  10. package/scripts/prune-embedding-runtime.mjs +3 -3
  11. package/scripts/sync-voice-runtime-manifest.mjs +46 -0
  12. package/scripts/verify-release-assets.mjs +106 -6
  13. package/scripts/verify-voice-runtime-release.mjs +89 -0
  14. package/scripts/voice-runtime-config.json +52 -0
  15. package/src/app.mjs +42 -5
  16. package/src/headless-exec.mjs +58 -32
  17. package/src/headless-exec.test.mjs +74 -13
  18. package/src/rules/lead/01-general.md +2 -0
  19. package/src/rules/shared/10-tool-workflow.md +7 -4
  20. package/src/rules/shared/30-exploration.md +2 -1
  21. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +28 -9
  22. package/src/runtime/agent/orchestrator/agent-trace-format.mjs +6 -1
  23. package/src/runtime/agent/orchestrator/config.mjs +53 -18
  24. package/src/runtime/agent/orchestrator/mcp/cancellation.test.mjs +139 -0
  25. package/src/runtime/agent/orchestrator/mcp/child-tree.mjs +34 -5
  26. package/src/runtime/agent/orchestrator/mcp/client.mjs +94 -10
  27. package/src/runtime/agent/orchestrator/providers/anthropic-betas.mjs +5 -0
  28. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.mjs +98 -0
  29. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.test.mjs +90 -0
  30. package/src/runtime/agent/orchestrator/providers/anthropic-leaked-toolcall.mjs +67 -16
  31. package/src/runtime/agent/orchestrator/providers/anthropic-messages.mjs +4 -82
  32. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-credentials.mjs +0 -5
  33. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +62 -121
  34. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.mjs +48 -0
  35. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.test.mjs +215 -0
  36. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +44 -48
  37. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +54 -31
  38. package/src/runtime/agent/orchestrator/providers/antigravity-oauth.mjs +56 -2
  39. package/src/runtime/agent/orchestrator/providers/cursor-auth.mjs +34 -2
  40. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +61 -1
  41. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +6 -1
  42. package/src/runtime/agent/orchestrator/providers/gemini.mjs +61 -15
  43. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +120 -1
  44. package/src/runtime/agent/orchestrator/providers/lib/env-utils.mjs +9 -0
  45. package/src/runtime/agent/orchestrator/providers/lib/stream-outcome.mjs +0 -3
  46. package/src/runtime/agent/orchestrator/providers/oauth-credential-probes.mjs +187 -84
  47. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +36 -36
  48. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +16 -6
  49. package/src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs +50 -213
  50. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +135 -126
  51. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +17 -11
  52. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +20 -7
  53. package/src/runtime/agent/orchestrator/providers/openai-ws-delta.mjs +11 -0
  54. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +132 -42
  55. package/src/runtime/agent/orchestrator/providers/openai-ws-stream.mjs +2 -2
  56. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +28 -10
  57. package/src/runtime/agent/orchestrator/providers/registry.mjs +122 -95
  58. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +58 -3
  59. package/src/runtime/agent/orchestrator/providers/tool-stream-state.mjs +4 -22
  60. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +7 -14
  61. package/src/runtime/agent/orchestrator/session/compact-policy.test.mjs +128 -0
  62. package/src/runtime/agent/orchestrator/session/context-compaction-policy.mjs +5 -0
  63. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +27 -48
  64. package/src/runtime/agent/orchestrator/session/loop/steering.mjs +19 -14
  65. package/src/runtime/agent/orchestrator/session/loop/stored-tool-args.mjs +9 -43
  66. package/src/runtime/agent/orchestrator/session/loop/tool-exec.mjs +5 -1
  67. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +15 -2
  68. package/src/runtime/agent/orchestrator/session/manager/pending-messages-persistence.test.mjs +325 -0
  69. package/src/runtime/agent/orchestrator/session/manager/pending-messages.mjs +599 -195
  70. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +22 -0
  71. package/src/runtime/agent/orchestrator/session/manager/session-crud.mjs +9 -2
  72. package/src/runtime/agent/orchestrator/session/manager.mjs +3 -0
  73. package/src/runtime/agent/orchestrator/session/pre-send-compact.mjs +26 -16
  74. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +23 -11
  75. package/src/runtime/agent/orchestrator/session/store-summary-reader.mjs +118 -3
  76. package/src/runtime/agent/orchestrator/session/store-summary-reader.test.mjs +332 -0
  77. package/src/runtime/agent/orchestrator/session/store.mjs +38 -1
  78. package/src/runtime/agent/orchestrator/tools/builtin/advisory-lock.mjs +27 -6
  79. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +12 -20
  80. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +291 -128
  81. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +45 -8
  82. package/src/runtime/agent/orchestrator/tools/builtin/edit-encoding-eol.test.mjs +224 -0
  83. package/src/runtime/agent/orchestrator/tools/builtin/edit-sequential-occupation.test.mjs +53 -3
  84. package/src/runtime/agent/orchestrator/tools/builtin/external-tool-adapters.mjs +255 -25
  85. package/src/runtime/agent/orchestrator/tools/builtin/find-search-budget.test.mjs +87 -0
  86. package/src/runtime/agent/orchestrator/tools/builtin/git-command-policy.mjs +1 -1
  87. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.mjs +132 -9
  88. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.test.mjs +10 -0
  89. package/src/runtime/agent/orchestrator/tools/builtin/lib/grep-pattern-fanout.mjs +29 -3
  90. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-job-records.mjs +1 -1
  91. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +178 -29
  92. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +4 -1
  93. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +32 -5
  94. package/src/runtime/agent/orchestrator/tools/builtin/native-search-health.test.mjs +5 -2
  95. package/src/runtime/agent/orchestrator/tools/builtin/native-search-runner.mjs +10 -1
  96. package/src/runtime/agent/orchestrator/tools/builtin/read-batch.mjs +38 -10
  97. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +12 -0
  98. package/src/runtime/agent/orchestrator/tools/builtin/read-snapshot-runtime.mjs +31 -1
  99. package/src/runtime/agent/orchestrator/tools/builtin/read-tool.mjs +11 -1
  100. package/src/runtime/agent/orchestrator/tools/builtin/read-windows.mjs +22 -4
  101. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +6 -8
  102. package/src/runtime/agent/orchestrator/tools/builtin/shell-analysis.mjs +25 -24
  103. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +152 -133
  104. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +114 -42
  105. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +129 -15
  106. package/src/runtime/agent/orchestrator/tools/code-graph/loose-file-target.test.mjs +72 -0
  107. package/src/runtime/agent/orchestrator/tools/code-graph/project-root.mjs +7 -8
  108. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +4 -4
  109. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +201 -19
  110. package/src/runtime/agent/orchestrator/tools/code-graph/span.mjs +26 -3
  111. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +10 -1
  112. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-search-scope.test.mjs +55 -0
  113. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +115 -25
  114. package/src/runtime/agent/orchestrator/tools/code-graph/text-span-mask.test.mjs +268 -0
  115. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +3 -3
  116. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +296 -46
  117. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.test.mjs +104 -0
  118. package/src/runtime/agent/orchestrator/tools/lib/shell-descendants.mjs +136 -0
  119. package/src/runtime/agent/orchestrator/tools/patch/dispatch.mjs +127 -38
  120. package/src/runtime/agent/orchestrator/tools/patch/engine-contract-gate.test.mjs +661 -0
  121. package/src/runtime/agent/orchestrator/tools/patch/matcher.mjs +350 -9
  122. package/src/runtime/agent/orchestrator/tools/patch/native-server.mjs +418 -44
  123. package/src/runtime/agent/orchestrator/tools/patch/orchestrator.mjs +27 -3
  124. package/src/runtime/agent/orchestrator/tools/patch/patch-codec-eol.test.mjs +552 -0
  125. package/src/runtime/agent/orchestrator/tools/patch/v4a-convert.mjs +65 -15
  126. package/src/runtime/agent/orchestrator/tools/patch-manifest.json +11 -11
  127. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +284 -109
  128. package/src/runtime/agent/orchestrator/tools/shell-exec-output.mjs +51 -21
  129. package/src/runtime/agent/orchestrator/tools/shell-exec-policy.mjs +44 -27
  130. package/src/runtime/agent/orchestrator/tools/shell-policy.mjs +6 -1
  131. package/src/runtime/agent/orchestrator/tools/spawn-manifest.json +11 -11
  132. package/src/runtime/attachments/store.mjs +11 -3
  133. package/src/runtime/channels/data/voice-runtime-manifest.json +46 -70
  134. package/src/runtime/channels/lib/event-queue.mjs +51 -41
  135. package/src/runtime/channels/lib/scheduler.mjs +23 -28
  136. package/src/runtime/channels/lib/voice-runtime-fetcher.mjs +6 -17
  137. package/src/runtime/channels/lib/voice-runtime-fetcher.test.mjs +17 -0
  138. package/src/runtime/channels/lib/webhook.mjs +39 -20
  139. package/src/runtime/channels/lib/whisper-server.mjs +46 -1
  140. package/src/runtime/channels/lib/worker-main.mjs +3 -1
  141. package/src/runtime/media/adapters/gemini-video.mjs +20 -4
  142. package/src/runtime/media/jobs.mjs +13 -0
  143. package/src/runtime/media/renditions.mjs +7 -1
  144. package/src/runtime/media/store.mjs +42 -22
  145. package/src/runtime/memory/index.mjs +4 -9
  146. package/src/runtime/memory/lib/agent-ipc.mjs +1 -6
  147. package/src/runtime/memory/lib/archive-security.test.mjs +21 -1
  148. package/src/runtime/memory/lib/core-memory-store.mjs +28 -50
  149. package/src/runtime/memory/lib/embedding-model-config.mjs +37 -1
  150. package/src/runtime/memory/lib/embedding-model-config.test.mjs +33 -0
  151. package/src/runtime/memory/lib/embedding-provider.mjs +34 -12
  152. package/src/runtime/memory/lib/embedding-worker.mjs +37 -5
  153. package/src/runtime/memory/lib/ko-morph.mjs +46 -15
  154. package/src/runtime/memory/lib/memory-action-handlers.mjs +18 -1
  155. package/src/runtime/memory/lib/memory-cycle1.mjs +1 -18
  156. package/src/runtime/memory/lib/memory-cycle2-gate.mjs +1 -18
  157. package/src/runtime/memory/lib/memory-cycle2-mutations.mjs +98 -45
  158. package/src/runtime/memory/lib/memory-cycle2-shared.mjs +71 -0
  159. package/src/runtime/memory/lib/memory-cycle2-shared.test.mjs +78 -0
  160. package/src/runtime/memory/lib/memory-cycle2.mjs +37 -3
  161. package/src/runtime/memory/lib/memory-cycle3.mjs +1 -1
  162. package/src/runtime/memory/lib/memory-embedding-migration.test.mjs +50 -0
  163. package/src/runtime/memory/lib/memory-recall-store.mjs +9 -24
  164. package/src/runtime/memory/lib/memory.mjs +50 -12
  165. package/src/runtime/memory/lib/pg/process.mjs +1 -10
  166. package/src/runtime/memory/lib/pg/supervisor.mjs +1 -9
  167. package/src/runtime/memory/lib/query-handlers.mjs +2 -4
  168. package/src/runtime/memory/lib/session-ingest-runtime.mjs +2 -2
  169. package/src/runtime/shared/background-tasks.mjs +15 -0
  170. package/src/runtime/shared/background-tasks.test.mjs +78 -0
  171. package/src/runtime/shared/child-guardian.mjs +2 -10
  172. package/src/runtime/shared/pid-liveness.mjs +27 -0
  173. package/src/runtime/shared/runtime-root.mjs +1 -11
  174. package/src/runtime/shared/service-discovery.mjs +1 -17
  175. package/src/runtime/shared/singleton-owner.mjs +1 -11
  176. package/src/runtime/shared/staged-update.mjs +2 -12
  177. package/src/runtime/shared/tool-status.mjs +5 -1
  178. package/src/runtime/shared/tool-surface.mjs +15 -7
  179. package/src/runtime/shared/turn-snapshot-store.mjs +168 -0
  180. package/src/runtime/shared/turn-snapshot.mjs +137 -13
  181. package/src/runtime/shared/turn-worktree-snapshot.mjs +110 -18
  182. package/src/runtime/shared/webhook-session-run.mjs +16 -2
  183. package/src/runtime/web-search/lib/http-fetch.mjs +34 -4
  184. package/src/runtime/web-search/lib/state.mjs +15 -15
  185. package/src/runtime/web-search/lib/web-tools.mjs +46 -5
  186. package/src/session-runtime/context-status.mjs +4 -12
  187. package/src/session-runtime/runtime-core.mjs +20 -1
  188. package/src/standalone/agent-dispatch-broker.mjs +33 -2
  189. package/src/standalone/agent-tool/job-task-reconcile.mjs +78 -0
  190. package/src/standalone/agent-tool/notify.mjs +3 -1
  191. package/src/standalone/agent-tool/spawn-flow.mjs +48 -66
  192. package/src/standalone/agent-tool/tag-registry.mjs +116 -33
  193. package/src/standalone/agent-tool/tool-def.mjs +2 -2
  194. package/src/standalone/agent-tool/worker-index.mjs +8 -11
  195. package/src/standalone/agent-tool/worker-rows.mjs +4 -1
  196. package/src/standalone/agent-tool.mjs +20 -55
  197. package/src/standalone/agent-watchdog-registry.mjs +28 -4
  198. package/src/standalone/channel-client.mjs +47 -15
  199. package/src/standalone/channel-transport.mjs +44 -25
  200. package/src/standalone/daemon.mjs +31 -2
  201. package/src/standalone/hook-bus/config.mjs +25 -9
  202. package/src/standalone/hook-bus/handlers.mjs +16 -52
  203. package/src/standalone/hook-bus.mjs +29 -23
  204. package/src/standalone/memory-runtime-proxy.mjs +1 -16
  205. package/src/standalone/session-client.mjs +86 -23
  206. package/src/standalone/session-protocol.mjs +0 -2
  207. package/src/standalone/session-runtime-host-health.test.mjs +5 -4
  208. package/src/standalone/session-runtime-host.mjs +101 -6
  209. package/src/standalone/session-runtime-record.mjs +1 -5
  210. package/src/standalone/session-runtime-worker.mjs +52 -57
  211. package/src/standalone/session-service.mjs +4 -1
  212. package/src/standalone/session-transport.mjs +56 -25
  213. package/src/tui/App.jsx +40 -49
  214. package/src/tui/app/app-view.jsx +14 -21
  215. package/src/tui/app/core-memory-picker.mjs +29 -16
  216. package/src/tui/app/create-app-pickers.mjs +15 -36
  217. package/src/tui/app/extension-pickers.mjs +60 -49
  218. package/src/tui/app/maintenance-pickers.mjs +100 -57
  219. package/src/tui/app/message-selector.mjs +6 -5
  220. package/src/tui/app/model-picker.mjs +30 -13
  221. package/src/tui/app/onboarding-steps.mjs +21 -12
  222. package/src/tui/app/panel-epoch.mjs +56 -0
  223. package/src/tui/app/panel-epoch.test.mjs +1009 -0
  224. package/src/tui/app/panel-surface.mjs +98 -0
  225. package/src/tui/app/project-picker.mjs +30 -29
  226. package/src/tui/app/prompt-submit.mjs +192 -97
  227. package/src/tui/app/prompt-submit.test.mjs +206 -0
  228. package/src/tui/app/provider-setup-picker.mjs +74 -43
  229. package/src/tui/app/resume-picker.mjs +11 -8
  230. package/src/tui/app/route-pickers.mjs +45 -28
  231. package/src/tui/app/settings-picker.mjs +69 -18
  232. package/src/tui/app/shell-layout.mjs +1 -3
  233. package/src/tui/app/slash-commands.mjs +0 -2
  234. package/src/tui/app/slash-dispatch.mjs +4 -2
  235. package/src/tui/app/text-entry-policy.mjs +25 -0
  236. package/src/tui/app/theme-effort-pickers.mjs +11 -16
  237. package/src/tui/app/usage-context-panels.mjs +21 -25
  238. package/src/tui/app/use-global-key-input.mjs +3 -2
  239. package/src/tui/app/use-prompt-draft-flow.mjs +6 -18
  240. package/src/tui/app/use-prompt-handlers.mjs +3 -2
  241. package/src/tui/app/use-welcome-prompt-hint.mjs +17 -3
  242. package/src/tui/components/Picker.jsx +1 -1
  243. package/src/tui/components/TextEntryPanel.jsx +7 -2
  244. package/src/tui/dist/index.mjs +652 -561
  245. package/src/tui/lib/voice-setup.mjs +1 -2
  246. package/src/tui/session/agent-job-feed.mjs +73 -11
  247. package/src/tui/session/session-api-ext.mjs +5 -6
  248. package/src/tui/session/session-api.mjs +1 -0
  249. package/src/tui/session/tool-approval.mjs +15 -5
  250. package/src/tui/session/tui-steering-persist.mjs +33 -19
  251. package/src/tui/session/tui-steering-persist.test.mjs +104 -0
  252. package/src/tui/session-local.mjs +0 -22
  253. package/scripts/.tmp-coverage-report.mjs +0 -96
  254. package/src/runtime/agent/orchestrator/tools/builtin/shell-monitor.mjs +0 -57
  255. package/src/runtime/agent/orchestrator/tools/builtin/shell-monitor.test.mjs +0 -57
@@ -115,8 +115,7 @@ function makeThrottledProgressNotice({ pushNotice, setProgressHint } = {}, inter
115
115
  */
116
116
  async function ensureVoiceRuntimeReady({ dataDir = resolvePluginData(), pushNotice, setProgressHint } = {}) {
117
117
  const fetcher = await loadVoiceRuntimeFetcher();
118
- // System-language default: Korean devices install the Korean fine-tune,
119
- // everything else the standard multilingual Q8. voice.model overrides.
118
+ // Every device installs the same standard multilingual Q8 model.
120
119
  const modelId = fetcher.selectVoiceModelId(readSection('voice'));
121
120
  let runtime = fetcher.resolveVoiceRuntime(dataDir, { modelId });
122
121
  if (runtime.installed) return runtime;
@@ -80,6 +80,45 @@ export function createAgentJobFeed({
80
80
  const terminalExecutionNotificationKeys = new Set();
81
81
  const terminalExecutionResponseKeys = new Set();
82
82
  const executionNotificationKeys = new Map();
83
+ // Notification enqueue ordering. Image notifications must read their files
84
+ // before they can be enqueued; running each load as an independent detached
85
+ // task let a later (or image-free) notification reach the model queue first.
86
+ // Everything that has to wait goes through this single FIFO chain, and
87
+ // notifications that need no I/O only join it while the chain is busy.
88
+ let notificationEnqueueChain = Promise.resolve();
89
+ let pendingNotificationEnqueues = 0;
90
+ // Hard ceiling for ONE queued task. A never-settling image read (dead FS
91
+ // handle, network-backed path) would otherwise hold the FIFO forever and
92
+ // stall every later notification.
93
+ const NOTIFICATION_TASK_TIMEOUT_MS = 30_000;
94
+ const chainNotificationEnqueue = (task, onFailure = null) => {
95
+ // Abandon marker: a task that is timed out here keeps running (a pending
96
+ // read cannot be cancelled), so it re-checks this flag before enqueueing
97
+ // and can never land out of order behind the notifications that passed it.
98
+ const slot = { abandoned: false };
99
+ pendingNotificationEnqueues += 1;
100
+ notificationEnqueueChain = notificationEnqueueChain
101
+ .then(() => new Promise((resolve, reject) => {
102
+ const timer = setTimeout(() => {
103
+ slot.abandoned = true;
104
+ reject(new Error(`notification task timed out after ${NOTIFICATION_TASK_TIMEOUT_MS}ms`));
105
+ }, NOTIFICATION_TASK_TIMEOUT_MS);
106
+ timer.unref?.();
107
+ Promise.resolve().then(() => task(slot)).then(
108
+ (value) => { clearTimeout(timer); resolve(value); },
109
+ (error) => { clearTimeout(timer); reject(error); },
110
+ );
111
+ }))
112
+ .catch((error) => {
113
+ slot.abandoned = true;
114
+ // A thrown/timed-out task must not silently DROP its notification:
115
+ // the fallback delivers what it can and the user is told either way.
116
+ try { onFailure?.(error); } catch { /* fallback delivery is best-effort */ }
117
+ try { pushNotice?.(`notification delivery failed: ${error?.message || error}`, 'warn'); } catch {}
118
+ })
119
+ .then(() => { pendingNotificationEnqueues -= 1; });
120
+ void notificationEnqueueChain;
121
+ };
83
122
  const AGENT_STATUS_COALESCE_MS = 16;
84
123
  let agentStatusRefreshTimer = null;
85
124
  let agentStatusRefreshForce = false;
@@ -98,12 +137,16 @@ export function createAgentJobFeed({
98
137
  if (terminal) terminalExecutionNotificationKeys.add(key);
99
138
  else terminalExecutionNotificationKeys.delete(key);
100
139
  while (displayedExecutionNotificationKeys.size >= executionDedupLimit) {
140
+ // Terminal keys are evicted FIRST (a finished execution can no longer
141
+ // emit), but the bound is absolute: with only nonterminal keys left the
142
+ // oldest one goes, otherwise the map grew for the whole session.
101
143
  const oldestTerminal = [...displayedExecutionNotificationKeys]
102
144
  .find((candidate) => terminalExecutionNotificationKeys.has(candidate));
103
- if (oldestTerminal == null) break;
104
- displayedExecutionNotificationKeys.delete(oldestTerminal);
105
- terminalExecutionNotificationKeys.delete(oldestTerminal);
106
- executionNotificationKeys.delete(oldestTerminal);
145
+ const evicted = oldestTerminal ?? displayedExecutionNotificationKeys.values().next().value;
146
+ if (evicted == null) break;
147
+ displayedExecutionNotificationKeys.delete(evicted);
148
+ terminalExecutionNotificationKeys.delete(evicted);
149
+ executionNotificationKeys.delete(evicted);
107
150
  }
108
151
  displayedExecutionNotificationKeys.add(key);
109
152
  };
@@ -126,11 +169,14 @@ export function createAgentJobFeed({
126
169
  if (terminal) terminalExecutionResponseKeys.add(key);
127
170
  else terminalExecutionResponseKeys.delete(key);
128
171
  while (displayedExecutionResponseStates.size >= executionDedupLimit) {
172
+ // Same absolute bound as the notification keys above: prefer terminal
173
+ // entries, fall back to the oldest entry so the map cannot grow forever.
129
174
  const oldestTerminal = [...displayedExecutionResponseStates.keys()]
130
175
  .find((candidate) => terminalExecutionResponseKeys.has(candidate));
131
- if (oldestTerminal == null) break;
132
- displayedExecutionResponseStates.delete(oldestTerminal);
133
- terminalExecutionResponseKeys.delete(oldestTerminal);
176
+ const evicted = oldestTerminal ?? displayedExecutionResponseStates.keys().next().value;
177
+ if (evicted == null) break;
178
+ displayedExecutionResponseStates.delete(evicted);
179
+ terminalExecutionResponseKeys.delete(evicted);
134
180
  }
135
181
  displayedExecutionResponseStates.set(key, value);
136
182
  };
@@ -400,9 +446,10 @@ export function createAgentJobFeed({
400
446
  if (imagePaths.length > 0) {
401
447
  // Read each downloaded image into a real image content block so the
402
448
  // channel turn is vision-visible. Async, but the notification is
403
- // already "handled" (return true) — the enqueue lands on resolve.
449
+ // already "handled" (return true) — the enqueue lands on resolve, in
450
+ // arrival order via the shared chain.
404
451
  // Any unreadable path is skipped; if none load, fall back to text.
405
- void (async () => {
452
+ chainNotificationEnqueue(async (slot) => {
406
453
  if (getDisposed()) return;
407
454
  const parts = [];
408
455
  if (modelContent) parts.push({ type: 'text', text: modelContent });
@@ -417,11 +464,26 @@ export function createAgentJobFeed({
417
464
  if (att.metadataText) parts.push({ type: 'text', text: att.metadataText });
418
465
  parts.push({ type: 'image', data: att.content, mimeType: att.mediaType || 'image/png' });
419
466
  }
420
- if (getDisposed()) return;
467
+ if (getDisposed() || slot.abandoned) return;
421
468
  const hasImage = parts.some((part) => part.type === 'image');
422
469
  if (!hasImage && !modelContent) return;
423
470
  enqueue(hasImage ? parts : modelContent, enqueueOpts);
424
- })();
471
+ }, () => {
472
+ // Image load failed or overran its budget: still deliver the text
473
+ // body so the notification is never silently lost.
474
+ if (getDisposed() || !modelContent) return;
475
+ enqueue(modelContent, enqueueOpts);
476
+ });
477
+ return true;
478
+ }
479
+ if (pendingNotificationEnqueues > 0) {
480
+ // An earlier image notification is still loading: queue behind it so
481
+ // this text body cannot overtake it in the model queue.
482
+ chainNotificationEnqueue((slot) => {
483
+ if (!getDisposed() && !slot.abandoned) enqueue(modelContent, enqueueOpts);
484
+ }, () => {
485
+ if (!getDisposed()) enqueue(modelContent, enqueueOpts);
486
+ });
425
487
  return true;
426
488
  }
427
489
  enqueue(modelContent, enqueueOpts);
@@ -541,7 +541,7 @@ export function createSessionApiB(bag) {
541
541
  // Desktop push-to-talk dictation: accept a recorded audio payload
542
542
  // (base64), stage it as a temp file, and run it through the SAME managed
543
543
  // whisper.cpp pipeline the channels use (ffmpeg convert -> whisper server,
544
- // model selected per voice.model/system language). Returns the transcript
544
+ // standard multilingual Q8 model). Returns the transcript
545
545
  // text or throws a user-actionable error (e.g. runtime not installed).
546
546
  transcribeAudio: async ({ data, mimeType = 'audio/webm' } = {}) => {
547
547
  const base64 = String(data || '');
@@ -701,11 +701,10 @@ export function createSessionApiB(bag) {
701
701
  return true;
702
702
  },
703
703
  saveOpenCodeGoUsageAuth: (opts) => {
704
- const result = runtime.saveOpenCodeGoUsageAuth(opts);
705
- pushNotice(result.workspaceId
706
- ? `OpenCode Go usage auth saved: ${result.workspaceId}`
707
- : 'OpenCode Go usage auth saved',
708
- 'info');
704
+ // User-facing notices never expose the raw workspace-derived `wrk_…`
705
+ // identifier (Project is the product vocabulary; "workspace" is not).
706
+ runtime.saveOpenCodeGoUsageAuth(opts);
707
+ pushNotice('OpenCode Go usage auth saved', 'info');
709
708
  return true;
710
709
  },
711
710
  loginOpenCodeGoUsage: async () => {
@@ -28,6 +28,7 @@ export function createSessionApi(bag) {
28
28
  toolModules: await read(api.getToolModuleSettings),
29
29
  channels: await read(api.getChannelSettings, { includeStatus: false }),
30
30
  systemShell: await read(api.getSystemShell),
31
+ webSearchRoute: await read(api.getWebSearchRoute),
31
32
  outputStyle: (await read(api.getOutputStyle)) || (await read(api.listOutputStyles)),
32
33
  channelWorker: await read(api.getChannelWorkerStatus),
33
34
  profile: await read(api.getProfile),
@@ -28,6 +28,17 @@ export function createToolApproval({ getState, set, nextId, getDisposed, timeout
28
28
  expiresAt: now + requestTimeoutMs,
29
29
  };
30
30
  }
31
+ // Every request expires from ITS OWN requestedAt, queued or active. Arming
32
+ // the timer only on presentation let a queued request sit past expiresAt
33
+ // (retaining its promise and surfacing an obsolete approval later).
34
+ function armToolApprovalTimeout(entry) {
35
+ if (!entry || entry.timer) return;
36
+ const remainingMs = Math.max(0, Number(entry.request?.expiresAt || 0) - Date.now());
37
+ entry.timer = setTimeout(() => {
38
+ finishToolApproval(entry.id, false, 'approval timed out');
39
+ }, remainingMs);
40
+ entry.timer.unref?.();
41
+ }
31
42
  function presentNextToolApproval() {
32
43
  if (activeToolApproval || getDisposed()) return;
33
44
  const entry = toolApprovalQueue.shift();
@@ -36,10 +47,7 @@ export function createToolApproval({ getState, set, nextId, getDisposed, timeout
36
47
  return;
37
48
  }
38
49
  activeToolApproval = entry;
39
- entry.timer = setTimeout(() => {
40
- finishToolApproval(entry.id, false, 'approval timed out');
41
- }, entry.request.timeoutMs);
42
- entry.timer.unref?.();
50
+ armToolApprovalTimeout(entry);
43
51
  set({ toolApproval: entry.request });
44
52
  }
45
53
  function finishToolApproval(id, approved, reason = '') {
@@ -80,7 +88,9 @@ export function createToolApproval({ getState, set, nextId, getDisposed, timeout
80
88
  if (getDisposed()) return Promise.resolve({ approved: false, reason: 'runtime disposed' });
81
89
  return new Promise((resolve) => {
82
90
  const id = nextId();
83
- toolApprovalQueue.push({ id, request: normalizeToolApprovalRequest(input, id), resolve, timer: null });
91
+ const entry = { id, request: normalizeToolApprovalRequest(input, id), resolve, timer: null };
92
+ toolApprovalQueue.push(entry);
93
+ armToolApprovalTimeout(entry);
84
94
  presentNextToolApproval();
85
95
  });
86
96
  }
@@ -76,21 +76,32 @@ function normalizePendingStore(raw) {
76
76
  : {};
77
77
  const out = { version: 1, updatedAt: storeUpdatedAt, sessions: {}, sessionTouchedAt: {} };
78
78
  for (const [sid, value] of Object.entries(sessions)) {
79
- if (!/^[A-Za-z0-9_-]+$/.test(sid) || !Array.isArray(value)) continue;
80
- const q = sid.startsWith('tui_')
81
- ? value.map(normalizeTuiSteeringQueueEntry).filter(Boolean)
82
- : value
83
- .map((entry) => {
84
- if (typeof entry === 'string') return entry;
85
- if (entry && typeof entry === 'object' && typeof entry.message === 'string') return entry.message;
86
- return '';
87
- })
88
- .filter(Boolean);
89
- if (q.length > 0) {
90
- out.sessions[sid] = q;
91
- const touched = Number(touchedRaw[sid]);
92
- out.sessionTouchedAt[sid] = Number.isFinite(touched) && touched > 0 ? touched : storeUpdatedAt;
79
+ if (!Array.isArray(value) || value.length === 0) continue;
80
+ if (!sid.startsWith('tui_')) {
81
+ // FOREIGN bucket. This file is SHARED with the runtime/manager pending
82
+ // -message spool, and every TUI write passes the whole store through
83
+ // here. Flattening those rows to plain strings destroyed id,
84
+ // enqueuedAt, options, structured content, the notification markers —
85
+ // and the handoffAt/handoffPid parking stamp that is the only reason an
86
+ // accepted-but-undelivered user message survives an owner crash. Rows
87
+ // this process does not own are copied through UNCHANGED (array copy
88
+ // only, so nothing here can alias-mutate them either).
89
+ out.sessions[sid] = value.slice();
90
+ const foreignTouched = Number(touchedRaw[sid]);
91
+ // Carry an existing stamp only: inventing one would reset the runtime's
92
+ // own orphan aging for a session this process does not own.
93
+ if (Number.isFinite(foreignTouched) && foreignTouched > 0) {
94
+ out.sessionTouchedAt[sid] = foreignTouched;
95
+ }
96
+ continue;
93
97
  }
98
+ // TUI-owned bucket: the only rows this module may reshape.
99
+ if (!/^[A-Za-z0-9_-]+$/.test(sid)) continue;
100
+ const q = value.map(normalizeTuiSteeringQueueEntry).filter(Boolean);
101
+ if (q.length === 0) continue;
102
+ out.sessions[sid] = q;
103
+ const touched = Number(touchedRaw[sid]);
104
+ out.sessionTouchedAt[sid] = Number.isFinite(touched) && touched > 0 ? touched : storeUpdatedAt;
94
105
  }
95
106
  return out;
96
107
  }
@@ -236,13 +247,16 @@ export function drainTuiSteeringPersist(leadSessionId) {
236
247
  return !stale;
237
248
  });
238
249
  drained = fresh.map(drainedRowToRestore).filter(Boolean);
239
- // Orphan cleanup: buckets of OTHER sessions whose every row already
240
- // aged past the restore TTL can never be restored (restore is keyed
241
- // by the live session id), so they only grow the file forever
250
+ // Orphan cleanup: TUI-owned buckets of OTHER lead sessions whose every
251
+ // row already aged past the restore TTL can never be restored (restore
252
+ // is keyed by the live session id), so they only grow the file forever
242
253
  // (observed live: queued rows from sessions closed days ago). Prune
243
- // them under the same lock/write.
254
+ // them under the same lock/write. Foreign (runtime/manager spool)
255
+ // buckets are NEVER reaped here: their rows are owned by another
256
+ // process, age on a different TTL, and may be parked handoff rows that
257
+ // are the last copy of accepted user input.
244
258
  for (const otherKey of Object.keys(next.sessions)) {
245
- if (otherKey === key) continue;
259
+ if (otherKey === key || !otherKey.startsWith('tui_')) continue;
246
260
  const rows = Array.isArray(next.sessions[otherKey]) ? next.sessions[otherKey] : [];
247
261
  const otherTouched = Number(next.sessionTouchedAt?.[otherKey]) || 0;
248
262
  const allStale = rows.every((row) => {
@@ -0,0 +1,104 @@
1
+ // session-pending-messages.json is SHARED between the TUI steering mirror and
2
+ // the runtime/manager pending-message spool. Every TUI write passes the whole
3
+ // store through normalizePendingStore, so these tests pin the invariant that a
4
+ // TUI write is lossless for foreign rows — including the handoffAt/handoffPid
5
+ // parking stamp that lets accepted user input survive an owner crash — and
6
+ // that orphan cleanup only reaps TUI-owned (`tui_`) buckets.
7
+ import assert from 'node:assert/strict';
8
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import test from 'node:test';
12
+
13
+ const dataDir = mkdtempSync(join(tmpdir(), 'mixdog-tui-steering-persist-'));
14
+ mkdirSync(dataDir, { recursive: true });
15
+ process.env.MIXDOG_DATA_DIR = dataDir;
16
+
17
+ const {
18
+ appendTuiSteeringPersist,
19
+ drainTuiSteeringPersist,
20
+ flushTuiSteeringPersist,
21
+ } = await import('./tui-steering-persist.mjs');
22
+
23
+ const spoolPath = join(dataDir, 'session-pending-messages.json');
24
+ const readSpool = () => JSON.parse(readFileSync(spoolPath, 'utf8'));
25
+
26
+ // Older than the TUI restore TTL (30m) and than the runtime orphan window, so
27
+ // the pre-fix orphan sweep would have reaped this whole bucket.
28
+ const OLD_AT = Date.now() - (10 * 24 * 60 * 60 * 1000);
29
+ // Runtime-shaped rows: a parked structured row (handoffAt/handoffPid +
30
+ // content array + options) and a completion-notification row.
31
+ const foreignRows = [
32
+ {
33
+ id: 'pm_structured_1',
34
+ content: [
35
+ { type: 'text', text: 'look at this shot' },
36
+ { type: 'image', data: 'ZmFrZS1pbWFnZQ==', mimeType: 'image/png' },
37
+ ],
38
+ text: 'look at this shot',
39
+ enqueuedAt: OLD_AT,
40
+ handoffAt: OLD_AT,
41
+ handoffPid: 4242,
42
+ options: { mode: 'user', priority: 'next', displayText: 'look at this shot' },
43
+ },
44
+ {
45
+ id: 'pm_notification_2',
46
+ message: 'agent task finished',
47
+ enqueuedAt: OLD_AT,
48
+ notificationKind: 'completion_notification',
49
+ executionId: 'exec_7',
50
+ },
51
+ ];
52
+
53
+ writeFileSync(spoolPath, `${JSON.stringify({
54
+ version: 1,
55
+ updatedAt: OLD_AT,
56
+ sessions: {
57
+ sess_runtime_owner: foreignRows,
58
+ tui_staleother: [{ id: 'ts_old', text: 'old steering', at: OLD_AT }],
59
+ },
60
+ sessionTouchedAt: { sess_runtime_owner: OLD_AT, tui_staleother: OLD_AT },
61
+ }, null, 2)}\n`, { mode: 0o600 });
62
+
63
+ test.after(() => {
64
+ try { rmSync(dataDir, { recursive: true, force: true }); } catch { /* temp dir */ }
65
+ });
66
+
67
+ test('a TUI steering append round-trips foreign runtime spool rows losslessly', async () => {
68
+ await appendTuiSteeringPersist('leadsessionone', { text: 'steer me' });
69
+ await flushTuiSteeringPersist();
70
+
71
+ const store = readSpool();
72
+ // Every field of every foreign row survives the TUI write untouched.
73
+ assert.deepEqual(store.sessions.sess_runtime_owner, foreignRows);
74
+ const parked = store.sessions.sess_runtime_owner[0];
75
+ assert.equal(parked.handoffAt, OLD_AT);
76
+ assert.equal(parked.handoffPid, 4242);
77
+ assert.equal(parked.id, 'pm_structured_1');
78
+ assert.equal(parked.enqueuedAt, OLD_AT);
79
+ assert.deepEqual(parked.options, { mode: 'user', priority: 'next', displayText: 'look at this shot' });
80
+ assert.equal(Array.isArray(parked.content), true);
81
+ assert.equal(parked.content[1].mimeType, 'image/png');
82
+ assert.equal(store.sessions.sess_runtime_owner[1].notificationKind, 'completion_notification');
83
+ assert.equal(store.sessions.sess_runtime_owner[1].executionId, 'exec_7');
84
+ // A foreign session's touch stamp is carried, never refreshed by our write.
85
+ assert.equal(store.sessionTouchedAt.sess_runtime_owner, OLD_AT);
86
+
87
+ const steering = store.sessions.tui_leadsessionone;
88
+ assert.equal(Array.isArray(steering), true);
89
+ assert.equal(steering.length, 1);
90
+ assert.equal(steering[0].text, 'steer me');
91
+ });
92
+
93
+ test('drain reaps only stale tui_ buckets and leaves foreign spool rows in place', async () => {
94
+ const drained = await drainTuiSteeringPersist('leadsessionone');
95
+ assert.deepEqual(drained.map((row) => row.text), ['steer me']);
96
+
97
+ const store = readSpool();
98
+ assert.deepEqual(store.sessions.sess_runtime_owner, foreignRows);
99
+ assert.equal(store.sessionTouchedAt.sess_runtime_owner, OLD_AT);
100
+ // Own bucket drained, other TUI lead session's stale bucket pruned.
101
+ assert.equal(store.sessions.tui_leadsessionone, undefined);
102
+ assert.equal(store.sessions.tui_staleother, undefined);
103
+ assert.equal(store.sessionTouchedAt.tui_staleother, undefined);
104
+ });
@@ -149,28 +149,6 @@ export function preloadAgentLoopRuntime() {
149
149
  return agentLoopPrewarmPromise;
150
150
  }
151
151
 
152
- // Provider init (SDK graph + stored credentials) used to start inside the
153
- // FIRST session create, so a cold runtime worker paid keychain + provider init serially
154
- // right in front of provider.send (measured: a 13.5s first turn whose title
155
- // sibling call timed out at 10s). Hosts warm the same registry the create and
156
- // title paths use; initProviders dedupes repeat calls, so the authoritative
157
- // create path simply finds it ready.
158
- let providerRuntimePrewarmPromise = null;
159
- export function preloadProviderRuntime() {
160
- providerRuntimePrewarmPromise ??= (async () => {
161
- const [{ loadConfig }, { initProviders }] = await Promise.all([
162
- import('../runtime/agent/orchestrator/config.mjs'),
163
- import('../runtime/agent/orchestrator/providers/registry.mjs'),
164
- ]);
165
- await initProviders(loadConfig().providers || {});
166
- })();
167
- void providerRuntimePrewarmPromise.catch(() => {
168
- // Opportunistic: the create path retries provider init on its own.
169
- providerRuntimePrewarmPromise = null;
170
- });
171
- return providerRuntimePrewarmPromise;
172
- }
173
-
174
152
  // Memory-runtime attach (PG proxy + embed warmup) measured ~6.5s cold and is
175
153
  // the largest first-turn blocker: loadCoreMemoryContext races it with a 2s
176
154
  // cap, but a cold attach stalls the event loop hard enough that even that
@@ -1,96 +0,0 @@
1
- // TEMPORARY (delete after use): replay every current rescue/classification
2
- // rule over the last 5 days of logged tool failures and report what would no
3
- // longer surface as a failure.
4
- import { readFileSync, existsSync } from 'node:fs';
5
- import { homedir } from 'node:os';
6
- import { join, resolve } from 'node:path';
7
- import { isLegitimateShellExit } from '../src/runtime/agent/orchestrator/session/result-classification.mjs';
8
- import { _isBenignSearchExitOne } from '../src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs';
9
- import { hasPowerShellOnlySyntax, planInlineScriptHoist } from '../src/runtime/agent/orchestrator/tools/builtin/shell-analysis.mjs';
10
- import { normalizeCoreOp, normalizeCoreInput } from '../src/runtime/memory/lib/core-memory-store.mjs';
11
-
12
- const dir = resolve(homedir(), '.mixdog', 'data', 'history');
13
- const rows = [];
14
- for (const file of ['tool-failures.jsonl', 'tool-failures.jsonl.1']) {
15
- const p = join(dir, file);
16
- if (!existsSync(p)) continue;
17
- for (const line of readFileSync(p, 'utf8').split(/\r?\n/)) {
18
- if (!line) continue;
19
- try { rows.push(JSON.parse(line)); } catch { /* skip */ }
20
- }
21
- }
22
- const recent = rows.filter((r) => Number(r.ts) >= Date.now() - 5 * 86400000);
23
-
24
- const TEST_FIXTURES = new Set(['unknown_test_tool', 'definitely_missing_tool']);
25
- const buckets = {
26
- total: recent.length,
27
- testNoise: 0,
28
- retiredGuard: 0,
29
- legitimateExit: 0,
30
- benignSearch: 0,
31
- bashRescue: 0,
32
- inlineHoist: 0,
33
- codeGraphDot: 0,
34
- memoryArgs: 0,
35
- webFetchArgs: 0,
36
- grepArgs: 0,
37
- realFailure: 0,
38
- };
39
-
40
- for (const row of recent) {
41
- const tool = String(row.tool_name || '');
42
- const head = String(row.error_first_line || '');
43
- const preview = String(row.error_preview || head);
44
- const cmd = String(row.tool_args?.command || '');
45
- if (TEST_FIXTURES.has(tool) || /^Error: patch failed$/.test(head)
46
- || /must be of type string\. Received undefined/.test(head)) { buckets.testNoise += 1; continue; }
47
- if (/resource pressure/i.test(preview)) { buckets.retiredGuard += 1; continue; }
48
- if (tool === 'shell') {
49
- if (/PowerShell preflight blocked/.test(head)) {
50
- if (cmd && !hasPowerShellOnlySyntax(cmd)) { buckets.bashRescue += 1; continue; }
51
- buckets.realFailure += 1; continue;
52
- }
53
- if (/\[exit code: 1\]/.test(head)) {
54
- if (cmd && _isBenignSearchExitOne(cmd, 1, null, '')) { buckets.benignSearch += 1; continue; }
55
- const body = preview.replace(/^Error:[^\n]*\n?/, '');
56
- const stderr = /\[stderr/.test(body) ? 'x' : '';
57
- if (isLegitimateShellExit({ exitCode: 1, signal: null, stdout: body, stderr })) { buckets.legitimateExit += 1; continue; }
58
- if (cmd && planInlineScriptHoist(cmd) && /SyntaxError|ParserError|Unexpected token|missing the terminator/i.test(preview)) {
59
- buckets.inlineHoist += 1; continue;
60
- }
61
- }
62
- buckets.realFailure += 1; continue;
63
- }
64
- if (tool === 'code_graph') {
65
- const a = row.tool_args || {};
66
- const files = Array.isArray(a.files) ? a.files : (typeof a.files === 'string' ? [a.files] : []);
67
- if (files.length && files.every((f) => String(f).trim() === '.')) { buckets.codeGraphDot += 1; continue; }
68
- buckets.realFailure += 1; continue;
69
- }
70
- if (tool === 'memory') {
71
- const a = row.tool_args || {};
72
- const opFixed = ['add', 'edit', 'delete', 'list', 'candidates', 'promote', 'dismiss'].includes(normalizeCoreOp(a.op));
73
- const argsFixed = normalizeCoreInput(a, { requireElement: true, requireSummary: true }).errors.length === 0;
74
- if (opFixed && argsFixed) { buckets.memoryArgs += 1; continue; }
75
- buckets.realFailure += 1; continue;
76
- }
77
- if (tool === 'web_fetch') {
78
- const url = row.tool_args?.url;
79
- if (typeof url === 'string' && /^\s*\[/.test(url)) { buckets.webFetchArgs += 1; continue; }
80
- buckets.realFailure += 1; continue;
81
- }
82
- if (tool === 'grep' || tool === 'glob' || tool === 'list' || tool === 'find') {
83
- if (/must be string or string\[\] \(got (?:null|undefined|array)\)/.test(head)) { buckets.grepArgs += 1; continue; }
84
- buckets.realFailure += 1; continue;
85
- }
86
- buckets.realFailure += 1;
87
- }
88
-
89
- const rescued = buckets.legitimateExit + buckets.benignSearch + buckets.bashRescue + buckets.inlineHoist
90
- + buckets.codeGraphDot + buckets.memoryArgs + buckets.webFetchArgs + buckets.grepArgs;
91
- const pct = (n) => `${((n / buckets.total) * 100).toFixed(1)}%`;
92
- console.log(JSON.stringify(buckets, null, 1));
93
- console.log(`\nrescued/reclassified: ${rescued} (${pct(rescued)})`);
94
- console.log(`test noise: ${buckets.testNoise} (${pct(buckets.testNoise)})`);
95
- console.log(`retired guard: ${buckets.retiredGuard} (${pct(buckets.retiredGuard)})`);
96
- console.log(`remaining real failures: ${buckets.realFailure} (${pct(buckets.realFailure)})`);
@@ -1,57 +0,0 @@
1
- export const SHELL_MONITOR_INTERVAL_DEFAULT_MS = 0;
2
- export const SHELL_MONITOR_INTERVAL_MIN_MS = 300_000;
3
- export const SHELL_MONITOR_INTERVAL_MAX_MS = 2_147_483_647;
4
-
5
- export function isValidShellMonitorIntervalMs(value) {
6
- return Number.isInteger(value)
7
- && (value === 0
8
- || (value >= SHELL_MONITOR_INTERVAL_MIN_MS
9
- && value <= SHELL_MONITOR_INTERVAL_MAX_MS));
10
- }
11
-
12
- export function resolveShellMonitorIntervalMs(value) {
13
- if (value == null) return SHELL_MONITOR_INTERVAL_DEFAULT_MS;
14
- const interval = Number(value);
15
- return isValidShellMonitorIntervalMs(interval)
16
- ? interval
17
- : SHELL_MONITOR_INTERVAL_DEFAULT_MS;
18
- }
19
-
20
- export function startShellMonitor({
21
- intervalMs,
22
- onTick,
23
- setTimer = setTimeout,
24
- clearTimer = clearTimeout,
25
- } = {}) {
26
- const delay = resolveShellMonitorIntervalMs(intervalMs);
27
- if (delay === 0) return () => false;
28
- let active = true;
29
- let timer = null;
30
- const schedule = () => {
31
- if (!active) return;
32
- timer = setTimer(() => {
33
- timer = null;
34
- if (!active) return;
35
- let keepRunning = true;
36
- try {
37
- keepRunning = onTick?.() !== false;
38
- } catch {
39
- keepRunning = true;
40
- }
41
- if (!active || !keepRunning) {
42
- active = false;
43
- return;
44
- }
45
- schedule();
46
- }, delay);
47
- timer?.unref?.();
48
- };
49
- schedule();
50
- return () => {
51
- if (!active) return false;
52
- active = false;
53
- if (timer != null) clearTimer(timer);
54
- timer = null;
55
- return true;
56
- };
57
- }
@@ -1,57 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import test from 'node:test';
3
- import {
4
- SHELL_MONITOR_INTERVAL_DEFAULT_MS,
5
- SHELL_MONITOR_INTERVAL_MAX_MS,
6
- resolveShellMonitorIntervalMs,
7
- startShellMonitor,
8
- } from './shell-monitor.mjs';
9
-
10
- test('shell monitor defaults to off and absorbs unsafe intervals as off', () => {
11
- assert.equal(resolveShellMonitorIntervalMs(), 0);
12
- assert.equal(resolveShellMonitorIntervalMs(0), 0);
13
- assert.equal(resolveShellMonitorIntervalMs(299_999), 0);
14
- assert.equal(resolveShellMonitorIntervalMs(SHELL_MONITOR_INTERVAL_MAX_MS + 1), 0);
15
- assert.equal(resolveShellMonitorIntervalMs(600_000), 600_000);
16
- });
17
-
18
- test('shell monitor keeps one non-overlapping timer and cancels cleanly', () => {
19
- const scheduled = [];
20
- const cleared = [];
21
- let ticks = 0;
22
- const cancel = startShellMonitor({
23
- intervalMs: 300_000,
24
- onTick: () => {
25
- ticks += 1;
26
- return ticks < 2;
27
- },
28
- setTimer: (fn, ms) => {
29
- const timer = { fn, ms, unrefCalled: false, unref() { this.unrefCalled = true; } };
30
- scheduled.push(timer);
31
- return timer;
32
- },
33
- clearTimer: (timer) => cleared.push(timer),
34
- });
35
-
36
- assert.equal(scheduled.length, 1);
37
- assert.equal(scheduled[0].ms, 300_000);
38
- assert.equal(scheduled[0].unrefCalled, true);
39
- scheduled.shift().fn();
40
- assert.equal(ticks, 1);
41
- assert.equal(scheduled.length, 1);
42
- scheduled.shift().fn();
43
- assert.equal(ticks, 2);
44
- assert.equal(scheduled.length, 0);
45
- assert.equal(cancel(), false);
46
- assert.equal(cleared.length, 0);
47
- });
48
-
49
- test('disabled shell monitor creates no timer', () => {
50
- const scheduled = [];
51
- const cancel = startShellMonitor({
52
- intervalMs: SHELL_MONITOR_INTERVAL_DEFAULT_MS,
53
- setTimer: (...args) => scheduled.push(args),
54
- });
55
- assert.equal(scheduled.length, 0);
56
- assert.equal(cancel(), false);
57
- });