@oxygen-agent/cli 1.1014.1895 → 1.1014.2040

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (351) hide show
  1. package/README.md +1 -1
  2. package/dist/auto-update.d.ts +1 -1
  3. package/dist/auto-update.js +3 -3
  4. package/dist/cli-install.d.ts +65 -0
  5. package/dist/cli-install.js +165 -0
  6. package/dist/command-families/tables/options.d.ts +1 -0
  7. package/dist/command-families/tables/register-automation.js +3 -1
  8. package/dist/commands/billing.js +1 -1
  9. package/dist/commands/managed-inboxes.js +6 -2
  10. package/dist/commands/observability.js +4 -4
  11. package/dist/commands/sequences.js +1 -1
  12. package/dist/commands/subscriptions.js +7 -5
  13. package/dist/commands/table-runs.js +10 -0
  14. package/dist/commands/tags.js +2 -2
  15. package/dist/commands/workflows.js +31 -10
  16. package/dist/http-client.d.ts +1 -1
  17. package/dist/http-client.js +1 -1
  18. package/dist/update.d.ts +4 -57
  19. package/dist/update.js +17 -163
  20. package/node_modules/@oxygen/formula/dist/cross-row-function.d.ts +13 -0
  21. package/node_modules/@oxygen/formula/dist/cross-row-function.js +1 -0
  22. package/node_modules/@oxygen/formula/dist/{refactor-internals → cross-row-functions}/novelty-score.d.ts +2 -0
  23. package/node_modules/@oxygen/formula/dist/{refactor-internals → cross-row-functions}/novelty-score.js +1 -0
  24. package/node_modules/@oxygen/formula/dist/cross-row-functions.generated.d.ts +3 -0
  25. package/node_modules/@oxygen/formula/dist/cross-row-functions.generated.js +3 -0
  26. package/node_modules/@oxygen/formula/dist/evaluate.d.ts +12 -1
  27. package/node_modules/@oxygen/formula/dist/evaluate.js +28 -3
  28. package/node_modules/@oxygen/recipe-sdk/dist/index.d.ts +2 -0
  29. package/node_modules/@oxygen/shared/dist/billing.d.ts +5 -1
  30. package/node_modules/@oxygen/shared/dist/billing.js +5 -1
  31. package/node_modules/@oxygen/shared/dist/capability-discovery-skill-audiences.generated.d.ts +30 -0
  32. package/node_modules/@oxygen/shared/dist/capability-discovery-skill-audiences.generated.js +33 -0
  33. package/node_modules/@oxygen/shared/dist/capability-discovery-skills.d.ts +39 -0
  34. package/node_modules/@oxygen/shared/dist/capability-discovery-skills.js +86 -0
  35. package/node_modules/@oxygen/shared/dist/capability-discovery-types.d.ts +93 -0
  36. package/node_modules/@oxygen/shared/dist/capability-discovery-types.js +1 -0
  37. package/node_modules/@oxygen/shared/dist/capability-discovery.d.ts +12 -270
  38. package/node_modules/@oxygen/shared/dist/capability-discovery.js +124 -3713
  39. package/node_modules/@oxygen/shared/dist/capability-intents/agency-directory.rules.d.ts +2 -0
  40. package/node_modules/@oxygen/shared/dist/capability-intents/agency-directory.rules.js +5 -0
  41. package/node_modules/@oxygen/shared/dist/capability-intents/agents.d.ts +10 -0
  42. package/node_modules/@oxygen/shared/dist/capability-intents/agents.js +53 -0
  43. package/node_modules/@oxygen/shared/dist/capability-intents/agents.rules.d.ts +2 -0
  44. package/node_modules/@oxygen/shared/dist/capability-intents/agents.rules.js +25 -0
  45. package/node_modules/@oxygen/shared/dist/capability-intents/billing-and-budgets.d.ts +31 -0
  46. package/node_modules/@oxygen/shared/dist/capability-intents/billing-and-budgets.js +70 -0
  47. package/node_modules/@oxygen/shared/dist/capability-intents/billing-and-budgets.rules.d.ts +2 -0
  48. package/node_modules/@oxygen/shared/dist/capability-intents/billing-and-budgets.rules.js +85 -0
  49. package/node_modules/@oxygen/shared/dist/capability-intents/collaboration.d.ts +9 -0
  50. package/node_modules/@oxygen/shared/dist/capability-intents/collaboration.js +54 -0
  51. package/node_modules/@oxygen/shared/dist/capability-intents/collaboration.rules.d.ts +2 -0
  52. package/node_modules/@oxygen/shared/dist/capability-intents/collaboration.rules.js +28 -0
  53. package/node_modules/@oxygen/shared/dist/capability-intents/connected-integrations.rules.d.ts +2 -0
  54. package/node_modules/@oxygen/shared/dist/capability-intents/connected-integrations.rules.js +23 -0
  55. package/node_modules/@oxygen/shared/dist/capability-intents/connected-linkedin.d.ts +43 -0
  56. package/node_modules/@oxygen/shared/dist/capability-intents/connected-linkedin.js +90 -0
  57. package/node_modules/@oxygen/shared/dist/capability-intents/connected-linkedin.rules.d.ts +2 -0
  58. package/node_modules/@oxygen/shared/dist/capability-intents/connected-linkedin.rules.js +58 -0
  59. package/node_modules/@oxygen/shared/dist/capability-intents/connected-whatsapp.rules.d.ts +2 -0
  60. package/node_modules/@oxygen/shared/dist/capability-intents/connected-whatsapp.rules.js +14 -0
  61. package/node_modules/@oxygen/shared/dist/capability-intents/geo.rules.d.ts +2 -0
  62. package/node_modules/@oxygen/shared/dist/capability-intents/geo.rules.js +9 -0
  63. package/node_modules/@oxygen/shared/dist/capability-intents/index.generated.d.ts +365 -0
  64. package/node_modules/@oxygen/shared/dist/capability-intents/index.generated.js +90 -0
  65. package/node_modules/@oxygen/shared/dist/capability-intents/knowledge-graph.d.ts +20 -0
  66. package/node_modules/@oxygen/shared/dist/capability-intents/knowledge-graph.js +37 -0
  67. package/node_modules/@oxygen/shared/dist/capability-intents/knowledge-graph.rules.d.ts +2 -0
  68. package/node_modules/@oxygen/shared/dist/capability-intents/knowledge-graph.rules.js +43 -0
  69. package/node_modules/@oxygen/shared/dist/capability-intents/linkedin-public-research.d.ts +4 -0
  70. package/node_modules/@oxygen/shared/dist/capability-intents/linkedin-public-research.js +26 -0
  71. package/node_modules/@oxygen/shared/dist/capability-intents/linkedin-public-research.rules.d.ts +2 -0
  72. package/node_modules/@oxygen/shared/dist/capability-intents/linkedin-public-research.rules.js +42 -0
  73. package/node_modules/@oxygen/shared/dist/capability-intents/messages.d.ts +6 -0
  74. package/node_modules/@oxygen/shared/dist/capability-intents/messages.js +16 -0
  75. package/node_modules/@oxygen/shared/dist/capability-intents/messages.rules.d.ts +2 -0
  76. package/node_modules/@oxygen/shared/dist/capability-intents/messages.rules.js +68 -0
  77. package/node_modules/@oxygen/shared/dist/capability-intents/normalize.d.ts +2 -0
  78. package/node_modules/@oxygen/shared/dist/capability-intents/normalize.js +4 -0
  79. package/node_modules/@oxygen/shared/dist/capability-intents/platform-operations.d.ts +6 -0
  80. package/node_modules/@oxygen/shared/dist/capability-intents/platform-operations.js +23 -0
  81. package/node_modules/@oxygen/shared/dist/capability-intents/platform-operations.rules.d.ts +2 -0
  82. package/node_modules/@oxygen/shared/dist/capability-intents/platform-operations.rules.js +25 -0
  83. package/node_modules/@oxygen/shared/dist/capability-intents/posts.d.ts +1 -0
  84. package/node_modules/@oxygen/shared/dist/capability-intents/posts.js +12 -0
  85. package/node_modules/@oxygen/shared/dist/capability-intents/posts.rules.d.ts +2 -0
  86. package/node_modules/@oxygen/shared/dist/capability-intents/posts.rules.js +20 -0
  87. package/node_modules/@oxygen/shared/dist/capability-intents/publishing.d.ts +86 -0
  88. package/node_modules/@oxygen/shared/dist/capability-intents/publishing.js +135 -0
  89. package/node_modules/@oxygen/shared/dist/capability-intents/publishing.rules.d.ts +2 -0
  90. package/node_modules/@oxygen/shared/dist/capability-intents/publishing.rules.js +89 -0
  91. package/node_modules/@oxygen/shared/dist/capability-intents/read-inspection.d.ts +7 -0
  92. package/node_modules/@oxygen/shared/dist/capability-intents/read-inspection.js +85 -0
  93. package/node_modules/@oxygen/shared/dist/capability-intents/read-inspection.rules.d.ts +2 -0
  94. package/node_modules/@oxygen/shared/dist/capability-intents/read-inspection.rules.js +28 -0
  95. package/node_modules/@oxygen/shared/dist/capability-intents/recipes.d.ts +7 -0
  96. package/node_modules/@oxygen/shared/dist/capability-intents/recipes.js +73 -0
  97. package/node_modules/@oxygen/shared/dist/capability-intents/recipes.rules.d.ts +2 -0
  98. package/node_modules/@oxygen/shared/dist/capability-intents/recipes.rules.js +36 -0
  99. package/node_modules/@oxygen/shared/dist/capability-intents/records.d.ts +86 -0
  100. package/node_modules/@oxygen/shared/dist/capability-intents/records.js +240 -0
  101. package/node_modules/@oxygen/shared/dist/capability-intents/records.rules.d.ts +2 -0
  102. package/node_modules/@oxygen/shared/dist/capability-intents/records.rules.js +71 -0
  103. package/node_modules/@oxygen/shared/dist/capability-intents/sending-infrastructure.d.ts +27 -0
  104. package/node_modules/@oxygen/shared/dist/capability-intents/sending-infrastructure.js +67 -0
  105. package/node_modules/@oxygen/shared/dist/capability-intents/sending-infrastructure.rules.d.ts +2 -0
  106. package/node_modules/@oxygen/shared/dist/capability-intents/sending-infrastructure.rules.js +115 -0
  107. package/node_modules/@oxygen/shared/dist/capability-intents/sequences.d.ts +71 -0
  108. package/node_modules/@oxygen/shared/dist/capability-intents/sequences.js +150 -0
  109. package/node_modules/@oxygen/shared/dist/capability-intents/sequences.rules.d.ts +2 -0
  110. package/node_modules/@oxygen/shared/dist/capability-intents/sequences.rules.js +149 -0
  111. package/node_modules/@oxygen/shared/dist/capability-intents/signals.d.ts +42 -0
  112. package/node_modules/@oxygen/shared/dist/capability-intents/signals.js +42 -0
  113. package/node_modules/@oxygen/shared/dist/capability-intents/signals.rules.d.ts +2 -0
  114. package/node_modules/@oxygen/shared/dist/capability-intents/signals.rules.js +47 -0
  115. package/node_modules/@oxygen/shared/dist/capability-intents/sourcing-and-provider-tools.d.ts +60 -0
  116. package/node_modules/@oxygen/shared/dist/capability-intents/sourcing-and-provider-tools.js +94 -0
  117. package/node_modules/@oxygen/shared/dist/capability-intents/sourcing-and-provider-tools.rules.d.ts +2 -0
  118. package/node_modules/@oxygen/shared/dist/capability-intents/sourcing-and-provider-tools.rules.js +94 -0
  119. package/node_modules/@oxygen/shared/dist/capability-intents/tables.d.ts +196 -0
  120. package/node_modules/@oxygen/shared/dist/capability-intents/tables.js +394 -0
  121. package/node_modules/@oxygen/shared/dist/capability-intents/tables.rules.d.ts +2 -0
  122. package/node_modules/@oxygen/shared/dist/capability-intents/tables.rules.js +384 -0
  123. package/node_modules/@oxygen/shared/dist/capability-intents/tags.rules.d.ts +2 -0
  124. package/node_modules/@oxygen/shared/dist/capability-intents/tags.rules.js +5 -0
  125. package/node_modules/@oxygen/shared/dist/capability-intents/visual-rendering.rules.d.ts +2 -0
  126. package/node_modules/@oxygen/shared/dist/capability-intents/visual-rendering.rules.js +8 -0
  127. package/node_modules/@oxygen/shared/dist/capability-intents/workflows.d.ts +2 -0
  128. package/node_modules/@oxygen/shared/dist/capability-intents/workflows.js +20 -0
  129. package/node_modules/@oxygen/shared/dist/capability-intents/workflows.rules.d.ts +2 -0
  130. package/node_modules/@oxygen/shared/dist/capability-intents/workflows.rules.js +90 -0
  131. package/node_modules/@oxygen/shared/dist/capability-intents/workspace-access.d.ts +59 -0
  132. package/node_modules/@oxygen/shared/dist/capability-intents/workspace-access.js +121 -0
  133. package/node_modules/@oxygen/shared/dist/capability-intents/workspace-access.rules.d.ts +2 -0
  134. package/node_modules/@oxygen/shared/dist/capability-intents/workspace-access.rules.js +58 -0
  135. package/node_modules/@oxygen/shared/dist/capability-routes/ads.d.ts +2 -0
  136. package/node_modules/@oxygen/shared/dist/capability-routes/ads.js +17 -0
  137. package/node_modules/@oxygen/shared/dist/capability-routes/agency-directory.d.ts +2 -0
  138. package/node_modules/@oxygen/shared/dist/capability-routes/agency-directory.js +17 -0
  139. package/node_modules/@oxygen/shared/dist/capability-routes/agents.d.ts +2 -0
  140. package/node_modules/@oxygen/shared/dist/capability-routes/agents.js +17 -0
  141. package/node_modules/@oxygen/shared/dist/capability-routes/billing-and-budgets.d.ts +2 -0
  142. package/node_modules/@oxygen/shared/dist/capability-routes/billing-and-budgets.js +17 -0
  143. package/node_modules/@oxygen/shared/dist/capability-routes/collaboration.d.ts +2 -0
  144. package/node_modules/@oxygen/shared/dist/capability-routes/collaboration.js +39 -0
  145. package/node_modules/@oxygen/shared/dist/capability-routes/connected-integrations.d.ts +2 -0
  146. package/node_modules/@oxygen/shared/dist/capability-routes/connected-integrations.js +17 -0
  147. package/node_modules/@oxygen/shared/dist/capability-routes/connected-linkedin.d.ts +2 -0
  148. package/node_modules/@oxygen/shared/dist/capability-routes/connected-linkedin.js +17 -0
  149. package/node_modules/@oxygen/shared/dist/capability-routes/connected-whatsapp.d.ts +2 -0
  150. package/node_modules/@oxygen/shared/dist/capability-routes/connected-whatsapp.js +17 -0
  151. package/node_modules/@oxygen/shared/dist/capability-routes/dashboards.d.ts +2 -0
  152. package/node_modules/@oxygen/shared/dist/capability-routes/dashboards.js +28 -0
  153. package/node_modules/@oxygen/shared/dist/capability-routes/discovery-and-skills.d.ts +2 -0
  154. package/node_modules/@oxygen/shared/dist/capability-routes/discovery-and-skills.js +22 -0
  155. package/node_modules/@oxygen/shared/dist/capability-routes/geo.d.ts +2 -0
  156. package/node_modules/@oxygen/shared/dist/capability-routes/geo.js +13 -0
  157. package/node_modules/@oxygen/shared/dist/capability-routes/index.d.ts +2 -0
  158. package/node_modules/@oxygen/shared/dist/capability-routes/index.js +64 -0
  159. package/node_modules/@oxygen/shared/dist/capability-routes/knowledge-graph.d.ts +2 -0
  160. package/node_modules/@oxygen/shared/dist/capability-routes/knowledge-graph.js +17 -0
  161. package/node_modules/@oxygen/shared/dist/capability-routes/linkedin-public-research.d.ts +2 -0
  162. package/node_modules/@oxygen/shared/dist/capability-routes/linkedin-public-research.js +18 -0
  163. package/node_modules/@oxygen/shared/dist/capability-routes/messages.d.ts +2 -0
  164. package/node_modules/@oxygen/shared/dist/capability-routes/messages.js +21 -0
  165. package/node_modules/@oxygen/shared/dist/capability-routes/observability.d.ts +2 -0
  166. package/node_modules/@oxygen/shared/dist/capability-routes/observability.js +17 -0
  167. package/node_modules/@oxygen/shared/dist/capability-routes/onboarding-and-copilot.d.ts +2 -0
  168. package/node_modules/@oxygen/shared/dist/capability-routes/onboarding-and-copilot.js +23 -0
  169. package/node_modules/@oxygen/shared/dist/capability-routes/platform-operations.d.ts +2 -0
  170. package/node_modules/@oxygen/shared/dist/capability-routes/platform-operations.js +17 -0
  171. package/node_modules/@oxygen/shared/dist/capability-routes/posts.d.ts +2 -0
  172. package/node_modules/@oxygen/shared/dist/capability-routes/posts.js +17 -0
  173. package/node_modules/@oxygen/shared/dist/capability-routes/publishing.d.ts +2 -0
  174. package/node_modules/@oxygen/shared/dist/capability-routes/publishing.js +20 -0
  175. package/node_modules/@oxygen/shared/dist/capability-routes/recipes.d.ts +2 -0
  176. package/node_modules/@oxygen/shared/dist/capability-routes/recipes.js +17 -0
  177. package/node_modules/@oxygen/shared/dist/capability-routes/records.d.ts +2 -0
  178. package/node_modules/@oxygen/shared/dist/capability-routes/records.js +20 -0
  179. package/node_modules/@oxygen/shared/dist/capability-routes/sending-infrastructure.d.ts +2 -0
  180. package/node_modules/@oxygen/shared/dist/capability-routes/sending-infrastructure.js +42 -0
  181. package/node_modules/@oxygen/shared/dist/capability-routes/sequences.d.ts +2 -0
  182. package/node_modules/@oxygen/shared/dist/capability-routes/sequences.js +32 -0
  183. package/node_modules/@oxygen/shared/dist/capability-routes/signals.d.ts +2 -0
  184. package/node_modules/@oxygen/shared/dist/capability-routes/signals.js +17 -0
  185. package/node_modules/@oxygen/shared/dist/capability-routes/sourcing-and-provider-tools.d.ts +2 -0
  186. package/node_modules/@oxygen/shared/dist/capability-routes/sourcing-and-provider-tools.js +21 -0
  187. package/node_modules/@oxygen/shared/dist/capability-routes/support-and-feedback.d.ts +2 -0
  188. package/node_modules/@oxygen/shared/dist/capability-routes/support-and-feedback.js +17 -0
  189. package/node_modules/@oxygen/shared/dist/capability-routes/tables.d.ts +2 -0
  190. package/node_modules/@oxygen/shared/dist/capability-routes/tables.js +34 -0
  191. package/node_modules/@oxygen/shared/dist/capability-routes/tags.d.ts +2 -0
  192. package/node_modules/@oxygen/shared/dist/capability-routes/tags.js +17 -0
  193. package/node_modules/@oxygen/shared/dist/capability-routes/visual-rendering.d.ts +2 -0
  194. package/node_modules/@oxygen/shared/dist/capability-routes/visual-rendering.js +17 -0
  195. package/node_modules/@oxygen/shared/dist/capability-routes/workflows.d.ts +2 -0
  196. package/node_modules/@oxygen/shared/dist/capability-routes/workflows.js +17 -0
  197. package/node_modules/@oxygen/shared/dist/capability-routes/workspace-access.d.ts +2 -0
  198. package/node_modules/@oxygen/shared/dist/capability-routes/workspace-access.js +26 -0
  199. package/node_modules/@oxygen/shared/dist/cell-format.js +2 -2
  200. package/node_modules/@oxygen/shared/dist/collab.d.ts +1 -1
  201. package/node_modules/@oxygen/shared/dist/contracts/connectors.js +2 -0
  202. package/node_modules/@oxygen/shared/dist/contracts/customer-operations.d.ts +1 -1
  203. package/node_modules/@oxygen/shared/dist/contracts/geo.js +1 -1
  204. package/node_modules/@oxygen/shared/dist/contracts/operations/agent-sessions.d.ts +1 -0
  205. package/node_modules/@oxygen/shared/dist/contracts/operations/agent-sessions.js +1 -0
  206. package/node_modules/@oxygen/shared/dist/contracts/operations/browser.d.ts +1 -0
  207. package/node_modules/@oxygen/shared/dist/contracts/operations/browser.js +1 -0
  208. package/node_modules/@oxygen/shared/dist/contracts/operations/clay-migration.d.ts +2 -0
  209. package/node_modules/@oxygen/shared/dist/contracts/operations/clay-migration.js +2 -0
  210. package/node_modules/@oxygen/shared/dist/contracts/operations/connectors.d.ts +2 -0
  211. package/node_modules/@oxygen/shared/dist/contracts/operations/connectors.js +2 -0
  212. package/node_modules/@oxygen/shared/dist/contracts/operations/geo.d.ts +1 -0
  213. package/node_modules/@oxygen/shared/dist/contracts/operations/geo.js +1 -0
  214. package/node_modules/@oxygen/shared/dist/contracts/operations/guided-activation.d.ts +1 -0
  215. package/node_modules/@oxygen/shared/dist/contracts/operations/guided-activation.js +1 -0
  216. package/node_modules/@oxygen/shared/dist/contracts/operations/index.generated.d.ts +2 -0
  217. package/node_modules/@oxygen/shared/dist/contracts/operations/index.generated.js +26 -0
  218. package/node_modules/@oxygen/shared/dist/contracts/operations/reply-oxygent.d.ts +1 -0
  219. package/node_modules/@oxygen/shared/dist/contracts/operations/reply-oxygent.js +1 -0
  220. package/node_modules/@oxygen/shared/dist/contracts/operations/sender-limits.d.ts +2 -0
  221. package/node_modules/@oxygen/shared/dist/contracts/operations/sender-limits.js +2 -0
  222. package/node_modules/@oxygen/shared/dist/contracts/operations/table-feed-update.d.ts +2 -0
  223. package/node_modules/@oxygen/shared/dist/contracts/operations/table-feed-update.js +2 -0
  224. package/node_modules/@oxygen/shared/dist/contracts/operations/teammates.d.ts +1 -0
  225. package/node_modules/@oxygen/shared/dist/contracts/operations/teammates.js +1 -0
  226. package/node_modules/@oxygen/shared/dist/contracts/operations/workspace-pages.d.ts +2 -0
  227. package/node_modules/@oxygen/shared/dist/contracts/operations/workspace-pages.js +2 -0
  228. package/node_modules/@oxygen/shared/dist/contracts/operations/workspace-skills.d.ts +1 -0
  229. package/node_modules/@oxygen/shared/dist/contracts/operations/workspace-skills.js +1 -0
  230. package/node_modules/@oxygen/shared/dist/contracts/operations.d.ts +6 -0
  231. package/node_modules/@oxygen/shared/dist/contracts/operations.js +7 -15
  232. package/node_modules/@oxygen/shared/dist/contracts/sender-limits.js +1 -0
  233. package/node_modules/@oxygen/shared/dist/diagnostic-storage-lock.js +33 -22
  234. package/node_modules/@oxygen/shared/dist/diagnostics.js +11 -8
  235. package/node_modules/@oxygen/shared/dist/dnc-identities.js +1 -1
  236. package/node_modules/@oxygen/shared/dist/error-redaction.d.ts +1 -1
  237. package/node_modules/@oxygen/shared/dist/error-redaction.js +2 -2
  238. package/node_modules/@oxygen/shared/dist/esp-contract.d.ts +133 -0
  239. package/node_modules/@oxygen/shared/dist/esp-contract.js +121 -0
  240. package/node_modules/@oxygen/shared/dist/first-month-offer-window.d.ts +3 -0
  241. package/node_modules/@oxygen/shared/dist/first-month-offer.d.ts +15 -7
  242. package/node_modules/@oxygen/shared/dist/first-month-offer.js +23 -9
  243. package/node_modules/@oxygen/shared/dist/{geo.js → geo/geo.js} +2 -2
  244. package/node_modules/@oxygen/shared/dist/guided-activation.d.ts +2 -0
  245. package/node_modules/@oxygen/shared/dist/index.d.ts +6 -5
  246. package/node_modules/@oxygen/shared/dist/index.js +7 -5
  247. package/node_modules/@oxygen/shared/dist/knowledge-bootstrap.js +1 -1
  248. package/node_modules/@oxygen/shared/dist/linkedin-connection-identity.js +1 -1
  249. package/node_modules/@oxygen/shared/dist/listed-website-platforms.d.ts +1 -1
  250. package/node_modules/@oxygen/shared/dist/listed-website-platforms.js +23 -1
  251. package/node_modules/@oxygen/shared/dist/{sending-domain-rollout.js → mailboxes/sending-domain-rollout.js} +1 -1
  252. package/node_modules/@oxygen/shared/dist/mcp-event-contract.js +1 -1
  253. package/node_modules/@oxygen/shared/dist/onboarding-leads.d.ts +67 -0
  254. package/node_modules/@oxygen/shared/dist/onboarding-leads.js +78 -0
  255. package/node_modules/@oxygen/shared/dist/otlp-log-sink.js +20 -0
  256. package/node_modules/@oxygen/shared/dist/plan-capabilities.js +1 -1
  257. package/node_modules/@oxygen/shared/dist/plan-limits.d.ts +2 -2
  258. package/node_modules/@oxygen/shared/dist/plan-limits.js +6 -7
  259. package/node_modules/@oxygen/shared/dist/{social-post-metrics-core.d.ts → posts/metrics-core.d.ts} +1 -1
  260. package/node_modules/@oxygen/shared/dist/{social-post-metrics-linkedin.d.ts → posts/metrics-linkedin.d.ts} +1 -1
  261. package/node_modules/@oxygen/shared/dist/{social-post-metrics-linkedin.js → posts/metrics-linkedin.js} +2 -2
  262. package/node_modules/@oxygen/shared/dist/{social-post-metrics-series.d.ts → posts/metrics-series.d.ts} +1 -1
  263. package/node_modules/@oxygen/shared/dist/{social-post-metrics-series.js → posts/metrics-series.js} +1 -1
  264. package/node_modules/@oxygen/shared/dist/{social-post-metrics-x.d.ts → posts/metrics-x.d.ts} +1 -1
  265. package/node_modules/@oxygen/shared/dist/{social-post-metrics-x.js → posts/metrics-x.js} +2 -2
  266. package/node_modules/@oxygen/shared/dist/{social-post-metrics.d.ts → posts/metrics.d.ts} +3 -3
  267. package/node_modules/@oxygen/shared/dist/{social-post-metrics.js → posts/metrics.js} +3 -3
  268. package/node_modules/@oxygen/shared/dist/recipient-provider.d.ts +2 -10
  269. package/node_modules/@oxygen/shared/dist/recipient-provider.js +1 -9
  270. package/node_modules/@oxygen/shared/dist/sending-domain-faults.d.ts +1 -1
  271. package/node_modules/@oxygen/shared/dist/sending-domain-faults.js +1 -1
  272. package/node_modules/@oxygen/shared/dist/sequence-internals/esp-policy.d.ts +2 -118
  273. package/node_modules/@oxygen/shared/dist/sequence-internals/esp-policy.js +2 -107
  274. package/node_modules/@oxygen/shared/dist/sequences.d.ts +0 -1
  275. package/node_modules/@oxygen/shared/dist/sequences.js +0 -2
  276. package/node_modules/@oxygen/shared/dist/{native-chat-discovery.d.ts → support/native-chat-discovery.d.ts} +1 -1
  277. package/node_modules/@oxygen/shared/dist/{native-chat-discovery.js → support/native-chat-discovery.js} +1 -1
  278. package/node_modules/@oxygen/shared/dist/suppression-entries.js +1 -1
  279. package/node_modules/@oxygen/shared/dist/table-field-types.d.ts +1 -1
  280. package/node_modules/@oxygen/shared/dist/table-field-types.js +2 -2
  281. package/node_modules/@oxygen/shared/dist/{column-output-fields.js → tables/column-output-fields.js} +4 -4
  282. package/node_modules/@oxygen/shared/dist/{tags.d.ts → tags/tags.d.ts} +1 -1
  283. package/node_modules/@oxygen/shared/dist/{tags.js → tags/tags.js} +1 -1
  284. package/node_modules/@oxygen/shared/dist/tenant-migration-names.d.ts +5 -0
  285. package/node_modules/@oxygen/shared/dist/tenant-migration-names.js +8 -0
  286. package/node_modules/@oxygen/shared/dist/ugc-amplification-identity.js +1 -1
  287. package/node_modules/@oxygen/shared/dist/version.generated.d.ts +1 -1
  288. package/node_modules/@oxygen/shared/dist/version.generated.js +1 -1
  289. package/node_modules/@oxygen/shared/dist/workspace-placement-bulk.d.ts +6 -0
  290. package/node_modules/@oxygen/shared/dist/workspace-placement-bulk.js +9 -2
  291. package/node_modules/@oxygen/shared/dist/workspace-placement-schedule.d.ts +44 -0
  292. package/node_modules/@oxygen/shared/dist/workspace-placement-schedule.js +90 -0
  293. package/node_modules/@oxygen/shared/dist/workspace-placement-view.d.ts +24 -0
  294. package/node_modules/@oxygen/shared/dist/workspace-placement-view.js +5 -4
  295. package/node_modules/@oxygen/shared/dist/workspace-placement.d.ts +4 -0
  296. package/node_modules/@oxygen/shared/dist/workspace-placement.js +7 -1
  297. package/node_modules/@oxygen/shared/package.json +0 -25
  298. package/node_modules/@oxygen/workflows/dist/cron.d.ts +42 -0
  299. package/node_modules/@oxygen/workflows/dist/cron.js +271 -0
  300. package/node_modules/@oxygen/workflows/dist/event-dispatch.d.ts +2 -1
  301. package/node_modules/@oxygen/workflows/dist/graph/condition.d.ts +3 -0
  302. package/node_modules/@oxygen/workflows/dist/graph/condition.js +19 -0
  303. package/node_modules/@oxygen/workflows/dist/graph/expression.d.ts +1 -2
  304. package/node_modules/@oxygen/workflows/dist/graph/expression.js +2 -19
  305. package/node_modules/@oxygen/workflows/dist/graph/lint.d.ts +1 -1
  306. package/node_modules/@oxygen/workflows/dist/graph/lint.js +4 -3
  307. package/node_modules/@oxygen/workflows/dist/graph/types.d.ts +4 -3
  308. package/node_modules/@oxygen/workflows/dist/index.d.ts +9 -1043
  309. package/node_modules/@oxygen/workflows/dist/index.js +11 -2124
  310. package/node_modules/@oxygen/workflows/dist/manifest-builders.d.ts +73 -0
  311. package/node_modules/@oxygen/workflows/dist/manifest-builders.js +102 -0
  312. package/node_modules/@oxygen/workflows/dist/manifest-guards.d.ts +16 -0
  313. package/node_modules/@oxygen/workflows/dist/manifest-guards.js +34 -0
  314. package/node_modules/@oxygen/workflows/dist/manifest-hash.d.ts +47 -0
  315. package/node_modules/@oxygen/workflows/dist/manifest-hash.js +102 -0
  316. package/node_modules/@oxygen/workflows/dist/manifest-lint.d.ts +17 -0
  317. package/node_modules/@oxygen/workflows/dist/manifest-lint.js +474 -0
  318. package/node_modules/@oxygen/workflows/dist/manifest-types.d.ts +256 -0
  319. package/node_modules/@oxygen/workflows/dist/manifest-types.js +9 -0
  320. package/node_modules/@oxygen/workflows/dist/manifest-validation.d.ts +75 -0
  321. package/node_modules/@oxygen/workflows/dist/manifest-validation.js +903 -0
  322. package/node_modules/@oxygen/workflows/dist/pure-function.d.ts +17 -0
  323. package/node_modules/@oxygen/workflows/dist/pure-function.js +130 -0
  324. package/node_modules/@oxygen/workflows/dist/refactor-internals/condition-comparison.d.ts +1 -17
  325. package/node_modules/@oxygen/workflows/dist/refactor-internals/condition-comparison.js +1 -93
  326. package/node_modules/@oxygen/workflows/dist/refactor-internals/condition-pattern.d.ts +16 -0
  327. package/node_modules/@oxygen/workflows/dist/refactor-internals/condition-pattern.js +92 -0
  328. package/node_modules/@oxygen/workflows/dist/workflow-schemas.d.ts +545 -0
  329. package/node_modules/@oxygen/workflows/dist/workflow-schemas.js +135 -0
  330. package/node_modules/@oxygen/workflows/package.json +4 -0
  331. package/package.json +1 -1
  332. /package/node_modules/@oxygen/shared/dist/{geo.d.ts → geo/geo.d.ts} +0 -0
  333. /package/node_modules/@oxygen/shared/dist/{sending-domain-rollout.d.ts → mailboxes/sending-domain-rollout.d.ts} +0 -0
  334. /package/node_modules/@oxygen/shared/dist/{attempt-provenance.d.ts → observability/attempt-provenance.d.ts} +0 -0
  335. /package/node_modules/@oxygen/shared/dist/{attempt-provenance.js → observability/attempt-provenance.js} +0 -0
  336. /package/node_modules/@oxygen/shared/dist/{linkedin-mentions.d.ts → posts/linkedin-mentions.d.ts} +0 -0
  337. /package/node_modules/@oxygen/shared/dist/{linkedin-mentions.js → posts/linkedin-mentions.js} +0 -0
  338. /package/node_modules/@oxygen/shared/dist/{linkedin-post-keywords.d.ts → posts/linkedin-post-keywords.d.ts} +0 -0
  339. /package/node_modules/@oxygen/shared/dist/{linkedin-post-keywords.js → posts/linkedin-post-keywords.js} +0 -0
  340. /package/node_modules/@oxygen/shared/dist/{linkedin-post-url.d.ts → posts/linkedin-post-url.d.ts} +0 -0
  341. /package/node_modules/@oxygen/shared/dist/{linkedin-post-url.js → posts/linkedin-post-url.js} +0 -0
  342. /package/node_modules/@oxygen/shared/dist/{social-post-metrics-core.js → posts/metrics-core.js} +0 -0
  343. /package/node_modules/@oxygen/shared/dist/{native-chat.d.ts → support/native-chat.d.ts} +0 -0
  344. /package/node_modules/@oxygen/shared/dist/{native-chat.js → support/native-chat.js} +0 -0
  345. /package/node_modules/@oxygen/shared/dist/{plain-support-events.d.ts → support/plain-support-events.d.ts} +0 -0
  346. /package/node_modules/@oxygen/shared/dist/{plain-support-events.js → support/plain-support-events.js} +0 -0
  347. /package/node_modules/@oxygen/shared/dist/{column-output-fields.d.ts → tables/column-output-fields.d.ts} +0 -0
  348. /package/node_modules/@oxygen/shared/dist/{linkedin-url.d.ts → tables/linkedin-url.d.ts} +0 -0
  349. /package/node_modules/@oxygen/shared/dist/{linkedin-url.js → tables/linkedin-url.js} +0 -0
  350. /package/node_modules/@oxygen/shared/dist/{select-options.d.ts → tables/select-options.d.ts} +0 -0
  351. /package/node_modules/@oxygen/shared/dist/{select-options.js → tables/select-options.js} +0 -0
@@ -1,7 +1,3 @@
1
- import { createHash } from "node:crypto";
2
- import * as vm from "node:vm"; // skipcq: JS-C1003
3
- import { isWorkflowGraphManifest, WORKFLOW_CODE_V1_DEFAULT_OUTPUT_BYTES, WORKFLOW_CODE_V1_DEFAULT_TIMEOUT_MS, WORKFLOW_CODE_V1_MAX_OUTPUT_BYTES, WORKFLOW_CODE_V1_MIN_OUTPUT_BYTES, WORKFLOW_CODE_V1_MIN_TIMEOUT_MS, } from "./graph/types.js";
4
- import { lintWorkflowGraphManifest } from "./graph/lint.js";
5
1
  export * from "./usage-estimate.js";
6
2
  // Pure event-dispatch semantics, shared by the apps/web and apps/worker event
7
3
  // dispatchers so the filter gate, idempotency rule, and delivery verdict cannot
@@ -9,2128 +5,19 @@ export * from "./usage-estimate.js";
9
5
  export * from "./event-dispatch.js";
10
6
  // oxygen-workflows-v2. The graph barrel is browser-safe on its own (importable as
11
7
  // "@oxygen/workflows/graph"); the linter is not — it reuses the v1 pure-function
12
- // scanner below — so it is re-exported here, from the node entry point only.
8
+ // scanner — so it is re-exported here, from the node entry point only.
13
9
  export * from "./graph/index.js";
14
10
  export * from "./graph/lint.js";
15
11
  export * from "./portable.js";
16
12
  export { RECIPE_TIMESTAMP_MILLIS_SOURCE } from "./recipe-timestamp.js";
17
13
  export * from "./refactor-internals/execution-policy.js";
18
- export const WORKFLOW_MANIFEST_VERSION = 1;
19
- export const WORKFLOW_COMPILER_VERSION = "oxygen-workflows-v1";
20
- export const DURABLE_RECIPE_COMPILER_VERSION = "oxygen-recipes-v2";
21
- export const BLUEPRINT_VERSION = 1;
22
- export const BLUEPRINT_COMPILER_VERSION = "oxygen-blueprints-v1";
23
- export const MAX_RECIPE_BUNDLE_BYTES = 2_000_000;
24
- export const MAX_BLUEPRINT_BYTES = 4_000_000;
25
- export const DEFAULT_WORKFLOW_CRON_TIMEZONE = "UTC";
26
- // Step ids that must not be used: they collide with JavaScript object internals
27
- // when the runtime assembles ctx.steps, so their outputs would be silently lost.
28
- const RESERVED_STEP_IDS = new Set(["__proto__", "constructor", "prototype"]);
29
- // Compatibility and determinism lint only. The Vercel sandbox process,
30
- // denied network policy, and runtime global guards are the security boundary.
31
- const UNSAFE_RECIPE_BUNDLE_PATTERNS = [
32
- { token: "globalThis", pattern: /\bglobalThis\b/ }, // skipcq: SCT-A000
33
- { token: "global", pattern: /\bglobal\b/ },
34
- { token: "process", pattern: /\bprocess\b/ },
35
- { token: "fetch", pattern: /\bfetch\b/ },
36
- { token: "XMLHttpRequest", pattern: /\bXMLHttpRequest\b/ }, // skipcq: SCT-A000
37
- { token: "WebSocket", pattern: /\bWebSocket\b/ },
38
- { token: "EventSource", pattern: /\bEventSource\b/ }, // skipcq: SCT-A000
39
- // Block CommonJS require(...) but allow a `.require` method access (the
40
- // ctx.approvals.require() durable-approval API). A real global require is a
41
- // bare identifier; any X.require on a dangerous global (globalThis/process/…)
42
- // is already caught by that global's own rule above.
43
- { token: "require", pattern: /(?<!\.)\brequire\b/ },
44
- { token: "dynamic import", pattern: /\bimport(?:\s|\/\*[\s\S]*?\*\/)*\(/ }, // skipcq: SCT-A000
45
- { token: "node module import", pattern: /\b(?:node:)?(?:fs|child_process|net|tls|http|https|dns|dgram|worker_threads)\b/ }, // skipcq: SCT-A000
46
- { token: "eval", pattern: /\beval\b/ },
47
- { token: "Function", pattern: /\bFunction\b/ },
48
- { token: "constructor", pattern: /\bconstructor\b/ },
49
- { token: "Date.now", pattern: /\bDate\s*\.\s*now\b/ },
50
- { token: "new Date", pattern: /\bnew\s+Date\b/ },
51
- { token: "Math.random", pattern: /\bMath\s*\.\s*random\b/ },
52
- { token: "crypto.randomUUID", pattern: /\bcrypto\s*\.\s*randomUUID\b/ },
53
- { token: "setTimeout", pattern: /\bsetTimeout\b/ },
54
- { token: "setInterval", pattern: /\bsetInterval\b/ }, // skipcq: SCT-A000
55
- ];
56
- // Code v1 has no ctx.now()/ctx.uuid() capability and runs as a pure transform,
57
- // so its determinism/capability denylist is intentionally stricter than the
58
- // durable-recipe compatibility scan above. Keep this separate: old immutable
59
- // recipe revisions must not acquire new lint failures merely because Code v1 is
60
- // introduced.
61
- const UNSAFE_WORKFLOW_CODE_SOURCE_PATTERNS = [
62
- ...UNSAFE_RECIPE_BUNDLE_PATTERNS,
63
- { token: "Date", pattern: /\bDate\b/ },
64
- { token: "WebAssembly", pattern: /\bWebAssembly\b/ },
65
- { token: "setImmediate", pattern: /\bsetImmediate\b/ },
66
- { token: "queueMicrotask", pattern: /\bqueueMicrotask\b/ },
67
- ];
68
- /** A valid workflow / recipe / trigger status. Optional everywhere it appears. */
69
- function isValidWorkflowStatus(value) {
70
- return value === "active" || value === "disabled";
71
- }
72
- export function defineWorkflow(input) {
73
- return {
74
- __oxygen_workflow_definition: true,
75
- id: input.id,
76
- name: input.name,
77
- ...(input.status ? { status: input.status } : {}),
78
- ...(input.specification ? { specification: input.specification } : {}),
79
- ...(input.trigger ? { trigger: input.trigger } : {}),
80
- ...(input.inputSchema ? { inputSchema: input.inputSchema } : {}),
81
- ...(input.maxCredits != null ? { maxCredits: input.maxCredits } : {}),
82
- steps: input.steps,
83
- };
84
- }
85
- export function apiTrigger(input = {}) {
86
- return {
87
- type: "api",
88
- ...(input.status ? { status: input.status } : {}),
89
- };
90
- }
91
- export function webhookTrigger(input) {
92
- return {
93
- type: "webhook",
94
- trigger_id: input.id,
95
- ...(input.name !== undefined ? { trigger_name: input.name } : {}),
96
- secret_required: input.secret ?? true,
97
- ...(input.idempotencyKeyPath !== undefined
98
- ? { idempotency_key_path: input.idempotencyKeyPath }
99
- : {}),
100
- ...(input.status ? { status: input.status } : {}),
101
- };
102
- }
103
- export function cronTrigger(input) {
104
- return {
105
- type: "cron",
106
- cron: input.cron,
107
- ...(input.timezone !== undefined ? { timezone: input.timezone } : {}),
108
- ...(input.status ? { status: input.status } : {}),
109
- };
110
- }
111
- export function eventTrigger(input) {
112
- return {
113
- type: "event",
114
- source: input.source,
115
- event: input.event,
116
- ...(input.filters ? { filters: input.filters } : {}),
117
- ...(input.idempotencyKeyPath !== undefined
118
- ? { idempotency_key_path: input.idempotencyKeyPath }
119
- : {}),
120
- ...(input.status ? { status: input.status } : {}),
121
- };
122
- }
123
- // Lookahead window for the next cron run. Must exceed the largest gap a *valid*
124
- // schedule can have, or legitimate sparse crons get falsely rejected: the worst
125
- // case is "Feb 29" across a century boundary (e.g. 2096 → 2104, an ~8-year gap,
126
- // since 2100 is not a leap year). The day-skipping scan below keeps even this
127
- // wide window cheap (~one zonedDateParts call per non-matching day).
128
- const MAX_CRON_LOOKAHEAD_DAYS = 366 * 8 + 2;
129
- export function nextCronRunAfter(input) {
130
- const schedule = parseCronSchedule(input.cron);
131
- const timezone = input.timezone?.trim() || DEFAULT_WORKFLOW_CRON_TIMEZONE;
132
- let candidate = roundUpToNextMinute(input.after ?? new Date());
133
- const deadline = candidate.getTime() + MAX_CRON_LOOKAHEAD_DAYS * 24 * 60 * 60 * 1000;
134
- while (candidate.getTime() <= deadline) {
135
- const parts = zonedDateParts(candidate, timezone);
136
- if (matchesCronSchedule(schedule, parts)) {
137
- return candidate;
138
- }
139
- // If the calendar date itself can't match, no minute that day matches —
140
- // jump to the next day instead of scanning all 1440 minutes. This keeps
141
- // sparse schedules (e.g. "0 9 29 2 *") and unsatisfiable ones fast over the
142
- // multi-year window. The jump targets ~00:00 of the next day, so a
143
- // subsequently matching date is scanned from its start (no missed minutes).
144
- if (!matchesCronDate(schedule, parts)) {
145
- const minutesToNextDay = Math.max(1, 24 * 60 - (parts.hour * 60 + parts.minute));
146
- let next = new Date(candidate.getTime() + minutesToNextDay * 60_000);
147
- // minutesToNextDay is a LOCAL-clock count added to a UTC instant. On a
148
- // spring-forward day the local day is < 24h, so the jump overshoots the
149
- // next local midnight and lands at ~01:00 — skipping an early-of-day match
150
- // (e.g. "0 0 …"), which can push the next run a full year out. If the jump
151
- // crossed into the next local day but past midnight, pull it back to that
152
- // midnight. (A fall-back day is > 24h: the jump undershoots and stays on
153
- // the same date, which the next iteration advances — left as-is.)
154
- const landed = zonedDateParts(next, timezone);
155
- const intoNextLocalDay = landed.hour * 60 + landed.minute;
156
- if (landed.dayOfMonth !== parts.dayOfMonth && intoNextLocalDay > 0) {
157
- next = new Date(next.getTime() - intoNextLocalDay * 60_000);
158
- }
159
- candidate = next;
160
- }
161
- else {
162
- candidate = new Date(candidate.getTime() + 60_000);
163
- }
164
- }
165
- throw new Error(`Cron expression has no matching run time in the next ${MAX_CRON_LOOKAHEAD_DAYS} days.`);
166
- }
167
- /**
168
- * The first slot of `cron` strictly after `after` that is also at least
169
- * `minIntervalMinutes` after `lastFireAt`. This is how a plan's minimum cron
170
- * interval (repricing 2026-09, decision L4.2) is enforced at fire time: a
171
- * schedule that fires closer together than the plan allows keeps running, only
172
- * slower, and is never deleted (proposal P-47). With no last fire or a minimum
173
- * of one minute or less it is exactly `nextCronRunAfter`.
174
- */
175
- export function nextCronRunAfterMinInterval(input) {
176
- const minIntervalMs = Math.max(0, input.minIntervalMinutes ?? 0) * 60_000;
177
- let after = input.after;
178
- if (input.lastFireAt && minIntervalMs > 60_000) {
179
- // One millisecond before the earliest allowed instant: nextCronRunAfter
180
- // returns the first whole-minute slot strictly after it, so a slot exactly
181
- // `minIntervalMinutes` after the last fire is allowed.
182
- const earliestAllowed = input.lastFireAt.getTime() + minIntervalMs - 1;
183
- if (earliestAllowed > after.getTime())
184
- after = new Date(earliestAllowed);
185
- }
186
- return nextCronRunAfter({ cron: input.cron, timezone: input.timezone ?? null, after });
187
- }
188
- // How many calendar days minCronGapMinutes scans for two matching days in a
189
- // row: two leap cycles, so a Feb 29 or a day-of-month/weekday coincidence is
190
- // always seen.
191
- const CRON_GAP_DAY_SCAN = 366 * 8 + 2;
192
- // Real-time simulation around a daylight-saving change covers the day it falls
193
- // in plus this many whole days either side (so the fire before a long gap that
194
- // straddles the change is inside the window), and stops after this many fires.
195
- const CRON_GAP_DST_WINDOW_DAYS = 1;
196
- const CRON_GAP_DST_MAX_FIRES = 5_000;
197
- /**
198
- * The smallest gap in minutes between two consecutive fires of `cron`, which is
199
- * what a plan's minimum cron interval is checked against (repricing 2026-09,
200
- * decision L4.2). It is the smallest gap, never the average: `0,5 9 * * *`
201
- * fires once a day on average but twice five minutes apart, so its gap is 5.
202
- *
203
- * Gaps are measured in real time in `timezone`. A daylight-saving change can
204
- * bring two fires closer than their wall-clock times suggest (01:55 and 03:05
205
- * are ten minutes apart on the night the clock skips from 02:00 to 03:00, and
206
- * a repeated hour can fire 01:45 and then 01:00 again), so the fires around
207
- * each change in the coming year are simulated as well.
208
- *
209
- * Returns null when the schedule never fires twice within the scan (for
210
- * example `0 9 29 2 *` fires once every few years and has no meaningful gap
211
- * for a minimum to bind). Throws on an unparseable expression, like
212
- * `nextCronRunAfter`.
213
- */
214
- export function minCronGapMinutes(input) {
215
- const schedule = parseCronSchedule(input.cron);
216
- const timezone = input.timezone?.trim() || DEFAULT_WORKFLOW_CRON_TIMEZONE;
217
- const fireMinutes = [...schedule.hours]
218
- .flatMap((hour) => [...schedule.minutes].map((minute) => hour * 60 + minute))
219
- .sort((a, b) => a - b);
220
- let gap = Number.POSITIVE_INFINITY;
221
- for (let index = 1; index < fireMinutes.length; index += 1) {
222
- gap = Math.min(gap, (fireMinutes[index] ?? 0) - (fireMinutes[index - 1] ?? 0));
223
- }
224
- const dayGap = smallestMatchingDayGap(schedule);
225
- const firstFire = fireMinutes[0];
226
- const lastFire = fireMinutes[fireMinutes.length - 1];
227
- if (dayGap !== null && firstFire !== undefined && lastFire !== undefined) {
228
- gap = Math.min(gap, dayGap * 24 * 60 + firstFire - lastFire);
229
- }
230
- // A one-minute gap is the floor of the cron grammar; daylight saving cannot
231
- // bring two fires closer than that.
232
- if (gap > 1) {
233
- const dstGap = smallestGapAroundDaylightSavingChanges(input.cron, timezone, input.now ?? new Date());
234
- if (dstGap !== null)
235
- gap = Math.min(gap, dstGap);
236
- }
237
- return Number.isFinite(gap) ? gap : null;
238
- }
239
- /** Fewest days between two calendar days the schedule's date fields both match. */
240
- function smallestMatchingDayGap(schedule) {
241
- // Calendar arithmetic only (no timezone): day-of-month, month and weekday
242
- // matching is the same on every clock. A fixed leap-year start covers every
243
- // weekday/day-of-month combination within the scan.
244
- const start = Date.UTC(2024, 0, 1);
245
- let previousMatch = null;
246
- let smallest = null;
247
- for (let day = 0; day < CRON_GAP_DAY_SCAN; day += 1) {
248
- const date = new Date(start + day * 24 * 60 * 60 * 1000);
249
- const matches = matchesCronDate(schedule, {
250
- minute: 0,
251
- hour: 0,
252
- dayOfMonth: date.getUTCDate(),
253
- month: date.getUTCMonth() + 1,
254
- dayOfWeek: date.getUTCDay(),
255
- });
256
- if (!matches)
257
- continue;
258
- if (previousMatch !== null) {
259
- const gap = day - previousMatch;
260
- smallest = smallest === null ? gap : Math.min(smallest, gap);
261
- if (smallest === 1)
262
- return 1;
263
- }
264
- previousMatch = day;
265
- }
266
- return smallest;
267
- }
268
- /**
269
- * The smallest real-time gap between fires in the days around each
270
- * daylight-saving change in the year after `now`; null when the zone has no
271
- * change in that year or no two fires fall in any window.
272
- */
273
- function smallestGapAroundDaylightSavingChanges(cron, timezone, now) {
274
- const dayMs = 24 * 60 * 60 * 1000;
275
- const start = Math.floor(now.getTime() / dayMs) * dayMs;
276
- let smallest = null;
277
- let previousOffset = zonedOffsetMinutes(new Date(start), timezone);
278
- for (let day = 1; day <= 367; day += 1) {
279
- const offset = zonedOffsetMinutes(new Date(start + day * dayMs), timezone);
280
- if (offset === previousOffset)
281
- continue;
282
- previousOffset = offset;
283
- const windowStart = new Date(start + (day - 1 - CRON_GAP_DST_WINDOW_DAYS) * dayMs);
284
- const windowEnd = start + (day + CRON_GAP_DST_WINDOW_DAYS) * dayMs;
285
- let fire = nextCronRunAfter({ cron, timezone, after: windowStart });
286
- for (let fires = 0; fires < CRON_GAP_DST_MAX_FIRES && fire.getTime() <= windowEnd; fires += 1) {
287
- const next = nextCronRunAfter({ cron, timezone, after: fire });
288
- if (next.getTime() > windowEnd)
289
- break;
290
- const gap = Math.round((next.getTime() - fire.getTime()) / 60_000);
291
- smallest = smallest === null ? gap : Math.min(smallest, gap);
292
- fire = next;
293
- }
294
- }
295
- return smallest;
296
- }
297
- /** Minutes the zone's wall clock is ahead of UTC at `date`. */
298
- function zonedOffsetMinutes(date, timezone) {
299
- const formatter = getZonedFormatter(timezone);
300
- const parts = new Map();
301
- for (const part of formatter.formatToParts(date)) {
302
- if (part.type !== "literal")
303
- parts.set(part.type, part.value);
304
- }
305
- const wallClock = Date.UTC(Number(parts.get("year")), Number(parts.get("month")) - 1, Number(parts.get("day")), Number(parts.get("hour")), Number(parts.get("minute")));
306
- const instant = Math.floor(date.getTime() / 60_000) * 60_000;
307
- return Math.round((wallClock - instant) / 60_000);
308
- }
309
- export function transformStep(input) {
310
- return {
311
- __oxygen_workflow_step: true,
312
- kind: "transform",
313
- id: input.id,
314
- ...(input.description ? { description: input.description } : {}),
315
- run: input.run,
316
- };
317
- }
318
- export function toolStep(input) {
319
- return {
320
- __oxygen_workflow_step: true,
321
- kind: "tool",
322
- id: input.id,
323
- ...(input.description ? { description: input.description } : {}),
324
- tool: input.tool,
325
- ...(input.effect ? { effect: input.effect } : {}),
326
- ...(input.mode ? { mode: input.mode } : {}),
327
- ...(input.connectionId !== undefined ? { connectionId: input.connectionId } : {}),
328
- ...(input.maxCredits != null ? { maxCredits: input.maxCredits } : {}),
329
- payload: input.payload,
330
- };
331
- }
332
- /**
333
- * Conditional step. `condition` is evaluated; control then flows by mode:
334
- *
335
- * - then only (no `else`, no `join`) — GUARD: truthy continues to `then` (steps
336
- * between the branch and `then` are skipped); falsy skips straight to the end
337
- * of the workflow (no step after the branch runs) and the run completes.
338
- * - then + else (no `join`) — skip-until-target jump to `then`/`else`; from the
339
- * chosen target, the remaining steps run sequentially through the end.
340
- * - then + else + join — real if/else: the non-chosen arm is skipped and `join`
341
- * is the convergence point where shared downstream work resumes.
342
- *
343
- * All targets must be ids of later steps (branches are forward-only).
344
- */
345
- export function branchStep(input) {
346
- return {
347
- __oxygen_workflow_step: true,
348
- kind: "branch",
349
- id: input.id,
350
- ...(input.description ? { description: input.description } : {}),
351
- condition: input.condition,
352
- then: input.then,
353
- ...(input.else !== undefined ? { else: input.else } : {}),
354
- ...(input.join !== undefined ? { join: input.join } : {}),
355
- };
356
- }
357
- export function isWorkflowDefinition(value) {
358
- return isRecord(value) && value.__oxygen_workflow_definition === true;
359
- }
360
- export function isWorkflowManifest(value) {
361
- return isRecord(value)
362
- && value.manifest_version === WORKFLOW_MANIFEST_VERSION
363
- && Array.isArray(value.steps);
364
- }
365
- export function isRecipeManifest(value) {
366
- return isRecord(value)
367
- && value.manifest_version === WORKFLOW_MANIFEST_VERSION
368
- && value.compiler_version === DURABLE_RECIPE_COMPILER_VERSION;
369
- }
370
- /**
371
- * Every manifest shape the platform can store and run: v1 hosted steps, durable
372
- * recipes, and oxygen-workflows-v2 graphs. This is the gate `workflows apply`
373
- * and the CLI loader route through, so a shape listed here must already have a
374
- * linter and a worker execution path — accepting a manifest we cannot run would
375
- * cut a revision that fails at run time instead of at authoring time.
376
- */
377
- export function isAnyWorkflowManifest(value) {
378
- return isWorkflowManifest(value) || isRecipeManifest(value) || isWorkflowGraphManifest(value);
379
- }
380
- export function compileWorkflowDefinition(// skipcq: JS-R1005 -- compiler validates workflow metadata, trigger, steps, branch targets, and defaults together.
381
- definition, options = {}) {
382
- const sourceHash = options.sourceHash
383
- ?? hashWorkflowSource(options.source ?? JSON.stringify(definition, workflowJsonReplacer));
384
- const manifest = {
385
- manifest_version: WORKFLOW_MANIFEST_VERSION,
386
- workflow: {
387
- id: definition.id,
388
- name: definition.name,
389
- ...(definition.status ? { status: definition.status } : {}),
390
- },
391
- ...(definition.specification ? { specification: definition.specification } : {}),
392
- ...(definition.trigger ? { trigger: definition.trigger } : {}),
393
- ...(definition.inputSchema ? { input_schema: definition.inputSchema } : {}),
394
- ...(definition.maxCredits != null ? { max_credits: definition.maxCredits } : {}),
395
- steps: definition.steps.map((step) => {
396
- if (step.kind === "transform") {
397
- return {
398
- kind: "transform",
399
- id: step.id,
400
- ...(step.description ? { description: step.description } : {}),
401
- run_source: serializeWorkflowFunction(step.run, `steps.${step.id}.run`),
402
- };
403
- }
404
- if (step.kind === "branch") {
405
- return {
406
- kind: "branch",
407
- id: step.id,
408
- ...(step.description ? { description: step.description } : {}),
409
- condition_source: serializeWorkflowFunction(step.condition, `steps.${step.id}.condition`),
410
- then_id: step.then,
411
- ...(step.else !== undefined ? { else_id: step.else } : {}),
412
- ...(step.join !== undefined ? { join_id: step.join } : {}),
413
- };
414
- }
415
- return {
416
- kind: "tool",
417
- id: step.id,
418
- ...(step.description ? { description: step.description } : {}),
419
- tool: step.tool,
420
- effect: step.effect ?? "external_read",
421
- ...(step.mode ? { mode: step.mode } : {}),
422
- ...(step.connectionId !== undefined ? { connection_id: step.connectionId } : {}),
423
- ...(step.maxCredits != null ? { max_credits: step.maxCredits } : {}),
424
- payload_source: serializeWorkflowFunction(step.payload, `steps.${step.id}.payload`),
425
- };
426
- }),
427
- source_hash: sourceHash,
428
- compiler_version: WORKFLOW_COMPILER_VERSION,
429
- created_at: (options.createdAt ?? new Date()).toISOString(),
430
- };
431
- assertWorkflowManifest(manifest);
432
- return manifest;
433
- }
434
- export function buildRecipeManifest(input) {
435
- const bundle = input.bundle;
436
- if (typeof bundle !== "string" || bundle.length === 0) {
437
- throw new Error("Recipe bundle source is required.");
438
- }
439
- const sourceHash = input.sourceHash ?? hashRecipeSource({
440
- bundle,
441
- ...(input.configurationSchema !== undefined
442
- ? { configurationSchema: input.configurationSchema }
443
- : {}),
444
- ...(input.configuration !== undefined ? { configuration: input.configuration } : {}),
445
- });
446
- const manifest = {
447
- manifest_version: WORKFLOW_MANIFEST_VERSION,
448
- workflow: {
449
- id: input.workflowId,
450
- name: input.workflowName,
451
- ...(input.status ? { status: input.status } : {}),
452
- },
453
- ...(input.trigger ? { trigger: input.trigger } : {}),
454
- ...(input.inputSchema ? { input_schema: input.inputSchema } : {}),
455
- ...(input.configurationSchema ? { configuration_schema: input.configurationSchema } : {}),
456
- ...(input.configuration ? { configuration: input.configuration } : {}),
457
- runtime: "durable",
458
- bundle,
459
- bundle_format: "esm",
460
- tools_used: Array.from(new Set((input.toolsUsed ?? []).filter(Boolean))).sort(),
461
- ...(input.visualPlan ? { visual_plan: input.visualPlan } : {}),
462
- ...(input.maxCredits != null ? { max_credits: input.maxCredits } : {}),
463
- source_hash: sourceHash,
464
- compiler_version: DURABLE_RECIPE_COMPILER_VERSION,
465
- created_at: (input.createdAt ?? new Date()).toISOString(),
466
- };
467
- return manifest;
468
- }
469
- /** Canonical executable identity shared by recipe compilers and repair paths. */
470
- export function hashRecipeSource(input) {
471
- // Preserve the historical bundle-only identity for recipes that have no
472
- // editable configuration. Configuration-bearing revisions include schema +
473
- // values because either can change the behavior of the same bundle source.
474
- if (input.configurationSchema === undefined && input.configuration === undefined) {
475
- return hashWorkflowSource(input.bundle);
476
- }
477
- return hashWorkflowSource(JSON.stringify({
478
- bundle: input.bundle,
479
- configuration_schema: input.configurationSchema ?? null,
480
- configuration: input.configuration ?? null,
481
- }, workflowJsonReplacer));
482
- }
483
- // Shared positive-finite validator for the optional per-run / per-step
484
- // max_credits caps (Gap 2). `undefined` is valid (no cap); anything else must be
485
- // a positive finite number, or lint rejects the manifest.
486
- // Exported for ./graph/lint.ts so the v2 graph linter enforces the same rule as
487
- // v1 rather than a second copy of it. Not part of the product surface.
488
- export function validateOptionalMaxCredits(value, path, add) {
489
- if (value === undefined)
490
- return;
491
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
492
- add(path, "invalid_max_credits", "max_credits must be a positive number.");
493
- }
494
- }
495
- export function lintWorkflowManifest(// skipcq: JS-R1005
496
- value, options = {}) {
497
- if (isWorkflowGraphManifest(value)) {
498
- return lintWorkflowGraphManifest(value, options);
499
- }
500
- if (isRecord(value)
501
- && typeof value.compiler_version === "string"
502
- && value.compiler_version.startsWith("oxygen-recipes-")) {
503
- return lintRecipeManifest(value, options);
504
- }
505
- const issues = [];
506
- const add = (path, code, message) => issues.push({ path, code, message });
507
- if (!isRecord(value)) {
508
- add("$", "invalid_manifest", "Workflow manifest must be an object.");
509
- return { ok: false, issues };
510
- }
511
- if (value.manifest_version !== WORKFLOW_MANIFEST_VERSION) {
512
- add("$.manifest_version", "invalid_manifest_version", "Workflow manifest version must be 1.");
513
- }
514
- const workflow = value.workflow;
515
- if (!isRecord(workflow)) {
516
- add("$.workflow", "missing_workflow", "Workflow metadata is required.");
517
- }
518
- else {
519
- if (!isNonEmptyString(workflow.id))
520
- add("$.workflow.id", "invalid_workflow_id", "Workflow id is required.");
521
- if (!isNonEmptyString(workflow.name))
522
- add("$.workflow.name", "invalid_workflow_name", "Workflow name is required.");
523
- if (workflow.status !== undefined && !isValidWorkflowStatus(workflow.status)) {
524
- add("$.workflow.status", "invalid_workflow_status", "Workflow status must be active or disabled.");
525
- }
526
- }
527
- if (value.trigger !== undefined)
528
- validateTrigger(value.trigger, "$.trigger", add);
529
- validateOptionalMaxCredits(value.max_credits, "$.max_credits", add);
530
- if (!Array.isArray(value.steps) || value.steps.length === 0) {
531
- add("$.steps", "missing_steps", "At least one workflow step is required.");
532
- }
533
- else {
534
- // Pre-pass: collect id → declared-index so branch targets can be
535
- // validated for existence + forward-only direction in the main pass.
536
- const idToIndex = new Map();
537
- value.steps.forEach((step, index) => {
538
- if (isRecord(step) && isNonEmptyString(step.id)) {
539
- if (!idToIndex.has(step.id))
540
- idToIndex.set(step.id, index);
541
- }
542
- });
543
- const ids = new Set();
544
- value.steps.forEach((step, index) => {
545
- const path = `$.steps.${index}`;
546
- if (!isRecord(step)) {
547
- add(path, "invalid_step", "Workflow step must be an object.");
548
- return;
549
- }
550
- if (!isNonEmptyString(step.id)) {
551
- add(`${path}.id`, "invalid_step_id", "Step id is required.");
552
- }
553
- else if (RESERVED_STEP_IDS.has(step.id)) {
554
- // Step ids become keys on the ctx.steps object the runtime assembles.
555
- // "__proto__" / "constructor" / "prototype" collide with JavaScript
556
- // object internals: assigning ctx.steps["__proto__"] = output hits the
557
- // prototype setter, so the output is silently dropped from step outputs
558
- // and unreadable downstream while the run still reports success. Reject
559
- // at authoring time instead of letting that data loss happen at runtime.
560
- add(`${path}.id`, "reserved_step_id", `Step id '${step.id}' is reserved (it collides with a JavaScript object key and would be dropped from step outputs). Choose another id.`);
561
- }
562
- else if (ids.has(step.id)) {
563
- add(`${path}.id`, "duplicate_step_id", `Step id '${step.id}' is duplicated.`);
564
- }
565
- else {
566
- ids.add(step.id);
567
- }
568
- if (step.kind === "transform") {
569
- if (!isNonEmptyString(step.run_source)) {
570
- add(`${path}.run_source`, "missing_step_code", "Transform step run_source is required.");
571
- }
572
- else {
573
- validatePureFunctionSource(step.run_source, `${path}.run_source`, add);
574
- }
575
- return;
576
- }
577
- if (step.kind === "tool") {
578
- if (!isNonEmptyString(step.tool)) {
579
- add(`${path}.tool`, "missing_tool", "Tool step tool id is required.");
580
- }
581
- else if (isWorkflowToolRejected(step.tool)) {
582
- add(`${path}.tool`, "unsupported_workflow_tool", `Tool '${step.tool}' is not allowed in workflow automations.`);
583
- }
584
- else if (options.isToolAllowed && !options.isToolAllowed(step.tool)) {
585
- add(`${path}.tool`, "tool_not_allowed", `Tool '${step.tool}' is not available for workflow automations.`);
586
- }
587
- if (!isNonEmptyString(step.payload_source)) {
588
- add(`${path}.payload_source`, "missing_step_code", "Tool step payload_source is required.");
589
- }
590
- else {
591
- validatePureFunctionSource(step.payload_source, `${path}.payload_source`, add);
592
- }
593
- if (step.effect !== "none"
594
- && step.effect !== "external_read"
595
- && step.effect !== "external_write") {
596
- add(`${path}.effect`, "invalid_step_effect", "Step effect is invalid.");
597
- }
598
- else if (isNonEmptyString(step.tool)) {
599
- // No resolver: skip the canonical cross-check rather than refuse.
600
- //
601
- // This function is reached by compileWorkflowDefinition, which the CLI
602
- // calls locally — and the CLI deliberately cannot classify effects,
603
- // because that is exactly the dependency removed from this package.
604
- // Refusing here would make `oxygen workflows` unable to compile any
605
- // manifest containing a tool step.
606
- //
607
- // Skipping is safe because this check is a CONVENIENCE, not the gate:
608
- // apply and the worker runtime both resolve the effect canonically and
609
- // both REFUSE what they cannot classify. The divergence v1.513.2 fixed
610
- // was lint disagreeing with apply, and that is addressed by the server
611
- // lint path always injecting resolveWorkflowToolEffect (see
612
- // apps/web/src/lib/workflows.ts lintHostedWorkflowManifest) — not by a
613
- // default inside this package.
614
- const resolveEffect = options.resolveToolEffect;
615
- if (resolveEffect) {
616
- const canonicalEffect = resolveEffect(step.tool);
617
- if (canonicalEffect !== null && step.effect !== canonicalEffect) {
618
- add(`${path}.effect`, "tool_effect_mismatch", `Tool '${step.tool}' has canonical effect '${canonicalEffect}', not '${String(step.effect)}'. Set step.effect to '${canonicalEffect}'.`);
619
- }
620
- }
621
- }
622
- if (step.mode !== undefined
623
- && step.mode !== "dry_run"
624
- && step.mode !== "live"
625
- && step.mode !== "smoke_test") {
626
- add(`${path}.mode`, "invalid_step_mode", "Step mode is invalid.");
627
- }
628
- if (step.connection_id !== undefined && !isNonEmptyString(step.connection_id)) {
629
- add(`${path}.connection_id`, "invalid_connection_id", "Tool step connection_id must be a non-empty string.");
630
- }
631
- validateOptionalMaxCredits(step.max_credits, `${path}.max_credits`, add);
632
- return;
633
- }
634
- if (step.kind === "branch") {
635
- if (!isNonEmptyString(step.condition_source)) {
636
- add(`${path}.condition_source`, "missing_step_code", "Branch step condition_source is required.");
637
- }
638
- else {
639
- validatePureFunctionSource(step.condition_source, `${path}.condition_source`, add);
640
- }
641
- validateBranchTarget(step.then_id, `${path}.then_id`, "then_id", index, idToIndex, add);
642
- if (step.else_id !== undefined) {
643
- validateBranchTarget(step.else_id, `${path}.else_id`, "else_id", index, idToIndex, add);
644
- }
645
- if (step.join_id !== undefined) {
646
- validateBranchTarget(step.join_id, `${path}.join_id`, "join_id", index, idToIndex, add);
647
- }
648
- return;
649
- }
650
- add(`${path}.kind`, "invalid_step_kind", "Step kind must be transform, tool, or branch.");
651
- });
652
- }
653
- if (!isNonEmptyString(value.source_hash)) {
654
- add("$.source_hash", "missing_source_hash", "Manifest source_hash is required.");
655
- }
656
- if (!isNonEmptyString(value.compiler_version)) {
657
- add("$.compiler_version", "missing_compiler_version", "Manifest compiler_version is required.");
658
- }
659
- return { ok: issues.length === 0, issues };
660
- }
661
- export function lintRecipeManifest(// skipcq: JS-R1005
662
- value, options = {}) {
663
- const issues = [];
664
- const add = (path, code, message) => issues.push({ path, code, message });
665
- if (!isRecord(value)) {
666
- add("$", "invalid_manifest", "Recipe manifest must be an object.");
667
- return { ok: false, issues };
668
- }
669
- if (value.manifest_version !== WORKFLOW_MANIFEST_VERSION) {
670
- add("$.manifest_version", "invalid_manifest_version", "Recipe manifest version must be 1.");
671
- }
672
- if (value.compiler_version !== DURABLE_RECIPE_COMPILER_VERSION) {
673
- add("$.compiler_version", "invalid_compiler_version", `Recipe manifest compiler_version must be '${DURABLE_RECIPE_COMPILER_VERSION}'.`);
674
- }
675
- const workflow = value.workflow;
676
- if (!isRecord(workflow)) {
677
- add("$.workflow", "missing_workflow", "Recipe metadata is required.");
678
- }
679
- else {
680
- if (!isNonEmptyString(workflow.id))
681
- add("$.workflow.id", "invalid_workflow_id", "Recipe id is required.");
682
- if (!isNonEmptyString(workflow.name))
683
- add("$.workflow.name", "invalid_workflow_name", "Recipe name is required.");
684
- if (workflow.status !== undefined && !isValidWorkflowStatus(workflow.status)) {
685
- add("$.workflow.status", "invalid_workflow_status", "Recipe status must be active or disabled.");
686
- }
687
- }
688
- if (value.trigger !== undefined)
689
- validateTrigger(value.trigger, "$.trigger", add);
690
- if (value.configuration_schema !== undefined && !isRecord(value.configuration_schema)) {
691
- add("$.configuration_schema", "invalid_configuration_schema", "Recipe configuration_schema must be a JSON Schema object.");
692
- }
693
- if (value.configuration !== undefined && !isRecord(value.configuration)) {
694
- add("$.configuration", "invalid_configuration", "Recipe configuration must be an object.");
695
- }
696
- else if (isRecord(value.configuration_schema)) {
697
- for (const issue of validateJsonSchemaValue(isRecord(value.configuration) ? value.configuration : {}, value.configuration_schema, "$.configuration")) {
698
- add(issue.path, issue.code, issue.message);
699
- }
700
- }
701
- if (!isNonEmptyString(value.bundle)) {
702
- add("$.bundle", "missing_bundle", "Recipe bundle is required.");
703
- }
704
- else if (Buffer.byteLength(value.bundle, "utf8") > MAX_RECIPE_BUNDLE_BYTES) {
705
- add("$.bundle", "bundle_too_large", "Recipe bundle exceeds the maximum allowed size.");
706
- }
707
- else {
708
- validateRecipeBundleSafety(value.bundle, "$.bundle", add);
709
- }
710
- if (value.bundle_format !== "esm") {
711
- add("$.bundle_format", "invalid_bundle_format", "Recipe bundle_format must be 'esm'.");
712
- }
713
- validateOptionalMaxCredits(value.max_credits, "$.max_credits", add);
714
- if (value.runtime !== "durable") {
715
- add("$.runtime", "invalid_recipe_runtime", "Durable recipe manifests must set runtime to durable.");
716
- }
717
- if (Array.isArray(value.tools_used)) {
718
- value.tools_used.forEach((toolId, index) => {
719
- if (typeof toolId !== "string" || !toolId.trim()) {
720
- add(`$.tools_used.${index}`, "invalid_tool_id", "Recipe tools_used entries must be non-empty strings.");
721
- }
722
- else if (isWorkflowToolRejected(toolId)) {
723
- add(`$.tools_used.${index}`, "unsupported_workflow_tool", `Tool '${toolId}' is not allowed in durable recipes.`);
724
- }
725
- else if (options.isToolAllowed && !options.isToolAllowed(toolId)) {
726
- add(`$.tools_used.${index}`, "tool_not_allowed", `Tool '${toolId}' is not available for durable recipes.`);
727
- }
728
- });
729
- }
730
- else if (value.tools_used !== undefined) {
731
- add("$.tools_used", "invalid_tools_used", "Recipe tools_used must be an array of tool ids.");
732
- }
733
- else {
734
- add("$.tools_used", "missing_recipe_tools", "Durable recipe manifests must declare tools_used (use [] for pure recipes).");
735
- }
736
- const declaredTools = Array.isArray(value.tools_used)
737
- ? new Set(value.tools_used.filter((toolId) => typeof toolId === "string" && toolId.trim().length > 0))
738
- : new Set();
739
- if (value.visual_plan !== undefined) {
740
- validateRecipeVisualPlan(value.visual_plan, "$.visual_plan", declaredTools, add);
741
- }
742
- if (!isNonEmptyString(value.source_hash)) {
743
- add("$.source_hash", "missing_source_hash", "Recipe manifest source_hash is required.");
744
- }
745
- return { ok: issues.length === 0, issues };
746
- }
747
- function validateRecipeVisualPlan(value, path, declaredTools, add) {
748
- if (!isRecord(value)) {
749
- add(path, "invalid_visual_plan", "Recipe visual_plan must be an object.");
750
- return;
751
- }
752
- if (value.version !== 1) {
753
- add(`${path}.version`, "invalid_visual_plan_version", "Recipe visual_plan version must be 1.");
754
- }
755
- if (!Array.isArray(value.steps)) {
756
- add(`${path}.steps`, "invalid_visual_plan_steps", "Recipe visual_plan steps must be an array.");
757
- return;
758
- }
759
- if (value.steps.length === 0) {
760
- add(`${path}.steps`, "missing_visual_plan_steps", "Recipe visual_plan must declare at least one step.");
761
- return;
762
- }
763
- const idToIndex = new Map();
764
- value.steps.forEach((step, index) => {
765
- if (isRecord(step) && isNonEmptyString(step.id) && !idToIndex.has(step.id)) {
766
- idToIndex.set(step.id, index);
767
- }
768
- });
769
- const ids = new Set();
770
- value.steps.forEach((step, index) => {
771
- const stepPath = `${path}.steps.${index}`;
772
- if (!isRecord(step)) {
773
- add(stepPath, "invalid_visual_plan_step", "Recipe visual_plan step must be an object.");
774
- return;
775
- }
776
- if (!isNonEmptyString(step.id)) {
777
- add(`${stepPath}.id`, "invalid_visual_plan_step_id", "Recipe visual_plan step id is required.");
778
- }
779
- else if (ids.has(step.id)) {
780
- add(`${stepPath}.id`, "duplicate_visual_plan_step_id", `Recipe visual_plan step id '${step.id}' is duplicated.`);
781
- }
782
- else {
783
- ids.add(step.id);
784
- }
785
- if (!isNonEmptyString(step.label)) {
786
- add(`${stepPath}.label`, "invalid_visual_plan_step_label", "Recipe visual_plan step label is required.");
787
- }
788
- if (step.description !== undefined && typeof step.description !== "string") {
789
- add(`${stepPath}.description`, "invalid_visual_plan_description", "Recipe visual_plan description must be a string.");
790
- }
791
- if (step.checkpoint_id !== undefined && !isNonEmptyString(step.checkpoint_id)) {
792
- add(`${stepPath}.checkpoint_id`, "invalid_visual_plan_checkpoint", "Recipe visual_plan checkpoint_id must be a non-empty string.");
793
- }
794
- if (step.kind === "tool") {
795
- if (!isNonEmptyString(step.tool)) {
796
- add(`${stepPath}.tool`, "missing_visual_plan_tool", "Recipe visual_plan tool step requires a tool id.");
797
- }
798
- else if (!declaredTools.has(step.tool)) {
799
- add(`${stepPath}.tool`, "visual_plan_tool_not_declared", `Recipe visual_plan tool '${step.tool}' must be present in tools_used.`);
800
- }
801
- if (step.effect !== undefined
802
- && step.effect !== "none"
803
- && step.effect !== "external_read"
804
- && step.effect !== "external_write") {
805
- add(`${stepPath}.effect`, "invalid_visual_plan_effect", "Recipe visual_plan tool effect is invalid.");
806
- }
807
- return;
808
- }
809
- if (step.kind === "step")
810
- return;
811
- if (step.kind === "branch") {
812
- if (step.condition_label !== undefined && typeof step.condition_label !== "string") {
813
- add(`${stepPath}.condition_label`, "invalid_visual_plan_condition", "Recipe visual_plan condition_label must be a string.");
814
- }
815
- validateBranchTarget(step.then_id, `${stepPath}.then_id`, "then_id", index, idToIndex, add);
816
- if (step.else_id !== undefined) {
817
- validateBranchTarget(step.else_id, `${stepPath}.else_id`, "else_id", index, idToIndex, add);
818
- }
819
- if (step.join_id !== undefined) {
820
- validateBranchTarget(step.join_id, `${stepPath}.join_id`, "join_id", index, idToIndex, add);
821
- }
822
- return;
823
- }
824
- add(`${stepPath}.kind`, "invalid_visual_plan_step_kind", "Recipe visual_plan step kind must be tool, step, or branch.");
825
- });
826
- }
827
- export function assertRecipeManifest(value, options = {}) {
828
- const result = lintRecipeManifest(value, options);
829
- if (result.ok)
830
- return;
831
- const first = result.issues[0];
832
- throw new Error(first ? `${first.code}: ${first.message}` : "Invalid recipe manifest.");
833
- }
834
- export function assertWorkflowManifest(value, options = {}) {
835
- const result = lintWorkflowManifest(value, options);
836
- if (result.ok)
837
- return;
838
- const first = result.issues[0];
839
- throw new Error(first ? `${first.code}: ${first.message}` : "Invalid workflow manifest.");
840
- }
841
- export function isBlueprint(value) {
842
- return isRecord(value)
843
- && value.blueprint_version === BLUEPRINT_VERSION
844
- && value.compiler_version === BLUEPRINT_COMPILER_VERSION;
845
- }
846
- const BLUEPRINT_REF_PATTERN = /^[a-z][a-z0-9_-]{0,79}$/;
847
- const BLUEPRINT_PROMPT_SLUG_PATTERN = /^[a-z][a-z0-9_-]{0,119}$/;
848
- export function lintBlueprint(// skipcq: JS-R1005
849
- value, options = {}) {
850
- const issues = [];
851
- const add = (path, code, message) => issues.push({ path, code, message });
852
- if (!isRecord(value)) {
853
- add("$", "invalid_blueprint", "Blueprint must be an object.");
854
- return { ok: false, issues };
855
- }
856
- if (value.blueprint_version !== BLUEPRINT_VERSION) {
857
- add("$.blueprint_version", "invalid_blueprint_version", "Blueprint version must be 1.");
858
- }
859
- if (value.compiler_version !== BLUEPRINT_COMPILER_VERSION) {
860
- add("$.compiler_version", "invalid_compiler_version", `Blueprint compiler_version must be '${BLUEPRINT_COMPILER_VERSION}'.`);
861
- }
862
- if (!isNonEmptyString(value.id))
863
- add("$.id", "invalid_blueprint_id", "Blueprint id is required.");
864
- if (!isNonEmptyString(value.name))
865
- add("$.name", "invalid_blueprint_name", "Blueprint name is required.");
866
- if (typeof value.summary !== "string")
867
- add("$.summary", "invalid_summary", "Blueprint summary must be a string.");
868
- if (!Array.isArray(value.tags)) {
869
- add("$.tags", "invalid_tags", "Blueprint tags must be an array of strings.");
870
- }
871
- if (!isNonEmptyString(value.exported_at)) {
872
- add("$.exported_at", "invalid_exported_at", "Blueprint exported_at must be an ISO timestamp.");
873
- }
874
- if (!isNonEmptyString(value.source_hash)) {
875
- add("$.source_hash", "missing_source_hash", "Blueprint source_hash is required.");
876
- }
877
- const tableRefs = new Set();
878
- if (!Array.isArray(value.tables)) {
879
- add("$.tables", "invalid_tables", "Blueprint tables must be an array.");
880
- }
881
- else {
882
- value.tables.forEach((table, index) => {
883
- const path = `$.tables.${index}`;
884
- if (!isRecord(table)) {
885
- add(path, "invalid_table", "Blueprint table must be an object.");
886
- return;
887
- }
888
- if (!isNonEmptyString(table.ref) || !BLUEPRINT_REF_PATTERN.test(table.ref)) {
889
- add(`${path}.ref`, "invalid_table_ref", "Blueprint table ref must be lowercase kebab/snake_case (a-z0-9_-).");
890
- }
891
- else {
892
- if (tableRefs.has(table.ref)) {
893
- add(`${path}.ref`, "duplicate_table_ref", `Blueprint table ref '${table.ref}' is duplicated.`);
894
- }
895
- tableRefs.add(table.ref);
896
- }
897
- if (!isNonEmptyString(table.name))
898
- add(`${path}.name`, "invalid_table_name", "Blueprint table name is required.");
899
- if (!Array.isArray(table.columns) || table.columns.length === 0) {
900
- add(`${path}.columns`, "invalid_table_columns", "Blueprint table must declare at least one column.");
901
- }
902
- else {
903
- table.columns.forEach((column, columnIndex) => {
904
- const columnPath = `${path}.columns.${columnIndex}`;
905
- if (!isRecord(column)) {
906
- add(columnPath, "invalid_column", "Blueprint column must be an object.");
907
- return;
908
- }
909
- if (!isNonEmptyString(column.label)) {
910
- add(`${columnPath}.label`, "invalid_column_label", "Blueprint column label is required.");
911
- }
912
- });
913
- }
914
- });
915
- }
916
- if (value.column_grafts !== undefined) {
917
- if (!Array.isArray(value.column_grafts)) {
918
- add("$.column_grafts", "invalid_column_grafts", "Blueprint column_grafts must be an array.");
919
- }
920
- else {
921
- value.column_grafts.forEach((graft, index) => {
922
- const path = `$.column_grafts.${index}`;
923
- if (!isRecord(graft)) {
924
- add(path, "invalid_column_graft", "Column graft must be an object.");
925
- return;
926
- }
927
- if (!isNonEmptyString(graft.table_ref) || !tableRefs.has(graft.table_ref)) {
928
- add(`${path}.table_ref`, "invalid_graft_ref", "Column graft table_ref must match a declared blueprint table ref.");
929
- }
930
- if (!isRecord(graft.column) || !isNonEmptyString(graft.column.label)) {
931
- add(`${path}.column`, "invalid_graft_column", "Column graft column must be an object with a label.");
932
- }
933
- });
934
- }
935
- }
936
- const promptSlugs = new Set();
937
- if (!Array.isArray(value.prompt_templates)) {
938
- add("$.prompt_templates", "invalid_prompt_templates", "Blueprint prompt_templates must be an array.");
939
- }
940
- else {
941
- value.prompt_templates.forEach((prompt, index) => {
942
- const path = `$.prompt_templates.${index}`;
943
- if (!isRecord(prompt)) {
944
- add(path, "invalid_prompt", "Blueprint prompt must be an object.");
945
- return;
946
- }
947
- if (!isNonEmptyString(prompt.slug) || !BLUEPRINT_PROMPT_SLUG_PATTERN.test(prompt.slug)) {
948
- add(`${path}.slug`, "invalid_prompt_slug", "Prompt slug must be lowercase kebab/snake_case (a-z0-9_-).");
949
- }
950
- else {
951
- if (promptSlugs.has(prompt.slug)) {
952
- add(`${path}.slug`, "duplicate_prompt_slug", `Prompt slug '${prompt.slug}' is duplicated.`);
953
- }
954
- promptSlugs.add(prompt.slug);
955
- }
956
- if (!isNonEmptyString(prompt.name))
957
- add(`${path}.name`, "invalid_prompt_name", "Prompt name is required.");
958
- if (!isNonEmptyString(prompt.body))
959
- add(`${path}.body`, "invalid_prompt_body", "Prompt body is required.");
960
- if (prompt.kind !== "ai_column_system" && prompt.kind !== "scoring_rubric" && prompt.kind !== "other") {
961
- add(`${path}.kind`, "invalid_prompt_kind", "Prompt kind must be ai_column_system, scoring_rubric, or other.");
962
- }
963
- });
964
- }
965
- if (!Array.isArray(value.workflows)) {
966
- add("$.workflows", "invalid_workflows", "Blueprint workflows must be an array.");
967
- }
968
- else if (value.workflows.length === 0) {
969
- add("$.workflows", "missing_workflows", "Blueprint must include at least one workflow.");
970
- }
971
- else {
972
- value.workflows.forEach((entry, index) => {
973
- const path = `$.workflows.${index}`;
974
- if (!isRecord(entry)) {
975
- add(path, "invalid_workflow_entry", "Workflow entry must be an object.");
976
- return;
977
- }
978
- const manifest = entry.manifest;
979
- const manifestResult = lintWorkflowManifest(manifest, options);
980
- if (!manifestResult.ok) {
981
- manifestResult.issues.forEach((issue) => {
982
- add(`${path}.manifest${issue.path.replace(/^\$/, "")}`, issue.code, issue.message);
983
- });
984
- }
985
- if (entry.table_refs !== undefined && !isRecord(entry.table_refs)) {
986
- add(`${path}.table_refs`, "invalid_workflow_table_refs", "Workflow table_refs must be an object map.");
987
- }
988
- else if (isRecord(entry.table_refs)) {
989
- for (const refName of Object.keys(entry.table_refs)) {
990
- if (!tableRefs.has(refName)) {
991
- add(`${path}.table_refs.${refName}`, "unknown_workflow_table_ref", `Workflow references table ref '${refName}' which is not declared on this blueprint.`);
992
- }
993
- }
994
- }
995
- if (entry.prompt_template_slugs !== undefined) {
996
- if (!Array.isArray(entry.prompt_template_slugs)) {
997
- add(`${path}.prompt_template_slugs`, "invalid_prompt_slug_list", "Workflow prompt_template_slugs must be an array of strings.");
998
- }
999
- else {
1000
- entry.prompt_template_slugs.forEach((slug, slugIndex) => {
1001
- if (!isNonEmptyString(slug)) {
1002
- add(`${path}.prompt_template_slugs.${slugIndex}`, "invalid_prompt_slug", "Workflow prompt slug references must be non-empty strings.");
1003
- }
1004
- else if (!promptSlugs.has(slug)) {
1005
- add(`${path}.prompt_template_slugs.${slugIndex}`, "unknown_prompt_slug", `Workflow references prompt slug '${slug}' which is not declared on this blueprint.`);
1006
- }
1007
- });
1008
- }
1009
- }
1010
- });
1011
- }
1012
- const requires = value.requires;
1013
- if (!isRecord(requires)) {
1014
- add("$.requires", "invalid_requires", "Blueprint requires must be an object.");
1015
- }
1016
- else {
1017
- if (requires.integrations !== undefined) {
1018
- if (!Array.isArray(requires.integrations)) {
1019
- add("$.requires.integrations", "invalid_requires_integrations", "Blueprint requires.integrations must be an array.");
1020
- }
1021
- else {
1022
- requires.integrations.forEach((entry, index) => {
1023
- const path = `$.requires.integrations.${index}`;
1024
- if (!isRecord(entry)) {
1025
- add(path, "invalid_integration", "Integration requirement must be an object.");
1026
- return;
1027
- }
1028
- if (!isNonEmptyString(entry.kind)) {
1029
- add(`${path}.kind`, "invalid_integration_kind", "Integration requirement kind is required (e.g. 'instantly', 'apollo').");
1030
- }
1031
- });
1032
- }
1033
- }
1034
- if (requires.context_keys !== undefined && !Array.isArray(requires.context_keys)) {
1035
- add("$.requires.context_keys", "invalid_context_keys", "Blueprint requires.context_keys must be an array of strings.");
1036
- }
1037
- }
1038
- return { ok: issues.length === 0, issues };
1039
- }
1040
- export function assertBlueprint(value, options = {}) {
1041
- const result = lintBlueprint(value, options);
1042
- if (result.ok)
1043
- return;
1044
- const first = result.issues[0];
1045
- throw new Error(first ? `${first.code}: ${first.message}` : "Invalid blueprint.");
1046
- }
1047
- export function buildBlueprint(input) {
1048
- const draft = {
1049
- blueprint_version: BLUEPRINT_VERSION,
1050
- id: input.id,
1051
- name: input.name,
1052
- summary: input.summary ?? "",
1053
- tags: Array.isArray(input.tags) ? Array.from(new Set(input.tags.filter(Boolean))) : [],
1054
- ...(input.audience ? { audience: input.audience } : {}),
1055
- requires: input.requires ?? {},
1056
- ...(input.inputSchema ? { input_schema: input.inputSchema } : {}),
1057
- tables: input.tables,
1058
- ...(input.columnGrafts && input.columnGrafts.length > 0 ? { column_grafts: input.columnGrafts } : {}),
1059
- prompt_templates: input.promptTemplates ?? [],
1060
- workflows: input.workflows,
1061
- exported_at: (input.exportedAt ?? new Date()).toISOString(),
1062
- ...(input.exportedFrom ? { exported_from: input.exportedFrom } : {}),
1063
- compiler_version: BLUEPRINT_COMPILER_VERSION,
1064
- };
1065
- const sourceHash = input.sourceHash
1066
- ?? hashWorkflowSource(JSON.stringify(draft, workflowJsonReplacer));
1067
- return { ...draft, source_hash: sourceHash };
1068
- }
1069
- export function validateJsonSchemaValue(value, schema, path = "$", maxIssues = Number.POSITIVE_INFINITY, maxVisits = Number.POSITIVE_INFINITY) {
1070
- if (!schema || typeof schema !== "object" || Array.isArray(schema))
1071
- return [];
1072
- const issues = [];
1073
- const budget = {
1074
- visits: 0,
1075
- maximum: Math.max(1, Math.floor(maxVisits)),
1076
- exhausted: false,
1077
- };
1078
- validateJsonSchemaValueInto(value, schema, path, issues, Math.max(1, Math.floor(maxIssues)), budget);
1079
- if (budget.exhausted) {
1080
- return [{
1081
- path,
1082
- code: "schema_validation_too_complex",
1083
- message: `${path} exceeded the JSON Schema validation work limit.`,
1084
- }];
1085
- }
1086
- return issues;
1087
- }
1088
- function consumeJsonSchemaValidationBudget(budget, amount = 1) {
1089
- if (budget.exhausted)
1090
- return false;
1091
- budget.visits += amount;
1092
- if (budget.visits <= budget.maximum)
1093
- return true;
1094
- budget.exhausted = true;
1095
- return false;
1096
- }
1097
- export function assertRecipeBundleSafe(bundle) {
1098
- const issues = lintRecipeBundleSafety(bundle, "$.bundle");
1099
- const first = issues[0];
1100
- if (first)
1101
- throw new Error(`${first.code}: ${first.message}`);
1102
- }
1103
- export function lintRecipeBundleSafety(bundle, path = "$.bundle") {
1104
- const issues = [];
1105
- validateRecipeBundleSafety(bundle, path, (issuePath, code, message) => {
1106
- issues.push({ path: issuePath, code, message });
1107
- });
1108
- return issues;
1109
- }
1110
- /** Comment/string-aware author feedback for the stricter oxygen-js-v1 runtime. */
1111
- export function lintWorkflowCodeSourceSafety(source, path = "$.source") {
1112
- const issues = [];
1113
- if (!source.trim()) {
1114
- issues.push({ path, code: "empty_function_source", message: "Typed code source cannot be empty." });
1115
- return issues;
1116
- }
1117
- const scan = stripCommentsAndStrings(source);
1118
- if (scan.ambiguousSlash) {
1119
- return [{ path, code: "unsafe_code_source", message: "Typed code source has an ambiguous slash after a brace. Parenthesize the expression or separate statements with a semicolon." }];
1120
- }
1121
- const scannable = scan.source;
1122
- for (const entry of UNSAFE_WORKFLOW_CODE_SOURCE_PATTERNS) {
1123
- if (!entry.pattern.test(scannable))
1124
- continue;
1125
- issues.push({
1126
- path,
1127
- code: "unsafe_code_source",
1128
- message: `Typed code source cannot reference '${entry.token}'. Bind deterministic JSON inputs and use explicit Tool nodes for capabilities.`,
1129
- });
1130
- break;
1131
- }
1132
- return issues;
1133
- }
1134
- /**
1135
- * The ceiling of the legacy synchronous `node:vm` path below. It stays at 10 s
1136
- * (and its callers pass 1 s) when the typed Code node rose to 30 s (repricing
1137
- * 2026-09, decision L4.3; proposal P-49): this path runs on the worker's own
1138
- * event loop, so a long synchronous script would stall every other job and its
1139
- * queue lock renewal. The typed Code node runs in a separate microVM instead.
1140
- */
1141
- export const PURE_WORKFLOW_FUNCTION_MAX_TIMEOUT_MS = 10_000;
1142
- export async function runPureWorkflowFunction(input) {
1143
- const timeoutMs = Math.max(WORKFLOW_CODE_V1_MIN_TIMEOUT_MS, Math.min(input.timeoutMs ?? WORKFLOW_CODE_V1_DEFAULT_TIMEOUT_MS, PURE_WORKFLOW_FUNCTION_MAX_TIMEOUT_MS));
1144
- const maxOutputBytes = Math.max(WORKFLOW_CODE_V1_MIN_OUTPUT_BYTES, Math.min(input.maxOutputBytes ?? WORKFLOW_CODE_V1_DEFAULT_OUTPUT_BYTES, WORKFLOW_CODE_V1_MAX_OUTPUT_BYTES));
1145
- const issues = [];
1146
- validatePureFunctionSource(input.source, "$.source", (path, code, message) => {
1147
- issues.push({ path, code, message });
1148
- });
1149
- if (issues.length > 0) {
1150
- const first = issues[0];
1151
- throw new Error(first ? `${first.code}: ${first.message}` : "Invalid workflow function source.");
1152
- }
1153
- // Cross the host/sandbox boundary as a JSON string, then parse INSIDE the
1154
- // vm context. If we passed the host object directly its prototype chain
1155
- // would point at the host's Object/Function, and the regex token blacklist
1156
- // is trivially bypassed (e.g. "con"+"structor") to reach
1157
- // __oxygen_context.constructor.constructor === host Function — which is
1158
- // not affected by the new context's codeGeneration setting and yields
1159
- // worker-process RCE. Parsing inside the context rebinds the prototype to
1160
- // the sandboxed Object, so the same walk reaches the sandboxed Function,
1161
- // which then trips contextCodeGeneration.strings=false below.
1162
- const context = toJsonValue(input.context, "context");
1163
- const contextJson = JSON.stringify(context);
1164
- const sandbox = Object.create(null);
1165
- sandbox.__oxygen_context_json = contextJson;
1166
- // Shadow dangerous globals on the sandbox surface. Defense-in-depth: the
1167
- // load-bearing block is contextCodeGeneration; this just removes the
1168
- // obvious top-level handles.
1169
- sandbox.Function = undefined;
1170
- sandbox.eval = undefined;
1171
- sandbox.setTimeout = undefined;
1172
- sandbox.setInterval = undefined;
1173
- sandbox.setImmediate = undefined;
1174
- sandbox.queueMicrotask = undefined;
1175
- sandbox.WebAssembly = undefined;
1176
- const script = new vm.Script('"use strict";\n'
1177
- + 'const __oxygen_context = JSON.parse(__oxygen_context_json);\n'
1178
- + `const __oxygen_fn = (${input.source});\n`
1179
- + '__oxygen_fn(__oxygen_context);');
1180
- // Disable dynamic code generation in the sandboxed context. Combined with
1181
- // the JSON re-parse above, this means every prototype-walk path to
1182
- // Function — direct, via context.constructor.constructor, or any other
1183
- // reachable Function instance — throws EvalError when called with source.
1184
- try {
1185
- const result = script.runInNewContext(sandbox, {
1186
- timeout: timeoutMs,
1187
- contextCodeGeneration: {
1188
- strings: false,
1189
- wasm: false,
1190
- },
1191
- });
1192
- const resolved = isPromiseLike(result)
1193
- ? await withTimeout(result, timeoutMs)
1194
- : result;
1195
- return enforceJsonOutput(resolved, maxOutputBytes);
1196
- }
1197
- catch (error) {
1198
- throw normalizeSandboxThrow(error);
1199
- }
1200
- }
1201
- // A throw from inside the vm sandbox is constructed with the sandbox realm's
1202
- // Error, so `error instanceof Error` is false in the host worker — and
1203
- // serializeOxygenError then drops the message and reports a generic
1204
- // "Workflow run failed.", leaving a failing transform/branch undebuggable.
1205
- // Reconstruct a host-realm Error preserving the user's message/name. Host-realm
1206
- // throws (vm timeout, enforceJsonOutput's workflow_output_too_large) already
1207
- // pass instanceof and are returned unchanged.
1208
- function normalizeSandboxThrow(error) {
1209
- if (error instanceof Error)
1210
- return error;
1211
- if (error && typeof error === "object") {
1212
- const record = error;
1213
- const message = typeof record.message === "string" && record.message
1214
- ? record.message
1215
- : "Workflow function threw.";
1216
- const normalized = new Error(message);
1217
- if (typeof record.name === "string" && record.name)
1218
- normalized.name = record.name;
1219
- return normalized;
1220
- }
1221
- return new Error(typeof error === "string" && error ? error : "Workflow function threw a non-error value.");
1222
- }
1223
- export const workflowApplySchema = {
1224
- $schema: "https://json-schema.org/draft/2020-12/schema",
1225
- title: "OXYGEN Workflow Apply Input",
1226
- type: "object",
1227
- additionalProperties: false,
1228
- properties: {
1229
- manifest: { $ref: "#/$defs/manifest" },
1230
- approved: {
1231
- type: "boolean",
1232
- description: "Standing tool authorization for this exact autonomous revision.",
1233
- },
1234
- max_credits: {
1235
- type: "number",
1236
- exclusiveMinimum: 0,
1237
- description: "Hard credit ceiling for each autonomous delivery.",
1238
- },
1239
- publish: {
1240
- type: "boolean",
1241
- description: "False saves an editable draft revision without publishing it. Defaults to true.",
1242
- },
1243
- },
1244
- required: ["manifest"],
1245
- $defs: {
1246
- manifest: { type: "object", additionalProperties: true },
1247
- },
1248
- };
1249
- export const workflowCallSchema = {
1250
- $schema: "https://json-schema.org/draft/2020-12/schema",
1251
- title: "OXYGEN Workflow Call Input",
1252
- type: "object",
1253
- additionalProperties: false,
1254
- properties: {
1255
- workflow: { type: "string" },
1256
- workflow_id: { type: "string" },
1257
- workflow_name: { type: "string" },
1258
- input: { type: "object", additionalProperties: true },
1259
- mode: { enum: ["dry_run", "live", "smoke_test"] },
1260
- idempotency_key: { type: "string" },
1261
- revision_version: {
1262
- type: "integer",
1263
- minimum: 1,
1264
- description: "Exact saved revision to run. Historical revisions are non-live only.",
1265
- },
1266
- approved: {
1267
- type: "boolean",
1268
- description: "Explicit approval required for live calls.",
1269
- },
1270
- max_credits: {
1271
- type: "number",
1272
- exclusiveMinimum: 0,
1273
- description: "Positive credit ceiling required for live calls.",
1274
- },
1275
- },
1276
- required: ["mode"],
1277
- };
1278
- export const workflowEventEmitSchema = {
1279
- $schema: "https://json-schema.org/draft/2020-12/schema",
1280
- title: "OXYGEN Workflow Event Emit Input",
1281
- type: "object",
1282
- additionalProperties: false,
1283
- properties: {
1284
- source: { type: "string" },
1285
- event: { type: "string" },
1286
- payload: { type: "object", additionalProperties: true },
1287
- raw_payload: { type: "object", additionalProperties: true },
1288
- headers: { type: "object", additionalProperties: true },
1289
- external_event_id: { type: "string" },
1290
- idempotency_key: { type: "string" },
1291
- mode: { enum: ["dry_run", "live", "smoke_test"] },
1292
- approved: {
1293
- type: "boolean",
1294
- description: "Explicit approval required when event deliveries run live.",
1295
- },
1296
- max_credits: {
1297
- type: "number",
1298
- exclusiveMinimum: 0,
1299
- description: "Positive per-delivery credit ceiling required for live event emission.",
1300
- },
1301
- },
1302
- required: ["source", "event", "payload", "mode"],
1303
- };
1304
- export const workflowTriggerSchema = {
1305
- $schema: "https://json-schema.org/draft/2020-12/schema",
1306
- title: "OXYGEN Workflow Trigger",
1307
- type: "object",
1308
- additionalProperties: false,
1309
- properties: {
1310
- type: { enum: ["api", "webhook", "cron", "event"] },
1311
- trigger_id: { type: "string" },
1312
- trigger_name: { type: ["string", "null"] },
1313
- secret_required: { type: "boolean" },
1314
- idempotency_key_path: { type: ["string", "null"] },
1315
- cron: { type: "string" },
1316
- timezone: { type: ["string", "null"] },
1317
- source: { type: "string" },
1318
- event: { type: "string" },
1319
- filters: {
1320
- type: "array",
1321
- items: {
1322
- type: "object",
1323
- additionalProperties: false,
1324
- properties: {
1325
- path: { type: "string" },
1326
- op: { enum: ["eq", "neq", "exists", "not_exists"] },
1327
- value: {},
1328
- },
1329
- required: ["path", "op"],
1330
- },
1331
- },
1332
- status: { enum: ["active", "disabled"] },
1333
- },
1334
- required: ["type"],
1335
- };
1336
- export const workflowManifestSchema = {
1337
- $schema: "https://json-schema.org/draft/2020-12/schema",
1338
- title: "OXYGEN Workflow Manifest",
1339
- type: "object",
1340
- additionalProperties: true,
1341
- required: ["manifest_version", "workflow", "steps", "source_hash", "compiler_version"],
1342
- };
1343
- export function getWorkflowSchema(subject = "apply") {
1344
- const schemas = {
1345
- apply: workflowApplySchema,
1346
- call: workflowCallSchema,
1347
- event: workflowEventEmitSchema,
1348
- trigger: workflowTriggerSchema,
1349
- manifest: workflowManifestSchema,
1350
- };
1351
- if (subject === "all")
1352
- return { schemas };
1353
- return schemas[subject];
1354
- }
1355
- function validateJsonSchemaValueInto(// skipcq: JS-R1005
1356
- value, schema, path, issues, maxIssues, budget) {
1357
- if (issues.length >= maxIssues || budget.exhausted)
1358
- return;
1359
- if (!consumeJsonSchemaValidationBudget(budget))
1360
- return;
1361
- const startCount = issues.length;
1362
- if (schema.const !== undefined && !jsonEqual(value, schema.const, budget)) {
1363
- addJsonSchemaValidationIssue(issues, maxIssues, {
1364
- path,
1365
- code: "schema_const_mismatch",
1366
- message: `${path} must equal the schema const value.`,
1367
- });
1368
- return;
1369
- }
1370
- if (Array.isArray(schema.enum)
1371
- && schema.enum.length > 0
1372
- && !schema.enum.some((entry) => budget.exhausted || jsonEqual(value, entry, budget))) {
1373
- addJsonSchemaValidationIssue(issues, maxIssues, {
1374
- path,
1375
- code: "schema_enum_mismatch",
1376
- message: `${path} must be one of the allowed values.`,
1377
- });
1378
- return;
1379
- }
1380
- if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
1381
- const matched = schema.anyOf.some((candidate) => {
1382
- if (budget.exhausted)
1383
- return true;
1384
- const candidateIssues = [];
1385
- validateJsonSchemaValueInto(value, candidate, path, candidateIssues, 1, budget);
1386
- return candidateIssues.length === 0;
1387
- });
1388
- if (!matched) {
1389
- addJsonSchemaValidationIssue(issues, maxIssues, {
1390
- path,
1391
- code: "schema_any_of_mismatch",
1392
- message: `${path} must match at least one allowed schema.`,
1393
- });
1394
- return;
1395
- }
1396
- // A matching anyOf does not erase sibling constraints. JSON Schema applies
1397
- // them together; returning here silently skipped object/array rules.
1398
- }
1399
- const expectedTypes = normalizeSchemaTypes(schema);
1400
- if (expectedTypes.length > 0 && !expectedTypes.some((type) => matchesJsonSchemaType(value, type))) {
1401
- addJsonSchemaValidationIssue(issues, maxIssues, {
1402
- path,
1403
- code: "schema_type_mismatch",
1404
- message: `${path} must be ${formatSchemaTypes(expectedTypes)}.`,
1405
- });
1406
- return;
1407
- }
1408
- const shouldValidateObject = expectedTypes.includes("object")
1409
- || Boolean(schema.properties)
1410
- || Array.isArray(schema.required)
1411
- || schema.additionalProperties !== undefined;
1412
- if (shouldValidateObject && isRecord(value)) {
1413
- const properties = schema.properties ?? {};
1414
- for (const requiredKey of schema.required ?? []) {
1415
- if (issues.length >= maxIssues || budget.exhausted)
1416
- break;
1417
- if (!consumeJsonSchemaValidationBudget(budget))
1418
- break;
1419
- if (!Object.hasOwn(value, requiredKey) || value[requiredKey] === undefined) {
1420
- addJsonSchemaValidationIssue(issues, maxIssues, {
1421
- path: `${path}.${requiredKey}`,
1422
- code: "schema_required",
1423
- message: `${path}.${requiredKey} is required.`,
1424
- });
1425
- }
1426
- }
1427
- // Object enumeration is real host work. Charge every key before iterating so
1428
- // a large output tested against many `anyOf` object candidates cannot rescan
1429
- // the same object hundreds of times outside the sandbox timeout.
1430
- const valueKeys = Object.keys(value);
1431
- if (!consumeJsonSchemaValidationBudget(budget, valueKeys.length))
1432
- return;
1433
- for (const key of valueKeys) {
1434
- if (issues.length >= maxIssues || budget.exhausted)
1435
- break;
1436
- const propertyValue = value[key];
1437
- const propertySchema = Object.hasOwn(properties, key) ? properties[key] : undefined;
1438
- if (isRecord(propertySchema)) {
1439
- validateJsonSchemaValueInto(propertyValue, propertySchema, `${path}.${key}`, issues, maxIssues, budget);
1440
- }
1441
- else if (schema.additionalProperties === false) {
1442
- addJsonSchemaValidationIssue(issues, maxIssues, {
1443
- path: `${path}.${key}`,
1444
- code: "schema_additional_property",
1445
- message: `${path}.${key} is not allowed.`,
1446
- });
1447
- }
1448
- else if (isRecord(schema.additionalProperties)) {
1449
- validateJsonSchemaValueInto(propertyValue, schema.additionalProperties, `${path}.${key}`, issues, maxIssues, budget);
1450
- }
1451
- }
1452
- }
1453
- const shouldValidateArray = expectedTypes.includes("array") || Boolean(schema.items);
1454
- if (shouldValidateArray && Array.isArray(value) && schema.items) {
1455
- for (let index = 0; index < value.length && issues.length < maxIssues && !budget.exhausted; index += 1) {
1456
- validateJsonSchemaValueInto(value[index], schema.items, `${path}.${index}`, issues, maxIssues, budget);
1457
- }
1458
- }
1459
- if (issues.length > startCount)
1460
- return;
1461
- }
1462
- function addJsonSchemaValidationIssue(issues, maxIssues, issue) {
1463
- if (issues.length < maxIssues)
1464
- issues.push(issue);
1465
- }
1466
- function normalizeSchemaTypes(schema) {
1467
- if (Array.isArray(schema.type))
1468
- return schema.type.filter((entry) => typeof entry === "string");
1469
- if (typeof schema.type === "string")
1470
- return [schema.type];
1471
- if (schema.properties || schema.required || schema.additionalProperties !== undefined)
1472
- return ["object"];
1473
- if (schema.items)
1474
- return ["array"];
1475
- return [];
1476
- }
1477
- function matchesJsonSchemaType(value, type) {
1478
- switch (type) {
1479
- case "array":
1480
- return Array.isArray(value);
1481
- case "boolean":
1482
- return typeof value === "boolean";
1483
- case "integer":
1484
- return typeof value === "number" && Number.isInteger(value);
1485
- case "null":
1486
- return value === null;
1487
- case "number":
1488
- return typeof value === "number" && Number.isFinite(value);
1489
- case "object":
1490
- return isRecord(value);
1491
- case "string":
1492
- return typeof value === "string";
1493
- default:
1494
- return true;
1495
- }
1496
- }
1497
- function formatSchemaTypes(types) {
1498
- if (types.length === 1)
1499
- return `a ${types[0]}`;
1500
- return types.map((type) => type === "null" ? "null" : `a ${type}`).join(" or ");
1501
- }
1502
- function jsonEqual(left, right, budget) {
1503
- return jsonEqualInto(left, right, new WeakMap(), budget);
1504
- }
1505
- function jsonEqualInto(left, right, seen, budget) {
1506
- if (!consumeJsonSchemaValidationBudget(budget))
1507
- return false;
1508
- if (left === right)
1509
- return true;
1510
- if (left === null || right === null || typeof left !== typeof right)
1511
- return false;
1512
- if (typeof left !== "object" || typeof right !== "object")
1513
- return false;
1514
- const leftArray = Array.isArray(left);
1515
- if (leftArray !== Array.isArray(right))
1516
- return false;
1517
- const compared = seen.get(left);
1518
- if (compared?.has(right))
1519
- return true;
1520
- if (compared)
1521
- compared.add(right);
1522
- else
1523
- seen.set(left, new WeakSet([right]));
1524
- if (leftArray) {
1525
- const rightArray = right;
1526
- return left.length === rightArray.length
1527
- && left.every((entry, index) => !budget.exhausted && jsonEqualInto(entry, rightArray[index], seen, budget));
1528
- }
1529
- const leftRecord = left;
1530
- const rightRecord = right;
1531
- const leftKeys = Object.keys(leftRecord);
1532
- const rightKeys = Object.keys(rightRecord);
1533
- if (!consumeJsonSchemaValidationBudget(budget, leftKeys.length + rightKeys.length))
1534
- return false;
1535
- return leftKeys.length === rightKeys.length
1536
- && leftKeys.every((key) => Object.hasOwn(rightRecord, key)
1537
- && !budget.exhausted
1538
- && jsonEqualInto(leftRecord[key], rightRecord[key], seen, budget));
1539
- }
1540
- // Optional idempotency_key_path (webhook + event triggers): when present it must
1541
- // be a non-empty string. `label` distinguishes the trigger type in the message.
1542
- function validateOptionalIdempotencyKeyPath(value, path, label, add) {
1543
- if (value !== undefined && value !== null && !isNonEmptyString(value)) {
1544
- add(`${path}.idempotency_key_path`, "invalid_idempotency_key_path", `${label} idempotency path is invalid.`);
1545
- }
1546
- }
1547
- // Exported for ./graph/lint.ts — see validateOptionalMaxCredits above.
1548
- export function validateTrigger(// skipcq: JS-R1005
1549
- value, path, add) {
1550
- if (!isRecord(value)) {
1551
- add(path, "invalid_trigger", "Workflow trigger must be an object.");
1552
- return;
1553
- }
1554
- if (value.status !== undefined && !isValidWorkflowStatus(value.status)) {
1555
- add(`${path}.status`, "invalid_trigger_status", "Trigger status must be active or disabled.");
1556
- }
1557
- if (value.type === "api")
1558
- return;
1559
- if (value.type === "webhook") {
1560
- if (!isNonEmptyString(value.trigger_id)) {
1561
- add(`${path}.trigger_id`, "invalid_trigger_id", "Webhook trigger_id is required.");
1562
- }
1563
- validateOptionalIdempotencyKeyPath(value.idempotency_key_path, path, "Webhook", add);
1564
- return;
1565
- }
1566
- if (value.type === "cron") {
1567
- if (!isNonEmptyString(value.cron)) {
1568
- add(`${path}.cron`, "invalid_cron", "Cron trigger cron expression is required.");
1569
- }
1570
- else {
1571
- try {
1572
- parseCronSchedule(value.cron);
1573
- }
1574
- catch (error) {
1575
- add(`${path}.cron`, "invalid_cron", error instanceof Error ? error.message : "Cron expression is invalid.");
1576
- }
1577
- }
1578
- // Validate the timezone here so an unknown zone fails lint with a typed
1579
- // issue, rather than passing lint and blowing up at apply time (the
1580
- // scheduler's Intl.DateTimeFormat throws on an unknown zone). null/empty
1581
- // are allowed — the scheduler falls back to UTC.
1582
- const { timezone } = value;
1583
- if (timezone !== undefined && timezone !== null) {
1584
- if (typeof timezone !== "string") {
1585
- add(`${path}.timezone`, "invalid_timezone", "Cron trigger timezone must be a string IANA timezone.");
1586
- }
1587
- else if (timezone.trim() && !isValidTimeZone(timezone.trim())) {
1588
- add(`${path}.timezone`, "invalid_timezone", `Unknown timezone '${timezone}'. Use an IANA timezone such as 'America/New_York' or 'UTC'.`);
1589
- }
1590
- }
1591
- return;
1592
- }
1593
- if (value.type === "event") {
1594
- if (!isNonEmptyString(value.source)) {
1595
- add(`${path}.source`, "invalid_event_source", "Event trigger source is required.");
1596
- }
1597
- if (!isNonEmptyString(value.event)) {
1598
- add(`${path}.event`, "invalid_event_type", "Event trigger event is required.");
1599
- }
1600
- validateOptionalIdempotencyKeyPath(value.idempotency_key_path, path, "Event", add);
1601
- if (value.filters !== undefined)
1602
- validateEventFilters(value.filters, `${path}.filters`, add);
1603
- return;
1604
- }
1605
- add(`${path}.type`, "invalid_trigger_type", "Trigger type must be api, webhook, cron, or event.");
1606
- }
1607
- function validateEventFilters(value, path, add) {
1608
- if (!Array.isArray(value)) {
1609
- add(path, "invalid_event_filters", "Event trigger filters must be an array.");
1610
- return;
1611
- }
1612
- value.forEach((filter, index) => {
1613
- const filterPath = `${path}.${index}`;
1614
- if (!isRecord(filter)) {
1615
- add(filterPath, "invalid_event_filter", "Event trigger filter must be an object.");
1616
- return;
1617
- }
1618
- if (!isNonEmptyString(filter.path)) {
1619
- add(`${filterPath}.path`, "invalid_event_filter_path", "Event filter path is required.");
1620
- }
1621
- if (filter.op !== "eq"
1622
- && filter.op !== "neq"
1623
- && filter.op !== "exists"
1624
- && filter.op !== "not_exists") {
1625
- add(`${filterPath}.op`, "invalid_event_filter_op", "Event filter op is invalid.");
1626
- }
1627
- if ((filter.op === "eq" || filter.op === "neq") && !Object.hasOwn(filter, "value")) {
1628
- add(`${filterPath}.value`, "missing_event_filter_value", "Event eq/neq filters require a value.");
1629
- }
1630
- });
1631
- }
1632
- function serializeWorkflowFunction(fn, path) {
1633
- if (typeof fn !== "function") {
1634
- throw new Error(`${path} must be a function.`);
1635
- }
1636
- const source = Function.prototype.toString.call(fn);
1637
- const issues = [];
1638
- validatePureFunctionSource(source, path, (issuePath, code, message) => {
1639
- issues.push({ path: issuePath, code, message });
1640
- });
1641
- if (issues.length > 0) {
1642
- const first = issues[0];
1643
- throw new Error(first ? `${first.code}: ${first.message}` : `${path} is invalid.`);
1644
- }
1645
- return source;
1646
- }
1647
- function validateBranchTarget(target, path, fieldLabel, branchIndex, idToIndex, add) {
1648
- if (typeof target !== "string" || target.trim().length === 0) {
1649
- add(path, `missing_branch_${fieldLabel}`, `Branch step ${fieldLabel} is required.`);
1650
- return;
1651
- }
1652
- const targetIndex = idToIndex.get(target);
1653
- if (targetIndex === undefined) {
1654
- add(path, "invalid_branch_target", `Branch ${fieldLabel} references unknown step id '${target}'.`);
1655
- return;
1656
- }
1657
- if (targetIndex <= branchIndex) {
1658
- add(path, "branch_back_jump", `Branch ${fieldLabel} must reference a step that comes after the branch in declared order.`);
1659
- }
1660
- }
1661
- // Exported for ./graph/lint.ts — see validateOptionalMaxCredits above. v2 `code`
1662
- // nodes are the v2 spelling of a v1 transform step and must clear the identical
1663
- // purity scan; the graph linter re-labels the issues it raises as
1664
- // `unsafe_code_source`.
1665
- export function validatePureFunctionSource(source, path, add) {
1666
- if (!source.trim()) {
1667
- add(path, "empty_function_source", "Workflow function source cannot be empty.");
1668
- return;
1669
- }
1670
- const forbidden = [
1671
- "import",
1672
- "require",
1673
- "process",
1674
- "global",
1675
- "globalThis",
1676
- "fetch",
1677
- "XMLHttpRequest",
1678
- "Function",
1679
- "eval",
1680
- "constructor",
1681
- "setTimeout",
1682
- "setInterval",
1683
- ];
1684
- for (const token of forbidden) {
1685
- const pattern = new RegExp(`\\b${escapeRegExp(token)}\\b`);
1686
- if (pattern.test(source)) {
1687
- add(path, "impure_workflow_function", `Workflow function source cannot reference '${token}'.`);
1688
- return;
1689
- }
1690
- }
1691
- }
1692
- // Blank out comment bodies and string/template-literal *text* so the unsafe-token
1693
- // scan matches only real code identifiers — not a bundle comment ("closed-loop
1694
- // eval") or a string ("retrieval"), which the raw \b-boundary scan flagged as
1695
- // false positives. A real eval(...) or new Function(...) — including inside a
1696
- // `${ ... }` template interpolation, which stays code — is still caught.
1697
- // @oxygen/workflows ships no AST parser, so this is a small hand-rolled lexer;
1698
- // the vm sandbox + runtime global guards remain the actual security boundary.
1699
- function stripCommentsAndStrings(source) {
1700
- const out = [];
1701
- const stack = [{ mode: "code", braces: 0 }];
1702
- const expressionKeywords = new Set(["return", "throw", "case", "delete", "void", "typeof", "yield", "await", "in", "instanceof", "else", "do"]);
1703
- const controlKeywords = new Set(["if", "while", "for", "with", "switch", "catch"]);
1704
- const statementBlockKeywords = new Set(["else", "do", "try", "finally", "catch"]);
1705
- const braceKinds = [];
1706
- const controlParens = [];
1707
- let regexAllowed = true;
1708
- let ambiguousAfterBrace = false;
1709
- let previousToken = "";
1710
- let previousWordEnd = 0;
1711
- let i = 0;
1712
- const n = source.length;
1713
- while (i < n) {
1714
- const top = stack[stack.length - 1];
1715
- const ch = source[i];
1716
- const next = i + 1 < n ? source[i + 1] : "";
1717
- if (top.mode === "template") {
1718
- if (ch === "\\") {
1719
- i += 2;
1720
- continue;
1721
- }
1722
- if (ch === "`") {
1723
- stack.pop();
1724
- regexAllowed = false;
1725
- previousToken = "literal";
1726
- i += 1;
1727
- continue;
1728
- }
1729
- if (ch === "$" && next === "{") {
1730
- stack.push({ mode: "code", braces: 0 });
1731
- regexAllowed = true;
1732
- previousToken = "";
1733
- out.push(" ");
1734
- i += 2;
1735
- continue;
1736
- }
1737
- i += 1; // drop template text
1738
- continue;
1739
- }
1740
- if (ch === "/" && next === "/") {
1741
- i += 2;
1742
- while (i < n && source[i] !== "\n")
1743
- i += 1;
1744
- continue;
1745
- }
1746
- if (ch === "/" && next === "*") {
1747
- i += 2;
1748
- while (i < n && !(source[i] === "*" && source[i + 1] === "/"))
1749
- i += 1;
1750
- i = Math.min(i + 2, n);
1751
- continue;
1752
- }
1753
- if (ch === "/" && ambiguousAfterBrace)
1754
- return { source: out.join(""), ambiguousSlash: true };
1755
- if (!/\s/.test(ch))
1756
- ambiguousAfterBrace = false;
1757
- // Regex quotes must not make the string scanner swallow executable code.
1758
- if (ch === "/" && regexAllowed) {
1759
- let end = i + 1;
1760
- let characterClass = false;
1761
- while (end < n && source[end] !== "\n" && source[end] !== "\r") {
1762
- const current = source[end];
1763
- if (current === "\\") {
1764
- end += 2;
1765
- continue;
1766
- }
1767
- if (current === "[")
1768
- characterClass = true;
1769
- else if (current === "]")
1770
- characterClass = false;
1771
- else if (current === "/" && !characterClass)
1772
- break;
1773
- end += 1;
1774
- }
1775
- if (end < n && source[end] === "/") {
1776
- end += 1;
1777
- while (end < n && /[a-z]/i.test(source[end]))
1778
- end += 1;
1779
- out.push('""');
1780
- i = end;
1781
- regexAllowed = false;
1782
- previousToken = "literal";
1783
- continue;
1784
- }
1785
- }
1786
- if (ch === '"' || ch === "'") {
1787
- const quote = ch;
1788
- i += 1;
1789
- while (i < n && source[i] !== quote)
1790
- i += source[i] === "\\" ? 2 : 1;
1791
- i += 1;
1792
- out.push('""');
1793
- regexAllowed = false;
1794
- previousToken = "literal";
1795
- continue;
1796
- }
1797
- if (ch === "`") {
1798
- stack.push({ mode: "template" });
1799
- i += 1;
1800
- continue;
1801
- }
1802
- if (/[a-z_$]/i.test(ch)) {
1803
- const start = i;
1804
- while (i < n && /[\w$]/.test(source[i]))
1805
- i += 1;
1806
- const word = source.slice(start, i);
1807
- out.push(word);
1808
- previousToken = previousToken === "." ? "identifier" : word;
1809
- previousWordEnd = i;
1810
- regexAllowed = expressionKeywords.has(previousToken);
1811
- continue;
1812
- }
1813
- if (ch === "}" && top.braces === 0 && stack.length > 1) {
1814
- stack.pop();
1815
- out.push(" ");
1816
- i += 1;
1817
- continue;
1818
- }
1819
- if (ch === "=" && next === ">") {
1820
- out.push("=>");
1821
- previousToken = "=>";
1822
- regexAllowed = true;
1823
- i += 2;
1824
- continue;
1825
- }
1826
- if (ch === "{") {
1827
- const enclosing = braceKinds[braceKinds.length - 1];
1828
- let kind = "unknown";
1829
- if ((previousToken === ")" && regexAllowed) || statementBlockKeywords.has(previousToken)
1830
- || previousToken === ";" || (previousToken === "{" && (enclosing === "statement" || enclosing === "function")))
1831
- kind = "statement";
1832
- else if (previousToken === "=>")
1833
- kind = "function";
1834
- else if (["=", "(", "[", ","].includes(previousToken) || (previousToken === ":" && enclosing === "object")
1835
- || (previousToken === "return" && !/[\r\n]/.test(source.slice(previousWordEnd, i))))
1836
- kind = "object";
1837
- braceKinds.push(kind);
1838
- }
1839
- if (ch === "(")
1840
- controlParens.push(controlKeywords.has(previousToken));
1841
- if (ch === ")")
1842
- regexAllowed = controlParens.pop() ?? false;
1843
- else if (ch === "}") {
1844
- const kind = braceKinds.pop();
1845
- regexAllowed = kind === "statement";
1846
- // Other brace forms need a parser to distinguish declarations from expressions.
1847
- ambiguousAfterBrace = kind === "unknown";
1848
- }
1849
- else if (!/\s/.test(ch)) {
1850
- if (!((ch === "+" || ch === "-") && (next === ch || previousToken === ch))) {
1851
- regexAllowed = /[([{,:;=!?&|+*%^~<>\/-]/.test(ch);
1852
- }
1853
- }
1854
- if (!/\s/.test(ch))
1855
- previousToken = ch;
1856
- if (ch === "{")
1857
- top.braces += 1;
1858
- else if (ch === "}")
1859
- top.braces = Math.max(0, top.braces - 1);
1860
- out.push(ch);
1861
- i += 1;
1862
- }
1863
- return { source: out.join(""), ambiguousSlash: false };
1864
- }
1865
- function validateRecipeBundleSafety(source, path, add) {
1866
- if (!source.trim()) {
1867
- add(path, "empty_recipe_bundle", "Recipe bundle cannot be empty.");
1868
- return;
1869
- }
1870
- // Scan only real code: comments and string literals are blanked first so a
1871
- // token that merely appears in prose or data (e.g. "eval" in a comment) does
1872
- // not trip the lint, while genuine calls survive.
1873
- const scan = stripCommentsAndStrings(source);
1874
- if (scan.ambiguousSlash) {
1875
- add(path, "unsafe_recipe_bundle", "Durable recipe bundle has an ambiguous slash after a brace. Parenthesize the expression or separate statements with a semicolon.");
1876
- return;
1877
- }
1878
- const scannable = scan.source;
1879
- for (const entry of UNSAFE_RECIPE_BUNDLE_PATTERNS) {
1880
- if (entry.pattern.test(scannable)) {
1881
- add(path, "unsafe_recipe_bundle", `Durable recipe bundle cannot reference '${entry.token}'. Use ctx.tools.run(), ctx.step(), ctx.now(), or ctx.uuid() instead.`);
1882
- return;
1883
- }
1884
- }
1885
- }
1886
- // Exported for ./graph/lint.ts — see validateOptionalMaxCredits above. One deny
1887
- // list, enforced identically for v1 tool steps and v2 tool nodes.
1888
- export function isWorkflowToolRejected(toolId) {
1889
- return toolId === "run_javascript" || toolId === "custom_http";
1890
- }
1891
- const CRON_FIELD_LIMITS = [
1892
- { name: "minute", min: 0, max: 59 },
1893
- { name: "hour", min: 0, max: 23 },
1894
- { name: "day-of-month", min: 1, max: 31 },
1895
- { name: "month", min: 1, max: 12 },
1896
- { name: "day-of-week", min: 0, max: 7 },
1897
- ];
1898
- const zonedFormatters = new Map();
1899
- function parseCronSchedule(value) {
1900
- const parts = value.trim().split(/\s+/);
1901
- if (parts.length !== 5) {
1902
- throw new Error("Cron expression must have five space-separated parts.");
1903
- }
1904
- const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;
1905
- if (!minute || !hour || !dayOfMonth || !month || !dayOfWeek) {
1906
- throw new Error("Cron expression must have five space-separated parts.");
1907
- }
1908
- const minutes = parseCronField(minute, CRON_FIELD_LIMITS[0]);
1909
- const hours = parseCronField(hour, CRON_FIELD_LIMITS[1]);
1910
- const daysOfMonth = parseCronField(dayOfMonth, CRON_FIELD_LIMITS[2]);
1911
- const months = parseCronField(month, CRON_FIELD_LIMITS[3]);
1912
- const daysOfWeek = normalizeDaysOfWeek(parseCronField(dayOfWeek, CRON_FIELD_LIMITS[4]));
1913
- return {
1914
- minutes,
1915
- hours,
1916
- daysOfMonth,
1917
- months,
1918
- daysOfWeek,
1919
- dayOfMonthRestricted: dayOfMonth !== "*",
1920
- dayOfWeekRestricted: dayOfWeek !== "*",
1921
- };
1922
- }
1923
- function parseCronField(expression, limits) {
1924
- const values = new Set();
1925
- for (const rawToken of expression.split(",")) {
1926
- const token = rawToken.trim();
1927
- if (!token)
1928
- throw new Error(`Cron ${limits.name} field contains an empty item.`);
1929
- const parts = token.split("/");
1930
- const rangePart = parts[0];
1931
- const stepPart = parts[1];
1932
- if (!rangePart || parts.length > 2) {
1933
- throw new Error(`Cron ${limits.name} field is invalid.`);
1934
- }
1935
- const step = stepPart === undefined ? 1 : Number(stepPart);
1936
- if (!Number.isInteger(step) || step < 1) {
1937
- throw new Error(`Cron ${limits.name} step must be a positive integer.`);
1938
- }
1939
- const [start, end] = parseCronRange(rangePart, limits);
1940
- for (let current = start; current <= end; current += step) {
1941
- values.add(current);
1942
- }
1943
- }
1944
- if (values.size === 0)
1945
- throw new Error(`Cron ${limits.name} field is empty.`);
1946
- return values;
1947
- }
1948
- function parseCronRange(value, limits) {
1949
- if (value === "*")
1950
- return [limits.min, limits.max];
1951
- const parts = value.split("-");
1952
- const startRaw = parts[0];
1953
- const endRaw = parts[1];
1954
- if (!startRaw || parts.length > 2) {
1955
- throw new Error(`Cron ${limits.name} range is invalid.`);
1956
- }
1957
- const start = Number(startRaw);
1958
- const end = endRaw === undefined ? start : Number(endRaw);
1959
- if (!Number.isInteger(start) || !Number.isInteger(end)) {
1960
- throw new Error(`Cron ${limits.name} values must be integers.`);
1961
- }
1962
- if (start < limits.min || end > limits.max || start > end) {
1963
- throw new Error(`Cron ${limits.name} values must be between ${limits.min} and ${limits.max}.`);
1964
- }
1965
- return [start, end];
1966
- }
1967
- function normalizeDaysOfWeek(values) {
1968
- const normalized = new Set();
1969
- for (const value of values) {
1970
- normalized.add(value === 7 ? 0 : value);
1971
- }
1972
- return normalized;
1973
- }
1974
- // Date-only match (month + day-of-month/day-of-week), excluding hour/minute.
1975
- // Lets nextCronRunAfter skip whole non-matching days in one jump.
1976
- function matchesCronDate(schedule, parts) {
1977
- if (!schedule.months.has(parts.month))
1978
- return false;
1979
- const dayOfMonthMatches = schedule.daysOfMonth.has(parts.dayOfMonth);
1980
- const dayOfWeekMatches = schedule.daysOfWeek.has(parts.dayOfWeek);
1981
- if (schedule.dayOfMonthRestricted && schedule.dayOfWeekRestricted) {
1982
- return dayOfMonthMatches || dayOfWeekMatches;
1983
- }
1984
- return dayOfMonthMatches && dayOfWeekMatches;
1985
- }
1986
- function matchesCronSchedule(schedule, parts) {
1987
- if (!schedule.minutes.has(parts.minute))
1988
- return false;
1989
- if (!schedule.hours.has(parts.hour))
1990
- return false;
1991
- return matchesCronDate(schedule, parts);
1992
- }
1993
- function roundUpToNextMinute(value) {
1994
- const result = new Date(value.getTime());
1995
- result.setUTCSeconds(0, 0);
1996
- if (result.getTime() <= value.getTime()) {
1997
- result.setUTCMinutes(result.getUTCMinutes() + 1);
1998
- }
1999
- return result;
2000
- }
2001
- function zonedDateParts(date, timezone) {
2002
- const formatter = getZonedFormatter(timezone);
2003
- const parts = new Map();
2004
- for (const part of formatter.formatToParts(date)) {
2005
- if (part.type !== "literal")
2006
- parts.set(part.type, part.value);
2007
- }
2008
- return {
2009
- minute: Number(parts.get("minute")),
2010
- hour: Number(parts.get("hour")),
2011
- dayOfMonth: Number(parts.get("day")),
2012
- month: Number(parts.get("month")),
2013
- dayOfWeek: weekdayToNumber(parts.get("weekday") ?? ""),
2014
- };
2015
- }
2016
- function isValidTimeZone(timezone) {
2017
- try {
2018
- // Throws RangeError for an unknown IANA zone; same mechanism the scheduler
2019
- // uses, so lint accepts exactly the zones the runtime can resolve.
2020
- new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format(0);
2021
- return true;
2022
- }
2023
- catch {
2024
- return false;
2025
- }
2026
- }
2027
- function getZonedFormatter(timezone) {
2028
- const cached = zonedFormatters.get(timezone);
2029
- if (cached)
2030
- return cached;
2031
- const formatter = new Intl.DateTimeFormat("en-US", {
2032
- timeZone: timezone,
2033
- weekday: "short",
2034
- year: "numeric",
2035
- month: "numeric",
2036
- day: "numeric",
2037
- hour: "numeric",
2038
- minute: "numeric",
2039
- hourCycle: "h23",
2040
- });
2041
- zonedFormatters.set(timezone, formatter);
2042
- return formatter;
2043
- }
2044
- function weekdayToNumber(value) {
2045
- switch (value.toLowerCase()) {
2046
- case "sun":
2047
- return 0;
2048
- case "mon":
2049
- return 1;
2050
- case "tue":
2051
- return 2;
2052
- case "wed":
2053
- return 3;
2054
- case "thu":
2055
- return 4;
2056
- case "fri":
2057
- return 5;
2058
- case "sat":
2059
- return 6;
2060
- default:
2061
- throw new Error(`Unsupported weekday '${value}'.`);
2062
- }
2063
- }
2064
- function hashWorkflowSource(source) {
2065
- return createHash("sha256").update(source).digest("hex");
2066
- }
2067
- // Deterministic plan hash (Gap 4): binds an approval decision to the exact
2068
- // reviewed plan + cost so it cannot be replayed against a changed plan. The
2069
- // durable mid-run approval gate (recipe-context) hashes its relevant fields
2070
- // through this; binding the imperative `workflows call` admission path the same
2071
- // way is a flagged follow-up. Canonical (sorted-key) JSON keeps the hash stable
2072
- // regardless of key order or undefined fields.
2073
- export function computeWorkflowPlanHash(input) {
2074
- return hashWorkflowSource(canonicalJsonStringify(input));
2075
- }
2076
- function canonicalJsonStringify(value) {
2077
- if (value === null || typeof value !== "object")
2078
- return JSON.stringify(value) ?? "null";
2079
- if (Array.isArray(value))
2080
- return `[${value.map(canonicalJsonStringify).join(",")}]`;
2081
- const entries = Object.entries(value)
2082
- .filter(([, entryValue]) => entryValue !== undefined)
2083
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
2084
- return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${canonicalJsonStringify(entryValue)}`).join(",")}}`;
2085
- }
2086
- function workflowJsonReplacer(_key, value) {
2087
- return typeof value === "function" ? Function.prototype.toString.call(value) : value;
2088
- }
2089
- function enforceJsonOutput(value, maxOutputBytes) {
2090
- const json = JSON.stringify(value);
2091
- if (json === undefined)
2092
- return null;
2093
- if (Buffer.byteLength(json) > maxOutputBytes) {
2094
- throw new Error("workflow_output_too_large: Workflow function output is too large.");
2095
- }
2096
- return JSON.parse(json);
2097
- }
2098
- function toJsonValue(value, label) {
2099
- const json = JSON.stringify(value);
2100
- if (json === undefined) {
2101
- throw new Error(`${label} must be JSON serializable.`);
2102
- }
2103
- return JSON.parse(json);
2104
- }
2105
- function isPromiseLike(value) {
2106
- return value !== null && typeof value === "object" && "then" in value
2107
- && typeof value.then === "function";
2108
- }
2109
- async function withTimeout(promise, timeoutMs) {
2110
- let timer = null;
2111
- try {
2112
- return await Promise.race([
2113
- promise,
2114
- new Promise((_, reject) => {
2115
- timer = setTimeout(() => reject(new Error("workflow_function_timeout: Workflow function timed out.")), timeoutMs);
2116
- }),
2117
- ]);
2118
- }
2119
- finally {
2120
- if (timer)
2121
- clearTimeout(timer);
2122
- }
2123
- }
2124
- function isRecord(value) {
2125
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2126
- }
2127
- function isNonEmptyString(value) {
2128
- return typeof value === "string" && value.trim().length > 0;
2129
- }
2130
- // The canonical list of internal workflow tool ids lives in @oxygen/tools
2131
- // (OXYGEN_INTERNAL_WORKFLOW_TOOL_IDS). Both the worker's runtime registry and the
2132
- // web's lint allowlist derive from it, so re-declaring it here would recreate
2133
- // exactly the drift that broke crm-sync.
2134
- function escapeRegExp(value) {
2135
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2136
- }
14
+ // The v1 manifest validators the v2 graph linter reuses; see manifest-validation.ts.
15
+ export { DURABLE_RECIPE_COMPILER_VERSION, isWorkflowToolRejected, lintRecipeManifest, lintWorkflowCodeSourceSafety, MAX_RECIPE_BUNDLE_BYTES, validateJsonSchemaValue, validateOptionalMaxCredits, validatePureFunctionSource, validateTrigger, WORKFLOW_MANIFEST_VERSION, } from "./manifest-validation.js";
16
+ export { WORKFLOW_COMPILER_VERSION, BLUEPRINT_VERSION, BLUEPRINT_COMPILER_VERSION, MAX_BLUEPRINT_BYTES, DEFAULT_WORKFLOW_CRON_TIMEZONE, } from "./manifest-types.js";
17
+ export { defineWorkflow, apiTrigger, webhookTrigger, cronTrigger, eventTrigger, transformStep, toolStep, branchStep, } from "./manifest-builders.js";
18
+ export { nextCronRunAfter, nextCronRunAfterMinInterval, minCronGapMinutes, } from "./cron.js";
19
+ export { isWorkflowDefinition, isWorkflowManifest, isRecipeManifest, isAnyWorkflowManifest, isBlueprint, } from "./manifest-guards.js";
20
+ export { buildRecipeManifest, hashRecipeSource, buildBlueprint, computeWorkflowPlanHash, } from "./manifest-hash.js";
21
+ export { compileWorkflowDefinition, lintWorkflowManifest, assertRecipeManifest, assertWorkflowManifest, lintBlueprint, assertBlueprint, assertRecipeBundleSafe, lintRecipeBundleSafety, } from "./manifest-lint.js";
22
+ export { PURE_WORKFLOW_FUNCTION_MAX_TIMEOUT_MS, runPureWorkflowFunction, } from "./pure-function.js";
23
+ export { workflowApplySchema, workflowCallSchema, workflowEventEmitSchema, workflowTriggerSchema, workflowManifestSchema, getWorkflowSchema, } from "./workflow-schemas.js";