@bastani/atomic 0.9.20-alpha.4 → 0.9.20-alpha.6

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 (474) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +37 -0
  3. package/dist/builtin/intercom/CHANGELOG.md +16 -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 +43 -12
  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 +18 -0
  14. package/dist/builtin/subagents/README.md +2 -0
  15. package/dist/builtin/subagents/agents/code-simplifier.md +1 -1
  16. package/dist/builtin/subagents/agents/codebase-analyzer.md +1 -1
  17. package/dist/builtin/subagents/agents/codebase-online-researcher.md +3 -3
  18. package/dist/builtin/subagents/agents/debugger.md +7 -5
  19. package/dist/builtin/subagents/agents/worker.md +4 -2
  20. package/dist/builtin/subagents/package.json +3 -3
  21. package/dist/builtin/subagents/skills/agent-browser/SKILL.md +56 -0
  22. package/dist/builtin/subagents/skills/cua-driver/BROWSER.md +494 -0
  23. package/dist/builtin/subagents/skills/cua-driver/EMBEDDING.md +578 -0
  24. package/dist/builtin/subagents/skills/cua-driver/LINUX.md +364 -0
  25. package/dist/builtin/subagents/skills/cua-driver/MACOS.md +509 -0
  26. package/dist/builtin/subagents/skills/cua-driver/README.md +113 -0
  27. package/dist/builtin/subagents/skills/cua-driver/RECORDING.md +162 -0
  28. package/dist/builtin/subagents/skills/cua-driver/SKILL.md +1105 -0
  29. package/dist/builtin/subagents/skills/cua-driver/WINDOWS.md +866 -0
  30. package/dist/builtin/subagents/skills/subagent/SKILL.md +32 -8
  31. package/dist/builtin/subagents/src/extension/index.bundle.mjs +7 -4
  32. package/dist/builtin/web-access/package.json +2 -2
  33. package/dist/builtin/workflows/CHANGELOG.md +43 -0
  34. package/dist/builtin/workflows/README.md +4 -2
  35. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  36. package/dist/builtin/workflows/builtin/{chunk-1dydq7w3.js → chunk-2hzrv5y8.js} +202 -45
  37. package/dist/builtin/workflows/builtin/{chunk-n4yxrsm9.js → chunk-3tx8ry44.js} +3 -2
  38. package/dist/builtin/workflows/builtin/{chunk-n8g2da69.js → chunk-5724b0cf.js} +1 -1
  39. package/dist/builtin/workflows/builtin/{chunk-scgprmdj.js → chunk-7n51c5gh.js} +1 -1
  40. package/dist/builtin/workflows/builtin/{chunk-9y0f90rd.js → chunk-9z3ztr2a.js} +1 -1
  41. package/dist/builtin/workflows/builtin/{chunk-vt9zgr9d.js → chunk-deq63d9p.js} +4 -4
  42. package/dist/builtin/workflows/builtin/{chunk-k18g9me8.js → chunk-dxjxtgmp.js} +1 -1
  43. package/dist/builtin/workflows/builtin/{chunk-kf5xpbkz.js → chunk-ffdrv23t.js} +1 -1
  44. package/dist/builtin/workflows/builtin/{chunk-119kxb28.js → chunk-hmt5w62g.js} +72 -45
  45. package/dist/builtin/workflows/builtin/{chunk-hnbbb5r0.js → chunk-jngsbbpm.js} +4 -4
  46. package/dist/builtin/workflows/builtin/{chunk-d1xqh1rd.js → chunk-njmf5ze7.js} +1 -1
  47. package/dist/builtin/workflows/builtin/{chunk-sn5mchnx.js → chunk-vn0wb31x.js} +1 -1
  48. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  49. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  50. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  51. package/dist/builtin/workflows/builtin/goal.js +4 -4
  52. package/dist/builtin/workflows/builtin/index.d.ts +1 -1
  53. package/dist/builtin/workflows/builtin/index.js +12 -12
  54. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  55. package/dist/builtin/workflows/builtin/open-claude-design.d.ts +1 -1
  56. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  57. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  58. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  59. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  60. package/dist/builtin/workflows/package.json +2 -2
  61. package/dist/builtin/workflows/skills/impeccable/SKILL.md +18 -11
  62. package/dist/builtin/workflows/skills/impeccable/reference/adapt.md +1 -1
  63. package/dist/builtin/workflows/skills/impeccable/reference/adapt.native.md +1 -1
  64. package/dist/builtin/workflows/skills/impeccable/reference/animate.md +1 -1
  65. package/dist/builtin/workflows/skills/impeccable/reference/audit.md +5 -5
  66. package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +6 -6
  67. package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +2 -2
  68. package/dist/builtin/workflows/skills/impeccable/reference/clarify.md +1 -1
  69. package/dist/builtin/workflows/skills/impeccable/reference/colorize.md +1 -1
  70. package/dist/builtin/workflows/skills/impeccable/reference/craft-floor.md +0 -6
  71. package/dist/builtin/workflows/skills/impeccable/reference/critique.md +19 -41
  72. package/dist/builtin/workflows/skills/impeccable/reference/degraded/asset-producer.md +11 -65
  73. package/dist/builtin/workflows/skills/impeccable/reference/degraded/documenter.md +3 -3
  74. package/dist/builtin/workflows/skills/impeccable/reference/degraded/finish-reviewer.md +4 -4
  75. package/dist/builtin/workflows/skills/impeccable/reference/degraded/manual-edit-applier.md +1 -1
  76. package/dist/builtin/workflows/skills/impeccable/reference/delight.md +1 -1
  77. package/dist/builtin/workflows/skills/impeccable/reference/distill.md +2 -2
  78. package/dist/builtin/workflows/skills/impeccable/reference/doctor.md +4 -4
  79. package/dist/builtin/workflows/skills/impeccable/reference/document.md +4 -4
  80. package/dist/builtin/workflows/skills/impeccable/reference/extract.md +1 -1
  81. package/dist/builtin/workflows/skills/impeccable/reference/harden.md +1 -1
  82. package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +21 -21
  83. package/dist/builtin/workflows/skills/impeccable/reference/init.md +8 -8
  84. package/dist/builtin/workflows/skills/impeccable/reference/layout.md +2 -2
  85. package/dist/builtin/workflows/skills/impeccable/reference/live-setup.md +10 -8
  86. package/dist/builtin/workflows/skills/impeccable/reference/live.md +39 -38
  87. package/dist/builtin/workflows/skills/impeccable/reference/new-work.md +48 -21
  88. package/dist/builtin/workflows/skills/impeccable/reference/onboard.md +1 -1
  89. package/dist/builtin/workflows/skills/impeccable/reference/optimize.md +1 -1
  90. package/dist/builtin/workflows/skills/impeccable/reference/overdrive.md +1 -1
  91. package/dist/builtin/workflows/skills/impeccable/reference/polish.md +11 -3
  92. package/dist/builtin/workflows/skills/impeccable/reference/quieter.md +2 -2
  93. package/dist/builtin/workflows/skills/impeccable/reference/routing.md +13 -7
  94. package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +2 -2
  95. package/dist/builtin/workflows/skills/impeccable/reference/visualize.md +13 -19
  96. package/dist/builtin/workflows/skills/impeccable/scripts/VERSION +1 -0
  97. package/dist/builtin/workflows/skills/impeccable/scripts/data/font-index-failures.json +121 -0
  98. package/dist/builtin/workflows/skills/impeccable/scripts/data/font-index.json +1 -0
  99. package/dist/builtin/workflows/skills/impeccable/scripts/impeccable +212 -0
  100. package/dist/builtin/workflows/skills/impeccable/scripts/impeccable.cmd +218 -0
  101. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-dom.js +21 -0
  102. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-ignores.js +242 -0
  103. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-session.js +25 -4
  104. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +666 -197
  105. package/dist/builtin/workflows/skills/research-codebase/SKILL.md +1 -1
  106. package/dist/builtin/workflows/src/extension/index.bundle.mjs +352 -117
  107. package/dist/builtin/workflows/src/index.js +1403 -1218
  108. package/dist/cli/args.d.ts.map +1 -1
  109. package/dist/cli/args.js +15 -4
  110. package/dist/cli/args.js.map +1 -1
  111. package/dist/cli/file-processor.d.ts +1 -1
  112. package/dist/cli/file-processor.d.ts.map +1 -1
  113. package/dist/cli/file-processor.js.map +1 -1
  114. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  115. package/dist/core/agent-session-auto-compaction.js +40 -12
  116. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  117. package/dist/core/agent-session-bash.d.ts.map +1 -1
  118. package/dist/core/agent-session-bash.js +9 -8
  119. package/dist/core/agent-session-bash.js.map +1 -1
  120. package/dist/core/agent-session-boundaries.d.ts +68 -0
  121. package/dist/core/agent-session-boundaries.d.ts.map +1 -0
  122. package/dist/core/agent-session-boundaries.js +334 -0
  123. package/dist/core/agent-session-boundaries.js.map +1 -0
  124. package/dist/core/agent-session-compaction.js +1 -1
  125. package/dist/core/agent-session-compaction.js.map +1 -1
  126. package/dist/core/agent-session-events.d.ts.map +1 -1
  127. package/dist/core/agent-session-events.js +27 -13
  128. package/dist/core/agent-session-events.js.map +1 -1
  129. package/dist/core/agent-session-export.d.ts.map +1 -1
  130. package/dist/core/agent-session-export.js +16 -20
  131. package/dist/core/agent-session-export.js.map +1 -1
  132. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  133. package/dist/core/agent-session-message-queue.js +3 -2
  134. package/dist/core/agent-session-message-queue.js.map +1 -1
  135. package/dist/core/agent-session-methods.d.ts +30 -4
  136. package/dist/core/agent-session-methods.d.ts.map +1 -1
  137. package/dist/core/agent-session-methods.js.map +1 -1
  138. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  139. package/dist/core/agent-session-persistent-custom-messages.js +2 -1
  140. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  141. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  142. package/dist/core/agent-session-prompt.js +93 -25
  143. package/dist/core/agent-session-prompt.js.map +1 -1
  144. package/dist/core/agent-session-retry.d.ts.map +1 -1
  145. package/dist/core/agent-session-retry.js +4 -9
  146. package/dist/core/agent-session-retry.js.map +1 -1
  147. package/dist/core/agent-session-runtime.js +1 -1
  148. package/dist/core/agent-session-runtime.js.map +1 -1
  149. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  150. package/dist/core/agent-session-tool-hooks.js +15 -5
  151. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  152. package/dist/core/agent-session-tree.d.ts.map +1 -1
  153. package/dist/core/agent-session-tree.js +2 -3
  154. package/dist/core/agent-session-tree.js.map +1 -1
  155. package/dist/core/agent-session-types.d.ts +6 -0
  156. package/dist/core/agent-session-types.d.ts.map +1 -1
  157. package/dist/core/agent-session-types.js.map +1 -1
  158. package/dist/core/agent-session.d.ts +15 -2
  159. package/dist/core/agent-session.d.ts.map +1 -1
  160. package/dist/core/agent-session.js +17 -1
  161. package/dist/core/agent-session.js.map +1 -1
  162. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  163. package/dist/core/compaction/branch-summarization.js +1 -0
  164. package/dist/core/compaction/branch-summarization.js.map +1 -1
  165. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  166. package/dist/core/compaction/compaction-boundary.js +11 -6
  167. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  168. package/dist/core/compaction/compaction.d.ts +3 -1
  169. package/dist/core/compaction/compaction.d.ts.map +1 -1
  170. package/dist/core/compaction/compaction.js +37 -0
  171. package/dist/core/compaction/compaction.js.map +1 -1
  172. package/dist/core/crash-log.d.ts +6 -0
  173. package/dist/core/crash-log.d.ts.map +1 -0
  174. package/dist/core/crash-log.js +69 -0
  175. package/dist/core/crash-log.js.map +1 -0
  176. package/dist/core/execution-model-router.d.ts +3 -0
  177. package/dist/core/execution-model-router.d.ts.map +1 -1
  178. package/dist/core/execution-model-router.js +45 -16
  179. package/dist/core/execution-model-router.js.map +1 -1
  180. package/dist/core/export-html/template-js/tree-filter-render.js +6 -1
  181. package/dist/core/export-html/template.js +6 -1
  182. package/dist/core/extensions/agent-events.d.ts +69 -3
  183. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  184. package/dist/core/extensions/agent-events.js.map +1 -1
  185. package/dist/core/extensions/api-types.d.ts +5 -3
  186. package/dist/core/extensions/api-types.d.ts.map +1 -1
  187. package/dist/core/extensions/api-types.js.map +1 -1
  188. package/dist/core/extensions/event-results.d.ts +3 -0
  189. package/dist/core/extensions/event-results.d.ts.map +1 -1
  190. package/dist/core/extensions/event-results.js.map +1 -1
  191. package/dist/core/extensions/event-types.d.ts +2 -2
  192. package/dist/core/extensions/event-types.d.ts.map +1 -1
  193. package/dist/core/extensions/event-types.js.map +1 -1
  194. package/dist/core/extensions/index.d.ts +1 -1
  195. package/dist/core/extensions/index.d.ts.map +1 -1
  196. package/dist/core/extensions/index.js.map +1 -1
  197. package/dist/core/extensions/provider-types.d.ts +2 -0
  198. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  199. package/dist/core/extensions/provider-types.js.map +1 -1
  200. package/dist/core/extensions/runner-events.d.ts +16 -2
  201. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  202. package/dist/core/extensions/runner-events.js +98 -5
  203. package/dist/core/extensions/runner-events.js.map +1 -1
  204. package/dist/core/extensions/runner.d.ts +3 -2
  205. package/dist/core/extensions/runner.d.ts.map +1 -1
  206. package/dist/core/extensions/runner.js +4 -1
  207. package/dist/core/extensions/runner.js.map +1 -1
  208. package/dist/core/index.d.ts +1 -1
  209. package/dist/core/index.d.ts.map +1 -1
  210. package/dist/core/index.js.map +1 -1
  211. package/dist/core/messages.d.ts +10 -0
  212. package/dist/core/messages.d.ts.map +1 -1
  213. package/dist/core/messages.js +57 -0
  214. package/dist/core/messages.js.map +1 -1
  215. package/dist/core/model-config.d.ts +52 -0
  216. package/dist/core/model-config.d.ts.map +1 -1
  217. package/dist/core/model-config.js +16 -0
  218. package/dist/core/model-config.js.map +1 -1
  219. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  220. package/dist/core/model-resolver-defaults.js +2 -1
  221. package/dist/core/model-resolver-defaults.js.map +1 -1
  222. package/dist/core/model-routing-task.d.ts +1 -1
  223. package/dist/core/model-routing-task.d.ts.map +1 -1
  224. package/dist/core/model-routing-task.js +4 -3
  225. package/dist/core/model-routing-task.js.map +1 -1
  226. package/dist/core/prompt-templates-async.d.ts +2 -2
  227. package/dist/core/prompt-templates-async.d.ts.map +1 -1
  228. package/dist/core/prompt-templates-async.js +57 -29
  229. package/dist/core/prompt-templates-async.js.map +1 -1
  230. package/dist/core/prompt-templates.d.ts +6 -1
  231. package/dist/core/prompt-templates.d.ts.map +1 -1
  232. package/dist/core/prompt-templates.js +61 -35
  233. package/dist/core/prompt-templates.js.map +1 -1
  234. package/dist/core/provider-composer-internal.d.ts +1 -0
  235. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  236. package/dist/core/provider-composer-internal.js +19 -0
  237. package/dist/core/provider-composer-internal.js.map +1 -1
  238. package/dist/core/resource-loader-assets.d.ts.map +1 -1
  239. package/dist/core/resource-loader-assets.js +6 -6
  240. package/dist/core/resource-loader-assets.js.map +1 -1
  241. package/dist/core/sdk.js +3 -2
  242. package/dist/core/sdk.js.map +1 -1
  243. package/dist/core/session-manager-core.d.ts +10 -3
  244. package/dist/core/session-manager-core.d.ts.map +1 -1
  245. package/dist/core/session-manager-core.js +65 -7
  246. package/dist/core/session-manager-core.js.map +1 -1
  247. package/dist/core/session-manager-entries.d.ts +4 -1
  248. package/dist/core/session-manager-entries.d.ts.map +1 -1
  249. package/dist/core/session-manager-entries.js +8 -0
  250. package/dist/core/session-manager-entries.js.map +1 -1
  251. package/dist/core/session-manager-history.d.ts +16 -1
  252. package/dist/core/session-manager-history.d.ts.map +1 -1
  253. package/dist/core/session-manager-history.js +105 -42
  254. package/dist/core/session-manager-history.js.map +1 -1
  255. package/dist/core/session-manager-types.d.ts +30 -3
  256. package/dist/core/session-manager-types.d.ts.map +1 -1
  257. package/dist/core/session-manager-types.js.map +1 -1
  258. package/dist/core/session-manager.d.ts +2 -2
  259. package/dist/core/session-manager.d.ts.map +1 -1
  260. package/dist/core/session-manager.js +1 -1
  261. package/dist/core/session-manager.js.map +1 -1
  262. package/dist/core/structured-output/index.d.ts +0 -1
  263. package/dist/core/structured-output/index.d.ts.map +1 -1
  264. package/dist/core/structured-output/index.js +3 -15
  265. package/dist/core/structured-output/index.js.map +1 -1
  266. package/dist/core/structured-output/jev-client.d.ts +4 -8
  267. package/dist/core/structured-output/jev-client.d.ts.map +1 -1
  268. package/dist/core/structured-output/jev-client.js +36 -32
  269. package/dist/core/structured-output/jev-client.js.map +1 -1
  270. package/dist/core/structured-output/jev.d.ts.map +1 -1
  271. package/dist/core/structured-output/jev.js +4 -12
  272. package/dist/core/structured-output/jev.js.map +1 -1
  273. package/dist/core/structured-output/types.d.ts +0 -2
  274. package/dist/core/structured-output/types.d.ts.map +1 -1
  275. package/dist/core/structured-output/types.js.map +1 -1
  276. package/dist/core/system-prompt.d.ts.map +1 -1
  277. package/dist/core/system-prompt.js +2 -1
  278. package/dist/core/system-prompt.js.map +1 -1
  279. package/dist/core/tools/read.d.ts +4 -0
  280. package/dist/core/tools/read.d.ts.map +1 -1
  281. package/dist/core/tools/read.js +5 -1
  282. package/dist/core/tools/read.js.map +1 -1
  283. package/dist/index-extensions.d.ts +1 -1
  284. package/dist/index-extensions.d.ts.map +1 -1
  285. package/dist/index-extensions.js.map +1 -1
  286. package/dist/index.d.ts +3 -3
  287. package/dist/index.d.ts.map +1 -1
  288. package/dist/index.js +3 -3
  289. package/dist/index.js.map +1 -1
  290. package/dist/main-app-mode.d.ts +1 -1
  291. package/dist/main-app-mode.d.ts.map +1 -1
  292. package/dist/main-app-mode.js +3 -2
  293. package/dist/main-app-mode.js.map +1 -1
  294. package/dist/main.d.ts.map +1 -1
  295. package/dist/main.js +1 -1
  296. package/dist/main.js.map +1 -1
  297. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  298. package/dist/modes/interactive/components/chat-message-renderer.js +4 -0
  299. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  300. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  301. package/dist/modes/interactive/components/tree-selector-content.js +6 -0
  302. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  303. package/dist/modes/interactive/components/tree-selector-model.d.ts.map +1 -1
  304. package/dist/modes/interactive/components/tree-selector-model.js +1 -0
  305. package/dist/modes/interactive/components/tree-selector-model.js.map +1 -1
  306. package/dist/modes/interactive/interactive-agent-events.js +17 -1
  307. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  308. package/dist/modes/interactive/interactive-mode-helpers.d.ts +1 -0
  309. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  310. package/dist/modes/interactive/interactive-mode-helpers.js +16 -0
  311. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  312. package/dist/modes/interactive/interactive-mode-surface.d.ts +1 -0
  313. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  314. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  315. package/dist/modes/interactive/interactive-process-lifecycle.js +13 -1
  316. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  317. package/dist/modes/interactive/interactive-session-runtime.js +5 -1
  318. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  319. package/dist/utils/mime.js +1 -1
  320. package/dist/utils/mime.js.map +1 -1
  321. package/dist/utils/tool-result-images.d.ts +3 -1
  322. package/dist/utils/tool-result-images.d.ts.map +1 -1
  323. package/dist/utils/tool-result-images.js +4 -1
  324. package/dist/utils/tool-result-images.js.map +1 -1
  325. package/docs/compaction.md +5 -1
  326. package/docs/computer-use.md +123 -73
  327. package/docs/extensions/events.md +75 -7
  328. package/docs/extensions.md +6 -2
  329. package/docs/getting-started/first-session.md +3 -2
  330. package/docs/getting-started/installation.md +6 -2
  331. package/docs/intercom/operations.md +13 -1
  332. package/docs/intercom.md +7 -2
  333. package/docs/models/evals.md +68 -82
  334. package/docs/models/model-selection.md +11 -7
  335. package/docs/models/reference.md +30 -2
  336. package/docs/packages.md +2 -0
  337. package/docs/prompt-templates.md +1 -0
  338. package/docs/providers.md +8 -2
  339. package/docs/quickstart.md +1 -1
  340. package/docs/sdk/reference.md +1 -2
  341. package/docs/sdk/structured-decisions.md +10 -9
  342. package/docs/sdk.md +13 -2
  343. package/docs/session-format.md +17 -2
  344. package/docs/settings.md +1 -1
  345. package/docs/skills.md +3 -1
  346. package/docs/subagents/reference.md +6 -6
  347. package/docs/subagents.md +8 -2
  348. package/docs/usage.md +2 -0
  349. package/docs/windows.md +1 -1
  350. package/docs/workflows/api-reference.md +5 -4
  351. package/docs/workflows/authoring.md +191 -0
  352. package/docs/workflows/builtins.md +2 -2
  353. package/docs/workflows/operations.md +10 -4
  354. package/docs/workflows/reliable-design.md +12 -1
  355. package/docs/workflows/verification.md +27 -14
  356. package/npm-shrinkwrap.json +69 -69
  357. package/package.json +8 -8
  358. package/dist/builtin/subagents/skills/playwright-cli/SKILL.md +0 -420
  359. package/dist/builtin/subagents/skills/playwright-cli/references/element-attributes.md +0 -23
  360. package/dist/builtin/subagents/skills/playwright-cli/references/playwright-tests.md +0 -39
  361. package/dist/builtin/subagents/skills/playwright-cli/references/request-mocking.md +0 -87
  362. package/dist/builtin/subagents/skills/playwright-cli/references/running-code.md +0 -241
  363. package/dist/builtin/subagents/skills/playwright-cli/references/session-management.md +0 -225
  364. package/dist/builtin/subagents/skills/playwright-cli/references/storage-state.md +0 -275
  365. package/dist/builtin/subagents/skills/playwright-cli/references/test-generation.md +0 -433
  366. package/dist/builtin/subagents/skills/playwright-cli/references/tracing.md +0 -139
  367. package/dist/builtin/subagents/skills/playwright-cli/references/video-recording.md +0 -143
  368. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_asset_producer.toml +0 -94
  369. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_documenter.toml +0 -27
  370. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_finish_reviewer.toml +0 -41
  371. package/dist/builtin/workflows/skills/impeccable/agents/impeccable_manual_edit_applier.toml +0 -95
  372. package/dist/builtin/workflows/skills/impeccable/agents/openai.yaml +0 -4
  373. package/dist/builtin/workflows/skills/impeccable/scripts/concept-seed.mjs +0 -695
  374. package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +0 -325
  375. package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +0 -1503
  376. package/dist/builtin/workflows/skills/impeccable/scripts/critique-storage.mjs +0 -222
  377. package/dist/builtin/workflows/skills/impeccable/scripts/detect-csp.mjs +0 -198
  378. package/dist/builtin/workflows/skills/impeccable/scripts/detect.mjs +0 -21
  379. package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +0 -2073
  380. package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +0 -432
  381. package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +0 -1121
  382. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +0 -8746
  383. package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns.mjs +0 -51
  384. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs +0 -376
  385. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +0 -1168
  386. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/css-cascade.mjs +0 -1192
  387. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs +0 -290
  388. package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/visual/screenshot-contrast.mjs +0 -189
  389. package/dist/builtin/workflows/skills/impeccable/scripts/detector/findings.mjs +0 -18
  390. package/dist/builtin/workflows/skills/impeccable/scripts/detector/node/file-system.mjs +0 -213
  391. package/dist/builtin/workflows/skills/impeccable/scripts/detector/profile/profiler.mjs +0 -166
  392. package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +0 -617
  393. package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +0 -5534
  394. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/color.mjs +0 -588
  395. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/constants.mjs +0 -112
  396. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/fonts.mjs +0 -30
  397. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/inline-ignores.mjs +0 -148
  398. package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/page.mjs +0 -35
  399. package/dist/builtin/workflows/skills/impeccable/scripts/doctor.mjs +0 -338
  400. package/dist/builtin/workflows/skills/impeccable/scripts/embed-prompt.mjs +0 -270
  401. package/dist/builtin/workflows/skills/impeccable/scripts/generate-image.mjs +0 -277
  402. package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +0 -783
  403. package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +0 -2305
  404. package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +0 -78
  405. package/dist/builtin/workflows/skills/impeccable/scripts/lib/artifact-schema.mjs +0 -93
  406. package/dist/builtin/workflows/skills/impeccable/scripts/lib/composition-catalog.mjs +0 -200
  407. package/dist/builtin/workflows/skills/impeccable/scripts/lib/concept-catalog.mjs +0 -395
  408. package/dist/builtin/workflows/skills/impeccable/scripts/lib/design-parser.mjs +0 -925
  409. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +0 -640
  410. package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-paths.mjs +0 -137
  411. package/dist/builtin/workflows/skills/impeccable/scripts/lib/is-generated.mjs +0 -72
  412. package/dist/builtin/workflows/skills/impeccable/scripts/lib/open-system-browser.mjs +0 -57
  413. package/dist/builtin/workflows/skills/impeccable/scripts/lib/provider.mjs +0 -5
  414. package/dist/builtin/workflows/skills/impeccable/scripts/lib/roll-selection.mjs +0 -369
  415. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-deep.mjs +0 -483
  416. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-notice.mjs +0 -169
  417. package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness.mjs +0 -528
  418. package/dist/builtin/workflows/skills/impeccable/scripts/lib/surface-briefs.mjs +0 -151
  419. package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-args.mjs +0 -42
  420. package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-slug.mjs +0 -33
  421. package/dist/builtin/workflows/skills/impeccable/scripts/lib/template-extensions.mjs +0 -146
  422. package/dist/builtin/workflows/skills/impeccable/scripts/live/accept-css.mjs +0 -617
  423. package/dist/builtin/workflows/skills/impeccable/scripts/live/accept-verify.mjs +0 -71
  424. package/dist/builtin/workflows/skills/impeccable/scripts/live/browser-script-parts.mjs +0 -77
  425. package/dist/builtin/workflows/skills/impeccable/scripts/live/completion.mjs +0 -28
  426. package/dist/builtin/workflows/skills/impeccable/scripts/live/event-validation.mjs +0 -199
  427. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/astro.mjs +0 -47
  428. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/detect-utils.mjs +0 -157
  429. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/index.mjs +0 -143
  430. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/journal.mjs +0 -205
  431. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/nextjs.mjs +0 -49
  432. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/nuxt.mjs +0 -170
  433. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/script-src.mjs +0 -26
  434. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/static-html.mjs +0 -26
  435. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/sveltekit.mjs +0 -71
  436. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/tag-strategy.mjs +0 -247
  437. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/tanstack-start.mjs +0 -70
  438. package/dist/builtin/workflows/skills/impeccable/scripts/live/frameworks/vite-generic.mjs +0 -42
  439. package/dist/builtin/workflows/skills/impeccable/scripts/live/generation-preflight.mjs +0 -149
  440. package/dist/builtin/workflows/skills/impeccable/scripts/live/insert-ui.mjs +0 -458
  441. package/dist/builtin/workflows/skills/impeccable/scripts/live/instructions.mjs +0 -169
  442. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-apply.mjs +0 -939
  443. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-edit-routes.mjs +0 -357
  444. package/dist/builtin/workflows/skills/impeccable/scripts/live/manual-edits-buffer.mjs +0 -152
  445. package/dist/builtin/workflows/skills/impeccable/scripts/live/poll-lanes.mjs +0 -14
  446. package/dist/builtin/workflows/skills/impeccable/scripts/live/roots.mjs +0 -670
  447. package/dist/builtin/workflows/skills/impeccable/scripts/live/session-store.mjs +0 -563
  448. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-lock.mjs +0 -105
  449. package/dist/builtin/workflows/skills/impeccable/scripts/live/source-search.mjs +0 -105
  450. package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-ast.mjs +0 -969
  451. package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-component.mjs +0 -1401
  452. package/dist/builtin/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs +0 -314
  453. package/dist/builtin/workflows/skills/impeccable/scripts/live/tanstack-adapter.mjs +0 -280
  454. package/dist/builtin/workflows/skills/impeccable/scripts/live/ui-surfaces.mjs +0 -75
  455. package/dist/builtin/workflows/skills/impeccable/scripts/live/vocabulary.mjs +0 -171
  456. package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +0 -961
  457. package/dist/builtin/workflows/skills/impeccable/scripts/live-commit-manual-edits.mjs +0 -1244
  458. package/dist/builtin/workflows/skills/impeccable/scripts/live-complete.mjs +0 -107
  459. package/dist/builtin/workflows/skills/impeccable/scripts/live-copy-edit-agent.mjs +0 -800
  460. package/dist/builtin/workflows/skills/impeccable/scripts/live-discard-manual-edits.mjs +0 -51
  461. package/dist/builtin/workflows/skills/impeccable/scripts/live-inject.mjs +0 -515
  462. package/dist/builtin/workflows/skills/impeccable/scripts/live-insert.mjs +0 -292
  463. package/dist/builtin/workflows/skills/impeccable/scripts/live-manual-edit-evidence.mjs +0 -371
  464. package/dist/builtin/workflows/skills/impeccable/scripts/live-poll.mjs +0 -427
  465. package/dist/builtin/workflows/skills/impeccable/scripts/live-resume.mjs +0 -123
  466. package/dist/builtin/workflows/skills/impeccable/scripts/live-server.mjs +0 -1675
  467. package/dist/builtin/workflows/skills/impeccable/scripts/live-status.mjs +0 -71
  468. package/dist/builtin/workflows/skills/impeccable/scripts/live-target.mjs +0 -30
  469. package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +0 -927
  470. package/dist/builtin/workflows/skills/impeccable/scripts/live.mjs +0 -365
  471. package/dist/builtin/workflows/skills/impeccable/scripts/palette.mjs +0 -628
  472. package/dist/builtin/workflows/skills/impeccable/scripts/pin.mjs +0 -224
  473. package/dist/builtin/workflows/skills/impeccable/scripts/serve-question.mjs +0 -1540
  474. package/dist/builtin/workflows/skills/impeccable/scripts/surface-brief.mjs +0 -74
@@ -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) {
@@ -5184,548 +4494,1254 @@ var require_pg_pool = __commonJS(function(exports, module) {
5184
4494
  this._idle.push(new IdleItem(client, idleListener, tid));
5185
4495
  this._pulseQueue();
5186
4496
  }
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) => {
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);
4543
+ }
4544
+ });
4545
+ return response.result;
4546
+ }
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);
4552
+ }
4553
+ this.ending = true;
4554
+ const promised = promisify(this.Promise, cb);
4555
+ this._endCallback = promised.callback;
4556
+ this._pulseQueue();
4557
+ return promised.result;
4558
+ }
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];
4617
+ }
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
+ });
4660
+ });
4661
+ } else {
4662
+ rows.forEach(function(row) {
4663
+ self.emit("row", row, results);
4664
+ });
4665
+ }
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);
4675
+ }
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);
4687
+ }
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;
4766
+ }
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;
4775
+ }
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);
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);
5343
4977
  }
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
- });
4978
+ };
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;
5355
5014
  }
5356
5015
  }
5357
- self.state = "end";
5358
- self.emit("end", results);
5359
- if (self.callback) {
5360
- self.callback(null, results);
5361
- }
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 } : {}
5110
+ });
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);
5362
5146
  };
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);
5377
- }
5378
- return client.native.execute(this.name, values, after);
5379
- }
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);
5385
- });
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
- });
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
- });
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}.`);
5587
5601
  }
5588
- let result;
5589
- if (!cb) {
5590
- result = new this._Promise(function(resolve, reject) {
5591
- cb = (err) => err ? reject(err) : resolve();
5592
- });
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;
5593
5668
  }
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
- });
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
@@ -6548,7 +6564,7 @@ async function withSetupLock(lockDir, fn, options = {}) {
6548
6564
  const isProcessAlive = options.isProcessAlive ?? processIsAlive2;
6549
6565
  let lease;
6550
6566
  for (let attempt = 0;attempt < attempts; attempt += 1) {
6551
- lease = acquireSetupLock(lockDir, clock(), staleMs, isProcessAlive);
6567
+ lease = acquireSetupLock(lockDir, clock(), staleMs, isProcessAlive, options.beforeOwnerMarkerWrite);
6552
6568
  if (lease !== undefined)
6553
6569
  break;
6554
6570
  if (attempt === attempts - 1) {
@@ -6570,29 +6586,15 @@ async function withSetupLock(lockDir, fn, options = {}) {
6570
6586
  releaseSetupLock(lease);
6571
6587
  }
6572
6588
  }
6573
- function acquireSetupLock(lockDir, now, staleMs, isProcessAlive) {
6589
+ function acquireSetupLock(lockDir, now, staleMs, isProcessAlive, beforeOwnerMarkerWrite) {
6574
6590
  const abandonedOwnerTokens = new Set;
6575
6591
  for (let attempt = 0;attempt < 2; attempt += 1) {
6576
6592
  const token = `${process.pid}-${crypto.randomUUID()}`;
6577
- const markerPath = join4(lockDir, `.owner-${token}`);
6578
- try {
6579
- mkdirSync2(lockDir);
6580
- try {
6581
- writeFileSync2(markerPath, serializeLockOwner({ token, pid: process.pid, heartbeatMonotonicMs: now.monotonicMs }), {
6582
- flag: "wx",
6583
- mode: 384
6584
- });
6585
- return { lockDir, markerPath, token, ownerPid: process.pid, abandonedOwnerTokens };
6586
- } catch (error) {
6587
- try {
6588
- rmdirSync(lockDir);
6589
- } catch {}
6590
- throw error;
6591
- }
6592
- } catch (error) {
6593
- const code = error instanceof Error && "code" in error ? error.code : undefined;
6594
- if (code !== "EEXIST")
6595
- throw error;
6593
+ if (createSetupLockDirectory(lockDir)) {
6594
+ beforeOwnerMarkerWrite?.(lockDir);
6595
+ const lease = claimCreatedSetupLock(lockDir, token, now, abandonedOwnerTokens);
6596
+ if (lease !== undefined)
6597
+ return lease;
6596
6598
  }
6597
6599
  const observation = observeSetupLock(lockDir);
6598
6600
  if (observation === undefined || !setupLockIsStale(observation, now, staleMs, isProcessAlive))
@@ -6605,6 +6607,52 @@ function acquireSetupLock(lockDir, now, staleMs, isProcessAlive) {
6605
6607
  }
6606
6608
  return;
6607
6609
  }
6610
+ function createSetupLockDirectory(lockDir) {
6611
+ try {
6612
+ mkdirSync2(lockDir);
6613
+ return true;
6614
+ } catch (error) {
6615
+ if (errorCode(error) === "EEXIST")
6616
+ return false;
6617
+ throw error;
6618
+ }
6619
+ }
6620
+ function claimCreatedSetupLock(lockDir, token, now, abandonedOwnerTokens) {
6621
+ const markerName = `.owner-${token}`;
6622
+ const markerPath = join4(lockDir, markerName);
6623
+ try {
6624
+ writeFileSync2(markerPath, serializeLockOwner({ token, pid: process.pid, heartbeatMonotonicMs: now.monotonicMs }), {
6625
+ flag: "wx",
6626
+ mode: 384
6627
+ });
6628
+ } catch (error) {
6629
+ try {
6630
+ rmdirSync(lockDir);
6631
+ } catch {}
6632
+ if (errorCode(error) === "ENOENT")
6633
+ return;
6634
+ throw error;
6635
+ }
6636
+ if (createdSetupLockHoldsOnly(lockDir, markerName)) {
6637
+ return { lockDir, markerPath, token, ownerPid: process.pid, abandonedOwnerTokens };
6638
+ }
6639
+ rmSync2(markerPath, { force: true });
6640
+ try {
6641
+ rmdirSync(lockDir);
6642
+ } catch {}
6643
+ return;
6644
+ }
6645
+ function createdSetupLockHoldsOnly(lockDir, markerName) {
6646
+ try {
6647
+ const entries = readdirSync2(lockDir);
6648
+ return entries.length === 1 && entries[0] === markerName;
6649
+ } catch {
6650
+ return false;
6651
+ }
6652
+ }
6653
+ function errorCode(error) {
6654
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
6655
+ }
6608
6656
  function refreshSetupLockLease(lease, now, beforeReplace) {
6609
6657
  if (!ownsSetupLock(lease))
6610
6658
  return false;
@@ -6725,9 +6773,15 @@ function setupLockIsStale(observation, now, staleMs, isProcessAlive) {
6725
6773
  return false;
6726
6774
  }
6727
6775
  }
6728
- if (!observation.hasUnexpectedState)
6729
- return observation.owners.length > 0;
6730
- return now.wallTimeMs < observation.latestMtimeMs || now.wallTimeMs - observation.latestMtimeMs > staleMs;
6776
+ if (observation.hasUnexpectedState) {
6777
+ return now.wallTimeMs < observation.latestMtimeMs || now.wallTimeMs - observation.latestMtimeMs > staleMs;
6778
+ }
6779
+ if (observation.owners.length > 0)
6780
+ return true;
6781
+ return emptySetupLockIsAbandoned(observation, now, staleMs);
6782
+ }
6783
+ function emptySetupLockIsAbandoned(observation, now, staleMs) {
6784
+ return Number.isFinite(observation.latestMtimeMs) && now.wallTimeMs - observation.latestMtimeMs > staleMs;
6731
6785
  }
6732
6786
  function serializeLockOwner(owner) {
6733
6787
  const serialized = JSON.stringify(owner);
@@ -6875,6 +6929,103 @@ function shutdownResolvedLocalDbos() {
6875
6929
  });
6876
6930
  return embeddedShutdown;
6877
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
+ }
6878
7029
  async function resolve() {
6879
7030
  const explicit = process.env.DBOS_SYSTEM_DATABASE_URL?.trim();
6880
7031
  if (explicit)
@@ -6900,6 +7051,7 @@ async function resolve() {
6900
7051
  }
6901
7052
  }
6902
7053
  async function ensureDockerDbosPostgres() {
7054
+ const endpoint = dockerFallbackEndpoint();
6903
7055
  const docker = await runLocalCommand("docker", ["version", "--format", "{{.Server.Version}}"]).catch(() => {
6904
7056
  return;
6905
7057
  });
@@ -6922,18 +7074,13 @@ async function ensureDockerDbosPostgres() {
6922
7074
  "-e",
6923
7075
  "PGDATA=/var/lib/postgresql/data",
6924
7076
  "-p",
6925
- "127.0.0.1:5432:5432",
7077
+ `127.0.0.1:${endpoint.port}:5432`,
6926
7078
  "-v",
6927
7079
  "dbos-db-data:/var/lib/postgresql/data",
6928
7080
  DOCKER_IMAGE
6929
7081
  ]);
6930
7082
  }
6931
- for (let attempt = 0;attempt < DOCKER_READY_ATTEMPTS; attempt += 1) {
6932
- if (await tcpReachable("127.0.0.1", 5432))
6933
- return;
6934
- await delay(DOCKER_READY_DELAY_MS);
6935
- }
6936
- 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 });
6937
7084
  }
6938
7085
  async function requireDockerSuccess(action, args) {
6939
7086
  const result = await runLocalCommand("docker", args);
@@ -6941,10 +7088,20 @@ async function requireDockerSuccess(action, args) {
6941
7088
  return;
6942
7089
  throw new Error(`Could not ${action}: ${commandFailureDetail(result)}`);
6943
7090
  }
6944
- 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;
6945
7092
  var init_dbos_local_postgres = __esm(() => {
7093
+ init_esm();
6946
7094
  init_dbos_embedded_postgres();
6947
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
+ ]);
6948
7105
  embeddedProvider = ensureEmbeddedDbosPostgres;
6949
7106
  dockerProvider = ensureDockerDbosPostgres;
6950
7107
  shutdownEmbeddedProvider = shutdownEmbeddedDbosPostgres;
@@ -22824,6 +22981,22 @@ function latestTerminalAssistantFailureSince(messages, startIndex) {
22824
22981
  }
22825
22982
  return;
22826
22983
  }
22984
+ function hasAssistantMessageSince(messages, startIndex) {
22985
+ for (let index = messages.length - 1;index >= Math.max(startIndex, 0); index -= 1) {
22986
+ if (messages[index]?.role === "assistant")
22987
+ return true;
22988
+ }
22989
+ return false;
22990
+ }
22991
+ var EMPTY_COMPLETION_FAILURE_MESSAGE = "Model turn ended without an assistant message after the prompt (empty completion)";
22992
+
22993
+ class WorkflowPromptEmptyCompletionFailure extends Error {
22994
+ code = "provider_error";
22995
+ constructor() {
22996
+ super(EMPTY_COMPLETION_FAILURE_MESSAGE);
22997
+ this.name = "WorkflowPromptEmptyCompletionFailure";
22998
+ }
22999
+ }
22827
23000
 
22828
23001
  class WorkflowPromptModelFailure extends Error {
22829
23002
  cause;
@@ -24236,9 +24409,9 @@ class StageSessionController {
24236
24409
  if (continuationSession !== undefined) {
24237
24410
  const outcome = await this.continueWithPauseResume(continuationSession);
24238
24411
  if (outcome.kind === "continued") {
24239
- return {
24240
- terminalScanStartIndex: terminalScanStartIndex ?? this.lastPromptStartIndex ?? messagesBeforeAttempt.length
24241
- };
24412
+ const continuedScanStartIndex = terminalScanStartIndex ?? this.lastPromptStartIndex ?? messagesBeforeAttempt.length;
24413
+ this.throwIfEmptyCompletion(activeSession, continuedScanStartIndex);
24414
+ return { terminalScanStartIndex: continuedScanStartIndex };
24242
24415
  }
24243
24416
  this.dropRetainedPrompt(activeSession, retainedPrompt);
24244
24417
  retainedPrompt = undefined;
@@ -24762,6 +24935,7 @@ class StageSessionController {
24762
24935
  continue;
24763
24936
  }
24764
24937
  this.throwUnresolvedContextOverflowIfPresent();
24938
+ this.throwIfEmptyCompletion(activeSession, promptStartIndex);
24765
24939
  return { terminalScanStartIndex: promptStartIndex };
24766
24940
  } catch (err) {
24767
24941
  const pendingPauseAfterThrow = this.pauseControl.currentResume();
@@ -24914,6 +25088,17 @@ class StageSessionController {
24914
25088
  if (message !== undefined)
24915
25089
  throw unresolvedContextOverflowFailure(message);
24916
25090
  }
25091
+ throwIfEmptyCompletion(activeSession, promptStartIndex) {
25092
+ if (this.structuredOutputCapture === undefined || this.structuredOutputCapture.called)
25093
+ return;
25094
+ if (this.disposed || hasAssistantMessageSince(activeSession.messages, promptStartIndex))
25095
+ return;
25096
+ if (this.opts.signal?.aborted)
25097
+ throw this.workflowAbortReason();
25098
+ if (this.startupWait.signal.aborted)
25099
+ throw this.abortReason ?? new DOMException("stage aborted", "AbortError");
25100
+ throw new WorkflowPromptEmptyCompletionFailure;
25101
+ }
24917
25102
  }
24918
25103
 
24919
25104
  // dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts