mixdog 1.3.0 → 1.3.2

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 (423) hide show
  1. package/NOTICE.md +52 -9
  2. package/README.md +8 -4
  3. package/package.json +2 -2
  4. package/scripts/native-release-status.mjs +238 -0
  5. package/src/defaults/shipped-history.json +8 -1
  6. package/src/defaults/skills/pptx/scripts/qc-pages.mjs +3 -2
  7. package/src/defaults/skills/setup/SKILL.md +23 -1
  8. package/src/defaults/skills/setup/references/actions.md +54 -4
  9. package/src/defaults/skills/setup/references/surfaces.md +23 -3
  10. package/src/defaults/skills/setup-guide/SKILL.md +17 -10
  11. package/src/defaults/skills/visualize/SKILL.md +9 -6
  12. package/src/defaults/skills/visualize/references/craft.md +8 -1
  13. package/src/help.mjs +1 -1
  14. package/src/lib/keychain-cjs.cjs +4 -1
  15. package/src/lib/rules-builder.cjs +14 -7
  16. package/src/output-styles/common.md +13 -8
  17. package/src/rules/agent-mode/AGENT_MODE.md +9 -6
  18. package/src/rules/agent-mode/MIXY.md +11 -6
  19. package/src/rules/lead/LEAD.md +2 -2
  20. package/src/rules/shared/10-tool-workflow.md +4 -0
  21. package/src/rules/shared/20-research.md +2 -0
  22. package/src/runtime/agent/orchestrator/agent-runtime/agent-dispatch/preset.mjs +5 -0
  23. package/src/runtime/agent/orchestrator/agent-runtime/agent-dispatch/session-prep.mjs +8 -0
  24. package/src/runtime/agent/orchestrator/agent-runtime/agent-progress-watchdog.mjs +6 -1
  25. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +114 -26
  26. package/src/runtime/agent/orchestrator/agent-runtime/maintenance-route.mjs +8 -0
  27. package/src/runtime/agent/orchestrator/agent-runtime/room-supervisor-completion.mjs +5 -4
  28. package/src/runtime/agent/orchestrator/agent-trace.mjs +3 -0
  29. package/src/runtime/agent/orchestrator/cache-break-trace.mjs +4 -0
  30. package/src/runtime/agent/orchestrator/config-presets.mjs +2 -0
  31. package/src/runtime/agent/orchestrator/config-storage.mjs +10 -3
  32. package/src/runtime/agent/orchestrator/config.mjs +11 -0
  33. package/src/runtime/agent/orchestrator/context/role-instructions.mjs +81 -16
  34. package/src/runtime/agent/orchestrator/mcp/agent-connectors.mjs +97 -4
  35. package/src/runtime/agent/orchestrator/mcp/child-tree.mjs +6 -10
  36. package/src/runtime/agent/orchestrator/mcp/client.mjs +7 -4
  37. package/src/runtime/agent/orchestrator/providers/anthropic-api-request.mjs +80 -31
  38. package/src/runtime/agent/orchestrator/providers/anthropic-model-resolve.mjs +1 -1
  39. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  40. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +67 -38
  41. package/src/runtime/agent/orchestrator/providers/anthropic-turn-result.mjs +2 -0
  42. package/src/runtime/agent/orchestrator/providers/antigravity-oauth-catalog.mjs +7 -2
  43. package/src/runtime/agent/orchestrator/providers/antigravity-request.mjs +6 -2
  44. package/src/runtime/agent/orchestrator/providers/auto-effort.mjs +34 -16
  45. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +31 -4
  46. package/src/runtime/agent/orchestrator/providers/cursor.mjs +4 -1
  47. package/src/runtime/agent/orchestrator/providers/custom-provider.mjs +11 -8
  48. package/src/runtime/agent/orchestrator/providers/lib/anthropic-prefix-trace.mjs +76 -0
  49. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +19 -1
  50. package/src/runtime/agent/orchestrator/providers/lib/tail-reminder-split.mjs +13 -0
  51. package/src/runtime/agent/orchestrator/providers/lib/tool-call-wire-ids.mjs +65 -0
  52. package/src/runtime/agent/orchestrator/providers/media-normalization.mjs +16 -1
  53. package/src/runtime/agent/orchestrator/providers/mixdog-local.mjs +3 -1
  54. package/src/runtime/agent/orchestrator/providers/model-proxy-provider.mjs +1 -0
  55. package/src/runtime/agent/orchestrator/providers/openai-codex-metadata.mjs +5 -5
  56. package/src/runtime/agent/orchestrator/providers/openai-compat-models.mjs +9 -5
  57. package/src/runtime/agent/orchestrator/providers/openai-compat-responses.mjs +9 -1
  58. package/src/runtime/agent/orchestrator/providers/openai-compat-retry-profile.mjs +8 -2
  59. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +10 -2
  60. package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +30 -3
  61. package/src/runtime/agent/orchestrator/providers/openai-model-capabilities.mjs +1 -1
  62. package/src/runtime/agent/orchestrator/providers/openai-responses-input.mjs +3 -1
  63. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +3 -1
  64. package/src/runtime/agent/orchestrator/providers/opencode-go-oauth.mjs +61 -8
  65. package/src/runtime/agent/orchestrator/providers/provider-error-kind.mjs +14 -2
  66. package/src/runtime/agent/orchestrator/providers/registry.mjs +9 -0
  67. package/src/runtime/agent/orchestrator/providers/retry-executor.mjs +17 -0
  68. package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +90 -24
  69. package/src/runtime/agent/orchestrator/runtime-core/fs-utils.mjs +8 -1
  70. package/src/runtime/agent/orchestrator/runtime-core/goal-mutations.mjs +1 -1
  71. package/src/runtime/agent/orchestrator/runtime-core/goal-storage.mjs +68 -22
  72. package/src/runtime/agent/orchestrator/runtime-core/goal-tool-exec.mjs +1 -1
  73. package/src/runtime/agent/orchestrator/runtime-core/orchestration.mjs +5 -5
  74. package/src/runtime/agent/orchestrator/runtime-core/route-context-state.mjs +81 -0
  75. package/src/runtime/agent/orchestrator/runtime-core/session-text.mjs +2 -1
  76. package/src/runtime/agent/orchestrator/runtime-core/tool-catalog.mjs +12 -1
  77. package/src/runtime/agent/orchestrator/runtime-core/tool-defs.mjs +17 -6
  78. package/src/runtime/agent/orchestrator/runtime-core/workflow/agents.mjs +41 -10
  79. package/src/runtime/agent/orchestrator/runtime-core/workflow/context.mjs +6 -4
  80. package/src/runtime/agent/orchestrator/runtime-core/workflow/packs.mjs +8 -4
  81. package/src/runtime/agent/orchestrator/runtime-core/workflow.mjs +2 -0
  82. package/src/runtime/agent/orchestrator/session/agent-mode.mjs +0 -6
  83. package/src/runtime/agent/orchestrator/session/agent-room-supervisor.d.mts +1 -1
  84. package/src/runtime/agent/orchestrator/session/agent-room-supervisor.mjs +22 -4
  85. package/src/runtime/agent/orchestrator/session/agent-room.d.mts +21 -2
  86. package/src/runtime/agent/orchestrator/session/agent-room.mjs +149 -45
  87. package/src/runtime/agent/orchestrator/session/attachment-preflight.mjs +80 -0
  88. package/src/runtime/agent/orchestrator/session/catalog-db/schema.mjs +4 -1
  89. package/src/runtime/agent/orchestrator/session/compact/execution-tail.mjs +14 -11
  90. package/src/runtime/agent/orchestrator/session/compact/forked-summary.mjs +3 -0
  91. package/src/runtime/agent/orchestrator/session/compact/runner.mjs +68 -18
  92. package/src/runtime/agent/orchestrator/session/compact/summary-mode.mjs +16 -0
  93. package/src/runtime/agent/orchestrator/session/compact/summary-route.mjs +87 -0
  94. package/src/runtime/agent/orchestrator/session/compact/summary.mjs +2 -0
  95. package/src/runtime/agent/orchestrator/session/compact/text-utils.mjs +5 -1
  96. package/src/runtime/agent/orchestrator/session/compact/user-message-kind.mjs +1 -1
  97. package/src/runtime/agent/orchestrator/session/compaction-archive-capture.mjs +1 -1
  98. package/src/runtime/agent/orchestrator/session/context-utils.mjs +41 -10
  99. package/src/runtime/agent/orchestrator/session/human-gate/delegation.mjs +230 -0
  100. package/src/runtime/agent/orchestrator/session/human-gate/gate.mjs +156 -25
  101. package/src/runtime/agent/orchestrator/session/human-gate/outbound-policy.mjs +20 -0
  102. package/src/runtime/agent/orchestrator/session/human-gate/requests.mjs +21 -9
  103. package/src/runtime/agent/orchestrator/session/human-gate/run-policy.mjs +73 -0
  104. package/src/runtime/agent/orchestrator/session/human-gate/store.mjs +55 -27
  105. package/src/runtime/agent/orchestrator/session/human-gate/unattended-port.mjs +15 -0
  106. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +4 -1
  107. package/src/runtime/agent/orchestrator/session/loop/fresh-context.mjs +189 -105
  108. package/src/runtime/agent/orchestrator/session/loop/loop-state.mjs +9 -0
  109. package/src/runtime/agent/orchestrator/session/loop/pre-dispatch-deny.mjs +6 -2
  110. package/src/runtime/agent/orchestrator/session/loop/route-fallback.mjs +111 -9
  111. package/src/runtime/agent/orchestrator/session/loop/send-phase.mjs +11 -14
  112. package/src/runtime/agent/orchestrator/session/loop/steering.mjs +3 -0
  113. package/src/runtime/agent/orchestrator/session/loop/tool-exec/before-hook.mjs +38 -5
  114. package/src/runtime/agent/orchestrator/session/loop/tool-exec/dispatch.mjs +21 -0
  115. package/src/runtime/agent/orchestrator/session/loop/tool-exec.mjs +2 -1
  116. package/src/runtime/agent/orchestrator/session/loop/tool-exposure-migration.mjs +12 -0
  117. package/src/runtime/agent/orchestrator/session/loop/tool-helpers.mjs +11 -5
  118. package/src/runtime/agent/orchestrator/session/loop/usage.mjs +46 -4
  119. package/src/runtime/agent/orchestrator/session/manager/ask-turn-auto-effort.mjs +13 -2
  120. package/src/runtime/agent/orchestrator/session/manager/ask-turn-commit.mjs +18 -8
  121. package/src/runtime/agent/orchestrator/session/manager/ask-turn-execute.mjs +4 -0
  122. package/src/runtime/agent/orchestrator/session/manager/ask-turn-prepare.mjs +6 -0
  123. package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +4 -0
  124. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +44 -18
  125. package/src/runtime/agent/orchestrator/session/manager/orchestration-mode-switch-notice.mjs +99 -0
  126. package/src/runtime/agent/orchestrator/session/manager/owner-route-fallbacks.mjs +42 -0
  127. package/src/runtime/agent/orchestrator/session/manager/pending-messages.mjs +3 -9
  128. package/src/runtime/agent/orchestrator/session/manager/pending-spool-file.mjs +1 -1
  129. package/src/runtime/agent/orchestrator/session/manager/pending-spool-shard.mjs +5 -3
  130. package/src/runtime/agent/orchestrator/session/manager/provider-replay.mjs +50 -0
  131. package/src/runtime/agent/orchestrator/session/manager/rules-cache.mjs +40 -1
  132. package/src/runtime/agent/orchestrator/session/manager/runtime-liveness.mjs +12 -0
  133. package/src/runtime/agent/orchestrator/session/manager/runtime-state.mjs +20 -0
  134. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +62 -47
  135. package/src/runtime/agent/orchestrator/session/manager/session-prompt-composition.mjs +6 -8
  136. package/src/runtime/agent/orchestrator/session/manager/session-record.mjs +12 -1
  137. package/src/runtime/agent/orchestrator/session/manager/turn-checkpoint-journal.mjs +6 -15
  138. package/src/runtime/agent/orchestrator/session/manager/turn-checkpoint.mjs +7 -1
  139. package/src/runtime/agent/orchestrator/session/manager/turn-interruption.mjs +24 -8
  140. package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +1 -1
  141. package/src/runtime/agent/orchestrator/session/manager/workflow-switch-notice.mjs +94 -13
  142. package/src/runtime/agent/orchestrator/session/mixy-name.mjs +5 -2
  143. package/src/runtime/agent/orchestrator/session/pre-send-compact.mjs +42 -10
  144. package/src/runtime/agent/orchestrator/session/provider-prefix-guard.mjs +21 -3
  145. package/src/runtime/agent/orchestrator/session/routine-result.d.mts +35 -4
  146. package/src/runtime/agent/orchestrator/session/routine-result.mjs +179 -16
  147. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +5 -1
  148. package/src/runtime/agent/orchestrator/session/side-question-store.mjs +3 -1
  149. package/src/runtime/agent/orchestrator/session/store/canonical-reader.mjs +41 -7
  150. package/src/runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs +10 -2
  151. package/src/runtime/agent/orchestrator/session/store/load-cache.mjs +14 -2
  152. package/src/runtime/agent/orchestrator/session/store/session-delete.mjs +15 -1
  153. package/src/runtime/agent/orchestrator/session/store/sweep/sweep-record.mjs +8 -3
  154. package/src/runtime/agent/orchestrator/session/store/sweep/sweep-row.mjs +36 -1
  155. package/src/runtime/agent/orchestrator/session/store-summary-catalog.mjs +4 -1
  156. package/src/runtime/agent/orchestrator/session/store-summary-index.mjs +40 -5
  157. package/src/runtime/agent/orchestrator/session/store-summary-last-message.mjs +47 -2
  158. package/src/runtime/agent/orchestrator/session/tail-reminder-rules.mjs +125 -0
  159. package/src/runtime/agent/orchestrator/session/tool-batch/finalize.mjs +4 -0
  160. package/src/runtime/agent/orchestrator/session/tool-result-offload.mjs +78 -43
  161. package/src/runtime/agent/orchestrator/session/transcript-restore/restore.mjs +49 -14
  162. package/src/runtime/agent/orchestrator/session/transcript-restore/user-text.mjs +134 -17
  163. package/src/runtime/agent/orchestrator/tools/builtin/advisory-lock.mjs +35 -13
  164. package/src/runtime/agent/orchestrator/tools/builtin/atomic-write.mjs +25 -5
  165. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool/backgrounded-result.mjs +4 -3
  166. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool/completed-result.mjs +13 -14
  167. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool/transport-artifacts.mjs +9 -0
  168. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +19 -14
  169. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +7 -1
  170. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-job-records.mjs +6 -14
  171. package/src/runtime/agent/orchestrator/tools/builtin/pdf-test-fixtures.mjs +5 -3
  172. package/src/runtime/agent/orchestrator/tools/builtin/read-image.mjs +4 -2
  173. package/src/runtime/agent/orchestrator/tools/builtin/read-single-media.mjs +47 -2
  174. package/src/runtime/agent/orchestrator/tools/builtin/read-special-files.mjs +264 -87
  175. package/src/runtime/agent/orchestrator/tools/builtin/shell-analysis.mjs +10 -4
  176. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +34 -21
  177. package/src/runtime/agent/orchestrator/tools/code-graph/constants.mjs +8 -4
  178. package/src/runtime/agent/orchestrator/tools/lib/shell-descendants.mjs +9 -30
  179. package/src/runtime/agent/orchestrator/tools/lib/shell-run-settle.mjs +24 -12
  180. package/src/runtime/agent/orchestrator/tools/lib/shell-run-spawn.mjs +3 -2
  181. package/src/runtime/agent/orchestrator/tools/lib/shell-run-state.mjs +6 -2
  182. package/src/runtime/agent/orchestrator/tools/patch/delete-quarantine.mjs +2 -1
  183. package/src/runtime/agent/orchestrator/tools/patch/replay-capture.mjs +4 -2
  184. package/src/runtime/agent/orchestrator/tools/patch/rollback-state.mjs +33 -2
  185. package/src/runtime/agent/orchestrator/tools/patch-manifest.json +13 -13
  186. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +5 -3
  187. package/src/runtime/agent/orchestrator/tools/shell-exec-output.mjs +3 -1
  188. package/src/runtime/attachments/attachment-reference.mjs +155 -0
  189. package/src/runtime/attachments/limits.mjs +5 -1
  190. package/src/runtime/attachments/office-extract.mjs +3 -6
  191. package/src/runtime/attachments/pdf-extract.mjs +84 -10
  192. package/src/runtime/attachments/store.mjs +55 -30
  193. package/src/runtime/browser-bridge/client.mjs +73 -20
  194. package/src/runtime/channels/lib/runtime-paths.mjs +1 -1
  195. package/src/runtime/channels/lib/scheduler.mjs +14 -7
  196. package/src/runtime/channels/lib/state-file.mjs +15 -15
  197. package/src/runtime/channels/lib/voice-runtime-fetcher.mjs +14 -13
  198. package/src/runtime/channels/lib/webhook/relay-tunnel.mjs +22 -18
  199. package/src/runtime/channels/lib/webhook/session-dispatch.mjs +14 -36
  200. package/src/runtime/channels/lib/worker-main.mjs +3 -2
  201. package/src/runtime/effort-judge/compact-tokenizer.mjs +8 -2
  202. package/src/runtime/effort-judge/judge-client.mjs +6 -3
  203. package/src/runtime/effort-judge/model-install.mjs +16 -8
  204. package/src/runtime/effort-judge/model-manifest.json +7 -7
  205. package/src/runtime/local-provider/asset-installer.mjs +10 -4
  206. package/src/runtime/local-provider/catalog.mjs +5 -2
  207. package/src/runtime/local-provider/registered-models.mjs +64 -27
  208. package/src/runtime/local-provider/server.mjs +2 -3
  209. package/src/runtime/media/adapters/image-api.mjs +89 -0
  210. package/src/runtime/media/auth.mjs +64 -1
  211. package/src/runtime/media/catalog.mjs +66 -4
  212. package/src/runtime/media/jobs.mjs +4 -0
  213. package/src/runtime/media/lanes.mjs +46 -5
  214. package/src/runtime/media/media-usage.mjs +17 -0
  215. package/src/runtime/media/renditions.mjs +15 -15
  216. package/src/runtime/media/store.mjs +36 -35
  217. package/src/runtime/media/tool.mjs +8 -1
  218. package/src/runtime/memory/lib/cycle-scheduler/health-ledger.mjs +8 -2
  219. package/src/runtime/memory/lib/embedding-model-files.mjs +30 -7
  220. package/src/runtime/memory/lib/ingest/transcript-tail.mjs +16 -7
  221. package/src/runtime/memory/lib/pg/process.mjs +8 -4
  222. package/src/runtime/memory/lib/project-id-resolver.mjs +5 -1
  223. package/src/runtime/memory/lib/runtime-fetcher.mjs +6 -1
  224. package/src/runtime/office/core/journal.mjs +7 -14
  225. package/src/runtime/office/design/library/design-library-core.mjs +4 -16
  226. package/src/runtime/office/pdf/ocr-engine-worker.mjs +37 -0
  227. package/src/runtime/office/pdf/ocr-engine.mjs +146 -0
  228. package/src/runtime/office/pdf/pdf-ocr.mjs +51 -21
  229. package/src/runtime/office/pdf/pdf-render.mjs +30 -18
  230. package/src/runtime/office/portable/ooxml-validator.mjs +2 -2
  231. package/src/runtime/office/portable/portable-soffice.mjs +4 -0
  232. package/src/runtime/shared/agent-kind-migration.mjs +200 -0
  233. package/src/runtime/shared/agent-kind.mjs +152 -0
  234. package/src/runtime/shared/agent-message-envelope.d.mts +6 -0
  235. package/src/runtime/shared/agent-message-envelope.mjs +44 -0
  236. package/src/runtime/shared/agent-reap-state.d.mts +4 -0
  237. package/src/runtime/shared/agent-route-config.d.mts +1 -0
  238. package/src/runtime/shared/agent-route-config.mjs +22 -8
  239. package/src/runtime/shared/agent-store.mjs +149 -0
  240. package/src/runtime/shared/agent-task-starts.mjs +27 -0
  241. package/src/runtime/shared/atomic-file.d.mts +50 -0
  242. package/src/runtime/shared/atomic-file.mjs +394 -132
  243. package/src/runtime/shared/background-tasks.mjs +7 -4
  244. package/src/runtime/shared/bot-hops.mjs +30 -0
  245. package/src/runtime/shared/bot-split-migration.mjs +457 -0
  246. package/src/runtime/shared/bounded-download.mjs +4 -2
  247. package/src/runtime/shared/config-patch.mjs +20 -1
  248. package/src/runtime/shared/config.mjs +39 -9
  249. package/src/runtime/shared/connector-catalog.d.mts +1 -2
  250. package/src/runtime/shared/connector-catalog.mjs +2 -4
  251. package/src/runtime/shared/connector-triggers.mjs +2 -0
  252. package/src/runtime/shared/defaults-separation.mjs +6 -2
  253. package/src/runtime/shared/delegated-approval-host.mjs +74 -0
  254. package/src/runtime/shared/err-text.mjs +7 -1
  255. package/src/runtime/shared/error-presentation.mjs +113 -10
  256. package/src/runtime/shared/file-has-data.mjs +28 -0
  257. package/src/runtime/shared/handoff-artifacts.d.mts +20 -0
  258. package/src/runtime/shared/handoff-artifacts.mjs +61 -0
  259. package/src/runtime/shared/llm/provider-model-identities.mjs +6 -1
  260. package/src/runtime/shared/llm/usage-accounting.mjs +7 -1
  261. package/src/runtime/shared/llm/usage-ledger-import.mjs +37 -18
  262. package/src/runtime/shared/model-route-fallback.mjs +79 -7
  263. package/src/runtime/shared/pending-agent-work.mjs +54 -0
  264. package/src/runtime/shared/plain-preview.mjs +22 -17
  265. package/src/runtime/shared/process-lifecycle.mjs +8 -12
  266. package/src/runtime/shared/projects.mjs +50 -41
  267. package/src/runtime/shared/provider-accounts.mjs +17 -12
  268. package/src/runtime/shared/routine-trigger.d.mts +6 -1
  269. package/src/runtime/shared/routine-trigger.mjs +14 -6
  270. package/src/runtime/shared/run-child.d.mts +3 -0
  271. package/src/runtime/shared/run-child.mjs +24 -3
  272. package/src/runtime/shared/sensitive-path-rules.d.mts +15 -0
  273. package/src/runtime/shared/sensitive-path-rules.mjs +256 -0
  274. package/src/runtime/shared/session-baseline-store.mjs +8 -2
  275. package/src/runtime/shared/singleton-owner.mjs +7 -6
  276. package/src/runtime/shared/skill-tool-dependencies.mjs +4 -10
  277. package/src/runtime/shared/staged-update.mjs +4 -2
  278. package/src/runtime/shared/statusline/statusline-segments.mjs +4 -15
  279. package/src/runtime/shared/tool-execution-contract.mjs +6 -0
  280. package/src/runtime/shared/transcript-metadata.mjs +28 -3
  281. package/src/runtime/shared/transcript-writer/session-record.mjs +7 -6
  282. package/src/runtime/shared/turn-snapshot-store.mjs +5 -4
  283. package/src/runtime/shared/turn-snapshot.mjs +44 -2
  284. package/src/runtime/shared/usage-readout-totals.mjs +15 -13
  285. package/src/runtime/shared/user-cwd.mjs +9 -4
  286. package/src/runtime/shared/user-data-guard.mjs +46 -44
  287. package/src/runtime/shared/utf8-cut.mjs +10 -0
  288. package/src/runtime/shared/worktrees/activity-gate.mjs +269 -61
  289. package/src/runtime/shared/worktrees/registry.mjs +26 -26
  290. package/src/runtime/tidy/core-install.mjs +26 -4
  291. package/src/runtime/tidy/install.mjs +91 -23
  292. package/src/runtime/web-search/lib/config.mjs +4 -16
  293. package/src/session-runtime/agent-home-delivery.mjs +859 -136
  294. package/src/session-runtime/agent-room-delivery.mjs +167 -19
  295. package/src/session-runtime/agent-task-sessions.mjs +831 -69
  296. package/src/session-runtime/agent-tool-routing.mjs +1 -0
  297. package/src/session-runtime/boot/apis.mjs +58 -24
  298. package/src/session-runtime/boot/config.mjs +1 -0
  299. package/src/session-runtime/boot/facade.mjs +11 -1
  300. package/src/session-runtime/boot/infrastructure.mjs +14 -2
  301. package/src/session-runtime/boot/providers.mjs +16 -6
  302. package/src/session-runtime/boot/shared.mjs +12 -6
  303. package/src/session-runtime/boot/tools.mjs +2 -2
  304. package/src/session-runtime/bot-status.mjs +432 -0
  305. package/src/session-runtime/config-lifecycle/lead-route-sync.mjs +29 -0
  306. package/src/session-runtime/config-lifecycle.mjs +78 -32
  307. package/src/session-runtime/cwd-plugins/core-memory-context.mjs +2 -4
  308. package/src/session-runtime/handoff-attachments.mjs +593 -0
  309. package/src/session-runtime/held-requests.mjs +36 -33
  310. package/src/session-runtime/internal-tool-executor/bridge-tools.mjs +10 -1
  311. package/src/session-runtime/internal-tool-executor/feature-tools.mjs +2 -2
  312. package/src/session-runtime/internal-tool-executor/workspace-tools.mjs +45 -6
  313. package/src/session-runtime/lifecycle/session-catalog.mjs +12 -2
  314. package/src/session-runtime/lifecycle/teardown.mjs +11 -3
  315. package/src/session-runtime/mcp-glue/connect.mjs +100 -186
  316. package/src/session-runtime/mcp-glue/initial-connect-gate.mjs +57 -0
  317. package/src/session-runtime/mcp-glue/server-connection.mjs +71 -0
  318. package/src/session-runtime/media-api.mjs +5 -2
  319. package/src/session-runtime/model-route/route-persist.mjs +2 -2
  320. package/src/session-runtime/model-route/route-tuning.mjs +11 -2
  321. package/src/session-runtime/model-route/set-route.mjs +82 -2
  322. package/src/session-runtime/native-web-search.mjs +2 -2
  323. package/src/session-runtime/new-session-config.mjs +6 -1
  324. package/src/session-runtime/owned-automation-run.mjs +8 -1
  325. package/src/session-runtime/room-member-gate.mjs +16 -3
  326. package/src/session-runtime/route-resolution.mjs +21 -19
  327. package/src/session-runtime/route-state.mjs +1 -59
  328. package/src/session-runtime/routine-home-turn.mjs +5 -3
  329. package/src/session-runtime/runtime-bootstrap.mjs +5 -3
  330. package/src/session-runtime/runtime-paths.mjs +11 -5
  331. package/src/session-runtime/runtime-tunables.mjs +6 -0
  332. package/src/session-runtime/services/agent-tool/close-flow/close-all.mjs +11 -2
  333. package/src/session-runtime/services/agent-tool/close-flow.mjs +4 -2
  334. package/src/session-runtime/services/agent-tool/execute-send.mjs +1 -0
  335. package/src/session-runtime/services/agent-tool/execute-spawn.mjs +1 -0
  336. package/src/session-runtime/services/agent-tool/helpers.mjs +24 -5
  337. package/src/session-runtime/services/agent-tool/restart-notify.mjs +10 -0
  338. package/src/session-runtime/services/agent-tool/send-flow.mjs +36 -24
  339. package/src/session-runtime/services/agent-tool/spawn-flow/job-start.mjs +4 -0
  340. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +6 -3
  341. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +12 -6
  342. package/src/session-runtime/services/agent-tool/spawn-preset.mjs +5 -8
  343. package/src/session-runtime/services/agent-tool/tool-def.mjs +7 -0
  344. package/src/session-runtime/services/agent-tool/worker-index/row-liveness.mjs +22 -2
  345. package/src/session-runtime/services/agent-tool/worker-index.mjs +4 -6
  346. package/src/session-runtime/services/agent-tool.mjs +6 -0
  347. package/src/session-runtime/services/daemon-crash-capture/daemon-exit-record.mjs +1 -1
  348. package/src/session-runtime/services/daemon-crash-capture/retention.mjs +4 -3
  349. package/src/session-runtime/services/hook-bus/config-loader.mjs +14 -5
  350. package/src/session-runtime/services/hook-bus/rule-file.mjs +49 -11
  351. package/src/session-runtime/services/plugin-admin.mjs +26 -26
  352. package/src/session-runtime/services/provider-admin.mjs +14 -4
  353. package/src/session-runtime/services/schedule-access.mjs +33 -4
  354. package/src/session-runtime/services/seeds.mjs +4 -3
  355. package/src/session-runtime/services/usage-dashboard.mjs +1 -1
  356. package/src/session-runtime/services/usage-stats-model.mjs +2 -1
  357. package/src/session-runtime/session-create/materialize.mjs +2 -3
  358. package/src/session-runtime/session-create/session-options.mjs +15 -2
  359. package/src/session-runtime/settings-builtin-tools-api.mjs +63 -1
  360. package/src/session-runtime/settings-compaction-api.mjs +86 -39
  361. package/src/session-runtime/setup-tool/executor.mjs +20 -3
  362. package/src/session-runtime/setup-tool/extended-actions.mjs +19 -7
  363. package/src/session-runtime/setup-tool/settings-contract.mjs +37 -1
  364. package/src/session-runtime/setup-tool/tool-defs.mjs +20 -3
  365. package/src/session-runtime/skills-api.mjs +12 -5
  366. package/src/session-runtime/tool-policy/agent-profile-fold.mjs +265 -0
  367. package/src/session-runtime/tool-policy/mode-switch.mjs +54 -0
  368. package/src/session-runtime/tool-policy/pending-switches.mjs +59 -0
  369. package/src/session-runtime/tool-policy/policy-stage.mjs +165 -0
  370. package/src/session-runtime/tool-policy/session-switches.mjs +169 -0
  371. package/src/session-runtime/tool-policy/surface-helpers.mjs +114 -0
  372. package/src/session-runtime/tool-policy/workflow-overlay.mjs +145 -0
  373. package/src/session-runtime/tool-policy-refresh.mjs +47 -358
  374. package/src/session-runtime/tool-surface.mjs +5 -3
  375. package/src/session-runtime/turn/turn-run/turn-prepare.mjs +99 -81
  376. package/src/session-runtime/turn/turn-run/turn-timing.mjs +4 -3
  377. package/src/session-runtime/turn/turn-run.mjs +2 -1
  378. package/src/session-runtime/workflow-agents-api/agent-connectors.mjs +54 -7
  379. package/src/session-runtime/workflow-agents-api/agent-editor.mjs +578 -301
  380. package/src/session-runtime/workflow-agents-api/agent-route.mjs +113 -53
  381. package/src/session-runtime/workflow-agents-api/onboarding.mjs +11 -4
  382. package/src/session-runtime/workflow-agents-api/shared.mjs +5 -1
  383. package/src/session-runtime/workflow-agents-api/style-and-mode.mjs +14 -1
  384. package/src/session-runtime/workflow-agents-api/workflow-packs.mjs +6 -3
  385. package/src/session-runtime/workspace/workspace-state.mjs +7 -6
  386. package/src/standalone/daemon-agent-control.mjs +4 -1
  387. package/src/standalone/daemon-session-control.mjs +60 -11
  388. package/src/standalone/daemon.mjs +34 -4
  389. package/src/standalone/local-session-runtime.mjs +22 -14
  390. package/src/standalone/session-client.mjs +7 -2
  391. package/src/standalone/session-protocol.mjs +7 -0
  392. package/src/standalone/session-service/agent-tree/agent-turns.mjs +46 -3
  393. package/src/standalone/session-service/agent-tree.mjs +4 -3
  394. package/src/standalone/session-service/session-calls/session-turns.mjs +19 -0
  395. package/src/standalone/session-service.mjs +11 -0
  396. package/src/standalone/session-state-projection.mjs +19 -9
  397. package/src/standalone/session-tool-output.mjs +35 -9
  398. package/src/tui/app/maintenance-pickers/auto-clear-picker.mjs +19 -13
  399. package/src/tui/app/settings-picker/settings-rows.mjs +2 -2
  400. package/src/tui/app/slash-commands.mjs +1 -1
  401. package/src/tui/app/usage-context-panels/context-model.mjs +8 -2
  402. package/src/tui/dist/index.mjs +599 -342
  403. package/src/tui/prompt-history-store.mjs +16 -21
  404. package/src/tui/session/context-state.mjs +4 -0
  405. package/src/tui/session/notice-surface.mjs +3 -4
  406. package/src/tui/session/session-api/intake/abort.mjs +19 -1
  407. package/src/tui/session/session-api/media.mjs +2 -1
  408. package/src/tui/session/session-api/routes-agent-definitions.mjs +75 -0
  409. package/src/tui/session/session-api/routes-write.mjs +203 -0
  410. package/src/tui/session/session-api/routes.mjs +23 -236
  411. package/src/tui/session/session-api/settings.mjs +14 -1
  412. package/src/tui/session/session-flow/drain.mjs +28 -3
  413. package/src/tui/session/session-flow/failed-turn-rewind.mjs +4 -2
  414. package/src/tui/session/session-flow/queue/take-entries.mjs +8 -0
  415. package/src/tui/session/session-flow/steering.mjs +8 -3
  416. package/src/tui/session/tool-approval.mjs +185 -20
  417. package/src/tui/session/transcript-intake.mjs +4 -0
  418. package/src/tui/session/turn-live-call.mjs +11 -3
  419. package/src/tui/session/turn.mjs +36 -17
  420. package/src/tui/transcript-tool-failures.mjs +8 -2
  421. package/src/vendor/statusline/src/gateway/route-meta.mjs +7 -8
  422. package/src/vendor/statusline/src/gateway/session-routes.mjs +6 -7
  423. package/src/rules/agent-mode/ROUTINE.md +0 -6
@@ -23113,10 +23113,10 @@ var require_stack_utils = __commonJS({
23113
23113
  });
23114
23114
 
23115
23115
  // src/runtime/shared/file-permissions.mjs
23116
- import { existsSync as existsSync4 } from "node:fs";
23117
- import { dirname as dirname3, join as join3, resolve as resolve3 } from "node:path";
23116
+ import { existsSync as existsSync3 } from "node:fs";
23117
+ import { dirname, join, resolve as resolve2 } from "node:path";
23118
23118
  import { execFile as execFile2, execFileSync as execFileSync2, spawn as spawn3 } from "node:child_process";
23119
- import { fileURLToPath as fileURLToPath2 } from "node:url";
23119
+ import { fileURLToPath } from "node:url";
23120
23120
  import { MessageChannel as MessageChannel2, receiveMessageOnPort, SHARE_ENV, Worker } from "node:worker_threads";
23121
23121
  function execFileAsync(file, args, options) {
23122
23122
  return new Promise((done, fail) => {
@@ -23169,7 +23169,7 @@ function startAclHelper(icacls, sid) {
23169
23169
  let child;
23170
23170
  try {
23171
23171
  child = spawn3(command.executable, command.args, {
23172
- cwd: dirname3(icacls),
23172
+ cwd: dirname(icacls),
23173
23173
  stdio: ["pipe", "pipe", "ignore"],
23174
23174
  windowsHide: true
23175
23175
  });
@@ -23250,7 +23250,7 @@ function syncBridge() {
23250
23250
  if (aclSyncBridge || aclSyncBridgeBroken) return aclSyncBridge;
23251
23251
  try {
23252
23252
  const url = new URL("./file-permissions-worker.mjs", import.meta.url);
23253
- if (!existsSync4(fileURLToPath2(url))) throw new Error("Windows ACL bridge worker is not shipped here");
23253
+ if (!existsSync3(fileURLToPath(url))) throw new Error("Windows ACL bridge worker is not shipped here");
23254
23254
  const { port1, port2 } = new MessageChannel2();
23255
23255
  const signal = new Int32Array(new SharedArrayBuffer(12));
23256
23256
  const worker = new Worker(url, {
@@ -23304,7 +23304,7 @@ function askSyncBridge(targetPath) {
23304
23304
  }
23305
23305
  function systemToolPath(name) {
23306
23306
  const systemRoot = process.env.SystemRoot || process.env.windir;
23307
- return systemRoot ? join3(systemRoot, "System32", name) : null;
23307
+ return systemRoot ? join(systemRoot, "System32", name) : null;
23308
23308
  }
23309
23309
  function currentUserSid(output) {
23310
23310
  return String(output).trim().match(/^"(?:[^"]|"")*","(S-\d+(?:-\d+)+)"$/)?.[1] || null;
@@ -23316,7 +23316,7 @@ function unresolvedUserError() {
23316
23316
  }
23317
23317
  function resolveCurrentUserPrincipal() {
23318
23318
  const whoami = systemToolPath("whoami.exe");
23319
- if (whoami && existsSync4(whoami)) {
23319
+ if (whoami && existsSync3(whoami)) {
23320
23320
  try {
23321
23321
  const output = execFileSync2(whoami, ["/user", "/fo", "csv", "/nh"], {
23322
23322
  encoding: "utf8",
@@ -23332,7 +23332,7 @@ function resolveCurrentUserPrincipal() {
23332
23332
  }
23333
23333
  async function resolveCurrentUserPrincipalAsync() {
23334
23334
  const whoami = systemToolPath("whoami.exe");
23335
- if (whoami && existsSync4(whoami)) {
23335
+ if (whoami && existsSync3(whoami)) {
23336
23336
  try {
23337
23337
  const { stdout: stdout2 } = await execFileAsync(whoami, ["/user", "/fo", "csv", "/nh"], {
23338
23338
  encoding: "utf8",
@@ -23352,7 +23352,7 @@ function icaclsPath() {
23352
23352
  error.code = "EACLNOROOT";
23353
23353
  throw error;
23354
23354
  }
23355
- if (!existsSync4(path2)) {
23355
+ if (!existsSync3(path2)) {
23356
23356
  const error = new Error(`icacls.exe not found at ${path2}; refusing to leave secret world-readable`);
23357
23357
  error.code = "EACLNOICACLS";
23358
23358
  throw error;
@@ -23361,7 +23361,7 @@ function icaclsPath() {
23361
23361
  }
23362
23362
  function powerShellCommand(icacls, script) {
23363
23363
  return {
23364
- executable: join3(dirname3(icacls), "WindowsPowerShell", "v1.0", "powershell.exe"),
23364
+ executable: join(dirname(icacls), "WindowsPowerShell", "v1.0", "powershell.exe"),
23365
23365
  label: "Windows ACL update",
23366
23366
  args: ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")]
23367
23367
  };
@@ -23402,7 +23402,7 @@ function enforceOwnerOnlyAclWin32(targetPath, { fresh = false } = {}) {
23402
23402
  if (process.platform !== "win32") return;
23403
23403
  const icacls = icaclsPath();
23404
23404
  if (fresh) {
23405
- const reply = askSyncBridge(resolve3(targetPath));
23405
+ const reply = askSyncBridge(resolve2(targetPath));
23406
23406
  if (reply.ok === true) return;
23407
23407
  if (reply.ok === false) throw Object.assign(new Error(reply.message), { code: reply.code || "EACLFAIL" });
23408
23408
  if (reply.timedOut) {
@@ -23425,7 +23425,7 @@ async function enforceOwnerOnlyAclWin32Async(targetPath, { fresh = false } = {})
23425
23425
  if (process.platform !== "win32") return;
23426
23426
  const icacls = icaclsPath();
23427
23427
  if (cachedUserSid === null) cachedUserSid = await resolveCurrentUserPrincipalAsync();
23428
- const reply = await askAclHelper(resolve3(targetPath), icacls, cachedUserSid);
23428
+ const reply = await askAclHelper(resolve2(targetPath), icacls, cachedUserSid);
23429
23429
  if (reply.status === "ok" || reply.status === "fixed") return;
23430
23430
  if (reply.status === "err") {
23431
23431
  throw aclFailure(targetPath, new Error(reply.detail || "unknown error"), "Windows ACL helper");
@@ -23500,13 +23500,13 @@ var init_sleep = __esm({
23500
23500
  // src/runtime/shared/file-lock.mjs
23501
23501
  import {
23502
23502
  linkSync,
23503
- mkdirSync as mkdirSync2,
23503
+ mkdirSync,
23504
23504
  readdirSync,
23505
- readFileSync as readFileSync3,
23506
- renameSync as renameSync2,
23505
+ readFileSync as readFileSync2,
23506
+ renameSync,
23507
23507
  statSync,
23508
23508
  unlinkSync as unlinkSync2,
23509
- writeFileSync as writeFileSync2
23509
+ writeFileSync
23510
23510
  } from "node:fs";
23511
23511
  import {
23512
23512
  link as linkAsync,
@@ -23516,7 +23516,7 @@ import {
23516
23516
  unlink as unlinkAsync,
23517
23517
  writeFile as writeFileAsync
23518
23518
  } from "node:fs/promises";
23519
- import { basename as basename2, dirname as dirname4, join as join4 } from "node:path";
23519
+ import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
23520
23520
  import { randomBytes as randomBytes2 } from "node:crypto";
23521
23521
  import { AsyncLocalStorage } from "node:async_hooks";
23522
23522
  function markOsHeld(lockPath) {
@@ -23780,7 +23780,7 @@ function lockStaleMs(opts) {
23780
23780
  function sweepStagedLockFiles(lockPath, now = Date.now()) {
23781
23781
  if (sweptLockPaths.has(lockPath)) return 0;
23782
23782
  sweptLockPaths.add(lockPath);
23783
- const dir = dirname4(lockPath);
23783
+ const dir = dirname2(lockPath);
23784
23784
  const prefix = `${basename2(lockPath)}.`;
23785
23785
  let removed = 0;
23786
23786
  let names;
@@ -23793,7 +23793,7 @@ function sweepStagedLockFiles(lockPath, now = Date.now()) {
23793
23793
  if (!name.startsWith(prefix)) continue;
23794
23794
  const match = /^(?:reclaim\.)?(\d+)\.[0-9a-f]{16}\.tmp$/.exec(name.slice(prefix.length));
23795
23795
  if (!match) continue;
23796
- const path2 = join4(dir, name);
23796
+ const path2 = join2(dir, name);
23797
23797
  try {
23798
23798
  if (now - statSync(path2).mtimeMs < STAGED_LOCK_FILE_STALE_MS) continue;
23799
23799
  if (ownerIsLive({ pid: Number(match[1]), token: null })) continue;
@@ -23808,7 +23808,7 @@ function* acquireLock(lockPath, opts, mode, markHeld, timing = null) {
23808
23808
  const timeoutMs = lockTimeoutMs(opts);
23809
23809
  const staleMs = lockStaleMs(opts);
23810
23810
  const deadline = Date.now() + timeoutMs;
23811
- yield ["mkdirp", dirname4(lockPath)];
23811
+ yield ["mkdirp", dirname2(lockPath)];
23812
23812
  sweepStagedLockFiles(lockPath);
23813
23813
  const waitStartedAt = Date.now();
23814
23814
  let attempt = 0;
@@ -23907,10 +23907,10 @@ var init_file_lock = __esm({
23907
23907
  SYNC_IO = {
23908
23908
  stat: (path2) => statSync(path2),
23909
23909
  statId: (path2) => statSync(path2, { bigint: true }),
23910
- rename: (from, to) => renameSync2(from, to),
23911
- read: (path2) => readFileSync3(path2, "utf8"),
23912
- mkdirp: (path2) => mkdirSync2(path2, { recursive: true }),
23913
- createExclusive: (path2, data) => writeFileSync2(path2, data, { encoding: "utf8", mode: 384, flag: "wx" }),
23910
+ rename: (from, to) => renameSync(from, to),
23911
+ read: (path2) => readFileSync2(path2, "utf8"),
23912
+ mkdirp: (path2) => mkdirSync(path2, { recursive: true }),
23913
+ createExclusive: (path2, data) => writeFileSync(path2, data, { encoding: "utf8", mode: 384, flag: "wx" }),
23914
23914
  link: (from, to) => linkSync(from, to),
23915
23915
  unlink: (path2) => unlinkSync2(path2),
23916
23916
  sleep: (ms) => sleepSync(ms)
@@ -23932,15 +23932,16 @@ var init_file_lock = __esm({
23932
23932
  // src/runtime/shared/atomic-file.mjs
23933
23933
  import {
23934
23934
  closeSync,
23935
- existsSync as existsSync5,
23935
+ existsSync as existsSync4,
23936
23936
  fsyncSync,
23937
23937
  linkSync as linkSync2,
23938
- mkdirSync as mkdirSync3,
23938
+ mkdirSync as mkdirSync2,
23939
23939
  openSync,
23940
- readFileSync as readFileSync4,
23941
- renameSync as renameSync3,
23940
+ readFileSync as readFileSync3,
23941
+ renameSync as renameSync2,
23942
+ statSync as statSync2,
23942
23943
  unlinkSync as unlinkSync3,
23943
- writeFileSync as writeFileSync3
23944
+ writeFileSync as writeFileSync2
23944
23945
  } from "node:fs";
23945
23946
  import {
23946
23947
  link as linkAsync2,
@@ -23948,11 +23949,10 @@ import {
23948
23949
  open as openAsync,
23949
23950
  readFile as readFileAsync3,
23950
23951
  rename as renameAsync,
23951
- unlink as unlinkAsync2,
23952
- writeFile as writeFileAsync2
23952
+ unlink as unlinkAsync2
23953
23953
  } from "node:fs/promises";
23954
23954
  import { tmpdir as tmpdir2 } from "node:os";
23955
- import { dirname as dirname5, basename as basename3, join as join5, relative, isAbsolute as isAbsolute2, resolve as resolve4 } from "node:path";
23955
+ import { dirname as dirname3, basename as basename3, join as join3, relative, isAbsolute as isAbsolute2, resolve as resolve3 } from "node:path";
23956
23956
  import { randomBytes as randomBytes3 } from "node:crypto";
23957
23957
  function _drainAdaptiveFileIo() {
23958
23958
  while (_ioActive < _ioLimit && _ioQueue.length > 0) {
@@ -23987,16 +23987,25 @@ function _runAdaptiveFileIo(run) {
23987
23987
  function renameBackoffs(opts) {
23988
23988
  return Array.isArray(opts.backoffs) && opts.backoffs.length > 0 ? opts.backoffs : DEFAULT_BACKOFFS_MS;
23989
23989
  }
23990
- function nextRenameDelayMs(err, attempt, backoffs) {
23990
+ function isReadOnlyFile(path2) {
23991
+ try {
23992
+ const stat2 = statSync2(path2);
23993
+ return stat2.isFile() && (stat2.mode & 128) === 0;
23994
+ } catch {
23995
+ return false;
23996
+ }
23997
+ }
23998
+ function nextRenameDelayMs(err, attempt, backoffs, dst) {
23991
23999
  if (!RETRY_CODES.has(err?.code) || attempt >= backoffs.length) return null;
24000
+ if ((err.code === "EPERM" || err.code === "EACCES") && isReadOnlyFile(dst)) return null;
23992
24001
  return backoffs[attempt] + Math.floor(Math.random() * Math.min(50, Math.max(1, backoffs[attempt])));
23993
24002
  }
23994
24003
  function renameAttempt(src, dst, attempt, opts = {}) {
23995
24004
  try {
23996
- renameSync3(src, dst);
24005
+ renameSync2(src, dst);
23997
24006
  return null;
23998
24007
  } catch (err) {
23999
- const delayMs = nextRenameDelayMs(err, attempt, renameBackoffs(opts));
24008
+ const delayMs = nextRenameDelayMs(err, attempt, renameBackoffs(opts), dst);
24000
24009
  if (delayMs === null) throw err;
24001
24010
  return delayMs;
24002
24011
  }
@@ -24017,13 +24026,16 @@ async function renameWithRetry(src, dst, opts = {}) {
24017
24026
  return true;
24018
24027
  } catch (err) {
24019
24028
  lastErr = err;
24020
- const delayMs = nextRenameDelayMs(err, attempt, backoffs);
24029
+ const delayMs = nextRenameDelayMs(err, attempt, backoffs, dst);
24021
24030
  if (delayMs === null) break;
24022
24031
  await sleep(Math.max(1, Number(delayMs) || 1));
24023
24032
  }
24024
24033
  }
24025
24034
  throw lastErr;
24026
24035
  }
24036
+ function isFileFsyncUnsupported(err) {
24037
+ return FILE_FSYNC_TOLERATED.includes(err?.code);
24038
+ }
24027
24039
  function fsyncPathSync(path2, tolerated) {
24028
24040
  let fd = null;
24029
24041
  try {
@@ -24052,120 +24064,188 @@ async function fsyncPathAsync(path2, tolerated) {
24052
24064
  }
24053
24065
  }
24054
24066
  }
24067
+ function writeFileDurableSync(path2, data, opts) {
24068
+ const fd = openSync(path2, opts.flag || "wx", opts.mode !== void 0 ? opts.mode : 384);
24069
+ try {
24070
+ writeFileSync2(fd, data, { encoding: opts.encoding || "utf8" });
24071
+ if (opts.fsync !== false) {
24072
+ try {
24073
+ fsyncSync(fd);
24074
+ } catch (err) {
24075
+ if (!isFileFsyncUnsupported(err)) throw err;
24076
+ }
24077
+ }
24078
+ } finally {
24079
+ closeSync(fd);
24080
+ }
24081
+ }
24082
+ async function writeFileDurableAsync(path2, data, opts) {
24083
+ const handle = await openAsync(path2, opts.flag || "wx", opts.mode !== void 0 ? opts.mode : 384);
24084
+ try {
24085
+ await handle.writeFile(data, { encoding: opts.encoding || "utf8" });
24086
+ if (opts.fsync !== false) {
24087
+ try {
24088
+ await handle.sync();
24089
+ } catch (err) {
24090
+ if (!isFileFsyncUnsupported(err)) throw err;
24091
+ }
24092
+ }
24093
+ } finally {
24094
+ await handle.close();
24095
+ }
24096
+ }
24097
+ function holdsNoData(content) {
24098
+ if (typeof content === "string") return /^[\0\s]*$/.test(content);
24099
+ for (const byte of content) {
24100
+ if (byte !== 0 && byte !== 32 && byte !== 9 && byte !== 10 && byte !== 13) return false;
24101
+ }
24102
+ return true;
24103
+ }
24104
+ function keepBackupSync(filePath, opts) {
24105
+ let previous;
24106
+ try {
24107
+ previous = readFileSync3(filePath);
24108
+ } catch (err) {
24109
+ if (err?.code === "ENOENT") return;
24110
+ throw err;
24111
+ }
24112
+ if (keepsAsBackup(opts, previous)) publishFileSync(`${filePath}.bak`, previous, backupWriteOpts(opts));
24113
+ }
24114
+ async function keepBackupAsync(filePath, opts) {
24115
+ let previous;
24116
+ try {
24117
+ previous = await readFileAsync3(filePath);
24118
+ } catch (err) {
24119
+ if (err?.code === "ENOENT") return;
24120
+ throw err;
24121
+ }
24122
+ if (keepsAsBackup(opts, previous)) await publishFileAsync(`${filePath}.bak`, previous, backupWriteOpts(opts));
24123
+ }
24055
24124
  function assertTestSecretWriteSafe(filePath, opts) {
24056
24125
  if (opts.secret !== true || !process.env.NODE_TEST_CONTEXT) return;
24057
- const rel = relative(resolve4(tmpdir2()).toLowerCase(), resolve4(filePath).toLowerCase());
24126
+ const rel = relative(resolve3(tmpdir2()).toLowerCase(), resolve3(filePath).toLowerCase());
24058
24127
  if (rel === "" || !rel.startsWith("..") && !isAbsolute2(rel)) return;
24059
24128
  throw new Error(`refusing to write a secret outside the temp dir under node --test: ${filePath}`);
24060
24129
  }
24061
24130
  function writeFileAtomicSync(filePath, data, opts = {}) {
24062
24131
  assertTestSecretWriteSafe(filePath, opts);
24063
- const run = () => {
24064
- const dir = dirname5(filePath);
24065
- mkdirSync3(dir, { recursive: true });
24066
- const tmp = join5(dir, `.${basename3(filePath)}.${randomBytes3(12).toString("hex")}.tmp`);
24067
- try {
24068
- const writeOpts = {
24069
- encoding: opts.encoding || "utf8",
24070
- flag: "wx",
24071
- mode: opts.mode !== void 0 ? opts.mode : 384
24072
- };
24073
- writeFileSync3(tmp, data, writeOpts);
24074
- if (opts.secret === true) enforceOwnerOnlyAclWin32(tmp, { fresh: true });
24075
- if (opts.fsync !== false) fsyncPathSync(tmp, FILE_FSYNC_TOLERATED);
24076
- if (opts.createOnly === true) {
24077
- try {
24078
- linkSync2(tmp, filePath);
24079
- } catch (err) {
24080
- try {
24081
- unlinkSync3(tmp);
24082
- } catch {
24083
- }
24084
- if (err?.code === "EEXIST") return false;
24085
- throw err;
24086
- }
24132
+ const run = () => publishFileSync(filePath, data, opts);
24133
+ if (opts.lock === true) {
24134
+ return withFileLockSync(`${filePath}.lock`, run, opts);
24135
+ }
24136
+ return run();
24137
+ }
24138
+ function publishTempPath(filePath) {
24139
+ return join3(dirname3(filePath), `${basename3(filePath)}.mixdog-tmp-${randomBytes3(8).toString("hex")}`);
24140
+ }
24141
+ function publishFileSync(filePath, data, opts) {
24142
+ const dir = dirname3(filePath);
24143
+ mkdirSync2(dir, { recursive: true });
24144
+ const tmp = publishTempPath(filePath);
24145
+ try {
24146
+ writeFileDurableSync(tmp, data, { ...opts, flag: "wx" });
24147
+ if (opts.secret === true) enforceOwnerOnlyAclWin32(tmp, { fresh: true });
24148
+ if (opts.backup === true && opts.createOnly !== true) keepBackupSync(filePath, opts);
24149
+ if (opts.createOnly === true) {
24150
+ try {
24151
+ linkSync2(tmp, filePath);
24152
+ } catch (err) {
24087
24153
  try {
24088
24154
  unlinkSync3(tmp);
24089
24155
  } catch {
24090
24156
  }
24091
- } else {
24092
- try {
24093
- renameWithRetrySync(tmp, filePath, opts);
24094
- } catch (err) {
24095
- if (opts.renameFallback === "truncate" && opts.secret !== true && process.platform === "win32" && RETRY_CODES.has(err?.code)) {
24096
- const data2 = readFileSync4(tmp);
24097
- writeFileSync3(filePath, data2, { mode: opts.mode !== void 0 ? opts.mode : 384 });
24098
- try {
24099
- unlinkSync3(tmp);
24100
- } catch {
24101
- }
24102
- } else {
24103
- throw err;
24104
- }
24105
- }
24157
+ if (err?.code === "EEXIST") return false;
24158
+ throw err;
24106
24159
  }
24107
- if (opts.fsyncDir === true) fsyncPathSync(dir, DIR_FSYNC_TOLERATED);
24108
- return true;
24109
- } catch (err) {
24110
24160
  try {
24111
- if (existsSync5(tmp)) unlinkSync3(tmp);
24161
+ unlinkSync3(tmp);
24112
24162
  } catch {
24113
24163
  }
24114
- throw err;
24164
+ } else {
24165
+ try {
24166
+ renameWithRetrySync(tmp, filePath, opts);
24167
+ } catch (err) {
24168
+ if (opts.renameFallback === "truncate" && opts.secret !== true && process.platform === "win32" && RETRY_CODES.has(err?.code)) {
24169
+ writeFileDurableSync(filePath, readFileSync3(tmp), { ...opts, flag: "w", encoding: void 0 });
24170
+ try {
24171
+ unlinkSync3(tmp);
24172
+ } catch {
24173
+ }
24174
+ } else {
24175
+ throw err;
24176
+ }
24177
+ }
24115
24178
  }
24116
- };
24117
- if (opts.lock === true) {
24118
- return withFileLockSync(`${filePath}.lock`, run, opts);
24179
+ if (opts.fsyncDir === true) fsyncPathSync(dir, DIR_FSYNC_TOLERATED);
24180
+ return true;
24181
+ } catch (err) {
24182
+ try {
24183
+ if (existsSync4(tmp)) unlinkSync3(tmp);
24184
+ } catch {
24185
+ }
24186
+ throw err;
24119
24187
  }
24120
- return run();
24121
24188
  }
24122
24189
  function writeJsonAtomicSync(filePath, value, opts = {}) {
24123
24190
  return writeFileAtomicSync(filePath, `${JSON.stringify(value, null, opts.compact ? 0 : 2)}
24124
- `, opts);
24191
+ `, jsonBackupOpts(opts));
24192
+ }
24193
+ function parseJsonText(text) {
24194
+ return JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
24195
+ }
24196
+ function isJsonContent(content) {
24197
+ try {
24198
+ parseJsonText(String(content));
24199
+ return true;
24200
+ } catch {
24201
+ return false;
24202
+ }
24203
+ }
24204
+ function readContentOrNullSync(filePath) {
24205
+ try {
24206
+ return readFileSync3(filePath);
24207
+ } catch (err) {
24208
+ if (err?.code === "ENOENT") return null;
24209
+ throw err;
24210
+ }
24211
+ }
24212
+ function reportDamaged(filePath, error, outcome) {
24213
+ const reason = String(error?.message || error).replace(/[\0-\x1f]/g, (c) => `\\x${c.charCodeAt(0).toString(16)}`);
24214
+ process.stderr.write(`[state] ${filePath} is damaged (${reason}); ${outcome}
24215
+ `);
24216
+ }
24217
+ function recoverDamagedSync(filePath, parse, opts) {
24218
+ const current = parse(readContentOrNullSync(filePath));
24219
+ if (current.state !== "damaged") return current;
24220
+ const backup = opts.restoreBackup === false ? NO_BACKUP : parse(readContentOrNullSync(`${filePath}.bak`));
24221
+ if (backup.state !== "ok" && opts.keepWithoutBackup) {
24222
+ reportDamaged(filePath, current.error, KEPT_IN_PLACE);
24223
+ return { state: "absent" };
24224
+ }
24225
+ const aside = quarantinePath(filePath);
24226
+ renameWithRetrySync(filePath, aside, opts);
24227
+ if (backup.state === "ok") publishFileSync(filePath, backup.content, restoreOpts(opts));
24228
+ reportDamaged(filePath, current.error, recoveredOutcome(aside, backup));
24229
+ return backup.state === "ok" ? backup : { state: "absent" };
24230
+ }
24231
+ function readJsonStateSync(filePath, { validate: validate2, decode, fallback = null, ...opts } = {}) {
24232
+ const parse = stateParser(validate2, decode);
24233
+ const first = parse(readContentOrNullSync(filePath));
24234
+ if (first.state === "ok") return first.value;
24235
+ if (first.state !== "damaged") return fallback;
24236
+ let recovered;
24237
+ try {
24238
+ recovered = withFileLockSync(`${filePath}.lock`, () => recoverDamagedSync(filePath, parse, opts), opts);
24239
+ } catch (err) {
24240
+ if (!LOCK_BUSY_CODES.has(err?.code)) throw err;
24241
+ reportDamaged(filePath, first.error, "left in place while another writer holds its lock");
24242
+ return fallback;
24243
+ }
24244
+ return recovered.state === "ok" ? recovered.value : fallback;
24125
24245
  }
24126
24246
  async function writeFileAtomicAsync(filePath, data, opts = {}) {
24127
24247
  assertTestSecretWriteSafe(filePath, opts);
24128
- const run = async () => {
24129
- const dir = dirname5(filePath);
24130
- await mkdirAsync2(dir, { recursive: true });
24131
- const tmp = join5(dir, `.${basename3(filePath)}.${randomBytes3(12).toString("hex")}.tmp`);
24132
- try {
24133
- const writeOpts = {
24134
- encoding: opts.encoding || "utf8",
24135
- flag: "wx",
24136
- mode: opts.mode !== void 0 ? opts.mode : 384
24137
- };
24138
- await writeFileAsync2(tmp, data, writeOpts);
24139
- if (opts.secret === true) await enforceOwnerOnlyAclWin32Async(tmp, { fresh: true });
24140
- if (opts.fsync !== false) await fsyncPathAsync(tmp, FILE_FSYNC_TOLERATED);
24141
- if (opts.createOnly === true) {
24142
- try {
24143
- await linkAsync2(tmp, filePath);
24144
- } catch (err) {
24145
- try {
24146
- await unlinkAsync2(tmp);
24147
- } catch {
24148
- }
24149
- if (err?.code === "EEXIST") return false;
24150
- throw err;
24151
- }
24152
- try {
24153
- await unlinkAsync2(tmp);
24154
- } catch {
24155
- }
24156
- } else {
24157
- await renameWithRetry(tmp, filePath, opts);
24158
- }
24159
- if (opts.fsyncDir === true) await fsyncPathAsync(dir, DIR_FSYNC_TOLERATED);
24160
- return true;
24161
- } catch (err) {
24162
- try {
24163
- await unlinkAsync2(tmp);
24164
- } catch {
24165
- }
24166
- throw err;
24167
- }
24168
- };
24248
+ const run = () => publishFileAsync(filePath, data, opts);
24169
24249
  if (opts.lock !== true) return _runAdaptiveFileIo(run);
24170
24250
  const lockPath = `${filePath}.lock`;
24171
24251
  return withFileLock(
@@ -24189,11 +24269,47 @@ async function writeFileAtomicAsync(filePath, data, opts = {}) {
24189
24269
  opts
24190
24270
  );
24191
24271
  }
24272
+ async function publishFileAsync(filePath, data, opts) {
24273
+ const dir = dirname3(filePath);
24274
+ await mkdirAsync2(dir, { recursive: true });
24275
+ const tmp = publishTempPath(filePath);
24276
+ try {
24277
+ await writeFileDurableAsync(tmp, data, { ...opts, flag: "wx" });
24278
+ if (opts.secret === true) await enforceOwnerOnlyAclWin32Async(tmp, { fresh: true });
24279
+ if (opts.backup === true && opts.createOnly !== true) await keepBackupAsync(filePath, opts);
24280
+ if (opts.createOnly === true) {
24281
+ try {
24282
+ await linkAsync2(tmp, filePath);
24283
+ } catch (err) {
24284
+ try {
24285
+ await unlinkAsync2(tmp);
24286
+ } catch {
24287
+ }
24288
+ if (err?.code === "EEXIST") return false;
24289
+ throw err;
24290
+ }
24291
+ try {
24292
+ await unlinkAsync2(tmp);
24293
+ } catch {
24294
+ }
24295
+ } else {
24296
+ await renameWithRetry(tmp, filePath, opts);
24297
+ }
24298
+ if (opts.fsyncDir === true) await fsyncPathAsync(dir, DIR_FSYNC_TOLERATED);
24299
+ return true;
24300
+ } catch (err) {
24301
+ try {
24302
+ await unlinkAsync2(tmp);
24303
+ } catch {
24304
+ }
24305
+ throw err;
24306
+ }
24307
+ }
24192
24308
  function writeJsonAtomicAsync(filePath, value, opts = {}) {
24193
24309
  return writeFileAtomicAsync(filePath, `${JSON.stringify(value, null, opts.compact ? 0 : 2)}
24194
- `, opts);
24310
+ `, jsonBackupOpts(opts));
24195
24311
  }
24196
- var _ioCeiling, _ioLimit, _ioActive, _ioFastStreak, _ioQueue, RETRY_CODES, FILE_FSYNC_TOLERATED, DIR_FSYNC_TOLERATED;
24312
+ var _ioCeiling, _ioLimit, _ioActive, _ioFastStreak, _ioQueue, RETRY_CODES, FILE_FSYNC_TOLERATED, DIR_FSYNC_TOLERATED, keepsAsBackup, backupWriteOpts, jsonBackupOpts, quarantinePath, LOCK_BUSY_CODES, STATE_UNSUPPORTED, acceptAny, utf8Text, stateParser, restoreOpts, KEPT_IN_PLACE, NO_BACKUP, recoveredOutcome, parseAnyJson;
24197
24313
  var init_atomic_file = __esm({
24198
24314
  "src/runtime/shared/atomic-file.mjs"() {
24199
24315
  init_file_lock();
@@ -24207,16 +24323,68 @@ var init_atomic_file = __esm({
24207
24323
  RETRY_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY", "EEXIST"]);
24208
24324
  FILE_FSYNC_TOLERATED = ["EPERM", "ENOTSUP", "EINVAL"];
24209
24325
  DIR_FSYNC_TOLERATED = ["EPERM", "ENOTSUP", "EINVAL", "EACCES"];
24326
+ keepsAsBackup = (opts, content) => opts.backupAccepts ? opts.backupAccepts(content) : !holdsNoData(content);
24327
+ backupWriteOpts = (opts) => ({ mode: opts.mode, secret: opts.secret, fsync: opts.fsync });
24328
+ jsonBackupOpts = (opts) => opts.backup === true && !opts.backupAccepts ? { ...opts, backupAccepts: isJsonContent } : opts;
24329
+ quarantinePath = (filePath) => {
24330
+ let stamp = Date.now();
24331
+ while (existsSync4(`${filePath}.corrupt-${stamp}`)) stamp += 1;
24332
+ return `${filePath}.corrupt-${stamp}`;
24333
+ };
24334
+ LOCK_BUSY_CODES = /* @__PURE__ */ new Set(["ELOCKCONTENDED", "ELOCKTIMEOUT"]);
24335
+ STATE_UNSUPPORTED = "ESTATEUNSUPPORTED";
24336
+ acceptAny = (value) => value;
24337
+ utf8Text = (content) => content.toString("utf8");
24338
+ stateParser = (validate2 = acceptAny, decode = utf8Text) => (content) => {
24339
+ if (content === null) return { state: "absent" };
24340
+ try {
24341
+ return { state: "ok", value: validate2(parseJsonText(decode(content))), content };
24342
+ } catch (error) {
24343
+ return { state: error?.code === STATE_UNSUPPORTED ? "unsupported" : "damaged", error };
24344
+ }
24345
+ };
24346
+ restoreOpts = (opts) => ({ mode: opts.mode, secret: opts.secret });
24347
+ KEPT_IN_PLACE = "left in place: no good copy to restore";
24348
+ NO_BACKUP = { state: "absent" };
24349
+ recoveredOutcome = (aside, backup) => `kept as ${aside}${backup.state === "ok" ? "; restored the last good copy" : "; starting empty"}`;
24350
+ parseAnyJson = stateParser();
24210
24351
  }
24211
24352
  });
24212
24353
 
24213
24354
  // src/runtime/shared/json-file.mjs
24214
- import { readFileSync as readFileSync5 } from "node:fs";
24355
+ import { readFileSync as readFileSync4 } from "node:fs";
24215
24356
  var init_json_file = __esm({
24216
24357
  "src/runtime/shared/json-file.mjs"() {
24217
24358
  }
24218
24359
  });
24219
24360
 
24361
+ // src/runtime/shared/file-has-data.mjs
24362
+ import { closeSync as closeSync2, openSync as openSync2, readSync } from "node:fs";
24363
+ function fileHasData(path2) {
24364
+ let fd;
24365
+ try {
24366
+ fd = openSync2(path2, "r");
24367
+ const head = Buffer.alloc(PROBE_BYTES);
24368
+ return !holdsNoData(head.subarray(0, readSync(fd, head, 0, PROBE_BYTES, 0)));
24369
+ } catch (err) {
24370
+ return err?.code !== "ENOENT" && err?.code !== "ENOTDIR";
24371
+ } finally {
24372
+ if (fd !== void 0) {
24373
+ try {
24374
+ closeSync2(fd);
24375
+ } catch {
24376
+ }
24377
+ }
24378
+ }
24379
+ }
24380
+ var PROBE_BYTES;
24381
+ var init_file_has_data = __esm({
24382
+ "src/runtime/shared/file-has-data.mjs"() {
24383
+ init_atomic_file();
24384
+ PROBE_BYTES = 4096;
24385
+ }
24386
+ });
24387
+
24220
24388
  // src/runtime/shared/bounded-download.mjs
24221
24389
  import { createWriteStream, rmSync as rmSync2 } from "node:fs";
24222
24390
  import { Transform as Transform2 } from "node:stream";
@@ -24241,7 +24409,7 @@ function responseByteLength(response, maximum, label) {
24241
24409
  }
24242
24410
  return advertised;
24243
24411
  }
24244
- async function streamResponseToFile(response, destPath, { maxBytes, expectedBytes = 0, label = "download", onProgress = null } = {}) {
24412
+ async function streamResponseToFile(response, destPath, { maxBytes, expectedBytes = 0, label = "download", onProgress = null, signal = void 0 } = {}) {
24245
24413
  const { maximum, expected } = downloadBounds(maxBytes, expectedBytes, label);
24246
24414
  const advertised = responseByteLength(response, maximum, label);
24247
24415
  if (expected && advertised && advertised !== expected) {
@@ -24277,7 +24445,7 @@ async function streamResponseToFile(response, destPath, { maxBytes, expectedByte
24277
24445
  }
24278
24446
  });
24279
24447
  try {
24280
- await pipeline(response.body, guard, createWriteStream(destPath));
24448
+ await pipeline(response.body, guard, createWriteStream(destPath, { flush: true }), { signal });
24281
24449
  return downloaded;
24282
24450
  } catch (error) {
24283
24451
  try {
@@ -24298,13 +24466,13 @@ var init_bounded_download = __esm({
24298
24466
  // src/runtime/shared/native-asset.mjs
24299
24467
  import { createHash as createHash5 } from "node:crypto";
24300
24468
  import {
24301
- chmodSync as chmodSync2,
24469
+ chmodSync,
24302
24470
  createReadStream,
24303
- existsSync as existsSync12,
24471
+ existsSync as existsSync11,
24304
24472
  mkdirSync as mkdirSync6,
24305
- readFileSync as readFileSync13,
24306
- readdirSync as readdirSync3,
24307
- renameSync as renameSync4,
24473
+ readFileSync as readFileSync12,
24474
+ readdirSync as readdirSync4,
24475
+ renameSync as renameSync3,
24308
24476
  rmSync as rmSync3
24309
24477
  } from "node:fs";
24310
24478
  import { join as join13 } from "node:path";
@@ -24368,21 +24536,21 @@ __export(voice_runtime_fetcher_exports, {
24368
24536
  });
24369
24537
  import { createHash as createHash6 } from "node:crypto";
24370
24538
  import {
24371
- chmodSync as chmodSync3,
24372
- closeSync as closeSync2,
24539
+ chmodSync as chmodSync2,
24540
+ closeSync as closeSync3,
24373
24541
  createReadStream as createReadStream2,
24374
24542
  createWriteStream as createWriteStream2,
24375
- existsSync as existsSync13,
24543
+ existsSync as existsSync12,
24376
24544
  mkdirSync as mkdirSync7,
24377
- openSync as openSync2,
24378
- readFileSync as readFileSync14,
24379
- readdirSync as readdirSync4,
24545
+ openSync as openSync3,
24546
+ readFileSync as readFileSync13,
24547
+ readdirSync as readdirSync5,
24380
24548
  rmSync as rmSync4,
24381
- statSync as statSync5,
24382
- writeFileSync as writeFileSync5
24549
+ statSync as statSync6,
24550
+ writeFileSync as writeFileSync3
24383
24551
  } from "node:fs";
24384
24552
  import { setTimeout as sleep2 } from "node:timers/promises";
24385
- import { join as join14, dirname as dirname11 } from "node:path";
24553
+ import { join as join14, dirname as dirname10 } from "node:path";
24386
24554
  import { fileURLToPath as fileURLToPath4 } from "node:url";
24387
24555
  import { pipeline as pipeline2 } from "node:stream/promises";
24388
24556
  import { spawnSync } from "node:child_process";
@@ -24400,7 +24568,7 @@ function lockAgeMs(holderTs, waitSince) {
24400
24568
  }
24401
24569
  function _readInstallLockToken(lockPath) {
24402
24570
  try {
24403
- const raw = readFileSync14(lockPath, "utf8").trim();
24571
+ const raw = readFileSync13(lockPath, "utf8").trim();
24404
24572
  if (!raw) return null;
24405
24573
  const [pidLine, tsLine = ""] = raw.split(/\r?\n/);
24406
24574
  const pid = Number(pidLine);
@@ -24418,7 +24586,7 @@ function _installLockTokenMatches(lockPath, expectedPid, expectedTs, expectedTok
24418
24586
  }
24419
24587
  function chmodExtractedBinariesPosix(rootDir, executable) {
24420
24588
  if (process.platform === "win32") return;
24421
- const execDir = join14(rootDir, dirname11(executable));
24589
+ const execDir = join14(rootDir, dirname10(executable));
24422
24590
  const targets = /* @__PURE__ */ new Set([
24423
24591
  join14(rootDir, executable),
24424
24592
  join14(execDir, "whisper-cli"),
@@ -24426,9 +24594,9 @@ function chmodExtractedBinariesPosix(rootDir, executable) {
24426
24594
  join14(execDir, "ffmpeg")
24427
24595
  ]);
24428
24596
  for (const p of targets) {
24429
- if (existsSync13(p)) {
24597
+ if (existsSync12(p)) {
24430
24598
  try {
24431
- chmodSync3(p, 493);
24599
+ chmodSync2(p, 493);
24432
24600
  } catch {
24433
24601
  }
24434
24602
  }
@@ -24450,9 +24618,9 @@ async function _withInstallLock(rootDir, lockName, fn, { pollMs = 250 } = {}) {
24450
24618
  };
24451
24619
  while (true) {
24452
24620
  try {
24453
- fd = openSync2(lockPath, "wx");
24621
+ fd = openSync3(lockPath, "wx");
24454
24622
  try {
24455
- writeFileSync5(lockPath, `${process.pid}
24623
+ writeFileSync3(lockPath, `${process.pid}
24456
24624
  ${Date.now()}`);
24457
24625
  } catch {
24458
24626
  }
@@ -24505,7 +24673,7 @@ ${Date.now()}`);
24505
24673
  if (released) return;
24506
24674
  released = true;
24507
24675
  try {
24508
- if (fd != null) closeSync2(fd);
24676
+ if (fd != null) closeSync3(fd);
24509
24677
  } catch {
24510
24678
  }
24511
24679
  try {
@@ -24522,21 +24690,21 @@ ${Date.now()}`);
24522
24690
  }
24523
24691
  }
24524
24692
  function readBundledManifest() {
24525
- return JSON.parse(readFileSync14(BUNDLED_MANIFEST_PATH, "utf8"));
24693
+ return JSON.parse(readFileSync13(BUNDLED_MANIFEST_PATH, "utf8"));
24526
24694
  }
24527
24695
  function readActiveName(rootDir) {
24528
24696
  const activeFile = join14(rootDir, "active-version");
24529
- if (!existsSync13(activeFile)) return "";
24530
- return readFileSync14(activeFile, "utf8").trim();
24697
+ if (!existsSync12(activeFile)) return "";
24698
+ return readFileSync13(activeFile, "utf8").trim();
24531
24699
  }
24532
24700
  async function loadManifest(dataDir2) {
24533
- if (existsSync13(BUNDLED_MANIFEST_PATH)) {
24701
+ if (existsSync12(BUNDLED_MANIFEST_PATH)) {
24534
24702
  return readBundledManifest();
24535
24703
  }
24536
24704
  const cachedPath = join14(dataDir2, "voice-runtime", "manifest.json");
24537
- if (existsSync13(cachedPath)) {
24705
+ if (existsSync12(cachedPath)) {
24538
24706
  try {
24539
- return JSON.parse(readFileSync14(cachedPath, "utf8"));
24707
+ return JSON.parse(readFileSync13(cachedPath, "utf8"));
24540
24708
  } catch {
24541
24709
  }
24542
24710
  }
@@ -24544,7 +24712,7 @@ async function loadManifest(dataDir2) {
24544
24712
  if (!res.ok) throw new Error(`[voice-runtime] manifest fetch failed: ${res.status} ${res.statusText}`);
24545
24713
  const manifest = await res.json();
24546
24714
  mkdirSync7(join14(dataDir2, "voice-runtime"), { recursive: true });
24547
- writeFileSync5(cachedPath, JSON.stringify(manifest, null, 2));
24715
+ writeJsonAtomicSync(cachedPath, manifest);
24548
24716
  return manifest;
24549
24717
  }
24550
24718
  function verifySha256(filePath, expected) {
@@ -24560,18 +24728,18 @@ function detectCudaMajorsWin32() {
24560
24728
  }
24561
24729
  for (const root of windowsProgramRoots()) {
24562
24730
  const standardRoot = join14(root, "NVIDIA GPU Computing Toolkit", "CUDA");
24563
- if (!existsSync13(standardRoot)) continue;
24731
+ if (!existsSync12(standardRoot)) continue;
24564
24732
  try {
24565
- for (const e of readdirSync4(standardRoot)) {
24733
+ for (const e of readdirSync5(standardRoot)) {
24566
24734
  if (/^v\d+\.\d+/.test(e)) dirs.push(join14(standardRoot, e, "bin"));
24567
24735
  }
24568
24736
  } catch {
24569
24737
  }
24570
24738
  }
24571
24739
  for (const d of dirs) {
24572
- if (!existsSync13(d)) continue;
24740
+ if (!existsSync12(d)) continue;
24573
24741
  try {
24574
- for (const f of readdirSync4(d)) {
24742
+ for (const f of readdirSync5(d)) {
24575
24743
  const m = /^cublas64_(\d+)\.dll$/i.exec(f);
24576
24744
  if (m) found.add(Number(m[1]));
24577
24745
  }
@@ -24591,9 +24759,9 @@ function detectCudaMajorsLinux() {
24591
24759
  const cudaPath = process.env.CUDA_PATH;
24592
24760
  if (cudaPath) dirs.push(`${cudaPath}/lib64`);
24593
24761
  for (const d of dirs) {
24594
- if (!existsSync13(d)) continue;
24762
+ if (!existsSync12(d)) continue;
24595
24763
  try {
24596
- for (const f of readdirSync4(d)) {
24764
+ for (const f of readdirSync5(d)) {
24597
24765
  const m = /^libcublas\.so\.(\d+)$/.exec(f);
24598
24766
  if (m) found.add(Number(m[1]));
24599
24767
  }
@@ -24614,7 +24782,7 @@ function hasNvidiaDriver() {
24614
24782
  const sys = windowsSystemRoot();
24615
24783
  if (!sys) return false;
24616
24784
  for (const f of ["System32\\nvidia-smi.exe", "System32\\nvml.dll"]) {
24617
- if (existsSync13(join14(sys, f))) return true;
24785
+ if (existsSync12(join14(sys, f))) return true;
24618
24786
  }
24619
24787
  return false;
24620
24788
  }
@@ -24652,10 +24820,10 @@ async function processExtras(extras, stagingDir, onProgress) {
24652
24820
  for (const f of extra.files) {
24653
24821
  const src = join14(extractDir, f.from);
24654
24822
  const dst = join14(stagingDir, f.to);
24655
- if (!existsSync13(src)) {
24823
+ if (!existsSync12(src)) {
24656
24824
  throw new Error(`[voice-runtime] extra ${tag}: expected file ${f.from} not present after extract`);
24657
24825
  }
24658
- mkdirSync7(dirname11(dst), { recursive: true });
24826
+ mkdirSync7(dirname10(dst), { recursive: true });
24659
24827
  renameWithRetrySync(src, dst);
24660
24828
  }
24661
24829
  try {
@@ -24669,8 +24837,8 @@ async function processExtras(extras, stagingDir, onProgress) {
24669
24837
  }
24670
24838
  }
24671
24839
  function gcStaleVersions(rootDir, activeName, prefix) {
24672
- if (!existsSync13(rootDir)) return;
24673
- for (const entry of readdirSync4(rootDir)) {
24840
+ if (!existsSync12(rootDir)) return;
24841
+ for (const entry of readdirSync5(rootDir)) {
24674
24842
  if (entry === activeName || entry === "active-version" || entry === "manifest.json") continue;
24675
24843
  if (!entry.startsWith(prefix) && !entry.startsWith("staging-")) continue;
24676
24844
  try {
@@ -24682,18 +24850,18 @@ function gcStaleVersions(rootDir, activeName, prefix) {
24682
24850
  function gcPublishedRuntimeSiblings(rootDir, prefix) {
24683
24851
  try {
24684
24852
  const activeName = readActiveName(rootDir);
24685
- if (!activeName.startsWith(prefix) || !existsSync13(join14(rootDir, activeName))) return;
24853
+ if (!activeName.startsWith(prefix) || !existsSync12(join14(rootDir, activeName))) return;
24686
24854
  gcStaleVersions(rootDir, activeName, prefix);
24687
24855
  } catch {
24688
24856
  }
24689
24857
  }
24690
24858
  async function extractGz(gzPath, destPath) {
24691
- await pipeline2(createReadStream2(gzPath), createGunzip(), createWriteStream2(destPath));
24859
+ await pipeline2(createReadStream2(gzPath), createGunzip(), createWriteStream2(destPath, { flush: true }));
24692
24860
  }
24693
24861
  function gcStagingPartials(dir) {
24694
- if (!existsSync13(dir)) return;
24862
+ if (!existsSync12(dir)) return;
24695
24863
  try {
24696
- for (const entry of readdirSync4(dir)) {
24864
+ for (const entry of readdirSync5(dir)) {
24697
24865
  if (!entry.startsWith(".staging-")) continue;
24698
24866
  try {
24699
24867
  rmSync4(join14(dir, entry), { force: true });
@@ -24771,12 +24939,12 @@ async function ensureWhisperRuntime(dataDir2, onProgress = null) {
24771
24939
  const activeName = `whisper-${ver}-${variant.id}`;
24772
24940
  const activeDir = join14(rootDir, activeName);
24773
24941
  const whisperCmd = join14(activeDir, variant.executable);
24774
- if (existsSync13(whisperCmd)) {
24942
+ if (fileHasData(whisperCmd)) {
24775
24943
  gcStaleVersions(rootDir, activeName, "whisper-");
24776
24944
  return { whisperCmd, version: ver, variantId: variant.id };
24777
24945
  }
24778
24946
  return _withInstallLock(rootDir, "install", async () => {
24779
- if (existsSync13(whisperCmd)) {
24947
+ if (fileHasData(whisperCmd)) {
24780
24948
  gcStaleVersions(rootDir, activeName, "whisper-");
24781
24949
  return { whisperCmd, version: ver, variantId: variant.id };
24782
24950
  }
@@ -24800,7 +24968,7 @@ async function ensureWhisperRuntime(dataDir2, onProgress = null) {
24800
24968
  rmSync4(archivePath, { force: true });
24801
24969
  chmodExtractedBinariesPosix(stagingDir, variant.executable);
24802
24970
  const stagedExec = join14(stagingDir, variant.executable);
24803
- if (!existsSync13(stagedExec)) {
24971
+ if (!existsSync12(stagedExec)) {
24804
24972
  throw new Error(`[voice-runtime] expected executable ${variant.executable} not present after extract`);
24805
24973
  }
24806
24974
  await processExtras(variant.extras, stagingDir, onProgress);
@@ -24822,7 +24990,7 @@ async function ensureWhisperRuntime(dataDir2, onProgress = null) {
24822
24990
  function isManagedWhisperStale(dataDir2) {
24823
24991
  const activeName = readActiveName(join14(dataDir2, "voice-runtime"));
24824
24992
  if (!activeName) return false;
24825
- if (!existsSync13(BUNDLED_MANIFEST_PATH)) return false;
24993
+ if (!existsSync12(BUNDLED_MANIFEST_PATH)) return false;
24826
24994
  try {
24827
24995
  const manifest = readBundledManifest();
24828
24996
  if (!manifest?.version) return false;
@@ -24835,7 +25003,7 @@ function resolveManagedWhisperCmd(dataDir2) {
24835
25003
  const activeName = readActiveName(join14(dataDir2, "voice-runtime"));
24836
25004
  if (!activeName) return null;
24837
25005
  const activeDir = join14(dataDir2, "voice-runtime", activeName);
24838
- if (existsSync13(BUNDLED_MANIFEST_PATH)) {
25006
+ if (existsSync12(BUNDLED_MANIFEST_PATH)) {
24839
25007
  try {
24840
25008
  const manifest = readBundledManifest();
24841
25009
  const key = platformEntryKey(manifest.platforms);
@@ -24846,7 +25014,7 @@ function resolveManagedWhisperCmd(dataDir2) {
24846
25014
  const variant = variants.find((v) => v.id === variantId);
24847
25015
  if (variant?.executable) {
24848
25016
  const p = join14(activeDir, variant.executable);
24849
- if (existsSync13(p)) return p;
25017
+ if (fileHasData(p)) return p;
24850
25018
  }
24851
25019
  }
24852
25020
  } catch {
@@ -24854,17 +25022,17 @@ function resolveManagedWhisperCmd(dataDir2) {
24854
25022
  }
24855
25023
  for (const c of ["Release/whisper-cli.exe", "Release/whisper-cli"]) {
24856
25024
  const p = join14(activeDir, c);
24857
- if (existsSync13(p)) return p;
25025
+ if (fileHasData(p)) return p;
24858
25026
  }
24859
25027
  return null;
24860
25028
  }
24861
25029
  function resolveManagedWhisperModelById(dataDir2, modelId = "standard") {
24862
- if (!existsSync13(BUNDLED_MANIFEST_PATH)) return null;
25030
+ if (!existsSync12(BUNDLED_MANIFEST_PATH)) return null;
24863
25031
  const entry = manifestModelEntry(readBundledManifest(), modelId);
24864
25032
  if (!entry?.filename) return null;
24865
25033
  const modelDir = join14(dataDir2, "voice", "models");
24866
25034
  const p = join14(modelDir, entry.filename);
24867
- return existsSync13(p) ? p : null;
25035
+ return fileHasData(p) ? p : null;
24868
25036
  }
24869
25037
  function gcUnknownModelFiles(manifest, modelDir) {
24870
25038
  const keep = /* @__PURE__ */ new Set();
@@ -24874,7 +25042,7 @@ function gcUnknownModelFiles(manifest, modelDir) {
24874
25042
  if (keep.size === 0) return;
24875
25043
  let names = [];
24876
25044
  try {
24877
- names = readdirSync4(modelDir);
25045
+ names = readdirSync5(modelDir);
24878
25046
  } catch {
24879
25047
  return;
24880
25048
  }
@@ -24903,12 +25071,12 @@ async function ensureFfmpegRuntime(dataDir2, onProgress = null) {
24903
25071
  const activeName = `ffmpeg-${ver}`;
24904
25072
  const activeDir = join14(rootDir, activeName);
24905
25073
  const ffmpegPath = join14(activeDir, platformEntry.executable);
24906
- if (existsSync13(ffmpegPath)) {
25074
+ if (fileHasData(ffmpegPath)) {
24907
25075
  gcStaleVersions(rootDir, activeName, "ffmpeg-");
24908
25076
  return { ffmpegPath, version: ver };
24909
25077
  }
24910
25078
  return _withInstallLock(rootDir, "install", async () => {
24911
- if (existsSync13(ffmpegPath)) {
25079
+ if (fileHasData(ffmpegPath)) {
24912
25080
  gcStaleVersions(rootDir, activeName, "ffmpeg-");
24913
25081
  return { ffmpegPath, version: ver };
24914
25082
  }
@@ -24937,13 +25105,13 @@ async function ensureFfmpegRuntime(dataDir2, onProgress = null) {
24937
25105
  throw new Error(`[voice-runtime] ffmpeg manifest format must be "gz" or "zip", got "${platformEntry.format}"`);
24938
25106
  }
24939
25107
  rmSync4(archivePath, { force: true });
24940
- if (!existsSync13(stagedExec)) {
25108
+ if (!existsSync12(stagedExec)) {
24941
25109
  throw new Error(
24942
25110
  `[voice-runtime] expected ffmpeg executable ${platformEntry.executable} not present after extract`
24943
25111
  );
24944
25112
  }
24945
25113
  if (process.platform !== "win32") {
24946
- chmodSync3(stagedExec, 493);
25114
+ chmodSync2(stagedExec, 493);
24947
25115
  }
24948
25116
  renameWithRetrySync(stagingDir, activeDir);
24949
25117
  writeFileAtomicSync(join14(rootDir, "active-version"), activeName, { fsyncDir: true });
@@ -24964,21 +25132,21 @@ function resolveManagedFfmpegPath(dataDir2) {
24964
25132
  const activeName = readActiveName(join14(dataDir2, "ffmpeg-runtime"));
24965
25133
  if (!activeName) return null;
24966
25134
  const activeDir = join14(dataDir2, "ffmpeg-runtime", activeName);
24967
- if (existsSync13(BUNDLED_MANIFEST_PATH)) {
25135
+ if (existsSync12(BUNDLED_MANIFEST_PATH)) {
24968
25136
  try {
24969
25137
  const manifest = readBundledManifest();
24970
25138
  const key = platformEntryKey(manifest.ffmpeg?.platforms);
24971
25139
  const platformEntry = manifest.ffmpeg?.platforms?.[key];
24972
25140
  if (platformEntry?.executable) {
24973
25141
  const p = join14(activeDir, platformEntry.executable);
24974
- if (existsSync13(p)) return p;
25142
+ if (fileHasData(p)) return p;
24975
25143
  }
24976
25144
  } catch {
24977
25145
  }
24978
25146
  }
24979
25147
  for (const c of ["ffmpeg.exe", "ffmpeg"]) {
24980
25148
  const p = join14(activeDir, c);
24981
- if (existsSync13(p)) return p;
25149
+ if (fileHasData(p)) return p;
24982
25150
  }
24983
25151
  return null;
24984
25152
  }
@@ -24993,7 +25161,7 @@ function voiceRuntimeInfo(runtime) {
24993
25161
  let modelBytes = model?.size || 0;
24994
25162
  if (runtime.modelPath) {
24995
25163
  try {
24996
- modelBytes = statSync5(runtime.modelPath).size;
25164
+ modelBytes = statSync6(runtime.modelPath).size;
24997
25165
  } catch {
24998
25166
  modelBytes = 0;
24999
25167
  }
@@ -25016,8 +25184,8 @@ function resolveVoiceRuntime(dataDir2, { modelId = "standard", cleanup = true }
25016
25184
  const managedModelPath = resolveManagedWhisperModelById(dataDir2, modelId);
25017
25185
  const managedFfmpegPath = resolveManagedFfmpegPath(dataDir2);
25018
25186
  const ext = process.platform === "win32" ? ".exe" : "";
25019
- const managedServerCmd = managedWhisperCmd ? join14(dirname11(managedWhisperCmd), `whisper-server${ext}`) : null;
25020
- const serverCmd = managedServerCmd && existsSync13(managedServerCmd) ? managedServerCmd : null;
25187
+ const managedServerCmd = managedWhisperCmd ? join14(dirname10(managedWhisperCmd), `whisper-server${ext}`) : null;
25188
+ const serverCmd = managedServerCmd && fileHasData(managedServerCmd) ? managedServerCmd : null;
25021
25189
  return {
25022
25190
  kind: "managed-whisper.cpp",
25023
25191
  label: "whisper.cpp",
@@ -25044,7 +25212,7 @@ async function ensureWhisperModel(dataDir2, onProgress = null, modelId = "standa
25044
25212
  }
25045
25213
  const modelDir = join14(dataDir2, "voice", "models");
25046
25214
  const modelPath = join14(modelDir, model.filename);
25047
- if (existsSync13(modelPath)) {
25215
+ if (existsSync12(modelPath)) {
25048
25216
  const actual = await sha256File(modelPath);
25049
25217
  if (actual === model.sha256) {
25050
25218
  return { modelPath, modelId: model.id, size: model.size };
@@ -25059,7 +25227,7 @@ async function ensureWhisperModel(dataDir2, onProgress = null, modelId = "standa
25059
25227
  }
25060
25228
  }
25061
25229
  return _withInstallLock(modelDir, "install", async () => {
25062
- if (existsSync13(modelPath)) {
25230
+ if (existsSync12(modelPath)) {
25063
25231
  const actual = await sha256File(modelPath);
25064
25232
  if (actual === model.sha256) {
25065
25233
  gcUnknownModelFiles(manifest, modelDir);
@@ -25101,6 +25269,7 @@ var BUNDLED_MANIFEST_PATH, MANIFEST_URL, LOCK_WAIT_CODES2, LOCK_MAX_AGE_MS, Voic
25101
25269
  var init_voice_runtime_fetcher = __esm({
25102
25270
  "src/runtime/channels/lib/voice-runtime-fetcher.mjs"() {
25103
25271
  init_atomic_file();
25272
+ init_file_has_data();
25104
25273
  init_bounded_download();
25105
25274
  init_native_asset();
25106
25275
  init_windows_roots();
@@ -35336,9 +35505,9 @@ import { useState as useState4, useEffect as useEffect5 } from "react";
35336
35505
  import { useState as useState5, useEffect as useEffect6, useCallback as useCallback4, useMemo as useMemo4 } from "react";
35337
35506
 
35338
35507
  // src/tui/index.jsx
35339
- import { closeSync as closeSync3, constants as fsConstants, createWriteStream as createWriteStream3, mkdirSync as mkdirSync8, openSync as openSync3, readSync } from "node:fs";
35508
+ import { closeSync as closeSync4, constants as fsConstants, createWriteStream as createWriteStream3, mkdirSync as mkdirSync8, openSync as openSync4, readSync as readSync2 } from "node:fs";
35340
35509
  import { tmpdir as tmpdir4 } from "node:os";
35341
- import { dirname as dirname12, join as join17 } from "node:path";
35510
+ import { dirname as dirname11, join as join17 } from "node:path";
35342
35511
  import { performance as performance2 } from "node:perf_hooks";
35343
35512
  import { format } from "node:util";
35344
35513
 
@@ -35664,7 +35833,7 @@ var SLASH_COMMANDS = [
35664
35833
  {
35665
35834
  name: "autoclear",
35666
35835
  usage: "/autoclear",
35667
- params: "[on|off|duration]",
35836
+ params: "[on|off|duration|unlimited]",
35668
35837
  description: "Reduce cache-miss cost after long idle gaps"
35669
35838
  },
35670
35839
  { name: "resume", usage: "/resume", params: "[id]", description: "Resume a saved chat" },
@@ -41995,7 +42164,8 @@ function pathOrId(path2, id, max) {
41995
42164
  }
41996
42165
 
41997
42166
  // src/tui/transcript-tool-failures.mjs
41998
- var HOOK_DENIAL_RE = /^Error:\s*tool\s*"[^"]*"\s*denied by hook\b/im;
42167
+ var HOOK_DENIAL_RE = /^Error:\s*tool\s*"[^"]*"\s*(?:denied by hook|was not approved)\b/im;
42168
+ var NOT_APPROVED_INSTRUCTION_RE = /\s*Do not retry it or reach the same result another way; report it\.\s*$/;
41999
42169
  var APPROVAL_UNAVAILABLE_RE = /denied by hook:\s*approval required but no approval UI is available/i;
42000
42170
  function toolItemResultText(item) {
42001
42171
  if (!item) return "";
@@ -42019,7 +42189,7 @@ function isHookApprovalDenialToolItem(item) {
42019
42189
  function formatHookDenialDetail(text) {
42020
42190
  const raw = String(text ?? "").trim();
42021
42191
  if (!raw) return "";
42022
- const stripped = raw.replace(/^Error:\s*tool\s*"[^"]*"\s*/i, "").trim();
42192
+ const stripped = raw.replace(/^Error:\s*tool\s*"[^"]*"\s*/i, "").replace(NOT_APPROVED_INSTRUCTION_RE, "").trim();
42023
42193
  return stripped || raw;
42024
42194
  }
42025
42195
  function isFullyFailedToolBatch(item) {
@@ -42465,8 +42635,19 @@ var CODE_KINDS = new Map(
42465
42635
  quota_exhausted: ["quota_exceeded", "quota_exhausted", "usage_limit_reached", "provider_accounts_exhausted"],
42466
42636
  context_overflow: ["context_length_exceeded", "context_window_exceeded", "model_context_window_exceeded"],
42467
42637
  request_too_large: ["request_too_large", "payload_too_large", "request_entity_too_large"],
42468
- auth: ["invalid_api_key", "authentication_error", "unauthenticated", "unauthorized", "invalid_authentication"],
42469
- permission: ["permission_error", "permission_denied", "forbidden"],
42638
+ // Google names a rejected or expired key with an ErrorInfo reason on an
42639
+ // INVALID_ARGUMENT 400; the reason outranks the envelope status.
42640
+ auth: [
42641
+ "invalid_api_key",
42642
+ "authentication_error",
42643
+ "unauthenticated",
42644
+ "unauthorized",
42645
+ "invalid_authentication",
42646
+ "api_key_invalid",
42647
+ "api_key_expired",
42648
+ "access_token_expired"
42649
+ ],
42650
+ permission: ["permission_error", "permission_denied", "forbidden", "service_disabled", "api_key_service_blocked"],
42470
42651
  overloaded: [
42471
42652
  "server_is_overloaded",
42472
42653
  "overloaded_error",
@@ -42504,6 +42685,7 @@ var CODE_KINDS = new Map(
42504
42685
  "not_found",
42505
42686
  "not_found_error",
42506
42687
  "model_not_found",
42688
+ "model_not_supported",
42507
42689
  "unsupported_parameter"
42508
42690
  ]
42509
42691
  }).flatMap(([kind, codes]) => codes.map((code) => [code, kind]))
@@ -42747,6 +42929,7 @@ var DETERMINISTIC_KINDS = /* @__PURE__ */ new Set([
42747
42929
  // src/runtime/shared/error-presentation.mjs
42748
42930
  var DETAILS_LIMIT = 12e3;
42749
42931
  var SUMMARY_LIMIT = 180;
42932
+ var LATEST_TURN_RE = /The latest message cannot fit this model \(LATEST_TURN_EXCEEDS_CONTEXT\)(: it needs about [\d,]+ tokens, but the [^.]* window leaves [\d,]+ for it\.)([\s\S]*)$/;
42750
42933
  function safeErrorDetails(value) {
42751
42934
  let text = String(value ?? "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/\r\n?/g, "\n").replace(/\b((?:https?|ssh):\/\/)[^/\s@]+@/gi, "$1[redacted]@").replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/gi, "$1 [redacted]").replace(/([?&](?:token|access_token|refresh_token|api_key|key|code|signature|sig)=)[^&\s"'<>]+/gi, "$1[redacted]").replace(
42752
42935
  /(["']?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|authorization|cookie|password|secret|client_secret)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi,
@@ -42854,6 +43037,42 @@ function resetLabel(resetAt) {
42854
43037
  const time = `${pad(reset.getHours())}:${pad(reset.getMinutes())}`;
42855
43038
  return reset.toDateString() === (/* @__PURE__ */ new Date()).toDateString() ? time : `${reset.getMonth() + 1}/${reset.getDate()} ${time}`;
42856
43039
  }
43040
+ var MODEL_REFUSAL_KINDS = /* @__PURE__ */ new Set(["invalid_request", "permission", "unknown"]);
43041
+ var MODEL_UNAVAILABLE_CODES = /* @__PURE__ */ new Set(["model_not_found", "model_not_supported"]);
43042
+ var MODEL_REFUSAL_PREDICATE = "(?:(?:is|was|has been)\\s+)?(?:not found|does not exist|doesn'?t exist|not (?:supported|available)|(?:currently\\s+)?unavailable|no longer (?:available|supported)|deprecated|retired|removed)\\b";
43043
+ var SENTENCE_START = "(?:^|[.:;!]\\s+)";
43044
+ var MODEL_UNAVAILABLE_RE = new RegExp(
43045
+ [
43046
+ // "The model `x` does not exist", "models/x is not found", Vertex
43047
+ // "Publisher Model `…` was not found", Ollama `model "x" not found`.
43048
+ `${SENTENCE_START}(?:(?:the|this|that|requested|selected|publisher)\\s+)*models?(?:\\/\\S+|\\s+[\`'"]?[\\w./:@-]+[\`'"]?)?\\s+${MODEL_REFUSAL_PREDICATE}`,
43049
+ // OpenAI "The 'gpt-x' model is not supported when using Codex …".
43050
+ `${SENTENCE_START}(?:the\\s+)?[\`'"][^\`'"\\n]+[\`'"]\\s+model\\s+${MODEL_REFUSAL_PREDICATE}`,
43051
+ `${SENTENCE_START}(?:unknown|invalid|unsupported) model\\b`,
43052
+ // OpenRouter: no provider serves this model id.
43053
+ `${SENTENCE_START}no endpoints found for [\\w.-]+\\/[\\w.:-]+`,
43054
+ "\\bis not a valid model\\b",
43055
+ "^model: \\S+$"
43056
+ ].join("|"),
43057
+ "im"
43058
+ );
43059
+ var MODEL_UNAVAILABLE_COPY = [
43060
+ "model-unavailable",
43061
+ "This model isn't available for this account.",
43062
+ "Choose another model, or check the model and endpoint in Providers."
43063
+ ];
43064
+ var NOT_FOUND_SUMMARY = "The provider couldn't find the requested model or endpoint.";
43065
+ var TOOL_SCHEMA_RE = /invalid schema for (?:function|tool)\b|\btools\.\d+\.(?:custom\.)?input_schema\b|\bfunction_declarations\[\d+\]\.parameters\b|\btools\[\d+\]\.function\.parameters\b|\binvalid (?:tool|function) (?:schema|parameters|definition)\b/i;
43066
+ var TOOL_SCHEMA_COPY = [
43067
+ "tool-schema",
43068
+ "The provider rejected a tool definition.",
43069
+ "Disable the tool or MCP server named in the details, then try again."
43070
+ ];
43071
+ function firstReadableLine(clean3) {
43072
+ const lines = clean3.split("\n").map((line) => line.trim()).filter(Boolean);
43073
+ const first = lines.find((line) => !/^at\s|^\{|^<!doctype|^<html/i.test(line)) || "";
43074
+ return first && !/^[{[]|^<|(?:API|HTTP)\s+[45]\d\d.*[<{]/i.test(first) ? first : "";
43075
+ }
42857
43076
  var LEGACY_TEXT_KINDS = [
42858
43077
  [/The provider usage limit was reached|quota.*(?:hit|exceed)|usage limit/i, "quota_exhausted"],
42859
43078
  [/rate[_ -]?limit|too many requests/i, "rate_limited"]
@@ -42903,11 +43122,15 @@ function describeError(value) {
42903
43122
  let recoveryTemplate = "";
42904
43123
  let params = null;
42905
43124
  const transport = transportErrorText(value) || typed && transportErrorText({ code: code.toUpperCase(), status }) || (!typed || descriptor.kind === "transient" ? transportErrorText(raw) : null);
42906
- if (value?.reauthRequired === true || !typed && /invalid_grant|refresh token (?:expired|revoked|not available)|sign in again|sign-in expired|Reauth Required/i.test(raw)) {
43125
+ if (value?.reauthRequired === true || !typed && /invalid_grant|refresh token (?:expired|revoked|not available)|sign in again|sign-in expired|Reauth Required/i.test(
43126
+ raw
43127
+ )) {
42907
43128
  kind = "reauth";
42908
43129
  summary = "Sign-in expired.";
42909
43130
  recovery = "Sign in again from Providers.";
42910
- } else if (descriptor.kind === "auth" || descriptor.kind === "unknown" && /\b(?:invalid|expired)\s+(?:api[ _-]?key|access token|credentials?)\b|Provider authentication failed/i.test(clean3)) {
43131
+ } else if (descriptor.kind === "auth" || descriptor.kind === "unknown" && /\b(?:invalid|expired)\s+(?:api[ _-]?key|access token|credentials?)\b|Provider authentication failed/i.test(
43132
+ clean3
43133
+ )) {
42911
43134
  kind = "authentication";
42912
43135
  summary = "Provider authentication failed";
42913
43136
  recovery = "Check your sign-in or API key, then try again.";
@@ -42921,6 +43144,19 @@ function describeError(value) {
42921
43144
  kind = "image-size";
42922
43145
  summary = "An attached image exceeds the provider limit.";
42923
43146
  recovery = "Reduce the image dimensions or number of images, then try again.";
43147
+ } else if (clean3 === MODEL_UNAVAILABLE_COPY[1] || MODEL_REFUSAL_KINDS.has(descriptor.kind) && (MODEL_UNAVAILABLE_CODES.has(code) || MODEL_UNAVAILABLE_RE.test(clean3))) {
43148
+ [kind, summary, recovery] = MODEL_UNAVAILABLE_COPY;
43149
+ } else if (clean3 === TOOL_SCHEMA_COPY[1] || ["invalid_request", "unknown"].includes(descriptor.kind) && TOOL_SCHEMA_RE.test(clean3)) {
43150
+ [kind, summary, recovery] = TOOL_SCHEMA_COPY;
43151
+ } else if (clean3 === NOT_FOUND_SUMMARY || MODEL_REFUSAL_KINDS.has(descriptor.kind) && (status === 404 || status === 410)) {
43152
+ kind = "not-found";
43153
+ summary = firstReadableLine(clean3) || NOT_FOUND_SUMMARY;
43154
+ recovery = MODEL_UNAVAILABLE_COPY[2];
43155
+ } else if (LATEST_TURN_RE.test(clean3)) {
43156
+ const [, headline, rest] = LATEST_TURN_RE.exec(clean3);
43157
+ kind = "latest-turn-size";
43158
+ summary = `The latest message cannot fit this model${headline}`;
43159
+ recovery = rest.trim();
42924
43160
  } else if (descriptor.kind === "unknown" && /payload too large|request (?:body )?too large|The request exceeds the size limit/i.test(clean3)) {
42925
43161
  [kind, summary, recovery] = KIND_COPY.request_too_large;
42926
43162
  } else if (copy) {
@@ -42943,12 +43179,11 @@ function describeError(value) {
42943
43179
  summary = "The provider rejected this request.";
42944
43180
  recovery = "Review the request details before trying again.";
42945
43181
  } else {
42946
- const lines = clean3.split("\n").map((line) => line.trim()).filter(Boolean);
42947
- const first = lines.find((line) => !/^at\s|^\{|^<!doctype|^<html/i.test(line)) || "";
42948
- summary = first && !/^[{[]|^<|(?:API|HTTP)\s+[45]\d\d.*[<{]/i.test(first) ? first : "Something went wrong.";
43182
+ summary = firstReadableLine(clean3) || "Something went wrong.";
42949
43183
  }
42950
43184
  summary = summary.replace(/\s+/g, " ").trim() || "Something went wrong.";
42951
43185
  if (summary.length > SUMMARY_LIMIT) summary = `${summary.slice(0, SUMMARY_LIMIT - 1).trimEnd()}\u2026`;
43186
+ const fingerprintStatus = kind === "reauth" ? "" : status || "";
42952
43187
  return {
42953
43188
  kind,
42954
43189
  summary,
@@ -42961,7 +43196,7 @@ function describeError(value) {
42961
43196
  details,
42962
43197
  // Known structured failures ignore volatile indexes; unknown failures
42963
43198
  // retain their diagnostic identity rather than merging unrelated work.
42964
- fingerprint: kind === "unknown" ? details : `${kind}:${kind === "reauth" ? "" : status || ""}`
43199
+ fingerprint: kind === "unknown" ? details : `${kind}:${fingerprintStatus}`
42965
43200
  };
42966
43201
  }
42967
43202
 
@@ -43157,7 +43392,9 @@ function typedStreamFailureText(error, text) {
43157
43392
  }
43158
43393
  function presentErrorText(error, options = {}) {
43159
43394
  const presentation = describeError(error);
43160
- if (["image-size", "payload-size", "request"].includes(presentation.kind)) return presentation.summary;
43395
+ if (["image-size", "payload-size", "request", "model-unavailable", "tool-schema"].includes(presentation.kind)) {
43396
+ return presentation.summary;
43397
+ }
43161
43398
  const kindLine = hasTypedEvidence(error) ? KIND_LINES[presentation.providerKind] : null;
43162
43399
  if (kindLine && presentation.kind !== "unknown") {
43163
43400
  return typeof kindLine === "function" ? kindLine(presentation) : kindLine;
@@ -43172,6 +43409,8 @@ function presentErrorText(error, options = {}) {
43172
43409
  if (code === "TOOL_SURFACE_EXCEEDS_CONTEXT" || /\(TOOL_SURFACE_EXCEEDS_CONTEXT\)/.test(text)) {
43173
43410
  return stripErrorPrefix(text);
43174
43411
  }
43412
+ const latestTurn = /The latest message cannot fit this model \(LATEST_TURN_EXCEEDS_CONTEXT\)[\s\S]*$/.exec(text);
43413
+ if (latestTurn) return latestTurn[0].replace(" (LATEST_TURN_EXCEEDS_CONTEXT)", "");
43175
43414
  const jsonError = extractJsonError(text);
43176
43415
  if (jsonError) text = jsonError;
43177
43416
  const embeddedError = extractEmbeddedError(text);
@@ -47888,15 +48127,16 @@ function projectNameFromPath(value) {
47888
48127
  }
47889
48128
 
47890
48129
  // src/tui/prompt-history-store.mjs
48130
+ init_atomic_file();
47891
48131
  import { createHash as createHash2 } from "node:crypto";
47892
- import { chmodSync, existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
47893
- import { chmod, mkdir, rename, writeFile } from "node:fs/promises";
47894
- import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
48132
+ import { mkdirSync as mkdirSync3 } from "node:fs";
48133
+ import { mkdir } from "node:fs/promises";
48134
+ import { dirname as dirname5, join as join5, resolve as resolve4 } from "node:path";
47895
48135
 
47896
48136
  // src/runtime/shared/plugin-paths.mjs
47897
48137
  import { homedir } from "node:os";
47898
- import { dirname, join } from "node:path";
47899
- import { fileURLToPath } from "node:url";
48138
+ import { dirname as dirname4, join as join4 } from "node:path";
48139
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
47900
48140
  var homeBase = null;
47901
48141
  var homePath = null;
47902
48142
  var dataBase = null;
@@ -47907,7 +48147,7 @@ function mixdogHome() {
47907
48147
  const home = homedir();
47908
48148
  if (home !== homeBase) {
47909
48149
  homeBase = home;
47910
- homePath = join(home, ".mixdog");
48150
+ homePath = join4(home, ".mixdog");
47911
48151
  }
47912
48152
  return homePath;
47913
48153
  }
@@ -47917,7 +48157,7 @@ function resolvePluginData() {
47917
48157
  const home = mixdogHome();
47918
48158
  if (home !== dataBase) {
47919
48159
  dataBase = home;
47920
- dataPath = join(home, "data");
48160
+ dataPath = join4(home, "data");
47921
48161
  }
47922
48162
  return dataPath;
47923
48163
  }
@@ -47929,10 +48169,16 @@ function promptHistoryKey(value) {
47929
48169
  return String(value || "").trim().replace(/\s+/g, " ");
47930
48170
  }
47931
48171
  function readEntries(filePath) {
47932
- if (!filePath || !existsSync3(filePath)) return [];
48172
+ if (!filePath) return [];
47933
48173
  try {
47934
- const parsed = JSON.parse(readFileSync2(filePath, "utf8"));
47935
- const entries = Array.isArray(parsed?.entries) ? parsed.entries : [];
48174
+ const parsed = readJsonStateSync(filePath, {
48175
+ mode: 384,
48176
+ validate: (value) => {
48177
+ if (!Array.isArray(value?.entries)) throw new TypeError("prompt history has no entries");
48178
+ return value;
48179
+ }
48180
+ });
48181
+ const entries = parsed ? parsed.entries : [];
47936
48182
  return entries.map((entry) => String(entry || "").trim()).filter((entry) => promptHistoryKey(entry));
47937
48183
  } catch {
47938
48184
  return [];
@@ -47945,14 +48191,8 @@ function buildPayload(entries) {
47945
48191
  function writeEntriesSync(filePath, entries) {
47946
48192
  if (!filePath) return false;
47947
48193
  try {
47948
- mkdirSync(dirname2(filePath), { recursive: true, mode: 448 });
47949
- const tmp = `${filePath}.${process.pid}.tmp`;
47950
- writeFileSync(tmp, buildPayload(entries), { encoding: "utf8", mode: 384 });
47951
- renameSync(tmp, filePath);
47952
- try {
47953
- chmodSync(filePath, 384);
47954
- } catch {
47955
- }
48194
+ mkdirSync3(dirname5(filePath), { recursive: true, mode: 448 });
48195
+ writeFileAtomicSync(filePath, buildPayload(entries), { mode: 384 });
47956
48196
  return true;
47957
48197
  } catch {
47958
48198
  return false;
@@ -48346,8 +48586,11 @@ function compactElapsed(value) {
48346
48586
  if (!Number.isFinite(n) || n <= 0) return "";
48347
48587
  return `${Math.max(1, Math.ceil(n / 1e3))}s`;
48348
48588
  }
48589
+ function compactionRunning(compaction) {
48590
+ return compaction.inProgress === true || compaction.lastStage === "compacting";
48591
+ }
48349
48592
  function compactionState(compaction) {
48350
- const compactRunning = compaction.inProgress === true || compaction.lastStage === "compacting";
48593
+ const compactRunning = compactionRunning(compaction);
48351
48594
  const autoClearFailed = compaction.lastStage === "auto_clear_failed" || !!compaction.lastClearCompactError;
48352
48595
  const autoClearStage = compaction.lastStage === "auto_clear" || compaction.lastClearAt;
48353
48596
  const compactInterrupted = compaction.lastStage === "interrupted";
@@ -48396,7 +48639,7 @@ function contextMetrics({ toolsStatus, mcpStatus, skillsStatus, pluginsStatus, c
48396
48639
  );
48397
48640
  const cacheDenom = Number(usage.lastContextTokens || 0) || cachedRead + freshInput + cacheWrite;
48398
48641
  const compactState = compactionState(compaction);
48399
- const compactDuration = compactElapsed(compaction.lastDurationMs);
48642
+ const compactDuration = compactionRunning(compaction) ? "" : compactElapsed(compaction.lastDurationMs);
48400
48643
  return {
48401
48644
  tools,
48402
48645
  mcp,
@@ -49970,7 +50213,7 @@ function useGlobalKeyInput({
49970
50213
  // src/runtime/shared/update-checker.mjs
49971
50214
  init_atomic_file();
49972
50215
  init_json_file();
49973
- import { existsSync as existsSync6, readFileSync as readFileSync6, realpathSync } from "node:fs";
50216
+ import { existsSync as existsSync5, readFileSync as readFileSync5, realpathSync } from "node:fs";
49974
50217
  import { basename as basename4, delimiter, dirname as dirname6, join as join6 } from "node:path";
49975
50218
  import { fileURLToPath as fileURLToPath3 } from "node:url";
49976
50219
  var PACKAGE_NAME = "mixdog";
@@ -49983,7 +50226,7 @@ var _localVersionCache = null;
49983
50226
  function localPackageVersion() {
49984
50227
  if (_localVersionCache) return _localVersionCache;
49985
50228
  try {
49986
- const raw = JSON.parse(readFileSync6(_PACKAGE_JSON_PATH, "utf8"));
50229
+ const raw = JSON.parse(readFileSync5(_PACKAGE_JSON_PATH, "utf8"));
49987
50230
  _localVersionCache = String(raw?.version || "0.0.0");
49988
50231
  } catch {
49989
50232
  _localVersionCache = "0.0.0";
@@ -50730,13 +50973,13 @@ import { homedir as homedir2 } from "node:os";
50730
50973
  import { join as join10 } from "node:path";
50731
50974
 
50732
50975
  // src/runtime/shared/llm/model-catalog.mjs
50733
- import { existsSync as existsSync8, readFileSync as readFileSync8 } from "node:fs";
50976
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
50734
50977
  import { join as join8 } from "node:path";
50735
50978
  import { createHash as createHash3 } from "node:crypto";
50736
50979
  init_atomic_file();
50737
50980
 
50738
50981
  // src/runtime/shared/llm/provider-catalog-cache.mjs
50739
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
50982
+ import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
50740
50983
  import { join as join7 } from "node:path";
50741
50984
 
50742
50985
  // src/runtime/shared/llm/provider-model-identities.mjs
@@ -50766,7 +51009,12 @@ var ANTIGRAVITY_MODELS = Object.freeze([
50766
51009
  low: "gemini-3.1-pro-low",
50767
51010
  high: "gemini-3.1-pro-high"
50768
51011
  }),
50769
- fallbackModel("gemini-4-argon", "Gemini 4 Argon", "gemini-pro", 1048576, "gemini-4-argon", ["low", "medium", "high"]),
51012
+ // The gateway serves Argon only through per-tier ids; bare `gemini-4-argon` is a 404.
51013
+ fallbackModel("gemini-4-argon", "Gemini 4 Argon", "gemini-pro", 1048576, {
51014
+ low: "gemini-4-argon-low",
51015
+ medium: "gemini-4-argon-medium",
51016
+ high: "gemini-4-argon-high"
51017
+ }),
50770
51018
  fallbackModel("claude-opus-4-6-thinking", "Claude Opus 4.6 (Thinking)", null, 25e4, "claude-opus-4-6-thinking", [
50771
51019
  "low",
50772
51020
  "medium",
@@ -51126,8 +51374,8 @@ var PRICING_CATALOG_REFRESH_MS = 6 * 60 * 60 * 1e3;
51126
51374
  var PRICING_CATALOG_RETRY_MS = 6e4;
51127
51375
  function readDiskCatalog(filePath) {
51128
51376
  try {
51129
- if (!existsSync8(filePath)) return null;
51130
- const raw = JSON.parse(readFileSync8(filePath, "utf-8"));
51377
+ if (!existsSync7(filePath)) return null;
51378
+ const raw = JSON.parse(readFileSync7(filePath, "utf-8"));
51131
51379
  return raw?.data ? raw : null;
51132
51380
  } catch {
51133
51381
  return null;
@@ -51207,7 +51455,7 @@ function createCatalogSource({ url, cacheFile, project, label = "" }) {
51207
51455
  warmFromDiskSync() {
51208
51456
  if (cache3) return;
51209
51457
  try {
51210
- const raw = JSON.parse(readFileSync8(cachePath(), "utf-8"));
51458
+ const raw = JSON.parse(readFileSync7(cachePath(), "utf-8"));
51211
51459
  if (raw?.data) {
51212
51460
  cache3 = project(raw.data);
51213
51461
  cacheAt = raw.fetchedAt || Date.now();
@@ -51331,11 +51579,11 @@ function isPidAlive(value) {
51331
51579
  }
51332
51580
 
51333
51581
  // src/runtime/shared/worktrees/git-head.mjs
51334
- import { readFileSync as readFileSync9, statSync as statSync2, watch } from "node:fs";
51582
+ import { readFileSync as readFileSync8, statSync as statSync3, watch } from "node:fs";
51335
51583
  import { dirname as dirname8, resolve as resolve6 } from "node:path";
51336
51584
 
51337
51585
  // src/runtime/shared/worktrees/paths.mjs
51338
- import { existsSync as existsSync9, realpathSync as realpathSync2 } from "node:fs";
51586
+ import { existsSync as existsSync8, realpathSync as realpathSync2 } from "node:fs";
51339
51587
  import { dirname as dirname7, isAbsolute as isAbsolute3, join as join9, relative as relative2, resolve as resolve5, sep } from "node:path";
51340
51588
 
51341
51589
  // src/runtime/shared/statusline/statusline-segments.mjs
@@ -51424,8 +51672,7 @@ async function refreshShellJobsStatus(ownerPid) {
51424
51672
  continue;
51425
51673
  }
51426
51674
  const unconfirmed = detail?.terminationUnconfirmed === true;
51427
- if (unconfirmed ? !isHeldShellJobAlive(detail, ownerByJob.get(id)) : !await isShellJobAlive(detail, p, dir, id))
51428
- continue;
51675
+ if (unconfirmed ? !isPidAlive(ownerByJob.get(id) || 0) : !await isShellJobAlive(detail, p, dir, id)) continue;
51429
51676
  if (detail?.foreground === true && !unconfirmed) continue;
51430
51677
  const ownedByThisHost = ownerByJob.get(id) === ownerPid;
51431
51678
  if (ownedByThisHost) count++;
@@ -51514,12 +51761,6 @@ function summarizeShellJobs({ count, oldestMs, jobs, bySession }) {
51514
51761
  }
51515
51762
  return { count, elapsedLabel, jobs, sessions };
51516
51763
  }
51517
- function isHeldShellJobAlive(detail, ownerPid) {
51518
- if (!isPidAlive(ownerPid || 0)) return false;
51519
- if (detail?.ownerSessionClosed !== true) return true;
51520
- const survivors = Array.isArray(detail?.survivorPids) ? detail.survivorPids : [];
51521
- return [detail?.pid, ...survivors].some((pid) => isPidAlive(positiveInt(pid)));
51522
- }
51523
51764
  async function isShellJobAlive(detail, detailPath, dir, id) {
51524
51765
  const pid = positiveInt(detail?.pid);
51525
51766
  if (!pid) return false;
@@ -58550,7 +58791,9 @@ function createExtensionPickers({
58550
58791
 
58551
58792
  // src/tui/app/maintenance-pickers/auto-clear-picker.mjs
58552
58793
  var HOUR_MS = 60 * 60 * 1e3;
58553
- var formatDurationInput = (ms) => {
58794
+ var UNLIMITED_INPUT = "unlimited";
58795
+ var formatDurationInput = (ms, unlimited = false) => {
58796
+ if (unlimited) return UNLIMITED_INPUT;
58554
58797
  const value = Math.max(0, Math.round(Number(ms) || 0));
58555
58798
  if (value > 0 && value % HOUR_MS === 0) return `${value / HOUR_MS}h`;
58556
58799
  if (value > 0 && value % 6e4 === 0) return `${value / 6e4}m`;
@@ -58581,7 +58824,7 @@ function createAutoClearPicker({
58581
58824
  label: entry.provider,
58582
58825
  marker: entry.provider === provider ? "\u2713" : "",
58583
58826
  markerColor: theme2.success,
58584
- meta: `${formatDuration2(entry.idleMs)}${entry.custom ? " custom" : ""}`,
58827
+ meta: `${entry.unlimited ? "Unlimited" : formatDuration2(entry.idleMs)}${entry.custom ? " custom" : ""}`,
58585
58828
  description: `Default idle window for ${entry.provider}. Enter to edit as text.`,
58586
58829
  _action: "provider-default",
58587
58830
  _entry: entry
@@ -58600,10 +58843,10 @@ function createAutoClearPicker({
58600
58843
  store.pushNotice("autoclear unavailable", "warn");
58601
58844
  return;
58602
58845
  }
58603
- store.pushNotice(
58604
- next.enabled ? `autoclear on \xB7 idle ${formatDuration2(next.idleMs)}` : "autoclear off",
58605
- "info"
58606
- );
58846
+ let notice = "autoclear off";
58847
+ if (next.enabled)
58848
+ notice = next.unlimited ? "autoclear on \xB7 unlimited" : `autoclear on \xB7 idle ${formatDuration2(next.idleMs)}`;
58849
+ store.pushNotice(notice, "info");
58607
58850
  }).catch((e) => store.pushNotice(`autoclear failed: ${e?.message || e}`, "error")).finally(settled);
58608
58851
  };
58609
58852
  const openProviderDurationEditor = (entry) => {
@@ -58612,8 +58855,8 @@ function createAutoClearPicker({
58612
58855
  setSettingsPrompt({
58613
58856
  kind: "autoclear-provider",
58614
58857
  label: `Auto-clear \xB7 ${entry.provider}`,
58615
- hint: `Type a duration like 10m, 1h, or 24h. Empty resets to built-in ${formatDurationInput(entry.builtInMs)}.`,
58616
- initialValue: formatDurationInput(entry.idleMs),
58858
+ hint: `Type a duration like 10m, 1h, or 24h, or ${UNLIMITED_INPUT} to never auto-clear. Empty resets to built-in ${formatDurationInput(entry.builtInMs, entry.builtInUnlimited)}.`,
58859
+ initialValue: formatDurationInput(entry.idleMs, entry.unlimited),
58617
58860
  provider: entry.provider,
58618
58861
  builtInMs: entry.builtInMs,
58619
58862
  returnTo
@@ -58641,16 +58884,18 @@ function createAutoClearPicker({
58641
58884
  const current = await readCurrent();
58642
58885
  const enabled = current?.enabled !== false;
58643
58886
  const idleMs = Number(current?.idleMs || HOUR_MS);
58887
+ const unlimited = current?.unlimited === true;
58644
58888
  const cacheTtlLabel = !enabled || idleMs >= HOUR_MS ? "1h" : "5m";
58645
58889
  let sourceLabel = `${current?.provider || "default"} default`;
58646
58890
  if (current?.providerCustom) sourceLabel = `${current.provider} override`;
58647
58891
  else if (current?.custom) sourceLabel = "global";
58892
+ const clearText = unlimited ? `Never clear idle sessions (${sourceLabel})` : `Clear idle sessions after ${formatDuration2(idleMs)} (${sourceLabel})`;
58648
58893
  const items = [
58649
58894
  {
58650
58895
  value: "toggle",
58651
58896
  label: "Auto-clear",
58652
58897
  meta: enabled ? "On" : "Off",
58653
- description: enabled ? `Clear idle sessions after ${formatDuration2(idleMs)} (${sourceLabel}) \xB7 lead cache TTL ${cacheTtlLabel}.` : "Idle auto-clear disabled.",
58898
+ description: enabled ? `${clearText} \xB7 lead cache TTL ${cacheTtlLabel}.` : "Idle auto-clear disabled.",
58654
58899
  _action: "toggle"
58655
58900
  },
58656
58901
  {
@@ -58662,7 +58907,7 @@ function createAutoClearPicker({
58662
58907
  ];
58663
58908
  own.paint({
58664
58909
  title: "Auto-clear",
58665
- description: `Clear idle context after ${enabled ? `${formatDuration2(idleMs)} (${sourceLabel})` : "never"} \xB7 lead cache TTL ${cacheTtlLabel}.`,
58910
+ description: `Clear idle context after ${enabled && !unlimited ? `${formatDuration2(idleMs)} (${sourceLabel})` : "never"} \xB7 lead cache TTL ${cacheTtlLabel}.`,
58666
58911
  help: "\u2191/\u2193 Select \xB7 \u2190/\u2192 Toggle On/Off \xB7 Enter Open/Toggle \xB7 Esc Close",
58667
58912
  indexMode: "always",
58668
58913
  labelWidth: 10,
@@ -59830,7 +60075,7 @@ function createOnboardingSteps({
59830
60075
  import { spawn as spawn4 } from "node:child_process";
59831
60076
 
59832
60077
  // src/runtime/shared/wsl.mjs
59833
- import { readFileSync as readFileSync10 } from "node:fs";
60078
+ import { readFileSync as readFileSync9 } from "node:fs";
59834
60079
  var _isWSL;
59835
60080
  function isWSL() {
59836
60081
  if (_isWSL !== void 0) return _isWSL;
@@ -59843,7 +60088,7 @@ function isWSL() {
59843
60088
  return _isWSL;
59844
60089
  }
59845
60090
  try {
59846
- const v = readFileSync10("/proc/version", "utf8").toLowerCase();
60091
+ const v = readFileSync9("/proc/version", "utf8").toLowerCase();
59847
60092
  _isWSL = v.includes("microsoft") || v.includes("wsl");
59848
60093
  } catch {
59849
60094
  _isWSL = false;
@@ -61420,8 +61665,8 @@ function createSettingsNavigation({ openers, openSettingsPicker, setSettingsProm
61420
61665
  }
61421
61666
 
61422
61667
  // src/runtime/shared/config.mjs
61423
- import { readFileSync as readFileSync12, statSync as statSync4, mkdirSync as mkdirSync5, existsSync as existsSync11, watch as fsWatch } from "node:fs";
61424
- import { join as join12, dirname as dirname10 } from "node:path";
61668
+ import { readFileSync as readFileSync11, readdirSync as readdirSync3, statSync as statSync5, mkdirSync as mkdirSync5, existsSync as existsSync10, watch as fsWatch } from "node:fs";
61669
+ import { basename as basename6, join as join12, dirname as dirname9 } from "node:path";
61425
61670
  import { createRequire as createRequire3 } from "node:module";
61426
61671
 
61427
61672
  // src/runtime/shared/object.mjs
@@ -61436,24 +61681,16 @@ function isPlainObject(value) {
61436
61681
  init_atomic_file();
61437
61682
 
61438
61683
  // src/runtime/shared/user-data-guard.mjs
61684
+ init_atomic_file();
61685
+ import { existsSync as existsSync9, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync10, rmSync, statSync as statSync4 } from "node:fs";
61439
61686
  import {
61440
- copyFileSync,
61441
- existsSync as existsSync10,
61442
- mkdirSync as mkdirSync4,
61443
- readdirSync as readdirSync2,
61444
- readFileSync as readFileSync11,
61445
- rmSync,
61446
- statSync as statSync3,
61447
- writeFileSync as writeFileSync4
61448
- } from "node:fs";
61449
- import {
61450
- copyFile as copyFileP,
61451
61687
  mkdir as mkdirP,
61688
+ readFile as readFileP,
61452
61689
  readdir as readdirP,
61453
61690
  rm as rmP,
61454
61691
  stat as statP
61455
61692
  } from "node:fs/promises";
61456
- import { basename as basename5, dirname as dirname9, join as join11, resolve as resolve7 } from "node:path";
61693
+ import { basename as basename5, join as join11, resolve as resolve7 } from "node:path";
61457
61694
  import { homedir as homedir3 } from "node:os";
61458
61695
  import { createHash as createHash4, randomUUID } from "node:crypto";
61459
61696
  function getBackupRoot() {
@@ -61540,12 +61777,24 @@ function safeReason(reason) {
61540
61777
  }
61541
61778
  function readInitInstanceId(dataDir2) {
61542
61779
  if (!dataDir2) return null;
61780
+ const path2 = join11(dataDir2, INIT_MARKER);
61781
+ let raw;
61543
61782
  try {
61544
- const marker = JSON.parse(readFileSync11(join11(dataDir2, INIT_MARKER), "utf8"));
61545
- return typeof marker?.instanceId === "string" && marker.instanceId ? marker.instanceId : null;
61546
- } catch {
61547
- return null;
61783
+ raw = readFileSync10(path2, "utf8");
61784
+ } catch (error) {
61785
+ if (error?.code === "ENOENT") return null;
61786
+ throw error;
61787
+ }
61788
+ let marker;
61789
+ try {
61790
+ marker = JSON.parse(raw);
61791
+ } catch (error) {
61792
+ throw new SyntaxError(`[user-data] invalid initialization marker at ${path2}`, { cause: error });
61548
61793
  }
61794
+ if (typeof marker?.instanceId !== "string" || !marker.instanceId) {
61795
+ throw new SyntaxError(`[user-data] initialization marker at ${path2} must have a non-empty instanceId`);
61796
+ }
61797
+ return marker.instanceId;
61549
61798
  }
61550
61799
  function hasUserDataInitMarker(dataDir2) {
61551
61800
  return readInitInstanceId(dataDir2) != null;
@@ -61557,7 +61806,7 @@ function legacyBackupRoots() {
61557
61806
  }
61558
61807
  function manifestDataDirMatches(backupDir, dataDirKey) {
61559
61808
  try {
61560
- const manifest = JSON.parse(readFileSync11(join11(backupDir, BACKUP_MANIFEST), "utf8"));
61809
+ const manifest = JSON.parse(readFileSync10(join11(backupDir, BACKUP_MANIFEST), "utf8"));
61561
61810
  return typeof manifest?.dataDir === "string" && normalizeDataDir(manifest.dataDir) === dataDirKey;
61562
61811
  } catch {
61563
61812
  return false;
@@ -61578,7 +61827,7 @@ function legacyMarkersFor(root, dataDir2, dataDirKey) {
61578
61827
  return names.filter((name) => {
61579
61828
  if (hashed.has(name)) return true;
61580
61829
  try {
61581
- const marker = JSON.parse(readFileSync11(join11(root, name), "utf8"));
61830
+ const marker = JSON.parse(readFileSync10(join11(root, name), "utf8"));
61582
61831
  return typeof marker?.dataDir === "string" && normalizeDataDir(marker.dataDir) === dataDirKey;
61583
61832
  } catch {
61584
61833
  return false;
@@ -61639,10 +61888,10 @@ function backupDirsNewestFirst(dir) {
61639
61888
  }
61640
61889
  function readRestorableConfig(backupDir, dataDirKey, instanceId) {
61641
61890
  try {
61642
- const manifest = JSON.parse(readFileSync11(join11(backupDir, BACKUP_MANIFEST), "utf8"));
61891
+ const manifest = JSON.parse(readFileSync10(join11(backupDir, BACKUP_MANIFEST), "utf8"));
61643
61892
  if (typeof manifest?.dataDir !== "string" || normalizeDataDir(manifest.dataDir) !== dataDirKey) return null;
61644
61893
  if (manifest.instanceId !== instanceId) return null;
61645
- const parsed = JSON.parse(readFileSync11(join11(backupDir, "mixdog-config.json"), "utf8"));
61894
+ const parsed = JSON.parse(readFileSync10(join11(backupDir, "mixdog-config.json"), "utf8"));
61646
61895
  return isStructurallyCompleteMixdogConfigBackup(parsed) ? parsed : null;
61647
61896
  } catch (error) {
61648
61897
  if (isAbsentBackupError(error)) return null;
@@ -61682,7 +61931,7 @@ function loadLegacyMixdogConfigFromBackup(dataDir2, options) {
61682
61931
  const evidence = findLegacyUserDataEvidence(dataDir2, options);
61683
61932
  for (const backupDir of evidence?.backups || []) {
61684
61933
  try {
61685
- const parsed = JSON.parse(readFileSync11(join11(backupDir, "mixdog-config.json"), "utf8"));
61934
+ const parsed = JSON.parse(readFileSync10(join11(backupDir, "mixdog-config.json"), "utf8"));
61686
61935
  if (isStructurallyCompleteMixdogConfigBackup(parsed)) return parsed;
61687
61936
  } catch {
61688
61937
  }
@@ -61690,7 +61939,7 @@ function loadLegacyMixdogConfigFromBackup(dataDir2, options) {
61690
61939
  return null;
61691
61940
  }
61692
61941
  function copyTree(src, dst, copied) {
61693
- const st = statSync3(src);
61942
+ const st = statSync4(src);
61694
61943
  if (st.isDirectory()) {
61695
61944
  for (const name of readdirSync2(src)) {
61696
61945
  copyTree(join11(src, name), join11(dst, name), copied);
@@ -61698,8 +61947,7 @@ function copyTree(src, dst, copied) {
61698
61947
  return;
61699
61948
  }
61700
61949
  if (!st.isFile()) return;
61701
- mkdirSync4(dirname9(dst), { recursive: true });
61702
- copyFileSync(src, dst);
61950
+ writeFileAtomicSync(dst, readFileSync10(src), { mode: st.mode & 511 });
61703
61951
  copied.push(dst);
61704
61952
  }
61705
61953
  function pruneBackups(scopeDir, names, own) {
@@ -61712,18 +61960,14 @@ function pruneBackups(scopeDir, names, own) {
61712
61960
  }
61713
61961
  function markUserDataInitialized(dataDir2) {
61714
61962
  const existing = readInitInstanceId(dataDir2);
61715
- if (existing || !dataDir2 || !existsSync10(dataDir2)) return existing;
61963
+ if (existing || !dataDir2 || !existsSync9(dataDir2)) return existing;
61716
61964
  try {
61717
- writeFileSync4(
61718
- join11(dataDir2, INIT_MARKER),
61719
- `${JSON.stringify(
61720
- { instanceId: randomUUID(), dataDir: resolve7(dataDir2), createdAt: (/* @__PURE__ */ new Date()).toISOString() },
61721
- null,
61722
- 2
61723
- )}
61724
- `,
61725
- // An unreadable marker is replaced; a concurrent creator's valid one wins.
61726
- { encoding: "utf8", flag: existsSync10(join11(dataDir2, INIT_MARKER)) ? "w" : "wx" }
61965
+ const marker = join11(dataDir2, INIT_MARKER);
61966
+ writeJsonAtomicSync(
61967
+ marker,
61968
+ { instanceId: randomUUID(), dataDir: resolve7(dataDir2), createdAt: (/* @__PURE__ */ new Date()).toISOString() },
61969
+ // Another creator may have published since the absent read; it wins.
61970
+ { createOnly: true }
61727
61971
  );
61728
61972
  } catch {
61729
61973
  }
@@ -61734,40 +61978,36 @@ function ensureUserDataInitialized(dataDir2) {
61734
61978
  if (!dataDir2) return;
61735
61979
  const key = normalizeDataDir(dataDir2);
61736
61980
  if (ensuredDataDirs.has(key)) return;
61737
- ensuredDataDirs.add(key);
61738
61981
  if (!hasUserDataInitMarker(dataDir2)) backupUserData(dataDir2, "initial-snapshot");
61982
+ ensuredDataDirs.add(key);
61739
61983
  }
61740
61984
  function skipBackups() {
61741
61985
  return process.env.MIXDOG_SKIP_USER_DATA_BACKUP === "1" || process.env.MIXDOG_SKIP_USER_DATA_BACKUP === "true";
61742
61986
  }
61743
61987
  function finishBackup(dataDir2, backupDir, reason) {
61744
61988
  const instanceId = markUserDataInitialized(dataDir2);
61745
- writeFileSync4(
61746
- join11(backupDir, BACKUP_MANIFEST),
61747
- `${JSON.stringify(
61748
- { dataDir: resolve7(dataDir2), instanceId, reason, createdAt: (/* @__PURE__ */ new Date()).toISOString() },
61749
- null,
61750
- 2
61751
- )}
61752
- `,
61753
- "utf8"
61754
- );
61989
+ writeJsonAtomicSync(join11(backupDir, BACKUP_MANIFEST), {
61990
+ dataDir: resolve7(dataDir2),
61991
+ instanceId,
61992
+ reason,
61993
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
61994
+ });
61755
61995
  restoreLookupCache.delete(normalizeDataDir(dataDir2));
61756
61996
  legacyEvidenceCache.delete(normalizeDataDir(dataDir2));
61757
61997
  }
61758
- function backupUserData(dataDir2, reason = "snapshot") {
61998
+ function backupUserData(dataDir2, reason = "snapshot", { dirs = [] } = {}) {
61759
61999
  if (skipBackups()) return { dir: null, copied: [] };
61760
- if (!dataDir2 || !existsSync10(dataDir2)) return { dir: null, copied: [] };
62000
+ if (!dataDir2 || !existsSync9(dataDir2)) return { dir: null, copied: [] };
61761
62001
  const scopeDir = scopeDirFor(dataDir2);
61762
62002
  const { backupDir, names } = reserveBackupDir(scopeDir, reason);
61763
62003
  const copied = [];
61764
62004
  for (const rel of USER_DATA_FILES) {
61765
62005
  const src = join11(dataDir2, rel);
61766
- if (existsSync10(src)) copyTree(src, join11(backupDir, rel), copied);
62006
+ if (existsSync9(src)) copyTree(src, join11(backupDir, rel), copied);
61767
62007
  }
61768
- for (const rel of USER_DATA_DIRS) {
62008
+ for (const rel of [...USER_DATA_DIRS, ...dirs]) {
61769
62009
  const src = join11(dataDir2, rel);
61770
- if (existsSync10(src)) copyTree(src, join11(backupDir, rel), copied);
62010
+ if (existsSync9(src)) copyTree(src, join11(backupDir, rel), copied);
61771
62011
  }
61772
62012
  if (copied.length > 0) {
61773
62013
  finishBackup(dataDir2, backupDir, reason);
@@ -61790,8 +62030,7 @@ async function copyTreeAsync(src, dst, copied) {
61790
62030
  return;
61791
62031
  }
61792
62032
  if (!st.isFile()) return;
61793
- await mkdirP(dirname9(dst), { recursive: true });
61794
- await copyFileP(src, dst);
62033
+ await writeFileAtomicAsync(dst, await readFileP(src), { mode: st.mode & 511 });
61795
62034
  copied.push(dst);
61796
62035
  }
61797
62036
  async function pruneBackupsAsync(scopeDir, names, own) {
@@ -61804,17 +62043,17 @@ async function pruneBackupsAsync(scopeDir, names, own) {
61804
62043
  }
61805
62044
  async function backupUserDataAsync(dataDir2, reason = "snapshot") {
61806
62045
  if (skipBackups()) return { dir: null, copied: [] };
61807
- if (!dataDir2 || !existsSync10(dataDir2)) return { dir: null, copied: [] };
62046
+ if (!dataDir2 || !existsSync9(dataDir2)) return { dir: null, copied: [] };
61808
62047
  const scopeDir = scopeDirFor(dataDir2);
61809
62048
  const { backupDir, names } = await reserveBackupDirAsync(scopeDir, reason);
61810
62049
  const copied = [];
61811
62050
  for (const rel of USER_DATA_FILES) {
61812
62051
  const src = join11(dataDir2, rel);
61813
- if (existsSync10(src)) await copyTreeAsync(src, join11(backupDir, rel), copied);
62052
+ if (existsSync9(src)) await copyTreeAsync(src, join11(backupDir, rel), copied);
61814
62053
  }
61815
62054
  for (const rel of USER_DATA_DIRS) {
61816
62055
  const src = join11(dataDir2, rel);
61817
- if (existsSync10(src)) await copyTreeAsync(src, join11(backupDir, rel), copied);
62056
+ if (existsSync9(src)) await copyTreeAsync(src, join11(backupDir, rel), copied);
61818
62057
  }
61819
62058
  if (copied.length > 0) {
61820
62059
  finishBackup(dataDir2, backupDir, reason);
@@ -61889,7 +62128,7 @@ function readConfigRawCached() {
61889
62128
  return _configReadCache.raw;
61890
62129
  }
61891
62130
  try {
61892
- const st2 = statSync4(configPath());
62131
+ const st2 = statSync5(configPath());
61893
62132
  if (st2.mtimeMs === _configReadCache.mtimeMs && st2.size === _configReadCache.size) {
61894
62133
  _configReadCache.atMs = now;
61895
62134
  return _configReadCache.raw;
@@ -61899,7 +62138,7 @@ function readConfigRawCached() {
61899
62138
  }
61900
62139
  let st = null;
61901
62140
  try {
61902
- st = statSync4(configPath());
62141
+ st = statSync5(configPath());
61903
62142
  } catch (err) {
61904
62143
  if (err.code === "ENOENT") {
61905
62144
  _configReadCache = null;
@@ -61911,7 +62150,7 @@ function readConfigRawCached() {
61911
62150
  }
61912
62151
  let raw;
61913
62152
  try {
61914
- raw = readFileSync12(configPath(), "utf8");
62153
+ raw = readFileSync11(configPath(), "utf8");
61915
62154
  } catch (err) {
61916
62155
  if (err.code === "ENOENT") {
61917
62156
  _configReadCache = null;
@@ -61978,7 +62217,7 @@ function readConfigFile() {
61978
62217
  const raw = readConfigRawCached();
61979
62218
  if (raw == null) return null;
61980
62219
  try {
61981
- return JSON.parse(raw);
62220
+ return parseJsonText(raw);
61982
62221
  } catch (err) {
61983
62222
  invalidateConfigReadCache();
61984
62223
  quarantineMalformedConfig(err);
@@ -61986,7 +62225,7 @@ function readConfigFile() {
61986
62225
  }
61987
62226
  }
61988
62227
  function writeConfigFile(data, postBackupReason = "post-config-write") {
61989
- mkdirSync5(dirname10(configPath()), { recursive: true, mode: 448 });
62228
+ mkdirSync5(dirname9(configPath()), { recursive: true, mode: 448 });
61990
62229
  try {
61991
62230
  backupUserData(resolvePluginData(), "pre-config-write");
61992
62231
  } catch {
@@ -62010,7 +62249,7 @@ function persistRestoredConfig(restored) {
62010
62249
  const wrote = withFileLockSync(
62011
62250
  `${path2}.lock`,
62012
62251
  () => {
62013
- if (existsSync11(path2)) return false;
62252
+ if (existsSync10(path2)) return false;
62014
62253
  writeAll(restored, "post-restore");
62015
62254
  return true;
62016
62255
  },
@@ -62056,23 +62295,42 @@ function readAll() {
62056
62295
  return {};
62057
62296
  }
62058
62297
  function quarantineMalformedConfig(parseErr) {
62059
- const corrupt = `${configPath()}.corrupt-${Date.now()}`;
62298
+ const corrupt = quarantinePath(configPath());
62299
+ let keptAside = false;
62060
62300
  try {
62061
- if (existsSync11(configPath())) renameWithRetrySync(configPath(), corrupt);
62301
+ if (existsSync10(configPath())) renameWithRetrySync(configPath(), corrupt);
62302
+ keptAside = existsSync10(corrupt);
62062
62303
  } catch {
62063
62304
  }
62064
62305
  process.stderr.write(
62065
62306
  `[config] mixdog-config.json is malformed (${parseErr.message}). Renamed to ${corrupt}. Restore it or delete to start fresh.
62066
62307
  `
62067
62308
  );
62309
+ return keptAside;
62068
62310
  }
62069
- function restoreAllForRmWOrThrow(reason) {
62311
+ function hasQuarantinedCopy() {
62312
+ const dir = dirname9(configPath());
62313
+ const prefix = `${basename6(configPath())}.corrupt-`;
62314
+ try {
62315
+ return readdirSync3(dir).some((name) => name.startsWith(prefix));
62316
+ } catch {
62317
+ return false;
62318
+ }
62319
+ }
62320
+ function restoreAllForRmWOrThrow(reason, keptAside = false) {
62070
62321
  const restored = loadLatestMixdogConfigFromBackup(resolvePluginData(), { fresh: true });
62071
62322
  if (restored && isPlainObject(restored)) {
62072
62323
  process.stderr.write(`[config] RMW read: restored mixdog-config.json from latest user-data backup (${reason})
62073
62324
  `);
62074
62325
  return restored;
62075
62326
  }
62327
+ if (keptAside) {
62328
+ process.stderr.write(
62329
+ `[config] RMW read: mixdog-config.json is unusable (${reason}); its bytes are kept aside and no backup exists; starting empty
62330
+ `
62331
+ );
62332
+ return {};
62333
+ }
62076
62334
  const legacy = findLegacyUserDataEvidence(resolvePluginData(), { fresh: true });
62077
62335
  if (legacy) {
62078
62336
  const err = new Error(
@@ -62088,11 +62346,11 @@ function restoreAllForRmWOrThrow(reason) {
62088
62346
  function readAllForRmW() {
62089
62347
  let raw;
62090
62348
  try {
62091
- raw = readFileSync12(configPath(), "utf8");
62349
+ raw = readFileSync11(configPath(), "utf8");
62092
62350
  } catch (err) {
62093
62351
  if (err.code === "ENOENT") {
62094
62352
  if (isUserDataRecoveryExpected(resolvePluginData(), { fresh: true })) {
62095
- return restoreAllForRmWOrThrow("config file missing after user-data was initialized");
62353
+ return restoreAllForRmWOrThrow("config file missing after user-data was initialized", hasQuarantinedCopy());
62096
62354
  }
62097
62355
  return {};
62098
62356
  }
@@ -62101,12 +62359,11 @@ function readAllForRmW() {
62101
62359
  throw err;
62102
62360
  }
62103
62361
  try {
62104
- const parsed = JSON.parse(raw);
62362
+ const parsed = parseJsonText(raw);
62105
62363
  if (!isPlainObject(parsed)) throw new SyntaxError("config root must be a JSON object");
62106
62364
  return parsed;
62107
62365
  } catch (parseErr) {
62108
- quarantineMalformedConfig(parseErr);
62109
- return restoreAllForRmWOrThrow(parseErr.message);
62366
+ return restoreAllForRmWOrThrow(parseErr.message, quarantineMalformedConfig(parseErr));
62110
62367
  }
62111
62368
  }
62112
62369
  var CONFIG_CHANGE_DEBOUNCE_MS = 100;
@@ -62135,7 +62392,7 @@ function readSection(section) {
62135
62392
  return stripGeneratedMarker(readAll()[section] ?? null) ?? {};
62136
62393
  }
62137
62394
  async function writeConfigFileAsync(data) {
62138
- mkdirSync5(dirname10(configPath()), { recursive: true, mode: 448 });
62395
+ mkdirSync5(dirname9(configPath()), { recursive: true, mode: 448 });
62139
62396
  try {
62140
62397
  await backupUserDataAsync(resolvePluginData(), "pre-config-write");
62141
62398
  } catch {
@@ -62456,8 +62713,8 @@ function buildSettingsItems({
62456
62713
  {
62457
62714
  value: "autoclear",
62458
62715
  label: "Auto-clear",
62459
- meta: autoClearEnabled ? `On (${formatDuration2(autoClear.idleMs)})` : "Off",
62460
- description: autoClearEnabled ? `Clear idle sessions after ${formatDuration2(autoClear.idleMs)}${autoClearSource}. Enter for options.` : "Idle auto-clear disabled. Enter for options.",
62716
+ meta: autoClearEnabled ? `On (${autoClear.unlimited ? "Unlimited" : formatDuration2(autoClear.idleMs)})` : "Off",
62717
+ description: autoClearEnabled ? `${autoClear.unlimited ? "Never clear idle sessions" : `Clear idle sessions after ${formatDuration2(autoClear.idleMs)}`}${autoClearSource}. Enter for options.` : "Idle auto-clear disabled. Enter for options.",
62461
62718
  _action: "autoclear"
62462
62719
  },
62463
62720
  {
@@ -63846,13 +64103,13 @@ import { useCallback as useCallback21, useEffect as useEffect27, useLayoutEffect
63846
64103
 
63847
64104
  // src/tui/session/transcript-spill.mjs
63848
64105
  import { randomBytes as randomBytes4 } from "node:crypto";
63849
- import { readFileSync as readFileSync16 } from "node:fs";
64106
+ import { readFileSync as readFileSync15 } from "node:fs";
63850
64107
  import { join as join16 } from "node:path";
63851
64108
  import { Worker as Worker2 } from "node:worker_threads";
63852
64109
 
63853
64110
  // src/tui/session/transcript-spill/spill-dir.mjs
63854
64111
  import { randomUUID as randomUUID2 } from "node:crypto";
63855
- import { mkdtempSync, readdirSync as readdirSync5, readFileSync as readFileSync15, rmSync as rmSync5, statSync as statSync6, writeFileSync as writeFileSync6 } from "node:fs";
64112
+ import { mkdtempSync, readdirSync as readdirSync6, readFileSync as readFileSync14, rmSync as rmSync5, statSync as statSync7, writeFileSync as writeFileSync4 } from "node:fs";
63856
64113
  import { tmpdir as tmpdir3 } from "node:os";
63857
64114
  import { join as join15 } from "node:path";
63858
64115
  var STALE_MS = 24 * 60 * 60 * 1e3;
@@ -66303,16 +66560,16 @@ function drainStdin(stdin = process.stdin) {
66303
66560
  let fd = -1;
66304
66561
  try {
66305
66562
  if (!wasRaw) tty3.setRawMode?.(true);
66306
- fd = openSync3("/dev/tty", fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
66563
+ fd = openSync4("/dev/tty", fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
66307
66564
  const buf = Buffer.alloc(1024);
66308
66565
  for (let i = 0; i < 64; i++) {
66309
- if (readSync(fd, buf, 0, buf.length, null) <= 0) break;
66566
+ if (readSync2(fd, buf, 0, buf.length, null) <= 0) break;
66310
66567
  }
66311
66568
  } catch {
66312
66569
  } finally {
66313
66570
  if (fd >= 0) {
66314
66571
  try {
66315
- closeSync3(fd);
66572
+ closeSync4(fd);
66316
66573
  } catch {
66317
66574
  }
66318
66575
  }
@@ -66330,7 +66587,7 @@ function installTuiStderrGuard() {
66330
66587
  const originalWrite = process.stderr.write.bind(process.stderr);
66331
66588
  const logPath = resolveTuiStderrLogPath();
66332
66589
  try {
66333
- mkdirSync8(dirname12(logPath), { recursive: true });
66590
+ mkdirSync8(dirname11(logPath), { recursive: true });
66334
66591
  } catch {
66335
66592
  }
66336
66593
  (0, import_mixdog_debug.rotateBoundedLog)(logPath, import_mixdog_debug.PLUGIN_LOG_MAX_BYTES, import_mixdog_debug.PLUGIN_LOG_KEEP_BYTES);