@bastani/atomic 0.10.15-alpha.2 → 0.10.16-alpha.1

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 (351) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/dist/__atomic_timers/index.js +112 -0
  3. package/dist/__atomic_timers/index.js.map +1 -0
  4. package/dist/_shared/dist-KOELCESV.js +2 -2
  5. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  6. package/dist/_shared/http-YFAPTIZD.js +20 -22
  7. package/dist/_shared/http-YFAPTIZD.js.map +1 -1
  8. package/dist/_shared/lib-4PES5P4V.js +2 -2
  9. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +55 -25
  10. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  11. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +13 -14
  12. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js.map +1 -1
  13. package/dist/_shared/mode-shared-2QJSCUM6.js +16 -17
  14. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  15. package/dist/_shared/p0-cli-BB45ZQY6.js +23 -37
  16. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  17. package/dist/_shared/p1a-prewarm-XIU57JHF.js +6 -5
  18. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  19. package/dist/_shared/{p1b-elig-TVB5CBLL.js → p1b-elig-BY2G5BUE.js} +28 -36
  20. package/dist/_shared/p1b-elig-BY2G5BUE.js.map +1 -0
  21. package/dist/_shared/runtime-O4KCSG4C.js +4 -4
  22. package/dist/_shared/sdk-OHKMDJ74.js +382 -45
  23. package/dist/_shared/sdk-OHKMDJ74.js.map +1 -1
  24. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  25. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  26. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -1
  27. package/dist/_shared/{startup-0-0-Q3MWKUK4.js → startup-0-0-ERMIDHQT.js} +296 -382
  28. package/dist/_shared/startup-0-0-ERMIDHQT.js.map +1 -0
  29. package/dist/_shared/{startup-0-1-M6OWAYHH.js → startup-0-1-RTASI3HG.js} +430 -102
  30. package/dist/_shared/startup-0-1-RTASI3HG.js.map +1 -0
  31. package/dist/_shared/{startup-0-2-2HUMCPKX.js → startup-0-2-YZZOC22D.js} +8109 -7962
  32. package/dist/_shared/startup-0-2-YZZOC22D.js.map +1 -0
  33. package/dist/_shared/{startup-0-3-4ZYBYQNM.js → startup-0-3-DE2NCS6A.js} +130 -83
  34. package/dist/_shared/startup-0-3-DE2NCS6A.js.map +1 -0
  35. package/dist/_shared/startup-0-4-ZMJV547D.js +7 -7
  36. package/dist/_shared/{startup-0-5-YDW47QX6.js → startup-0-5-HZX3ZPTP.js} +411 -85
  37. package/dist/_shared/startup-0-5-HZX3ZPTP.js.map +1 -0
  38. package/dist/_shared/startup-10-0-TDQNBDDL.js +42 -29
  39. package/dist/_shared/startup-10-0-TDQNBDDL.js.map +1 -1
  40. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  41. package/dist/_shared/startup-14-0-MLX36RBG.js +11 -10
  42. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  43. package/dist/_shared/startup-15-0-YUKGAC63.js +9 -8
  44. package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
  45. package/dist/_shared/startup-15-1-4S7FLMNG.js +24 -16
  46. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  47. package/dist/_shared/startup-8-0-34CBHPZH.js +40 -19
  48. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  49. package/dist/_shared/startup-8-1-LZFXSD3Z.js +129 -92
  50. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -1
  51. package/dist/_shared/storage-command-7MGXLJGZ.js +6 -4
  52. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  53. package/dist/_shared/storage-status-K7PX2RXA.js +7 -6
  54. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -1
  55. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  56. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  57. package/dist/_shared/team-DOQKICG2.js +4 -3
  58. package/dist/_shared/team-DOQKICG2.js.map +1 -1
  59. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  60. package/dist/builtin/intercom/index.bundle.mjs +1 -2
  61. package/dist/builtin/intercom/package.json +1 -1
  62. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  63. package/dist/builtin/mcp/package.json +1 -1
  64. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  65. package/dist/builtin/subagents/package.json +1 -1
  66. package/dist/builtin/subagents/src/extension/index.bundle.mjs +102 -42
  67. package/dist/builtin/web-access/index.bundle.mjs +1 -2
  68. package/dist/builtin/web-access/package.json +1 -1
  69. package/dist/cli/args.js +2 -2
  70. package/dist/cli/auth-cli.code.js +6 -6
  71. package/dist/cli/auth-cli.impl.js +3 -3
  72. package/dist/cli/auth-cli.js +3 -3
  73. package/dist/cli/blueprint-command.code.js +7 -6
  74. package/dist/cli/blueprint-command.code.js.map +1 -1
  75. package/dist/cli/blueprint-command.impl.js +3 -3
  76. package/dist/cli/blueprint-command.js +3 -3
  77. package/dist/cli/intercom-command.code.js +3 -3
  78. package/dist/cli/intercom-command.impl.js +3 -3
  79. package/dist/cli/intercom-command.js +3 -3
  80. package/dist/cli/list-models.code.js +2 -2
  81. package/dist/cli/list-models.impl.js +3 -3
  82. package/dist/cli/list-models.js +3 -3
  83. package/dist/cli/session-picker.code.js +2 -2
  84. package/dist/cli/session-picker.impl.js +3 -3
  85. package/dist/cli/session-picker.js +3 -3
  86. package/dist/cli/startup-ui.code.js +2 -2
  87. package/dist/cli/startup-ui.impl.js +3 -3
  88. package/dist/cli/startup-ui.js +3 -3
  89. package/dist/cli/storage-command.impl.js +3 -3
  90. package/dist/cli/storage-command.js +3 -3
  91. package/dist/cli/storage-search-session.code.js +1 -1
  92. package/dist/cli/storage-search-session.impl.js +3 -3
  93. package/dist/cli/storage-search-session.js +3 -3
  94. package/dist/cli/team-command.code.js +2 -2
  95. package/dist/cli/team-command.impl.js +3 -3
  96. package/dist/cli/team-command.js +3 -3
  97. package/dist/cli.js +2 -2
  98. package/dist/core/agent-session.d.ts +1 -0
  99. package/dist/core/debug.code.js +1 -1
  100. package/dist/core/debug.impl.js +3 -3
  101. package/dist/core/debug.js +3 -3
  102. package/dist/core/export-html/card-projection.code.js +1 -1
  103. package/dist/core/export-html/card-projection.impl.js +3 -3
  104. package/dist/core/export-html/card-projection.js +3 -3
  105. package/dist/core/export-html/index.code.js +2 -2
  106. package/dist/core/export-html/index.impl.js +3 -3
  107. package/dist/core/export-html/index.js +3 -3
  108. package/dist/core/export-html/json-spans.impl.js +3 -3
  109. package/dist/core/export-html/json-spans.js +3 -3
  110. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  111. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  112. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  113. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  114. package/dist/core/export-html/tool-renderer.js +3 -3
  115. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  116. package/dist/core/extensions/jiti-loader.js +3 -3
  117. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  118. package/dist/core/extensions/jiti-static-loader.js +3 -3
  119. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  120. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  121. package/dist/core/extensions/loader-host-modules.js +3 -3
  122. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  123. package/dist/core/extensions/runner-context.js +1 -1
  124. package/dist/core/http-dispatcher.d.ts +2 -1
  125. package/dist/core/intercom-broker-control-host.code.js +1 -1
  126. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  127. package/dist/core/intercom-broker-control-host.js +3 -3
  128. package/dist/core/intercom-broker-control.code.js +3 -3
  129. package/dist/core/intercom-broker-control.impl.js +3 -3
  130. package/dist/core/intercom-broker-control.js +3 -3
  131. package/dist/core/lock-takeover.d.ts +2 -0
  132. package/dist/core/model-config.d.ts +28 -0
  133. package/dist/core/model-registry.js +1 -1
  134. package/dist/core/model-runtime-streaming.d.ts +3 -2
  135. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  136. package/dist/core/package-manager-storage-adapters.js +3 -3
  137. package/dist/core/provider-rate-limits.d.ts +17 -10
  138. package/dist/core/provider-request-admission.d.ts +16 -0
  139. package/dist/core/resume/blueprint/barrier.d.ts +6 -6
  140. package/dist/core/resume/blueprint/build.d.ts +3 -1
  141. package/dist/core/resume/blueprint/ledger.d.ts +3 -2
  142. package/dist/core/resume/blueprint/resume.d.ts +2 -1
  143. package/dist/core/retry-policy.d.ts +3 -1
  144. package/dist/core/sdk.code.js +3 -3
  145. package/dist/core/sdk.impl.js +3 -3
  146. package/dist/core/sdk.js +3 -3
  147. package/dist/core/session-manager-core.js +6 -6
  148. package/dist/core/session-manager-list.impl.js +3 -3
  149. package/dist/core/session-manager-list.js +3 -3
  150. package/dist/core/session-manager-types.d.ts +1 -1
  151. package/dist/core/session-manager.code.js +2 -2
  152. package/dist/core/session-manager.impl.js +3 -3
  153. package/dist/core/session-manager.js +3 -3
  154. package/dist/core/session-open-markers.js +1 -1
  155. package/dist/core/session-storage.impl.js +3 -3
  156. package/dist/core/session-storage.js +3 -3
  157. package/dist/core/settings-duration.d.ts +3 -0
  158. package/dist/core/settings-manager-resource-accessors.d.ts +2 -1
  159. package/dist/core/settings-schema.d.ts +1 -0
  160. package/dist/core/storage/index.js +2 -2
  161. package/dist/core/storage/node-sqlite-file-gate.js +7 -6
  162. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  163. package/dist/core/storage/node-sqlite-thread.js +2 -2
  164. package/dist/core/storage/node-sqlite.js +2 -2
  165. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  166. package/dist/core/storage/offline-snapshot-file.js +3 -3
  167. package/dist/core/storage/prefix.js +3 -0
  168. package/dist/core/storage/prefix.js.map +1 -1
  169. package/dist/core/storage/provider.js +2 -2
  170. package/dist/core/storage/selection.js +2 -2
  171. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  172. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  173. package/dist/core/storage/session/branch-fork-source.js +3 -3
  174. package/dist/core/storage/session/card-view.impl.js +3 -3
  175. package/dist/core/storage/session/card-view.js +3 -3
  176. package/dist/core/storage/session/child-reader.code.js +24 -7
  177. package/dist/core/storage/session/child-reader.code.js.map +1 -1
  178. package/dist/core/storage/session/child-reader.impl.js +3 -3
  179. package/dist/core/storage/session/child-reader.js +3 -3
  180. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  181. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  182. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  183. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  184. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  185. package/dist/core/storage/session/expanded-child-details.js +3 -3
  186. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  187. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  188. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  189. package/dist/core/storage/session/fork-row-index.js +3 -3
  190. package/dist/core/storage/session/fork-staging.code.js +1 -1
  191. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  192. package/dist/core/storage/session/fork-staging.js +3 -3
  193. package/dist/core/storage/session/fork-window.code.js +4 -4
  194. package/dist/core/storage/session/fork-window.impl.js +3 -3
  195. package/dist/core/storage/session/fork-window.js +3 -3
  196. package/dist/core/storage/session/history-pages.impl.js +3 -3
  197. package/dist/core/storage/session/history-pages.js +3 -3
  198. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  199. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  200. package/dist/core/storage/session/jsonl-session-store.d.ts +2 -2
  201. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  202. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  203. package/dist/core/storage/session/memory-session-store.d.ts +2 -2
  204. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  205. package/dist/core/storage/session/memory-session-store.js +3 -3
  206. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  207. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  208. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  209. package/dist/core/storage/session/released-history-files.code.js +4 -4
  210. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  211. package/dist/core/storage/session/released-history-files.js +3 -3
  212. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  213. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  214. package/dist/core/storage/session/session-resume.impl.js +3 -3
  215. package/dist/core/storage/session/session-resume.js +3 -3
  216. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  217. package/dist/core/storage/session/snapshot-cut.js +3 -3
  218. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  219. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  220. package/dist/core/storage/session/snapshot-history.js +3 -3
  221. package/dist/core/storage/session/sql-session-store.d.ts +13 -4
  222. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  223. package/dist/core/storage/session/sql-session-store.js +3 -3
  224. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  225. package/dist/core/storage/session/tree-outline.js +3 -3
  226. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  227. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  228. package/dist/core/storage/session/tree-presentation.js +3 -3
  229. package/dist/core/storage/session/types.d.ts +20 -2
  230. package/dist/core/storage/sqlite-facade.js +14 -13
  231. package/dist/core/storage/sqlite-facade.js.map +1 -1
  232. package/dist/core/storage/storage-status.impl.js +3 -3
  233. package/dist/core/storage/storage-status.js +3 -3
  234. package/dist/core/storage/team.impl.js +3 -3
  235. package/dist/core/storage/team.js +3 -3
  236. package/dist/core/structured-output/index.impl.js +3 -3
  237. package/dist/core/structured-output/index.js +3 -3
  238. package/dist/core/tasks/heartbeat.d.ts +1 -0
  239. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  240. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  241. package/dist/core/tasks/task-completion-entry.js +3 -3
  242. package/dist/core/tasks/task-file-history.code.js +3 -3
  243. package/dist/core/tasks/task-file-history.impl.js +3 -3
  244. package/dist/core/tasks/task-file-history.js +3 -3
  245. package/dist/core/tasks/task-reference-archive.code.js +3 -3
  246. package/dist/core/tasks/task-reference-archive.js +3 -3
  247. package/dist/core/tasks/task-reference-identity.js +3 -3
  248. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  249. package/dist/core/tasks/task-reference-stream.js +3 -3
  250. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  251. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  252. package/dist/core/tasks/task-view-source.impl.js +3 -3
  253. package/dist/core/tasks/task-view-source.js +3 -3
  254. package/dist/core/tools/ask-user-question/ask-user-question.d.ts +1 -1
  255. package/dist/core/tools/history-session.d.ts +2 -0
  256. package/dist/core/tools/read-url.code.js +3 -3
  257. package/dist/core/tools/read-url.impl.js +3 -3
  258. package/dist/core/tools/read-url.js +3 -3
  259. package/dist/core/worktree-snapshot/blob-store.js +5 -6
  260. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  261. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  262. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  263. package/dist/core/worktree-snapshot/errors.js +3 -3
  264. package/dist/core/worktree-snapshot/git.d.ts +2 -0
  265. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  266. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  267. package/dist/extensions/codemode/execute.code.js +6 -5
  268. package/dist/extensions/codemode/execute.code.js.map +1 -1
  269. package/dist/extensions/codemode/execute.impl.js +3 -3
  270. package/dist/extensions/codemode/execute.js +3 -3
  271. package/dist/extensions/codemode/renderer.code.js +1 -1
  272. package/dist/extensions/codemode/renderer.impl.js +3 -3
  273. package/dist/extensions/codemode/renderer.js +3 -3
  274. package/dist/extensions/mcp/cli.code.js +8 -4
  275. package/dist/extensions/mcp/cli.code.js.map +1 -1
  276. package/dist/extensions/mcp/cli.impl.js +3 -3
  277. package/dist/extensions/mcp/cli.js +3 -3
  278. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  279. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  280. package/dist/extensions/mcp/cli.lazy.js +3 -3
  281. package/dist/extensions/mcp/runtime.impl.js +3 -3
  282. package/dist/extensions/mcp/runtime.js +3 -3
  283. package/dist/index.js +6 -6
  284. package/dist/main-first-time-setup.code.js +2 -2
  285. package/dist/main-first-time-setup.impl.js +3 -3
  286. package/dist/main-first-time-setup.js +3 -3
  287. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  288. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  289. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  290. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  291. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  292. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  293. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  294. package/dist/package-manager-cli.code.js +7 -7
  295. package/dist/package-manager-cli.impl.js +3 -3
  296. package/dist/package-manager-cli.js +3 -3
  297. package/dist/rpc-entry.js +1 -1
  298. package/dist/startup-files.json +1 -1
  299. package/dist/startup-stages/10.js +1 -1
  300. package/dist/startup-stages/11.js +1 -1
  301. package/dist/startup-stages/12.js +1 -1
  302. package/dist/startup-stages/13.js +1 -0
  303. package/dist/startup-stages/2.js +2 -6
  304. package/dist/startup-stages/3.js +6 -1
  305. package/dist/startup-stages/4.js +1 -1
  306. package/dist/startup-stages/5.js +12 -1
  307. package/dist/startup-stages/6.js +8 -4
  308. package/dist/startup-stages/7.js +4 -3
  309. package/dist/startup-stages/8.js +1 -5
  310. package/dist/startup-stages/9.js +5 -1
  311. package/dist/startup-stages/stages.json +1 -1
  312. package/dist/utils/startup-database-spare.code.js +3 -3
  313. package/dist/utils/startup-database-spare.impl.js +3 -3
  314. package/dist/utils/startup-database-spare.js +3 -3
  315. package/dist/utils/tools-manager.code.js +1 -1
  316. package/dist/utils/tools-manager.impl.js +3 -3
  317. package/dist/utils/tools-manager.js +3 -3
  318. package/dist/utils/windows-cwd.js +3 -3
  319. package/dist/utils/windows-cwd.js.map +1 -1
  320. package/docs/changelog.mdx +2 -2
  321. package/docs/codemode.md +5 -2
  322. package/docs/compaction/branch-summaries.md +1 -1
  323. package/docs/compaction/custom-compactors.md +1 -1
  324. package/docs/custom-provider/api-reference.md +1 -1
  325. package/docs/custom-provider/registration.md +3 -0
  326. package/docs/custom-provider/streaming.md +1 -1
  327. package/docs/environment-variables.md +2 -2
  328. package/docs/guides/resume-on-any-machine.md +1 -0
  329. package/docs/libraries/ai.md +4 -2
  330. package/docs/libraries/codemode.md +1 -1
  331. package/docs/models/choose-a-model.md +1 -1
  332. package/docs/models-configuration.md +5 -2
  333. package/docs/models.md +32 -0
  334. package/docs/providers.md +33 -1
  335. package/docs/sdk/structured-decisions.md +4 -2
  336. package/docs/sessions.md +1 -1
  337. package/docs/settings.md +78 -16
  338. package/docs/storage/postgres/tuning.md +1 -0
  339. package/docs/subagents/reference.md +2 -1
  340. package/docs/tools.md +4 -3
  341. package/docs/worktree-snapshots/reference.md +2 -0
  342. package/docs/worktree-snapshots.md +4 -0
  343. package/package.json +9 -9
  344. package/schemas/models.schema.json +21 -0
  345. package/schemas/settings.schema.json +14 -1
  346. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +0 -1
  347. package/dist/_shared/startup-0-0-Q3MWKUK4.js.map +0 -1
  348. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +0 -1
  349. package/dist/_shared/startup-0-2-2HUMCPKX.js.map +0 -1
  350. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +0 -1
  351. package/dist/_shared/startup-0-5-YDW47QX6.js.map +0 -1
@@ -1,11 +1,11 @@
1
1
  import { __commonJSMin, __name, __require, __toESM } from "./rolldown-runtime-BGM3D5V3.js";
2
2
  import { APP_NAME, BLUEPRINT_FILE_NAME, CONFIG_DIR_NAME, ENV_MODEL_CATALOG_URL, canonicalizePath as canonicalizePath$1, canonicalizePathAsync as canonicalizePathAsync$1, createChildProcessEnvironment, createModuleRequire, findHelperExecutableAsync, getAgentDir, getAgentDirs, getBinDir, getDocsPath, getEnvValue, getExamplesPath, getExtensionTranspileCacheDir, getPathComparisonKey, getProjectConfigDirs, getReadmePath, getUserConfigPaths, isBunBinary, isBundledBuild, isLocalPath, isPathWithin, markPathIgnoredByCloudSync, moduleDirFromMetaUrl, normalizePath, pathsEqual, processLaunch, processLaunchAsync, rehydrateDebugError, resolutionBaseUrl, resolvePath, resolveSafeWindowsWorkingDirectoryAsync, spawnLaunchedProcess, spawnLaunchedProcessSync, stripBom, updatedInstallError } from "./p0-cli-BB45ZQY6.js";
3
- import { BUILTIN_PATH_PREFIX, BlueprintInvalidError, COMMAND_DETAIL_TAIL_BYTES, DEFAULT_THINKING_LEVEL, FILE_KINDS, FILE_PATTERNS, FORKED_PACKAGE_WORKSPACE_DIRS, GitUnavailableError, HOST, NETWORK_TIMEOUT_MS, POST_LOGOUT_AUTH_CHECK_TIMEOUT_MS, RESOURCE_TYPES, ROW_INTENT_META, THINKING_LEVELS, TYPEBOX_SUBPATHS, TaskCleanupError, VisualLinePreview, asyncScope, bindSavedReadLines, cancelReasonText, containProcessTree, conventionDirsForResource, createBatchedCanonicalizePathAsync, createGitEnvironment, createSyntheticSourceInfo, createTypeScriptSourceSpecifierTransform, emitProgress, experimentalToolSamplingProperty, findPreferredAvailableModel, forkedPackageExportAliases, formatNoApiKeyFoundMessage, formatSize, formatTimeoutSeconds, formatTokenCount, formatToolCallWithArgs, getDefaultSessionDirPath, getHostQuestionnaire, getManifestFromPackageJson, getResourcePathKey, getTextOutput, holdProcessDescendants, holdProcessDescendantsResult, holderRuns as holderRuns$1, isCodexTokenInvalidationError, isGitProvisionError, isGitUnavailableError, isSerializedMissingSessionCwdError, isStaleExtensionContextError, isStdoutTakenOver, isSyntheticPath, legacyWorkflowFilePaths, legacyWorkflowFilePatterns, loadConfig, loadedConfig, lockShared, normalizeWaitPolicy, operationSignal, parseSerializedCompactionError, parseSlashCommand, raceWithAbortSignal, readTaskOutputTail, redactCredentials, redactOAuthErrorText, rehydrateCompactionError, rehydrateMissingSessionCwdError, removedProviderMessage, replaceTabs, require_applyReviver, require_constants, require_debug, require_errors, require_identifiers, require_identity, require_ignore, require_line_counter, require_parse_options, require_resolve_end, require_resolve_props, require_stringifyComment, require_util_contains_newline, resolvePhysicalPath, resolvePhysicalPathAsync, resolveSchemaRef, resourceInternals, sanitizeMcpServers, sentinelsToAppend, serializeSessionMutation, sharedClockNow, sleep, spanElapsedMs, spawnHostProcess, startShellDeadline, taskOutcomeStatus, taskOutputText, taskStoppedForResume, thisProcess, truncateMiddle, validateGuidanceFields, windowsTemporaryFiles, withInstallLock, withLegacyPackageNames, withProgress, writeOutputFile, yieldToEventLoopIfSlow } from "./startup-0-0-Q3MWKUK4.js";
4
- import { NestedGitignore, NoUsableModelError, QuestionParamsSchema, STORAGE_JOIN_COMMAND, TaskToolError, WorkspaceBindingError, WorkspaceConfigError, WorkspaceDriftError, WorkspaceGitError, WorkspaceRestoreError, WorkspaceSandboxError, WorkspaceSnapshotError, WorkspaceTimeoutError, addResource, attachCleanupCause, cancelPausedOwnerTasks, computeFocusedOptionHasPreview, createAccumulator, createProviderAlias, deferRestorePhase, formatAnswerScalar, getBuiltinExtensionEntryLabel, getCommandEnv, getLoaderAgentDirs, getToolEnv, getToolPath, getVirtualModules, gitInstallCommand, gitignoreMatcher, hasLazyBuiltinSpec, isContentFilterRefusal, isNativeBuiltinExtensionPath, isOfflineModeEnabled, isProviderCredentialRejection, isRetryableModelFailure, isRetryableSameModelFailure, isSafetyRefusalFailure, isSourceBuiltinExtensionPath, isUnrecognizedModelFailure, isWorkspaceBindingError, isWorkspaceError, isWorkspaceGitError, isWorkspaceRestoreError, isWorkspaceSnapshotError, loadVirtualModules, normalizeModelFailureSignal, normalizeModelProvider, normalizeProviderKeys, noteRestoreFetch, prewarmModelApi, readInlineCaret, readInlineDraft, registerLazyBuiltin, requestedThinkingLevelForModelSwitch, require_int as require_int$1, require_int$1 as require_int, require_log, require_re, require_timestamp, require_toJS, require_trim_comparator_whitespace, require_util_flow_indent_check, require_util_map_includes, require_visit, resolveResourcePath, routeKey, runCallback, sessionLifecycleCreation, settingsWriteOwner, skillUri, startupRegistrationTokens, subagentsLazyBuiltinSpec, timeRestorePhase, toResolvedPaths, trackAdmittedAgentTask, trackTranspileCacheWrite, unreadablePathError, unwritablePathError, waitResultTail, withInlineDraft } from "./startup-0-1-M6OWAYHH.js";
3
+ import { BUILTIN_PATH_PREFIX, BlueprintInvalidError, COMMAND_DETAIL_TAIL_BYTES, DEFAULT_THINKING_LEVEL, FILE_KINDS, FILE_PATTERNS, FORKED_PACKAGE_WORKSPACE_DIRS, GitUnavailableError, HOST, NETWORK_TIMEOUT_MS, POST_LOGOUT_AUTH_CHECK_TIMEOUT_MS, RESOURCE_TYPES, ROW_INTENT_META, THINKING_LEVELS, TYPEBOX_SUBPATHS, TaskCleanupError, VisualLinePreview, asyncScope, bindSavedReadLines, canWatchProcessUntilHostDies, cancelReasonText, containProcessTree, conventionDirsForResource, createBatchedCanonicalizePathAsync, createGitEnvironment, createSyntheticSourceInfo, createTypeScriptSourceSpecifierTransform, emitProgress, experimentalToolSamplingProperty, findPreferredAvailableModel, forkedPackageExportAliases, formatNoApiKeyFoundMessage, formatSize, formatTimeoutSeconds, formatTokenCount, formatToolCallWithArgs, getDefaultSessionDirPath, getHostQuestionnaire, getManifestFromPackageJson, getResourcePathKey, getTextOutput, holdProcessDescendants, holdProcessDescendantsResult, holderRuns as holderRuns$1, isCodexTokenInvalidationError, isGitProvisionError, isGitUnavailableError, isSerializedMissingSessionCwdError, isStaleExtensionContextError, isStdoutTakenOver, isSyntheticPath, legacyWorkflowFilePaths, legacyWorkflowFilePatterns, loadConfig, loadedConfig, lockNamesLocalHolder, lockShared, normalizeWaitPolicy, operationSignal, parseSerializedCompactionError, parseSlashCommand, raceWithAbortSignal, readTaskOutputTail, redactCredentials, redactOAuthErrorText, rehydrateCompactionError, rehydrateMissingSessionCwdError, removedProviderMessage, replaceTabs, require_applyReviver, require_constants, require_debug, require_errors, require_identifiers, require_identity, require_ignore, require_line_counter, require_parse_options, require_resolve_end, require_resolve_props, require_stringifyComment, require_util_contains_newline, resolvePhysicalPath, resolvePhysicalPathAsync, resolveSchemaRef, resourceInternals, sanitizeMcpServers, sentinelsToAppend, serializeSessionMutation, sharedClockNow, sleep, spanElapsedMs, spawnContainedProcess, spawnHostProcess, startShellDeadline, takeOverDeadHolderAsync, taskOutcomeStatus, taskOutputText, taskStoppedForResume, thisProcess, truncateMiddle, validateGuidanceFields, watchProcessUntilHostDies, windowsTemporaryFiles, withInstallLock, withLegacyPackageNames, withProgress, writeOutputFile, yieldToEventLoopIfSlow } from "./startup-0-0-ERMIDHQT.js";
4
+ import { NestedGitignore, NoUsableModelError, QuestionParamsSchema, STORAGE_JOIN_COMMAND, TaskToolError, WorkspaceBindingError, WorkspaceConfigError, WorkspaceDriftError, WorkspaceGitError, WorkspaceRestoreError, WorkspaceSandboxError, WorkspaceSnapshotError, WorkspaceTimeoutError, addResource, attachCleanupCause, cancelPausedOwnerTasks, computeFocusedOptionHasPreview, createAccumulator, createProviderAlias, deferRestorePhase, failedProviderAccount, formatAnswerScalar, getBuiltinExtensionEntryLabel, getCommandEnv, getLoaderAgentDirs, getToolEnv, getToolPath, getVirtualModules, gitInstallCommand, gitignoreMatcher, hasLazyBuiltinSpec, isContentFilterRefusal, isNativeBuiltinExtensionPath, isOfflineModeEnabled, isProviderCredentialRejection, isRetryableModelFailure, isRetryableSameModelFailure, isSafetyRefusalFailure, isSourceBuiltinExtensionPath, isUnrecognizedModelFailure, isWorkspaceBindingError, isWorkspaceError, isWorkspaceGitError, isWorkspaceRestoreError, isWorkspaceSnapshotError, loadVirtualModules, lockSharedWithHolder, normalizeModelFailureSignal, normalizeModelProvider, normalizeProviderKeys, noteRestoreFetch, prewarmModelApi, providerAccount, readInlineCaret, readInlineDraft, registerLazyBuiltin, reportWorktreeLockProgress, requestedThinkingLevelForModelSwitch, require_int as require_int$1, require_int$1 as require_int, require_log, require_re, require_timestamp, require_toJS, require_trim_comparator_whitespace, require_util_flow_indent_check, require_util_map_includes, require_visit, resolveResourcePath, routeKey, runCallback, sessionLifecycleCreation, settingsWriteOwner, skillUri, startupRegistrationTokens, subagentsLazyBuiltinSpec, timeRestorePhase, toResolvedPaths, trackAdmittedAgentTask, trackTranspileCacheWrite, unreadablePathError, unwritablePathError, waitResultTail, withInlineDraft } from "./startup-0-1-RTASI3HG.js";
5
5
  import { TerminalTextSanitizer, graphemeAt, keyHint, loadThemeFromContent, resolveColorMode, singleLineDisplayText, terminalDisplayText } from "./p2-shell-main-B2WIALFD.js";
6
- import { failureDebugFields, redactUrlCredentials, releaseLock, renameReplacingAsync, renameWithRetry, reportDebugAsync, takeTakeoverMutexAsync } from "./p1b-elig-TVB5CBLL.js";
7
- import { LONG_STREAM_CUT_ADVICE, ModelConfig, ResumePreconditionError, TaskSupervisor, assertSessionOpen, assertWorkspace, automaticWaitBudgetMs, buildFallbackModel, buildQuestionnaireResponse, buildToolResult, classifyRepository, findSourceInfoForPath, getCallableTools, getDefaultSourceInfoForPath, getShellConfigAsync, getShellEnvAsync, importAfterEvaluation, installHostModuleBridge, isLongStreamCut, isWorkspace, nextRetryDecision, observeAccountCatalog, prepareSourceEntries, prepareSourceEntry, recordProviderSuccess, recordedRepo, reduce, registerSourceBuiltinLoad, repeatsLongStreamCut, require_Node, require_anchors, require_directives, require_semver as require_semver$1, runCommand, runCommandCapture, runCommandSync, runWithConcurrency, sessionGenerationClosing, sessionLifetime, summarizeQuestions, taskOwnTranscriptEntries, trackSessionWork, transformTemplate, validateQuestionnaire, withDiscoveredModels, withPersonalizedCatalog, withRemoteCatalog } from "./startup-0-2-2HUMCPKX.js";
8
- import { DEFAULT_WORKTREE_SNAPSHOT_SETTINGS, FileModelsStore, InMemoryCodingAgentModelsStore, admitProviderStream, completeUtf8PrefixLength, computeEnvironmentHash, fallbackKey, getBaseDirForScope, getBaseDirsForScope, getConfigValueEnvVarNames, getGitInstallPath, getGitInstallRoot, getHomeDir, getInstalledGitInstallPath, getNpmInstallRoot, isCommandConfigValue, isConfigValueConfigured, llamaExtension, parseGitUrl, require_Alias, require_Scalar, require_compare, require_compare_build, require_inc, require_major, require_minor, require_parse, require_patch, resolveCliModel, resolveConfigValue, resolveFallbackModel as resolveFallbackModel$1, resolveFallbackModelWithoutCredentials, resolveHeadersOrThrow, resolveHeadersOrThrowAsync, resolveManagerPath, resolvePathFromBase, resolveWorktreeSnapshotSettings, sha256Hex as sha256Hex$1, snapshotBlob, splitFallbackModel, waitFor } from "./startup-0-3-4ZYBYQNM.js";
6
+ import { failureDebugFields, lockHolderAsync, processMayRunAsync, processStartTokenAsync, redactUrlCredentials, releaseLock, renameReplacingAsync, renameWithRetry, reportDebugAsync, takeTakeoverMutexAsync } from "./p1b-elig-BY2G5BUE.js";
7
+ import { LONG_STREAM_CUT_ADVICE, ModelConfig, ResumePreconditionError, TaskSupervisor, assertSessionOpen, assertWorkspace, automaticWaitBudgetMs, buildFallbackModel, buildQuestionnaireResponse, buildToolResult, classifyRepository, findSourceInfoForPath, getCallableTools, getDefaultSourceInfoForPath, getShellConfigAsync, getShellEnvAsync, hasBlockingAccountLimit, importAfterEvaluation, installHostModuleBridge, isLongStreamCut, isWorkspace, nextRetryDecision, observeAccountCatalog, overCapServerRetryDelay, prepareSourceEntries, prepareSourceEntry, providerCooldownMs, providerUnavailableMs, recordedRepo, reduce, registerSourceBuiltinLoad, repeatsLongStreamCut, require_Node, require_anchors, require_directives, require_semver as require_semver$1, runCommand, runCommandCapture, runCommandSync, runWithConcurrency, sessionGenerationClosing, sessionLifetime, summarizeQuestions, taskOwnTranscriptEntries, trackSessionWork, transformTemplate, validateQuestionnaire, withDiscoveredModels, withPersonalizedCatalog, withRemoteCatalog } from "./startup-0-2-YZZOC22D.js";
8
+ import { DEFAULT_WORKTREE_SNAPSHOT_SETTINGS, FileModelsStore, InMemoryCodingAgentModelsStore, admitProviderStream, completeUtf8PrefixLength, computeEnvironmentHash, fallbackKey, getBaseDirForScope, getBaseDirsForScope, getConfigValueEnvVarNames, getGitInstallPath, getGitInstallRoot, getHomeDir, getInstalledGitInstallPath, getNpmInstallRoot, isCommandConfigValue, isConfigValueConfigured, llamaExtension, parseGitUrl, require_Alias, require_Scalar, require_compare, require_compare_build, require_inc, require_major, require_minor, require_parse, require_patch, resolveCliModel, resolveConfigValue, resolveFallbackModel as resolveFallbackModel$1, resolveFallbackModelWithoutCredentials, resolveHeadersOrThrow, resolveHeadersOrThrowAsync, resolveManagerPath, resolvePathFromBase, resolveWorktreeSnapshotSettings, sha256Hex as sha256Hex$1, snapshotBlob, splitFallbackModel, waitFor } from "./startup-0-3-DE2NCS6A.js";
9
9
  import { SESSION_HISTORY_PAGE_BYTES } from "./settings-startup-HXQLSUWM.js";
10
10
  import { AuthStorage, OutputAccumulator, ReadOnlyAuthStorage, TOOL_BLOCK_LIMITS, ToolBlock, ToolBlockMarkdown, ToolBlockRecords, accountSnapshotVersion, applyAutoloadDisabledNamePatterns, applyAutoloadDisabledPatterns, applyCompactorModelOverride, applyExtension, applyModelOverride, applyModelsJson, applyNamePatterns, applyPatterns, assertRestorePathBudget, assertWorkspaceGitAvailable, buildQuestionnaire, canonicalizeWorktreePathAsync, captureIndexPath, checkoutStoreIdOf, codemode_default, collapseToolBlockLines, composeApiKeyAuth, composeOAuthAuth, configuredApiKey, configuredHeaders, containsAuthConfig, containsCredential, containsCredentialValue, defaultWorktreeSnapshotStoreDir, formatModelLabel, formatModelReferenceLabel, gitOutput, hasGlobPattern, isEnabledByOverrides, isOverridePattern, jsonParser, pathExists as pathExists$1, rawModelHeaders, repositoryIdOf, repositoryIdsOf, require_bool as require_bool$1, require_bool$1 as require_bool, require_clean, require_coerce, require_compare_loose, require_createNode, require_diff, require_eq, require_float as require_float$1, require_float$1 as require_float, require_gt, require_gte, require_lt, require_lte, require_merge, require_neq, require_null, require_prerelease, require_rcompare, require_resolve_block_scalar, require_resolve_flow_scalar, require_rsort, require_sort, require_stringifyString, require_truncate, require_valid as require_valid$1, runWorkspaceGit, sameRemote, sharedRepositoryIdOf, sharedRepositoryIdsOf, splitPatterns, stagingWorktreeName, toLlmContent, toPosixPath as toPosixPath$2 } from "./startup-0-4-ZMJV547D.js";
11
11
  import { SETTINGS_DEFAULTS } from "./p2-common-YLSYXMDQ.js";
@@ -19,6 +19,7 @@ import * as path from "node:path";
19
19
  import { basename as basename$1, dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, posix, relative as relative$1, resolve as resolve$1, sep as sep$1, toNamespacedPath } from "node:path";
20
20
  import { fileURLToPath, pathToFileURL } from "node:url";
21
21
  import { execFile, spawn } from "node:child_process";
22
+ import { setLongTimeout, setWallTimeoutAt, sleepFor } from "../__atomic_timers/index.js";
22
23
  import { canonicalizePathAsync } from "../utils/canonical-path.js";
23
24
  import { pathExists } from "../utils/path-exists.js";
24
25
  import * as fs from "node:fs";
@@ -28,7 +29,7 @@ import { Container, Spacer, Text, decodeKittyPrintable, getKeybindings, stripTer
28
29
  import chalk from "chalk";
29
30
  import { StorageAdapterLoadError, findStorageWriteLockTimeoutError } from "../core/storage/errors.js";
30
31
  import * as crypto$1 from "node:crypto";
31
- import { createHash, randomUUID } from "node:crypto";
32
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
32
33
  import { isDeepStrictEqual, promisify, stripVTControlCharacters } from "node:util";
33
34
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
34
35
  import { clampThinkingLevel, getApiProvider, getSupportedThinkingLevels, isContextOverflow, modelsAreEqual, normalizeContext as normalizeContext$1, streamOpenAICodexResponses, streamOpenAIResponses, streamSimple } from "@bastani/atomic-ai/compat";
@@ -36,6 +37,8 @@ import { AsyncLocalStorage } from "node:async_hooks";
36
37
  import { snapshotBlobHashes } from "../core/worktree-snapshot/blob-store.js";
37
38
  import { loadStorageAdapter, secretFilePath } from "../core/storage/provider.js";
38
39
  import { memoizeAsync, memoizeAsyncByKey } from "../utils/memoize-async.js";
40
+ import { DEFAULT_MAX_RETRY_DELAY_MS } from "@bastani/atomic-ai/utils/provider-retry";
41
+ import { withProviderTimeout } from "@bastani/atomic-ai/utils/provider-waits/timeout";
39
42
  import { discoverGitHubCopilotModels, parseGitHubCopilotDiscoveredModels, readGitHubCopilotAccountModelList } from "@bastani/atomic-ai/providers/github-copilot";
40
43
  import { defaultSessionDatabasePath, storageHomeDir } from "../core/storage/file-identity.js";
41
44
  import { Type as Type$1 } from "@bastani/atomic-ai/utils/typebox/index";
@@ -212,10 +215,10 @@ async function taskkillTree(pid, deadline, isAlive) {
212
215
  return;
213
216
  }
214
217
  const done = () => {
215
- clearTimeout(bound);
218
+ bound.clear();
216
219
  resolve(output.split(/\r?\n/).map((line) => Number(/\d+/.exec(line)?.[0])).filter((id) => Number.isInteger(id) && id !== process.pid));
217
220
  };
218
- const bound = setTimeout(done, Math.max(0, deadline - Date.now()));
221
+ const bound = setWallTimeoutAt(done, deadline);
219
222
  taskkill.stdout?.on("data", (chunk) => {
220
223
  output += chunk.toString("utf8");
221
224
  });
@@ -319,12 +322,23 @@ async function runGit(args, options) {
319
322
  const env = environmentOf(executable);
320
323
  Object.assign(env, options.env);
321
324
  if (options.nonInteractive && !env.GIT_SSH_COMMAND && !env.GIT_SSH && !await configuresSshCommand(options)) env.GIT_SSH_COMMAND = `ssh -o BatchMode=yes -o ConnectTimeout=15`;
322
- const detached = options.nonInteractive === true && process.platform !== "win32";
325
+ const publishing = options.onPublicationChild !== void 0;
326
+ const watched = publishing && canWatchProcessUntilHostDies();
327
+ const detached = (options.nonInteractive === true || watched) && process.platform !== "win32";
323
328
  const argv = [
324
329
  ...BASE_CONFIG,
325
330
  ...options.neutral ? NEUTRAL_CONVERSION_CONFIG : [],
326
331
  ...args
327
332
  ];
333
+ const gated = publishing && process.platform !== "win32";
334
+ const command = gated ? "/bin/sh" : executable.path;
335
+ const commandArgs = gated ? [
336
+ "-c",
337
+ "IFS= read -r start && [ \"$start\" = go ] || exit 1\nexec \"$@\"",
338
+ "atomic-worktree-move",
339
+ executable.path,
340
+ ...argv
341
+ ] : argv;
328
342
  const spawnFailure = async (error) => (error.code === "ENOENT" || error.code === "EACCES") && await isDirectory(options.cwd) ? await unreadableDirectory(options.cwd) ?? new GitUnavailableError({
329
343
  code: "not-installed",
330
344
  platform: process.platform,
@@ -341,27 +355,43 @@ async function runGit(args, options) {
341
355
  exitCode: null,
342
356
  detail: await pathExists(options.cwd) ? firstLine(error.message) : "the working directory does not exist"
343
357
  }, error);
358
+ const launch = {
359
+ cwd: options.cwd,
360
+ env,
361
+ stdio: "pipe",
362
+ detached,
363
+ endWithParent: publishing && !watched
364
+ };
365
+ const contained = publishing && process.platform === "win32" ? await spawnContainedProcess(executable.path, argv, launch).catch(async (error) => {
366
+ throw await spawnFailure(error);
367
+ }) : void 0;
344
368
  return new Promise((resolve, reject) => {
345
369
  let child;
346
370
  try {
347
- child = spawnHostProcess(executable.path, argv, {
348
- cwd: options.cwd,
349
- env,
350
- stdio: "pipe",
351
- detached
352
- });
371
+ child = contained ?? spawnHostProcess(command, commandArgs, launch);
353
372
  } catch (error) {
354
373
  spawnFailure(error).then(reject, reject);
355
374
  return;
356
375
  }
357
- const tree = child.pid === void 0 ? void 0 : containProcessTree(child.pid);
376
+ const pid = child.pid;
377
+ const tree = contained !== void 0 || pid === void 0 ? void 0 : containProcessTree(pid);
378
+ const deathWatch = watched && pid !== void 0 ? watchProcessUntilHostDies(pid) : void 0;
379
+ if (deathWatch !== void 0) child.once("exit", () => deathWatch.release());
380
+ let publicationRecorded = false;
381
+ const recorded = pid === void 0 ? void 0 : options.onPublicationChild?.(pid).then(() => {
382
+ publicationRecorded = true;
383
+ }, () => {});
358
384
  const stdout = [];
359
385
  const stderr = [];
360
386
  let settled = false;
361
387
  const onAbort = () => {
362
388
  if (settled) return;
363
389
  settled = true;
364
- stopCommand(child, detached, tree).then(() => reject(options.signal?.reason));
390
+ contained?.endTree();
391
+ stopCommand(child, detached, tree).then(async () => {
392
+ await recorded;
393
+ reject(options.signal?.reason);
394
+ });
365
395
  };
366
396
  options.signal?.addEventListener("abort", onAbort, { once: true });
367
397
  const finish = (action) => {
@@ -373,8 +403,9 @@ async function runGit(args, options) {
373
403
  child.stdout?.on("data", (chunk) => stdout.push(chunk));
374
404
  child.stderr?.on("data", (chunk) => stderr.push(chunk));
375
405
  child.on("error", (error) => finish(() => {
406
+ deathWatch?.release();
376
407
  tree?.close();
377
- spawnFailure(error).then(reject, reject);
408
+ Promise.resolve(recorded).then(() => spawnFailure(error)).then(reject, reject);
378
409
  }));
379
410
  child.stdin?.on("error", exitStatusReportsClosedInput);
380
411
  child.on("close", (code) => finish(() => {
@@ -383,7 +414,9 @@ async function runGit(args, options) {
383
414
  stderr: Buffer.concat(stderr).toString("utf8"),
384
415
  exitCode: code ?? -1
385
416
  };
386
- endTree(tree).then(() => {
417
+ contained?.endTree();
418
+ endTree(tree).then(async () => {
419
+ await recorded;
387
420
  if (code === 0 || code !== null && options.allowExitCodes?.includes(code)) resolve(result);
388
421
  else reject(new WorkspaceGitError({
389
422
  operation: gitOperation(args),
@@ -393,7 +426,8 @@ async function runGit(args, options) {
393
426
  }));
394
427
  });
395
428
  }));
396
- child.stdin?.end(options.input === void 0 ? void 0 : options.input);
429
+ if (gated) Promise.resolve(recorded).then(() => child.stdin?.end(publicationRecorded ? "go\n" : void 0));
430
+ else child.stdin?.end(options.input === void 0 ? void 0 : options.input);
397
431
  });
398
432
  }
399
433
  /** Runs a Git command and returns its standard output as UTF-8 text without the trailing newline. */
@@ -2308,6 +2342,141 @@ async function captureCheckout(locate, settings, options, wroteBy) {
2308
2342
  };
2309
2343
  });
2310
2344
  }
2345
+ // dist/core/worktree-snapshot/publication-fence.js
2346
+ /** The window for the host-death guardian to finish an orphan before reporting a blocked publication. */
2347
+ const MOVE_EXIT_WAIT_MS = 5e3;
2348
+ const MOVE_EXIT_POLL_MS = 50;
2349
+ async function locateDestination(target) {
2350
+ const existing = await realpath(target).catch((error) => {
2351
+ if (error.code !== "ENOENT") throw unreadablePathError(target, error);
2352
+ });
2353
+ const parent = existing === void 0 ? await canonicalizeWorktreePathAsync(dirname$1(target)) : dirname$1(existing);
2354
+ const name = basename$1(existing ?? target);
2355
+ const fenceDirectory = name.toUpperCase() === ".ATOMIC-FENCE" ? ".atomic-fence-alt" : ".atomic-fence";
2356
+ return {
2357
+ file: join$1(parent, fenceDirectory, name),
2358
+ targetIdentity: existing === void 0 ? void 0 : await lockHolderAsync(existing)
2359
+ };
2360
+ }
2361
+ async function createFence(file, fence) {
2362
+ const directory = dirname$1(file);
2363
+ for (let attempt = 1;; attempt++) {
2364
+ await mkdir(directory, {
2365
+ recursive: true,
2366
+ mode: 448
2367
+ });
2368
+ try {
2369
+ if (!(await lstat(directory)).isDirectory()) throw new Error(`not a publication fence directory: ${directory}`);
2370
+ await writeFile(file, JSON.stringify(fence), {
2371
+ flag: "wx",
2372
+ mode: 384
2373
+ });
2374
+ return;
2375
+ } catch (error) {
2376
+ if (attempt === 4 || error.code !== "ENOENT") throw error;
2377
+ }
2378
+ }
2379
+ }
2380
+ async function removeFence(file) {
2381
+ await rm(file, { force: true });
2382
+ await rmdir(dirname$1(file)).catch(() => {});
2383
+ }
2384
+ async function physicalStoreIdentity(store) {
2385
+ const { dev, ino, birthtimeNs } = await stat(store, { bigint: true });
2386
+ return `${dev}:${ino}:${birthtimeNs}`;
2387
+ }
2388
+ async function readFence(file) {
2389
+ let text;
2390
+ try {
2391
+ if (!(await lstat(dirname$1(file))).isDirectory() || !(await lstat(file)).isFile()) throw new Error(`not a publication fence: ${file}`);
2392
+ text = await readFile(file, "utf8");
2393
+ } catch (error) {
2394
+ if (error.code === "ENOENT") return void 0;
2395
+ throw error;
2396
+ }
2397
+ const value = JSON.parse(text);
2398
+ if (typeof value !== "object" || value === null) throw new Error("unreadable worktree publication record");
2399
+ const record = value;
2400
+ const git = record.git;
2401
+ if (typeof record.storeIdentity !== "string" || typeof record.staging !== "string" || git !== void 0 && (typeof git !== "object" || git === null || typeof git.host !== "string" || !Number.isSafeInteger(git.pid) || git.pid <= 0 || git.started !== void 0 && typeof git.started !== "string")) throw new Error("unreadable worktree publication record");
2402
+ return record;
2403
+ }
2404
+ async function mayStillMove(git) {
2405
+ return git === void 0 || processMayRunAsync(git);
2406
+ }
2407
+ /** Under the repository lock, don't sweep a staging worktree out from under its possible orphaned Git move. */
2408
+ async function cleanInterruptedPublication(store, target, staging, clean) {
2409
+ const { file } = await locateDestination(target);
2410
+ const record = await readFence(file);
2411
+ if (record?.staging !== staging) return clean(false);
2412
+ if (record.storeIdentity !== await physicalStoreIdentity(store)) throw new Error("the interrupted move's repository has changed");
2413
+ if (await mayStillMove(record.git)) throw new Error("the interrupted Git worktree move may still be running");
2414
+ const result = await clean(true);
2415
+ await removeFence(file);
2416
+ return result;
2417
+ }
2418
+ /**
2419
+ * Fence the target before Git may write it. The caller holds the repository lock and rechecks the destination after
2420
+ * admission. An orphan must be gone, not just signaled, before we remove a previous fence and publish to that path.
2421
+ */
2422
+ async function withPublicationFence(store, target, staging, signal, onWait, action) {
2423
+ const [{ file, targetIdentity }, storeIdentity] = await Promise.all([locateDestination(target), physicalStoreIdentity(store)]);
2424
+ const message = `Waiting for a previous Git worktree move into ${target} to stop`;
2425
+ const blocked = (cause) => new WorkspaceGitError({
2426
+ operation: "worktree move",
2427
+ cwd: target,
2428
+ exitCode: null,
2429
+ detail: `cannot verify that a previous Git worktree move has stopped; use a fresh target or check the process before removing ${file}`
2430
+ }, cause instanceof Error ? cause : void 0);
2431
+ const previous = await readFence(file).catch((error) => {
2432
+ throw blocked(error);
2433
+ });
2434
+ if (previous !== void 0) {
2435
+ if (previous.storeIdentity !== storeIdentity || previous.git === void 0 || previous.git.host !== hostname()) throw blocked();
2436
+ const deadline = performance.now() + MOVE_EXIT_WAIT_MS;
2437
+ let announced = false;
2438
+ while (await mayStillMove(previous.git)) {
2439
+ signal?.throwIfAborted();
2440
+ if (performance.now() >= deadline) throw blocked();
2441
+ if (!announced) {
2442
+ announced = true;
2443
+ onWait(message);
2444
+ }
2445
+ await setTimeout$1(MOVE_EXIT_POLL_MS);
2446
+ }
2447
+ await rm(file);
2448
+ }
2449
+ signal?.throwIfAborted();
2450
+ await createFence(file, {
2451
+ storeIdentity,
2452
+ staging
2453
+ });
2454
+ try {
2455
+ return await action(async (pid) => {
2456
+ const git = {
2457
+ host: hostname(),
2458
+ pid,
2459
+ started: await processStartTokenAsync(pid)
2460
+ };
2461
+ const temporary = join$1(dirname$1(file), `.writing-${randomBytes(16).toString("hex")}`);
2462
+ try {
2463
+ await writeFile(temporary, JSON.stringify({
2464
+ storeIdentity,
2465
+ staging,
2466
+ git
2467
+ }), {
2468
+ flag: "wx",
2469
+ mode: 384
2470
+ });
2471
+ await renameWithRetry(temporary, file);
2472
+ } finally {
2473
+ await rm(temporary, { force: true }).catch(() => {});
2474
+ }
2475
+ }, targetIdentity);
2476
+ } finally {
2477
+ await removeFence(file).catch(() => {});
2478
+ }
2479
+ }
2311
2480
  // dist/core/worktree-snapshot/records.js
2312
2481
  const OBJECT_ID$1 = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
2313
2482
  const BLOB_HASH = /^[0-9a-f]{64}$/;
@@ -2554,10 +2723,12 @@ async function withProcessRepositoryLock(store, action) {
2554
2723
  if (repositoryLocks.get(store) === chained) repositoryLocks.delete(store);
2555
2724
  }
2556
2725
  }
2557
- /** The repository lock's constants: a stopped process loses it after 30 seconds; a held one is checked every 50 ms. */
2726
+ /** A lock without a locally identifiable holder keeps its 30-second heartbeat timeout (#6800). */
2558
2727
  const REPOSITORY_LOCK_STALE_MS = 3e4;
2559
2728
  const REPOSITORY_LOCK_UPDATE_MS = 1e4;
2560
2729
  const REPOSITORY_LOCK_POLL_MS = 50;
2730
+ /** Don't announce brief contention, such as two restores entering the store just to read its refs. */
2731
+ const REPOSITORY_LOCK_NOTICE_MS = 500;
2561
2732
  /**
2562
2733
  * Whether creating the lock directory failed only for a moment: Windows refuses with EPERM to create a directory
2563
2734
  * another process has just removed while a third still has it open, as other waiters' checks of the lock do.
@@ -2570,8 +2741,9 @@ __name(refusedForAMoment$2, "refusedForAMoment");
2570
2741
  * Serializes work on one shared object store, in this process and across processes (#4951): creating the store,
2571
2742
  * configuring its remotes, fetching into it and updating its refs. Git's own locks fail rather than wait, so two
2572
2743
  * processes doing either at once would fail one of them. Waiters in this process queue behind each other; across
2573
- * processes, the store's lock file `<store>.lock` is polled until it is free or its holder stopped refreshing it. On
2574
- * Windows a lock directory refused with EPERM is polled too, for up to {@link REPOSITORY_LOCK_REFUSED_MS} on end.
2744
+ * processes, `<store>.lock` is polled until it is free or its holder is proven gone. A lock without a locally
2745
+ * identifiable holder still ages out. On Windows a lock directory refused with EPERM is polled too, for up to
2746
+ * {@link REPOSITORY_LOCK_REFUSED_MS} on end.
2575
2747
  */
2576
2748
  function withRepositoryLock$1(store, snapshotId, signal, action) {
2577
2749
  return withProcessRepositoryLock(store, async () => {
@@ -2588,23 +2760,32 @@ __name(withRepositoryLock$1, "withRepositoryLock");
2588
2760
  async function lockRepository(store, snapshotId, signal) {
2589
2761
  const repositories = dirname$1(store);
2590
2762
  await writing(repositories, snapshotId, () => mkdir(repositories, { recursive: true }));
2763
+ const lockPath = `${store}.lock`;
2591
2764
  let refusedSince;
2765
+ let waitingSince;
2766
+ let announced = false;
2592
2767
  for (;;) {
2593
2768
  signal?.throwIfAborted();
2594
2769
  try {
2595
- return await lockShared(store, {
2770
+ return await lockSharedWithHolder(store, {
2596
2771
  realpath: false,
2597
2772
  stale: REPOSITORY_LOCK_STALE_MS,
2598
2773
  update: REPOSITORY_LOCK_UPDATE_MS,
2599
- retries: 0,
2600
- onCompromised: () => {}
2774
+ retries: 0
2601
2775
  });
2602
2776
  } catch (error) {
2603
2777
  if (refusedForAMoment$2(error)) {
2604
2778
  refusedSince ??= Date.now();
2605
- if (Date.now() - refusedSince >= 1e4) throw unwritablePathError(`${store}.lock`, snapshotId, error);
2606
- } else if (error.code === "ELOCKED") refusedSince = void 0;
2607
- else throw unwritablePathError(`${store}.lock`, snapshotId, error);
2779
+ if (Date.now() - refusedSince >= 1e4) throw unwritablePathError(lockPath, snapshotId, error);
2780
+ } else if (error.code === "ELOCKED") {
2781
+ refusedSince = void 0;
2782
+ if (await takeOverDeadHolderAsync(lockPath)) continue;
2783
+ waitingSince ??= performance.now();
2784
+ if (!announced && performance.now() - waitingSince >= REPOSITORY_LOCK_NOTICE_MS) {
2785
+ announced = true;
2786
+ reportWorktreeLockProgress(`Waiting for another Atomic process restoring this repository (${store})`);
2787
+ }
2788
+ } else throw unwritablePathError(lockPath, snapshotId, error);
2608
2789
  }
2609
2790
  await setTimeout$1(REPOSITORY_LOCK_POLL_MS);
2610
2791
  }
@@ -3159,7 +3340,10 @@ async function sweepRestoreRecords(storeDir, warn, signal) {
3159
3340
  const record = JSON.parse(await readFile(recordPath, "utf8"));
3160
3341
  if (!isRestoreRecord(record, storeDir, match[1])) throw new Error("Invalid restore crash record");
3161
3342
  warningPath = record.staging;
3162
- await cleanUpRestore(record, null, signal).catch((cause) => {
3343
+ await cleanUpRestore(record, null, signal, () => cleanInterruptedPublication(record.store, record.target, record.staging, async (interrupted) => {
3344
+ if (interrupted && await repairInterruptedMove(record, signal)) return [];
3345
+ return cleanRestoreRecord(record, signal);
3346
+ })).catch((cause) => {
3163
3347
  warningPath = keptPath(cause, record, false);
3164
3348
  throw cause;
3165
3349
  });
@@ -3186,6 +3370,46 @@ async function sweepRestoreRecords(storeDir, warn, signal) {
3186
3370
  }
3187
3371
  }
3188
3372
  }
3373
+ /** If Git moved the exact staging directory but died before registering its new path, preserve it and repair the link. */
3374
+ async function repairInterruptedMove(record, signal) {
3375
+ const found = await directoryIdentity$1(record.target);
3376
+ if (found === void 0 || record.identity === void 0 || !sameIdentity(found, record.identity)) return false;
3377
+ try {
3378
+ const admin = await worktreeAdminDir(record.target);
3379
+ const worktrees = await storeAdminDirs(record.store);
3380
+ if (admin === void 0 || worktrees === void 0 || !includesPath([worktrees], dirname$1(admin))) throw new WorkspaceRestoreError("unsafe-target", {
3381
+ snapshotId: null,
3382
+ target: record.target,
3383
+ reason: "not-restored"
3384
+ });
3385
+ const git = {
3386
+ cwd: dirname$1(record.store),
3387
+ env: { GIT_DIR: record.store },
3388
+ signal
3389
+ };
3390
+ const target = await physicalPath(record.target);
3391
+ if (!includesPath(await registeredWorktrees(git), target)) {
3392
+ await runGit([
3393
+ "worktree",
3394
+ "repair",
3395
+ target
3396
+ ], git);
3397
+ if (!includesPath(await registeredWorktrees(git), target)) throw new WorkspaceGitError({
3398
+ operation: "worktree repair",
3399
+ cwd: target,
3400
+ exitCode: null,
3401
+ detail: "the checkout is still not registered"
3402
+ });
3403
+ }
3404
+ return true;
3405
+ } catch (cause) {
3406
+ if (cause instanceof Error) Object.defineProperty(cause, "keptAt", {
3407
+ value: record.target,
3408
+ configurable: true
3409
+ });
3410
+ throw cause;
3411
+ }
3412
+ }
3189
3413
  /**
3190
3414
  * Under the store lock, cleanup after a restore that failed or was stopped once it asked Git to move its worktree toward
3191
3415
  * the target (#4748): the worktree, at the target or nested in a directory that appeared there, is set aside like its
@@ -4857,7 +5081,7 @@ async function publishWorktree(publish) {
4857
5081
  }
4858
5082
  measured = await timeRestorePhase("verify", () => verifyRestoredTree(staging, path, head, tree, publish.verify, scratch, snapshotId, signal));
4859
5083
  assertActive();
4860
- await timeRestorePhase("publish", () => withRepositoryLock$1(store, snapshotId, signal, () => moveIntoPlace(publish, record, snapshotId, moving)));
5084
+ await timeRestorePhase("publish", () => withRepositoryLock$1(store, snapshotId, signal, () => withPublicationFence(store, path, staging, signal, reportWorktreeLockProgress, (started, targetIdentity) => moveIntoPlace(publish, record, snapshotId, moving, started, targetIdentity))));
4861
5085
  assertActive();
4862
5086
  if (pending !== void 0 && deferred !== void 0) {
4863
5087
  const worktree = {
@@ -4897,7 +5121,7 @@ async function verifyRestoredTree(dir, target, head, tree, verify, scratch, snap
4897
5121
  * `moving` where the worktree may be: `unchecked` as Git is asked to move it, then `published` once it is registered at
4898
5122
  * that path, or `checked` once a nested move was refused.
4899
5123
  */
4900
- async function moveIntoPlace(publish, record, snapshotId, moving) {
5124
+ async function moveIntoPlace(publish, record, snapshotId, moving, onPublicationChild, targetIdentity) {
4901
5125
  const { git, path, signal } = publish;
4902
5126
  const { staging, createdTarget } = record;
4903
5127
  if (createdTarget) {
@@ -4906,7 +5130,14 @@ async function moveIntoPlace(publish, record, snapshotId, moving) {
4906
5130
  target: path,
4907
5131
  reason: "not-empty"
4908
5132
  });
4909
- } else await writing(path, snapshotId, () => rmdir(path));
5133
+ } else {
5134
+ if (targetIdentity === void 0 || await lockHolderAsync(path) !== targetIdentity) throw new WorkspaceRestoreError("unsafe-target", {
5135
+ snapshotId,
5136
+ target: path,
5137
+ reason: "not-empty"
5138
+ });
5139
+ await writing(path, snapshotId, () => rmdir(path));
5140
+ }
4910
5141
  signal?.throwIfAborted();
4911
5142
  moving("unchecked");
4912
5143
  await runGit([
@@ -4917,7 +5148,8 @@ async function moveIntoPlace(publish, record, snapshotId, moving) {
4917
5148
  path
4918
5149
  ], {
4919
5150
  ...git,
4920
- signal: void 0
5151
+ signal: void 0,
5152
+ onPublicationChild
4921
5153
  });
4922
5154
  const registered = await registeredWorktrees({
4923
5155
  ...git,
@@ -5375,6 +5607,7 @@ const LEASE_STALE_MS = 3e4;
5375
5607
  const LEASE_UPDATE_MS = 1e4;
5376
5608
  const POOL_LOCK_POLL_MS = 50;
5377
5609
  const POOL_LOCK_WAIT_MS = 6e4;
5610
+ const POOL_LOCK_NOTICE_MS = 500;
5378
5611
  /**
5379
5612
  * How long a lease of this host that names no start of its process keeps its slot without being refreshed while a
5380
5613
  * process of its id runs (#4990): such a lease, written where the start cannot be read or before #4990, cannot tell its
@@ -5535,20 +5768,22 @@ function refusedForAMoment$1(error, since) {
5535
5768
  return error.code === "EPERM" && process.platform === "win32" && Date.now() - since < 1e4;
5536
5769
  }
5537
5770
  __name(refusedForAMoment$1, "refusedForAMoment");
5538
- function lockHeldAndWaiting(error, wait, startedAt) {
5539
- return wait && error.code === "ELOCKED" && Date.now() - startedAt < POOL_LOCK_WAIT_MS;
5540
- }
5541
5771
  /**
5542
- * Locks `path` with the restore-record constants: a stopped process loses the lock after 30 seconds. `wait` retries a
5543
- * lock another process holds for up to 60 seconds with 50 ms polls, as when a slot's record is briefly being written.
5772
+ * Admission and slot-record locks identify their process so a dead local holder can be replaced before its heartbeat
5773
+ * expires. Session leases still use the heartbeat and the separate lease/grace rules. `wait` polls a busy lock for up
5774
+ * to 60 seconds; a dead lock can be reclaimed even when the caller would skip a busy slot.
5544
5775
  */
5545
- async function lockPath(path, wait, onLost, signal) {
5776
+ async function lockPath(path, kind, wait, onLost, signal) {
5777
+ const lock = kind === "lease" ? lockShared : lockSharedWithHolder;
5778
+ const lockDirectory = `${path}.lock`;
5546
5779
  const startedAt = Date.now();
5547
5780
  let refusedSince;
5781
+ let waitingSince;
5782
+ let announced = false;
5548
5783
  for (;;) {
5549
5784
  signal?.throwIfAborted();
5550
5785
  try {
5551
- return await lockShared(path, {
5786
+ return await lock(path, {
5552
5787
  realpath: false,
5553
5788
  stale: LEASE_STALE_MS,
5554
5789
  update: LEASE_UPDATE_MS,
@@ -5564,8 +5799,16 @@ async function lockPath(path, wait, onLost, signal) {
5564
5799
  } catch (error) {
5565
5800
  const since = refusedSince ?? Date.now();
5566
5801
  if (refusedForAMoment$1(error, since)) refusedSince = since;
5567
- else if (lockHeldAndWaiting(error, wait, startedAt)) refusedSince = void 0;
5568
- else throw error;
5802
+ else if (error.code === "ELOCKED") {
5803
+ refusedSince = void 0;
5804
+ if (kind !== "lease" && await takeOverDeadHolderAsync(lockDirectory)) continue;
5805
+ if (!wait || Date.now() - startedAt >= POOL_LOCK_WAIT_MS) throw error;
5806
+ waitingSince ??= performance.now();
5807
+ if (!announced && performance.now() - waitingSince >= POOL_LOCK_NOTICE_MS && await lockNamesLocalHolder(lockDirectory)) {
5808
+ announced = true;
5809
+ reportWorktreeLockProgress(`Waiting for another Atomic process to finish updating the worktree pool (${path})`);
5810
+ }
5811
+ } else throw error;
5569
5812
  }
5570
5813
  await setTimeout$1(POOL_LOCK_POLL_MS, void 0, { signal });
5571
5814
  }
@@ -5593,7 +5836,7 @@ async function readLockToken(file) {
5593
5836
  */
5594
5837
  async function withSlotLock(file, wait, action, signal) {
5595
5838
  let lost = false;
5596
- const unlock = await lockPath(file, wait, () => {
5839
+ const unlock = await lockPath(file, "slot", wait, () => {
5597
5840
  lost = true;
5598
5841
  }, signal);
5599
5842
  const token = randomUUID();
@@ -5681,7 +5924,7 @@ function lockLostError(file) {
5681
5924
  */
5682
5925
  async function leaseSlot(file, held, signal) {
5683
5926
  const lease = `${file}.${await ownLease()}.lease`;
5684
- const unlock = await lockPath(lease, false, () => {
5927
+ const unlock = await lockPath(lease, "lease", false, () => {
5685
5928
  held.compromised = true;
5686
5929
  }, signal);
5687
5930
  return () => unlock().catch(() => rm(`${lease}.lock`, {
@@ -5850,7 +6093,7 @@ async function admitPooledWorktree(admission, owner) {
5850
6093
  const directory = join$1(storeDir, "pool", repository);
5851
6094
  await mkdir(directory, { recursive: true });
5852
6095
  let repositoryLost;
5853
- const unlockRepository = await lockPath(directory, true, (error) => {
6096
+ const unlockRepository = await lockPath(directory, "admission", true, (error) => {
5854
6097
  repositoryLost ??= error;
5855
6098
  }, admission.signal);
5856
6099
  try {
@@ -11862,14 +12105,26 @@ function noteSkipped(skipped, model, reason) {
11862
12105
  function fallsBackOnContentFilter() {
11863
12106
  return this.settingsManager.getRetrySettings().fallbackOnContentFilter !== false;
11864
12107
  }
12108
+ /** Only server hints use this cap; retries without a hint keep their ordinary local backoff. */
12109
+ function rateLimitGuidance(message, capMs = DEFAULT_MAX_RETRY_DELAY_MS, status) {
12110
+ const summary = `Provider rate limit reached${status === 429 || /(?:^429(?:\s|:|$)|\bHTTP 429\b)/.test(message.errorMessage ?? "") ? " (HTTP 429)" : ""}.`;
12111
+ const overCap = overCapServerRetryDelay(message, capMs);
12112
+ if (overCap !== void 0) {
12113
+ const cap = capMs % 1e3 === 0 ? `${capMs / 1e3}s` : `${capMs}ms`;
12114
+ return `${summary} The ${Math.ceil(overCap / 1e3)}s wait exceeds the configured ${cap} retry limit. Switch models or try again after the rate limit resets.`;
12115
+ }
12116
+ const seconds = message.retryAfterMs !== void 0 ? Math.ceil(message.retryAfterMs / 1e3) : 0;
12117
+ return `${summary} Switch models or try again ${seconds > 0 ? `in ${seconds}s` : "after the rate limit resets"}.`;
12118
+ }
11865
12119
  /** Whether an assistant error may advance the configured fallback chain. */
11866
12120
  function _isFallbackableError(message) {
11867
12121
  if (message.stopReason !== "error") return false;
12122
+ const signal = normalizeModelFailureSignal(message);
12123
+ if (signal.kind === "rate_limit") return true;
11868
12124
  const contextWindow = this.model?.contextWindow ?? 0;
11869
12125
  if (isContextOverflow(message, contextWindow)) return false;
11870
12126
  const provider = message.provider || this.model?.provider;
11871
12127
  if (provider && containsCodexTokenInvalidation(provider, message)) return true;
11872
- const signal = normalizeModelFailureSignal(message);
11873
12128
  if (signal.kind === "cancelled" || signal.kind === "task_failure") return false;
11874
12129
  if (signal.kind === "content_filter") return fallsBackOnContentFilter.call(this);
11875
12130
  return isRetryableModelFailure(message);
@@ -11884,6 +12139,7 @@ function _isFallbackableError(message) {
11884
12139
  */
11885
12140
  function _isRetryableError(message) {
11886
12141
  if (message.stopReason !== "error") return false;
12142
+ if (normalizeModelFailureSignal(message).kind === "rate_limit") return true;
11887
12143
  const contextWindow = this.model?.contextWindow ?? 0;
11888
12144
  if (isContextOverflow(message, contextWindow)) return false;
11889
12145
  const provider = message.provider || this.model?.provider;
@@ -12083,16 +12339,46 @@ async function selectFallback(session, from, fromLevel, to, toLevel, reason, ski
12083
12339
  await session._emitModelSelect(to, from, "fallback");
12084
12340
  await session._recordSystemPromptForModelSwitch();
12085
12341
  }
12342
+ async function resolveFallbackAccount(session, model) {
12343
+ const controller = new AbortController();
12344
+ session._retryAbortController = controller;
12345
+ try {
12346
+ const timeoutMs = session.settingsManager.getProviderRetrySettings().timeoutMs || session.settingsManager.getHttpIdleTimeoutMs() || 0x7fffffff;
12347
+ const auth = await withProviderTimeout(timeoutMs, controller.signal, (signal) => session._modelRuntime.getRequestAuth(model, { signal }), "Fallback credential setup");
12348
+ return auth && providerAccount(model, {
12349
+ ...auth.auth,
12350
+ env: auth.env
12351
+ });
12352
+ } catch {
12353
+ return;
12354
+ } finally {
12355
+ if (session._retryAbortController === controller) session._retryAbortController = void 0;
12356
+ }
12357
+ }
12358
+ function blockedAccountReason(blocked, key) {
12359
+ if (blocked.has(key)) return "auth-failed";
12360
+ if (blocked.has(`quota:${key}`)) return "quota-exhausted";
12361
+ }
12086
12362
  async function _trySwitchToFallbackModel(message) {
12087
12363
  const currentModel = this.agent.state.model ?? this.model;
12088
12364
  if (this._fallbackModels.length === 0 || currentModel === void 0) return false;
12365
+ const generation = this._retryGeneration;
12366
+ const scopeGeneration = this._fallbackScopeGeneration;
12367
+ if (!retryIsCurrent(this, generation)) return false;
12089
12368
  if (isRetryableModelFailure(message) && !isRetryableSameModelFailure(message)) {
12090
12369
  if (!this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, currentModel))) this._fallbackBlockedModels.push(currentModel);
12091
12370
  }
12092
- if (isProviderCredentialRejection(message)) this._fallbackBlockedProviders.add(currentModel.provider);
12371
+ const quotaExhausted = normalizeModelFailureSignal(message).kind === "quota_exhausted";
12372
+ if (quotaExhausted || isProviderCredentialRejection(message)) {
12373
+ const account = failedProviderAccount(message);
12374
+ const key = account === void 0 ? `provider:${currentModel.provider}` : `account:${account}`;
12375
+ this._fallbackBlockedProviders.add(quotaExhausted ? `quota:${key}` : key);
12376
+ }
12093
12377
  const currentThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;
12094
12378
  const fromModel = currentModel;
12095
12379
  const skipped = [];
12380
+ const retryCapMs = () => this.settingsManager.getRetrySettings().maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
12381
+ const hasBlockedAccount = [...this._fallbackBlockedProviders].some((key) => key.startsWith("account:") || key.startsWith("quota:account:"));
12096
12382
  for (const rawCandidate of this._fallbackModels) {
12097
12383
  const candidate = resolveFallbackModel.call(this, rawCandidate);
12098
12384
  if (!candidate) {
@@ -12107,11 +12393,32 @@ async function _trySwitchToFallbackModel(message) {
12107
12393
  if (this._fallbackAttemptedKeys.has(key)) continue;
12108
12394
  if (modelsAreEqual(nextModel, fromModel) && nextLevel === currentThinkingLevel) continue;
12109
12395
  if (this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, nextModel))) continue;
12110
- if (this._fallbackBlockedProviders.has(nextModel.provider)) {
12111
- noteSkipped(skipped, nextModel, "auth-failed");
12396
+ const providerBlock = blockedAccountReason(this._fallbackBlockedProviders, `provider:${nextModel.provider}`);
12397
+ if (providerBlock !== void 0) {
12398
+ noteSkipped(skipped, nextModel, providerBlock);
12112
12399
  continue;
12113
12400
  }
12114
- const generation = this._retryGeneration;
12401
+ const account = hasBlockedAccount || hasBlockingAccountLimit(retryCapMs) ? await resolveFallbackAccount(this, nextModel) : void 0;
12402
+ if (!retryIsCurrent(this, generation)) return true;
12403
+ if (this._fallbackScopeGeneration !== scopeGeneration) return false;
12404
+ const accountBlock = account === void 0 ? void 0 : blockedAccountReason(this._fallbackBlockedProviders, `account:${account}`);
12405
+ if (accountBlock !== void 0) {
12406
+ noteSkipped(skipped, nextModel, accountBlock);
12407
+ continue;
12408
+ }
12409
+ const now = Date.now();
12410
+ if (providerUnavailableMs(nextModel.provider, nextModel.id, now, account ?? null) > 0) {
12411
+ noteSkipped(skipped, nextModel, "quota-exhausted");
12412
+ continue;
12413
+ }
12414
+ const cooldownMs = providerCooldownMs(nextModel.provider, nextModel.id, now, account ?? null);
12415
+ if (cooldownMs > 0) {
12416
+ const capMs = retryCapMs();
12417
+ if (capMs > 0 && cooldownMs > capMs) {
12418
+ noteSkipped(skipped, nextModel, "rate-limited");
12419
+ continue;
12420
+ }
12421
+ }
12115
12422
  const createdRetryPromise = this._retryPromise === void 0;
12116
12423
  ensureRetryPromise(this);
12117
12424
  try {
@@ -12198,13 +12505,15 @@ async function _handleRetryableError(message) {
12198
12505
  if (this._agentRunAbortRequested) return false;
12199
12506
  const generation = this._retryGeneration;
12200
12507
  const settings = this.settingsManager.getRetrySettings();
12508
+ const rateLimited = normalizeModelFailureSignal(message).kind === "rate_limit";
12509
+ const overCap = overCapServerRetryDelay(message, settings.maxRetryDelayMs) !== void 0;
12201
12510
  const retryableError = this._isRetryableError?.(message) ?? true;
12202
12511
  const fallbackableError = this._isFallbackableError?.(message) ?? retryableError;
12203
12512
  const emptyCompletion = this._isEmptyCompletion?.(message) ?? false;
12204
12513
  const safetyRefusal = this._isSafetyRefusal?.(message) ?? false;
12205
12514
  const canRetrySameModel = retryableError || emptyCompletion || safetyRefusal;
12206
12515
  const canAdvanceToFallback = fallbackableError || emptyCompletion;
12207
- if (!settings.enabled || !canRetrySameModel) {
12516
+ if (!settings.enabled || !canRetrySameModel || overCap) {
12208
12517
  if (canAdvanceToFallback && await this._trySwitchToFallbackModel(message)) return true;
12209
12518
  if (this._retryAttempt > 0) this._emit({
12210
12519
  type: "auto_retry_end",
@@ -12248,6 +12557,11 @@ async function _handleRetryableError(message) {
12248
12557
  });
12249
12558
  try {
12250
12559
  await this._omitTrailingAssistantAttempt();
12560
+ if (rateLimited) await this.sessionManager.appendCustomEntry("rate-limit-retry", {
12561
+ model: modelLabel(this.model),
12562
+ attempt: decision.attempt,
12563
+ delayMs
12564
+ });
12251
12565
  } catch (error) {
12252
12566
  if (this._retryAbortController === backoff) this._retryAbortController = void 0;
12253
12567
  if (retryIsCurrent(this, generation)) {
@@ -12274,7 +12588,7 @@ async function _handleRetryableError(message) {
12274
12588
  }
12275
12589
  const fallbackGeneration = this._fallbackOriginGeneration;
12276
12590
  scheduleRetry(this, generation, () => {
12277
- this.agent.continue().catch(async (error) => {
12591
+ this.agent.continue({ retryOf: message }).catch(async (error) => {
12278
12592
  if (!retryIsCurrent(this, generation)) return;
12279
12593
  const attempt = this._retryAttempt;
12280
12594
  const finalError = error instanceof Error ? error.message : String(error);
@@ -17150,7 +17464,10 @@ function buildRules(selectedTools, toolGuidelines, promptGuidelines, cwd, sessio
17150
17464
  }
17151
17465
  if (shouldIncludeAskUserFallbackGuidance) addGuideline("If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.");
17152
17466
  if (hasAskUserQuestion) addGuideline("When `ask_user_question` or an equivalent question tool is available, all agent-authored questions to the user must use that tool instead of plain text, including clarifications, choices, confirmations, and permission to proceed. Prefer `ask_user_question` when available; otherwise use the equivalent tool's supported schema. In these sessions, never end a status or final message with a prose-only question. Intercom questions are for agents, not a substitute for user approval.");
17153
- if (tools.length > 0) addGuideline("When human input is unavailable because no usable question tool exists or the session is headless, do not stall on a question. Choose the interpretation best supported by the stated objective and repository evidence: mine git history, commits, PRs, issues, and the user's own comments to infer how they would decide, record the assumption and rationale, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve explicit approval gates, safety, authorization, and budget limits. A cancelled or unanswered available question is not permission to use this fallback.");
17467
+ if (tools.length > 0) {
17468
+ addGuideline("When using a question tool, include all context needed to answer in the question and options, even if you already gave it in a progress update.");
17469
+ addGuideline("When human input is unavailable because no usable question tool exists or the session is headless, do not stall on a question. Choose the interpretation best supported by the stated objective and repository evidence: mine git history, commits, PRs, issues, and the user's own comments to infer how they would decide, record the assumption and rationale, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve explicit approval gates, safety, authorization, and budget limits. A cancelled or unanswered available question is not permission to use this fallback.");
17470
+ }
17154
17471
  if (hasBash || hasPowerShell) addGuideline("**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.");
17155
17472
  const sessionMemory = buildSessionMemoryGuideline(tools, cwd, sessionFolder);
17156
17473
  if (sessionMemory) addGuideline(sessionMemory);
@@ -17945,10 +18262,12 @@ function buildItemsForQuestion(question) {
17945
18262
  });
17946
18263
  return items;
17947
18264
  }
18265
+ const selfContainedQuestionGuidance = "Make each question answerable on its own. State the decision and relevant facts and numbers in the question; explain the consequence of each option in its description or preview. Include this context even if you already gave it in a progress update.";
17948
18266
  const askUserQuestionToolSystemPromptContribution = Object.freeze({
17949
18267
  snippet: `Ask all user questions through this tool, including clarifications and approvals; up to 4 questions with 2-4 options each`,
17950
18268
  guidelines: Object.freeze([
17951
18269
  "When ask_user_question or an equivalent question tool is available, all questions to the user must use that tool instead of plain text, including clarifications, preferences, confirmations, approvals, and permission to proceed. Prefer ask_user_question when available. In these sessions, do not end a progress update or final response with a prose-only question such as 'Proceed?'.",
18270
+ selfContainedQuestionGuidance,
17952
18271
  "Ask only when a decision is needed; do not seek approval again for already-authorized work. For a confirmation, put the concrete action and its scope in the question and offer explicit proceed and decline options. A cancelled or unanswered question is not approval.",
17953
18272
  `Each question MUST have 2-4 options. Every option requires a concise label (1-5 words) and a description explaining what the choice means or its trade-offs. The user can additionally type a custom answer ("Type something." row is appended automatically to single-select questions) or pick "Chat about this" to abandon the questionnaire.`,
17954
18273
  `Set multiSelect: true when multiple answers are valid; this suppresses the "Type something." row. Provide an options[].preview markdown string when an option benefits from richer side-by-side context (mockups, code snippets, diagrams, configs) — single-select only. NOTE: any non-empty preview on a single-select question ALSO suppresses the "Type something." row (no room in the side-by-side layout); "Chat about this" remains the escape hatch. If you recommend a specific option, make it the first option and append "(Recommended)" to its label.`,
@@ -17977,6 +18296,7 @@ function defineAskUserQuestionTool(config, options) {
17977
18296
  4. Request confirmation, approval, or permission to proceed
17978
18297
 
17979
18298
  Usage notes:
18299
+ - ${selfContainedQuestionGuidance}
17980
18300
  - Ask only for decisions that are needed; do not re-request existing authorization. State the exact action and scope, with explicit proceed and decline options for confirmations. A cancelled or unanswered question is not approval.
17981
18301
  - If ask_user_question is unavailable, use an equivalent available question tool with its supported schema. If no usable question tool is available, continue autonomously using best judgment and state evidence-backed assumptions. Tool unavailability alone is not a blocker; preserve safety and authorization constraints.
17982
18302
  - Users will always be able to type a custom answer ("Type something." row is appended automatically to every single-select question) or pick "Chat about this" to abandon the questionnaire and continue in free-form conversation. Do NOT author "Other" / "Type something." / "Chat about this" labels yourself — duplicates are rejected at runtime.
@@ -19324,8 +19644,6 @@ const TASK_HEARTBEAT_OUTPUT_SAMPLE_MS = 3e4;
19324
19644
  const OUTPUT_TAIL_BYTES = 2048;
19325
19645
  const LINE_CHARS = 160;
19326
19646
  const TITLE_CHARS = 120;
19327
- /** Longest delay a host timer accepts before it overflows to an immediate fire. */
19328
- const MAX_TIMER_DELAY_MS = 0x7fffffff;
19329
19647
  /** The owner's default cadence, or the built-in one when its setting cannot be read or is out of range. */
19330
19648
  function defaultTaskHeartbeatMs(delivery) {
19331
19649
  try {
@@ -19338,12 +19656,8 @@ function defaultTaskHeartbeatMs(delivery) {
19338
19656
  /** Times the cadence on the monotonic clock, so a step of the wall clock neither delays nor bunches heartbeats (#5058). */
19339
19657
  const systemClock = {
19340
19658
  now: () => performance.now(),
19341
- setTimeout: (run, delayMs) => {
19342
- const handle = setTimeout(run, delayMs);
19343
- handle.unref();
19344
- return handle;
19345
- },
19346
- clearTimeout: (handle) => clearTimeout(handle)
19659
+ setTimeout: (run, delayMs) => setLongTimeout(run, delayMs, { ref: false }),
19660
+ clearTimeout: (handle) => handle.clear()
19347
19661
  };
19348
19662
  function activityKey(task) {
19349
19663
  return JSON.stringify([
@@ -19488,7 +19802,7 @@ var TaskHeartbeatMonitor = class {
19488
19802
  if (this.timer !== void 0 && this.timerAt === wakeAt) return;
19489
19803
  this.disarm();
19490
19804
  if (!Number.isFinite(wakeAt)) return;
19491
- const delay = Math.min(Math.max(1, Math.ceil(wakeAt - this.clock.now())), MAX_TIMER_DELAY_MS);
19805
+ const delay = Math.max(1, Math.ceil(wakeAt - this.clock.now()));
19492
19806
  this.timerAt = wakeAt;
19493
19807
  this.timer = this.clock.setTimeout(() => {
19494
19808
  this.timer = void 0;
@@ -20740,7 +21054,7 @@ async function addWorktree(repository, repo, path, branch, steps) {
20740
21054
  });
20741
21055
  if (busy === void 0) return;
20742
21056
  if (busy.adder === null || probe >= additionWait.probes) throw additionInProgress(busy);
20743
- await new Promise((resolveWait) => setTimeout(resolveWait, additionWait.intervalMs));
21057
+ await sleepFor(additionWait.intervalMs);
20744
21058
  }
20745
21059
  }
20746
21060
  /** Whether `path` is a complete worktree that no recorded git is still adding or removing. */
@@ -24314,7 +24628,7 @@ var DefaultPackageManager = class {
24314
24628
  let stdout = "";
24315
24629
  let stderr = "";
24316
24630
  let timedOut = false;
24317
- const timeout = typeof options?.timeoutMs === "number" ? setTimeout(() => {
24631
+ const timeout = typeof options?.timeoutMs === "number" ? setLongTimeout(() => {
24318
24632
  timedOut = true;
24319
24633
  child.kill();
24320
24634
  }, options.timeoutMs) : void 0;
@@ -24325,11 +24639,11 @@ var DefaultPackageManager = class {
24325
24639
  stderr += data.toString();
24326
24640
  });
24327
24641
  child.once("error", (error) => {
24328
- if (timeout) clearTimeout(timeout);
24642
+ timeout?.clear();
24329
24643
  reject(error);
24330
24644
  });
24331
24645
  child.once("close", (code, signal) => {
24332
- if (timeout) clearTimeout(timeout);
24646
+ timeout?.clear();
24333
24647
  if (timedOut) {
24334
24648
  reject(/* @__PURE__ */ new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`));
24335
24649
  return;
@@ -26032,22 +26346,30 @@ var ModelRuntimeStreaming = class {
26032
26346
  return this.streamSimple(model, context, options).result();
26033
26347
  }
26034
26348
  streamWithCredentialRetry(model, options, invoke) {
26035
- const prepare = () => this.prepareRequest(model, options);
26036
- const reprepareCredentials = async (previous) => {
26037
- if (options?.signal?.aborted) return void 0;
26349
+ const inSetup = (operation) => withProviderTimeout(options?.timeoutMs === 0 ? void 0 : options?.timeoutMs, options?.signal, operation, "Provider request setup");
26350
+ const prepare = () => inSetup((signal) => this.prepareRequest(model, {
26351
+ ...options,
26352
+ signal
26353
+ }));
26354
+ const retry = (previous) => inSetup(async (signal) => {
26038
26355
  await this.reloadCredentials();
26356
+ signal.throwIfAborted();
26039
26357
  const { preparedRequestAuth: previousAuth, ...callerOptions } = options ?? {};
26040
26358
  const reprepared = previousAuth?.reprepare ? await previousAuth.reprepare() : void 0;
26359
+ signal.throwIfAborted();
26041
26360
  const next = reprepared ? await this.prepareRequest(reprepared.model, {
26042
26361
  ...callerOptions,
26043
26362
  apiKey: reprepared.options.apiKey,
26044
26363
  headers: reprepared.options.headers,
26045
26364
  env: reprepared.options.env,
26046
- preparedRequestAuth: reprepared.options.preparedRequestAuth
26047
- }) : await this.prepareRequest(model, callerOptions);
26365
+ preparedRequestAuth: reprepared.options.preparedRequestAuth,
26366
+ signal
26367
+ }) : await this.prepareRequest(model, {
26368
+ ...callerOptions,
26369
+ signal
26370
+ });
26048
26371
  return next.authIdentity !== previous.authIdentity ? next : void 0;
26049
- };
26050
- const retry = (previous) => reprepareCredentials(previous).catch(() => void 0);
26372
+ }).catch(() => void 0);
26051
26373
  const ownsTransport = (requestModel) => this.ownsExtensionTransport(requestModel);
26052
26374
  const iterate = async function* () {
26053
26375
  let prepared = await prepare();
@@ -26066,7 +26388,7 @@ var ModelRuntimeStreaming = class {
26066
26388
  let terminal = false;
26067
26389
  for await (const event of source) {
26068
26390
  if (event.type === "error") admission.observeFailure(event.error);
26069
- if (event.type === "done") recordProviderSuccess(prepared.model.provider, prepared.model.id);
26391
+ if (event.type === "done") admission.observeSuccess();
26070
26392
  if (event.type === "start") {
26071
26393
  pending.push(event);
26072
26394
  continue;
@@ -26082,7 +26404,7 @@ var ModelRuntimeStreaming = class {
26082
26404
  }
26083
26405
  if (!rejection && !terminal) {
26084
26406
  const result = await source.result();
26085
- if (result.stopReason !== "error" && result.stopReason !== "aborted") recordProviderSuccess(prepared.model.provider, prepared.model.id);
26407
+ if (result.stopReason !== "error" && result.stopReason !== "aborted") admission.observeSuccess();
26086
26408
  if (result.stopReason === "error") admission.observeFailure(result);
26087
26409
  const event = result.stopReason === "error" || result.stopReason === "aborted" ? {
26088
26410
  type: "error",
@@ -26152,11 +26474,15 @@ var ModelRuntimeStreaming = class {
26152
26474
  return lazyStream(model, async () => iterate(), options?.signal);
26153
26475
  }
26154
26476
  async fetchDeferred(model, handle, options) {
26155
- return lazyStream(model, async () => {
26156
- const prepared = await this.prepareRequest(model, options);
26477
+ return lazyStream(model, async (signal) => {
26478
+ const prepared = await this.prepareRequest(model, {
26479
+ ...options,
26480
+ signal
26481
+ });
26482
+ signal.throwIfAborted();
26157
26483
  if (!prepared.provider.fetchDeferred) throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
26158
26484
  return prepared.provider.fetchDeferred(prepared.model, handle, prepared.options);
26159
- }, options?.signal).result();
26485
+ }, options?.signal, options?.timeoutMs).result();
26160
26486
  }
26161
26487
  async cancelDeferred(model, handle, options) {
26162
26488
  const prepared = await this.prepareRequest(model, options);
@@ -26318,14 +26644,14 @@ var ModelRuntime = class ModelRuntime {
26318
26644
  runtime.#sessionDiscoveryEnabled = allowModelNetwork !== false;
26319
26645
  const refreshFromNetwork = allowModelNetwork === true;
26320
26646
  const controller = refreshFromNetwork ? new AbortController() : void 0;
26321
- const timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15e3) : void 0;
26647
+ const timeout = controller ? setLongTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15e3) : void 0;
26322
26648
  try {
26323
26649
  if (options.refreshOnCreate !== false) await runtime.refresh({
26324
26650
  allowNetwork: refreshFromNetwork,
26325
26651
  signal: controller?.signal
26326
26652
  });
26327
26653
  } finally {
26328
- if (timeout) clearTimeout(timeout);
26654
+ timeout?.clear();
26329
26655
  }
26330
26656
  return runtime;
26331
26657
  }
@@ -28188,16 +28514,16 @@ function assertRpcSuccess(response) {
28188
28514
  if (response.errorCode === "missing_session_cwd" && isSerializedMissingSessionCwdError(response.errorDetails)) throw rehydrateMissingSessionCwdError(response.errorDetails);
28189
28515
  throw new Error(response.error);
28190
28516
  }
28191
- export { ANTHROPIC_FAST_MODE_MODEL_IDS, AgentTaskHost, BLUEPRINT_RULES, Bm25Ranker, CredentialSynchronizationError, DEFAULT_TASK_HEARTBEAT_MS, DefaultPackageManager, FAST_MODEL_ID_SUFFIX, FAST_MODEL_SERVICE_TIER, FAST_MODEL_SPEED, LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, MIN_TASK_HEARTBEAT_MS, ModelRuntime, OAuthLoginTransactionError, QuestionnaireSession, READ_MCP_RESOURCE_TOOL, SNAPSHOT_DENY_PATTERNS, SNAPSHOT_IGNORE_FILE, SNAPSHOT_KEY_FILE_PATTERNS, TASK_COMPLETION_MESSAGE_TYPE, TASK_HEARTBEAT_MESSAGE_TYPE, TOOL_SEARCH_TOOL_NAME, TaskCompletionOutbox, WORKSPACE_BINDING_ENTRY_TYPE, WORKSPACE_WRITE_TOOL_NAMES, abortTurnRetries, acquireWorkspaceWriterLease, activatesOnRegistration, admitPooledWorktree, adoptPrebuiltSeed, agentSessionModelsMethods, agentSessionRetryMethods, applyToolLoadout, assertRpcSuccess, assertSessionManagerInWorktreeAsync, authForStream, bindSessionWorkspace, bindingOf, blueprintPlatformOf, buildItemsForQuestion, buildSessionMemoryGuideline, buildSessionOptions, buildSkillCatalog, buildSkillCatalogAsync, buildSkillCatalogWith, buildSystemPrompt, buildSystemPromptSections, cancelFirstPromptModel, captureLocatedCheckout, captureWorktreeSnapshot, carryOverDegradedWork, checkResumeStoragePreconditions, childOfAttempt, chunkedAnswerContent, chunkedAnswerHeader, chunkedBranchState, chunkedChildHeading, chunkedEntryHasId, chunkedForkLink, chunkedPrefixFields, chunkedResumeProjection, chunkedTaskDetailFields, chunkedToolResult, chunkedToolResultEntry, chunkedTreeOutline, claimIdleWorktree, clearExtensionCache, commandOutputExcerpt, completionTitleDescription, completionTitleText, computeDeferExtensions, computeInteractiveEngineResourceDeferral, computeStartupInputCaptureEnabled, computeStartupTrustPromptPossible, confirmPooledWorktreeLease, copilotAdvertisedFastModelIds, createAskUserQuestionToolDefinition, createAuthInteraction, createHostModuleJiti, createLoadedAskUserQuestionToolDefinition, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, createToolNameMatcher, createToolSearchDocument, createToolSearchExtension, createToolSearchToolDefinition, defaultBuiltinExtensions, defaultResumePreflightIo, deferFirstPromptModel, deriveFastModelVariants, diffSystemPromptSections, discardPooledWorktree, emitProjectTrustEvent, emptySkillCatalog, enablePrintModelSelection, engineExtensionsCanDecide, ensureDefaultLazyBuiltinsRegistered, ensureRetryPromise, evictIdleWorktrees, executeNativePty, executeSupervisedCommand, expandPromptTemplate, expandSkillCommand, extensionLoaderTestHooks, extensionsCanDecideProjectTrust, fastModelId, findInitialModel, finishedSubagentResumeText, firstSubagentAttempt, forkSeedFields, formatScopedModelList, formatSkillsForPrompt, formatTaskHeartbeatDuration, formatTaskHeartbeatStatus, getExistingGitInstallPathAsync, getManagedNpmInstallPath, getModelFastRoute, getSkillCatalog, gitText, gitUnavailableProblem, hasPrintModelSelection, holdRestoredWorktree, holdsSessionSnapshotRef, hostPlatform, inheritWorkspace, insideThroughDirectories, isBoundWorkspace, isDegradableRestoreFailure, isDeniedSnapshotPath, isHeadOnlyAdvance, isMcpToolName, isNativeFastRouteApi, isOAuthLoginCancelled, isRecoverableRestoreFailure, isRegisteredToolAllowed, isResumableStop, isRetiredToolName, isToolActivatable, isToolDeclarationHidden, keepSessionSnapshotCommit, latestSubagentAttempt, latestSubagentAttempts, loadExtensionModule, loadPromptsStageAsync, loadSkills, loadSkillsFromDir, loadSkillsStageAsync, loadSnapshotPathPolicy, loadThemesStageAsync, locateCheckout, loginIsolatedApiKeyProvider, loginIsolatedOAuthProvider, loginRuntimeOAuthProvider, lookupOwnedTask, markRuntimeStreamFunction, mergeHeaders, messageHeadIn, messageRoleIn, namesSessionFolderInGuidelines, nextCaptureTick, normalizeBuildSystemPromptOptions, normalizeOAuthLoginError, nulFields, objectStorePath, openWorkspaceRepository, parseBlueprint, parseFrontmatter, parseSource, pendingLfsDownload, pendingTaskCompletionIntents, pooledWorktreeHolder, prepareExtensionEntries, preparePromptsCommitAsync, prepareSkillsCommitAsync, prepareThemesCommitAsync, presentQuestionnaire, projectForkMetadata, projectToolLoadout, ranOnModelLine, read, readChunkedWorkflowRunId, readExtensionGraphManifest, readRepositoryConfig, readValue, recordPooledWorktreeState, recordSessionWorkspace, recordWorktreeCapture, releaseRestoredWorktree, releaseSessionSnapshotRefs, releasedWaitingOn, removeRestoredWorktree, require_dist, require_semver, resolveDeferredStartupModel, resolveRestoredModelReference, resolveToolNames, resolveUpstreamModelId, resolveWorkspace, restoreBestWorktree, restoreDegradedWorktree, restoreDegradedWorktreeAt, restoreWorkspace, restoreWorktree, restoreWorktreeAt, restoreWorktreeSnapshot, resumableSubagentResult, retireSessionSnapshotRefs, retryIsCurrent, runBeforeAgentStartHandlers, runBeforeProviderRequestHandlers, runBoundaryHandlers, runContextHandlers, runGenericHandlers, runGit, runInputHandlers, runMessageEndHandlers, runResourcesDiscoverHandlers, runSessionRecoveryHandlers, runToolCallHandlers, runToolResultHandlers, runUserBashHandlers, seedDirectory, seedManifestPath, seedPathSegments, selectDocument, selectedToolNames, sessionAccountCheckpoint, setAsideWorktree, setWorktreeSnapshotGit, settledTaskResumeId, skip, snapshotEventHandlers, snapshotRestoreWarnings, startupErrorHandlerTokens, storagePreconditionProblems, storeCheckoutHead, streamWithFastRoute, stringValue, stripFrontmatter, subagentResumeId, supersededSettledAttempts, taskCompletionMessage, taskHeartbeatKindLabel, taskNoticeLine, uncachedCopilotModelHint, unresolvedFallbackModelDiagnostics, unrestoredRecord, updatePromptsFromPathsAsync, updateSkillsFromPathsAsync, updateThemesFromPathsAsync, useExtensionCacheCwd, usesAnthropicFastMode, usesChatGptCodexTransport, usesFirstPartyCodexRouting, usesOpenAIFastServiceTier, usesXaiFastServiceTier, validateBashWait, validateTaskHeartbeatMs, verifyWorktree$1 as verifyWorktree, waitForSupervisedCommand, waitingReleasedShells, waitingReleasedTools, withCodexFastRouteHeaders, withDefaultBuiltinExtensions, withFastModelVariants, withFastRouteStreamOptions, withScratchDirectory, withSeedLock, withoutSupersededAttempts, workspaceSandboxDenial, workspaceSessionCwd, workspaceSessionCwdAsync, worktreeSetAside, writeSeedManifest, writeWorkingTree };
28517
+ export { ANTHROPIC_FAST_MODE_MODEL_IDS, AgentTaskHost, BLUEPRINT_RULES, Bm25Ranker, CredentialSynchronizationError, DEFAULT_TASK_HEARTBEAT_MS, DefaultPackageManager, FAST_MODEL_ID_SUFFIX, FAST_MODEL_SERVICE_TIER, FAST_MODEL_SPEED, LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, MIN_TASK_HEARTBEAT_MS, ModelRuntime, OAuthLoginTransactionError, QuestionnaireSession, READ_MCP_RESOURCE_TOOL, SNAPSHOT_DENY_PATTERNS, SNAPSHOT_IGNORE_FILE, SNAPSHOT_KEY_FILE_PATTERNS, TASK_COMPLETION_MESSAGE_TYPE, TASK_HEARTBEAT_MESSAGE_TYPE, TOOL_SEARCH_TOOL_NAME, TaskCompletionOutbox, WORKSPACE_BINDING_ENTRY_TYPE, WORKSPACE_WRITE_TOOL_NAMES, abortTurnRetries, acquireWorkspaceWriterLease, activatesOnRegistration, admitPooledWorktree, adoptPrebuiltSeed, agentSessionModelsMethods, agentSessionRetryMethods, applyToolLoadout, assertRpcSuccess, assertSessionManagerInWorktreeAsync, authForStream, bindSessionWorkspace, bindingOf, blueprintPlatformOf, buildItemsForQuestion, buildSessionMemoryGuideline, buildSessionOptions, buildSkillCatalog, buildSkillCatalogAsync, buildSkillCatalogWith, buildSystemPrompt, buildSystemPromptSections, cancelFirstPromptModel, captureLocatedCheckout, captureWorktreeSnapshot, carryOverDegradedWork, checkResumeStoragePreconditions, childOfAttempt, chunkedAnswerContent, chunkedAnswerHeader, chunkedBranchState, chunkedChildHeading, chunkedEntryHasId, chunkedForkLink, chunkedPrefixFields, chunkedResumeProjection, chunkedTaskDetailFields, chunkedToolResult, chunkedToolResultEntry, chunkedTreeOutline, claimIdleWorktree, clearExtensionCache, commandOutputExcerpt, completionTitleDescription, completionTitleText, computeDeferExtensions, computeInteractiveEngineResourceDeferral, computeStartupInputCaptureEnabled, computeStartupTrustPromptPossible, confirmPooledWorktreeLease, copilotAdvertisedFastModelIds, createAskUserQuestionToolDefinition, createAuthInteraction, createHostModuleJiti, createLoadedAskUserQuestionToolDefinition, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, createToolNameMatcher, createToolSearchDocument, createToolSearchExtension, createToolSearchToolDefinition, defaultBuiltinExtensions, defaultResumePreflightIo, deferFirstPromptModel, deriveFastModelVariants, diffSystemPromptSections, discardPooledWorktree, emitProjectTrustEvent, emptySkillCatalog, enablePrintModelSelection, engineExtensionsCanDecide, ensureDefaultLazyBuiltinsRegistered, ensureRetryPromise, evictIdleWorktrees, executeNativePty, executeSupervisedCommand, expandPromptTemplate, expandSkillCommand, extensionLoaderTestHooks, extensionsCanDecideProjectTrust, fastModelId, findInitialModel, finishedSubagentResumeText, firstSubagentAttempt, forkSeedFields, formatScopedModelList, formatSkillsForPrompt, formatTaskHeartbeatDuration, formatTaskHeartbeatStatus, getExistingGitInstallPathAsync, getManagedNpmInstallPath, getModelFastRoute, getSkillCatalog, gitText, gitUnavailableProblem, hasPrintModelSelection, holdRestoredWorktree, holdsSessionSnapshotRef, hostPlatform, inheritWorkspace, insideThroughDirectories, isBoundWorkspace, isDegradableRestoreFailure, isDeniedSnapshotPath, isHeadOnlyAdvance, isMcpToolName, isNativeFastRouteApi, isOAuthLoginCancelled, isRecoverableRestoreFailure, isRegisteredToolAllowed, isResumableStop, isRetiredToolName, isToolActivatable, isToolDeclarationHidden, keepSessionSnapshotCommit, latestSubagentAttempt, latestSubagentAttempts, loadExtensionModule, loadPromptsStageAsync, loadSkills, loadSkillsFromDir, loadSkillsStageAsync, loadSnapshotPathPolicy, loadThemesStageAsync, locateCheckout, loginIsolatedApiKeyProvider, loginIsolatedOAuthProvider, loginRuntimeOAuthProvider, lookupOwnedTask, markRuntimeStreamFunction, mergeHeaders, messageHeadIn, messageRoleIn, namesSessionFolderInGuidelines, nextCaptureTick, normalizeBuildSystemPromptOptions, normalizeOAuthLoginError, nulFields, objectStorePath, openWorkspaceRepository, parseBlueprint, parseFrontmatter, parseSource, pendingLfsDownload, pendingTaskCompletionIntents, pooledWorktreeHolder, prepareExtensionEntries, preparePromptsCommitAsync, prepareSkillsCommitAsync, prepareThemesCommitAsync, presentQuestionnaire, projectForkMetadata, projectToolLoadout, ranOnModelLine, rateLimitGuidance, read, readChunkedWorkflowRunId, readExtensionGraphManifest, readRepositoryConfig, readValue, recordPooledWorktreeState, recordSessionWorkspace, recordWorktreeCapture, releaseRestoredWorktree, releaseSessionSnapshotRefs, releasedWaitingOn, removeRestoredWorktree, require_dist, require_semver, resolveDeferredStartupModel, resolveRestoredModelReference, resolveToolNames, resolveUpstreamModelId, resolveWorkspace, restoreBestWorktree, restoreDegradedWorktree, restoreDegradedWorktreeAt, restoreWorkspace, restoreWorktree, restoreWorktreeAt, restoreWorktreeSnapshot, resumableSubagentResult, retireSessionSnapshotRefs, retryIsCurrent, runBeforeAgentStartHandlers, runBeforeProviderRequestHandlers, runBoundaryHandlers, runContextHandlers, runGenericHandlers, runGit, runInputHandlers, runMessageEndHandlers, runResourcesDiscoverHandlers, runSessionRecoveryHandlers, runToolCallHandlers, runToolResultHandlers, runUserBashHandlers, seedDirectory, seedManifestPath, seedPathSegments, selectDocument, selectedToolNames, sessionAccountCheckpoint, setAsideWorktree, setWorktreeSnapshotGit, settledTaskResumeId, skip, snapshotEventHandlers, snapshotRestoreWarnings, startupErrorHandlerTokens, storagePreconditionProblems, storeCheckoutHead, streamWithFastRoute, stringValue, stripFrontmatter, subagentResumeId, supersededSettledAttempts, taskCompletionMessage, taskHeartbeatKindLabel, taskNoticeLine, uncachedCopilotModelHint, unresolvedFallbackModelDiagnostics, unrestoredRecord, updatePromptsFromPathsAsync, updateSkillsFromPathsAsync, updateThemesFromPathsAsync, useExtensionCacheCwd, usesAnthropicFastMode, usesChatGptCodexTransport, usesFirstPartyCodexRouting, usesOpenAIFastServiceTier, usesXaiFastServiceTier, validateBashWait, validateTaskHeartbeatMs, verifyWorktree$1 as verifyWorktree, waitForSupervisedCommand, waitingReleasedShells, waitingReleasedTools, withCodexFastRouteHeaders, withDefaultBuiltinExtensions, withFastModelVariants, withFastRouteStreamOptions, withScratchDirectory, withSeedLock, withoutSupersededAttempts, workspaceSandboxDenial, workspaceSessionCwd, workspaceSessionCwdAsync, worktreeSetAside, writeSeedManifest, writeWorkingTree };
28192
28518
 
28193
- //# sourceMappingURL=startup-0-5-YDW47QX6.js.map
28519
+ //# sourceMappingURL=startup-0-5-HZX3ZPTP.js.map
28194
28520
  // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
28195
28521
  // demand that fails in a process an in-place update left running says to restart.
28196
28522
  function __atomicOnDemandFailed(error, feature) {
28197
28523
  return (async () => {
28198
28524
  const root = new URL("../", import.meta.url);
28199
28525
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
28200
- const key = `${root.href}#0.10.15-alpha.2`;
28526
+ const key = `${root.href}#0.10.16-alpha.1`;
28201
28527
  let release = releases.get(key);
28202
28528
  if (release === undefined) {
28203
28529
  const current = (async () => {
@@ -28225,7 +28551,7 @@ function __atomicOnDemandFailed(error, feature) {
28225
28551
  } catch {
28226
28552
  // No installation to read, as in a bundle of the package: the release the process runs decides.
28227
28553
  }
28228
- const updatedTo = typeof installed === "string" && installed !== "0.10.15-alpha.2" ? installed : running !== undefined && running.version !== "0.10.15-alpha.2" ? "0.10.15-alpha.2" : undefined;
28554
+ const updatedTo = typeof installed === "string" && installed !== "0.10.16-alpha.1" ? installed : running !== undefined && running.version !== "0.10.16-alpha.1" ? "0.10.16-alpha.1" : undefined;
28229
28555
  if (updatedTo === undefined) throw error;
28230
28556
  const application = typeof running?.name === "string" ? running.name : "atomic";
28231
28557
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {