@bastani/atomic 0.10.11-alpha.1 → 0.10.11-alpha.3

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 (457) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +9 -9
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +8 -8
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +9 -9
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  16. package/dist/_shared/{sdk-AVFII7NK.js → sdk-B5LEWGGI.js} +2633 -488
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  21. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  22. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  23. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-EZUKEP4Q.js} +436 -51
  24. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-RTOHJFDJ.js} +240 -279
  26. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +254 -46
  28. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  29. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  30. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  31. package/dist/_shared/startup-0-4-ZMJV547D.js +14 -9
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  33. package/dist/_shared/startup-0-5-YDW47QX6.js +10 -10
  34. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  37. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -7
  38. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +7 -7
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +22 -30
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +455 -102
  43. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  44. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +162 -1184
  45. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  46. package/dist/_shared/storage-command-7MGXLJGZ.js +189 -36
  47. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  48. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  49. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  50. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  51. package/dist/_shared/team-DOQKICG2.js +376 -0
  52. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  53. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  54. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  55. package/dist/builtin/intercom/README.md +2 -2
  56. package/dist/builtin/intercom/broker/broker.bundle.mjs +1091 -344
  57. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  58. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  59. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  60. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +208 -101
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +516 -102
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  70. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +199 -27
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  81. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  82. package/dist/builtin/web-access/package.json +1 -1
  83. package/dist/bun/bundled-sqlite.js +41 -0
  84. package/dist/bun/bundled-sqlite.js.map +1 -0
  85. package/dist/cli/args.js +2 -2
  86. package/dist/cli/auth-cli.code.js +6 -6
  87. package/dist/cli/auth-cli.impl.js +3 -3
  88. package/dist/cli/auth-cli.js +3 -3
  89. package/dist/cli/blueprint-command.code.js +4 -4
  90. package/dist/cli/blueprint-command.impl.js +3 -3
  91. package/dist/cli/blueprint-command.js +3 -3
  92. package/dist/cli/intercom-command.code.js +4 -4
  93. package/dist/cli/intercom-command.code.js.map +1 -1
  94. package/dist/cli/intercom-command.impl.js +3 -3
  95. package/dist/cli/intercom-command.js +3 -3
  96. package/dist/cli/list-models.code.js +2 -2
  97. package/dist/cli/list-models.impl.js +3 -3
  98. package/dist/cli/list-models.js +3 -3
  99. package/dist/cli/session-picker.code.js +2 -2
  100. package/dist/cli/session-picker.impl.js +3 -3
  101. package/dist/cli/session-picker.js +3 -3
  102. package/dist/cli/startup-ui.code.js +2 -2
  103. package/dist/cli/startup-ui.impl.js +3 -3
  104. package/dist/cli/startup-ui.js +3 -3
  105. package/dist/cli/storage-command.impl.js +3 -3
  106. package/dist/cli/storage-command.js +3 -3
  107. package/dist/cli/storage-search-session.code.js +3 -3
  108. package/dist/cli/storage-search-session.impl.js +3 -3
  109. package/dist/cli/storage-search-session.js +3 -3
  110. package/dist/cli/team-command.code.js +20 -114
  111. package/dist/cli/team-command.code.js.map +1 -1
  112. package/dist/cli/team-command.impl.js +3 -3
  113. package/dist/cli/team-command.js +3 -3
  114. package/dist/cli.js +5 -18
  115. package/dist/cli.js.map +1 -1
  116. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  117. package/dist/core/compaction/compactor.d.ts +3 -3
  118. package/dist/core/debug.code.js +1 -1
  119. package/dist/core/debug.impl.js +3 -3
  120. package/dist/core/debug.js +3 -3
  121. package/dist/core/export-html/card-projection.impl.js +3 -3
  122. package/dist/core/export-html/card-projection.js +3 -3
  123. package/dist/core/export-html/index.code.js +2 -2
  124. package/dist/core/export-html/index.impl.js +3 -3
  125. package/dist/core/export-html/index.js +3 -3
  126. package/dist/core/export-html/json-spans.impl.js +3 -3
  127. package/dist/core/export-html/json-spans.js +3 -3
  128. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  129. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  131. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  132. package/dist/core/export-html/tool-renderer.js +3 -3
  133. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  134. package/dist/core/extensions/jiti-loader.js +3 -3
  135. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.js +3 -3
  137. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  138. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  139. package/dist/core/extensions/loader-host-modules.js +3 -3
  140. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  141. package/dist/core/extensions/runner-context.js +3 -3
  142. package/dist/core/intercom-broker-control-host.code.js +2 -2
  143. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  144. package/dist/core/intercom-broker-control-host.js +3 -3
  145. package/dist/core/intercom-broker-control.code.js +3 -3
  146. package/dist/core/intercom-broker-control.impl.js +3 -3
  147. package/dist/core/intercom-broker-control.js +3 -3
  148. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  149. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  150. package/dist/core/package-manager-storage-adapters.js +3 -3
  151. package/dist/core/process-start-token.d.ts +8 -0
  152. package/dist/core/process-tree-containment.d.ts +16 -0
  153. package/dist/core/sdk-types.d.ts +1 -2
  154. package/dist/core/sdk-types.js.map +1 -1
  155. package/dist/core/sdk.code.js +4 -4
  156. package/dist/core/sdk.impl.js +3 -3
  157. package/dist/core/sdk.js +3 -3
  158. package/dist/core/session-manager-core.js +27 -15
  159. package/dist/core/session-manager-core.js.map +1 -1
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +3 -3
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-open-markers.js +3 -0
  166. package/dist/core/session-open-markers.js.map +1 -0
  167. package/dist/core/session-storage.code.js +1 -1
  168. package/dist/core/session-storage.impl.js +3 -3
  169. package/dist/core/session-storage.js +3 -3
  170. package/dist/core/settings-schema.d.ts +0 -3
  171. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  172. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  173. package/dist/core/storage/added-exports.js +3 -0
  174. package/dist/core/storage/added-exports.js.map +1 -1
  175. package/dist/core/storage/creation-time.js +105 -0
  176. package/dist/core/storage/creation-time.js.map +1 -0
  177. package/dist/core/storage/database.d.ts +56 -5
  178. package/dist/core/storage/database.js.map +1 -1
  179. package/dist/core/storage/dialect.d.ts +1 -1
  180. package/dist/core/storage/dialect.js +1 -1
  181. package/dist/core/storage/dialect.js.map +1 -1
  182. package/dist/core/storage/errors.d.ts +13 -13
  183. package/dist/core/storage/errors.js +10 -16
  184. package/dist/core/storage/errors.js.map +1 -1
  185. package/dist/core/storage/fenced-paths.d.ts +11 -0
  186. package/dist/core/storage/fenced-paths.js +11 -0
  187. package/dist/core/storage/fenced-paths.js.map +1 -1
  188. package/dist/core/storage/file-identity.d.ts +2 -0
  189. package/dist/core/storage/file-identity.js +24 -8
  190. package/dist/core/storage/file-identity.js.map +1 -1
  191. package/dist/core/storage/index.d.ts +4 -3
  192. package/dist/core/storage/index.js +5 -3
  193. package/dist/core/storage/index.js.map +1 -1
  194. package/dist/core/storage/libsql-removed.d.ts +71 -0
  195. package/dist/core/storage/libsql-removed.js +123 -0
  196. package/dist/core/storage/libsql-removed.js.map +1 -0
  197. package/dist/core/storage/migrations.d.ts +81 -8
  198. package/dist/core/storage/migrations.js +386 -47
  199. package/dist/core/storage/migrations.js.map +1 -1
  200. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  201. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  202. package/dist/core/storage/node-sqlite-thread.js +36 -12
  203. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  204. package/dist/core/storage/node-sqlite.js +135 -3
  205. package/dist/core/storage/node-sqlite.js.map +1 -1
  206. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  207. package/dist/core/storage/offline-snapshot-file.js +3 -3
  208. package/dist/core/storage/prefix.d.ts +1 -1
  209. package/dist/core/storage/prefix.js +14 -2
  210. package/dist/core/storage/prefix.js.map +1 -1
  211. package/dist/core/storage/process-selection.d.ts +5 -5
  212. package/dist/core/storage/provider.js +2 -2
  213. package/dist/core/storage/schema-catalog.d.ts +82 -5
  214. package/dist/core/storage/schema-catalog.js +244 -34
  215. package/dist/core/storage/schema-catalog.js.map +1 -1
  216. package/dist/core/storage/selection.d.ts +7 -82
  217. package/dist/core/storage/selection.js +20 -235
  218. package/dist/core/storage/selection.js.map +1 -1
  219. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  220. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  221. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  222. package/dist/core/storage/session/branch-fork-source.js +3 -3
  223. package/dist/core/storage/session/card-view.impl.js +3 -3
  224. package/dist/core/storage/session/card-view.js +3 -3
  225. package/dist/core/storage/session/child-reader.code.js +4 -4
  226. package/dist/core/storage/session/child-reader.impl.js +3 -3
  227. package/dist/core/storage/session/child-reader.js +3 -3
  228. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  229. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  230. package/dist/core/storage/session/errors.js +1 -1
  231. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  232. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  233. package/dist/core/storage/session/expanded-child-details.js +3 -3
  234. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  235. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  236. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  237. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  238. package/dist/core/storage/session/fork-row-index.js +3 -3
  239. package/dist/core/storage/session/fork-schema.js +53 -0
  240. package/dist/core/storage/session/fork-schema.js.map +1 -0
  241. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  242. package/dist/core/storage/session/fork-staging.code.js +5 -8
  243. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  244. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  245. package/dist/core/storage/session/fork-staging.js +3 -3
  246. package/dist/core/storage/session/fork-sweep.js +61 -0
  247. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  248. package/dist/core/storage/session/fork-window.code.js +4 -4
  249. package/dist/core/storage/session/fork-window.impl.js +3 -3
  250. package/dist/core/storage/session/fork-window.js +3 -3
  251. package/dist/core/storage/session/history-pages.impl.js +3 -3
  252. package/dist/core/storage/session/history-pages.js +3 -3
  253. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  254. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  255. package/dist/core/storage/session/jsonl-session-store.d.ts +42 -2
  256. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  257. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  258. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  259. package/dist/core/storage/session/memory-session-store.js +3 -3
  260. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  261. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  262. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  263. package/dist/core/storage/session/released-history-files.code.js +4 -4
  264. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  265. package/dist/core/storage/session/released-history-files.js +3 -3
  266. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  267. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  268. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  269. package/dist/core/storage/session/session-resume.impl.js +3 -3
  270. package/dist/core/storage/session/session-resume.js +3 -3
  271. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  272. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  273. package/dist/core/storage/session/snapshot-cut.js +3 -3
  274. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  275. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  276. package/dist/core/storage/session/snapshot-history.js +3 -3
  277. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  278. package/dist/core/storage/session/sql-session-store.d.ts +394 -20
  279. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  280. package/dist/core/storage/session/sql-session-store.js +4 -4
  281. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  282. package/dist/core/storage/session/tree-outline.js +3 -3
  283. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  284. package/dist/core/storage/session/tree-presentation.js +3 -3
  285. package/dist/core/storage/session/types.d.ts +22 -0
  286. package/dist/core/storage/sqlite-facade.d.ts +23 -2
  287. package/dist/core/storage/sqlite-facade.js +34 -0
  288. package/dist/core/storage/sqlite-facade.js.map +1 -1
  289. package/dist/core/storage/storage-status.code.js +1 -1
  290. package/dist/core/storage/storage-status.impl.js +3 -3
  291. package/dist/core/storage/storage-status.js +3 -3
  292. package/dist/core/storage/team.code.js +1 -1
  293. package/dist/core/storage/team.d.ts +26 -115
  294. package/dist/core/storage/team.impl.js +3 -3
  295. package/dist/core/storage/team.js +3 -3
  296. package/dist/core/structured-output/index.code.js +1 -1
  297. package/dist/core/structured-output/index.impl.js +3 -3
  298. package/dist/core/structured-output/index.js +3 -3
  299. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  300. package/dist/core/tasks/task-completion-entry.js +3 -3
  301. package/dist/core/tasks/task-file-history.code.js +4 -4
  302. package/dist/core/tasks/task-file-history.impl.js +3 -3
  303. package/dist/core/tasks/task-file-history.js +3 -3
  304. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  305. package/dist/core/tasks/task-reference-archive.js +3 -3
  306. package/dist/core/tasks/task-reference-identity.js +3 -3
  307. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  308. package/dist/core/tasks/task-reference-stream.js +3 -3
  309. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  310. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  311. package/dist/core/tasks/task-view-source.code.js +1 -1
  312. package/dist/core/tasks/task-view-source.impl.js +3 -3
  313. package/dist/core/tasks/task-view-source.js +3 -3
  314. package/dist/core/tools/history-session.d.ts +2 -0
  315. package/dist/core/tools/history-tasks.d.ts +3 -2
  316. package/dist/core/tools/read-url.code.js +4 -4
  317. package/dist/core/tools/read-url.impl.js +3 -3
  318. package/dist/core/tools/read-url.js +3 -3
  319. package/dist/core/worktree-snapshot/blob-store.d.ts +71 -3
  320. package/dist/core/worktree-snapshot/blob-store.js +575 -67
  321. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  322. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  323. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/errors.js +3 -3
  325. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  326. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  327. package/dist/core/worktree-snapshot/fork-snapshot-index.js +162 -0
  328. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  329. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  330. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  331. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  332. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  333. package/dist/extensions/codemode/execute.code.js +2 -2
  334. package/dist/extensions/codemode/execute.impl.js +3 -3
  335. package/dist/extensions/codemode/execute.js +3 -3
  336. package/dist/extensions/codemode/renderer.code.js +2 -2
  337. package/dist/extensions/codemode/renderer.impl.js +3 -3
  338. package/dist/extensions/codemode/renderer.js +3 -3
  339. package/dist/extensions/mcp/cli.code.js +3 -3
  340. package/dist/extensions/mcp/cli.impl.js +3 -3
  341. package/dist/extensions/mcp/cli.js +3 -3
  342. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  343. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  344. package/dist/extensions/mcp/cli.lazy.js +3 -3
  345. package/dist/extensions/mcp/runtime.code.js +1 -1
  346. package/dist/extensions/mcp/runtime.impl.js +3 -3
  347. package/dist/extensions/mcp/runtime.js +3 -3
  348. package/dist/index.d.ts +3 -1
  349. package/dist/index.js +8 -8
  350. package/dist/main-first-time-setup.code.js +2 -2
  351. package/dist/main-first-time-setup.impl.js +3 -3
  352. package/dist/main-first-time-setup.js +3 -3
  353. package/dist/main.js +1 -1
  354. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  355. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  356. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  357. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  358. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  359. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  360. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  361. package/dist/modes/print-mode.js +1 -1
  362. package/dist/package-manager-cli.code.js +7 -7
  363. package/dist/package-manager-cli.impl.js +3 -3
  364. package/dist/package-manager-cli.js +3 -3
  365. package/dist/rpc-entry.js +1 -1
  366. package/dist/startup-files.json +1 -1
  367. package/dist/startup-stages/10.js +1 -1
  368. package/dist/startup-stages/11.js +1 -1
  369. package/dist/startup-stages/12.js +1 -1
  370. package/dist/startup-stages/2.js +2 -3
  371. package/dist/startup-stages/3.js +1 -3
  372. package/dist/startup-stages/4.js +1 -2
  373. package/dist/startup-stages/5.js +1 -1
  374. package/dist/startup-stages/6.js +5 -7
  375. package/dist/startup-stages/7.js +3 -6
  376. package/dist/startup-stages/8.js +7 -2
  377. package/dist/startup-stages/9.js +1 -7
  378. package/dist/startup-stages/stages.json +1 -1
  379. package/dist/utils/compile-cache-deferral.js +8 -13
  380. package/dist/utils/compile-cache-deferral.js.map +1 -1
  381. package/dist/utils/compile-cache-warmup-host.js +3 -4
  382. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  383. package/dist/utils/compile-cache.js +12 -100
  384. package/dist/utils/compile-cache.js.map +1 -1
  385. package/dist/utils/startup-database-spare.code.js +3 -3
  386. package/dist/utils/startup-database-spare.impl.js +3 -3
  387. package/dist/utils/startup-database-spare.js +3 -3
  388. package/dist/utils/tools-manager.code.js +1 -1
  389. package/dist/utils/tools-manager.impl.js +3 -3
  390. package/dist/utils/tools-manager.js +3 -3
  391. package/dist/utils/worker-threads.js +2 -15
  392. package/dist/utils/worker-threads.js.map +1 -1
  393. package/docs/build.md +3 -3
  394. package/docs/changelog.mdx +1421 -69
  395. package/docs/compaction/reference.md +5 -5
  396. package/docs/compaction.md +7 -9
  397. package/docs/containerization.md +2 -2
  398. package/docs/custom-provider/api-reference.md +1 -1
  399. package/docs/docs.json +37 -10
  400. package/docs/environment-variables.md +0 -2
  401. package/docs/extensions/api-reference.md +4 -4
  402. package/docs/getting-started/installation.md +3 -0
  403. package/docs/guides/configuration.md +1 -1
  404. package/docs/guides/non-interactive.md +1 -1
  405. package/docs/guides/resume-on-any-machine.md +14 -22
  406. package/docs/guides/team-setup.md +56 -83
  407. package/docs/guides.md +2 -4
  408. package/docs/herdr.md +1 -1
  409. package/docs/index.md +1 -1
  410. package/docs/intercom/operations.md +26 -21
  411. package/docs/intercom/reference.md +2 -2
  412. package/docs/intercom.md +1 -1
  413. package/docs/libraries/storage-postgres.md +9 -9
  414. package/docs/libraries.md +2 -3
  415. package/docs/models-configuration.md +2 -2
  416. package/docs/models.md +2 -3
  417. package/docs/packages/authoring.md +7 -7
  418. package/docs/packages.md +1 -1
  419. package/docs/programmatic.md +2 -2
  420. package/docs/quickstart.md +1 -1
  421. package/docs/reference/cli.md +6 -11
  422. package/docs/reference.md +2 -2
  423. package/docs/rpc/extension-ui.md +2 -2
  424. package/docs/sdk/reference.md +5 -4
  425. package/docs/sdk/storage.md +8 -92
  426. package/docs/sdk/structured-decisions.md +1 -1
  427. package/docs/sdk/web-server.md +3 -3
  428. package/docs/sdk.md +14 -4
  429. package/docs/security.md +1 -1
  430. package/docs/session-format.md +5 -5
  431. package/docs/sessions.md +31 -42
  432. package/docs/settings.md +7 -8
  433. package/docs/storage/custom-adapters.md +255 -0
  434. package/docs/storage/jsonl.md +117 -0
  435. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +73 -68
  436. package/docs/storage/postgres/tuning.md +337 -0
  437. package/docs/storage/postgres.md +556 -0
  438. package/docs/storage/sqlite.md +99 -0
  439. package/docs/storage.md +333 -956
  440. package/docs/subagents/authoring.md +1 -1
  441. package/docs/subagents.md +2 -2
  442. package/docs/tools.md +1 -1
  443. package/docs/worktree-snapshots.md +2 -2
  444. package/package.json +9 -9
  445. package/schemas/models.schema.json +2 -2
  446. package/schemas/settings.schema.json +0 -14
  447. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  448. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  449. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  450. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  451. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  452. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  453. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  454. package/dist/core/intercom-broker-control.d.ts +0 -129
  455. package/dist/startup-stages/13.js +0 -1
  456. package/docs/guides/postgres-tuning.md +0 -311
  457. package/docs/libraries/storage-libsql.md +0 -97
@@ -1,13 +1,13 @@
1
1
  import { __name } from "./rolldown-runtime-BGM3D5V3.js";
2
- import { APP_NAME, BUILTIN_PACKAGE_DIR_NAMES, CONFIG_DIR_NAME, ENV_CLEAR_ON_SHRINK, ENV_HARDWARE_CURSOR, ENV_SESSION_DIR, INTERACTIVE_ENGINE_BOOTSTRAP_FLAG, addHostStorageAdapter, canonicalizePath as canonicalizePath$1, createChildProcessEnvironment, flushPersistentCompileCache, formatPathRelativeToCwdOrAbsolute, getAgentConfigPaths, getAgentDir, getAgentDirs, getBinDir, getBlueprintActionsDir, getCwdRelativePath, getEnvValue, getGlobalBlueprintPath, getHomeDir, getProjectBlueprintPath, getProjectConfigPaths, getReadmePath, hostStorageAdapter, isBunBinary, isBunRuntime, isChildProcessExitStatusUnknownError, isLocalPath, markLifecycleTiming, normalizePath, removeOwnedInteractiveEngineBootstrapAsync, resolvePath, shortenHomePath, splitBom, stripBom, waitForChildProcess, writeInteractiveEngineBootstrapAsync } from "./p0-cli-BB45ZQY6.js";
3
- import { BLUEPRINT_CONTEXT_TYPE, BlueprintBuildFailedError, BlueprintError, BlueprintInvalidError, BlueprintStepFailedError, BlueprintStepTimedOutError, BlueprintUsesUnsupportedError, CACHE_WARMING_MODES, COMMAND_FOREGROUND_BUDGET_MS, CompactionConfigError, DEFAULT_BUILTIN_SELECTION_EXTRA_TOOLS, DEFAULT_MAX_BYTES, EditInputError, EditMatchError, EditTargetError, FileToolAbortedError, HostListenerFailures, LONG_LIVED_COMMANDS, Minimatch, RESTART_CANCELLED_MESSAGE, STALE_EXTENSION_CONTEXT_MESSAGE, ShellTimeoutError, SqliteSelectorConnection, SubscriptionChildUnavailableError, SubscriptionClosedError, SubscriptionConfigError, TASK_MARKS, TaskMessageError, TaskMessageTimeoutError, WriteSelectorError, activeToolExecutionStarts, allToolNames, announceBlueprintBuildWaiting, applyBashSessionEnvironment, asyncScope, attachJsonlLineReader, attachLineReader, bindSavedTaskOrigins, blueprintBuildShared, blueprintDigest, canonicalEventBusFor, chatPosition, clearAssignmentIfClosed, clearLockHolder, clearLockHolderAsync, convertBufferWithMarkit, convertFileWithMarkit, createGitEnvironment, defaultToolNamesFor, defineTool, detectSupportedImageMimeTypeFromFile, displayTodoId, entryLines, expandSearchUrl, experimentalToolSamplingProperty, filterSearchOutputByLineRange, formatReadLineRange as formatReadLineRange$1, formatSelectedLines, formatSize, formatTimeoutSeconds as formatTimeoutSeconds$1, formatTodoId, frozenClocks, getManifestFromPackageJson, getTextOutput, getTodoPath, getTodoStatus, getTodoTitle, getTodosDir, getTodosDirLabel, getToolListError, handOverBuildTimings, holdDeprecationWarnings, holdToolsUntilBuilt, hostInputError, invalidArgText, invalidateNativeSearchCache, isBlueprintError, isGitProvisionError, isGitUnavailableError, isPathInside, isReadResourceSelector, isReadableUrlPath, isTodoClosed, isToolModifier, keptTaskHint, linkPath, literalPathLike, loadNativeSearchBinding, mergeReadRanges, nativeModuleProblem, normalizePathLikeInput, normalizeTodoId, noteSavedSeq, openAdapterSelectionDatabase, originalHistoryNote, prepareLockTakeover, projectTrustHandlerRegistered, projectTrustedBeforeExtensions, readLedger, readTaskOutputTail, receiveChatReceipt, recordLockHolder, recordLockHolderAsync, registerCanonicalEventBus, releaseDeprecationWarnings, renderBlueprintContext, renderToolPath, replaceTabs, reportContained, repositoryKey, resolvePhysicalPathAsync, rootKey, savedReadLines, scopedBackgroundTasks, searchPosition, selectExactReadRanges, selectReadRanges, serializeJsonLine, settingsFileNoticeKey, settingsInternals, shortenPath, sleep, sliceHead, snapshotBashSessionEnvironment, sortTodos, spawnHostProcess, splitLineRangeSelector, splitPathLikeGlob, splitReadLineSelector, splitTodosByAssignment, startShellDeadline, startToolTimer, str, stringEntries, takeOverDeadHolder, takeOverDeadHolderAsync, takeQueuedDeliveryChange, taskResumer, timestamp, toolTimerText, transcriptHeaderLines, truncateHead, truncateLine, updateLedger, validateTodoId, warnDeprecation, withFileMutationQueue, withResolvingFileMutationQueue, workspaceKey } from "./startup-0-0-57KF6LZH.js";
4
- import { EMPTY_OUTPUT_TEXT, HistorySearchPositions, MAX_INDEXED_ENTRY_CHARS, ResumeTimingsRecorder, SEARCH_PART_CHARS, SessionStorageSelectionSchema, TaskElapsedClocks, TaskToolError, WorkspaceDriftError, WorkspaceRestoreError, WorkspaceSnapshotError, bindTaskClock, bindTaskClockSource, buildDirectoryTree, buildDirectoryTreeFromOperations, cancelReceiptSentence, captureRegistrationInvocation, compareCreated, compareFrozen, conflictEntries, convertToLlm, createBranchSummaryMessage, createCustomMessage, diffLines, ensureTool, execCommand, findSessionOpenHolder, findWorkspaceError, formatResumeTimings, invocationExtension, invocationRuntime, isWorkspaceConfigError, isWorkspaceDriftError, isWorkspaceError, isWorkspaceGitError, isWorkspaceSnapshotError, lifecycleScopeForOwner, normalizeAzureSettings, openEventSubscription, originalRegistrationCallback, ownedSettingsManagers, parseArgs, parseConflictBytes, parseInteractiveEngineMessage, parseSkillUri, presentTaskError, prewarmModelApi, readConflictUrl, readLocalFileChunks, recordBlueprintStep, recordResumeTimings, recordSettingsWrite, refreshConflictFile, registerConflictBlocks, registerFactoryStartupHandler, renderTodoCall, renderTodoResult, resolveInstalledGit, resolveInvocationRuntime, selectReadLinesFromChunks, selectReadLinesFromList, serializeInteractiveEngineFrame, serializeTodoForAgent, serializeTodoListForAgent, sessionPosition, settingsWriteOwner, splitSearchTextParts, startupSourceId, taskClockOf, taskClockRunning, timeCheckoutRestore, unpackIds, unreadablePathError, validateEventSource, validateSubscriptionAdmission, waitResultTail, waitStatus, withoutSearchPosition, writeRenderers } from "./startup-0-1-GIY75K46.js";
2
+ import { APP_NAME, BUILTIN_PACKAGE_DIR_NAMES, CONFIG_DIR_NAME, ENV_CLEAR_ON_SHRINK, ENV_HARDWARE_CURSOR, INTERACTIVE_ENGINE_BOOTSTRAP_FLAG, addHostStorageAdapter, canonicalizePath as canonicalizePath$1, createChildProcessEnvironment, flushPersistentCompileCache, formatPathRelativeToCwdOrAbsolute, getAgentConfigPaths, getAgentDir, getAgentDirs, getBinDir, getBlueprintActionsDir, getCwdRelativePath, getEnvValue, getGlobalBlueprintPath, getHomeDir, getProjectBlueprintPath, getProjectConfigPaths, getReadmePath, hostStorageAdapter, isBunBinary, isBunRuntime, isChildProcessExitStatusUnknownError, isLocalPath, markLifecycleTiming, normalizePath, removeOwnedInteractiveEngineBootstrapAsync, resolvePath, shortenHomePath, splitBom, stripBom, waitForChildProcess, writeInteractiveEngineBootstrapAsync } from "./p0-cli-BB45ZQY6.js";
3
+ import { BLUEPRINT_CONTEXT_TYPE, BlueprintBuildFailedError, BlueprintError, BlueprintInvalidError, BlueprintStepFailedError, BlueprintStepTimedOutError, BlueprintUsesUnsupportedError, CACHE_WARMING_MODES, COMMAND_FOREGROUND_BUDGET_MS, CompactionConfigError, DEFAULT_BUILTIN_SELECTION_EXTRA_TOOLS, DEFAULT_MAX_BYTES, EditInputError, EditMatchError, EditTargetError, FileToolAbortedError, HostListenerFailures, LONG_LIVED_COMMANDS, Minimatch, RESTART_CANCELLED_MESSAGE, STALE_EXTENSION_CONTEXT_MESSAGE, ShellTimeoutError, SqliteSelectorConnection, SubscriptionChildUnavailableError, SubscriptionClosedError, SubscriptionConfigError, TASK_MARKS, TaskMessageError, TaskMessageTimeoutError, WriteSelectorError, activeToolExecutionStarts, allToolNames, announceBlueprintBuildWaiting, applyBashSessionEnvironment, asyncScope, attachJsonlLineReader, attachLineReader, bindSavedTaskOrigins, blueprintBuildShared, blueprintDigest, canonicalEventBusFor, chatPosition, clearAssignmentIfClosed, clearLockHolder, clearLockHolderAsync, convertBufferWithMarkit, convertFileWithMarkit, createGitEnvironment, defaultToolNamesFor, defineTool, detectSupportedImageMimeTypeFromFile, displayTodoId, entryLines, expandSearchUrl, experimentalToolSamplingProperty, filterSearchOutputByLineRange, formatReadLineRange as formatReadLineRange$1, formatSelectedLines, formatSize, formatTimeoutSeconds as formatTimeoutSeconds$1, formatTodoId, frozenClocks, getManifestFromPackageJson, getTextOutput, getTodoPath, getTodoStatus, getTodoTitle, getTodosDir, getTodosDirLabel, getToolListError, handOverBuildTimings, holdDeprecationWarnings, holdToolsUntilBuilt, hostInputError, invalidArgText, invalidateNativeSearchCache, isBlueprintError, isGitProvisionError, isGitUnavailableError, isPathInside, isReadResourceSelector, isReadableUrlPath, isTodoClosed, isToolModifier, keptTaskHint, linkPath, literalPathLike, loadNativeSearchBinding, mergeReadRanges, nativeModuleProblem, normalizePathLikeInput, normalizeTodoId, noteSavedSeq, originalHistoryNote, prepareLockTakeover, projectTrustHandlerRegistered, projectTrustedBeforeExtensions, readLedger, readTaskOutputTail, receiveChatReceipt, recordLockHolder, recordLockHolderAsync, registerCanonicalEventBus, releaseDeprecationWarnings, renderBlueprintContext, renderToolPath, replaceTabs, reportContained, repositoryKey, resolvePhysicalPathAsync, rootKey, savedReadLines, scopedBackgroundTasks, searchPosition, selectExactReadRanges, selectReadRanges, serializeJsonLine, settingsFileNoticeKey, settingsInternals, shortenPath, sleep, sliceHead, snapshotBashSessionEnvironment, sortTodos, spawnHostProcess, splitLineRangeSelector, splitPathLikeGlob, splitReadLineSelector, splitTodosByAssignment, startShellDeadline, startToolTimer, str, stringEntries, takeOverDeadHolder, takeOverDeadHolderAsync, takeQueuedDeliveryChange, taskResumer, timestamp, toolTimerText, transcriptHeaderLines, truncateHead, truncateLine, updateLedger, validateTodoId, warnDeprecation, withFileMutationQueue, withResolvingFileMutationQueue, workspaceKey } from "./startup-0-0-EZUKEP4Q.js";
4
+ import { EMPTY_OUTPUT_TEXT, HistorySearchPositions, MAX_INDEXED_ENTRY_CHARS, ResumeTimingsRecorder, SEARCH_PART_CHARS, SessionStorageSelectionSchema, TaskElapsedClocks, TaskToolError, WorkspaceDriftError, WorkspaceRestoreError, WorkspaceSnapshotError, bindTaskClock, bindTaskClockSource, buildDirectoryTree, buildDirectoryTreeFromOperations, cancelReceiptSentence, captureRegistrationInvocation, compareCreated, compareFrozen, conflictEntries, convertToLlm, createBranchSummaryMessage, createCustomMessage, diffLines, ensureTool, execCommand, findWorkspaceError, formatResumeTimings, invocationExtension, invocationRuntime, isWorkspaceConfigError, isWorkspaceDriftError, isWorkspaceError, isWorkspaceGitError, isWorkspaceSnapshotError, lifecycleScopeForOwner, normalizeAzureSettings, openEventSubscription, originalRegistrationCallback, ownedSettingsManagers, parseArgs, parseConflictBytes, parseInteractiveEngineMessage, parseSkillUri, presentTaskError, prewarmModelApi, readConflictUrl, readLocalFileChunks, recordBlueprintStep, recordResumeTimings, recordSettingsWrite, refreshConflictFile, registerConflictBlocks, registerFactoryStartupHandler, renderTodoCall, renderTodoResult, resolveInstalledGit, resolveInvocationRuntime, selectReadLinesFromChunks, selectReadLinesFromList, serializeInteractiveEngineFrame, serializeTodoForAgent, serializeTodoListForAgent, sessionPosition, settingsWriteOwner, splitSearchTextParts, startupSourceId, taskClockOf, taskClockRunning, timeCheckoutRestore, unpackIds, unreadablePathError, validateEventSource, validateSubscriptionAdmission, waitResultTail, waitStatus, withoutSearchPosition, writeRenderers } from "./startup-0-1-RTOHJFDJ.js";
5
5
  import { CodeHighlighter, FS_WATCH_RETRY_DELAY_MS, applyEarlyInputChunk, closeWatcher, getLanguageFromPath, graphemeAt, highlightCode, isSafeFsWatchPathError, keepStartupDialogDraft, migrateKeybindingsConfig, parenthesizedKeyHint, recordTimingLines, sanitizeTerminalText, singleLineDisplayText, slashCommandHint, terminalDisplayText, theme, watchWithErrorHandlerAsync, withEarlyInputHeldForStartupDialog } from "./p2-shell-main-B2WIALFD.js";
6
6
  import { parseJsonFileContent } from "./p1-shared-RG5I5LJ6.js";
7
- import { ProjectTrustStore, failureDebugFields, hasProjectTrustInputs, hasProjectTrustInputsAsync, inLockTurn, matchesOnSameLineCI, redactUrlCredentials, releaseLock, releaseLockSync, renameReplacing, renameReplacingAsync, renameWithRetry, reportDebugAsync, waitForLock, waitForLockSync } from "./p1b-elig-ENCUPKKJ.js";
8
- import { FILE_HEADERS_ONLY, InteractiveEngineMonitor, ModelConfig, RpcTerminalDrain, SESSIONS_STORAGE_ENV, STORAGE_ENV, TodoParams, addShellOutputPreview, assertSessionOpen, bindTaskChatPage, captureTaskChatFile, chatPageRequest, createTwoFilesPatch, drainSessionWork, dropWrongTypedSettings, estimateTokens, formatKillCall, formatPatch, formatTruncationNotice, formatWorkingElapsed, getNativeMcpToolIdentity, getPowerShellConfigAsync, getShellConfigAsync, getShellEnvAsync, hasCallingSessionWork, invalidSettingMessage, isPowerShellAvailable, isResumePreconditionError, isTodoOperationError, killChildProcessTree, loadTaskOwnTranscriptEntries, markNativeMcpToolDefinition, processSharedStorageSelection, processSharedStorageSelectionAsync, processStorageEnvironment, rebuildKillResult, rebuildShellWaitResult, selectProcessStorage, selectProcessStorageSteps, sessionGenerationClosing, sessionLifetime, spawnShellProcess, structuredPatch, taskChatPage, taskExtensionStatuses, taskOwnTranscriptEntries, taskTranscriptSource, trackDetachedChildPid, trackDetachedChildProcess, trackSessionWork, untrackDetachedChildPid, watchTaskExtensionStatuses, wrapToolDefinition } from "./startup-0-2-27OWFHV6.js";
9
- import { appendToLog, applyContextEdit, assertExtensionAction, buildProcessStarting, extensionWorkOpen, getBaseDirsForScope, getOwnerTaskSession, getOwnerTaskStore, inExtensionCleanup, isResumeFailure, isRetiredExtensionCleanup, isTaskTurnInterrupted, loadArchiveSnapshot, logTail, migrateAzureProvider, migrateAzureProviderAsync, onExtensionSessionQuit, openStepLog, processImage, resolvePathFromBase, resolveWorktreeSnapshotSettings, runLoggedProcess, sessionEntryToContextMessages, sha256Hex, startElapsedMs, stripLeadingCdCommandAsync, taskResumedTurns, trackExtensionWork, watchOwnerTaskStoreBinding, withTodoLock } from "./startup-0-3-T4DVFYWX.js";
10
- import { DecisionConfigError, SessionHistoryNotLoadedError, asAcceptedRequestFailure, isDecisionConfigError, markRpcTransportFailure, rpcTransportError } from "./settings-startup-4QCVCI53.js";
7
+ import { ProjectTrustStore, failureDebugFields, hasProjectTrustInputsAsync, inLockTurn, matchesOnSameLineCI, redactUrlCredentials, releaseLock, releaseLockSync, renameReplacing, renameReplacingAsync, renameWithRetry, reportDebugAsync, waitForLock, waitForLockSync } from "./p1b-elig-TVB5CBLL.js";
8
+ import { FILE_HEADERS_ONLY, InteractiveEngineMonitor, ModelConfig, RpcTerminalDrain, TodoParams, addShellOutputPreview, assertSessionOpen, bindTaskChatPage, captureTaskChatFile, chatPageRequest, createTwoFilesPatch, drainSessionWork, dropWrongTypedSettings, estimateTokens, formatKillCall, formatPatch, formatTruncationNotice, formatWorkingElapsed, getNativeMcpToolIdentity, getPowerShellConfigAsync, getShellConfigAsync, getShellEnvAsync, hasCallingSessionWork, invalidSettingMessage, isPowerShellAvailable, isResumePreconditionError, isTodoOperationError, killChildProcessTree, loadTaskOwnTranscriptEntries, markNativeMcpToolDefinition, rebuildKillResult, rebuildShellWaitResult, selectProcessStorageSteps, sessionGenerationClosing, sessionLifetime, spawnShellProcess, structuredPatch, taskChatPage, taskExtensionStatuses, taskOwnTranscriptEntries, taskTranscriptSource, trackDetachedChildPid, trackDetachedChildProcess, trackSessionWork, untrackDetachedChildPid, watchTaskExtensionStatuses, wrapToolDefinition } from "./startup-0-2-5QHPCEON.js";
9
+ import { appendToLog, applyContextEdit, assertExtensionAction, buildProcessStarting, extensionWorkOpen, findSessionOpenHolder, getBaseDirsForScope, getOwnerTaskSession, getOwnerTaskStore, inExtensionCleanup, isResumeFailure, isRetiredExtensionCleanup, isTaskTurnInterrupted, loadArchiveSnapshot, logTail, migrateAzureProvider, migrateAzureProviderAsync, onExtensionSessionQuit, openStepLog, processImage, resolvePathFromBase, resolveWorktreeSnapshotSettings, runLoggedProcess, sessionEntryToContextMessages, sha256Hex, startElapsedMs, stripLeadingCdCommandAsync, taskResumedTurns, trackExtensionWork, watchOwnerTaskStoreBinding, withTodoLock } from "./startup-0-3-4ZYBYQNM.js";
10
+ import { DecisionConfigError, SessionHistoryNotLoadedError, asAcceptedRequestFailure, isDecisionConfigError, markRpcTransportFailure, rpcTransportError } from "./settings-startup-HXQLSUWM.js";
11
11
  import { JsonlSessionStore, LegacySessionStore, checkedCustomMessage, checkedCustomType, checkedLabel, getLastConversationMessageId, getLatestSessionSummary, historyPageGeneration, storeSnapshotIndex, transcriptCursorWithin } from "./startup-8-0-34CBHPZH.js";
12
12
  import { TASK_COMPLETION_MESSAGE_TYPE, admitPooledWorktree, adoptPrebuiltSeed, assertRpcSuccess, authForStream, captureLocatedCheckout, captureWorktreeSnapshot, carryOverDegradedWork, childOfAttempt, chunkedToolResult, chunkedToolResultEntry, claimIdleWorktree, completionTitleDescription, confirmPooledWorktreeLease, createLoadedAskUserQuestionToolDefinition, createToolNameMatcher, defaultResumePreflightIo, discardPooledWorktree, evictIdleWorktrees, executeNativePty, executeSupervisedCommand, expandSkillCommand, extensionsCanDecideProjectTrust, getExistingGitInstallPathAsync, getManagedNpmInstallPath, gitText, holdRestoredWorktree, holdsSessionSnapshotRef, hostPlatform, inheritWorkspace, isHeadOnlyAdvance, isMcpToolName, isRecoverableRestoreFailure, keepSessionSnapshotCommit, loadSnapshotPathPolicy, locateCheckout, lookupOwnedTask, nextCaptureTick, parseBlueprint, parseSource, pendingLfsDownload, pooledWorktreeHolder, readRepositoryConfig, recordPooledWorktreeState, recordWorktreeCapture, releaseRestoredWorktree, releaseSessionSnapshotRefs, removeRestoredWorktree, require_dist, restoreBestWorktree, restoreDegradedWorktree, restoreDegradedWorktreeAt, restoreWorktree, restoreWorktreeAt, retireSessionSnapshotRefs, runGit, selectDocument, setAsideWorktree, snapshotRestoreWarnings, unrestoredRecord, validateBashWait, validateTaskHeartbeatMs, verifyWorktree, waitForSupervisedCommand, waitingReleasedTools, withScratchDirectory, withoutSupersededAttempts, worktreeSetAside, writeWorkingTree } from "./startup-0-5-YDW47QX6.js";
13
13
  import { OutputAccumulator, SNAPSHOT_COLLECTION_SESSION_DELAY_MS, TOOL_BLOCK_LIMITS, ToolBlockRecords, applyModelsJson, cancelledBuilds, canonicalPaths, canonicalizeWorktreePathAsync, collapseToolBlockLines, defaultWorktreeSnapshotStoreDir, migrateAuthJsonConfigValues, migrateAuthJsonConfigValuesAsync, migrateModelsJsonConfigValues, migrateModelsJsonConfigValuesAsync, renderDiff, runCanonicalSteps, runCanonicalStepsAsync, sameRemote, scheduleSnapshotCollection, settleOtherBuilds, taskTranscriptPageWithCuts, withBuildLocks } from "./startup-0-4-ZMJV547D.js";
@@ -19,19 +19,18 @@ import { chmodSync, constants, existsSync, lstatSync, mkdirSync, promises, readF
19
19
  import nodePath, { dirname, isAbsolute, join, resolve, sep } from "path";
20
20
  import { constants as constants$1, tmpdir } from "node:os";
21
21
  import path, { basename as basename$1, delimiter as delimiter$1, dirname as dirname$1, extname, isAbsolute as isAbsolute$1, join as join$1, parse as parse$2, relative as relative$1, resolve as resolve$1, sep as sep$1, win32 as win32$1 } from "node:path";
22
- import { fileURLToPath } from "node:url";
23
22
  import { spawn } from "node:child_process";
24
23
  import { execFile as execFile$1 } from "child_process";
25
24
  import { createSessionCwdMatcherAsync } from "../utils/canonical-path.js";
26
25
  import { pathExists, pathExists as pathExists$1 } from "../utils/path-exists.js";
27
- import { accessSync as accessSync$1, chmodSync as chmodSync$1, constants as constants$2, createReadStream, existsSync as existsSync$1, mkdirSync as mkdirSync$1, readFileSync as readFileSync$1, realpath as realpath$2, realpathSync as realpathSync$1, renameSync as renameSync$1, rmSync as rmSync$1, statSync as statSync$1, writeFileSync as writeFileSync$1, writeSync } from "node:fs";
26
+ import { accessSync as accessSync$1, constants as constants$2, createReadStream, existsSync as existsSync$1, readFileSync as readFileSync$1, realpath as realpath$2, realpathSync as realpathSync$1, statSync as statSync$1, writeSync } from "node:fs";
28
27
  import { Worker } from "node:worker_threads";
29
28
  import { EVAL_WORKER_BUILTIN, evalWorkerExecArgv } from "../utils/worker-threads.js";
30
29
  import { startupNodeOptions } from "@bastani/atomic-codemode/node-options";
31
30
  import { isModelType, normalizeContext, normalizeProviderId, retryAssistantCall, uuidv7 } from "@bastani/atomic-ai";
32
31
  import { Box, Container, Spacer, Text, getImageDimensions, truncateToWidth, wrapTextWithAnsi } from "@bastani/atomic-tui";
33
32
  import chalk from "chalk";
34
- import { StorageAdapterLoadError, StorageConfigError, StorageError, TeamProfileError, TeamProfileTimeoutError, describeStorageError, describeStorageError as describeStorageError$1, isStorageError } from "../core/storage/errors.js";
33
+ import { StorageConfigError, isStorageError } from "../core/storage/errors.js";
35
34
  import { access as access$1, lstat as lstat$1, mkdir as mkdir$1, readFile as readFile$1, readdir as readdir$1, readlink as readlink$1, rename as rename$1, rm as rm$1, stat as stat$2, writeFile as writeFile$1 } from "fs/promises";
36
35
  import crypto$1, { createHash, randomUUID } from "node:crypto";
37
36
  import { inspect, isDeepStrictEqual, promisify, types } from "node:util";
@@ -40,15 +39,15 @@ import { completeSimple } from "@bastani/atomic-ai/compat";
40
39
  import { randomUUID as randomUUID$1 } from "crypto";
41
40
  import { createInterface } from "node:readline";
42
41
  import { DEGRADED_RESTORE_RETENTION_DAYS, snapshotBlobHashes } from "../core/worktree-snapshot/blob-store.js";
43
- import { StorageProvider, loadStorageAdapter, resolveAdapterOptions, secretFilePath as secretFilePath$1, storageSelectionKey } from "../core/storage/provider.js";
42
+ import { StorageProvider } from "../core/storage/provider.js";
44
43
  import { setImmediate as setImmediate$1 } from "node:timers";
45
44
  import { isProxy } from "node:util/types";
46
- import { defaultSessionDatabasePath, defaultSessionDatabasePathAsync, defaultSessionDatabasePathSteps, defaultSharedStoragePath, defaultSharedStoragePathSteps, runStorageSteps, runStorageStepsSync, storageHomeDir, storagePathBaseDir, storagePathBaseDirSteps, storageSettingsSteps, takeStorageAdoptionNotice } from "../core/storage/file-identity.js";
45
+ import { defaultSessionDatabasePathAsync, defaultSessionDatabasePathSteps, defaultSharedStoragePathSteps, runStorageSteps, runStorageStepsSync, storagePathBaseDirSteps, storageSettingsSteps } from "../core/storage/file-identity.js";
47
46
  import { Type as Type$1 } from "@bastani/atomic-ai/utils/typebox/index";
48
47
  import { deflateRaw as deflateRaw$1, gunzip as gunzip$1, gzip as gzip$1, inflateRaw as inflateRaw$1 } from "node:zlib";
49
48
  import { getAllBuiltinModels } from "@bastani/atomic-ai/providers/all";
50
49
  import { Value } from "@bastani/atomic-ai/utils/typebox/value";
51
- import { LIBSQL_ADAPTER_PACKAGE, LOCAL_SESSIONS_STORAGE, POSTGRES_ADAPTER_PACKAGE, STORAGE_TOKEN_FILE, TEAM_PROFILE_ENV, checkSharedDatabaseArguments, checkTeamPrefix, checkTeamUrl, conflictingTeamToken, emptyTeamToken, environmentTeamProfileAsync, inMemorySecret, isFileUrl, isPostgresUrl, missingTeamToken, readTeamTokenFile, selectStorage, selectStorageSteps } from "../core/storage/selection.js";
50
+ import { selectStorageSteps } from "../core/storage/selection.js";
52
51
  // dist/core/session-worktree-snapshots.js
53
52
  /** Built-in tools that can change files: a turn that called one records a snapshot. */
54
53
  const FILE_WRITING_TOOLS = /* @__PURE__ */ new Set([
@@ -7655,11 +7654,10 @@ function promptAnswerOptionsOf(item) {
7655
7654
  ...item.choices === void 0 ? {} : { choices: [...item.choices] }
7656
7655
  };
7657
7656
  }
7658
- function sourceOf$1(session, id) {
7657
+ function sourceOf(session, id) {
7659
7658
  if (typeof id !== "string" || id.length === 0 || id === "main" || id.startsWith(taskPrefix)) return void 0;
7660
7659
  for (const source of hubOf(session)?.all() ?? []) for (const item of sourceItems(source)) if (item.id === id) return source;
7661
7660
  }
7662
- __name(sourceOf$1, "sourceOf");
7663
7661
  function normalizeActionResult(result) {
7664
7662
  if (typeof result !== "object" || result === null) return {
7665
7663
  ok: false,
@@ -7679,7 +7677,7 @@ function normalizeActionResult(result) {
7679
7677
  function openAgentPanelItem(session, id, options) {
7680
7678
  try {
7681
7679
  if (typeof id !== "string" || id.length === 0) return false;
7682
- const source = sourceOf$1(session, id);
7680
+ const source = sourceOf(session, id);
7683
7681
  const open = source === void 0 ? void 0 : readPanelField(source, "open");
7684
7682
  if (source === void 0 || typeof open !== "function") return false;
7685
7683
  const onReturn = options?.onReturn;
@@ -7717,7 +7715,7 @@ async function stopAgentPanelItem(session, id) {
7717
7715
  ok: false,
7718
7716
  reason: "This item cannot be stopped from here."
7719
7717
  };
7720
- const source = sourceOf$1(session, id);
7718
+ const source = sourceOf(session, id);
7721
7719
  const taskId = agentPanelTaskId(id);
7722
7720
  if (taskId !== void 0 && source === void 0) {
7723
7721
  const store = getOwnerTaskStore(session);
@@ -7754,7 +7752,7 @@ async function answerAgentPanelItem(session, id, text, options) {
7754
7752
  ok: false,
7755
7753
  reason: "This item cannot be answered from here."
7756
7754
  };
7757
- const source = sourceOf$1(session, id);
7755
+ const source = sourceOf(session, id);
7758
7756
  const answer = source === void 0 ? void 0 : readPanelField(source, "answer");
7759
7757
  if (source === void 0 || typeof answer !== "function") return {
7760
7758
  ok: false,
@@ -13277,35 +13275,51 @@ parentPort.on("message", (msg) => {
13277
13275
  }
13278
13276
  });
13279
13277
  `;
13278
+ /**
13279
+ * How long a task with no time limit (a background history task's) runs on the shared worker before it gets that
13280
+ * worker to itself and the tasks after it get a new one. Its pattern may backtrack for minutes, and nothing but its
13281
+ * own stop would end it, so every other history call would otherwise wait behind it.
13282
+ */
13283
+ const OWN_WORKER_AFTER_MS = 200;
13280
13284
  let activeWorker;
13281
13285
  let activeTask;
13282
13286
  const waitingQueue = [];
13287
+ /** Workers handed to one long task with no time limit; each runs only that task and ends with it. */
13288
+ const ownWorkers = /* @__PURE__ */ new Map();
13283
13289
  let nextRequestId = 1;
13284
- function getWorker() {
13285
- if (!activeWorker) {
13286
- const worker = new Worker(WORKER_SCRIPT, {
13287
- eval: true,
13288
- execArgv: evalWorkerExecArgv()
13289
- });
13290
- worker.on("message", (message) => {
13291
- if (!activeTask || !message || message.id !== activeTask.id) return;
13292
- const task = activeTask;
13293
- activeTask = void 0;
13294
- if (message.error !== void 0) task.settle({ error: new Error(message.error) });
13295
- else task.settle({ reply: message });
13296
- pumpQueue();
13297
- });
13298
- worker.on("error", (error) => {
13299
- if (worker !== activeWorker) return;
13290
+ function spawnWorker() {
13291
+ const worker = new Worker(WORKER_SCRIPT, {
13292
+ eval: true,
13293
+ execArgv: evalWorkerExecArgv()
13294
+ });
13295
+ worker.on("message", (message) => {
13296
+ const task = worker === activeWorker ? activeTask : ownWorkers.get(worker);
13297
+ if (!task || !message || message.id !== task.id) return;
13298
+ if (worker === activeWorker) activeTask = void 0;
13299
+ else endOwnWorker(worker);
13300
+ if (message.error !== void 0) task.settle({ error: new Error(message.error) });
13301
+ else task.settle({ reply: message });
13302
+ pumpQueue();
13303
+ });
13304
+ worker.on("error", (error) => {
13305
+ let task;
13306
+ if (worker === activeWorker) {
13300
13307
  killActiveWorker();
13301
- const task = activeTask;
13308
+ task = activeTask;
13302
13309
  activeTask = void 0;
13303
- task?.settle({ error });
13304
- pumpQueue();
13305
- });
13306
- worker.unref();
13307
- activeWorker = worker;
13308
- }
13310
+ } else {
13311
+ task = ownWorkers.get(worker);
13312
+ if (!task) return;
13313
+ endOwnWorker(worker);
13314
+ }
13315
+ task?.settle({ error });
13316
+ pumpQueue();
13317
+ });
13318
+ worker.unref();
13319
+ return worker;
13320
+ }
13321
+ function getWorker() {
13322
+ activeWorker ??= spawnWorker();
13309
13323
  return activeWorker;
13310
13324
  }
13311
13325
  function killActiveWorker() {
@@ -13313,6 +13327,17 @@ function killActiveWorker() {
13313
13327
  activeWorker = void 0;
13314
13328
  if (current) current.terminate();
13315
13329
  }
13330
+ function endOwnWorker(worker) {
13331
+ ownWorkers.delete(worker);
13332
+ worker.terminate();
13333
+ }
13334
+ function handOffActiveWorker(task) {
13335
+ if (activeTask !== task || !activeWorker) return;
13336
+ ownWorkers.set(activeWorker, task);
13337
+ activeWorker = void 0;
13338
+ activeTask = void 0;
13339
+ pumpQueue();
13340
+ }
13316
13341
  function pumpQueue() {
13317
13342
  while (activeTask === void 0 && waitingQueue.length > 0) {
13318
13343
  const next = waitingQueue.shift();
@@ -13327,6 +13352,10 @@ function pumpQueue() {
13327
13352
  }, next.transfer ? [...next.transfer] : []);
13328
13353
  next.dispatched = true;
13329
13354
  activeTask = next;
13355
+ if (!Number.isFinite(next.deadline)) {
13356
+ next.handOff = setTimeout(() => handOffActiveWorker(next), OWN_WORKER_AFTER_MS);
13357
+ next.handOff.unref?.();
13358
+ }
13330
13359
  } catch (error) {
13331
13360
  activeTask = void 0;
13332
13361
  next.dispatched = false;
@@ -13351,6 +13380,7 @@ function runWorkerTask(payload, timeoutMs, signal, transfer) {
13351
13380
  if (settled) return;
13352
13381
  settled = true;
13353
13382
  clearTimeout(timer);
13383
+ clearTimeout(task.handOff);
13354
13384
  signal?.removeEventListener("abort", onAbort);
13355
13385
  if ("error" in outcome) reject(outcome.error);
13356
13386
  else if ("timedOut" in outcome) resolve(outcome);
@@ -13370,6 +13400,13 @@ function runWorkerTask(payload, timeoutMs, signal, transfer) {
13370
13400
  killActiveWorker();
13371
13401
  task.settle(outcome);
13372
13402
  pumpQueue();
13403
+ return;
13404
+ }
13405
+ for (const [worker, owner] of ownWorkers) {
13406
+ if (owner !== task) continue;
13407
+ endOwnWorker(worker);
13408
+ task.settle(outcome);
13409
+ return;
13373
13410
  }
13374
13411
  };
13375
13412
  const onAbort = () => {
@@ -13612,14 +13649,25 @@ function cutTextToUtf8Bytes(text, maxBytes) {
13612
13649
  }
13613
13650
  function entryPager(store, sessionId) {
13614
13651
  if (store.readEntryRange === void 0) throw new Error(`history:// cannot read session ${sessionId}: its session store (${store.descriptor.adapter}) does not implement SessionStore.readEntryRange`);
13615
- return { page: (fromSeq, toSeq, budget, maxChars = PAGE_CHARS) => budget.race(store.readEntryRange(sessionId, {
13616
- fromSeq,
13617
- toSeq,
13618
- maxChars,
13652
+ const read = (query, budget) => budget.race(store.readEntryRange(sessionId, {
13653
+ ...query,
13619
13654
  largeEntryBytes: LARGE_ENTRY_BYTES,
13620
13655
  skipTypes: SKIPPED_TYPES,
13621
13656
  signal: budget.storeSignal
13622
- })) };
13657
+ }));
13658
+ return {
13659
+ page: (fromSeq, toSeq, budget, maxChars = PAGE_CHARS) => read({
13660
+ fromSeq,
13661
+ toSeq,
13662
+ maxChars
13663
+ }, budget),
13664
+ pick: (seqs, budget) => read({
13665
+ fromSeq: seqs[0] ?? 1,
13666
+ toSeq: seqs.at(-1) ?? 0,
13667
+ seqs,
13668
+ maxChars: PAGE_CHARS
13669
+ }, budget)
13670
+ };
13623
13671
  }
13624
13672
  function renderedLines(entry) {
13625
13673
  return entryLines(entry).flatMap((line) => line.split("\n"));
@@ -14399,6 +14447,10 @@ var SessionSearcher = class {
14399
14447
  startTimedOut = false;
14400
14448
  lines = [];
14401
14449
  entryCache = /* @__PURE__ */ new Map();
14450
+ /** Entries read ahead of the search, each as the page a read of it alone returns (`readAheadFrom`). */
14451
+ readAhead = /* @__PURE__ */ new Map();
14452
+ /** The entries the search expects to read next, in ascending order: the index's candidates and their context. */
14453
+ planned = [];
14402
14454
  shown = 0;
14403
14455
  more = 0;
14404
14456
  firstMore;
@@ -14537,7 +14589,12 @@ var SessionSearcher = class {
14537
14589
  const to = Math.min(this.lastSeq, toSeq, from + rowsLeft - 1);
14538
14590
  if (from > to) return "ok";
14539
14591
  let page;
14540
- try {
14592
+ if (from === to && !this.readAhead.has(from)) await this.readAheadFrom(from);
14593
+ const ahead = from === to ? this.readAhead.get(from) : void 0;
14594
+ if (ahead !== void 0) {
14595
+ this.readAhead.delete(from);
14596
+ page = ahead;
14597
+ } else try {
14541
14598
  page = await this.pager.page(from, to, budget);
14542
14599
  } catch (error) {
14543
14600
  if (isHistoryDeadlineError(error)) return "timedOut";
@@ -14586,6 +14643,7 @@ var SessionSearcher = class {
14586
14643
  this.indexing = false;
14587
14644
  return { next: pos };
14588
14645
  }
14646
+ this.planReads(seqs);
14589
14647
  for (const seq of seqs) {
14590
14648
  const reason = budget.spent();
14591
14649
  if (reason && this.examined) return { stop: {
@@ -14629,6 +14687,49 @@ var SessionSearcher = class {
14629
14687
  }
14630
14688
  return { next: seqs.at(-1) + 1 };
14631
14689
  }
14690
+ /**
14691
+ * Plans to read ahead the entries at `candidates` and the ones next to them that their context lines may show: an
14692
+ * entry shows at least one line, so at most as many on each side as context lines asked for.
14693
+ */
14694
+ planReads(candidates) {
14695
+ const { contextBefore, contextAfter } = this.search.request;
14696
+ const before = Math.min(Math.max(0, contextBefore), CONTEXT_SPAN_SEQS);
14697
+ const after = Math.min(Math.max(0, contextAfter), CONTEXT_SPAN_SEQS);
14698
+ const seqs = /* @__PURE__ */ new Set();
14699
+ for (const candidate of candidates) for (let seq = Math.max(1, candidate - before); seq <= Math.min(this.lastSeq, candidate + after); seq++) seqs.add(seq);
14700
+ this.planned = [...seqs].sort((a, b) => a - b);
14701
+ this.readAhead.clear();
14702
+ }
14703
+ /**
14704
+ * Reads the planned entries from `seq`'s context on that the search has not read, a page of them in one read, as a database
14705
+ * reads ahead the pages an index scan will visit: each candidate the index names, and each entry its context shows,
14706
+ * used to cost a read, and a round trip, of its own. Each entry is kept as the page a read of it alone returns, and
14707
+ * taken in that read's place when the search reaches it, so the search counts rows, stops and resumes as it did. A
14708
+ * failed read keeps nothing: the search then reads each entry alone, as before, and meets the failure, or the time
14709
+ * budget, there.
14710
+ */
14711
+ async readAheadFrom(seq) {
14712
+ if (!this.planned.includes(seq)) return;
14713
+ const from = seq - Math.min(Math.max(0, this.search.request.contextBefore), CONTEXT_SPAN_SEQS);
14714
+ const wanted = this.planned.filter((each) => each >= from && (each === seq || !this.entryCache.has(each) && !this.readAhead.has(each)));
14715
+ if (wanted.length < 2) return;
14716
+ let page;
14717
+ try {
14718
+ page = await this.pager.pick(wanted, this.search.budget);
14719
+ } catch {
14720
+ return;
14721
+ }
14722
+ const found = new Map(page.entries.map((item) => [item.seq, item]));
14723
+ for (const each of wanted) {
14724
+ if (each > page.throughSeq) break;
14725
+ const item = found.get(each);
14726
+ this.readAhead.set(each, {
14727
+ lastSeq: page.lastSeq,
14728
+ entries: item === void 0 ? [] : [item],
14729
+ throughSeq: each
14730
+ });
14731
+ }
14732
+ }
14632
14733
  timeoutOnEntry(seq, completedMatches = 0) {
14633
14734
  if (!this.emittedAny && seq === this.coveredFromSeq) {
14634
14735
  this.skipped = seq;
@@ -25174,1137 +25275,6 @@ async function resolveSessionStore(cwd, options = {}) {
25174
25275
  throw error;
25175
25276
  }
25176
25277
  }
25177
- // dist/core/storage/storage-status.js
25178
- /** How long one database connectivity check may take, from opening the database to the answer of its `SELECT 1`. */
25179
- const STORAGE_PROBE_TIMEOUT_MS = 15e3;
25180
- /**
25181
- * How long `storage status` waits for an adapter module to load before giving up on a hung evaluation; separate from
25182
- * {@link STORAGE_PROBE_TIMEOUT_MS} so the server-probe timer starts only once the connection attempt starts.
25183
- */
25184
- const STORAGE_ADAPTER_LOAD_TIMEOUT_MS = 15e3;
25185
- const errorText = describeStorageError;
25186
- function envSet(name) {
25187
- const value = process.env[name];
25188
- return value !== void 0 && value.length > 0;
25189
- }
25190
- function prefixSuffix(prefix) {
25191
- return prefix ? ` (prefix ${prefix})` : "";
25192
- }
25193
- function describeStorageSelection(selection) {
25194
- switch (selection.kind) {
25195
- case "memory": return "memory";
25196
- case "jsonl": return `JSONL directory ${selection.dir}`;
25197
- case "sqlite": return `SQLite ${selection.path}${prefixSuffix(selection.prefix)}`;
25198
- case "database": return `database ${selection.database.descriptor.adapter}${prefixSuffix(selection.prefix)}`;
25199
- case "adapter": {
25200
- const server = postgresServer(selection);
25201
- if (server !== void 0) return `PostgreSQL ${server} via ${selection.module}${prefixSuffix(selection.prefix)}`;
25202
- return `adapter ${selection.module}${prefixSuffix(selection.prefix)}`;
25203
- }
25204
- }
25205
- }
25206
- /** A Postgres selection's server, without the user name, the query and the fragment; undefined for other selections. */
25207
- function postgresServer(selection) {
25208
- const url = selection.options?.url;
25209
- if (selection.module !== POSTGRES_ADAPTER_PACKAGE || typeof url !== "string" || !URL.canParse(url)) return void 0;
25210
- const server = new URL(url);
25211
- server.username = "";
25212
- server.password = "";
25213
- server.search = "";
25214
- server.hash = "";
25215
- return server.href;
25216
- }
25217
- function withTimeout(operation, label, timeoutMs) {
25218
- let timer;
25219
- return Promise.race([operation, new Promise((_, reject) => {
25220
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${label} did not answer within ${timeoutMs / 1e3} s`)), timeoutMs);
25221
- })]).finally(() => clearTimeout(timer));
25222
- }
25223
- /**
25224
- * Load the selection's adapter and run `SELECT 1` on its database; `inspect` reads it before it closes. Nothing is
25225
- * created: a SQLite file that does not exist yet is not opened, and no Atomic table is touched.
25226
- */
25227
- async function probeSelection(selection, context, inspect, timeoutMs) {
25228
- if (selection.kind === "memory") return { connection: {
25229
- status: "skipped",
25230
- detail: "in memory; nothing to open"
25231
- } };
25232
- if (selection.kind === "jsonl") return { connection: {
25233
- status: "skipped",
25234
- detail: existsSync$1(selection.dir) ? "directory exists" : "directory not created yet"
25235
- } };
25236
- if (selection.kind === "database") return { connection: {
25237
- status: "skipped",
25238
- detail: "caller-owned database"
25239
- } };
25240
- if (selection.kind === "sqlite") {
25241
- if (selection.path === "" || selection.path === ":memory:") return { connection: {
25242
- status: "skipped",
25243
- detail: "in memory; nothing to open"
25244
- } };
25245
- if (!existsSync$1(selection.path)) return { connection: {
25246
- status: "skipped",
25247
- detail: "file not created yet; Atomic creates it on first use"
25248
- } };
25249
- const { openNodeSqliteDatabase } = await import("../core/storage/node-sqlite.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
25250
- return { connection: await roundTrip(() => openNodeSqliteDatabase(selection.path, { readOnly: true }), "SQLite file", inspect, timeoutMs) };
25251
- }
25252
- const module = selection.module;
25253
- let adapter;
25254
- try {
25255
- adapter = await withTimeout(loadStorageAdapter(module, context), "Loading the adapter", Math.max(timeoutMs, STORAGE_ADAPTER_LOAD_TIMEOUT_MS));
25256
- } catch (error) {
25257
- return {
25258
- adapter: {
25259
- module,
25260
- loaded: false,
25261
- detail: errorText(error)
25262
- },
25263
- connection: {
25264
- status: "skipped",
25265
- detail: "adapter not loaded"
25266
- }
25267
- };
25268
- }
25269
- const { resolvePackageStorageAdapter } = await import("../core/package-manager-storage-adapters.code.js").catch((error) => __atomicOnDemandFailed(error, "this feature"));
25270
- const resolved = await resolvePackageStorageAdapter(module, context.agentDir);
25271
- const loaded = {
25272
- module,
25273
- loaded: true,
25274
- ...resolved === void 0 ? {} : { detail: `from ${resolved}` }
25275
- };
25276
- if (adapter.openDatabase === void 0) return {
25277
- adapter: loaded,
25278
- noDatabaseHook: true,
25279
- connection: {
25280
- status: "skipped",
25281
- detail: "the adapter has no openDatabase hook; its stores were not opened"
25282
- }
25283
- };
25284
- let options;
25285
- try {
25286
- options = await resolveAdapterOptions(selection, context, adapter.liveSecrets);
25287
- } catch (error) {
25288
- return {
25289
- adapter: loaded,
25290
- connection: {
25291
- status: "failed",
25292
- detail: errorText(error)
25293
- }
25294
- };
25295
- }
25296
- if (typeof options.url === "string" && options.url.startsWith("file:")) {
25297
- if (!options.url.startsWith("file:/")) return {
25298
- adapter: loaded,
25299
- connection: {
25300
- status: "skipped",
25301
- detail: "relative file: URL cannot be safely probed"
25302
- }
25303
- };
25304
- try {
25305
- const path = fileURLToPath(options.url);
25306
- if (!existsSync$1(path)) return {
25307
- adapter: loaded,
25308
- connection: {
25309
- status: "skipped",
25310
- detail: "file not found; Atomic creates it on first use"
25311
- }
25312
- };
25313
- return {
25314
- adapter: loaded,
25315
- connection: (await probeSelection({
25316
- kind: "sqlite",
25317
- path
25318
- }, context, inspect, timeoutMs)).connection
25319
- };
25320
- } catch (error) {
25321
- return {
25322
- adapter: loaded,
25323
- connection: {
25324
- status: "failed",
25325
- detail: errorText(error)
25326
- }
25327
- };
25328
- }
25329
- }
25330
- return {
25331
- adapter: loaded,
25332
- connection: await roundTrip(() => openAdapterSelectionDatabase(selection, context, adapter), "The database", inspect, timeoutMs, postgresServer(selection))
25333
- };
25334
- }
25335
- /** The server version a Postgres database reports, as status shows it after the `SELECT 1` answer. */
25336
- async function postgresServerVersion(database) {
25337
- return `PostgreSQL ${(await database.get("SELECT current_setting('server_version') AS version")).version}`;
25338
- }
25339
- /**
25340
- * How a Postgres database's wake-ups reach this process (#5103): through `LISTEN`, or by polling alone, and why. Undefined
25341
- * for a database without notifications.
25342
- */
25343
- async function postgresWakeUps(database) {
25344
- const state = await database.notifications?.state();
25345
- if (state === void 0) return void 0;
25346
- if (state.status === "listening") return "wake-ups: LISTEN/NOTIFY";
25347
- if (state.status === "connecting") return "wake-ups: connecting";
25348
- return state.reason === "pooler" ? "wake-ups: polling only, notifications do not pass the URL's transaction pooler (set listenUrl to a direct endpoint)" : "wake-ups: polling only, the listen connection failed";
25349
- }
25350
- async function roundTrip(open, label, inspect, timeoutMs, postgres) {
25351
- const started = Date.now();
25352
- let database;
25353
- try {
25354
- database = await withTimeout(open(), label, timeoutMs);
25355
- const opened = database;
25356
- await withTimeout(opened.get("SELECT 1 AS ok"), label, timeoutMs);
25357
- const elapsed = Date.now() - started;
25358
- if (inspect) await withTimeout(inspect(opened), "Inspecting the database", timeoutMs).catch(() => {});
25359
- if (postgres !== void 0) {
25360
- const version = await withTimeout(postgresServerVersion(opened), "Reading the server version", timeoutMs).catch(() => void 0);
25361
- const wakeUps = await withTimeout(postgresWakeUps(opened), "Probing wake-ups", timeoutMs).catch(() => void 0);
25362
- return {
25363
- status: "ok",
25364
- detail: `postgres ${postgres} answered in ${elapsed} ms${version === void 0 ? "" : `, ${version}`}${wakeUps === void 0 ? "" : `; ${wakeUps}`}`
25365
- };
25366
- }
25367
- return {
25368
- status: "ok",
25369
- detail: `${opened.descriptor.adapter} ${opened.descriptor.location} answered in ${elapsed} ms`
25370
- };
25371
- } catch (error) {
25372
- return {
25373
- status: "failed",
25374
- detail: errorText(error)
25375
- };
25376
- } finally {
25377
- if (database) await withTimeout(database.close(), "Closing the database", timeoutMs).catch(() => {});
25378
- }
25379
- }
25380
- function settingLayers(global, project, projectTrusted, read, field) {
25381
- return [{
25382
- label: `project settings: ${field}`,
25383
- present: projectTrusted && read(project) !== void 0
25384
- }, {
25385
- label: `global settings: ${field}`,
25386
- present: read(global) !== void 0
25387
- }];
25388
- }
25389
- function sourceOf(layers) {
25390
- const present = layers.filter((layer) => layer.present).map((layer) => layer.label);
25391
- return {
25392
- source: present[0] ?? "default",
25393
- overridden: present.slice(1)
25394
- };
25395
- }
25396
- /** The source label of the `ATOMIC_PROFILE=ci` team database. */
25397
- const TEAM_PROFILE_SOURCE = `${TEAM_PROFILE_ENV}=ci`;
25398
- /**
25399
- * The shared selection this process and these settings make: `--storage`, `ATOMIC_STORAGE` or the
25400
- * `ATOMIC_PROFILE=ci` team database, else the `storage` setting; `undefined` when none of them is set.
25401
- */
25402
- function selectSharedStorage(agentDir, settings) {
25403
- const processChoice = selectProcessStorage("shared", agentDir, void 0, settings);
25404
- if (processChoice !== void 0) return processChoice.selection;
25405
- const value = settings.storage;
25406
- if (value === void 0) return void 0;
25407
- const selection = selectStorage(value, "settings", "storage", () => defaultSharedStoragePath(agentDir, settings));
25408
- return selection.kind === "sqlite" && !isAbsolute$1(selection.path) ? {
25409
- ...selection,
25410
- path: join$1(storagePathBaseDir(selection.path, agentDir, settings), selection.path)
25411
- } : selection;
25412
- }
25413
- /**
25414
- * The raw shared selection a broker started from this process would read: `--storage`, `ATOMIC_STORAGE` or the
25415
- * `ATOMIC_PROFILE=ci` team database, else global `storage`.
25416
- */
25417
- function sharedSelection(globalStorage, processSelection = processSharedStorageSelection()) {
25418
- if (processSelection === void 0) return globalStorage;
25419
- const parsed = JSON.parse(processSelection);
25420
- return parsed === null || typeof parsed !== "object" || Array.isArray(parsed) ? void 0 : parsed;
25421
- }
25422
- /**
25423
- * The shared selection Intercom's multi-node routing would use, resolved like the broker resolves it; `undefined`
25424
- * when there is none or it is in memory, which leaves multi-node routing off.
25425
- */
25426
- function selectIntercomStorage(agentDir, globalStorage) {
25427
- const processSelection = processSharedStorageSelection();
25428
- const value = sharedSelection(globalStorage, processSelection);
25429
- if (value === void 0) return void 0;
25430
- const settings = globalStorage === void 0 ? void 0 : { storage: globalStorage };
25431
- const selection = selectStorage(value, processSelection === void 0 ? "settings" : "env", "storage", () => defaultSharedStoragePath(agentDir, settings));
25432
- if (selection.kind === "memory" || selection.kind === "sqlite" && selection.path === ":memory:") return void 0;
25433
- return selection.kind === "sqlite" && !isAbsolute$1(selection.path) ? {
25434
- ...selection,
25435
- path: resolvePath(selection.path, storagePathBaseDir(selection.path, agentDir, settings))
25436
- } : selection;
25437
- }
25438
- function projectTrust(cwd, agentDir) {
25439
- if (!hasProjectTrustInputs(cwd)) return true;
25440
- return new ProjectTrustStore(agentDir).get(cwd) ?? SettingsManager.create(cwd, agentDir, { projectTrusted: false }).getDefaultProjectTrust() === "always";
25441
- }
25442
- /** The shared selection {@link selectSharedStorage} makes in this directory, with its trusted project settings. */
25443
- function effectiveSharedSelection(cwd, agentDir) {
25444
- return selectSharedStorage(agentDir, SettingsManager.create(cwd, agentDir, { projectTrusted: projectTrust(cwd, agentDir) }).getSettings());
25445
- }
25446
- /**
25447
- * Which storage each domain selects and where that selection comes from, following the same precedence as
25448
- * sessions and the Intercom broker; with `probe`, whether each adapter loads and each database answers, and what the
25449
- * running broker uses.
25450
- */
25451
- async function collectStorageStatus(options) {
25452
- const { cwd, agentDir } = options;
25453
- const projectTrusted = projectTrust(cwd, agentDir);
25454
- const manager = SettingsManager.create(cwd, agentDir, { projectTrusted });
25455
- const settingsErrors = manager.drainErrors().filter(({ invalidKey }) => invalidKey === void 0);
25456
- if (settingsErrors.length > 0) throw new Error(`Cannot load settings: ${settingsErrors.map(({ scope, error }) => `${scope} settings: ${error.message}`).join("; ")}`);
25457
- const global = manager.getGlobalSettings();
25458
- const project = manager.getProjectSettings();
25459
- const merged = manager.getSettings();
25460
- const notes = [];
25461
- let usesLocalStorage = false;
25462
- const unappliedProject = projectTrusted ? {} : SettingsManager.create(cwd, agentDir, { projectTrusted: true }).getProjectSettings();
25463
- if (unappliedProject.storage !== void 0 || unappliedProject.sessions?.storage !== void 0) notes.push("Project settings select storage, but the project is not trusted, so they are not applied.");
25464
- if (projectTrusted && project.storage !== void 0) notes.push("Project settings set `storage`, which Intercom ignores: multi-node routing reads only global settings or ATOMIC_STORAGE.");
25465
- const env = (name) => ({
25466
- label: name,
25467
- present: envSet(name)
25468
- });
25469
- const teamProfile = {
25470
- label: TEAM_PROFILE_SOURCE,
25471
- present: envSet(TEAM_PROFILE_ENV)
25472
- };
25473
- const sessionsSetting = (settings) => settings.sessions?.storage;
25474
- const storageSetting = (settings) => settings.storage;
25475
- const layers = {
25476
- sessions: [
25477
- env(SESSIONS_STORAGE_ENV),
25478
- env(ENV_SESSION_DIR),
25479
- env(STORAGE_ENV),
25480
- teamProfile,
25481
- ...settingLayers(global, project, projectTrusted, sessionsSetting, "sessions.storage"),
25482
- ...settingLayers(global, project, projectTrusted, storageSetting, "storage")
25483
- ],
25484
- intercom: [
25485
- env(STORAGE_ENV),
25486
- teamProfile,
25487
- {
25488
- label: "global settings: storage",
25489
- present: global.storage !== void 0
25490
- }
25491
- ]
25492
- };
25493
- const checked = /* @__PURE__ */ new Map();
25494
- const probeOnce = async (domain, selection, inspect) => {
25495
- if (!options.probe) return void 0;
25496
- const key = storageSelectionKey(selection, agentDir);
25497
- const earlier = checked.get(key);
25498
- if (earlier !== void 0 && inspect === void 0) return {
25499
- ...earlier.probe,
25500
- sameAs: earlier.domain
25501
- };
25502
- const probe = await probeSelection(selection, {
25503
- agentDir,
25504
- domain
25505
- }, inspect, options.probeTimeoutMs ?? 15e3);
25506
- if (earlier === void 0) checked.set(key, {
25507
- domain,
25508
- probe
25509
- });
25510
- return probe;
25511
- };
25512
- const domains = [];
25513
- const sessions = sourceOf(layers.sessions);
25514
- try {
25515
- const selection = selectSessionStorageWithSettings(cwd, {
25516
- agentDir,
25517
- settings: merged
25518
- });
25519
- if (selection.kind === "sqlite" || selection.kind === "jsonl") usesLocalStorage = true;
25520
- const probe = await probeOnce("sessions", selection);
25521
- domains.push({
25522
- domain: "sessions",
25523
- selection: describeStorageSelection(selection),
25524
- source: sessions.source,
25525
- overridden: sessions.overridden,
25526
- ...probe === void 0 ? {} : { probe }
25527
- });
25528
- } catch (error) {
25529
- domains.push({
25530
- domain: "sessions",
25531
- selection: "invalid",
25532
- source: sessions.source,
25533
- overridden: sessions.overridden,
25534
- error: errorText(error)
25535
- });
25536
- }
25537
- const intercom = sourceOf(layers.intercom);
25538
- try {
25539
- const resolved = selectIntercomStorage(agentDir, global.storage);
25540
- if (resolved === void 0) domains.push({
25541
- domain: "intercom",
25542
- selection: "off",
25543
- source: intercom.source,
25544
- overridden: intercom.overridden,
25545
- multiNode: sharedSelection(global.storage) === void 0 ? "off: no shared storage selection (top-level `storage` in global settings, ATOMIC_STORAGE, or ATOMIC_PROFILE=ci)" : "off: the shared storage selection is in memory"
25546
- });
25547
- else {
25548
- if (resolved.kind === "sqlite") usesLocalStorage = true;
25549
- let liveBrokers;
25550
- const control = options.control;
25551
- const probe = await probeOnce("intercom", resolved, control === void 0 ? void 0 : async (database) => {
25552
- liveBrokers = await control.readLiveBrokers(database, resolved.kind === "adapter" || resolved.kind === "sqlite" ? resolved.prefix : void 0) ?? [];
25553
- });
25554
- const multiNode = probe === void 0 ? void 0 : probe.adapter?.loaded === false ? "off: the adapter cannot be loaded" : probe.noDatabaseHook ? "off: the adapter has no openDatabase hook" : probe.connection.status === "failed" ? "unavailable: the database did not answer" : resolved.kind === "sqlite" ? "on (a local SQLite file: only brokers on this machine share it)" : "on";
25555
- domains.push({
25556
- domain: "intercom",
25557
- selection: describeStorageSelection(resolved),
25558
- source: intercom.source,
25559
- overridden: intercom.overridden,
25560
- ...probe === void 0 ? {} : { probe },
25561
- ...multiNode === void 0 ? {} : { multiNode },
25562
- ...liveBrokers === void 0 ? {} : { liveBrokers }
25563
- });
25564
- }
25565
- } catch (error) {
25566
- domains.push({
25567
- domain: "intercom",
25568
- selection: "invalid",
25569
- source: intercom.source,
25570
- overridden: intercom.overridden,
25571
- error: errorText(error)
25572
- });
25573
- }
25574
- if (usesLocalStorage) {
25575
- const adoptionNotice = takeStorageAdoptionNotice(agentDir, merged);
25576
- if (adoptionNotice !== void 0) notes.unshift(adoptionNotice);
25577
- }
25578
- return {
25579
- agentDir,
25580
- cwd,
25581
- projectTrusted,
25582
- domains,
25583
- notes,
25584
- ...options.control === void 0 ? {} : { broker: await brokerSection(options.control, agentDir) }
25585
- };
25586
- }
25587
- async function brokerSection(control, agentDir) {
25588
- try {
25589
- const query = await control.queryIntercomBroker(agentDir);
25590
- if (query.state === "stopped") return { state: "stopped" };
25591
- if (query.state === "legacy") return query.pid === void 0 ? { state: "legacy" } : {
25592
- state: "legacy",
25593
- pid: query.pid
25594
- };
25595
- const { report } = query;
25596
- const expected = control.expectedBrokerStorage(agentDir, processStorageEnvironment());
25597
- return {
25598
- state: "running",
25599
- pid: report.pid,
25600
- sessions: report.sessions,
25601
- matchesCurrent: report.storage?.digest === expected?.digest,
25602
- ...report.storage === void 0 ? {} : { source: report.storage.source },
25603
- multiNode: report.multiNode,
25604
- multiNodeLine: control.describeMultiNodeStatus(report.multiNode)
25605
- };
25606
- } catch (error) {
25607
- return {
25608
- state: "unknown",
25609
- error: errorText(error)
25610
- };
25611
- }
25612
- }
25613
- /**
25614
- * The launch warning for a shared storage adapter this executable cannot load: the Intercom broker would leave
25615
- * multi-node routing off with only a `broker.log` line. Load-only: no database is opened. `undefined` when the
25616
- * shared selection names no adapter or it loads.
25617
- */
25618
- async function checkSharedStorageAdapter(agentDir, globalStorage) {
25619
- let value;
25620
- try {
25621
- value = sharedSelection(globalStorage);
25622
- } catch {
25623
- return;
25624
- }
25625
- const module = value?.adapter;
25626
- if (typeof module !== "string" || module.length === 0) return void 0;
25627
- try {
25628
- await loadStorageAdapter(module, {
25629
- agentDir,
25630
- domain: "intercom"
25631
- });
25632
- return;
25633
- } catch (error) {
25634
- const executable = isBunBinary ? process.execPath : process.argv[1] ?? process.execPath;
25635
- const cause = error instanceof StorageAdapterLoadError && error.cause instanceof Error ? error.cause : error;
25636
- return `Storage adapter "${module}" cannot be loaded by this Atomic (${executable}): ${errorText(cause)}. Intercom multi-node routing stays off, and sessions that select this adapter fail to open. Run "atomic storage status" for details.`;
25637
- }
25638
- }
25639
- // dist/core/storage/team.js
25640
- /**
25641
- * Team setup: one settings write that shares Intercom routing through a team database while
25642
- * sessions stay in the local store (`joinTeam`), its exact undo (`leaveTeam`), the layout in effect
25643
- * (`getTeamProfile`), and the shared-database join that `atomic storage join` and `atomic team join` both run.
25644
- */
25645
- function settingsPathOf(agentDir) {
25646
- return join$1(agentDir, "settings.json");
25647
- }
25648
- /**
25649
- * Why a settings file cannot be read, without any of its content: the file-system error code, or where its JSON
25650
- * breaks. A parser message can quote part of the file, such as a key, so it is never shown.
25651
- */
25652
- function unreadableSettingsDetail(error) {
25653
- const code = error.code;
25654
- if (typeof code === "string") return code;
25655
- if (!(error instanceof SyntaxError)) return error.name;
25656
- const position = /\(line (\d+) column (\d+)\)/.exec(error.message);
25657
- return position === null ? "not valid JSON" : `not valid JSON at line ${position[1]}, column ${position[2]}`;
25658
- }
25659
- function unreadableSettingsError(subject, cause) {
25660
- return new TeamProfileError("settings-unreadable", {
25661
- subject,
25662
- detail: unreadableSettingsDetail(cause),
25663
- hint: `Fix ${subject} first, then run the command again.`,
25664
- cause
25665
- });
25666
- }
25667
- function openGlobalSettings(cwd, agentDir) {
25668
- const manager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });
25669
- const failure = manager.drainErrors().find(({ invalidKey }) => invalidKey === void 0);
25670
- if (failure !== void 0) {
25671
- const settingsPath = failure.path ?? settingsPathOf(agentDir);
25672
- if (isLocked(failure.error)) throw lockedError(settingsPath, failure.error, "Nothing was changed.");
25673
- throw unreadableSettingsError(settingsPath, failure.error);
25674
- }
25675
- return manager;
25676
- }
25677
- function writePrivateFile(path, token) {
25678
- mkdirSync$1(dirname$1(path), { recursive: true });
25679
- const temporary = `${path}.${process.pid}.tmp`;
25680
- try {
25681
- writeFileSync$1(temporary, token, { mode: 384 });
25682
- chmodSync$1(temporary, 384);
25683
- renameSync$1(temporary, path);
25684
- } catch (error) {
25685
- rmSync$1(temporary, { force: true });
25686
- throw error;
25687
- }
25688
- }
25689
- async function checkConnection(target, agentDir, adapter) {
25690
- const database = await openAdapterSelectionDatabase({
25691
- kind: "adapter",
25692
- module: target.adapter,
25693
- options: target.options,
25694
- ...target.secret === void 0 ? {} : { secrets: { [target.secretName]: inMemorySecret(target.secret) } }
25695
- }, {
25696
- agentDir,
25697
- domain: "sessions"
25698
- }, adapter);
25699
- try {
25700
- await database.get("SELECT 1 AS ok");
25701
- } finally {
25702
- await database.close();
25703
- }
25704
- }
25705
- /** The `StorageConfigError` `error` is, or was caused by, if any. */
25706
- function storageConfigCause(error) {
25707
- let current = error;
25708
- for (let depth = 0; depth < 8 && current instanceof Error; depth++) {
25709
- if (current instanceof StorageConfigError) return current;
25710
- current = current.cause;
25711
- }
25712
- }
25713
- /** How long a join waits for the team database to connect and answer `SELECT 1`, after the adapter has loaded. */
25714
- const TEAM_CONNECTION_TIMEOUT_MS = 15e3;
25715
- /**
25716
- * `checkConnection`, bounded by `timeoutMs` once the adapter module has loaded: a database that does not answer fails
25717
- * with a retryable {@link TeamProfileTimeoutError} instead of waiting for the operating system's connection timeout. A
25718
- * check that fails after the deadline is recorded as the timeout error's `cleanupCause`. `elapsedMs` is never below
25719
- * `timeoutMs`: Node can fire a timer a millisecond before the wall clock shows its delay has passed.
25720
- */
25721
- async function checkConnectionWithin(target, agentDir, timeoutMs) {
25722
- const url = target.options.url;
25723
- let timer;
25724
- let started = 0;
25725
- let check;
25726
- let outcome;
25727
- try {
25728
- const adapter = await loadStorageAdapter(target.adapter, {
25729
- agentDir,
25730
- domain: "sessions"
25731
- });
25732
- started = Date.now();
25733
- check = checkConnection(target, agentDir, adapter).then(() => "answered");
25734
- const deadline = new Promise((resolveDeadline) => {
25735
- timer = setTimeout(() => resolveDeadline("timed-out"), timeoutMs);
25736
- });
25737
- outcome = await Promise.race([check, deadline]);
25738
- } catch (error) {
25739
- const config = storageConfigCause(error);
25740
- if (config?.reason === "auth-unavailable") throw new TeamProfileError("auth-unavailable", {
25741
- subject: url,
25742
- detail: "auth-unavailable",
25743
- hint: `Nothing was changed. ${config.hint ?? "Check the cloud identity's sign-in"}`,
25744
- cause: error
25745
- });
25746
- if (config !== void 0) throw config;
25747
- throw new TeamProfileError("connection-failed", {
25748
- subject: url,
25749
- detail: describeStorageError$1(error),
25750
- hint: "Nothing was changed. Check the URL, the token and the network, then run the command again.",
25751
- cause: error
25752
- });
25753
- } finally {
25754
- clearTimeout(timer);
25755
- }
25756
- if (outcome === "answered") return;
25757
- const timeout = new TeamProfileTimeoutError({
25758
- subject: url,
25759
- timeoutMs,
25760
- elapsedMs: Math.max(Date.now() - started, timeoutMs),
25761
- phase: "connect",
25762
- hint: "Nothing was changed. Check that the database is reachable from this machine, then run the command again."
25763
- });
25764
- check.catch((late) => {
25765
- Object.defineProperty(timeout, "cleanupCause", {
25766
- value: late,
25767
- configurable: true
25768
- });
25769
- });
25770
- throw timeout;
25771
- }
25772
- /** The token file a `{ file }` reference names, resolved like the storage provider resolves it. */
25773
- function secretFilePath(ref, agentDir) {
25774
- if (ref === void 0 || !("file" in ref)) return void 0;
25775
- return resolve$1(secretFilePath$1(ref.file, agentDir));
25776
- }
25777
- /** Whether a path is a token file that a join created in this agent directory. */
25778
- function isJoinTokenFile(path, agentDir) {
25779
- return dirname$1(path) === resolve$1(agentDir) && basename$1(path).startsWith(`${STORAGE_TOKEN_FILE}.`);
25780
- }
25781
- /** The join-created token file `storage` references as `secretName`, when it already holds `token`. */
25782
- function reusableTokenFile(storage, secretName, token, agentDir) {
25783
- const path = secretFilePath(storage?.secrets?.[secretName], agentDir);
25784
- if (path === void 0 || !isJoinTokenFile(path, agentDir)) return void 0;
25785
- let stored;
25786
- try {
25787
- stored = readFileSync$1(path, "utf8");
25788
- } catch (error) {
25789
- if (error instanceof Error) return void 0;
25790
- throw error;
25791
- }
25792
- return stored === token ? path : void 0;
25793
- }
25794
- function isLocked(error) {
25795
- return error.code === "ELOCKED";
25796
- }
25797
- /** Another process holds the settings lock: retryable, since a lock left by a killed process expires. */
25798
- function lockedError(settingsPath, cause, outcome) {
25799
- return new TeamProfileError("settings-locked", {
25800
- subject: settingsPath,
25801
- hint: `${outcome} Run the command again in a few seconds; a lock left by a killed process expires after 10 seconds.`,
25802
- cause
25803
- });
25804
- }
25805
- /** A failed settings write: `settings-locked` while another process holds the lock, else the I/O error. */
25806
- function settingsWriteError(settingsPath, cause, outcome) {
25807
- if (isLocked(cause)) return lockedError(settingsPath, cause, outcome);
25808
- return new TeamProfileError("settings-write-failed", {
25809
- subject: settingsPath,
25810
- detail: describeStorageError$1(cause),
25811
- hint: `${outcome} Check that the file and its directory are writable and the disk has space, then run the command again.`,
25812
- cause
25813
- });
25814
- }
25815
- function withGlobalSettings(agentDir, outcome, run) {
25816
- const settingsPath = settingsPathOf(agentDir);
25817
- let result;
25818
- try {
25819
- new FileSettingsStorage(dirname$1(agentDir), agentDir).withPrimaryWriteLock("global", (current) => {
25820
- let settings = {};
25821
- if (current !== void 0) try {
25822
- const parsed = parseJsonFileContent(current);
25823
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("not a JSON object");
25824
- settings = parsed;
25825
- } catch (error) {
25826
- throw unreadableSettingsError(settingsPath, error);
25827
- }
25828
- result = run(settings);
25829
- });
25830
- } catch (error) {
25831
- if (error instanceof TeamProfileError) throw error;
25832
- throw settingsWriteError(settingsPath, error, outcome);
25833
- }
25834
- return result;
25835
- }
25836
- function cleanupAfter(primary, cleanup) {
25837
- try {
25838
- cleanup();
25839
- } catch (cleanupCause) {
25840
- Object.defineProperty(primary, "cleanupCause", {
25841
- value: cleanupCause,
25842
- configurable: true
25843
- });
25844
- }
25845
- }
25846
- function joinPlan(options, source, cwd) {
25847
- if (!options.pinLocalSessions && isPostgresUrl(options.url)) {
25848
- const checked = checkSharedDatabaseArguments(options);
25849
- const target = {
25850
- adapter: POSTGRES_ADAPTER_PACKAGE,
25851
- secretName: "password"
25852
- };
25853
- if (checked.auth !== void 0) return { target: {
25854
- ...target,
25855
- options: {
25856
- url: checked.url,
25857
- auth: checked.auth
25858
- }
25859
- } };
25860
- if (checked.passwordFile !== void 0) {
25861
- const password = readTeamTokenFile(resolve$1(cwd, checked.passwordFile), source, "--password-file");
25862
- return {
25863
- target: {
25864
- ...target,
25865
- options: { url: checked.url },
25866
- secret: password
25867
- },
25868
- copy: password
25869
- };
25870
- }
25871
- const reference = resolve$1(cwd, checked.tokenFile);
25872
- const password = readTeamTokenFile(reference, source, void 0, "as-connections-read");
25873
- return {
25874
- target: {
25875
- ...target,
25876
- options: { url: checked.url },
25877
- secret: password
25878
- },
25879
- reference
25880
- };
25881
- }
25882
- const url = checkTeamUrl(options.url, source);
25883
- if (options.token !== void 0 && options.tokenFile !== void 0) throw conflictingTeamToken(source, source === "cli" ? ["--token-file"] : ["token", "tokenFile"]);
25884
- let token;
25885
- if (options.tokenFile !== void 0) token = readTeamTokenFile(resolve$1(cwd, options.tokenFile), source);
25886
- else if (options.token !== void 0) {
25887
- token = options.token.trim();
25888
- if (token.length === 0) throw emptyTeamToken(source);
25889
- } else if (!isFileUrl(url)) throw missingTeamToken(url, source);
25890
- return {
25891
- target: {
25892
- adapter: LIBSQL_ADAPTER_PACKAGE,
25893
- options: { url },
25894
- secretName: "authToken",
25895
- secret: token
25896
- },
25897
- copy: token
25898
- };
25899
- }
25900
- /**
25901
- * Point the global `storage` setting at a shared libSQL / Turso or PostgreSQL database, as `atomic storage join` and
25902
- * `atomic team join` do. Every input and precondition is checked before the first write: the URL, the token, the
25903
- * prefix, readable global settings, the installed adapter and a `SELECT 1` on the database. The token is stored in a
25904
- * private file in the agent directory (mode 600), reusing the file the current selection references when it already
25905
- * holds the same token, and settings are written in one update; with `pinLocalSessions`, that update also sets
25906
- * `sessions.storage` to the local default store. On failure nothing is changed.
25907
- */
25908
- async function joinSharedDatabase(options, source, connectionTimeoutMs = TEAM_CONNECTION_TIMEOUT_MS) {
25909
- const agentDir = resolve$1(options.agentDir ?? getAgentDir());
25910
- const cwd = resolve$1(options.cwd ?? process.cwd());
25911
- const plan = joinPlan(options, source, cwd);
25912
- const { target } = plan;
25913
- const token = plan.copy;
25914
- const prefix = checkTeamPrefix(options.prefix, source);
25915
- openGlobalSettings(cwd, agentDir);
25916
- const settingsPath = settingsPathOf(agentDir);
25917
- if (await resolvePackageStorageAdapter(target.adapter, agentDir) === void 0) throw new TeamProfileError("adapter-not-installed", {
25918
- subject: `${target.adapter} for ${agentDir}`,
25919
- hint: `Install it, then run this command again: atomic install npm:${target.adapter}`
25920
- });
25921
- await checkConnectionWithin(target, agentDir, connectionTimeoutMs);
25922
- const unchanged = "Nothing was changed: the previous selection and its token are kept.";
25923
- await prepareLockTakeover(`${settingsPath}.lock`);
25924
- const { storage, previous, previousPin, tokenPath, reused } = withGlobalSettings(agentDir, unchanged, (settings) => {
25925
- const previous = settings.storage;
25926
- const reused = token === void 0 ? void 0 : reusableTokenFile(previous, target.secretName, token, agentDir);
25927
- const tokenPath = token === void 0 ? void 0 : reused ?? join$1(agentDir, `${STORAGE_TOKEN_FILE}.${randomUUID()}`);
25928
- const created = token !== void 0 && tokenPath !== void 0 && reused === void 0 ? tokenPath : void 0;
25929
- if (token !== void 0 && created !== void 0) try {
25930
- writePrivateFile(created, token);
25931
- } catch (error) {
25932
- throw new TeamProfileError("token-write-failed", {
25933
- subject: created,
25934
- detail: describeStorageError$1(error),
25935
- hint: "Nothing was changed. Check that the agent directory is writable, then run the command again.",
25936
- cause: error
25937
- });
25938
- }
25939
- const file = tokenPath === void 0 ? plan.reference : relative$1(storageHomeDir(agentDir), tokenPath).split(sep$1).join("/");
25940
- const storage = {
25941
- adapter: target.adapter,
25942
- options: target.options,
25943
- ...file === void 0 ? {} : { secrets: { [target.secretName]: { file } } },
25944
- ...prefix === void 0 ? {} : { prefix }
25945
- };
25946
- const next = {
25947
- ...settings,
25948
- storage
25949
- };
25950
- if (options.pinLocalSessions) {
25951
- next.sessions = {
25952
- ...settings.sessions,
25953
- storage: LOCAL_SESSIONS_STORAGE
25954
- };
25955
- next.teamJoin = { storage: storageFingerprint(storage) };
25956
- }
25957
- try {
25958
- writeSettingsFile(settingsPath, JSON.stringify(next, null, 2));
25959
- } catch (error) {
25960
- const failure = settingsWriteError(settingsPath, error, unchanged);
25961
- if (created !== void 0) cleanupAfter(failure, () => rmSync$1(created, { force: true }));
25962
- throw failure;
25963
- }
25964
- return {
25965
- storage,
25966
- previous,
25967
- previousPin: settings.sessions?.storage,
25968
- tokenPath,
25969
- reused
25970
- };
25971
- });
25972
- return {
25973
- settingsPath,
25974
- storage,
25975
- ...options.pinLocalSessions ? { sessionsStorage: LOCAL_SESSIONS_STORAGE } : {},
25976
- ...tokenPath === void 0 ? {} : { tokenPath },
25977
- token: tokenPath === void 0 ? "none" : reused === void 0 ? "new" : "reused",
25978
- ...plan.reference === void 0 ? {} : { referencedFile: plan.reference },
25979
- ...previous === void 0 || JSON.stringify(previous) === JSON.stringify(storage) ? {} : { replaced: describePrevious(() => selectStorage(previous, "settings", "storage", "")) },
25980
- ...options.pinLocalSessions && previousPin !== void 0 && !isLocalSessionsPin(previousPin) ? { replacedSessionsStorage: describePrevious(() => selectSessionSetting(previousPin, "sessions.storage", agentDir)) } : {}
25981
- };
25982
- }
25983
- function describePrevious(select) {
25984
- try {
25985
- return describeStorageSelection(select());
25986
- } catch (error) {
25987
- if (error instanceof StorageError) return "an invalid selection";
25988
- throw error;
25989
- }
25990
- }
25991
- async function restartBroker(agentDir, context, onProgress) {
25992
- try {
25993
- return await (context.loadControl ? await context.loadControl() : await (await import("../core/intercom-broker-control.code.js").catch((error) => __atomicOnDemandFailed(error, "intercom"))).loadIntercomBrokerControl()).restartIntercomBroker(agentDir, onProgress === void 0 ? {} : { onProgress });
25994
- } catch (error) {
25995
- return {
25996
- status: "failed",
25997
- error: new TeamProfileError("broker-restart-failed", {
25998
- subject: agentDir,
25999
- detail: describeStorageError$1(error),
26000
- hint: "The settings are saved. Run `atomic intercom restart` so the broker uses them.",
26001
- cause: error
26002
- })
26003
- };
26004
- }
26005
- }
26006
- const installedAdapters = /* @__PURE__ */ new Map();
26007
- async function loadTeamAdapter(agentDir, reason) {
26008
- try {
26009
- await loadStorageAdapter(LIBSQL_ADAPTER_PACKAGE, {
26010
- agentDir,
26011
- domain: "sessions"
26012
- });
26013
- } catch (error) {
26014
- if (!(error instanceof StorageAdapterLoadError)) throw error;
26015
- throw new TeamProfileError("adapter-not-installed", {
26016
- subject: `${LIBSQL_ADAPTER_PACKAGE} for ${agentDir}`,
26017
- detail: describeStorageError$1(error.cause instanceof Error ? error.cause : error),
26018
- hint: `${reason} opens the team database through it. Install it, then run again: atomic install npm:${LIBSQL_ADAPTER_PACKAGE}`,
26019
- cause: error
26020
- });
26021
- }
26022
- }
26023
- /**
26024
- * Whether `ATOMIC_PROFILE=ci` still selects the team database in this process. `--storage` and `ATOMIC_STORAGE`
26025
- * outrank it for sessions and the Intercom broker alike, while a domain variable outranks it only for
26026
- * its own store. So the profile selects some store exactly when it is the shared selection the broker receives.
26027
- */
26028
- async function teamProfileInEffect() {
26029
- const team = await environmentTeamProfileAsync();
26030
- return team !== void 0 && await processSharedStorageSelectionAsync() === JSON.stringify(team);
26031
- }
26032
- /**
26033
- * Fail fast, before any store opens, when this process selects the team database but cannot load the libSQL
26034
- * adapter: `ATOMIC_PROFILE=ci` while it selects a store, or an SDK `storage` selection naming the adapter. The
26035
- * adapter is loaded, not opened, once per agent directory and process. The CLI checks at startup and
26036
- * `createAgentSession` before it creates a session.
26037
- */
26038
- async function assertTeamAdapterInstalled(agentDir, selection) {
26039
- const reason = await teamProfileInEffect() ? "ATOMIC_PROFILE=ci" : selection !== void 0 && "adapter" in selection && selection.adapter === LIBSQL_ADAPTER_PACKAGE ? "The storage selection" : void 0;
26040
- if (reason === void 0) return;
26041
- const key = resolve$1(agentDir);
26042
- let check = installedAdapters.get(key);
26043
- if (check === void 0) {
26044
- const current = loadTeamAdapter(key, reason).catch((error) => {
26045
- if (installedAdapters.get(key) === current) installedAdapters.delete(key);
26046
- throw error;
26047
- });
26048
- installedAdapters.set(key, current);
26049
- check = current;
26050
- }
26051
- return check;
26052
- }
26053
- /** `joinTeam` with the input source its errors name and the CLI's broker control. */
26054
- async function joinTeamWith(options, source, context = {}) {
26055
- const joined = await joinSharedDatabase({
26056
- ...options,
26057
- pinLocalSessions: true
26058
- }, source, context.connectionTimeoutMs ?? 15e3);
26059
- context.onJoined?.(joined);
26060
- const broker = await restartBroker(dirname$1(joined.settingsPath), context, options.onProgress);
26061
- return {
26062
- ...joined,
26063
- sessionsStorage: LOCAL_SESSIONS_STORAGE,
26064
- broker
26065
- };
26066
- }
26067
- /**
26068
- * Use a team database for Intercom while sessions stay private: checks every input and the
26069
- * connection first, then sets the global `storage` setting to the team database and `sessions.storage` to the local
26070
- * default store in one settings write, and restarts the Intercom broker so it routes through the team database.
26071
- * Throws {@link TeamProfileConfigError} for an invalid input and {@link TeamProfileError} otherwise; on any thrown
26072
- * failure nothing was changed. A failed broker restart is reported in `broker`, not thrown.
26073
- */
26074
- function joinTeam(options) {
26075
- return joinTeamWith(options, "sdk");
26076
- }
26077
- function canonicalJson(value) {
26078
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
26079
- if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
26080
- return JSON.stringify(value);
26081
- }
26082
- function storageFingerprint(storage) {
26083
- return `sha256:${createHash("sha256").update(canonicalJson(storage)).digest("hex")}`;
26084
- }
26085
- /** Whether `storage` is exactly the selection the last team join recorded, for this agent directory. */
26086
- function isJoinedStorage(storage, record, agentDir) {
26087
- if (storage === void 0 || record?.storage !== storageFingerprint(storage)) return false;
26088
- if (storage.adapter !== LIBSQL_ADAPTER_PACKAGE) return false;
26089
- const keys = Object.keys(storage).filter((key) => key !== "prefix" && key !== "secrets");
26090
- if (keys.length !== 2 || !keys.includes("adapter") || !keys.includes("options")) return false;
26091
- const options = storage.options ?? {};
26092
- if (Object.keys(options).length !== 1 || typeof options.url !== "string") return false;
26093
- if (storage.secrets === void 0) return isFileUrl(options.url);
26094
- const names = Object.keys(storage.secrets);
26095
- const path = secretFilePath(storage.secrets.authToken, agentDir);
26096
- return names.length === 1 && path !== void 0 && isJoinTokenFile(path, agentDir);
26097
- }
26098
- function isLocalSessionsPin(value) {
26099
- return value !== void 0 && JSON.stringify(Object.keys(value)) === JSON.stringify(["path"]) && "path" in value && value.path === LOCAL_SESSIONS_STORAGE.path;
26100
- }
26101
- /** Every token file the given settings reference. */
26102
- function referencedTokenFiles(settings, agentDir) {
26103
- const workflows = settings.workflows;
26104
- const journal = workflows !== null && typeof workflows === "object" && !Array.isArray(workflows) ? workflows.journal : void 0;
26105
- const sessions = settings.sessions?.storage;
26106
- return [
26107
- settings.storage,
26108
- journal,
26109
- sessions && !("dir" in sessions) ? sessions : void 0
26110
- ].flatMap((selection) => Object.values(selection?.secrets ?? {}).flatMap((ref) => secretFilePath(ref, agentDir) ?? []));
26111
- }
26112
- function projectSettingsPathOf(cwd) {
26113
- return getProjectConfigPaths(cwd, "settings.json")[0];
26114
- }
26115
- function isSameFile(first, second) {
26116
- return existsSync$1(first) && existsSync$1(second) && realpathSync$1(first) === realpathSync$1(second);
26117
- }
26118
- function readIndependentProjectSettings(cwd, settingsPath) {
26119
- let merged = {};
26120
- for (const path of getProjectConfigPaths(cwd, "settings.json").reverse()) {
26121
- if (!existsSync$1(path) || isSameFile(settingsPath, path)) continue;
26122
- try {
26123
- merged = deepMergeSettings(merged, parseJsonFileContent(readFileSync$1(path, "utf-8")));
26124
- } catch (error) {
26125
- throw unreadableSettingsError(path, error);
26126
- }
26127
- }
26128
- return merged;
26129
- }
26130
- function readIndependentGlobalSettings(agentDir, settingsPath) {
26131
- const paths = agentDir === getAgentDir() ? getAgentConfigPaths("settings.json") : [settingsPath];
26132
- let merged = {};
26133
- for (const path of paths.reverse()) {
26134
- if (!existsSync$1(path) || isSameFile(settingsPath, path)) continue;
26135
- try {
26136
- merged = deepMergeSettings(merged, parseJsonFileContent(readFileSync$1(path, "utf-8")));
26137
- } catch (error) {
26138
- throw unreadableSettingsError(path, error);
26139
- }
26140
- }
26141
- return merged;
26142
- }
26143
- function readProjectSettings(cwd, agentDir) {
26144
- const projectPath = projectSettingsPathOf(cwd);
26145
- const storage = new FileSettingsStorage(cwd, agentDir, { projectReadPaths: getProjectConfigPaths(cwd, "settings.json") });
26146
- try {
26147
- let merged;
26148
- storage.withLock("project", (current) => {
26149
- merged = current;
26150
- });
26151
- return merged === void 0 ? {} : parseJsonFileContent(merged);
26152
- } catch (error) {
26153
- if (isLocked(error)) throw lockedError(projectPath, error, "Nothing was changed.");
26154
- throw unreadableSettingsError(projectPath, error);
26155
- }
26156
- }
26157
- /** `leaveTeam` with the CLI's broker control. */
26158
- async function leaveTeamWith(options = {}, context = {}) {
26159
- const agentDir = resolve$1(options.agentDir ?? getAgentDir());
26160
- const cwd = resolve$1(options.cwd ?? process.cwd());
26161
- const settingsPath = settingsPathOf(agentDir);
26162
- openGlobalSettings(cwd, agentDir);
26163
- const unchanged = "Nothing was changed.";
26164
- const empty = {
26165
- settingsPath,
26166
- removed: [],
26167
- kept: [],
26168
- deletedTokenFiles: [],
26169
- keptTokenFiles: []
26170
- };
26171
- if (!existsSync$1(settingsPath)) return empty;
26172
- const trusted = projectTrust(cwd, agentDir);
26173
- await Promise.all([prepareLockTakeover(`${settingsPath}.lock`), prepareLockTakeover(`${projectSettingsPathOf(cwd)}.lock`)]);
26174
- const outcome = withGlobalSettings(agentDir, unchanged, (global) => {
26175
- const project = isSameFile(settingsPath, projectSettingsPathOf(cwd)) ? readIndependentProjectSettings(cwd, settingsPath) : readProjectSettings(cwd, agentDir);
26176
- const inherited = readIndependentGlobalSettings(agentDir, settingsPath);
26177
- const storage = global.storage;
26178
- const removed = [];
26179
- const kept = [];
26180
- if (isJoinedStorage(storage, global.teamJoin, agentDir)) removed.push("storage");
26181
- else if (storage !== void 0) kept.push({
26182
- key: "storage",
26183
- reason: "changed"
26184
- });
26185
- const pin = global.sessions?.storage;
26186
- const storageRemains = storage !== void 0 && !removed.includes("storage") || inherited.storage !== void 0 || trusted && project.storage !== void 0;
26187
- if (isLocalSessionsPin(pin)) {
26188
- if (storageRemains) kept.push({
26189
- key: "sessions.storage",
26190
- reason: "storage-remains"
26191
- });
26192
- else removed.push("sessions.storage");
26193
- } else if (pin !== void 0) kept.push({
26194
- key: "sessions.storage",
26195
- reason: "changed"
26196
- });
26197
- if (removed.length === 0) return {
26198
- ...empty,
26199
- kept
26200
- };
26201
- const tokenPath = removed.includes("storage") ? secretFilePath(storage?.secrets?.authToken, agentDir) : void 0;
26202
- const next = { ...global };
26203
- if (removed.includes("storage")) delete next.storage;
26204
- if (next.storage === void 0) delete next.teamJoin;
26205
- if (removed.includes("sessions.storage")) {
26206
- const { storage: _pin, ...sessions } = { ...global.sessions };
26207
- if (Object.keys(sessions).length === 0) delete next.sessions;
26208
- else next.sessions = sessions;
26209
- }
26210
- try {
26211
- writeSettingsFile(settingsPath, JSON.stringify(next, null, 2));
26212
- } catch (error) {
26213
- throw settingsWriteError(settingsPath, error, unchanged);
26214
- }
26215
- const deletedTokenFiles = [];
26216
- const keptTokenFiles = [];
26217
- let tokenFailure;
26218
- if (tokenPath !== void 0) {
26219
- if ([
26220
- next,
26221
- inherited,
26222
- project
26223
- ].flatMap((settings) => referencedTokenFiles(settings, agentDir)).includes(tokenPath)) keptTokenFiles.push(tokenPath);
26224
- else try {
26225
- rmSync$1(tokenPath, { force: true });
26226
- deletedTokenFiles.push(tokenPath);
26227
- } catch (error) {
26228
- tokenFailure = new TeamProfileError("token-delete-failed", {
26229
- subject: tokenPath,
26230
- detail: describeStorageError$1(error),
26231
- hint: "The team settings were removed. Delete the token file yourself.",
26232
- cause: error
26233
- });
26234
- }
26235
- }
26236
- return {
26237
- settingsPath,
26238
- removed,
26239
- kept,
26240
- deletedTokenFiles,
26241
- keptTokenFiles,
26242
- tokenFailure
26243
- };
26244
- });
26245
- if (outcome.removed.length === 0) return outcome;
26246
- context.onLeft?.({
26247
- settingsPath,
26248
- removed: outcome.removed,
26249
- kept: outcome.kept
26250
- });
26251
- const broker = outcome.removed.includes("storage") ? await restartBroker(agentDir, context, options.onProgress) : void 0;
26252
- if ("tokenFailure" in outcome && outcome.tokenFailure !== void 0) throw outcome.tokenFailure;
26253
- return {
26254
- settingsPath,
26255
- removed: outcome.removed,
26256
- kept: outcome.kept,
26257
- deletedTokenFiles: outcome.deletedTokenFiles,
26258
- keptTokenFiles: outcome.keptTokenFiles,
26259
- ...broker === void 0 ? {} : { broker }
26260
- };
26261
- }
26262
- /**
26263
- * Restore the individual layout: remove the global `storage` setting and the `sessions.storage` pin when they hold
26264
- * exactly what `joinTeam` writes, leave every other value in place, delete the removed selection's token file unless
26265
- * another setting references it, and restart the Intercom broker when `storage` was removed. The pin is kept while
26266
- * another `storage` remains, because sessions would otherwise move to it. Running it again changes nothing.
26267
- */
26268
- function leaveTeam(options = {}) {
26269
- return leaveTeamWith(options);
26270
- }
26271
- function isLocalDefault(selection, agentDir, settings) {
26272
- return selection.kind === "sqlite" && !selection.prefix && resolve$1(selection.path) === resolve$1(defaultSessionDatabasePath(agentDir, settings));
26273
- }
26274
- /**
26275
- * The layout in effect for this process and working directory, from the storage each domain selects (process-level
26276
- * selections, `ATOMIC_PROFILE=ci`, trusted project settings and global settings, as sessions and the Intercom broker
26277
- * resolve them). Reads only; an invalid selection throws its `StorageConfigError`.
26278
- */
26279
- function selectTeamProfile(options = {}) {
26280
- const agentDir = resolve$1(options.agentDir ?? getAgentDir());
26281
- const cwd = resolve$1(options.cwd ?? process.cwd());
26282
- const manager = SettingsManager.create(cwd, agentDir, { projectTrusted: projectTrust(cwd, agentDir) });
26283
- const failure = manager.drainErrors().find(({ invalidKey }) => invalidKey === void 0);
26284
- if (failure !== void 0) {
26285
- if (isLocked(failure.error)) throw lockedError(`${failure.scope} settings`, failure.error, "Nothing was read.");
26286
- throw new TeamProfileError("settings-unreadable", {
26287
- subject: `${failure.scope} settings`,
26288
- detail: unreadableSettingsDetail(failure.error),
26289
- hint: "Fix the settings file, then run the command again.",
26290
- cause: failure.error
26291
- });
26292
- }
26293
- const merged = manager.getSettings();
26294
- const sessions = selectSessionStorageWithSettings(cwd, {
26295
- agentDir,
26296
- settings: merged
26297
- });
26298
- const selected = selectSharedStorage(agentDir, merged);
26299
- const intercom = selectIntercomStorage(agentDir, manager.getGlobalSettings().storage);
26300
- const shared = intercom?.kind === "adapter" ? storageSelectionKey(intercom, agentDir) : void 0;
26301
- const sharesStorage = shared !== void 0 && selected !== void 0 && storageSelectionKey(selected, agentDir) === shared;
26302
- return {
26303
- profile: isLocalDefault(sessions, agentDir, merged) && (selected === void 0 || isLocalDefault(selected, agentDir, merged)) && intercom === void 0 ? "individual" : sharesStorage && isLocalDefault(sessions, agentDir, merged) ? "team" : sharesStorage && storageSelectionKey(sessions, agentDir) === shared ? "ci" : "custom",
26304
- sessions: describeStorageSelection(sessions),
26305
- intercom: intercom === void 0 ? "off" : describeStorageSelection(intercom)
26306
- };
26307
- }
26308
25278
  // dist/cli/file-processor.js
26309
25279
  /**
26310
25280
  * Process @file CLI arguments into text content and image attachments
@@ -27622,6 +26592,14 @@ function appendBoundedStderr(existing, chunk) {
27622
26592
  while (start < bytes.length && (bytes[start] & 192) === 128) start++;
27623
26593
  return `${bytes.subarray(start).toString("utf8")}${marker}`;
27624
26594
  }
26595
+ /**
26596
+ * `<name>(<pid>) MallocStackLogging: …`, a macOS notice. Once a memory-pressure or memory-limit event has made libmalloc
26597
+ * load its stack-logging support, every fork() of that process prints "can't turn off malloc stack logging because it
26598
+ * was not enabled" from inside fork(), to the parent's stderr, before the child sets up its own stdio. The native task
26599
+ * supervisor forks to start each command in a session of its own, so the engine's stderr got one per command. It is
26600
+ * the OS's, never the child's, and nothing a user can act on.
26601
+ */
26602
+ const MACOS_STACK_LOGGING_NOTICE = /^\S+\(\d+\) MallocStackLogging: .*(?:\n|$)/gm;
27625
26603
  /** Batch noisy child output outside the pipe callback without filesystem work. */
27626
26604
  function createStderrReporter(report) {
27627
26605
  let pending = "";
@@ -27631,10 +26609,10 @@ function createStderrReporter(report) {
27631
26609
  if (scheduled) return;
27632
26610
  scheduled = true;
27633
26611
  setImmediate(() => {
27634
- const message = pending;
26612
+ const message = pending.replace(MACOS_STACK_LOGGING_NOTICE, "");
27635
26613
  pending = "";
27636
26614
  scheduled = false;
27637
- report(message);
26615
+ if (message) report(message);
27638
26616
  });
27639
26617
  };
27640
26618
  }
@@ -28712,16 +27690,16 @@ function getArtifactManager(artifactsDir) {
28712
27690
  }
28713
27691
  return manager;
28714
27692
  }
28715
- export { ACTIONS_GITHUB_BASE_URL_ENV, BASH_SHELL_PRESENTATION, BLUEPRINT_FULL_BUILD_MAX_AGE_MS, BLUEPRINT_STEP_TIMEOUT_MS, DEGRADED_RESTORE_RETENTION_DAYS, ENGINE_SESSION_STORAGE_FLAG, ENGINE_SHUTDOWN_GRACE_MS, EVENT_REPORT_MESSAGE_TYPE, EVENT_SUBSCRIPTION_CHILD_ENTRY_TYPE, EVENT_SUBSCRIPTION_ENTRY_TYPE, EVENT_SUBSCRIPTION_PROCESSED_ENTRY_TYPE, FooterDataProvider, HistoryTaskRegistry, RpcClient, SETUP_COMMAND_ALIAS, STORAGE_ADAPTER_LOAD_TIMEOUT_MS, STORAGE_PROBE_TIMEOUT_MS, SUBSCRIPTION_REPORT_TOOL_NAME, SessionWorktreeSnapshotRecorder, SettingsFileChangedError, SettingsManager, TEAM_CONNECTION_TIMEOUT_MS, TEAM_PROFILE_SOURCE, adoptInlineSnapshotBlobs, agentPanelExtensionItems, agentPanelItems, agentPanelSourceHubOf, agentPanelSourcesGeneration, agentPanelTaskId, agentSessionSummaryMethods, agentSessionTreeMethods, answerAgentPanelItem, appendBoundedStderr, applyReadLineSelection, applyToolModifiers, assertTeamAdapterInstalled, bashToolSystemPromptContribution, bindTaskTranscriptFragments, blueprintNotices, blueprintRepository, boundExtensionRuntimes, buildInteractiveEngineArgs, builtinToolBlockPresentation, canIsolateSessionStore, cancelSessionSubscriptions, checkSharedStorageAdapter, checkoutsNeedingRebuild, collectEntriesForBranchSummary, collectStorageStatus, compareWorktreeSnapshot, composeInternalRouters, continueSessionWhereItWorked, copyPanelItemStableKey, createBashTool, createBashToolDefinition, createCodingTools, createEditTool, createEditToolDefinition, createExtensionAPI, createExtensionRuntime, createFindTool, createFindToolDefinition, createHistoryRouter, createKillTool, createKillToolDefinition, createLoadedToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsTool, createLsToolDefinition, createPowerShellTool, createPowerShellToolDefinition, createReadOnlyTools, createReadTool, createReadToolDefinition, createSearchTool, createSearchToolDefinition, createSubscriberReportTool, createToolDefinitionsFor, createWriteTool, createWriteToolDefinition, currentWorktreeRestoreNotices, currentWorktreeRootMappings, currentWorktreeSnapshots, decodeReadableUrl, defaultToolSelectionFor, degradedRestorePin, deleteSessionWithSnapshotRefs, describeBlueprints, describeExportedSnapshots, describeLastCapture, describeSnapshotExport, describeStorageError, describeStorageSelection, describeWorktreeRestoreStatus, describeWorktreeSnapshot, discardDegradedRestore, dismissedAgentPanelItems, drainExtensionAPIWork, editToolSystemPromptContribution, effectiveSharedSelection, extractDocumentMarkdown, findToolSystemPromptContribution, findUnansweredToolCall, formatDegradedRestoreNotice, formatEventReport, formatToolBlockElapsed, formatUnrestoredNotice, formatWorktreeRestoreNotice, formatWorktreeRestoreWarning, generateBranchSummary, generateDiffString, generateUnifiedPatch, getArtifactManager, getEngineSessionStorage, hasSubagentCaptures, hostStoragePackagesRegistered, inheritChildSessionOptionsWithDefaults, inheritedRemotes, inlineSnapshotBlobs, isBuiltinToolCallRenderer, isBuiltinToolResultRenderer, isDocumentPath, isInside$1 as isInside, isInterruptedPanelTask, isPlainRuntimeMetadataCommand, joinSharedDatabase, joinTeam, joinTeamWith, latestSessionSnapshot, latestSessionSnapshotAsync, launchedTaskViewSource, lazyTaskPanelItem, leaveTeam, leaveTeamWith, liveTaskRowOrigin, loadProjectContextFiles, loadProjectContextFilesAsync, lsToolSystemPromptContribution, mapPathForCwd, mapPathForCwdAsync, mapRestoredPath, mapRestoredPathAsync, markInterruptedPanelTask, materializePanelItem, modelHasReasoning, needsRebuild, notifyAgentPanelChanged, notifyAgentPanelSourceHubRebound, onOwnerTaskAction, openAgentPanelItem, openSessionInWorktree, ownerTaskViewSource, panelItemStableKey, parentHistoryNotices, parseActionReference, pathExists, plainNoticeBlock, prepareBranchEntries, prepareInitialMessage, prepareSessionResume, prewarmHostDefaultModelApi, prewarmInteractiveEngineRpcMode, projectSettingsChooseSessionStorage, projectTrust, promptAnswerOptionsOf, readTaskDetailForView, readTaskPageForChat, readTaskPageForView, readToolSystemPromptContribution, recordBlueprintContext, recordRestoredWorktreeContext, registerHostStoragePackages, registerHostStoragePackagesAsync, releaseSessionWorktrees, removeSavedModelRoutingSettings, removeSavedModelRoutingSettingsAsync, resolveAppMode, resolveCliPaths, resolveExcludedToolsForAppMode, resolveExistingPromptSourcePath, resolveExistingPromptSourcePaths, resolvePackageStorageAdapter, resolvePromptInput, resolveSessionStore, resumeSessionWorktree, resumeStoreDir, retainTaskWindowReader, retireExtensionAPI, runAction, runBlueprintBuild, runExtensionAPICleanup, runMigrations, runMigrationsAsync, runResourceRegistrationBatch, sampleAgentPanelSources, savedBoundaryCursor, savedProjectTrust, savedProjectTrustAsync, sealExtensionAPI, searchToolSystemPromptContribution, seedEventPrompt, selectIntercomStorage, selectSessionSetting, selectSessionStorage, selectSessionStorageWithSettings, selectSessionStorageWithSettingsAsync, selectSharedStorage, selectTeamProfile, serializeConversation, sessionManagerContinuesIn, sessionManagerRunsInRecordedCheckout, sessionResumeOptions, sessionSnapshotBlobs, sessionStorageSettingsDiffer, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, shellCommandPrefixFor, shortTaskTitle, shouldStartRpcCatalogRefresh, showDeprecationWarnings, snapshotBlobInliner, sourceError, stopAgentPanelItem, storageFingerprint, subscribeAgentPanel, subscribeAgentPanelExtensions, subscribeSession, takeEngineSessionStorageArg, taskCursorsAround, taskPanelItem, taskPanelItems, taskPanelModel, taskPanelRole, taskPanelState, taskRunGeneration, taskTranscriptFile, taskTranscriptFragments, taskTranscriptUnsavedAnswer, toPrintOutputMode, toolsWithReport, withTaskTranscriptArchive, withWorktreeRestoreNotices, withWorktreeRootMappings, worktreeNeedsRestore, worktreeRestoreNotices, writeSettingsFile, writeSettingsFileAsync, writeToolSystemPromptContribution };
27693
+ export { ACTIONS_GITHUB_BASE_URL_ENV, BASH_SHELL_PRESENTATION, BLUEPRINT_FULL_BUILD_MAX_AGE_MS, BLUEPRINT_STEP_TIMEOUT_MS, DEGRADED_RESTORE_RETENTION_DAYS, ENGINE_SESSION_STORAGE_FLAG, ENGINE_SHUTDOWN_GRACE_MS, EVENT_REPORT_MESSAGE_TYPE, EVENT_SUBSCRIPTION_CHILD_ENTRY_TYPE, EVENT_SUBSCRIPTION_ENTRY_TYPE, EVENT_SUBSCRIPTION_PROCESSED_ENTRY_TYPE, FileSettingsStorage, FooterDataProvider, HistoryTaskRegistry, RpcClient, SETUP_COMMAND_ALIAS, SUBSCRIPTION_REPORT_TOOL_NAME, SessionWorktreeSnapshotRecorder, SettingsFileChangedError, SettingsManager, adoptInlineSnapshotBlobs, agentPanelExtensionItems, agentPanelItems, agentPanelSourceHubOf, agentPanelSourcesGeneration, agentPanelTaskId, agentSessionSummaryMethods, agentSessionTreeMethods, answerAgentPanelItem, appendBoundedStderr, applyReadLineSelection, applyToolModifiers, bashToolSystemPromptContribution, bindTaskTranscriptFragments, blueprintNotices, blueprintRepository, boundExtensionRuntimes, buildInteractiveEngineArgs, builtinToolBlockPresentation, canIsolateSessionStore, cancelSessionSubscriptions, checkoutsNeedingRebuild, collectEntriesForBranchSummary, compareWorktreeSnapshot, composeInternalRouters, continueSessionWhereItWorked, copyPanelItemStableKey, createBashTool, createBashToolDefinition, createCodingTools, createEditTool, createEditToolDefinition, createExtensionAPI, createExtensionRuntime, createFindTool, createFindToolDefinition, createHistoryRouter, createKillTool, createKillToolDefinition, createLoadedToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsTool, createLsToolDefinition, createPowerShellTool, createPowerShellToolDefinition, createReadOnlyTools, createReadTool, createReadToolDefinition, createSearchTool, createSearchToolDefinition, createSubscriberReportTool, createToolDefinitionsFor, createWriteTool, createWriteToolDefinition, currentWorktreeRestoreNotices, currentWorktreeRootMappings, currentWorktreeSnapshots, decodeReadableUrl, defaultToolSelectionFor, degradedRestorePin, deleteSessionWithSnapshotRefs, describeBlueprints, describeExportedSnapshots, describeLastCapture, describeSnapshotExport, describeWorktreeRestoreStatus, describeWorktreeSnapshot, discardDegradedRestore, dismissedAgentPanelItems, drainExtensionAPIWork, editToolSystemPromptContribution, extractDocumentMarkdown, findToolSystemPromptContribution, findUnansweredToolCall, formatDegradedRestoreNotice, formatEventReport, formatToolBlockElapsed, formatUnrestoredNotice, formatWorktreeRestoreNotice, formatWorktreeRestoreWarning, generateBranchSummary, generateDiffString, generateUnifiedPatch, getArtifactManager, getEngineSessionStorage, hasSubagentCaptures, hostStoragePackagesRegistered, inheritChildSessionOptionsWithDefaults, inheritedRemotes, inlineSnapshotBlobs, isBuiltinToolCallRenderer, isBuiltinToolResultRenderer, isDocumentPath, isInside$1 as isInside, isInterruptedPanelTask, isPlainRuntimeMetadataCommand, latestSessionSnapshot, latestSessionSnapshotAsync, launchedTaskViewSource, lazyTaskPanelItem, liveTaskRowOrigin, loadProjectContextFiles, loadProjectContextFilesAsync, lsToolSystemPromptContribution, mapPathForCwd, mapPathForCwdAsync, mapRestoredPath, mapRestoredPathAsync, markInterruptedPanelTask, materializePanelItem, modelHasReasoning, needsRebuild, notifyAgentPanelChanged, notifyAgentPanelSourceHubRebound, onOwnerTaskAction, openAgentPanelItem, openSessionInWorktree, ownerTaskViewSource, panelItemStableKey, parentHistoryNotices, parseActionReference, pathExists, plainNoticeBlock, prepareBranchEntries, prepareInitialMessage, prepareSessionResume, prewarmHostDefaultModelApi, prewarmInteractiveEngineRpcMode, projectSettingsChooseSessionStorage, promptAnswerOptionsOf, readTaskDetailForView, readTaskPageForChat, readTaskPageForView, readToolSystemPromptContribution, recordBlueprintContext, recordRestoredWorktreeContext, registerHostStoragePackages, registerHostStoragePackagesAsync, releaseSessionWorktrees, removeSavedModelRoutingSettings, removeSavedModelRoutingSettingsAsync, resolveAppMode, resolveCliPaths, resolveExcludedToolsForAppMode, resolveExistingPromptSourcePath, resolveExistingPromptSourcePaths, resolvePackageStorageAdapter, resolvePromptInput, resolveSessionStore, resumeSessionWorktree, resumeStoreDir, retainTaskWindowReader, retireExtensionAPI, runAction, runBlueprintBuild, runExtensionAPICleanup, runMigrations, runMigrationsAsync, runResourceRegistrationBatch, sampleAgentPanelSources, savedBoundaryCursor, savedProjectTrust, savedProjectTrustAsync, sealExtensionAPI, searchToolSystemPromptContribution, seedEventPrompt, selectSessionSetting, selectSessionStorage, selectSessionStorageWithSettings, selectSessionStorageWithSettingsAsync, serializeConversation, sessionManagerContinuesIn, sessionManagerRunsInRecordedCheckout, sessionResumeOptions, sessionSnapshotBlobs, sessionStorageSettingsDiffer, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, shellCommandPrefixFor, shortTaskTitle, shouldStartRpcCatalogRefresh, showDeprecationWarnings, snapshotBlobInliner, sourceError, stopAgentPanelItem, subscribeAgentPanel, subscribeAgentPanelExtensions, subscribeSession, takeEngineSessionStorageArg, taskCursorsAround, taskPanelItem, taskPanelItems, taskPanelModel, taskPanelRole, taskPanelState, taskRunGeneration, taskTranscriptFile, taskTranscriptFragments, taskTranscriptUnsavedAnswer, toPrintOutputMode, toolsWithReport, withTaskTranscriptArchive, withWorktreeRestoreNotices, withWorktreeRootMappings, worktreeNeedsRestore, worktreeRestoreNotices, writeSettingsFile, writeSettingsFileAsync, writeToolSystemPromptContribution };
28716
27694
 
28717
- //# sourceMappingURL=startup-8-1-X32CYSXB.js.map
27695
+ //# sourceMappingURL=startup-8-1-LZFXSD3Z.js.map
28718
27696
  // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
28719
27697
  // demand that fails in a process an in-place update left running says to restart.
28720
27698
  function __atomicOnDemandFailed(error, feature) {
28721
27699
  return (async () => {
28722
27700
  const root = new URL("../", import.meta.url);
28723
27701
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
28724
- const key = `${root.href}#0.10.11-alpha.1`;
27702
+ const key = `${root.href}#0.10.11-alpha.3`;
28725
27703
  let release = releases.get(key);
28726
27704
  if (release === undefined) {
28727
27705
  const current = (async () => {
@@ -28749,7 +27727,7 @@ function __atomicOnDemandFailed(error, feature) {
28749
27727
  } catch {
28750
27728
  // No installation to read, as in a bundle of the package: the release the process runs decides.
28751
27729
  }
28752
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
27730
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.3" ? installed : running !== undefined && running.version !== "0.10.11-alpha.3" ? "0.10.11-alpha.3" : undefined;
28753
27731
  if (updatedTo === undefined) throw error;
28754
27732
  const application = typeof running?.name === "string" ? running.name : "atomic";
28755
27733
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {