@bastani/atomic 0.9.20-alpha.5 → 0.9.20-alpha.7

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 (374) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +37 -0
  3. package/dist/builtin/intercom/CHANGELOG.md +10 -0
  4. package/dist/builtin/intercom/broker/broker.ts +110 -39
  5. package/dist/builtin/intercom/broker/client.ts +8 -1
  6. package/dist/builtin/intercom/index.bundle.mjs +61 -2
  7. package/dist/builtin/intercom/live-route-refusal.ts +69 -0
  8. package/dist/builtin/intercom/package.json +2 -2
  9. package/dist/builtin/intercom/recoverable-disconnect.ts +16 -4
  10. package/dist/builtin/intercom/skills/intercom/SKILL.md +11 -11
  11. package/dist/builtin/intercom/types.ts +3 -1
  12. package/dist/builtin/mcp/package.json +2 -2
  13. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  14. package/dist/builtin/subagents/package.json +3 -3
  15. package/dist/builtin/subagents/skills/cua-driver/BROWSER.md +494 -0
  16. package/dist/builtin/subagents/skills/cua-driver/EMBEDDING.md +578 -0
  17. package/dist/builtin/subagents/skills/cua-driver/LINUX.md +364 -0
  18. package/dist/builtin/subagents/skills/cua-driver/MACOS.md +509 -0
  19. package/dist/builtin/subagents/skills/cua-driver/README.md +113 -0
  20. package/dist/builtin/subagents/skills/cua-driver/RECORDING.md +162 -0
  21. package/dist/builtin/subagents/skills/cua-driver/SKILL.md +1105 -0
  22. package/dist/builtin/subagents/skills/cua-driver/WINDOWS.md +866 -0
  23. package/dist/builtin/subagents/src/extension/index.bundle.mjs +18 -8
  24. package/dist/builtin/web-access/package.json +2 -2
  25. package/dist/builtin/workflows/CHANGELOG.md +34 -0
  26. package/dist/builtin/workflows/README.md +5 -19
  27. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  28. package/dist/builtin/workflows/builtin/{chunk-7f381xnq.js → chunk-2hzrv5y8.js} +140 -21
  29. package/dist/builtin/workflows/builtin/{chunk-e83tc6nr.js → chunk-3tx8ry44.js} +3 -2
  30. package/dist/builtin/workflows/builtin/{chunk-00ywx588.js → chunk-5724b0cf.js} +1 -1
  31. package/dist/builtin/workflows/builtin/{chunk-zj5162bh.js → chunk-7bzcersz.js} +33 -22
  32. package/dist/builtin/workflows/builtin/{chunk-ne6vh5ct.js → chunk-7n51c5gh.js} +1 -1
  33. package/dist/builtin/workflows/builtin/{chunk-x2nftpgj.js → chunk-9z3ztr2a.js} +1 -1
  34. package/dist/builtin/workflows/builtin/{chunk-7h7s5xdj.js → chunk-dxjxtgmp.js} +1 -1
  35. package/dist/builtin/workflows/builtin/{chunk-tvcydq13.js → chunk-ffdrv23t.js} +1 -1
  36. package/dist/builtin/workflows/builtin/{chunk-pfm1kgqz.js → chunk-hmt5w62g.js} +12 -4
  37. package/dist/builtin/workflows/builtin/{chunk-tdqvdrg1.js → chunk-jngsbbpm.js} +3 -3
  38. package/dist/builtin/workflows/builtin/{chunk-55p5dxjk.js → chunk-njmf5ze7.js} +1 -1
  39. package/dist/builtin/workflows/builtin/{chunk-evfb0312.js → chunk-vn0wb31x.js} +1 -1
  40. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  41. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  42. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  43. package/dist/builtin/workflows/builtin/goal.js +4 -4
  44. package/dist/builtin/workflows/builtin/index.js +12 -12
  45. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  46. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  47. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  48. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  49. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  50. package/dist/builtin/workflows/package.json +2 -2
  51. package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +10 -9
  52. package/dist/builtin/workflows/skills/prompt-engineer/references/advanced_patterns.md +4 -4
  53. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_fable_5.md +96 -23
  54. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_fable_5_1.md +75 -27
  55. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_4_8.md +72 -26
  56. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_5.md +58 -22
  57. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_opus_5_5.md +118 -0
  58. package/dist/builtin/workflows/skills/prompt-engineer/references/claude_sonnet_5.md +70 -29
  59. package/dist/builtin/workflows/skills/prompt-engineer/references/core_prompting.md +1 -1
  60. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_5_5.md +95 -32
  61. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_5_6.md +79 -30
  62. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6.md +139 -0
  63. package/dist/builtin/workflows/skills/prompt-engineer/references/quality_improvement.md +4 -4
  64. package/dist/builtin/workflows/src/extension/index.bundle.mjs +446 -639
  65. package/dist/builtin/workflows/src/index.js +1434 -1277
  66. package/dist/cli/args.d.ts.map +1 -1
  67. package/dist/cli/args.js +15 -4
  68. package/dist/cli/args.js.map +1 -1
  69. package/dist/cli/file-processor.d.ts +1 -1
  70. package/dist/cli/file-processor.d.ts.map +1 -1
  71. package/dist/cli/file-processor.js.map +1 -1
  72. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  73. package/dist/core/agent-session-auto-compaction.js +40 -12
  74. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  75. package/dist/core/agent-session-bash.d.ts.map +1 -1
  76. package/dist/core/agent-session-bash.js +9 -8
  77. package/dist/core/agent-session-bash.js.map +1 -1
  78. package/dist/core/agent-session-boundaries.d.ts +68 -0
  79. package/dist/core/agent-session-boundaries.d.ts.map +1 -0
  80. package/dist/core/agent-session-boundaries.js +334 -0
  81. package/dist/core/agent-session-boundaries.js.map +1 -0
  82. package/dist/core/agent-session-compaction.js +1 -1
  83. package/dist/core/agent-session-compaction.js.map +1 -1
  84. package/dist/core/agent-session-events.d.ts.map +1 -1
  85. package/dist/core/agent-session-events.js +27 -13
  86. package/dist/core/agent-session-events.js.map +1 -1
  87. package/dist/core/agent-session-export.d.ts.map +1 -1
  88. package/dist/core/agent-session-export.js +16 -20
  89. package/dist/core/agent-session-export.js.map +1 -1
  90. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  91. package/dist/core/agent-session-message-queue.js +6 -3
  92. package/dist/core/agent-session-message-queue.js.map +1 -1
  93. package/dist/core/agent-session-methods.d.ts +33 -4
  94. package/dist/core/agent-session-methods.d.ts.map +1 -1
  95. package/dist/core/agent-session-methods.js.map +1 -1
  96. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  97. package/dist/core/agent-session-persistent-custom-messages.js +2 -1
  98. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  99. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  100. package/dist/core/agent-session-prompt.js +93 -25
  101. package/dist/core/agent-session-prompt.js.map +1 -1
  102. package/dist/core/agent-session-retry.d.ts.map +1 -1
  103. package/dist/core/agent-session-retry.js +4 -9
  104. package/dist/core/agent-session-retry.js.map +1 -1
  105. package/dist/core/agent-session-runtime.d.ts +4 -0
  106. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  107. package/dist/core/agent-session-runtime.js +7 -1
  108. package/dist/core/agent-session-runtime.js.map +1 -1
  109. package/dist/core/agent-session-tasks.d.ts +9 -0
  110. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  111. package/dist/core/agent-session-tasks.js +68 -16
  112. package/dist/core/agent-session-tasks.js.map +1 -1
  113. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  114. package/dist/core/agent-session-tool-hooks.js +15 -5
  115. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  116. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  117. package/dist/core/agent-session-tool-registry.js +9 -21
  118. package/dist/core/agent-session-tool-registry.js.map +1 -1
  119. package/dist/core/agent-session-tree.d.ts.map +1 -1
  120. package/dist/core/agent-session-tree.js +2 -3
  121. package/dist/core/agent-session-tree.js.map +1 -1
  122. package/dist/core/agent-session-types.d.ts +8 -0
  123. package/dist/core/agent-session-types.d.ts.map +1 -1
  124. package/dist/core/agent-session-types.js.map +1 -1
  125. package/dist/core/agent-session.d.ts +18 -2
  126. package/dist/core/agent-session.d.ts.map +1 -1
  127. package/dist/core/agent-session.js +22 -3
  128. package/dist/core/agent-session.js.map +1 -1
  129. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  130. package/dist/core/compaction/branch-summarization.js +1 -0
  131. package/dist/core/compaction/branch-summarization.js.map +1 -1
  132. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  133. package/dist/core/compaction/compaction-boundary.js +11 -6
  134. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  135. package/dist/core/compaction/compaction.d.ts +3 -1
  136. package/dist/core/compaction/compaction.d.ts.map +1 -1
  137. package/dist/core/compaction/compaction.js +37 -0
  138. package/dist/core/compaction/compaction.js.map +1 -1
  139. package/dist/core/crash-log.d.ts +6 -0
  140. package/dist/core/crash-log.d.ts.map +1 -0
  141. package/dist/core/crash-log.js +69 -0
  142. package/dist/core/crash-log.js.map +1 -0
  143. package/dist/core/execution-model-router.d.ts +15 -0
  144. package/dist/core/execution-model-router.d.ts.map +1 -1
  145. package/dist/core/execution-model-router.js +82 -33
  146. package/dist/core/execution-model-router.js.map +1 -1
  147. package/dist/core/export-html/template-js/tree-filter-render.js +6 -1
  148. package/dist/core/export-html/template.js +6 -1
  149. package/dist/core/extensions/agent-events.d.ts +69 -3
  150. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  151. package/dist/core/extensions/agent-events.js.map +1 -1
  152. package/dist/core/extensions/api-types.d.ts +5 -3
  153. package/dist/core/extensions/api-types.d.ts.map +1 -1
  154. package/dist/core/extensions/api-types.js.map +1 -1
  155. package/dist/core/extensions/event-results.d.ts +3 -0
  156. package/dist/core/extensions/event-results.d.ts.map +1 -1
  157. package/dist/core/extensions/event-results.js.map +1 -1
  158. package/dist/core/extensions/event-types.d.ts +2 -2
  159. package/dist/core/extensions/event-types.d.ts.map +1 -1
  160. package/dist/core/extensions/event-types.js.map +1 -1
  161. package/dist/core/extensions/index.d.ts +1 -1
  162. package/dist/core/extensions/index.d.ts.map +1 -1
  163. package/dist/core/extensions/index.js.map +1 -1
  164. package/dist/core/extensions/provider-types.d.ts +2 -0
  165. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  166. package/dist/core/extensions/provider-types.js.map +1 -1
  167. package/dist/core/extensions/runner-events.d.ts +16 -2
  168. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  169. package/dist/core/extensions/runner-events.js +98 -5
  170. package/dist/core/extensions/runner-events.js.map +1 -1
  171. package/dist/core/extensions/runner.d.ts +3 -2
  172. package/dist/core/extensions/runner.d.ts.map +1 -1
  173. package/dist/core/extensions/runner.js +4 -1
  174. package/dist/core/extensions/runner.js.map +1 -1
  175. package/dist/core/fast-model-variants.d.ts +16 -0
  176. package/dist/core/fast-model-variants.d.ts.map +1 -1
  177. package/dist/core/fast-model-variants.js +27 -0
  178. package/dist/core/fast-model-variants.js.map +1 -1
  179. package/dist/core/index.d.ts +1 -1
  180. package/dist/core/index.d.ts.map +1 -1
  181. package/dist/core/index.js.map +1 -1
  182. package/dist/core/messages.d.ts +10 -0
  183. package/dist/core/messages.d.ts.map +1 -1
  184. package/dist/core/messages.js +57 -0
  185. package/dist/core/messages.js.map +1 -1
  186. package/dist/core/model-config.d.ts +52 -0
  187. package/dist/core/model-config.d.ts.map +1 -1
  188. package/dist/core/model-config.js +16 -0
  189. package/dist/core/model-config.js.map +1 -1
  190. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  191. package/dist/core/model-resolver-defaults.js +2 -1
  192. package/dist/core/model-resolver-defaults.js.map +1 -1
  193. package/dist/core/model-runtime.d.ts +13 -1
  194. package/dist/core/model-runtime.d.ts.map +1 -1
  195. package/dist/core/model-runtime.js +16 -1
  196. package/dist/core/model-runtime.js.map +1 -1
  197. package/dist/core/prompt-templates-async.d.ts +2 -2
  198. package/dist/core/prompt-templates-async.d.ts.map +1 -1
  199. package/dist/core/prompt-templates-async.js +57 -29
  200. package/dist/core/prompt-templates-async.js.map +1 -1
  201. package/dist/core/prompt-templates.d.ts +6 -1
  202. package/dist/core/prompt-templates.d.ts.map +1 -1
  203. package/dist/core/prompt-templates.js +61 -35
  204. package/dist/core/prompt-templates.js.map +1 -1
  205. package/dist/core/provider-composer-internal.d.ts +1 -0
  206. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  207. package/dist/core/provider-composer-internal.js +19 -0
  208. package/dist/core/provider-composer-internal.js.map +1 -1
  209. package/dist/core/resource-loader-assets.d.ts.map +1 -1
  210. package/dist/core/resource-loader-assets.js +6 -6
  211. package/dist/core/resource-loader-assets.js.map +1 -1
  212. package/dist/core/sdk-types.d.ts +5 -0
  213. package/dist/core/sdk-types.d.ts.map +1 -1
  214. package/dist/core/sdk-types.js.map +1 -1
  215. package/dist/core/sdk.d.ts.map +1 -1
  216. package/dist/core/sdk.js +7 -2
  217. package/dist/core/sdk.js.map +1 -1
  218. package/dist/core/session-manager-core.d.ts +10 -3
  219. package/dist/core/session-manager-core.d.ts.map +1 -1
  220. package/dist/core/session-manager-core.js +65 -7
  221. package/dist/core/session-manager-core.js.map +1 -1
  222. package/dist/core/session-manager-entries.d.ts +4 -1
  223. package/dist/core/session-manager-entries.d.ts.map +1 -1
  224. package/dist/core/session-manager-entries.js +8 -0
  225. package/dist/core/session-manager-entries.js.map +1 -1
  226. package/dist/core/session-manager-history.d.ts +16 -1
  227. package/dist/core/session-manager-history.d.ts.map +1 -1
  228. package/dist/core/session-manager-history.js +105 -42
  229. package/dist/core/session-manager-history.js.map +1 -1
  230. package/dist/core/session-manager-types.d.ts +30 -3
  231. package/dist/core/session-manager-types.d.ts.map +1 -1
  232. package/dist/core/session-manager-types.js.map +1 -1
  233. package/dist/core/session-manager.d.ts +2 -2
  234. package/dist/core/session-manager.d.ts.map +1 -1
  235. package/dist/core/session-manager.js +1 -1
  236. package/dist/core/session-manager.js.map +1 -1
  237. package/dist/core/settings-types.js.map +1 -1
  238. package/dist/core/structured-output/index.d.ts +1 -1
  239. package/dist/core/structured-output/index.d.ts.map +1 -1
  240. package/dist/core/structured-output/index.js +37 -41
  241. package/dist/core/structured-output/index.js.map +1 -1
  242. package/dist/core/structured-output/jev-client.d.ts +13 -8
  243. package/dist/core/structured-output/jev-client.d.ts.map +1 -1
  244. package/dist/core/structured-output/jev-client.js +90 -32
  245. package/dist/core/structured-output/jev-client.js.map +1 -1
  246. package/dist/core/structured-output/jev.d.ts.map +1 -1
  247. package/dist/core/structured-output/jev.js +38 -64
  248. package/dist/core/structured-output/jev.js.map +1 -1
  249. package/dist/core/structured-output/resolver.d.ts +32 -24
  250. package/dist/core/structured-output/resolver.d.ts.map +1 -1
  251. package/dist/core/structured-output/resolver.js +57 -9
  252. package/dist/core/structured-output/resolver.js.map +1 -1
  253. package/dist/core/structured-output/types.d.ts +8 -6
  254. package/dist/core/structured-output/types.d.ts.map +1 -1
  255. package/dist/core/structured-output/types.js.map +1 -1
  256. package/dist/core/system-prompt.js +1 -1
  257. package/dist/core/system-prompt.js.map +1 -1
  258. package/dist/core/tasks/child-command-owner.d.ts +34 -0
  259. package/dist/core/tasks/child-command-owner.d.ts.map +1 -0
  260. package/dist/core/tasks/child-command-owner.js +70 -0
  261. package/dist/core/tasks/child-command-owner.js.map +1 -0
  262. package/dist/core/tools/bash-pty-native.d.ts +5 -1
  263. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  264. package/dist/core/tools/bash-pty-native.js +15 -7
  265. package/dist/core/tools/bash-pty-native.js.map +1 -1
  266. package/dist/core/tools/kill.d.ts +2 -2
  267. package/dist/core/tools/kill.d.ts.map +1 -1
  268. package/dist/core/tools/kill.js +3 -4
  269. package/dist/core/tools/kill.js.map +1 -1
  270. package/dist/core/tools/read.d.ts +4 -0
  271. package/dist/core/tools/read.d.ts.map +1 -1
  272. package/dist/core/tools/read.js +5 -1
  273. package/dist/core/tools/read.js.map +1 -1
  274. package/dist/index-extensions.d.ts +1 -1
  275. package/dist/index-extensions.d.ts.map +1 -1
  276. package/dist/index-extensions.js.map +1 -1
  277. package/dist/index.d.ts +4 -4
  278. package/dist/index.d.ts.map +1 -1
  279. package/dist/index.js +4 -4
  280. package/dist/index.js.map +1 -1
  281. package/dist/main-app-mode.d.ts +1 -1
  282. package/dist/main-app-mode.d.ts.map +1 -1
  283. package/dist/main-app-mode.js +3 -2
  284. package/dist/main-app-mode.js.map +1 -1
  285. package/dist/main.d.ts.map +1 -1
  286. package/dist/main.js +1 -1
  287. package/dist/main.js.map +1 -1
  288. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  289. package/dist/modes/interactive/components/tree-selector-content.js +6 -0
  290. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  291. package/dist/modes/interactive/components/tree-selector-model.d.ts.map +1 -1
  292. package/dist/modes/interactive/components/tree-selector-model.js +1 -0
  293. package/dist/modes/interactive/components/tree-selector-model.js.map +1 -1
  294. package/dist/modes/interactive/interactive-agent-events.js +17 -1
  295. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  296. package/dist/modes/interactive/interactive-auth-login.js +2 -4
  297. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  298. package/dist/modes/interactive/interactive-mode-helpers.d.ts +1 -0
  299. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  300. package/dist/modes/interactive/interactive-mode-helpers.js +16 -0
  301. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  302. package/dist/modes/interactive/interactive-mode-surface.d.ts +1 -0
  303. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  304. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  305. package/dist/modes/interactive/interactive-process-lifecycle.js +13 -1
  306. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  307. package/dist/modes/interactive/interactive-session-runtime.js +5 -1
  308. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  309. package/dist/modes/interactive-engine/isolated-auth.d.ts +16 -0
  310. package/dist/modes/interactive-engine/isolated-auth.d.ts.map +1 -1
  311. package/dist/modes/interactive-engine/isolated-auth.js +27 -0
  312. package/dist/modes/interactive-engine/isolated-auth.js.map +1 -1
  313. package/dist/modes/interactive-engine/isolated-runtime.d.ts +4 -0
  314. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  315. package/dist/modes/interactive-engine/isolated-runtime.js +4 -1
  316. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  317. package/dist/modes/rpc/rpc-client-api.d.ts +2 -1
  318. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  319. package/dist/modes/rpc/rpc-client-api.js +7 -2
  320. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  321. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  322. package/dist/modes/rpc/rpc-command-handler.js +3 -1
  323. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  324. package/dist/modes/rpc/rpc-provider-auth.d.ts +2 -1
  325. package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -1
  326. package/dist/modes/rpc/rpc-provider-auth.js +2 -2
  327. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  328. package/dist/modes/rpc/rpc-types.d.ts +2 -0
  329. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  330. package/dist/modes/rpc/rpc-types.js.map +1 -1
  331. package/dist/utils/mime.js +1 -1
  332. package/dist/utils/mime.js.map +1 -1
  333. package/dist/utils/tool-result-images.d.ts +3 -1
  334. package/dist/utils/tool-result-images.d.ts.map +1 -1
  335. package/dist/utils/tool-result-images.js +4 -1
  336. package/dist/utils/tool-result-images.js.map +1 -1
  337. package/docs/background-tasks.md +11 -2
  338. package/docs/compaction.md +5 -1
  339. package/docs/computer-use.md +105 -56
  340. package/docs/environment-variables.md +1 -1
  341. package/docs/extensions/events.md +75 -7
  342. package/docs/extensions.md +6 -2
  343. package/docs/getting-started/first-session.md +3 -2
  344. package/docs/intercom/operations.md +13 -1
  345. package/docs/intercom.md +1 -1
  346. package/docs/llama-cpp.md +2 -2
  347. package/docs/models/evals.md +108 -118
  348. package/docs/models/reference.md +31 -3
  349. package/docs/packages.md +2 -0
  350. package/docs/prompt-templates.md +1 -0
  351. package/docs/providers.md +19 -6
  352. package/docs/reference/cli.md +2 -2
  353. package/docs/rpc/examples.md +2 -0
  354. package/docs/sdk/reference.md +2 -3
  355. package/docs/sdk/structured-decisions.md +25 -18
  356. package/docs/sdk.md +13 -2
  357. package/docs/session-format.md +17 -2
  358. package/docs/settings.md +8 -8
  359. package/docs/skills.md +8 -2
  360. package/docs/subagents/reference.md +4 -4
  361. package/docs/subagents.md +2 -2
  362. package/docs/workflows/api-reference.md +7 -34
  363. package/docs/workflows/authoring.md +191 -0
  364. package/docs/workflows/builtins.md +1 -1
  365. package/docs/workflows/operations.md +18 -78
  366. package/docs/workflows/reliable-design.md +14 -29
  367. package/docs/workflows/verification.md +21 -8
  368. package/docs/workflows.md +8 -7
  369. package/examples/rpc-client.ts +38 -0
  370. package/examples/rpc-extension-ui.ts +19 -5
  371. package/examples/sdk/README.md +1 -1
  372. package/npm-shrinkwrap.json +69 -69
  373. package/package.json +8 -8
  374. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_astra.md +0 -58
@@ -115,696 +115,6 @@ var init_dbos_admission = __esm(() => {
115
115
  dbosAdmissionContext = bag[key2];
116
116
  });
117
117
 
118
- // dist/builtin/workflows/src/durable/local-command.ts
119
- import { spawn } from "node:child_process";
120
- import { connect } from "node:net";
121
- import { createChildProcessEnvironment } from "@bastani/atomic";
122
- function runLocalCommand(command, args, options) {
123
- return new Promise((resolve, reject) => {
124
- const child = spawn(command, [...args], {
125
- stdio: ["ignore", "pipe", "pipe"],
126
- windowsHide: true,
127
- env: createChildProcessEnvironment(options?.env ? { ...options.env } : undefined),
128
- ...options?.uid !== undefined ? { uid: options.uid } : {},
129
- ...options?.gid !== undefined ? { gid: options.gid } : {}
130
- });
131
- let stdout = "";
132
- let stderr = "";
133
- let stdoutTruncated = false;
134
- let stderrTruncated = false;
135
- let settled = false;
136
- let exitFallback;
137
- child.stdout.setEncoding("utf8");
138
- child.stderr.setEncoding("utf8");
139
- const onStdout = (chunk) => {
140
- const appended = boundedAppend(stdout, chunk);
141
- stdout = appended.value;
142
- stdoutTruncated ||= appended.truncated;
143
- };
144
- const onStderr = (chunk) => {
145
- const appended = boundedAppend(stderr, chunk);
146
- stderr = appended.value;
147
- stderrTruncated ||= appended.truncated;
148
- };
149
- const cleanup = () => {
150
- if (exitFallback !== undefined)
151
- clearImmediate(exitFallback);
152
- child.off("error", onError);
153
- child.off("exit", onExit);
154
- child.off("close", onClose);
155
- child.stdout.off("data", onStdout);
156
- child.stderr.off("data", onStderr);
157
- child.stdout.destroy();
158
- child.stderr.destroy();
159
- };
160
- const finish = (code) => {
161
- if (settled)
162
- return;
163
- settled = true;
164
- cleanup();
165
- resolve({
166
- exitCode: code ?? 1,
167
- stdout,
168
- stderr,
169
- ...stdoutTruncated ? { stdoutTruncated: true } : {},
170
- ...stderrTruncated ? { stderrTruncated: true } : {}
171
- });
172
- };
173
- const onError = (error) => {
174
- if (settled)
175
- return;
176
- settled = true;
177
- cleanup();
178
- reject(error);
179
- };
180
- const onExit = (code) => {
181
- if (code !== 0)
182
- return;
183
- exitFallback = setImmediate(() => finish(code));
184
- };
185
- const onClose = (code) => finish(code);
186
- child.stdout.on("data", onStdout);
187
- child.stderr.on("data", onStderr);
188
- child.once("error", onError);
189
- if (options?.completion === "successful-exit")
190
- child.once("exit", onExit);
191
- child.once("close", onClose);
192
- });
193
- }
194
- function commandFailureDetail(result) {
195
- return result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`;
196
- }
197
- function delay(ms) {
198
- return new Promise((resolve) => setTimeout(resolve, ms));
199
- }
200
- function tcpReachable(host, port, timeoutMs = 1000) {
201
- return new Promise((resolve) => {
202
- const socket = connect({ host, port });
203
- const finish = (reachable) => {
204
- socket.removeAllListeners();
205
- socket.destroy();
206
- resolve(reachable);
207
- };
208
- socket.setTimeout(timeoutMs);
209
- socket.once("connect", () => finish(true));
210
- socket.once("timeout", () => finish(false));
211
- socket.once("error", () => finish(false));
212
- });
213
- }
214
- function boundedAppend(current, chunk) {
215
- const next = current + chunk;
216
- return next.length <= OUTPUT_LIMIT_BYTES ? { value: next, truncated: false } : { value: next.slice(-OUTPUT_LIMIT_BYTES), truncated: true };
217
- }
218
- var OUTPUT_LIMIT_BYTES = 16384;
219
- var init_local_command = () => {};
220
-
221
- // dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts
222
- import { createHash as createHash3 } from "node:crypto";
223
- import {
224
- chmod,
225
- chown,
226
- cp,
227
- lstat,
228
- mkdir,
229
- open,
230
- readdir,
231
- readlink,
232
- realpath,
233
- rename,
234
- rm,
235
- writeFile
236
- } from "node:fs/promises";
237
- import { homedir } from "node:os";
238
- import { dirname, isAbsolute, join, relative, sep } from "node:path";
239
- function defaultEmbeddedBaseDir() {
240
- return join(homedir(), ".atomic", "postgres");
241
- }
242
- async function resolveEmbeddedRunContext(runner = runLocalCommand, euid = process.getuid?.(), platform = process.platform) {
243
- if (platform !== "linux" || euid !== 0) {
244
- return { baseDir: defaultEmbeddedBaseDir(), runAsOwner: runner };
245
- }
246
- for (const name of OWNER_CANDIDATES) {
247
- const owner = await lookupOwner(runner, name);
248
- if (owner === undefined)
249
- continue;
250
- const runAsOwner = await resolvePrivilegeDrop(runner, owner);
251
- if (runAsOwner === undefined)
252
- continue;
253
- return { baseDir: ROOT_EMBEDDED_BASE_DIR, owner, runAsOwner };
254
- }
255
- return { baseDir: defaultEmbeddedBaseDir(), runAsOwner: runner };
256
- }
257
- async function resolvePrivilegeDrop(runner, owner) {
258
- const strategies = [
259
- (command, args, options) => runner(command, args, { ...options, uid: owner.uid, gid: owner.gid }),
260
- (command, args, options) => runner("setpriv", [`--reuid=${owner.uid}`, `--regid=${owner.gid}`, "--clear-groups", "--", command, ...args], options),
261
- (command, args, options) => runner("runuser", ["-u", owner.name, "--", command, ...args], options),
262
- (command, args, options) => runner("su", ["-s", "/bin/sh", "-c", shellCommand(command, args), owner.name], options)
263
- ];
264
- for (const strategy of strategies) {
265
- if (await provesOwnerIdentity(strategy, owner))
266
- return strategy;
267
- }
268
- return;
269
- }
270
- async function provesOwnerIdentity(strategy, owner) {
271
- try {
272
- const uid = parseIdentityNumber(await strategy("id", ["-u"]));
273
- if (uid !== owner.uid)
274
- return false;
275
- const gid = parseIdentityNumber(await strategy("id", ["-g"]));
276
- if (gid !== owner.gid)
277
- return false;
278
- const groups = parseIdentityGroups(await strategy("id", ["-G"]));
279
- return groups?.has(owner.gid) === true && (owner.uid === 0 || !groups.has(0));
280
- } catch {
281
- return false;
282
- }
283
- }
284
- function parseIdentityNumber(result) {
285
- if (result.exitCode !== 0 || result.stdoutTruncated === true)
286
- return;
287
- const match = /^(0|[1-9]\d*)\r?\n?$/.exec(result.stdout);
288
- if (match === null)
289
- return;
290
- const value = Number(match[1]);
291
- return Number.isSafeInteger(value) ? value : undefined;
292
- }
293
- function parseIdentityGroups(result) {
294
- if (result.exitCode !== 0 || result.stdoutTruncated === true || !/^(0|[1-9]\d*)(?:[ \t]+(0|[1-9]\d*))*\r?\n?$/.test(result.stdout)) {
295
- return;
296
- }
297
- const values = result.stdout.trimEnd().split(/[ \t]+/).map(Number);
298
- if (values.some((value) => !Number.isSafeInteger(value)))
299
- return;
300
- const groups = new Set(values);
301
- return groups.size === values.length ? groups : undefined;
302
- }
303
- async function prepareBinariesForOwner(binaries, context, runner = runLocalCommand, options = {}) {
304
- const owner = context.owner;
305
- if (owner === undefined)
306
- return binaries;
307
- const probe = await context.runAsOwner(binaries.initdb, ["--version"]).catch(() => {
308
- return;
309
- });
310
- if (probe !== undefined && probe.exitCode === 0)
311
- return binaries;
312
- const sourceNativeDir = dirname(dirname(binaries.initdb));
313
- const copiedRuntimeDir = join(context.baseDir, "pg-runtime");
314
- const publisher = publisherIdentity();
315
- const progress = runtimeProgress(options);
316
- const sourceSnapshot = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
317
- await options.afterInitialSourceSnapshot?.();
318
- const copiedNativeDir = await findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options);
319
- return {
320
- pg_ctl: join(copiedNativeDir, "bin", "pg_ctl"),
321
- initdb: join(copiedNativeDir, "bin", "initdb"),
322
- postgres: join(copiedNativeDir, "bin", "postgres")
323
- };
324
- }
325
- async function cleanupAbandonedRuntimeStages(baseDir, abandonedOwnerTokens = new Set) {
326
- if (abandonedOwnerTokens.size === 0)
327
- return;
328
- const copiedRuntimeDir = join(baseDir, "pg-runtime");
329
- let entries;
330
- try {
331
- entries = await readdir(copiedRuntimeDir);
332
- } catch (error) {
333
- const code = error instanceof Error && "code" in error ? error.code : undefined;
334
- if (code === "ENOENT")
335
- return;
336
- throw error;
337
- }
338
- for (const entry of entries) {
339
- if (!entry.startsWith(".native-staged-"))
340
- continue;
341
- const stage = join(copiedRuntimeDir, entry);
342
- let ownerToken;
343
- try {
344
- ownerToken = await readSmallFile(join(stage, STAGE_OWNER_FILE));
345
- } catch {
346
- continue;
347
- }
348
- if (abandonedOwnerTokens.has(ownerToken))
349
- await rm(stage, { recursive: true, force: true });
350
- }
351
- }
352
- async function findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options) {
353
- await mkdir(copiedRuntimeDir, { recursive: true, mode: 493 });
354
- const runtimeStat = await lstat(copiedRuntimeDir);
355
- if (!runtimeStat.isDirectory() || runtimeStat.isSymbolicLink()) {
356
- throw new Error(`Embedded Postgres runtime parent must be a real directory: ${copiedRuntimeDir}`);
357
- }
358
- await chown(copiedRuntimeDir, publisher.uid, publisher.gid);
359
- await chmod(copiedRuntimeDir, 493);
360
- const generationNativeDir = join(copiedRuntimeDir, `native-${sourceSnapshot.sourceIdentity}`);
361
- const existing = await lstatOrUndefined(generationNativeDir);
362
- if (existing !== undefined) {
363
- try {
364
- if (await snapshotSealedRuntime(generationNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
365
- throw new Error("sealed identity mismatch");
366
- }
367
- await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while selecting an existing generation.");
368
- return generationNativeDir;
369
- } catch (error) {
370
- if (error instanceof SourceRuntimeChangedError)
371
- throw error;
372
- const detail = error instanceof Error ? error.message : String(error);
373
- throw new Error(`Embedded Postgres runtime generation is corrupt and cannot be replaced while it may be in use (${generationNativeDir}): ${detail}`);
374
- }
375
- }
376
- const stageOwner = options.publicationLease?.ownerToken ?? `unmanaged-${process.pid}-${crypto.randomUUID()}`;
377
- const stagedRoot = join(copiedRuntimeDir, `.native-staged-${process.pid}-${crypto.randomUUID()}`);
378
- const stagedNativeDir = join(stagedRoot, STAGE_PAYLOAD_DIR);
379
- await mkdir(stagedRoot, { mode: 448 });
380
- await writeFile(join(stagedRoot, STAGE_OWNER_FILE), stageOwner, { mode: 384, flag: "wx" });
381
- try {
382
- await progress();
383
- await cp(sourceNativeDir, stagedNativeDir, { recursive: true, verbatimSymlinks: true });
384
- const copiedSnapshot = await snapshotSourceRuntime(stagedNativeDir, publisher, progress);
385
- if (copiedSnapshot.sourceIdentity !== sourceSnapshot.sourceIdentity) {
386
- throw new Error("Copied embedded Postgres runtime did not match its source package.");
387
- }
388
- await sealRuntimeForPublisher(stagedNativeDir, publisher, runner, progress);
389
- if (await snapshotSealedRuntime(stagedNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
390
- throw new Error("Sealed embedded Postgres runtime did not match its source package.");
391
- }
392
- await options.beforePublish?.(stagedNativeDir);
393
- if (await snapshotSealedRuntime(stagedNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
394
- throw new Error("Embedded Postgres runtime changed after sealed validation and before publication.");
395
- }
396
- await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while preparing a generation.");
397
- assertPublicationLease(options, "Embedded Postgres runtime publication lost its setup lease.");
398
- await progress();
399
- await rename(stagedNativeDir, generationNativeDir);
400
- await options.afterPublish?.(generationNativeDir);
401
- if (await snapshotSealedRuntime(generationNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
402
- throw new Error("Embedded Postgres published runtime changed during publication.");
403
- }
404
- await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed during publication.");
405
- await options.afterPublishValidation?.(generationNativeDir);
406
- assertPublicationLease(options, "Embedded Postgres runtime lost its setup lease after publication.");
407
- return generationNativeDir;
408
- } finally {
409
- await makeUnpublishedStageRemovable(stagedNativeDir).catch(() => {});
410
- await rm(stagedRoot, { recursive: true, force: true });
411
- }
412
- }
413
- async function assertSourceSnapshotUnchanged(sourceNativeDir, expected, publisher, progress, message) {
414
- const current = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
415
- if (current.sourceIdentity !== expected.sourceIdentity || current.sealedIdentity !== expected.sealedIdentity) {
416
- throw new SourceRuntimeChangedError(message);
417
- }
418
- }
419
- function assertPublicationLease(options, message) {
420
- if (options.publicationLease !== undefined && !options.publicationLease.refresh())
421
- throw new Error(message);
422
- }
423
- function runtimeProgress(options) {
424
- let operations = 0;
425
- const yieldToEventLoop = options.yieldToEventLoop ?? (() => new Promise((resolve) => setImmediate(resolve)));
426
- return async () => {
427
- if (operations % TRAVERSAL_OPERATIONS_PER_YIELD === 0) {
428
- if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
429
- throw new Error("Embedded Postgres runtime publication lost its setup lease.");
430
- }
431
- if (operations > 0) {
432
- await yieldToEventLoop();
433
- if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
434
- throw new Error("Embedded Postgres runtime publication lost its setup lease.");
435
- }
436
- }
437
- }
438
- operations += 1;
439
- };
440
- }
441
- async function snapshotSourceRuntime(root, publisher, progress) {
442
- const rootStat = await lstat(root);
443
- assertRuntimeRoot(root, rootStat);
444
- const rootRealPath = await realpath(root);
445
- const sourceHash = createHash3("sha256");
446
- const sealedHash = createHash3("sha256");
447
- await hashSourceEntry(sourceHash, sealedHash, root, ".", rootRealPath, publisher, progress);
448
- return { sourceIdentity: sourceHash.digest("hex"), sealedIdentity: sealedHash.digest("hex") };
449
- }
450
- async function hashSourceEntry(sourceHash, sealedHash, path, relativePath, rootRealPath, publisher, progress) {
451
- await progress();
452
- const stat = await lstat(path);
453
- if (stat.isSymbolicLink()) {
454
- const target = await validatedLinkTarget(path, relativePath, rootRealPath);
455
- hashField(sourceHash, "link", relativePath, target);
456
- hashField(sealedHash, "link", relativePath, String(publisher.uid), String(publisher.gid), target);
457
- return;
458
- }
459
- if (stat.isDirectory()) {
460
- hashField(sourceHash, "directory", relativePath, String(stat.mode & 511));
461
- hashField(sealedHash, "directory", relativePath, String(sealedDirectoryMode(relativePath === ".")), String(publisher.uid), String(publisher.gid));
462
- for (const entry of (await readdir(path)).sort()) {
463
- await hashSourceEntry(sourceHash, sealedHash, join(path, entry), relativePath === "." ? entry : join(relativePath, entry), rootRealPath, publisher, progress);
464
- }
465
- return;
466
- }
467
- if (stat.isFile()) {
468
- hashField(sourceHash, "file", relativePath, String(stat.mode & 511), String(stat.size));
469
- hashField(sealedHash, "file", relativePath, String(sealedFileMode(stat.mode)), String(publisher.uid), String(publisher.gid), String(stat.size));
470
- await hashFileInto([sourceHash, sealedHash], path, progress);
471
- return;
472
- }
473
- throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
474
- }
475
- async function snapshotSealedRuntime(root, progress) {
476
- const rootStat = await lstat(root);
477
- assertRuntimeRoot(root, rootStat);
478
- const rootRealPath = await realpath(root);
479
- const hash = createHash3("sha256");
480
- await hashSealedEntry(hash, root, ".", rootRealPath, progress);
481
- return hash.digest("hex");
482
- }
483
- async function hashSealedEntry(hash, path, relativePath, rootRealPath, progress) {
484
- await progress();
485
- const stat = await lstat(path);
486
- if (stat.isSymbolicLink()) {
487
- const target = await validatedLinkTarget(path, relativePath, rootRealPath);
488
- hashField(hash, "link", relativePath, String(stat.uid), String(stat.gid), target);
489
- return;
490
- }
491
- if (stat.isDirectory()) {
492
- hashField(hash, "directory", relativePath, String(stat.mode & 511), String(stat.uid), String(stat.gid));
493
- for (const entry of (await readdir(path)).sort()) {
494
- await hashSealedEntry(hash, join(path, entry), relativePath === "." ? entry : join(relativePath, entry), rootRealPath, progress);
495
- }
496
- return;
497
- }
498
- if (stat.isFile()) {
499
- hashField(hash, "file", relativePath, String(stat.mode & 511), String(stat.uid), String(stat.gid), String(stat.size));
500
- await hashFileInto([hash], path, progress);
501
- return;
502
- }
503
- throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
504
- }
505
- async function validatedLinkTarget(path, relativePath, rootRealPath) {
506
- const target = await readlink(path);
507
- if (isAbsolute(target))
508
- throw new Error(`Embedded Postgres runtime contains an absolute link: ${relativePath}`);
509
- const resolvedTarget = await realpath(path);
510
- const targetFromRoot = relative(rootRealPath, resolvedTarget);
511
- if (targetFromRoot === ".." || targetFromRoot.startsWith(`..${sep}`) || isAbsolute(targetFromRoot)) {
512
- throw new Error(`Embedded Postgres runtime link escapes its tree: ${relativePath}`);
513
- }
514
- return target;
515
- }
516
- async function hashFileInto(hashes, path, progress) {
517
- const handle = await open(path, "r");
518
- const buffer = Buffer.allocUnsafe(HASH_CHUNK_BYTES);
519
- try {
520
- for (;; ) {
521
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
522
- if (bytesRead === 0)
523
- return;
524
- const chunk = buffer.subarray(0, bytesRead);
525
- for (const hash of hashes)
526
- hash.update(chunk);
527
- await progress();
528
- }
529
- } finally {
530
- await handle.close();
531
- }
532
- }
533
- async function sealRuntimeForPublisher(runtimeDir, publisher, runner, progress) {
534
- const result = await runner("chown", ["-R", `${publisher.uid}:${publisher.gid}`, runtimeDir]);
535
- if (result.exitCode !== 0) {
536
- throw new Error(`Could not seal the copied embedded Postgres runtime: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`}`);
537
- }
538
- await sealRuntimeModes(runtimeDir, progress, true);
539
- }
540
- async function sealRuntimeModes(path, progress, isRoot = false) {
541
- await progress();
542
- const stat = await lstat(path);
543
- if (stat.isSymbolicLink())
544
- return;
545
- if (stat.isDirectory()) {
546
- await chmod(path, 448);
547
- for (const entry of await readdir(path))
548
- await sealRuntimeModes(join(path, entry), progress);
549
- await chmod(path, sealedDirectoryMode(isRoot));
550
- return;
551
- }
552
- if (stat.isFile()) {
553
- await chmod(path, sealedFileMode(stat.mode));
554
- return;
555
- }
556
- throw new Error(`Embedded Postgres runtime contains an unsupported entry while sealing: ${path}`);
557
- }
558
- async function makeUnpublishedStageRemovable(path) {
559
- const stat = await lstatOrUndefined(path);
560
- if (stat === undefined || stat.isSymbolicLink())
561
- return;
562
- if (stat.isDirectory()) {
563
- await chmod(path, 448);
564
- for (const entry of await readdir(path))
565
- await makeUnpublishedStageRemovable(join(path, entry));
566
- } else if (stat.isFile()) {
567
- await chmod(path, 384);
568
- }
569
- }
570
- function sealedDirectoryMode(isRoot) {
571
- if (process.platform === "win32")
572
- return 292;
573
- return isRoot ? 493 : 365;
574
- }
575
- function sealedFileMode(mode) {
576
- if (process.platform === "win32")
577
- return 292;
578
- return (mode & 73) === 0 ? 292 : 365;
579
- }
580
- function publisherIdentity() {
581
- return { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };
582
- }
583
- function assertRuntimeRoot(root, stat) {
584
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
585
- throw new Error(`Embedded Postgres runtime must be a real directory: ${root}`);
586
- }
587
- }
588
- async function lstatOrUndefined(path) {
589
- try {
590
- return await lstat(path);
591
- } catch (error) {
592
- const code = error instanceof Error && "code" in error ? error.code : undefined;
593
- if (code === "ENOENT")
594
- return;
595
- throw error;
596
- }
597
- }
598
- async function readSmallFile(path) {
599
- const handle = await open(path, "r");
600
- try {
601
- const stat = await handle.stat();
602
- if (stat.size > 4096)
603
- throw new Error(`Unexpectedly large runtime stage owner marker: ${path}`);
604
- return (await handle.readFile("utf8")).trim();
605
- } finally {
606
- await handle.close();
607
- }
608
- }
609
- function hashField(hash, ...values) {
610
- for (const value of values)
611
- hash.update(`${Buffer.byteLength(value)}:${value}`);
612
- }
613
- async function lookupOwner(runner, name) {
614
- const uid = await lookupId(runner, ["-u", name]);
615
- const gid = await lookupId(runner, ["-g", name]);
616
- if (uid === undefined || gid === undefined || uid === 0)
617
- return;
618
- return { uid, gid, name };
619
- }
620
- async function lookupId(runner, args) {
621
- try {
622
- const value = parseIdentityNumber(await runner("id", args));
623
- return value !== undefined && value > 0 ? value : undefined;
624
- } catch {
625
- return;
626
- }
627
- }
628
- function shellCommand(command, args) {
629
- return [command, ...args].map((part) => `'${part.replaceAll("'", "'\\''")}'`).join(" ");
630
- }
631
- var ROOT_EMBEDDED_BASE_DIR = "/var/lib/atomic-postgres", OWNER_CANDIDATES, STAGE_OWNER_FILE = ".atomic-stage-owner", STAGE_PAYLOAD_DIR = "runtime", TRAVERSAL_OPERATIONS_PER_YIELD = 16, HASH_CHUNK_BYTES, SourceRuntimeChangedError;
632
- var init_dbos_embedded_postgres_root = __esm(() => {
633
- init_local_command();
634
- OWNER_CANDIDATES = ["postgres", "nobody", "daemon"];
635
- HASH_CHUNK_BYTES = 64 * 1024;
636
- SourceRuntimeChangedError = class SourceRuntimeChangedError extends Error {
637
- };
638
- });
639
-
640
- // dist/builtin/workflows/src/durable/dbos-embedded-postgres-targets.ts
641
- import { existsSync } from "node:fs";
642
- function detectLinuxLibc(signals) {
643
- if (signals.glibcVersionRuntime !== undefined && signals.glibcVersionRuntime.length > 0)
644
- return "glibc";
645
- if (signals.muslLoaderExists)
646
- return "musl";
647
- return "unknown";
648
- }
649
- function detectCurrentHostLibc(platform = process.platform, arch = process.arch) {
650
- if (platform !== "linux")
651
- return;
652
- const report = process.report?.getReport();
653
- return detectLinuxLibc({
654
- glibcVersionRuntime: report?.header?.glibcVersionRuntime,
655
- muslLoaderExists: existsSync(`/lib/ld-musl-${arch === "x64" ? "x86_64" : arch === "arm64" ? "aarch64" : arch}.so.1`)
656
- });
657
- }
658
- function resolveEmbeddedPostgresTarget(host) {
659
- if (host.platform === "linux" && host.libc === "musl") {
660
- if (host.arch !== "x64" && host.arch !== "arm64") {
661
- throw new Error(`Embedded Postgres does not support Linux musl architecture ${host.arch}.`);
662
- }
663
- const id = `linux-${host.arch}-musl`;
664
- return {
665
- id,
666
- bundledDirectory: id,
667
- nativeLeafPackageName: `@bastani/atomic-natives-linux-${host.arch}-musl`,
668
- emulated: false
669
- };
670
- }
671
- if (host.platform === "win32" && host.arch === "arm64") {
672
- return {
673
- id: "windows-arm64",
674
- bundledDirectory: "windows-arm64",
675
- nativeLeafPackageName: "@bastani/atomic-natives-win32-arm64-msvc",
676
- emulated: true,
677
- reason: "Windows ARM64 runs the Windows x64 PostgreSQL runtime through Windows 11 x64 emulation."
678
- };
679
- }
680
- const platform = host.platform === "win32" ? "windows" : host.platform;
681
- const id = `${platform}-${host.arch}`;
682
- const nativeSuffix = host.arch === "x64" || host.arch === "arm64" ? host.platform === "linux" ? `linux-${host.arch}-gnu` : host.platform === "darwin" ? id : host.platform === "win32" ? `win32-${host.arch}-msvc` : undefined : undefined;
683
- return {
684
- id,
685
- bundledDirectory: id,
686
- nativeLeafPackageName: nativeSuffix === undefined ? undefined : `@bastani/atomic-natives-${nativeSuffix}`,
687
- npmPackageName: `@embedded-postgres/${id}`,
688
- emulated: false
689
- };
690
- }
691
- var init_dbos_embedded_postgres_targets = () => {};
692
-
693
- // dist/builtin/workflows/src/durable/dbos-postgres-health.ts
694
- class PostgresHealth {
695
- operations;
696
- pending;
697
- timer;
698
- stopped = false;
699
- available;
700
- attempts = 0;
701
- failure;
702
- revision = 0;
703
- listeners = new Set;
704
- constructor(operations) {
705
- this.operations = operations;
706
- }
707
- get lastFailure() {
708
- return this.failure;
709
- }
710
- subscribe(listener) {
711
- this.listeners.add(listener);
712
- return () => this.listeners.delete(listener);
713
- }
714
- invalidate() {
715
- this.revision++;
716
- this.available = undefined;
717
- for (const listener of this.listeners)
718
- listener();
719
- }
720
- async validate(client) {
721
- try {
722
- if (this.stopped)
723
- throw new DbosDependencyError;
724
- await this.operations.validate?.(client);
725
- } catch (error) {
726
- this.failure = error instanceof Error ? error : new Error(String(error));
727
- this.invalidate();
728
- throw error;
729
- }
730
- }
731
- check() {
732
- if (this.stopped)
733
- return Promise.reject(new Error("Managed Postgres health observer is stopped."));
734
- this.pending ??= this.refresh().finally(() => {
735
- this.pending = undefined;
736
- });
737
- return this.pending;
738
- }
739
- start() {
740
- if (this.stopped || this.timer !== undefined)
741
- return;
742
- this.timer = setTimeout(() => {
743
- this.timer = undefined;
744
- this.check().catch(() => {}).finally(() => this.start());
745
- }, HEALTH_INTERVAL_MS);
746
- this.timer.unref();
747
- }
748
- async stop() {
749
- this.stopped = true;
750
- if (this.timer !== undefined)
751
- clearTimeout(this.timer);
752
- this.timer = undefined;
753
- await this.pending?.catch(() => {});
754
- this.listeners.clear();
755
- }
756
- async probe() {
757
- const revision = this.revision;
758
- const identity = await this.operations.probe();
759
- if (revision !== this.revision)
760
- return;
761
- if (this.stopped)
762
- throw new Error("Managed Postgres health observer is stopped.");
763
- if (!identity)
764
- return;
765
- if (this.available && this.available.identity !== identity.identity)
766
- this.invalidate();
767
- this.available = identity;
768
- this.attempts = 0;
769
- return identity.url;
770
- }
771
- async refresh() {
772
- try {
773
- const ready = await this.probe();
774
- if (ready !== undefined)
775
- return ready;
776
- } catch (error) {
777
- this.failure = error instanceof Error ? error : new Error(String(error));
778
- if (!(error instanceof Error && ("code" in error) && error.code === "53300"))
779
- this.invalidate();
780
- throw error;
781
- }
782
- if (this.attempts === 0)
783
- this.failure = new DbosDependencyError("Managed PostgreSQL failed its live health check.");
784
- this.invalidate();
785
- while (!this.stopped && this.attempts < RECOVERY_ATTEMPTS) {
786
- const attempt = this.attempts++;
787
- if (attempt > 0)
788
- await (this.operations.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(250 * 2 ** (attempt - 1));
789
- if (this.stopped)
790
- break;
791
- try {
792
- await this.operations.recover();
793
- const ready = await this.probe();
794
- if (ready !== undefined)
795
- return ready;
796
- } catch (error) {
797
- this.failure = error instanceof Error ? error : new Error(String(error));
798
- }
799
- }
800
- throw new DbosDependencyError("Managed Postgres is unavailable after bounded recovery. Preserve its data and ownership records.");
801
- }
802
- }
803
- var HEALTH_INTERVAL_MS = 5000, RECOVERY_ATTEMPTS = 3;
804
- var init_dbos_postgres_health = __esm(() => {
805
- init_dbos_admission();
806
- });
807
-
808
118
  // ../../node_modules/postgres-array/index.js
809
119
  var require_postgres_array = __commonJS(function(exports) {
810
120
  exports.parse = function(source, transform) {
@@ -5094,638 +4404,1344 @@ var require_pg_pool = __commonJS(function(exports, module) {
5094
4404
  });
5095
4405
  return;
5096
4406
  }
5097
- return this._afterConnect(client, pendingItem, idleListener);
4407
+ return this._afterConnect(client, pendingItem, idleListener);
4408
+ }
4409
+ });
4410
+ }
4411
+ _afterConnect(client, pendingItem, idleListener) {
4412
+ if (this.options.maxLifetimeSeconds !== 0) {
4413
+ const maxLifetimeTimeout = setTimeout(() => {
4414
+ this.log("ending client due to expired lifetime");
4415
+ this._expired.add(client);
4416
+ const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
4417
+ if (idleIndex !== -1) {
4418
+ this._acquireClient(client, new PendingItem((err, client, clientRelease) => clientRelease()), idleListener, false);
4419
+ }
4420
+ }, this.options.maxLifetimeSeconds * 1000);
4421
+ maxLifetimeTimeout.unref();
4422
+ client.once("end", () => clearTimeout(maxLifetimeTimeout));
4423
+ }
4424
+ return this._acquireClient(client, pendingItem, idleListener, true);
4425
+ }
4426
+ _acquireClient(client, pendingItem, idleListener, isNew) {
4427
+ if (isNew) {
4428
+ this.emit("connect", client);
4429
+ }
4430
+ this.emit("acquire", client);
4431
+ client.release = this._releaseOnce(client, idleListener);
4432
+ client.removeListener("error", idleListener);
4433
+ if (!pendingItem.timedOut) {
4434
+ if (isNew && this.options.verify) {
4435
+ this.options.verify(client, (err) => {
4436
+ if (err) {
4437
+ client.release(err);
4438
+ return pendingItem.callback(err, undefined, NOOP);
4439
+ }
4440
+ pendingItem.callback(undefined, client, client.release);
4441
+ });
4442
+ } else {
4443
+ pendingItem.callback(undefined, client, client.release);
4444
+ }
4445
+ } else {
4446
+ if (isNew && this.options.verify) {
4447
+ this.options.verify(client, client.release);
4448
+ } else {
4449
+ client.release();
4450
+ }
4451
+ }
4452
+ }
4453
+ _releaseOnce(client, idleListener) {
4454
+ let released = false;
4455
+ return (err) => {
4456
+ if (released) {
4457
+ throwOnDoubleRelease();
4458
+ }
4459
+ released = true;
4460
+ this._release(client, idleListener, err);
4461
+ };
4462
+ }
4463
+ _release(client, idleListener, err) {
4464
+ client.on("error", idleListener);
4465
+ client._poolUseCount = (client._poolUseCount || 0) + 1;
4466
+ this.emit("release", err, client);
4467
+ if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) {
4468
+ if (client._poolUseCount >= this.options.maxUses) {
4469
+ this.log("remove expended client");
4470
+ }
4471
+ return this._remove(client, this._pulseQueue.bind(this));
4472
+ }
4473
+ const isExpired = this._expired.has(client);
4474
+ if (isExpired) {
4475
+ this.log("remove expired client");
4476
+ this._expired.delete(client);
4477
+ return this._remove(client, this._pulseQueue.bind(this));
4478
+ }
4479
+ let tid;
4480
+ if (this.options.idleTimeoutMillis && this._isAboveMin()) {
4481
+ tid = setTimeout(() => {
4482
+ if (this._isAboveMin()) {
4483
+ this.log("remove idle client");
4484
+ this._remove(client, this._pulseQueue.bind(this));
4485
+ }
4486
+ }, this.options.idleTimeoutMillis);
4487
+ if (this.options.allowExitOnIdle) {
4488
+ tid.unref();
4489
+ }
4490
+ }
4491
+ if (this.options.allowExitOnIdle) {
4492
+ client.unref();
4493
+ }
4494
+ this._idle.push(new IdleItem(client, idleListener, tid));
4495
+ this._pulseQueue();
4496
+ }
4497
+ query(text, values, cb) {
4498
+ if (typeof text === "function") {
4499
+ const response = promisify(this.Promise, text);
4500
+ setImmediate(function() {
4501
+ return response.callback(new Error("Passing a function as the first parameter to pool.query is not supported"));
4502
+ });
4503
+ return response.result;
4504
+ }
4505
+ if (typeof values === "function") {
4506
+ cb = values;
4507
+ values = undefined;
4508
+ }
4509
+ const response = promisify(this.Promise, cb);
4510
+ cb = response.callback;
4511
+ this.connect((err, client) => {
4512
+ if (err) {
4513
+ return cb(err);
4514
+ }
4515
+ let clientReleased = false;
4516
+ const onError = (err) => {
4517
+ if (clientReleased) {
4518
+ return;
4519
+ }
4520
+ clientReleased = true;
4521
+ client.release(err);
4522
+ cb(err);
4523
+ };
4524
+ client.once("error", onError);
4525
+ this.log("dispatching query");
4526
+ try {
4527
+ client.query(text, values, (err, res) => {
4528
+ this.log("query dispatched");
4529
+ client.removeListener("error", onError);
4530
+ if (clientReleased) {
4531
+ return;
4532
+ }
4533
+ clientReleased = true;
4534
+ client.release(err);
4535
+ if (err) {
4536
+ return cb(err);
4537
+ }
4538
+ return cb(undefined, res);
4539
+ });
4540
+ } catch (err) {
4541
+ client.release(err);
4542
+ return cb(err);
5098
4543
  }
5099
4544
  });
4545
+ return response.result;
5100
4546
  }
5101
- _afterConnect(client, pendingItem, idleListener) {
5102
- if (this.options.maxLifetimeSeconds !== 0) {
5103
- const maxLifetimeTimeout = setTimeout(() => {
5104
- this.log("ending client due to expired lifetime");
5105
- this._expired.add(client);
5106
- const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
5107
- if (idleIndex !== -1) {
5108
- this._acquireClient(client, new PendingItem((err, client, clientRelease) => clientRelease()), idleListener, false);
5109
- }
5110
- }, this.options.maxLifetimeSeconds * 1000);
5111
- maxLifetimeTimeout.unref();
5112
- client.once("end", () => clearTimeout(maxLifetimeTimeout));
4547
+ end(cb) {
4548
+ this.log("ending");
4549
+ if (this.ending) {
4550
+ const err = new Error("Called end on pool more than once");
4551
+ return cb ? cb(err) : this.Promise.reject(err);
5113
4552
  }
5114
- return this._acquireClient(client, pendingItem, idleListener, true);
4553
+ this.ending = true;
4554
+ const promised = promisify(this.Promise, cb);
4555
+ this._endCallback = promised.callback;
4556
+ this._pulseQueue();
4557
+ return promised.result;
5115
4558
  }
5116
- _acquireClient(client, pendingItem, idleListener, isNew) {
5117
- if (isNew) {
5118
- this.emit("connect", client);
4559
+ get waitingCount() {
4560
+ return this._pendingQueue.length;
4561
+ }
4562
+ get idleCount() {
4563
+ return this._idle.length;
4564
+ }
4565
+ get expiredCount() {
4566
+ return this._clients.reduce((acc, client) => acc + (this._expired.has(client) ? 1 : 0), 0);
4567
+ }
4568
+ get totalCount() {
4569
+ return this._clients.length;
4570
+ }
4571
+ }
4572
+ module.exports = Pool;
4573
+ });
4574
+
4575
+ // ../../node_modules/pg/lib/native/query.js
4576
+ var require_query2 = __commonJS(function(exports, module) {
4577
+ var EventEmitter = __require("events").EventEmitter;
4578
+ var util = __require("util");
4579
+ var utils = require_utils();
4580
+ var NativeQuery = module.exports = function(config, values, callback) {
4581
+ EventEmitter.call(this);
4582
+ config = utils.normalizeQueryConfig(config, values, callback);
4583
+ this.text = config.text;
4584
+ this.values = config.values;
4585
+ this.name = config.name;
4586
+ this.queryMode = config.queryMode;
4587
+ this.callback = config.callback;
4588
+ this.state = "new";
4589
+ this._arrayMode = config.rowMode === "array";
4590
+ this._emitRowEvents = false;
4591
+ this.on("newListener", function(event) {
4592
+ if (event === "row")
4593
+ this._emitRowEvents = true;
4594
+ }.bind(this));
4595
+ };
4596
+ util.inherits(NativeQuery, EventEmitter);
4597
+ var errorFieldMap = {
4598
+ sqlState: "code",
4599
+ statementPosition: "position",
4600
+ messagePrimary: "message",
4601
+ context: "where",
4602
+ schemaName: "schema",
4603
+ tableName: "table",
4604
+ columnName: "column",
4605
+ dataTypeName: "dataType",
4606
+ constraintName: "constraint",
4607
+ sourceFile: "file",
4608
+ sourceLine: "line",
4609
+ sourceFunction: "routine"
4610
+ };
4611
+ NativeQuery.prototype.handleError = function(err) {
4612
+ const fields = this.native.pq.resultErrorFields();
4613
+ if (fields) {
4614
+ for (const key in fields) {
4615
+ const normalizedFieldName = errorFieldMap[key] || key;
4616
+ err[normalizedFieldName] = fields[key];
5119
4617
  }
5120
- this.emit("acquire", client);
5121
- client.release = this._releaseOnce(client, idleListener);
5122
- client.removeListener("error", idleListener);
5123
- if (!pendingItem.timedOut) {
5124
- if (isNew && this.options.verify) {
5125
- this.options.verify(client, (err) => {
5126
- if (err) {
5127
- client.release(err);
5128
- return pendingItem.callback(err, undefined, NOOP);
5129
- }
5130
- pendingItem.callback(undefined, client, client.release);
4618
+ }
4619
+ if (this.callback) {
4620
+ this.callback(err);
4621
+ } else {
4622
+ this.emit("error", err);
4623
+ }
4624
+ this.state = "error";
4625
+ };
4626
+ NativeQuery.prototype.then = function(onSuccess, onFailure) {
4627
+ return this._getPromise().then(onSuccess, onFailure);
4628
+ };
4629
+ NativeQuery.prototype.catch = function(callback) {
4630
+ return this._getPromise().catch(callback);
4631
+ };
4632
+ NativeQuery.prototype._getPromise = function() {
4633
+ if (this._promise)
4634
+ return this._promise;
4635
+ this._promise = new Promise(function(resolve, reject) {
4636
+ this._once("end", resolve);
4637
+ this._once("error", reject);
4638
+ }.bind(this));
4639
+ return this._promise;
4640
+ };
4641
+ NativeQuery.prototype.submit = function(client) {
4642
+ this.state = "running";
4643
+ const self = this;
4644
+ this.native = client.native;
4645
+ client.native.arrayMode = this._arrayMode;
4646
+ let after = function(err, rows, results) {
4647
+ client.native.arrayMode = false;
4648
+ setImmediate(function() {
4649
+ self.emit("_done");
4650
+ });
4651
+ if (err) {
4652
+ return self.handleError(err);
4653
+ }
4654
+ if (self._emitRowEvents) {
4655
+ if (results.length > 1) {
4656
+ rows.forEach((rowOfRows, i) => {
4657
+ rowOfRows.forEach((row) => {
4658
+ self.emit("row", row, results[i]);
4659
+ });
5131
4660
  });
5132
4661
  } else {
5133
- pendingItem.callback(undefined, client, client.release);
5134
- }
5135
- } else {
5136
- if (isNew && this.options.verify) {
5137
- this.options.verify(client, client.release);
5138
- } else {
5139
- client.release();
4662
+ rows.forEach(function(row) {
4663
+ self.emit("row", row, results);
4664
+ });
5140
4665
  }
5141
4666
  }
4667
+ self.state = "end";
4668
+ self.emit("end", results);
4669
+ if (self.callback) {
4670
+ self.callback(null, results);
4671
+ }
4672
+ };
4673
+ if (process.domain) {
4674
+ after = process.domain.bind(after);
5142
4675
  }
5143
- _releaseOnce(client, idleListener) {
5144
- let released = false;
5145
- return (err) => {
5146
- if (released) {
5147
- throwOnDoubleRelease();
4676
+ if (this.name) {
4677
+ if (this.name.length > 63) {
4678
+ console.error("Warning! Postgres only supports 63 characters for query names.");
4679
+ console.error("You supplied %s (%s)", this.name, this.name.length);
4680
+ console.error("This can cause conflicts and silent errors executing queries");
4681
+ }
4682
+ const values = (this.values || []).map(utils.prepareValue);
4683
+ if (client.namedQueries[this.name]) {
4684
+ if (this.text && client.namedQueries[this.name] !== this.text) {
4685
+ const err = new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);
4686
+ return after(err);
5148
4687
  }
5149
- released = true;
5150
- this._release(client, idleListener, err);
5151
- };
4688
+ return client.native.execute(this.name, values, after);
4689
+ }
4690
+ return client.native.prepare(this.name, this.text, values.length, function(err) {
4691
+ if (err)
4692
+ return after(err);
4693
+ client.namedQueries[self.name] = self.text;
4694
+ return self.native.execute(self.name, values, after);
4695
+ });
4696
+ } else if (this.values) {
4697
+ if (!Array.isArray(this.values)) {
4698
+ const err = new Error("Query values must be an array");
4699
+ return after(err);
4700
+ }
4701
+ const vals = this.values.map(utils.prepareValue);
4702
+ client.native.query(this.text, vals, after);
4703
+ } else if (this.queryMode === "extended") {
4704
+ client.native.query(this.text, [], after);
4705
+ } else {
4706
+ client.native.query(this.text, after);
4707
+ }
4708
+ };
4709
+ });
4710
+
4711
+ // ../../node_modules/pg/lib/native/client.js
4712
+ var require_client2 = __commonJS(function(exports, module) {
4713
+ var nodeUtils = __require("util");
4714
+ var Native;
4715
+ try {
4716
+ Native = (()=>{throw new Error("Cannot require module "+"pg-native");})();
4717
+ } catch (e) {
4718
+ throw e;
4719
+ }
4720
+ var TypeOverrides = require_type_overrides();
4721
+ var EventEmitter = __require("events").EventEmitter;
4722
+ var util = __require("util");
4723
+ var ConnectionParameters = require_connection_parameters();
4724
+ var NativeQuery = require_query2();
4725
+ var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(() => {}, "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");
4726
+ var Client = module.exports = function(config) {
4727
+ EventEmitter.call(this);
4728
+ config = config || {};
4729
+ this._Promise = config.Promise || global.Promise;
4730
+ this._types = new TypeOverrides(config.types);
4731
+ this.native = new Native({
4732
+ types: this._types
4733
+ });
4734
+ this._queryQueue = [];
4735
+ this._ending = false;
4736
+ this._connecting = false;
4737
+ this._connected = false;
4738
+ this._queryable = true;
4739
+ const cp = this.connectionParameters = new ConnectionParameters(config);
4740
+ if (config.nativeConnectionString)
4741
+ cp.nativeConnectionString = config.nativeConnectionString;
4742
+ this.user = cp.user;
4743
+ Object.defineProperty(this, "password", {
4744
+ configurable: true,
4745
+ enumerable: false,
4746
+ writable: true,
4747
+ value: cp.password
4748
+ });
4749
+ this.database = cp.database;
4750
+ this.host = cp.host;
4751
+ this.port = cp.port;
4752
+ this.namedQueries = {};
4753
+ };
4754
+ Client.Query = NativeQuery;
4755
+ util.inherits(Client, EventEmitter);
4756
+ Client.prototype._errorAllQueries = function(err) {
4757
+ const enqueueError = (query) => {
4758
+ process.nextTick(() => {
4759
+ query.native = this.native;
4760
+ query.handleError(err);
4761
+ });
4762
+ };
4763
+ if (this._hasActiveQuery()) {
4764
+ enqueueError(this._activeQuery);
4765
+ this._activeQuery = null;
5152
4766
  }
5153
- _release(client, idleListener, err) {
5154
- client.on("error", idleListener);
5155
- client._poolUseCount = (client._poolUseCount || 0) + 1;
5156
- this.emit("release", err, client);
5157
- if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) {
5158
- if (client._poolUseCount >= this.options.maxUses) {
5159
- this.log("remove expended client");
5160
- }
5161
- return this._remove(client, this._pulseQueue.bind(this));
5162
- }
5163
- const isExpired = this._expired.has(client);
5164
- if (isExpired) {
5165
- this.log("remove expired client");
5166
- this._expired.delete(client);
5167
- return this._remove(client, this._pulseQueue.bind(this));
5168
- }
5169
- let tid;
5170
- if (this.options.idleTimeoutMillis && this._isAboveMin()) {
5171
- tid = setTimeout(() => {
5172
- if (this._isAboveMin()) {
5173
- this.log("remove idle client");
5174
- this._remove(client, this._pulseQueue.bind(this));
5175
- }
5176
- }, this.options.idleTimeoutMillis);
5177
- if (this.options.allowExitOnIdle) {
5178
- tid.unref();
5179
- }
5180
- }
5181
- if (this.options.allowExitOnIdle) {
5182
- client.unref();
5183
- }
5184
- this._idle.push(new IdleItem(client, idleListener, tid));
5185
- this._pulseQueue();
4767
+ this._queryQueue.forEach(enqueueError);
4768
+ this._queryQueue.length = 0;
4769
+ };
4770
+ Client.prototype._connect = function(cb) {
4771
+ const self = this;
4772
+ if (this._connecting) {
4773
+ process.nextTick(() => cb(new Error("Client has already been connected. You cannot reuse a client.")));
4774
+ return;
5186
4775
  }
5187
- query(text, values, cb) {
5188
- if (typeof text === "function") {
5189
- const response = promisify(this.Promise, text);
5190
- setImmediate(function() {
5191
- return response.callback(new Error("Passing a function as the first parameter to pool.query is not supported"));
5192
- });
5193
- return response.result;
5194
- }
5195
- if (typeof values === "function") {
5196
- cb = values;
5197
- values = undefined;
5198
- }
5199
- const response = promisify(this.Promise, cb);
5200
- cb = response.callback;
5201
- this.connect((err, client) => {
4776
+ this._connecting = true;
4777
+ this.connectionParameters.getLibpqConnectionString(function(err, conString) {
4778
+ if (self.connectionParameters.nativeConnectionString)
4779
+ conString = self.connectionParameters.nativeConnectionString;
4780
+ if (err)
4781
+ return cb(err);
4782
+ self.native.connect(conString, function(err) {
5202
4783
  if (err) {
4784
+ self.native.end();
5203
4785
  return cb(err);
5204
4786
  }
5205
- let clientReleased = false;
5206
- const onError = (err) => {
5207
- if (clientReleased) {
5208
- return;
5209
- }
5210
- clientReleased = true;
5211
- client.release(err);
5212
- cb(err);
5213
- };
5214
- client.once("error", onError);
5215
- this.log("dispatching query");
5216
- try {
5217
- client.query(text, values, (err, res) => {
5218
- this.log("query dispatched");
5219
- client.removeListener("error", onError);
5220
- if (clientReleased) {
5221
- return;
5222
- }
5223
- clientReleased = true;
5224
- client.release(err);
5225
- if (err) {
5226
- return cb(err);
5227
- }
5228
- return cb(undefined, res);
4787
+ self._connected = true;
4788
+ self.native.on("error", function(err) {
4789
+ self._queryable = false;
4790
+ self._errorAllQueries(err);
4791
+ self.emit("error", err);
4792
+ });
4793
+ self.native.on("notification", function(msg) {
4794
+ self.emit("notification", {
4795
+ channel: msg.relname,
4796
+ payload: msg.extra
5229
4797
  });
5230
- } catch (err) {
5231
- client.release(err);
5232
- return cb(err);
5233
- }
4798
+ });
4799
+ self.emit("connect");
4800
+ self._pulseQueryQueue(true);
4801
+ cb(null, this);
5234
4802
  });
5235
- return response.result;
4803
+ });
4804
+ };
4805
+ Client.prototype.connect = function(callback) {
4806
+ if (callback) {
4807
+ this._connect(callback);
4808
+ return;
5236
4809
  }
5237
- end(cb) {
5238
- this.log("ending");
5239
- if (this.ending) {
5240
- const err = new Error("Called end on pool more than once");
5241
- return cb ? cb(err) : this.Promise.reject(err);
4810
+ return new this._Promise((resolve, reject) => {
4811
+ this._connect((error) => {
4812
+ if (error) {
4813
+ reject(error);
4814
+ } else {
4815
+ resolve(this);
4816
+ }
4817
+ });
4818
+ });
4819
+ };
4820
+ Client.prototype.query = function(config, values, callback) {
4821
+ let query;
4822
+ let result;
4823
+ let readTimeout;
4824
+ let readTimeoutTimer;
4825
+ let queryCallback;
4826
+ if (config === null || config === undefined) {
4827
+ throw new TypeError("Client was passed a null or undefined query");
4828
+ } else if (typeof config.submit === "function") {
4829
+ readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4830
+ result = query = config;
4831
+ if (typeof values === "function") {
4832
+ config.callback = values;
4833
+ }
4834
+ } else {
4835
+ readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4836
+ query = new NativeQuery(config, values, callback);
4837
+ if (!query.callback) {
4838
+ let resolveOut, rejectOut;
4839
+ result = new this._Promise((resolve, reject) => {
4840
+ resolveOut = resolve;
4841
+ rejectOut = reject;
4842
+ }).catch((err) => {
4843
+ Error.captureStackTrace(err);
4844
+ throw err;
4845
+ });
4846
+ query.callback = (err, res) => err ? rejectOut(err) : resolveOut(res);
5242
4847
  }
5243
- this.ending = true;
5244
- const promised = promisify(this.Promise, cb);
5245
- this._endCallback = promised.callback;
5246
- this._pulseQueue();
5247
- return promised.result;
5248
4848
  }
5249
- get waitingCount() {
5250
- return this._pendingQueue.length;
4849
+ if (readTimeout) {
4850
+ queryCallback = query.callback || (() => {});
4851
+ readTimeoutTimer = setTimeout(() => {
4852
+ const error = new Error("Query read timeout");
4853
+ process.nextTick(() => {
4854
+ query.handleError(error, this.connection);
4855
+ });
4856
+ queryCallback(error);
4857
+ query.callback = () => {};
4858
+ const index = this._queryQueue.indexOf(query);
4859
+ if (index > -1) {
4860
+ this._queryQueue.splice(index, 1);
4861
+ }
4862
+ this._pulseQueryQueue();
4863
+ }, readTimeout);
4864
+ query.callback = (err, res) => {
4865
+ clearTimeout(readTimeoutTimer);
4866
+ queryCallback(err, res);
4867
+ };
5251
4868
  }
5252
- get idleCount() {
5253
- return this._idle.length;
4869
+ if (!this._queryable) {
4870
+ query.native = this.native;
4871
+ process.nextTick(() => {
4872
+ query.handleError(new Error("Client has encountered a connection error and is not queryable"));
4873
+ });
4874
+ return result;
5254
4875
  }
5255
- get expiredCount() {
5256
- return this._clients.reduce((acc, client) => acc + (this._expired.has(client) ? 1 : 0), 0);
4876
+ if (this._ending) {
4877
+ query.native = this.native;
4878
+ process.nextTick(() => {
4879
+ query.handleError(new Error("Client was closed and is not queryable"));
4880
+ });
4881
+ return result;
5257
4882
  }
5258
- get totalCount() {
5259
- return this._clients.length;
4883
+ if (this._queryQueue.length > 0) {
4884
+ queryQueueLengthDeprecationNotice();
5260
4885
  }
5261
- }
5262
- module.exports = Pool;
5263
- });
5264
-
5265
- // ../../node_modules/pg/lib/native/query.js
5266
- var require_query2 = __commonJS(function(exports, module) {
5267
- var EventEmitter = __require("events").EventEmitter;
5268
- var util = __require("util");
5269
- var utils = require_utils();
5270
- var NativeQuery = module.exports = function(config, values, callback) {
5271
- EventEmitter.call(this);
5272
- config = utils.normalizeQueryConfig(config, values, callback);
5273
- this.text = config.text;
5274
- this.values = config.values;
5275
- this.name = config.name;
5276
- this.queryMode = config.queryMode;
5277
- this.callback = config.callback;
5278
- this.state = "new";
5279
- this._arrayMode = config.rowMode === "array";
5280
- this._emitRowEvents = false;
5281
- this.on("newListener", function(event) {
5282
- if (event === "row")
5283
- this._emitRowEvents = true;
5284
- }.bind(this));
4886
+ this._queryQueue.push(query);
4887
+ this._pulseQueryQueue();
4888
+ return result;
5285
4889
  };
5286
- util.inherits(NativeQuery, EventEmitter);
5287
- var errorFieldMap = {
5288
- sqlState: "code",
5289
- statementPosition: "position",
5290
- messagePrimary: "message",
5291
- context: "where",
5292
- schemaName: "schema",
5293
- tableName: "table",
5294
- columnName: "column",
5295
- dataTypeName: "dataType",
5296
- constraintName: "constraint",
5297
- sourceFile: "file",
5298
- sourceLine: "line",
5299
- sourceFunction: "routine"
4890
+ Client.prototype.end = function(cb) {
4891
+ const self = this;
4892
+ this._ending = true;
4893
+ if (this._connecting && !this._connected) {
4894
+ this.once("connect", () => {
4895
+ this.end(() => {});
4896
+ });
4897
+ }
4898
+ let result;
4899
+ if (!cb) {
4900
+ result = new this._Promise(function(resolve, reject) {
4901
+ cb = (err) => err ? reject(err) : resolve();
4902
+ });
4903
+ }
4904
+ this.native.end(function() {
4905
+ self._connected = false;
4906
+ self._errorAllQueries(new Error("Connection terminated"));
4907
+ process.nextTick(() => {
4908
+ self.emit("end");
4909
+ if (cb)
4910
+ cb();
4911
+ });
4912
+ });
4913
+ return result;
5300
4914
  };
5301
- NativeQuery.prototype.handleError = function(err) {
5302
- const fields = this.native.pq.resultErrorFields();
5303
- if (fields) {
5304
- for (const key in fields) {
5305
- const normalizedFieldName = errorFieldMap[key] || key;
5306
- err[normalizedFieldName] = fields[key];
4915
+ Client.prototype._hasActiveQuery = function() {
4916
+ return this._activeQuery && this._activeQuery.state !== "error" && this._activeQuery.state !== "end";
4917
+ };
4918
+ Client.prototype._pulseQueryQueue = function(initialConnection) {
4919
+ if (!this._connected) {
4920
+ return;
4921
+ }
4922
+ if (this._hasActiveQuery()) {
4923
+ return;
4924
+ }
4925
+ const query = this._queryQueue.shift();
4926
+ if (!query) {
4927
+ if (!initialConnection) {
4928
+ this.emit("drain");
5307
4929
  }
4930
+ return;
5308
4931
  }
5309
- if (this.callback) {
5310
- this.callback(err);
5311
- } else {
5312
- this.emit("error", err);
4932
+ this._activeQuery = query;
4933
+ query.submit(this);
4934
+ const self = this;
4935
+ query.once("_done", function() {
4936
+ self._pulseQueryQueue();
4937
+ });
4938
+ };
4939
+ Client.prototype.cancel = function(query) {
4940
+ if (this._activeQuery === query) {
4941
+ this.native.cancel(function() {});
4942
+ } else if (this._queryQueue.indexOf(query) !== -1) {
4943
+ this._queryQueue.splice(this._queryQueue.indexOf(query), 1);
5313
4944
  }
5314
- this.state = "error";
5315
4945
  };
5316
- NativeQuery.prototype.then = function(onSuccess, onFailure) {
5317
- return this._getPromise().then(onSuccess, onFailure);
4946
+ Client.prototype.ref = function() {};
4947
+ Client.prototype.unref = function() {};
4948
+ Client.prototype.setTypeParser = function(oid, format, parseFn) {
4949
+ return this._types.setTypeParser(oid, format, parseFn);
5318
4950
  };
5319
- NativeQuery.prototype.catch = function(callback) {
5320
- return this._getPromise().catch(callback);
4951
+ Client.prototype.getTypeParser = function(oid, format) {
4952
+ return this._types.getTypeParser(oid, format);
5321
4953
  };
5322
- NativeQuery.prototype._getPromise = function() {
5323
- if (this._promise)
5324
- return this._promise;
5325
- this._promise = new Promise(function(resolve, reject) {
5326
- this._once("end", resolve);
5327
- this._once("error", reject);
5328
- }.bind(this));
5329
- return this._promise;
4954
+ Client.prototype.isConnected = function() {
4955
+ return this._connected;
5330
4956
  };
5331
- NativeQuery.prototype.submit = function(client) {
5332
- this.state = "running";
5333
- const self = this;
5334
- this.native = client.native;
5335
- client.native.arrayMode = this._arrayMode;
5336
- let after = function(err, rows, results) {
5337
- client.native.arrayMode = false;
5338
- setImmediate(function() {
5339
- self.emit("_done");
5340
- });
5341
- if (err) {
5342
- return self.handleError(err);
5343
- }
5344
- if (self._emitRowEvents) {
5345
- if (results.length > 1) {
5346
- rows.forEach((rowOfRows, i) => {
5347
- rowOfRows.forEach((row) => {
5348
- self.emit("row", row, results[i]);
5349
- });
5350
- });
5351
- } else {
5352
- rows.forEach(function(row) {
5353
- self.emit("row", row, results);
5354
- });
5355
- }
5356
- }
5357
- self.state = "end";
5358
- self.emit("end", results);
5359
- if (self.callback) {
5360
- self.callback(null, results);
4957
+ Client.prototype.getTransactionStatus = function() {
4958
+ return this.native.getTransactionStatus();
4959
+ };
4960
+ });
4961
+
4962
+ // ../../node_modules/pg/lib/index.js
4963
+ var require_lib2 = __commonJS(function(exports, module) {
4964
+ var Client = require_client();
4965
+ var defaults = require_defaults();
4966
+ var Connection = require_connection();
4967
+ var Result = require_result();
4968
+ var utils = require_utils();
4969
+ var Pool = require_pg_pool();
4970
+ var TypeOverrides = require_type_overrides();
4971
+ var { DatabaseError } = require_dist();
4972
+ var { escapeIdentifier, escapeLiteral } = require_utils();
4973
+ var poolFactory = (Client) => {
4974
+ return class BoundPool extends Pool {
4975
+ constructor(options) {
4976
+ super(options, Client);
5361
4977
  }
5362
4978
  };
5363
- if (process.domain) {
5364
- after = process.domain.bind(after);
5365
- }
5366
- if (this.name) {
5367
- if (this.name.length > 63) {
5368
- console.error("Warning! Postgres only supports 63 characters for query names.");
5369
- console.error("You supplied %s (%s)", this.name, this.name.length);
5370
- console.error("This can cause conflicts and silent errors executing queries");
5371
- }
5372
- const values = (this.values || []).map(utils.prepareValue);
5373
- if (client.namedQueries[this.name]) {
5374
- if (this.text && client.namedQueries[this.name] !== this.text) {
5375
- const err = new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);
5376
- return after(err);
4979
+ };
4980
+ var PG = function(clientConstructor) {
4981
+ this.defaults = defaults;
4982
+ this.Client = clientConstructor;
4983
+ this.Query = this.Client.Query;
4984
+ this.Pool = poolFactory(this.Client);
4985
+ this._pools = [];
4986
+ this.Connection = Connection;
4987
+ this.types = require_pg_types();
4988
+ this.DatabaseError = DatabaseError;
4989
+ this.TypeOverrides = TypeOverrides;
4990
+ this.escapeIdentifier = escapeIdentifier;
4991
+ this.escapeLiteral = escapeLiteral;
4992
+ this.Result = Result;
4993
+ this.utils = utils;
4994
+ };
4995
+ var clientConstructor = Client;
4996
+ var forceNative = false;
4997
+ try {
4998
+ forceNative = !!process.env.NODE_PG_FORCE_NATIVE;
4999
+ } catch {}
5000
+ if (forceNative) {
5001
+ clientConstructor = require_client2();
5002
+ }
5003
+ module.exports = new PG(clientConstructor);
5004
+ Object.defineProperty(module.exports, "native", {
5005
+ configurable: true,
5006
+ enumerable: false,
5007
+ get() {
5008
+ let native = null;
5009
+ try {
5010
+ native = new PG(require_client2());
5011
+ } catch (err) {
5012
+ if (err.code !== "MODULE_NOT_FOUND") {
5013
+ throw err;
5377
5014
  }
5378
- return client.native.execute(this.name, values, after);
5379
5015
  }
5380
- return client.native.prepare(this.name, this.text, values.length, function(err) {
5381
- if (err)
5382
- return after(err);
5383
- client.namedQueries[self.name] = self.text;
5384
- return self.native.execute(self.name, values, after);
5016
+ Object.defineProperty(module.exports, "native", {
5017
+ value: native
5018
+ });
5019
+ return native;
5020
+ }
5021
+ });
5022
+ });
5023
+
5024
+ // ../../node_modules/pg/esm/index.mjs
5025
+ var import_lib, Client, Pool, Connection, types, Query, DatabaseError, escapeIdentifier, escapeLiteral, Result, TypeOverrides, defaults;
5026
+ var init_esm = __esm(() => {
5027
+ import_lib = __toESM(require_lib2(), 1);
5028
+ Client = import_lib.default.Client;
5029
+ Pool = import_lib.default.Pool;
5030
+ Connection = import_lib.default.Connection;
5031
+ types = import_lib.default.types;
5032
+ Query = import_lib.default.Query;
5033
+ DatabaseError = import_lib.default.DatabaseError;
5034
+ escapeIdentifier = import_lib.default.escapeIdentifier;
5035
+ escapeLiteral = import_lib.default.escapeLiteral;
5036
+ Result = import_lib.default.Result;
5037
+ TypeOverrides = import_lib.default.TypeOverrides;
5038
+ defaults = import_lib.default.defaults;
5039
+ });
5040
+
5041
+ // dist/builtin/workflows/src/durable/dbos-default-postgres-url.ts
5042
+ function defaultPostgresUrl(database, host = process.env.PGHOST || "localhost", port = process.env.PGPORT || "5432") {
5043
+ const url = new URL("postgresql://localhost");
5044
+ url.pathname = `/${database}`;
5045
+ if (host.startsWith("/") || host.includes(":"))
5046
+ url.searchParams.set("host", host);
5047
+ else
5048
+ url.hostname = host;
5049
+ url.port = port;
5050
+ url.username = encodeURIComponent(process.env.PGUSER || "postgres");
5051
+ url.password = encodeURIComponent(process.env.PGPASSWORD || "dbos");
5052
+ url.searchParams.set("connect_timeout", process.env.PGCONNECT_TIMEOUT || "10");
5053
+ url.searchParams.set("sslmode", process.env.PGSSLMODE || (host === "localhost" ? "disable" : "allow"));
5054
+ return url.toString();
5055
+ }
5056
+
5057
+ // dist/builtin/workflows/src/durable/local-command.ts
5058
+ import { spawn } from "node:child_process";
5059
+ import { connect } from "node:net";
5060
+ import { createChildProcessEnvironment } from "@bastani/atomic";
5061
+ function runLocalCommand(command, args, options) {
5062
+ return new Promise((resolve, reject) => {
5063
+ const child = spawn(command, [...args], {
5064
+ stdio: ["ignore", "pipe", "pipe"],
5065
+ windowsHide: true,
5066
+ env: createChildProcessEnvironment(options?.env ? { ...options.env } : undefined),
5067
+ ...options?.uid !== undefined ? { uid: options.uid } : {},
5068
+ ...options?.gid !== undefined ? { gid: options.gid } : {}
5069
+ });
5070
+ let stdout = "";
5071
+ let stderr = "";
5072
+ let stdoutTruncated = false;
5073
+ let stderrTruncated = false;
5074
+ let settled = false;
5075
+ let exitFallback;
5076
+ child.stdout.setEncoding("utf8");
5077
+ child.stderr.setEncoding("utf8");
5078
+ const onStdout = (chunk) => {
5079
+ const appended = boundedAppend(stdout, chunk);
5080
+ stdout = appended.value;
5081
+ stdoutTruncated ||= appended.truncated;
5082
+ };
5083
+ const onStderr = (chunk) => {
5084
+ const appended = boundedAppend(stderr, chunk);
5085
+ stderr = appended.value;
5086
+ stderrTruncated ||= appended.truncated;
5087
+ };
5088
+ const cleanup = () => {
5089
+ if (exitFallback !== undefined)
5090
+ clearImmediate(exitFallback);
5091
+ child.off("error", onError);
5092
+ child.off("exit", onExit);
5093
+ child.off("close", onClose);
5094
+ child.stdout.off("data", onStdout);
5095
+ child.stderr.off("data", onStderr);
5096
+ child.stdout.destroy();
5097
+ child.stderr.destroy();
5098
+ };
5099
+ const finish = (code) => {
5100
+ if (settled)
5101
+ return;
5102
+ settled = true;
5103
+ cleanup();
5104
+ resolve({
5105
+ exitCode: code ?? 1,
5106
+ stdout,
5107
+ stderr,
5108
+ ...stdoutTruncated ? { stdoutTruncated: true } : {},
5109
+ ...stderrTruncated ? { stderrTruncated: true } : {}
5385
5110
  });
5386
- } else if (this.values) {
5387
- if (!Array.isArray(this.values)) {
5388
- const err = new Error("Query values must be an array");
5389
- return after(err);
5390
- }
5391
- const vals = this.values.map(utils.prepareValue);
5392
- client.native.query(this.text, vals, after);
5393
- } else if (this.queryMode === "extended") {
5394
- client.native.query(this.text, [], after);
5395
- } else {
5396
- client.native.query(this.text, after);
5397
- }
5398
- };
5399
- });
5111
+ };
5112
+ const onError = (error) => {
5113
+ if (settled)
5114
+ return;
5115
+ settled = true;
5116
+ cleanup();
5117
+ reject(error);
5118
+ };
5119
+ const onExit = (code) => {
5120
+ if (code !== 0)
5121
+ return;
5122
+ exitFallback = setImmediate(() => finish(code));
5123
+ };
5124
+ const onClose = (code) => finish(code);
5125
+ child.stdout.on("data", onStdout);
5126
+ child.stderr.on("data", onStderr);
5127
+ child.once("error", onError);
5128
+ if (options?.completion === "successful-exit")
5129
+ child.once("exit", onExit);
5130
+ child.once("close", onClose);
5131
+ });
5132
+ }
5133
+ function commandFailureDetail(result) {
5134
+ return result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`;
5135
+ }
5136
+ function delay(ms) {
5137
+ return new Promise((resolve) => setTimeout(resolve, ms));
5138
+ }
5139
+ function tcpReachable(host, port, timeoutMs = 1000) {
5140
+ return new Promise((resolve) => {
5141
+ const socket = connect({ host, port });
5142
+ const finish = (reachable) => {
5143
+ socket.removeAllListeners();
5144
+ socket.destroy();
5145
+ resolve(reachable);
5146
+ };
5147
+ socket.setTimeout(timeoutMs);
5148
+ socket.once("connect", () => finish(true));
5149
+ socket.once("timeout", () => finish(false));
5150
+ socket.once("error", () => finish(false));
5151
+ });
5152
+ }
5153
+ function boundedAppend(current, chunk) {
5154
+ const next = current + chunk;
5155
+ return next.length <= OUTPUT_LIMIT_BYTES ? { value: next, truncated: false } : { value: next.slice(-OUTPUT_LIMIT_BYTES), truncated: true };
5156
+ }
5157
+ var OUTPUT_LIMIT_BYTES = 16384;
5158
+ var init_local_command = () => {};
5400
5159
 
5401
- // ../../node_modules/pg/lib/native/client.js
5402
- var require_client2 = __commonJS(function(exports, module) {
5403
- var nodeUtils = __require("util");
5404
- var Native;
5160
+ // dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts
5161
+ import { createHash as createHash3 } from "node:crypto";
5162
+ import {
5163
+ chmod,
5164
+ chown,
5165
+ cp,
5166
+ lstat,
5167
+ mkdir,
5168
+ open,
5169
+ readdir,
5170
+ readlink,
5171
+ realpath,
5172
+ rename,
5173
+ rm,
5174
+ writeFile
5175
+ } from "node:fs/promises";
5176
+ import { homedir } from "node:os";
5177
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
5178
+ function defaultEmbeddedBaseDir() {
5179
+ return join(homedir(), ".atomic", "postgres");
5180
+ }
5181
+ async function resolveEmbeddedRunContext(runner = runLocalCommand, euid = process.getuid?.(), platform = process.platform) {
5182
+ if (platform !== "linux" || euid !== 0) {
5183
+ return { baseDir: defaultEmbeddedBaseDir(), runAsOwner: runner };
5184
+ }
5185
+ for (const name of OWNER_CANDIDATES) {
5186
+ const owner = await lookupOwner(runner, name);
5187
+ if (owner === undefined)
5188
+ continue;
5189
+ const runAsOwner = await resolvePrivilegeDrop(runner, owner);
5190
+ if (runAsOwner === undefined)
5191
+ continue;
5192
+ return { baseDir: ROOT_EMBEDDED_BASE_DIR, owner, runAsOwner };
5193
+ }
5194
+ return { baseDir: defaultEmbeddedBaseDir(), runAsOwner: runner };
5195
+ }
5196
+ async function resolvePrivilegeDrop(runner, owner) {
5197
+ const strategies = [
5198
+ (command, args, options) => runner(command, args, { ...options, uid: owner.uid, gid: owner.gid }),
5199
+ (command, args, options) => runner("setpriv", [`--reuid=${owner.uid}`, `--regid=${owner.gid}`, "--clear-groups", "--", command, ...args], options),
5200
+ (command, args, options) => runner("runuser", ["-u", owner.name, "--", command, ...args], options),
5201
+ (command, args, options) => runner("su", ["-s", "/bin/sh", "-c", shellCommand(command, args), owner.name], options)
5202
+ ];
5203
+ for (const strategy of strategies) {
5204
+ if (await provesOwnerIdentity(strategy, owner))
5205
+ return strategy;
5206
+ }
5207
+ return;
5208
+ }
5209
+ async function provesOwnerIdentity(strategy, owner) {
5405
5210
  try {
5406
- Native = (()=>{throw new Error("Cannot require module "+"pg-native");})();
5407
- } catch (e) {
5408
- throw e;
5211
+ const uid = parseIdentityNumber(await strategy("id", ["-u"]));
5212
+ if (uid !== owner.uid)
5213
+ return false;
5214
+ const gid = parseIdentityNumber(await strategy("id", ["-g"]));
5215
+ if (gid !== owner.gid)
5216
+ return false;
5217
+ const groups = parseIdentityGroups(await strategy("id", ["-G"]));
5218
+ return groups?.has(owner.gid) === true && (owner.uid === 0 || !groups.has(0));
5219
+ } catch {
5220
+ return false;
5409
5221
  }
5410
- var TypeOverrides = require_type_overrides();
5411
- var EventEmitter = __require("events").EventEmitter;
5412
- var util = __require("util");
5413
- var ConnectionParameters = require_connection_parameters();
5414
- var NativeQuery = require_query2();
5415
- var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(() => {}, "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");
5416
- var Client = module.exports = function(config) {
5417
- EventEmitter.call(this);
5418
- config = config || {};
5419
- this._Promise = config.Promise || global.Promise;
5420
- this._types = new TypeOverrides(config.types);
5421
- this.native = new Native({
5422
- types: this._types
5423
- });
5424
- this._queryQueue = [];
5425
- this._ending = false;
5426
- this._connecting = false;
5427
- this._connected = false;
5428
- this._queryable = true;
5429
- const cp = this.connectionParameters = new ConnectionParameters(config);
5430
- if (config.nativeConnectionString)
5431
- cp.nativeConnectionString = config.nativeConnectionString;
5432
- this.user = cp.user;
5433
- Object.defineProperty(this, "password", {
5434
- configurable: true,
5435
- enumerable: false,
5436
- writable: true,
5437
- value: cp.password
5438
- });
5439
- this.database = cp.database;
5440
- this.host = cp.host;
5441
- this.port = cp.port;
5442
- this.namedQueries = {};
5443
- };
5444
- Client.Query = NativeQuery;
5445
- util.inherits(Client, EventEmitter);
5446
- Client.prototype._errorAllQueries = function(err) {
5447
- const enqueueError = (query) => {
5448
- process.nextTick(() => {
5449
- query.native = this.native;
5450
- query.handleError(err);
5451
- });
5452
- };
5453
- if (this._hasActiveQuery()) {
5454
- enqueueError(this._activeQuery);
5455
- this._activeQuery = null;
5456
- }
5457
- this._queryQueue.forEach(enqueueError);
5458
- this._queryQueue.length = 0;
5459
- };
5460
- Client.prototype._connect = function(cb) {
5461
- const self = this;
5462
- if (this._connecting) {
5463
- process.nextTick(() => cb(new Error("Client has already been connected. You cannot reuse a client.")));
5464
- return;
5465
- }
5466
- this._connecting = true;
5467
- this.connectionParameters.getLibpqConnectionString(function(err, conString) {
5468
- if (self.connectionParameters.nativeConnectionString)
5469
- conString = self.connectionParameters.nativeConnectionString;
5470
- if (err)
5471
- return cb(err);
5472
- self.native.connect(conString, function(err) {
5473
- if (err) {
5474
- self.native.end();
5475
- return cb(err);
5476
- }
5477
- self._connected = true;
5478
- self.native.on("error", function(err) {
5479
- self._queryable = false;
5480
- self._errorAllQueries(err);
5481
- self.emit("error", err);
5482
- });
5483
- self.native.on("notification", function(msg) {
5484
- self.emit("notification", {
5485
- channel: msg.relname,
5486
- payload: msg.extra
5487
- });
5488
- });
5489
- self.emit("connect");
5490
- self._pulseQueryQueue(true);
5491
- cb(null, this);
5492
- });
5493
- });
5222
+ }
5223
+ function parseIdentityNumber(result) {
5224
+ if (result.exitCode !== 0 || result.stdoutTruncated === true)
5225
+ return;
5226
+ const match = /^(0|[1-9]\d*)\r?\n?$/.exec(result.stdout);
5227
+ if (match === null)
5228
+ return;
5229
+ const value = Number(match[1]);
5230
+ return Number.isSafeInteger(value) ? value : undefined;
5231
+ }
5232
+ function parseIdentityGroups(result) {
5233
+ if (result.exitCode !== 0 || result.stdoutTruncated === true || !/^(0|[1-9]\d*)(?:[ \t]+(0|[1-9]\d*))*\r?\n?$/.test(result.stdout)) {
5234
+ return;
5235
+ }
5236
+ const values = result.stdout.trimEnd().split(/[ \t]+/).map(Number);
5237
+ if (values.some((value) => !Number.isSafeInteger(value)))
5238
+ return;
5239
+ const groups = new Set(values);
5240
+ return groups.size === values.length ? groups : undefined;
5241
+ }
5242
+ async function prepareBinariesForOwner(binaries, context, runner = runLocalCommand, options = {}) {
5243
+ const owner = context.owner;
5244
+ if (owner === undefined)
5245
+ return binaries;
5246
+ const probe = await context.runAsOwner(binaries.initdb, ["--version"]).catch(() => {
5247
+ return;
5248
+ });
5249
+ if (probe !== undefined && probe.exitCode === 0)
5250
+ return binaries;
5251
+ const sourceNativeDir = dirname(dirname(binaries.initdb));
5252
+ const copiedRuntimeDir = join(context.baseDir, "pg-runtime");
5253
+ const publisher = publisherIdentity();
5254
+ const progress = runtimeProgress(options);
5255
+ const sourceSnapshot = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
5256
+ await options.afterInitialSourceSnapshot?.();
5257
+ const copiedNativeDir = await findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options);
5258
+ return {
5259
+ pg_ctl: join(copiedNativeDir, "bin", "pg_ctl"),
5260
+ initdb: join(copiedNativeDir, "bin", "initdb"),
5261
+ postgres: join(copiedNativeDir, "bin", "postgres")
5494
5262
  };
5495
- Client.prototype.connect = function(callback) {
5496
- if (callback) {
5497
- this._connect(callback);
5263
+ }
5264
+ async function cleanupAbandonedRuntimeStages(baseDir, abandonedOwnerTokens = new Set) {
5265
+ if (abandonedOwnerTokens.size === 0)
5266
+ return;
5267
+ const copiedRuntimeDir = join(baseDir, "pg-runtime");
5268
+ let entries;
5269
+ try {
5270
+ entries = await readdir(copiedRuntimeDir);
5271
+ } catch (error) {
5272
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
5273
+ if (code === "ENOENT")
5498
5274
  return;
5275
+ throw error;
5276
+ }
5277
+ for (const entry of entries) {
5278
+ if (!entry.startsWith(".native-staged-"))
5279
+ continue;
5280
+ const stage = join(copiedRuntimeDir, entry);
5281
+ let ownerToken;
5282
+ try {
5283
+ ownerToken = await readSmallFile(join(stage, STAGE_OWNER_FILE));
5284
+ } catch {
5285
+ continue;
5499
5286
  }
5500
- return new this._Promise((resolve, reject) => {
5501
- this._connect((error) => {
5502
- if (error) {
5503
- reject(error);
5504
- } else {
5505
- resolve(this);
5506
- }
5507
- });
5508
- });
5509
- };
5510
- Client.prototype.query = function(config, values, callback) {
5511
- let query;
5512
- let result;
5513
- let readTimeout;
5514
- let readTimeoutTimer;
5515
- let queryCallback;
5516
- if (config === null || config === undefined) {
5517
- throw new TypeError("Client was passed a null or undefined query");
5518
- } else if (typeof config.submit === "function") {
5519
- readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
5520
- result = query = config;
5521
- if (typeof values === "function") {
5522
- config.callback = values;
5523
- }
5524
- } else {
5525
- readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
5526
- query = new NativeQuery(config, values, callback);
5527
- if (!query.callback) {
5528
- let resolveOut, rejectOut;
5529
- result = new this._Promise((resolve, reject) => {
5530
- resolveOut = resolve;
5531
- rejectOut = reject;
5532
- }).catch((err) => {
5533
- Error.captureStackTrace(err);
5534
- throw err;
5535
- });
5536
- query.callback = (err, res) => err ? rejectOut(err) : resolveOut(res);
5287
+ if (abandonedOwnerTokens.has(ownerToken))
5288
+ await rm(stage, { recursive: true, force: true });
5289
+ }
5290
+ }
5291
+ async function findOrCreateRuntimeGeneration(sourceNativeDir, sourceSnapshot, copiedRuntimeDir, publisher, runner, progress, options) {
5292
+ await mkdir(copiedRuntimeDir, { recursive: true, mode: 493 });
5293
+ const runtimeStat = await lstat(copiedRuntimeDir);
5294
+ if (!runtimeStat.isDirectory() || runtimeStat.isSymbolicLink()) {
5295
+ throw new Error(`Embedded Postgres runtime parent must be a real directory: ${copiedRuntimeDir}`);
5296
+ }
5297
+ await chown(copiedRuntimeDir, publisher.uid, publisher.gid);
5298
+ await chmod(copiedRuntimeDir, 493);
5299
+ const generationNativeDir = join(copiedRuntimeDir, `native-${sourceSnapshot.sourceIdentity}`);
5300
+ const existing = await lstatOrUndefined(generationNativeDir);
5301
+ if (existing !== undefined) {
5302
+ try {
5303
+ if (await snapshotSealedRuntime(generationNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5304
+ throw new Error("sealed identity mismatch");
5537
5305
  }
5306
+ await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while selecting an existing generation.");
5307
+ return generationNativeDir;
5308
+ } catch (error) {
5309
+ if (error instanceof SourceRuntimeChangedError)
5310
+ throw error;
5311
+ const detail = error instanceof Error ? error.message : String(error);
5312
+ throw new Error(`Embedded Postgres runtime generation is corrupt and cannot be replaced while it may be in use (${generationNativeDir}): ${detail}`);
5538
5313
  }
5539
- if (readTimeout) {
5540
- queryCallback = query.callback || (() => {});
5541
- readTimeoutTimer = setTimeout(() => {
5542
- const error = new Error("Query read timeout");
5543
- process.nextTick(() => {
5544
- query.handleError(error, this.connection);
5545
- });
5546
- queryCallback(error);
5547
- query.callback = () => {};
5548
- const index = this._queryQueue.indexOf(query);
5549
- if (index > -1) {
5550
- this._queryQueue.splice(index, 1);
5314
+ }
5315
+ const stageOwner = options.publicationLease?.ownerToken ?? `unmanaged-${process.pid}-${crypto.randomUUID()}`;
5316
+ const stagedRoot = join(copiedRuntimeDir, `.native-staged-${process.pid}-${crypto.randomUUID()}`);
5317
+ const stagedNativeDir = join(stagedRoot, STAGE_PAYLOAD_DIR);
5318
+ await mkdir(stagedRoot, { mode: 448 });
5319
+ await writeFile(join(stagedRoot, STAGE_OWNER_FILE), stageOwner, { mode: 384, flag: "wx" });
5320
+ try {
5321
+ await progress();
5322
+ await cp(sourceNativeDir, stagedNativeDir, { recursive: true, verbatimSymlinks: true });
5323
+ const copiedSnapshot = await snapshotSourceRuntime(stagedNativeDir, publisher, progress);
5324
+ if (copiedSnapshot.sourceIdentity !== sourceSnapshot.sourceIdentity) {
5325
+ throw new Error("Copied embedded Postgres runtime did not match its source package.");
5326
+ }
5327
+ await sealRuntimeForPublisher(stagedNativeDir, publisher, runner, progress);
5328
+ if (await snapshotSealedRuntime(stagedNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5329
+ throw new Error("Sealed embedded Postgres runtime did not match its source package.");
5330
+ }
5331
+ await options.beforePublish?.(stagedNativeDir);
5332
+ if (await snapshotSealedRuntime(stagedNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5333
+ throw new Error("Embedded Postgres runtime changed after sealed validation and before publication.");
5334
+ }
5335
+ await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed while preparing a generation.");
5336
+ assertPublicationLease(options, "Embedded Postgres runtime publication lost its setup lease.");
5337
+ await progress();
5338
+ await rename(stagedNativeDir, generationNativeDir);
5339
+ await options.afterPublish?.(generationNativeDir);
5340
+ if (await snapshotSealedRuntime(generationNativeDir, progress) !== sourceSnapshot.sealedIdentity) {
5341
+ throw new Error("Embedded Postgres published runtime changed during publication.");
5342
+ }
5343
+ await assertSourceSnapshotUnchanged(sourceNativeDir, sourceSnapshot, publisher, progress, "Embedded Postgres source package changed during publication.");
5344
+ await options.afterPublishValidation?.(generationNativeDir);
5345
+ assertPublicationLease(options, "Embedded Postgres runtime lost its setup lease after publication.");
5346
+ return generationNativeDir;
5347
+ } finally {
5348
+ await makeUnpublishedStageRemovable(stagedNativeDir).catch(() => {});
5349
+ await rm(stagedRoot, { recursive: true, force: true });
5350
+ }
5351
+ }
5352
+ async function assertSourceSnapshotUnchanged(sourceNativeDir, expected, publisher, progress, message) {
5353
+ const current = await snapshotSourceRuntime(sourceNativeDir, publisher, progress);
5354
+ if (current.sourceIdentity !== expected.sourceIdentity || current.sealedIdentity !== expected.sealedIdentity) {
5355
+ throw new SourceRuntimeChangedError(message);
5356
+ }
5357
+ }
5358
+ function assertPublicationLease(options, message) {
5359
+ if (options.publicationLease !== undefined && !options.publicationLease.refresh())
5360
+ throw new Error(message);
5361
+ }
5362
+ function runtimeProgress(options) {
5363
+ let operations = 0;
5364
+ const yieldToEventLoop = options.yieldToEventLoop ?? (() => new Promise((resolve) => setImmediate(resolve)));
5365
+ return async () => {
5366
+ if (operations % TRAVERSAL_OPERATIONS_PER_YIELD === 0) {
5367
+ if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
5368
+ throw new Error("Embedded Postgres runtime publication lost its setup lease.");
5369
+ }
5370
+ if (operations > 0) {
5371
+ await yieldToEventLoop();
5372
+ if (options.publicationLease !== undefined && !options.publicationLease.refresh()) {
5373
+ throw new Error("Embedded Postgres runtime publication lost its setup lease.");
5551
5374
  }
5552
- this._pulseQueryQueue();
5553
- }, readTimeout);
5554
- query.callback = (err, res) => {
5555
- clearTimeout(readTimeoutTimer);
5556
- queryCallback(err, res);
5557
- };
5375
+ }
5558
5376
  }
5559
- if (!this._queryable) {
5560
- query.native = this.native;
5561
- process.nextTick(() => {
5562
- query.handleError(new Error("Client has encountered a connection error and is not queryable"));
5563
- });
5564
- return result;
5377
+ operations += 1;
5378
+ };
5379
+ }
5380
+ async function snapshotSourceRuntime(root, publisher, progress) {
5381
+ const rootStat = await lstat(root);
5382
+ assertRuntimeRoot(root, rootStat);
5383
+ const rootRealPath = await realpath(root);
5384
+ const sourceHash = createHash3("sha256");
5385
+ const sealedHash = createHash3("sha256");
5386
+ await hashSourceEntry(sourceHash, sealedHash, root, ".", rootRealPath, publisher, progress);
5387
+ return { sourceIdentity: sourceHash.digest("hex"), sealedIdentity: sealedHash.digest("hex") };
5388
+ }
5389
+ async function hashSourceEntry(sourceHash, sealedHash, path, relativePath, rootRealPath, publisher, progress) {
5390
+ await progress();
5391
+ const stat = await lstat(path);
5392
+ if (stat.isSymbolicLink()) {
5393
+ const target = await validatedLinkTarget(path, relativePath, rootRealPath);
5394
+ hashField(sourceHash, "link", relativePath, target);
5395
+ hashField(sealedHash, "link", relativePath, String(publisher.uid), String(publisher.gid), target);
5396
+ return;
5397
+ }
5398
+ if (stat.isDirectory()) {
5399
+ hashField(sourceHash, "directory", relativePath, String(stat.mode & 511));
5400
+ hashField(sealedHash, "directory", relativePath, String(sealedDirectoryMode(relativePath === ".")), String(publisher.uid), String(publisher.gid));
5401
+ for (const entry of (await readdir(path)).sort()) {
5402
+ await hashSourceEntry(sourceHash, sealedHash, join(path, entry), relativePath === "." ? entry : join(relativePath, entry), rootRealPath, publisher, progress);
5565
5403
  }
5566
- if (this._ending) {
5567
- query.native = this.native;
5568
- process.nextTick(() => {
5569
- query.handleError(new Error("Client was closed and is not queryable"));
5570
- });
5571
- return result;
5404
+ return;
5405
+ }
5406
+ if (stat.isFile()) {
5407
+ hashField(sourceHash, "file", relativePath, String(stat.mode & 511), String(stat.size));
5408
+ hashField(sealedHash, "file", relativePath, String(sealedFileMode(stat.mode)), String(publisher.uid), String(publisher.gid), String(stat.size));
5409
+ await hashFileInto([sourceHash, sealedHash], path, progress);
5410
+ return;
5411
+ }
5412
+ throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
5413
+ }
5414
+ async function snapshotSealedRuntime(root, progress) {
5415
+ const rootStat = await lstat(root);
5416
+ assertRuntimeRoot(root, rootStat);
5417
+ const rootRealPath = await realpath(root);
5418
+ const hash = createHash3("sha256");
5419
+ await hashSealedEntry(hash, root, ".", rootRealPath, progress);
5420
+ return hash.digest("hex");
5421
+ }
5422
+ async function hashSealedEntry(hash, path, relativePath, rootRealPath, progress) {
5423
+ await progress();
5424
+ const stat = await lstat(path);
5425
+ if (stat.isSymbolicLink()) {
5426
+ const target = await validatedLinkTarget(path, relativePath, rootRealPath);
5427
+ hashField(hash, "link", relativePath, String(stat.uid), String(stat.gid), target);
5428
+ return;
5429
+ }
5430
+ if (stat.isDirectory()) {
5431
+ hashField(hash, "directory", relativePath, String(stat.mode & 511), String(stat.uid), String(stat.gid));
5432
+ for (const entry of (await readdir(path)).sort()) {
5433
+ await hashSealedEntry(hash, join(path, entry), relativePath === "." ? entry : join(relativePath, entry), rootRealPath, progress);
5572
5434
  }
5573
- if (this._queryQueue.length > 0) {
5574
- queryQueueLengthDeprecationNotice();
5435
+ return;
5436
+ }
5437
+ if (stat.isFile()) {
5438
+ hashField(hash, "file", relativePath, String(stat.mode & 511), String(stat.uid), String(stat.gid), String(stat.size));
5439
+ await hashFileInto([hash], path, progress);
5440
+ return;
5441
+ }
5442
+ throw new Error(`Embedded Postgres runtime contains an unsupported entry: ${relativePath}`);
5443
+ }
5444
+ async function validatedLinkTarget(path, relativePath, rootRealPath) {
5445
+ const target = await readlink(path);
5446
+ if (isAbsolute(target))
5447
+ throw new Error(`Embedded Postgres runtime contains an absolute link: ${relativePath}`);
5448
+ const resolvedTarget = await realpath(path);
5449
+ const targetFromRoot = relative(rootRealPath, resolvedTarget);
5450
+ if (targetFromRoot === ".." || targetFromRoot.startsWith(`..${sep}`) || isAbsolute(targetFromRoot)) {
5451
+ throw new Error(`Embedded Postgres runtime link escapes its tree: ${relativePath}`);
5452
+ }
5453
+ return target;
5454
+ }
5455
+ async function hashFileInto(hashes, path, progress) {
5456
+ const handle = await open(path, "r");
5457
+ const buffer = Buffer.allocUnsafe(HASH_CHUNK_BYTES);
5458
+ try {
5459
+ for (;; ) {
5460
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
5461
+ if (bytesRead === 0)
5462
+ return;
5463
+ const chunk = buffer.subarray(0, bytesRead);
5464
+ for (const hash of hashes)
5465
+ hash.update(chunk);
5466
+ await progress();
5575
5467
  }
5576
- this._queryQueue.push(query);
5577
- this._pulseQueryQueue();
5578
- return result;
5468
+ } finally {
5469
+ await handle.close();
5470
+ }
5471
+ }
5472
+ async function sealRuntimeForPublisher(runtimeDir, publisher, runner, progress) {
5473
+ const result = await runner("chown", ["-R", `${publisher.uid}:${publisher.gid}`, runtimeDir]);
5474
+ if (result.exitCode !== 0) {
5475
+ throw new Error(`Could not seal the copied embedded Postgres runtime: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`}`);
5476
+ }
5477
+ await sealRuntimeModes(runtimeDir, progress, true);
5478
+ }
5479
+ async function sealRuntimeModes(path, progress, isRoot = false) {
5480
+ await progress();
5481
+ const stat = await lstat(path);
5482
+ if (stat.isSymbolicLink())
5483
+ return;
5484
+ if (stat.isDirectory()) {
5485
+ await chmod(path, 448);
5486
+ for (const entry of await readdir(path))
5487
+ await sealRuntimeModes(join(path, entry), progress);
5488
+ await chmod(path, sealedDirectoryMode(isRoot));
5489
+ return;
5490
+ }
5491
+ if (stat.isFile()) {
5492
+ await chmod(path, sealedFileMode(stat.mode));
5493
+ return;
5494
+ }
5495
+ throw new Error(`Embedded Postgres runtime contains an unsupported entry while sealing: ${path}`);
5496
+ }
5497
+ async function makeUnpublishedStageRemovable(path) {
5498
+ const stat = await lstatOrUndefined(path);
5499
+ if (stat === undefined || stat.isSymbolicLink())
5500
+ return;
5501
+ if (stat.isDirectory()) {
5502
+ await chmod(path, 448);
5503
+ for (const entry of await readdir(path))
5504
+ await makeUnpublishedStageRemovable(join(path, entry));
5505
+ } else if (stat.isFile()) {
5506
+ await chmod(path, 384);
5507
+ }
5508
+ }
5509
+ function sealedDirectoryMode(isRoot) {
5510
+ if (process.platform === "win32")
5511
+ return 292;
5512
+ return isRoot ? 493 : 365;
5513
+ }
5514
+ function sealedFileMode(mode) {
5515
+ if (process.platform === "win32")
5516
+ return 292;
5517
+ return (mode & 73) === 0 ? 292 : 365;
5518
+ }
5519
+ function publisherIdentity() {
5520
+ return { uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0 };
5521
+ }
5522
+ function assertRuntimeRoot(root, stat) {
5523
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
5524
+ throw new Error(`Embedded Postgres runtime must be a real directory: ${root}`);
5525
+ }
5526
+ }
5527
+ async function lstatOrUndefined(path) {
5528
+ try {
5529
+ return await lstat(path);
5530
+ } catch (error) {
5531
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
5532
+ if (code === "ENOENT")
5533
+ return;
5534
+ throw error;
5535
+ }
5536
+ }
5537
+ async function readSmallFile(path) {
5538
+ const handle = await open(path, "r");
5539
+ try {
5540
+ const stat = await handle.stat();
5541
+ if (stat.size > 4096)
5542
+ throw new Error(`Unexpectedly large runtime stage owner marker: ${path}`);
5543
+ return (await handle.readFile("utf8")).trim();
5544
+ } finally {
5545
+ await handle.close();
5546
+ }
5547
+ }
5548
+ function hashField(hash, ...values) {
5549
+ for (const value of values)
5550
+ hash.update(`${Buffer.byteLength(value)}:${value}`);
5551
+ }
5552
+ async function lookupOwner(runner, name) {
5553
+ const uid = await lookupId(runner, ["-u", name]);
5554
+ const gid = await lookupId(runner, ["-g", name]);
5555
+ if (uid === undefined || gid === undefined || uid === 0)
5556
+ return;
5557
+ return { uid, gid, name };
5558
+ }
5559
+ async function lookupId(runner, args) {
5560
+ try {
5561
+ const value = parseIdentityNumber(await runner("id", args));
5562
+ return value !== undefined && value > 0 ? value : undefined;
5563
+ } catch {
5564
+ return;
5565
+ }
5566
+ }
5567
+ function shellCommand(command, args) {
5568
+ return [command, ...args].map((part) => `'${part.replaceAll("'", "'\\''")}'`).join(" ");
5569
+ }
5570
+ var ROOT_EMBEDDED_BASE_DIR = "/var/lib/atomic-postgres", OWNER_CANDIDATES, STAGE_OWNER_FILE = ".atomic-stage-owner", STAGE_PAYLOAD_DIR = "runtime", TRAVERSAL_OPERATIONS_PER_YIELD = 16, HASH_CHUNK_BYTES, SourceRuntimeChangedError;
5571
+ var init_dbos_embedded_postgres_root = __esm(() => {
5572
+ init_local_command();
5573
+ OWNER_CANDIDATES = ["postgres", "nobody", "daemon"];
5574
+ HASH_CHUNK_BYTES = 64 * 1024;
5575
+ SourceRuntimeChangedError = class SourceRuntimeChangedError extends Error {
5579
5576
  };
5580
- Client.prototype.end = function(cb) {
5581
- const self = this;
5582
- this._ending = true;
5583
- if (this._connecting && !this._connected) {
5584
- this.once("connect", () => {
5585
- this.end(() => {});
5586
- });
5587
- }
5588
- let result;
5589
- if (!cb) {
5590
- result = new this._Promise(function(resolve, reject) {
5591
- cb = (err) => err ? reject(err) : resolve();
5592
- });
5577
+ });
5578
+
5579
+ // dist/builtin/workflows/src/durable/dbos-embedded-postgres-targets.ts
5580
+ import { existsSync } from "node:fs";
5581
+ function detectLinuxLibc(signals) {
5582
+ if (signals.glibcVersionRuntime !== undefined && signals.glibcVersionRuntime.length > 0)
5583
+ return "glibc";
5584
+ if (signals.muslLoaderExists)
5585
+ return "musl";
5586
+ return "unknown";
5587
+ }
5588
+ function detectCurrentHostLibc(platform = process.platform, arch = process.arch) {
5589
+ if (platform !== "linux")
5590
+ return;
5591
+ const report = process.report?.getReport();
5592
+ return detectLinuxLibc({
5593
+ glibcVersionRuntime: report?.header?.glibcVersionRuntime,
5594
+ muslLoaderExists: existsSync(`/lib/ld-musl-${arch === "x64" ? "x86_64" : arch === "arm64" ? "aarch64" : arch}.so.1`)
5595
+ });
5596
+ }
5597
+ function resolveEmbeddedPostgresTarget(host) {
5598
+ if (host.platform === "linux" && host.libc === "musl") {
5599
+ if (host.arch !== "x64" && host.arch !== "arm64") {
5600
+ throw new Error(`Embedded Postgres does not support Linux musl architecture ${host.arch}.`);
5593
5601
  }
5594
- this.native.end(function() {
5595
- self._connected = false;
5596
- self._errorAllQueries(new Error("Connection terminated"));
5597
- process.nextTick(() => {
5598
- self.emit("end");
5599
- if (cb)
5600
- cb();
5601
- });
5602
+ const id = `linux-${host.arch}-musl`;
5603
+ return {
5604
+ id,
5605
+ bundledDirectory: id,
5606
+ nativeLeafPackageName: `@bastani/atomic-natives-linux-${host.arch}-musl`,
5607
+ emulated: false
5608
+ };
5609
+ }
5610
+ if (host.platform === "win32" && host.arch === "arm64") {
5611
+ return {
5612
+ id: "windows-arm64",
5613
+ bundledDirectory: "windows-arm64",
5614
+ nativeLeafPackageName: "@bastani/atomic-natives-win32-arm64-msvc",
5615
+ emulated: true,
5616
+ reason: "Windows ARM64 runs the Windows x64 PostgreSQL runtime through Windows 11 x64 emulation."
5617
+ };
5618
+ }
5619
+ const platform = host.platform === "win32" ? "windows" : host.platform;
5620
+ const id = `${platform}-${host.arch}`;
5621
+ const nativeSuffix = host.arch === "x64" || host.arch === "arm64" ? host.platform === "linux" ? `linux-${host.arch}-gnu` : host.platform === "darwin" ? id : host.platform === "win32" ? `win32-${host.arch}-msvc` : undefined : undefined;
5622
+ return {
5623
+ id,
5624
+ bundledDirectory: id,
5625
+ nativeLeafPackageName: nativeSuffix === undefined ? undefined : `@bastani/atomic-natives-${nativeSuffix}`,
5626
+ npmPackageName: `@embedded-postgres/${id}`,
5627
+ emulated: false
5628
+ };
5629
+ }
5630
+ var init_dbos_embedded_postgres_targets = () => {};
5631
+
5632
+ // dist/builtin/workflows/src/durable/dbos-postgres-health.ts
5633
+ class PostgresHealth {
5634
+ operations;
5635
+ pending;
5636
+ timer;
5637
+ stopped = false;
5638
+ available;
5639
+ attempts = 0;
5640
+ failure;
5641
+ revision = 0;
5642
+ listeners = new Set;
5643
+ constructor(operations) {
5644
+ this.operations = operations;
5645
+ }
5646
+ get lastFailure() {
5647
+ return this.failure;
5648
+ }
5649
+ subscribe(listener) {
5650
+ this.listeners.add(listener);
5651
+ return () => this.listeners.delete(listener);
5652
+ }
5653
+ invalidate() {
5654
+ this.revision++;
5655
+ this.available = undefined;
5656
+ for (const listener of this.listeners)
5657
+ listener();
5658
+ }
5659
+ async validate(client) {
5660
+ try {
5661
+ if (this.stopped)
5662
+ throw new DbosDependencyError;
5663
+ await this.operations.validate?.(client);
5664
+ } catch (error) {
5665
+ this.failure = error instanceof Error ? error : new Error(String(error));
5666
+ this.invalidate();
5667
+ throw error;
5668
+ }
5669
+ }
5670
+ check() {
5671
+ if (this.stopped)
5672
+ return Promise.reject(new Error("Managed Postgres health observer is stopped."));
5673
+ this.pending ??= this.refresh().finally(() => {
5674
+ this.pending = undefined;
5602
5675
  });
5603
- return result;
5604
- };
5605
- Client.prototype._hasActiveQuery = function() {
5606
- return this._activeQuery && this._activeQuery.state !== "error" && this._activeQuery.state !== "end";
5607
- };
5608
- Client.prototype._pulseQueryQueue = function(initialConnection) {
5609
- if (!this._connected) {
5676
+ return this.pending;
5677
+ }
5678
+ start() {
5679
+ if (this.stopped || this.timer !== undefined)
5610
5680
  return;
5611
- }
5612
- if (this._hasActiveQuery()) {
5681
+ this.timer = setTimeout(() => {
5682
+ this.timer = undefined;
5683
+ this.check().catch(() => {}).finally(() => this.start());
5684
+ }, HEALTH_INTERVAL_MS);
5685
+ this.timer.unref();
5686
+ }
5687
+ async stop() {
5688
+ this.stopped = true;
5689
+ if (this.timer !== undefined)
5690
+ clearTimeout(this.timer);
5691
+ this.timer = undefined;
5692
+ await this.pending?.catch(() => {});
5693
+ this.listeners.clear();
5694
+ }
5695
+ async probe() {
5696
+ const revision = this.revision;
5697
+ const identity = await this.operations.probe();
5698
+ if (revision !== this.revision)
5613
5699
  return;
5614
- }
5615
- const query = this._queryQueue.shift();
5616
- if (!query) {
5617
- if (!initialConnection) {
5618
- this.emit("drain");
5619
- }
5700
+ if (this.stopped)
5701
+ throw new Error("Managed Postgres health observer is stopped.");
5702
+ if (!identity)
5620
5703
  return;
5621
- }
5622
- this._activeQuery = query;
5623
- query.submit(this);
5624
- const self = this;
5625
- query.once("_done", function() {
5626
- self._pulseQueryQueue();
5627
- });
5628
- };
5629
- Client.prototype.cancel = function(query) {
5630
- if (this._activeQuery === query) {
5631
- this.native.cancel(function() {});
5632
- } else if (this._queryQueue.indexOf(query) !== -1) {
5633
- this._queryQueue.splice(this._queryQueue.indexOf(query), 1);
5634
- }
5635
- };
5636
- Client.prototype.ref = function() {};
5637
- Client.prototype.unref = function() {};
5638
- Client.prototype.setTypeParser = function(oid, format, parseFn) {
5639
- return this._types.setTypeParser(oid, format, parseFn);
5640
- };
5641
- Client.prototype.getTypeParser = function(oid, format) {
5642
- return this._types.getTypeParser(oid, format);
5643
- };
5644
- Client.prototype.isConnected = function() {
5645
- return this._connected;
5646
- };
5647
- Client.prototype.getTransactionStatus = function() {
5648
- return this.native.getTransactionStatus();
5649
- };
5650
- });
5651
-
5652
- // ../../node_modules/pg/lib/index.js
5653
- var require_lib2 = __commonJS(function(exports, module) {
5654
- var Client = require_client();
5655
- var defaults = require_defaults();
5656
- var Connection = require_connection();
5657
- var Result = require_result();
5658
- var utils = require_utils();
5659
- var Pool = require_pg_pool();
5660
- var TypeOverrides = require_type_overrides();
5661
- var { DatabaseError } = require_dist();
5662
- var { escapeIdentifier, escapeLiteral } = require_utils();
5663
- var poolFactory = (Client) => {
5664
- return class BoundPool extends Pool {
5665
- constructor(options) {
5666
- super(options, Client);
5667
- }
5668
- };
5669
- };
5670
- var PG = function(clientConstructor) {
5671
- this.defaults = defaults;
5672
- this.Client = clientConstructor;
5673
- this.Query = this.Client.Query;
5674
- this.Pool = poolFactory(this.Client);
5675
- this._pools = [];
5676
- this.Connection = Connection;
5677
- this.types = require_pg_types();
5678
- this.DatabaseError = DatabaseError;
5679
- this.TypeOverrides = TypeOverrides;
5680
- this.escapeIdentifier = escapeIdentifier;
5681
- this.escapeLiteral = escapeLiteral;
5682
- this.Result = Result;
5683
- this.utils = utils;
5684
- };
5685
- var clientConstructor = Client;
5686
- var forceNative = false;
5687
- try {
5688
- forceNative = !!process.env.NODE_PG_FORCE_NATIVE;
5689
- } catch {}
5690
- if (forceNative) {
5691
- clientConstructor = require_client2();
5704
+ if (this.available && this.available.identity !== identity.identity)
5705
+ this.invalidate();
5706
+ this.available = identity;
5707
+ this.attempts = 0;
5708
+ return identity.url;
5692
5709
  }
5693
- module.exports = new PG(clientConstructor);
5694
- Object.defineProperty(module.exports, "native", {
5695
- configurable: true,
5696
- enumerable: false,
5697
- get() {
5698
- let native = null;
5710
+ async refresh() {
5711
+ try {
5712
+ const ready = await this.probe();
5713
+ if (ready !== undefined)
5714
+ return ready;
5715
+ } catch (error) {
5716
+ this.failure = error instanceof Error ? error : new Error(String(error));
5717
+ if (!(error instanceof Error && ("code" in error) && error.code === "53300"))
5718
+ this.invalidate();
5719
+ throw error;
5720
+ }
5721
+ if (this.attempts === 0)
5722
+ this.failure = new DbosDependencyError("Managed PostgreSQL failed its live health check.");
5723
+ this.invalidate();
5724
+ while (!this.stopped && this.attempts < RECOVERY_ATTEMPTS) {
5725
+ const attempt = this.attempts++;
5726
+ if (attempt > 0)
5727
+ await (this.operations.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(250 * 2 ** (attempt - 1));
5728
+ if (this.stopped)
5729
+ break;
5699
5730
  try {
5700
- native = new PG(require_client2());
5701
- } catch (err) {
5702
- if (err.code !== "MODULE_NOT_FOUND") {
5703
- throw err;
5704
- }
5731
+ await this.operations.recover();
5732
+ const ready = await this.probe();
5733
+ if (ready !== undefined)
5734
+ return ready;
5735
+ } catch (error) {
5736
+ this.failure = error instanceof Error ? error : new Error(String(error));
5705
5737
  }
5706
- Object.defineProperty(module.exports, "native", {
5707
- value: native
5708
- });
5709
- return native;
5710
5738
  }
5711
- });
5712
- });
5713
-
5714
- // ../../node_modules/pg/esm/index.mjs
5715
- var import_lib, Client, Pool, Connection, types, Query, DatabaseError, escapeIdentifier, escapeLiteral, Result, TypeOverrides, defaults;
5716
- var init_esm = __esm(() => {
5717
- import_lib = __toESM(require_lib2(), 1);
5718
- Client = import_lib.default.Client;
5719
- Pool = import_lib.default.Pool;
5720
- Connection = import_lib.default.Connection;
5721
- types = import_lib.default.types;
5722
- Query = import_lib.default.Query;
5723
- DatabaseError = import_lib.default.DatabaseError;
5724
- escapeIdentifier = import_lib.default.escapeIdentifier;
5725
- escapeLiteral = import_lib.default.escapeLiteral;
5726
- Result = import_lib.default.Result;
5727
- TypeOverrides = import_lib.default.TypeOverrides;
5728
- defaults = import_lib.default.defaults;
5739
+ throw new DbosDependencyError("Managed Postgres is unavailable after bounded recovery. Preserve its data and ownership records.");
5740
+ }
5741
+ }
5742
+ var HEALTH_INTERVAL_MS = 5000, RECOVERY_ATTEMPTS = 3;
5743
+ var init_dbos_postgres_health = __esm(() => {
5744
+ init_dbos_admission();
5729
5745
  });
5730
5746
 
5731
5747
  // dist/builtin/workflows/src/durable/dbos-postgres-ownership.ts
@@ -6913,6 +6929,103 @@ function shutdownResolvedLocalDbos() {
6913
6929
  });
6914
6930
  return embeddedShutdown;
6915
6931
  }
6932
+ function postgresReadinessPort(value) {
6933
+ const port = Number(value);
6934
+ const validFormat = typeof value !== "string" || /^\d+$/.test(value);
6935
+ const validPort = Number.isInteger(port) && port >= 1 && port <= 65535;
6936
+ if (!validFormat || !validPort)
6937
+ throw new Error("PostgreSQL readiness port (PGPORT) must be an integer between 1 and 65535.");
6938
+ return port;
6939
+ }
6940
+ function dockerFallbackEndpoint() {
6941
+ return {
6942
+ host: process.env.PGHOST || "localhost",
6943
+ port: postgresReadinessPort(process.env.PGPORT || "5432"),
6944
+ user: process.env.PGUSER || "postgres",
6945
+ password: process.env.PGPASSWORD || "dbos"
6946
+ };
6947
+ }
6948
+ async function waitForPostgresProtocolReadiness(options) {
6949
+ postgresReadinessPort(options.port);
6950
+ const attempts = options.attempts ?? DOCKER_READY_ATTEMPTS;
6951
+ const delayMs = options.delayMs ?? DOCKER_READY_DELAY_MS;
6952
+ const wait = options.wait ?? delay;
6953
+ const isReady = options.isReady ?? dockerPostgresQueryReady;
6954
+ const deadline = performance.now() + attempts * delayMs;
6955
+ for (let attempt = 0;attempt < attempts && performance.now() < deadline; attempt += 1) {
6956
+ try {
6957
+ if (await isReady(options.host, options.port))
6958
+ return;
6959
+ } catch (error) {
6960
+ if (!isTransientStartupError(readStartupFailure(error)))
6961
+ throw error;
6962
+ }
6963
+ if (attempt + 1 < attempts && performance.now() < deadline)
6964
+ await wait(delayMs);
6965
+ }
6966
+ throw new Error(`The DBOS Postgres container started but did not become ready within ${attempts * delayMs / 1000} seconds.`);
6967
+ }
6968
+ function readStartupFailure(value) {
6969
+ if (!(value instanceof Error))
6970
+ return { message: String(value) };
6971
+ const cause = value.cause;
6972
+ return {
6973
+ message: value.message,
6974
+ code: "code" in value && typeof value.code === "string" ? value.code : undefined,
6975
+ cause: cause === undefined ? undefined : cause instanceof Error ? cause : String(cause),
6976
+ source: value
6977
+ };
6978
+ }
6979
+ function isTransientStartupError(error) {
6980
+ const seen = new Set;
6981
+ let current = error;
6982
+ while (current !== undefined) {
6983
+ const { code, message, source, cause } = current;
6984
+ if (typeof code === "string" && TRANSIENT_STARTUP_CODES.has(code))
6985
+ return true;
6986
+ if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code))
6987
+ return false;
6988
+ if (/\b(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE)\b|^connection (?:refused|terminated(?: unexpectedly| due to connection timeout)?)(?:\s|$)|^connect(?:ion)? (?:timeout|timed out)(?:\s|$)|^timeout (?:expired|exceeded when trying to connect)$/i.test(message))
6989
+ return true;
6990
+ if (source === undefined || seen.has(source))
6991
+ return false;
6992
+ seen.add(source);
6993
+ current = cause === undefined ? undefined : readStartupFailure(cause);
6994
+ }
6995
+ return false;
6996
+ }
6997
+ async function dockerPostgresQueryReady(host, port) {
6998
+ const client = new Client({
6999
+ connectionString: defaultPostgresUrl("postgres", host, String(port)),
7000
+ connectionTimeoutMillis: DOCKER_READY_QUERY_TIMEOUT_MS,
7001
+ query_timeout: DOCKER_READY_QUERY_TIMEOUT_MS,
7002
+ statement_timeout: DOCKER_READY_QUERY_TIMEOUT_MS
7003
+ });
7004
+ client.on("error", () => {});
7005
+ let timer;
7006
+ try {
7007
+ await Promise.race([
7008
+ (async () => {
7009
+ await client.connect();
7010
+ await client.query("SELECT 1");
7011
+ })(),
7012
+ new Promise((_, reject) => {
7013
+ timer = setTimeout(() => reject(new Error("timeout expired")), DOCKER_READY_QUERY_TIMEOUT_MS);
7014
+ })
7015
+ ]);
7016
+ return true;
7017
+ } catch (error) {
7018
+ if (isTransientStartupError(readStartupFailure(error)))
7019
+ return false;
7020
+ throw error;
7021
+ } finally {
7022
+ if (timer !== undefined)
7023
+ clearTimeout(timer);
7024
+ client.end().catch(() => {
7025
+ return;
7026
+ });
7027
+ }
7028
+ }
6916
7029
  async function resolve() {
6917
7030
  const explicit = process.env.DBOS_SYSTEM_DATABASE_URL?.trim();
6918
7031
  if (explicit)
@@ -6938,6 +7051,7 @@ async function resolve() {
6938
7051
  }
6939
7052
  }
6940
7053
  async function ensureDockerDbosPostgres() {
7054
+ const endpoint = dockerFallbackEndpoint();
6941
7055
  const docker = await runLocalCommand("docker", ["version", "--format", "{{.Server.Version}}"]).catch(() => {
6942
7056
  return;
6943
7057
  });
@@ -6960,18 +7074,13 @@ async function ensureDockerDbosPostgres() {
6960
7074
  "-e",
6961
7075
  "PGDATA=/var/lib/postgresql/data",
6962
7076
  "-p",
6963
- "127.0.0.1:5432:5432",
7077
+ `127.0.0.1:${endpoint.port}:5432`,
6964
7078
  "-v",
6965
7079
  "dbos-db-data:/var/lib/postgresql/data",
6966
7080
  DOCKER_IMAGE
6967
7081
  ]);
6968
7082
  }
6969
- for (let attempt = 0;attempt < DOCKER_READY_ATTEMPTS; attempt += 1) {
6970
- if (await tcpReachable("127.0.0.1", 5432))
6971
- return;
6972
- await delay(DOCKER_READY_DELAY_MS);
6973
- }
6974
- throw new Error("The DBOS Postgres container started but did not become ready within 30 seconds.");
7083
+ await waitForPostgresProtocolReadiness({ host: endpoint.host, port: endpoint.port });
6975
7084
  }
6976
7085
  async function requireDockerSuccess(action, args) {
6977
7086
  const result = await runLocalCommand("docker", args);
@@ -6979,10 +7088,20 @@ async function requireDockerSuccess(action, args) {
6979
7088
  return;
6980
7089
  throw new Error(`Could not ${action}: ${commandFailureDetail(result)}`);
6981
7090
  }
6982
- var DOCKER_CONTAINER = "dbos-db", DOCKER_IMAGE = "pgvector/pgvector:pg16", DOCKER_READY_ATTEMPTS = 60, DOCKER_READY_DELAY_MS = 500, resolution, resolvedProvider, embeddedProvider, dockerProvider, shutdownEmbeddedProvider, embeddedShutdown, ownerKey, ownerBag3, owner;
7091
+ var DOCKER_CONTAINER = "dbos-db", DOCKER_IMAGE = "pgvector/pgvector:pg16", DOCKER_READY_ATTEMPTS = 60, DOCKER_READY_DELAY_MS = 500, DOCKER_READY_QUERY_TIMEOUT_MS = 1000, TRANSIENT_STARTUP_CODES, resolution, resolvedProvider, embeddedProvider, dockerProvider, shutdownEmbeddedProvider, embeddedShutdown, ownerKey, ownerBag3, owner;
6983
7092
  var init_dbos_local_postgres = __esm(() => {
7093
+ init_esm();
6984
7094
  init_dbos_embedded_postgres();
6985
7095
  init_local_command();
7096
+ TRANSIENT_STARTUP_CODES = new Set([
7097
+ "ECONNREFUSED",
7098
+ "ECONNRESET",
7099
+ "ETIMEDOUT",
7100
+ "EPIPE",
7101
+ "57P01",
7102
+ "57P02",
7103
+ "57P03"
7104
+ ]);
6986
7105
  embeddedProvider = ensureEmbeddedDbosPostgres;
6987
7106
  dockerProvider = ensureDockerDbosPostgres;
6988
7107
  shutdownEmbeddedProvider = shutdownEmbeddedDbosPostgres;
@@ -22218,6 +22337,7 @@ import { createStructuredOutputCapture, runCallback as runCallback2 } from "@bas
22218
22337
 
22219
22338
  // dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts
22220
22339
  import {
22340
+ AutoRoutingInferenceError,
22221
22341
  convertToLlm,
22222
22342
  parseModelConstraints
22223
22343
  } from "@bastani/atomic";
@@ -22862,6 +22982,22 @@ function latestTerminalAssistantFailureSince(messages, startIndex) {
22862
22982
  }
22863
22983
  return;
22864
22984
  }
22985
+ function hasAssistantMessageSince(messages, startIndex) {
22986
+ for (let index = messages.length - 1;index >= Math.max(startIndex, 0); index -= 1) {
22987
+ if (messages[index]?.role === "assistant")
22988
+ return true;
22989
+ }
22990
+ return false;
22991
+ }
22992
+ var EMPTY_COMPLETION_FAILURE_MESSAGE = "Model turn ended without an assistant message after the prompt (empty completion)";
22993
+
22994
+ class WorkflowPromptEmptyCompletionFailure extends Error {
22995
+ code = "provider_error";
22996
+ constructor() {
22997
+ super(EMPTY_COMPLETION_FAILURE_MESSAGE);
22998
+ this.name = "WorkflowPromptEmptyCompletionFailure";
22999
+ }
23000
+ }
22865
23001
 
22866
23002
  class WorkflowPromptModelFailure extends Error {
22867
23003
  cause;
@@ -23792,13 +23928,22 @@ class StageSessionController {
23792
23928
  parseModelConstraints(options?.modelConstraints),
23793
23929
  ...thinking === undefined ? [] : [{ allowedEfforts: [thinking] }]
23794
23930
  ].filter((c) => c !== undefined);
23795
- this.modelRoute = await route({
23796
- task: text,
23797
- stageName: this.opts.stageName,
23798
- constraints,
23799
- signal: this.startupWait.signal,
23800
- selection: options?.routerSelection
23801
- });
23931
+ try {
23932
+ this.modelRoute = await route({
23933
+ task: text,
23934
+ stageName: this.opts.stageName,
23935
+ constraints,
23936
+ signal: this.startupWait.signal,
23937
+ selection: options?.routerSelection
23938
+ });
23939
+ } catch (error) {
23940
+ this.startupWait.signal.throwIfAborted();
23941
+ this.opts.signal?.throwIfAborted();
23942
+ if (!(error instanceof AutoRoutingInferenceError) || error.currentModelRoute === undefined)
23943
+ throw error;
23944
+ this.modelRoute = error.currentModelRoute;
23945
+ this.modelCatalog?.recordWarning?.(`workflows: stage auto routing failed; running "${this.opts.stageName}" on the current chat model ${this.modelRoute.modelOverride}.`);
23946
+ }
23802
23947
  this.modelRoute.assertCurrent();
23803
23948
  this.meta.stageOptions = { ...options, model: this.modelRoute.modelOverride };
23804
23949
  this.opts.onModelFallbackMetaChange?.(this.currentModelFallbackMeta());
@@ -24274,9 +24419,9 @@ class StageSessionController {
24274
24419
  if (continuationSession !== undefined) {
24275
24420
  const outcome = await this.continueWithPauseResume(continuationSession);
24276
24421
  if (outcome.kind === "continued") {
24277
- return {
24278
- terminalScanStartIndex: terminalScanStartIndex ?? this.lastPromptStartIndex ?? messagesBeforeAttempt.length
24279
- };
24422
+ const continuedScanStartIndex = terminalScanStartIndex ?? this.lastPromptStartIndex ?? messagesBeforeAttempt.length;
24423
+ this.throwIfEmptyCompletion(activeSession, continuedScanStartIndex);
24424
+ return { terminalScanStartIndex: continuedScanStartIndex };
24280
24425
  }
24281
24426
  this.dropRetainedPrompt(activeSession, retainedPrompt);
24282
24427
  retainedPrompt = undefined;
@@ -24800,6 +24945,7 @@ class StageSessionController {
24800
24945
  continue;
24801
24946
  }
24802
24947
  this.throwUnresolvedContextOverflowIfPresent();
24948
+ this.throwIfEmptyCompletion(activeSession, promptStartIndex);
24803
24949
  return { terminalScanStartIndex: promptStartIndex };
24804
24950
  } catch (err) {
24805
24951
  const pendingPauseAfterThrow = this.pauseControl.currentResume();
@@ -24952,6 +25098,17 @@ class StageSessionController {
24952
25098
  if (message !== undefined)
24953
25099
  throw unresolvedContextOverflowFailure(message);
24954
25100
  }
25101
+ throwIfEmptyCompletion(activeSession, promptStartIndex) {
25102
+ if (this.structuredOutputCapture === undefined || this.structuredOutputCapture.called)
25103
+ return;
25104
+ if (this.disposed || hasAssistantMessageSince(activeSession.messages, promptStartIndex))
25105
+ return;
25106
+ if (this.opts.signal?.aborted)
25107
+ throw this.workflowAbortReason();
25108
+ if (this.startupWait.signal.aborted)
25109
+ throw this.abortReason ?? new DOMException("stage aborted", "AbortError");
25110
+ throw new WorkflowPromptEmptyCompletionFailure;
25111
+ }
24955
25112
  }
24956
25113
 
24957
25114
  // dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts