@elevasis/sdk 1.44.3 → 1.46.0

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 (259) hide show
  1. package/dist/cli.cjs +35026 -30226
  2. package/dist/index.d.ts +1786 -808
  3. package/dist/index.js +789 -739
  4. package/dist/node/index.d.ts +105 -181
  5. package/dist/node/index.js +2 -2
  6. package/dist/test-utils/index.d.ts +901 -359
  7. package/dist/test-utils/index.js +587 -824
  8. package/dist/worker/index.d.ts +12685 -0
  9. package/dist/worker/index.js +188 -216
  10. package/package.json +4 -7
  11. package/reference/_navigation.md +161 -22
  12. package/reference/_reference-manifest.json +228 -4
  13. package/reference/claude-config.md +8 -0
  14. package/reference/core/exports.mdx +2 -0
  15. package/reference/core/index.mdx +3 -3
  16. package/reference/examples/organization-model.ts +117 -111
  17. package/reference/index.mdx +4 -4
  18. package/reference/packages/core/src/business/README.md +4 -1
  19. package/reference/packages/core/src/content/README.md +19 -0
  20. package/reference/packages/core/src/organization-model/README.md +148 -149
  21. package/reference/packages/core/src/organization-model/readiness/README.md +42 -0
  22. package/reference/packages/ui/src/features/README.md +28 -28
  23. package/reference/rules/active-change-index.md +40 -54
  24. package/reference/rules/agent-runtime.md +81 -0
  25. package/reference/rules/agent-start-here.md +71 -163
  26. package/reference/rules/deployment.md +33 -10
  27. package/reference/rules/error-handling.md +26 -0
  28. package/reference/rules/execution.md +13 -0
  29. package/reference/rules/frontend.md +10 -3
  30. package/reference/rules/observability.md +9 -1
  31. package/reference/rules/operations.md +26 -17
  32. package/reference/rules/organization-model.md +74 -88
  33. package/reference/rules/organization-os.md +71 -88
  34. package/reference/rules/package-taxonomy.md +11 -2
  35. package/reference/rules/platform.md +13 -7
  36. package/reference/rules/shared-types.md +36 -0
  37. package/reference/rules/task-tracking.md +30 -5
  38. package/reference/rules/ui.md +145 -3
  39. package/reference/rules/vibe-intents.md +271 -0
  40. package/reference/rules/vibe.md +17 -243
  41. package/reference/scaffold/core/organization-graph.mdx +112 -99
  42. package/reference/scaffold/core/organization-model.mdx +231 -215
  43. package/reference/scaffold/operations/propagation-pipeline.md +16 -17
  44. package/reference/scaffold/operations/scaffold-maintenance.md +22 -20
  45. package/reference/scaffold/operations/workflow-recipes.md +72 -20
  46. package/reference/scaffold/recipes/add-a-feature.md +156 -146
  47. package/reference/scaffold/recipes/add-a-resource.md +123 -117
  48. package/reference/scaffold/recipes/customize-crm-actions.md +28 -13
  49. package/reference/scaffold/recipes/customize-knowledge-browser.md +52 -117
  50. package/reference/scaffold/recipes/customize-organization-model.md +161 -149
  51. package/reference/scaffold/recipes/extend-a-base-entity.md +156 -140
  52. package/reference/scaffold/recipes/extend-content.md +265 -0
  53. package/reference/scaffold/recipes/extend-crm.md +16 -11
  54. package/reference/scaffold/recipes/extend-lead-gen.md +37 -21
  55. package/reference/scaffold/recipes/gate-by-feature-or-admin.md +160 -118
  56. package/reference/scaffold/recipes/index.md +6 -3
  57. package/reference/scaffold/recipes/query-the-knowledge-graph.md +23 -23
  58. package/reference/scaffold/reference/contracts.md +30 -56
  59. package/reference/scaffold/reference/feature-registry.md +3 -0
  60. package/reference/scaffold/reference/glossary.md +4 -4
  61. package/reference/scaffold/reference/system-interface-capabilities.md +5 -4
  62. package/reference/scaffold/ui/composition-extensibility.mdx +271 -232
  63. package/reference/scaffold/ui/customization.md +2 -2
  64. package/reference/scaffold/ui/feature-flags-and-gating.md +14 -6
  65. package/reference/scaffold/ui/feature-shell.mdx +277 -62
  66. package/reference/scaffold/ui/recipes.md +229 -197
  67. package/reference/sdk/cli-management.mdx +166 -33
  68. package/reference/sdk/cli.mdx +90 -13
  69. package/reference/sdk/concepts.mdx +2 -0
  70. package/reference/sdk/define-builders.mdx +76 -0
  71. package/reference/sdk/deployment/command-center.mdx +6 -2
  72. package/reference/sdk/deployment/execution-reference.mdx +64 -186
  73. package/reference/sdk/deployment/index.mdx +2 -0
  74. package/reference/sdk/exports.mdx +4 -4
  75. package/reference/sdk/framework/agent.mdx +52 -116
  76. package/reference/sdk/framework/index.mdx +46 -65
  77. package/reference/sdk/framework/project-structure.mdx +150 -205
  78. package/reference/sdk/framework/tutorial-system.mdx +2 -2
  79. package/reference/sdk/human-in-the-loop.mdx +152 -0
  80. package/reference/sdk/index.mdx +6 -7
  81. package/reference/sdk/platform-tools/adapters-platform.mdx +3 -1
  82. package/reference/sdk/platform-tools/index.mdx +12 -0
  83. package/reference/sdk/platform-tools/type-safety.mdx +4 -0
  84. package/reference/sdk/project-deployment-spec.mdx +131 -0
  85. package/reference/sdk/resources/index.mdx +21 -7
  86. package/reference/sdk/resources/patterns.mdx +54 -24
  87. package/reference/sdk/resources/types.mdx +7 -4
  88. package/reference/sdk/templates/data-enrichment.mdx +7 -3
  89. package/reference/sdk/templates/email-sender.mdx +139 -135
  90. package/reference/sdk/templates/lead-scorer.mdx +5 -1
  91. package/reference/sdk/templates/pdf-generator.mdx +155 -151
  92. package/reference/sdk/templates/recurring-job.mdx +195 -189
  93. package/reference/sdk/templates/text-classifier.mdx +4 -0
  94. package/reference/sdk/templates/web-scraper.mdx +139 -135
  95. package/reference/spine/spine-primer.md +135 -96
  96. package/reference/ui/exports.mdx +1 -0
  97. package/reference/ui/index.mdx +14 -7
  98. package/dist/types/worker/adapters/anymailfinder.d.ts +0 -14
  99. package/dist/types/worker/adapters/apify.d.ts +0 -14
  100. package/dist/types/worker/adapters/approval.d.ts +0 -23
  101. package/dist/types/worker/adapters/attio.d.ts +0 -22
  102. package/dist/types/worker/adapters/clickup.d.ts +0 -22
  103. package/dist/types/worker/adapters/create-adapter.d.ts +0 -41
  104. package/dist/types/worker/adapters/crm.d.ts +0 -20
  105. package/dist/types/worker/adapters/dropbox.d.ts +0 -14
  106. package/dist/types/worker/adapters/email.d.ts +0 -25
  107. package/dist/types/worker/adapters/execution.d.ts +0 -22
  108. package/dist/types/worker/adapters/gmail.d.ts +0 -14
  109. package/dist/types/worker/adapters/google-sheets.d.ts +0 -14
  110. package/dist/types/worker/adapters/index.d.ts +0 -33
  111. package/dist/types/worker/adapters/instantly.d.ts +0 -14
  112. package/dist/types/worker/adapters/lead.d.ts +0 -28
  113. package/dist/types/worker/adapters/list.d.ts +0 -9
  114. package/dist/types/worker/adapters/llm.d.ts +0 -45
  115. package/dist/types/worker/adapters/millionverifier.d.ts +0 -14
  116. package/dist/types/worker/adapters/notification.d.ts +0 -28
  117. package/dist/types/worker/adapters/pdf.d.ts +0 -22
  118. package/dist/types/worker/adapters/projects.d.ts +0 -20
  119. package/dist/types/worker/adapters/resend.d.ts +0 -14
  120. package/dist/types/worker/adapters/scheduler.d.ts +0 -25
  121. package/dist/types/worker/adapters/signature-api.d.ts +0 -14
  122. package/dist/types/worker/adapters/storage.d.ts +0 -33
  123. package/dist/types/worker/adapters/stripe.d.ts +0 -14
  124. package/dist/types/worker/adapters/tomba.d.ts +0 -14
  125. package/dist/types/worker/index.d.ts +0 -60
  126. package/dist/types/worker/platform.d.ts +0 -90
  127. package/dist/types/worker/utils.d.ts +0 -9
  128. package/reference/claude-config/Overview.md +0 -230
  129. package/reference/claude-config/hooks/post-edit-validate.mjs +0 -98
  130. package/reference/claude-config/hooks/scaffold-registry-reminder.mjs +0 -187
  131. package/reference/claude-config/hooks/tool-failure-recovery.mjs +0 -73
  132. package/reference/claude-config/registries/graph-skills.json +0 -4
  133. package/reference/claude-config/registries/knowledge-flags.json +0 -154
  134. package/reference/claude-config/registries/skill-coverage.json +0 -20
  135. package/reference/claude-config/rules/active-change-index.md +0 -22
  136. package/reference/claude-config/rules/agent-start-here.md +0 -22
  137. package/reference/claude-config/rules/deployment.md +0 -22
  138. package/reference/claude-config/rules/error-handling.md +0 -22
  139. package/reference/claude-config/rules/execution.md +0 -22
  140. package/reference/claude-config/rules/frontend.md +0 -22
  141. package/reference/claude-config/rules/observability.md +0 -22
  142. package/reference/claude-config/rules/operations.md +0 -22
  143. package/reference/claude-config/rules/organization-model.md +0 -22
  144. package/reference/claude-config/rules/organization-os.md +0 -22
  145. package/reference/claude-config/rules/package-taxonomy.md +0 -22
  146. package/reference/claude-config/rules/platform.md +0 -22
  147. package/reference/claude-config/rules/shared-types.md +0 -22
  148. package/reference/claude-config/rules/task-tracking.md +0 -22
  149. package/reference/claude-config/rules/topbar-actions.md +0 -70
  150. package/reference/claude-config/rules/ui.md +0 -22
  151. package/reference/claude-config/rules/vibe.md +0 -22
  152. package/reference/claude-config/scripts/statusline-command.js +0 -18
  153. package/reference/claude-config/settings.json +0 -30
  154. package/reference/claude-config/skills/client/SKILL.md +0 -201
  155. package/reference/claude-config/skills/deploy/SKILL.md +0 -159
  156. package/reference/claude-config/skills/dsp/SKILL.md +0 -66
  157. package/reference/claude-config/skills/elevasis/SKILL.md +0 -251
  158. package/reference/claude-config/skills/explore/SKILL.md +0 -78
  159. package/reference/claude-config/skills/git-sync/SKILL.md +0 -166
  160. package/reference/claude-config/skills/om/SKILL.md +0 -475
  161. package/reference/claude-config/skills/om/operations/build.md +0 -237
  162. package/reference/claude-config/skills/om/operations/codify-level-a.md +0 -109
  163. package/reference/claude-config/skills/om/operations/codify-level-b.md +0 -159
  164. package/reference/claude-config/skills/om/operations/customers.md +0 -114
  165. package/reference/claude-config/skills/om/operations/features.md +0 -88
  166. package/reference/claude-config/skills/om/operations/goals.md +0 -123
  167. package/reference/claude-config/skills/om/operations/identity.md +0 -97
  168. package/reference/claude-config/skills/om/operations/labels.md +0 -110
  169. package/reference/claude-config/skills/om/operations/offerings.md +0 -114
  170. package/reference/claude-config/skills/om/operations/roles.md +0 -104
  171. package/reference/claude-config/skills/om/operations/scaffold.md +0 -163
  172. package/reference/claude-config/skills/om/operations/techStack.md +0 -38
  173. package/reference/claude-config/skills/project/SKILL.md +0 -1114
  174. package/reference/claude-config/skills/run-ui/SKILL.md +0 -73
  175. package/reference/claude-config/skills/save/SKILL.md +0 -183
  176. package/reference/claude-config/skills/setup/SKILL.md +0 -290
  177. package/reference/claude-config/skills/status/SKILL.md +0 -59
  178. package/reference/claude-config/skills/submit-request/SKILL.md +0 -180
  179. package/reference/claude-config/skills/sync/SKILL.md +0 -47
  180. package/reference/claude-config/skills/tutorial/SKILL.md +0 -259
  181. package/reference/claude-config/skills/tutorial/progress-template.md +0 -74
  182. package/reference/claude-config/skills/tutorial/technical.md +0 -1303
  183. package/reference/claude-config/skills/tutorial/vibe-coder.md +0 -890
  184. package/reference/claude-config/sync-notes/2026-04-22-git-sync-and-sync-notes.md +0 -27
  185. package/reference/claude-config/sync-notes/2026-04-22-lead-gen-deliverability-removal.md +0 -30
  186. package/reference/claude-config/sync-notes/2026-04-24-test-utils-and-template-tests.md +0 -73
  187. package/reference/claude-config/sync-notes/2026-04-24-ui-consolidation-and-sdk-cli-train.md +0 -86
  188. package/reference/claude-config/sync-notes/2026-04-25-auth-role-system-and-settings-roles.md +0 -55
  189. package/reference/claude-config/sync-notes/2026-04-27-crm-hitl-action-layer-cutover.md +0 -97
  190. package/reference/claude-config/sync-notes/2026-04-27-lead-gen-substrate-train.md +0 -112
  191. package/reference/claude-config/sync-notes/2026-04-29-crm-state-and-lead-gen-processing-status.md +0 -93
  192. package/reference/claude-config/sync-notes/2026-05-02-crm-ownership-next-action.md +0 -58
  193. package/reference/claude-config/sync-notes/2026-05-02-template-hardcode-workos-config.md +0 -56
  194. package/reference/claude-config/sync-notes/2026-05-04-elevasis-workspace.md +0 -71
  195. package/reference/claude-config/sync-notes/2026-05-04-knowledge-bundle.md +0 -83
  196. package/reference/claude-config/sync-notes/2026-05-04-template-skills-run-ui-and-tutorial.md +0 -59
  197. package/reference/claude-config/sync-notes/2026-05-05-list-builder.md +0 -42
  198. package/reference/claude-config/sync-notes/2026-05-06-crm-spine.md +0 -60
  199. package/reference/claude-config/sync-notes/2026-05-06-sdk-changes-release-train.md +0 -37
  200. package/reference/claude-config/sync-notes/2026-05-07-sdk-changes-release-train.md +0 -34
  201. package/reference/claude-config/sync-notes/2026-05-08-resource-governance-scaffold-guidance.md +0 -38
  202. package/reference/claude-config/sync-notes/2026-05-09-clients-domain.md +0 -32
  203. package/reference/claude-config/sync-notes/2026-05-09-command-system.md +0 -33
  204. package/reference/claude-config/sync-notes/2026-05-09-resource-governance-and-misc.md +0 -69
  205. package/reference/claude-config/sync-notes/2026-05-12-sdk-ready-release-train.md +0 -30
  206. package/reference/claude-config/sync-notes/2026-05-14-organization-model-ontology-refactor.md +0 -45
  207. package/reference/claude-config/sync-notes/2026-05-15-om-skill-rename-and-write-family.md +0 -52
  208. package/reference/claude-config/sync-notes/2026-05-17-sdk-boundary-consolidation.md +0 -33
  209. package/reference/claude-config/sync-notes/2026-05-20-om-define-helpers.md +0 -32
  210. package/reference/claude-config/sync-notes/2026-05-22-access-model-and-right-panel.md +0 -43
  211. package/reference/claude-config/sync-notes/2026-05-22-lead-gen-tenant-config.md +0 -40
  212. package/reference/claude-config/sync-notes/2026-05-22-org-model-multi-file-split.md +0 -61
  213. package/reference/claude-config/sync-notes/2026-05-23-branding-names-to-identity.md +0 -49
  214. package/reference/claude-config/sync-notes/2026-05-23-lead-gen-manage-access.md +0 -31
  215. package/reference/claude-config/sync-notes/2026-05-23-om-deployment-drift-detection.md +0 -42
  216. package/reference/claude-config/sync-notes/2026-05-23-om-full-model-deploy-contract.md +0 -33
  217. package/reference/claude-config/sync-notes/2026-05-23-ui-sdk-package-fixes.md +0 -37
  218. package/reference/claude-config/sync-notes/2026-05-24-platform-invite-router-core-baseline.md +0 -28
  219. package/reference/claude-config/sync-notes/2026-05-24-system-interface-readiness.md +0 -43
  220. package/reference/claude-config/sync-notes/2026-05-25-invitation-login-loader.md +0 -26
  221. package/reference/claude-config/sync-notes/2026-05-25-om-topbar-requests.md +0 -33
  222. package/reference/claude-config/sync-notes/2026-05-25-system-interface-profile-registry-and-substrate.md +0 -35
  223. package/reference/claude-config/sync-notes/2026-05-25-tenant-om-scaffold-cli.md +0 -49
  224. package/reference/claude-config/sync-notes/2026-05-25-vibe-operate-intent.md +0 -47
  225. package/reference/claude-config/sync-notes/2026-05-28-om-snapshot-sdk-workflow-config.md +0 -33
  226. package/reference/claude-config/sync-notes/2026-05-30-client-source-and-om-profiles.md +0 -39
  227. package/reference/claude-config/sync-notes/2026-06-02-knowledge-nested-group-routing.md +0 -27
  228. package/reference/claude-config/sync-notes/2026-06-02-nest-projects-under-platform.md +0 -45
  229. package/reference/claude-config/sync-notes/2026-06-03-skill-autogen-and-client-skill.md +0 -34
  230. package/reference/claude-config/sync-notes/2026-06-04-scaffold-registry-lane-severity.md +0 -34
  231. package/reference/claude-config/sync-notes/2026-06-05-appearance-app-mode-decouple.md +0 -29
  232. package/reference/claude-config/sync-notes/2026-06-05-ontology-endpoint-rename-and-knowledge-browser-ui.md +0 -86
  233. package/reference/claude-config/sync-notes/2026-06-06-om-build-systems-scaffold.md +0 -47
  234. package/reference/claude-config/sync-notes/2026-06-06-om-item-copy-references.md +0 -50
  235. package/reference/claude-config/sync-notes/2026-06-08-knowledge-base-page-not-found-fix.md +0 -76
  236. package/reference/claude-config/sync-notes/2026-06-09-agent-sessions-public-agent-chat-route.md +0 -75
  237. package/reference/claude-config/sync-notes/2026-06-09-sdk-cli-load-org-model-resolution.md +0 -42
  238. package/reference/claude-config/sync-notes/2026-06-12-agent-grants-visualizer-operations.md +0 -30
  239. package/reference/claude-config/sync-notes/2026-06-14-session-ux-and-project-cli-json.md +0 -33
  240. package/reference/claude-config/sync-notes/2026-06-14-shared-session-conversation-view.md +0 -26
  241. package/reference/claude-config/sync-notes/2026-06-15-session-chat-zero-wiring.md +0 -46
  242. package/reference/claude-config/sync-notes/2026-06-17-agent-session-ux-features.md +0 -34
  243. package/reference/claude-config/sync-notes/2026-06-25-shared-page-scroll-contract-guard.md +0 -52
  244. package/reference/claude-config/sync-notes/2026-06-26-leadgen-overview-om-telemetry.md +0 -47
  245. package/reference/claude-config/sync-notes/2026-07-21-agent-scaffold-hardening.md +0 -75
  246. package/reference/claude-config/sync-notes/2026-07-23-agent-session-memory.md +0 -49
  247. package/reference/claude-config/sync-notes/2026-07-23-workos-org-marker.md +0 -50
  248. package/reference/claude-config/sync-notes/2026-07-24-claude-5-models-and-session-surface-fixes.md +0 -116
  249. package/reference/claude-config/sync-notes/2026-07-27-agent-strict-output-and-turn-drift.md +0 -73
  250. package/reference/claude-config/sync-notes/2026-07-28-agent-reply-is-its-own-field.md +0 -84
  251. package/reference/claude-config/sync-notes/2026-07-30-login-screen-and-member-provisioning-state.md +0 -114
  252. package/reference/claude-config/sync-notes/2026-08-02-auth-guard-defaults-and-truncation-fix.md +0 -122
  253. package/reference/claude-config/sync-notes/2026-08-03-agent-prose-escape-normalization.md +0 -88
  254. package/reference/claude-config/sync-notes/2026-08-03-cli-gateway-errors-and-request-timeout.md +0 -120
  255. package/reference/claude-config/sync-notes/README.md +0 -43
  256. package/reference/sdk/framework/interaction-guidance.mdx +0 -182
  257. package/reference/sdk/framework/memory.mdx +0 -326
  258. package/reference/sdk/framework/resource-documentation.mdx +0 -90
  259. package/reference/sdk/roadmap.mdx +0 -164
@@ -638,13 +638,13 @@ var init_magic_string_es = __esm({
638
638
  }
639
639
  };
640
640
  Chunk = class _Chunk {
641
- constructor(start, end, content) {
641
+ constructor(start, end, content2) {
642
642
  this.start = start;
643
643
  this.end = end;
644
- this.original = content;
644
+ this.original = content2;
645
645
  this.intro = "";
646
646
  this.outro = "";
647
- this.content = content;
647
+ this.content = content2;
648
648
  this.storeName = false;
649
649
  this.edited = false;
650
650
  {
@@ -652,11 +652,11 @@ var init_magic_string_es = __esm({
652
652
  this.next = null;
653
653
  }
654
654
  }
655
- appendLeft(content) {
656
- this.outro += content;
655
+ appendLeft(content2) {
656
+ this.outro += content2;
657
657
  }
658
- appendRight(content) {
659
- this.intro = this.intro + content;
658
+ appendRight(content2) {
659
+ this.intro = this.intro + content2;
660
660
  }
661
661
  clone() {
662
662
  const chunk = new _Chunk(this.start, this.end, this.original);
@@ -684,8 +684,8 @@ var init_magic_string_es = __esm({
684
684
  chunk = chunk.previous;
685
685
  }
686
686
  }
687
- edit(content, storeName, contentOnly) {
688
- this.content = content;
687
+ edit(content2, storeName, contentOnly) {
688
+ this.content = content2;
689
689
  if (!contentOnly) {
690
690
  this.intro = "";
691
691
  this.outro = "";
@@ -694,11 +694,11 @@ var init_magic_string_es = __esm({
694
694
  this.edited = true;
695
695
  return this;
696
696
  }
697
- prependLeft(content) {
698
- this.outro = content + this.outro;
697
+ prependLeft(content2) {
698
+ this.outro = content2 + this.outro;
699
699
  }
700
- prependRight(content) {
701
- this.intro = content + this.intro;
700
+ prependRight(content2) {
701
+ this.intro = content2 + this.intro;
702
702
  }
703
703
  reset() {
704
704
  this.intro = "";
@@ -805,10 +805,10 @@ var init_magic_string_es = __esm({
805
805
  this.rawSegments = this.raw[this.generatedCodeLine] = [];
806
806
  this.pending = null;
807
807
  }
808
- addEdit(sourceIndex, content, loc, nameIndex) {
809
- if (content.length) {
810
- const contentLengthMinusOne = content.length - 1;
811
- let contentLineEnd = content.indexOf("\n", 0);
808
+ addEdit(sourceIndex, content2, loc, nameIndex) {
809
+ if (content2.length) {
810
+ const contentLengthMinusOne = content2.length - 1;
811
+ let contentLineEnd = content2.indexOf("\n", 0);
812
812
  let previousContentLineEnd = -1;
813
813
  while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
814
814
  const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
@@ -820,17 +820,17 @@ var init_magic_string_es = __esm({
820
820
  this.raw[this.generatedCodeLine] = this.rawSegments = [];
821
821
  this.generatedCodeColumn = 0;
822
822
  previousContentLineEnd = contentLineEnd;
823
- contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
823
+ contentLineEnd = content2.indexOf("\n", contentLineEnd + 1);
824
824
  }
825
825
  const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
826
826
  if (nameIndex >= 0) {
827
827
  segment.push(nameIndex);
828
828
  }
829
829
  this.rawSegments.push(segment);
830
- this.advance(content.slice(previousContentLineEnd + 1));
830
+ this.advance(content2.slice(previousContentLineEnd + 1));
831
831
  } else if (this.pending) {
832
832
  this.rawSegments.push(this.pending);
833
- this.advance(content);
833
+ this.advance(content2);
834
834
  }
835
835
  this.pending = null;
836
836
  }
@@ -917,32 +917,32 @@ var init_magic_string_es = __esm({
917
917
  addSourcemapLocation(char) {
918
918
  this.sourcemapLocations.add(char);
919
919
  }
920
- append(content) {
921
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
922
- this.outro += content;
920
+ append(content2) {
921
+ if (typeof content2 !== "string") throw new TypeError("outro content must be a string");
922
+ this.outro += content2;
923
923
  return this;
924
924
  }
925
- appendLeft(index2, content) {
925
+ appendLeft(index2, content2) {
926
926
  index2 = index2 + this.offset;
927
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
927
+ if (typeof content2 !== "string") throw new TypeError("inserted content must be a string");
928
928
  this._split(index2);
929
929
  const chunk = this.byEnd[index2];
930
930
  if (chunk) {
931
- chunk.appendLeft(content);
931
+ chunk.appendLeft(content2);
932
932
  } else {
933
- this.intro += content;
933
+ this.intro += content2;
934
934
  }
935
935
  return this;
936
936
  }
937
- appendRight(index2, content) {
937
+ appendRight(index2, content2) {
938
938
  index2 = index2 + this.offset;
939
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
939
+ if (typeof content2 !== "string") throw new TypeError("inserted content must be a string");
940
940
  this._split(index2);
941
941
  const chunk = this.byStart[index2];
942
942
  if (chunk) {
943
- chunk.appendRight(content);
943
+ chunk.appendRight(content2);
944
944
  } else {
945
- this.outro += content;
945
+ this.outro += content2;
946
946
  }
947
947
  return this;
948
948
  }
@@ -1096,23 +1096,23 @@ var init_magic_string_es = __esm({
1096
1096
  "magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
1097
1097
  );
1098
1098
  }
1099
- insertLeft(index2, content) {
1099
+ insertLeft(index2, content2) {
1100
1100
  if (!warned.insertLeft) {
1101
1101
  console.warn(
1102
1102
  "magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
1103
1103
  );
1104
1104
  warned.insertLeft = true;
1105
1105
  }
1106
- return this.appendLeft(index2, content);
1106
+ return this.appendLeft(index2, content2);
1107
1107
  }
1108
- insertRight(index2, content) {
1108
+ insertRight(index2, content2) {
1109
1109
  if (!warned.insertRight) {
1110
1110
  console.warn(
1111
1111
  "magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
1112
1112
  );
1113
1113
  warned.insertRight = true;
1114
1114
  }
1115
- return this.prependRight(index2, content);
1115
+ return this.prependRight(index2, content2);
1116
1116
  }
1117
1117
  move(start, end, index2) {
1118
1118
  start = start + this.offset;
@@ -1144,14 +1144,14 @@ var init_magic_string_es = __esm({
1144
1144
  if (!newRight) this.lastChunk = last;
1145
1145
  return this;
1146
1146
  }
1147
- overwrite(start, end, content, options) {
1147
+ overwrite(start, end, content2, options) {
1148
1148
  options = options || {};
1149
- return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
1149
+ return this.update(start, end, content2, { ...options, overwrite: !options.contentOnly });
1150
1150
  }
1151
- update(start, end, content, options) {
1151
+ update(start, end, content2, options) {
1152
1152
  start = start + this.offset;
1153
1153
  end = end + this.offset;
1154
- if (typeof content !== "string") throw new TypeError("replacement content must be a string");
1154
+ if (typeof content2 !== "string") throw new TypeError("replacement content must be a string");
1155
1155
  if (this.original.length !== 0) {
1156
1156
  while (start < 0) start += this.original.length;
1157
1157
  while (end < 0) end += this.original.length;
@@ -1193,40 +1193,40 @@ var init_magic_string_es = __esm({
1193
1193
  chunk = chunk.next;
1194
1194
  chunk.edit("", false);
1195
1195
  }
1196
- first.edit(content, storeName, !overwrite);
1196
+ first.edit(content2, storeName, !overwrite);
1197
1197
  } else {
1198
- const newChunk = new Chunk(start, end, "").edit(content, storeName);
1198
+ const newChunk = new Chunk(start, end, "").edit(content2, storeName);
1199
1199
  last.next = newChunk;
1200
1200
  newChunk.previous = last;
1201
1201
  }
1202
1202
  return this;
1203
1203
  }
1204
- prepend(content) {
1205
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
1206
- this.intro = content + this.intro;
1204
+ prepend(content2) {
1205
+ if (typeof content2 !== "string") throw new TypeError("outro content must be a string");
1206
+ this.intro = content2 + this.intro;
1207
1207
  return this;
1208
1208
  }
1209
- prependLeft(index2, content) {
1209
+ prependLeft(index2, content2) {
1210
1210
  index2 = index2 + this.offset;
1211
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1211
+ if (typeof content2 !== "string") throw new TypeError("inserted content must be a string");
1212
1212
  this._split(index2);
1213
1213
  const chunk = this.byEnd[index2];
1214
1214
  if (chunk) {
1215
- chunk.prependLeft(content);
1215
+ chunk.prependLeft(content2);
1216
1216
  } else {
1217
- this.intro = content + this.intro;
1217
+ this.intro = content2 + this.intro;
1218
1218
  }
1219
1219
  return this;
1220
1220
  }
1221
- prependRight(index2, content) {
1221
+ prependRight(index2, content2) {
1222
1222
  index2 = index2 + this.offset;
1223
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1223
+ if (typeof content2 !== "string") throw new TypeError("inserted content must be a string");
1224
1224
  this._split(index2);
1225
1225
  const chunk = this.byStart[index2];
1226
1226
  if (chunk) {
1227
- chunk.prependRight(content);
1227
+ chunk.prependRight(content2);
1228
1228
  } else {
1229
- this.outro = content + this.outro;
1229
+ this.outro = content2 + this.outro;
1230
1230
  }
1231
1231
  return this;
1232
1232
  }
@@ -4343,6 +4343,23 @@ var Workflow = class {
4343
4343
 
4344
4344
  // ../core/src/execution/engine/agent/observability/logging.ts
4345
4345
  function createAgentLogger(logger, agentId, sessionId) {
4346
+ function emitAction(actionType, message, iteration, startTime, endTime, duration) {
4347
+ const event = {
4348
+ type: "agent",
4349
+ agentId,
4350
+ lifecycle: "iteration",
4351
+ eventType: "action",
4352
+ iteration,
4353
+ actionType,
4354
+ startTime,
4355
+ endTime,
4356
+ duration,
4357
+ data: { message },
4358
+ ...sessionId && { sessionId }
4359
+ // Include sessionId if present
4360
+ };
4361
+ logger.info("action", event);
4362
+ }
4346
4363
  return {
4347
4364
  lifecycle(lifecycle, stage, data) {
4348
4365
  let event;
@@ -4409,21 +4426,15 @@ function createAgentLogger(logger, agentId, sessionId) {
4409
4426
  logger.info("reasoning", event);
4410
4427
  },
4411
4428
  action(actionType, message, iteration, startTime, endTime, duration) {
4412
- const event = {
4413
- type: "agent",
4414
- agentId,
4415
- lifecycle: "iteration",
4416
- eventType: "action",
4417
- iteration,
4418
- actionType,
4419
- startTime,
4420
- endTime,
4421
- duration,
4422
- data: { message },
4423
- ...sessionId && { sessionId }
4424
- // Include sessionId if present
4425
- };
4426
- logger.info("action", event);
4429
+ emitAction(actionType, message, iteration, startTime, endTime, duration);
4430
+ },
4431
+ async timed(actionType, iteration, work, message) {
4432
+ const startTime = Date.now();
4433
+ const result = await work();
4434
+ const endTime = Date.now();
4435
+ const resolvedActionType = typeof actionType === "function" ? actionType(result) : actionType;
4436
+ emitAction(resolvedActionType, message(result), iteration, startTime, endTime, endTime - startTime);
4437
+ return result;
4427
4438
  },
4428
4439
  toolCall(toolName, iteration, startTime, endTime, duration, success, error, input, output) {
4429
4440
  const event = {
@@ -4955,8 +4966,8 @@ function preview(text, n2 = 120) {
4955
4966
  // ../core/src/platform/utils/token-counter.ts
4956
4967
  var CHARS_PER_TOKEN = 3.5;
4957
4968
  function estimateTokens(text) {
4958
- const content = typeof text === "string" ? text : JSON.stringify(text);
4959
- const chars4 = content.length;
4969
+ const content2 = typeof text === "string" ? text : JSON.stringify(text);
4970
+ const chars4 = content2.length;
4960
4971
  return Math.ceil(chars4 / CHARS_PER_TOKEN);
4961
4972
  }
4962
4973
  function truncationCharBudget(maxTokens, noticeLength = 0) {
@@ -4996,7 +5007,7 @@ function buildUntrustedDataPolicy(securityLevel) {
4996
5007
  }
4997
5008
  function buildAgentMessages(systemPrompt, memory, currentInput, securityLevel, conversationHistory = []) {
4998
5009
  const policy = buildUntrustedDataPolicy(securityLevel);
4999
- const historyMessages = conversationHistory.map(({ role, content }) => ({ role, content }));
5010
+ const historyMessages = conversationHistory.map(({ role, content: content2 }) => ({ role, content: content2 }));
5000
5011
  if (historyMessages.length > 0) {
5001
5012
  historyMessages[historyMessages.length - 1].cacheBreakpoint = true;
5002
5013
  }
@@ -5351,66 +5362,21 @@ async function processReasoning(iterationContext) {
5351
5362
  reasoning: response.reasoning
5352
5363
  });
5353
5364
  iterationContext.logger.reasoning(response.reasoning, iterationContext.iteration, startTime, endTime, duration);
5354
- const memoryStartTime = Date.now();
5355
- iterationContext.memoryManager.addToHistory({
5356
- type: "reasoning",
5357
- content: response.reasoning,
5358
- turnNumber: iterationContext.executionContext.sessionTurnNumber ?? null,
5359
- iterationNumber: iterationContext.iteration,
5360
- source: "model"
5361
- });
5362
- const memoryEndTime = Date.now();
5363
- const memoryDuration = memoryEndTime - memoryStartTime;
5364
- iterationContext.logger.action(
5365
+ await iterationContext.logger.timed(
5365
5366
  "memory-reasoning",
5366
- `Stored reasoning (${response.reasoning.length} chars), history size: ${iterationContext.memoryManager.getHistoryLength()}, actions: ${response.nextActions.map((a3) => a3.type).join(", ")}`,
5367
5367
  iterationContext.iteration,
5368
- memoryStartTime,
5369
- memoryEndTime,
5370
- memoryDuration
5368
+ () => iterationContext.memoryManager.addToHistory({
5369
+ type: "reasoning",
5370
+ content: response.reasoning,
5371
+ turnNumber: iterationContext.executionContext.sessionTurnNumber ?? null,
5372
+ iterationNumber: iterationContext.iteration,
5373
+ source: "model"
5374
+ }),
5375
+ () => `Stored reasoning (${response.reasoning.length} chars), history size: ${iterationContext.memoryManager.getHistoryLength()}, actions: ${response.nextActions.map((a3) => a3.type).join(", ")}`
5371
5376
  );
5372
5377
  return response;
5373
5378
  }
5374
5379
 
5375
- // ../core/src/execution/engine/agent/memory/domains.ts
5376
- var MEMORY_DOMAINS = {
5377
- /**
5378
- * Tool-owned keys
5379
- * Updated automatically by tools as side effects
5380
- * LLM cannot modify these via memoryOps
5381
- *
5382
- * Tools manage complex structured data (caches, indexes, etc.)
5383
- * that would be error-prone for LLM to update via JSON strings.
5384
- *
5385
- * No tool currently writes these three keys, so in practice the guard reserves the names
5386
- * against the LLM rather than arbitrating a live conflict. That is still enforcement --
5387
- * see `validateMemoryKeyOwnership` in `./utils` -- not dead code.
5388
- */
5389
- TOOL_OWNED: [
5390
- "notion-pages-cache",
5391
- // Notion tools manage page hierarchy
5392
- "github-repo-cache",
5393
- // GitHub tools manage repository structure
5394
- "slack-channel-cache"
5395
- // Slack tools manage channel data
5396
- ]
5397
- /**
5398
- * LLM-owned keys
5399
- * All keys NOT in TOOL_OWNED
5400
- * Managed via memoryOps by agent reasoning
5401
- *
5402
- * LLM manages semantic memory (business context, decisions, etc.)
5403
- * that requires understanding and judgment.
5404
- */
5405
- };
5406
- function isToolOwnedKey(key) {
5407
- return MEMORY_DOMAINS.TOOL_OWNED.includes(key);
5408
- }
5409
- function getKeyOwner(key) {
5410
- if (isToolOwnedKey(key)) return "tool";
5411
- return "llm";
5412
- }
5413
-
5414
5380
  // ../core/src/execution/engine/agent/memory/utils.ts
5415
5381
  function addToolError(memoryManager, action, errorMessage, iteration, turnNumber = null, metadata) {
5416
5382
  memoryManager.addToHistory({
@@ -5434,11 +5400,10 @@ function addToolError(memoryManager, action, errorMessage, iteration, turnNumber
5434
5400
  });
5435
5401
  }
5436
5402
  function validateMemoryKeyOwnership(key, logger, iteration) {
5437
- if (isToolOwnedKey(key)) {
5438
- const owner = getKeyOwner(key);
5403
+ if (key.startsWith("_")) {
5439
5404
  logger.action(
5440
5405
  "memory-set-rejected",
5441
- `Rejected LLM update to ${owner}-managed key: ${key}`,
5406
+ `Rejected LLM update to framework-reserved key: ${key}`,
5442
5407
  iteration,
5443
5408
  Date.now(),
5444
5409
  Date.now(),
@@ -5556,11 +5521,11 @@ function safeStructuralPrefix(raw, cutAt) {
5556
5521
  const base = stripDanglingTail(raw.slice(0, cutPoint), stack[stack.length - 1] === "}");
5557
5522
  return base + [...stack].reverse().join("");
5558
5523
  }
5559
- function truncateContent(content, maxTokens) {
5560
- const estimated = estimateTokens(content);
5561
- if (estimated <= maxTokens) return { content };
5524
+ function truncateContent(content2, maxTokens) {
5525
+ const estimated = estimateTokens(content2);
5526
+ if (estimated <= maxTokens) return { content: content2 };
5562
5527
  const cutAt = truncationCharBudget(maxTokens, CLOSING_BRACKET_RESERVE);
5563
- const safeContent = safeStructuralPrefix(content, cutAt);
5528
+ const safeContent = safeStructuralPrefix(content2, cutAt);
5564
5529
  const omittedTokens = estimated - maxTokens;
5565
5530
  return { content: safeContent, truncated: { omittedTokens } };
5566
5531
  }
@@ -5656,9 +5621,9 @@ async function executeToolCall(iterationContext, action) {
5656
5621
  const validatedResult = tool.outputSchema.parse(rawResult);
5657
5622
  let boundedResult = validatedResult;
5658
5623
  if (tool.maxOutputTokens !== void 0) {
5659
- const { content, truncated } = truncateContent(JSON.stringify(validatedResult), tool.maxOutputTokens);
5624
+ const { content: content2, truncated } = truncateContent(JSON.stringify(validatedResult), tool.maxOutputTokens);
5660
5625
  if (truncated) {
5661
- boundedResult = content;
5626
+ boundedResult = content2;
5662
5627
  }
5663
5628
  }
5664
5629
  const toolEndTime = Date.now();
@@ -5680,25 +5645,19 @@ async function executeToolCall(iterationContext, action) {
5680
5645
  action.input,
5681
5646
  boundedResult
5682
5647
  );
5683
- const memoryStartTime = Date.now();
5684
5648
  const memoryContent = typeof boundedResult === "string" ? boundedResult : JSON.stringify(boundedResult);
5685
- iterationContext.memoryManager.addToHistory({
5686
- type: "tool-result",
5687
- content: memoryContent,
5688
- toolName: action.name,
5689
- turnNumber: iterationContext.executionContext.sessionTurnNumber ?? null,
5690
- iterationNumber: iterationContext.iteration,
5691
- source: "tool"
5692
- });
5693
- const memoryEndTime = Date.now();
5694
- const memoryDuration = memoryEndTime - memoryStartTime;
5695
- iterationContext.logger.action(
5649
+ await iterationContext.logger.timed(
5696
5650
  "memory-tool-result",
5697
- `Stored tool-result for ${action.name} (${memoryContent.length} chars), history size: ${iterationContext.memoryManager.getHistoryLength()}`,
5698
5651
  iterationContext.iteration,
5699
- memoryStartTime,
5700
- memoryEndTime,
5701
- memoryDuration
5652
+ () => iterationContext.memoryManager.addToHistory({
5653
+ type: "tool-result",
5654
+ content: memoryContent,
5655
+ toolName: action.name,
5656
+ turnNumber: iterationContext.executionContext.sessionTurnNumber ?? null,
5657
+ iterationNumber: iterationContext.iteration,
5658
+ source: "tool"
5659
+ }),
5660
+ () => `Stored tool-result for ${action.name} (${memoryContent.length} chars), history size: ${iterationContext.memoryManager.getHistoryLength()}`
5702
5661
  );
5703
5662
  } catch (error) {
5704
5663
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -5721,29 +5680,25 @@ async function executeToolCall(iterationContext, action) {
5721
5680
  action.input,
5722
5681
  void 0
5723
5682
  );
5724
- const memoryStartTime = Date.now();
5725
- const metadata = error instanceof ToolingError ? {
5726
- errorType: error.errorType,
5727
- severity: error.severity,
5728
- isRetryable: error.isRetryable()
5729
- } : void 0;
5730
- addToolError(
5731
- iterationContext.memoryManager,
5732
- action,
5733
- errorMessage,
5734
- iterationContext.iteration,
5735
- iterationContext.executionContext.sessionTurnNumber ?? null,
5736
- metadata
5737
- );
5738
- const memoryEndTime = Date.now();
5739
- const memoryDuration = memoryEndTime - memoryStartTime;
5740
- iterationContext.logger.action(
5683
+ await iterationContext.logger.timed(
5741
5684
  "memory-tool-error",
5742
- `Stored error for ${action.name}: ${errorMessage}, history size: ${iterationContext.memoryManager.getHistoryLength()}`,
5743
5685
  iterationContext.iteration,
5744
- memoryStartTime,
5745
- memoryEndTime,
5746
- memoryDuration
5686
+ () => {
5687
+ const metadata = error instanceof ToolingError ? {
5688
+ errorType: error.errorType,
5689
+ severity: error.severity,
5690
+ isRetryable: error.isRetryable()
5691
+ } : void 0;
5692
+ addToolError(
5693
+ iterationContext.memoryManager,
5694
+ action,
5695
+ errorMessage,
5696
+ iterationContext.iteration,
5697
+ iterationContext.executionContext.sessionTurnNumber ?? null,
5698
+ metadata
5699
+ );
5700
+ },
5701
+ () => `Stored error for ${action.name}: ${errorMessage}, history size: ${iterationContext.memoryManager.getHistoryLength()}`
5747
5702
  );
5748
5703
  }
5749
5704
  }
@@ -5977,15 +5932,17 @@ async function processMemory(memoryManager, response, logger, iteration) {
5977
5932
  if (!response.memoryOps) return;
5978
5933
  const { memoryOps } = response;
5979
5934
  if (memoryOps.set) {
5980
- for (const [key, content] of Object.entries(memoryOps.set)) {
5935
+ for (const [key, content2] of Object.entries(memoryOps.set)) {
5981
5936
  if (!validateMemoryKeyOwnership(key, logger, iteration)) {
5982
5937
  continue;
5983
5938
  }
5984
- const startTime = Date.now();
5985
- const stringValue2 = typeof content === "string" ? content : JSON.stringify(content);
5986
- memoryManager.set(key, stringValue2);
5987
- const endTime = Date.now();
5988
- logger.action("memory-set", `Set: ${key}`, iteration, startTime, endTime, endTime - startTime);
5939
+ await logger.timed(
5940
+ "memory-set",
5941
+ iteration,
5942
+ // Auto-stringify non-string values (arrays, objects, etc.)
5943
+ () => memoryManager.set(key, typeof content2 === "string" ? content2 : JSON.stringify(content2)),
5944
+ () => `Set: ${key}`
5945
+ );
5989
5946
  }
5990
5947
  }
5991
5948
  if (memoryOps.delete) {
@@ -5993,21 +5950,12 @@ async function processMemory(memoryManager, response, logger, iteration) {
5993
5950
  if (!validateMemoryKeyOwnership(key, logger, iteration)) {
5994
5951
  continue;
5995
5952
  }
5996
- const startTime = Date.now();
5997
- const deleted = memoryManager.delete(key);
5998
- const endTime = Date.now();
5999
- if (deleted) {
6000
- logger.action("memory-delete", `Deleted: ${key}`, iteration, startTime, endTime, endTime - startTime);
6001
- } else {
6002
- logger.action(
6003
- "memory-delete-missing",
6004
- `Attempted to delete non-existent key: ${key}`,
6005
- iteration,
6006
- startTime,
6007
- endTime,
6008
- endTime - startTime
6009
- );
6010
- }
5953
+ await logger.timed(
5954
+ (deleted) => deleted ? "memory-delete" : "memory-delete-missing",
5955
+ iteration,
5956
+ () => memoryManager.delete(key),
5957
+ (deleted) => deleted ? `Deleted: ${key}` : `Attempted to delete non-existent key: ${key}`
5958
+ );
6011
5959
  }
6012
5960
  }
6013
5961
  }
@@ -6112,13 +6060,13 @@ var MAX_TOOL_RESULT_TOKENS = 4e3;
6112
6060
 
6113
6061
  // ../core/src/execution/engine/agent/memory/manager.ts
6114
6062
  var ENVELOPE_FULL_RESULT_WINDOW = 3;
6115
- function parseIfJson(content) {
6116
- const trimmed = content.trim();
6117
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return content;
6063
+ function parseIfJson(content2) {
6064
+ const trimmed = content2.trim();
6065
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return content2;
6118
6066
  try {
6119
- return JSON.parse(content);
6067
+ return JSON.parse(content2);
6120
6068
  } catch {
6121
- return content;
6069
+ return content2;
6122
6070
  }
6123
6071
  }
6124
6072
  function isInTurnScope(entry, currentTurn) {
@@ -6134,7 +6082,6 @@ var MemoryManager = class {
6134
6082
  this.constraints = constraints;
6135
6083
  this.logger = logger;
6136
6084
  }
6137
- cachedSnapshot;
6138
6085
  /**
6139
6086
  * Rolling correction for `estimateTokens`'s bias, learned from real provider usage.
6140
6087
  * `undefined` until the first `recordActualUsage` call -- the cold-start state, where
@@ -6182,8 +6129,8 @@ var MemoryManager = class {
6182
6129
  * @param key - Session memory key
6183
6130
  * @param content - String content from agent
6184
6131
  */
6185
- set(key, content, source = "model") {
6186
- const entryTokens = estimateTokens(content);
6132
+ set(key, content2, source = "model") {
6133
+ const entryTokens = estimateTokens(content2);
6187
6134
  let truncated;
6188
6135
  if (entryTokens > MAX_SINGLE_ENTRY_TOKENS) {
6189
6136
  const truncateTime = Date.now();
@@ -6195,13 +6142,13 @@ var MemoryManager = class {
6195
6142
  truncateTime,
6196
6143
  0
6197
6144
  );
6198
- const result = truncateContent(content, MAX_SINGLE_ENTRY_TOKENS);
6199
- content = result.content;
6145
+ const result = truncateContent(content2, MAX_SINGLE_ENTRY_TOKENS);
6146
+ content2 = result.content;
6200
6147
  truncated = result.truncated;
6201
6148
  }
6202
6149
  this.memory.sessionMemory[key] = {
6203
6150
  type: "context",
6204
- content,
6151
+ content: content2,
6205
6152
  timestamp: Date.now(),
6206
6153
  turnNumber: null,
6207
6154
  // Session memory entries are not turn-specific
@@ -6211,7 +6158,7 @@ var MemoryManager = class {
6211
6158
  ...truncated && { truncated },
6212
6159
  // Screened once, here, instead of by re-scanning the whole envelope on every iteration this
6213
6160
  // key gets re-sent for — see `MemoryEntry.warnings`.
6214
- warnings: sanitizeUserInput(content).warnings
6161
+ warnings: sanitizeUserInput(content2).warnings
6215
6162
  };
6216
6163
  }
6217
6164
  /**
@@ -6249,14 +6196,14 @@ var MemoryManager = class {
6249
6196
  iterationNumber: entry.iterationNumber
6250
6197
  });
6251
6198
  }
6252
- let content = entry.content;
6199
+ let content2 = entry.content;
6253
6200
  let truncated;
6254
6201
  if (entry.type === "tool-result" || entry.type === "error") {
6255
- const before = content;
6256
- const result = truncateContent(content, MAX_TOOL_RESULT_TOKENS);
6257
- content = result.content;
6202
+ const before = content2;
6203
+ const result = truncateContent(content2, MAX_TOOL_RESULT_TOKENS);
6204
+ content2 = result.content;
6258
6205
  truncated = result.truncated;
6259
- if (content !== before) {
6206
+ if (content2 !== before) {
6260
6207
  const truncateTime = Date.now();
6261
6208
  this.logger?.action(
6262
6209
  "memory-tool-result-truncate",
@@ -6270,12 +6217,12 @@ var MemoryManager = class {
6270
6217
  }
6271
6218
  this.memory.history.push({
6272
6219
  ...entry,
6273
- content,
6220
+ content: content2,
6274
6221
  timestamp: Date.now(),
6275
6222
  ...truncated && { truncated },
6276
6223
  // Screened once, here, instead of by re-scanning the whole accumulated envelope on every
6277
6224
  // iteration this entry gets re-sent for — see `MemoryEntry.warnings`.
6278
- warnings: sanitizeUserInput(content).warnings
6225
+ warnings: sanitizeUserInput(content2).warnings
6279
6226
  });
6280
6227
  this.autoCompact();
6281
6228
  }
@@ -6423,21 +6370,15 @@ var MemoryManager = class {
6423
6370
  };
6424
6371
  }
6425
6372
  /**
6426
- * Create memory snapshot for persistence
6427
- * Caches snapshot internally for later retrieval
6373
+ * Create a memory snapshot for persistence.
6374
+ *
6375
+ * Stateless: every call returns a fresh `structuredClone` of the current memory, so the caller
6376
+ * owns caching if it needs to hold onto the result across calls (see `Agent.memorySnapshot`).
6377
+ *
6428
6378
  * @returns Deep copy of current memory state
6429
6379
  */
6430
- toSnapshot() {
6431
- this.cachedSnapshot = structuredClone(this.memory);
6432
- return this.cachedSnapshot;
6433
- }
6434
- /**
6435
- * Get cached memory snapshot
6436
- * Returns snapshot created by toSnapshot()
6437
- * @returns Cached snapshot (undefined if toSnapshot() not called yet)
6438
- */
6439
- getSnapshot() {
6440
- return this.cachedSnapshot;
6380
+ snapshot() {
6381
+ return structuredClone(this.memory);
6441
6382
  }
6442
6383
  /**
6443
6384
  * Build the framework framing and the untrusted data envelope for an LLM call.
@@ -6569,6 +6510,12 @@ var Agent = class {
6569
6510
  * reading memory history after the fact, because the emit is the user-visible event and memory
6570
6511
  * can be compacted or restructured without changing whether the turn spoke. */
6571
6512
  spokeThisTurn = false;
6513
+ /** Cached result of `memoryManager.snapshot()` -- `MemoryManager.snapshot()` itself is stateless
6514
+ * (a fresh `structuredClone` every call), so caching the LAST one taken is this class's job. Set
6515
+ * once, in the `finally` around `iterate()` and again in `complete()` -- see `getMemorySnapshot()`
6516
+ * for why `undefined`-before-first-iteration is a contract other callers (`session.ts`, the SDK
6517
+ * worker) depend on. */
6518
+ memorySnapshot;
6572
6519
  /**
6573
6520
  * Create a new agent instance from definition
6574
6521
  * Memory will be initialized during execution
@@ -6609,7 +6556,7 @@ var Agent = class {
6609
6556
  try {
6610
6557
  await this.iterate(this.executionContext);
6611
6558
  } finally {
6612
- this.memoryManager.toSnapshot();
6559
+ this.memorySnapshot = this.memoryManager.snapshot();
6613
6560
  }
6614
6561
  }
6615
6562
  const output = await this.complete();
@@ -6722,22 +6669,21 @@ var Agent = class {
6722
6669
  async initializeMemoryManager(context) {
6723
6670
  const memory = await this.resolveInitialMemory(context);
6724
6671
  const memoryManager = new MemoryManager(memory, this.config.constraints, this.logger);
6725
- const inputStartTime = Date.now();
6726
- memoryManager.addToHistory({
6727
- type: "input",
6728
- content: this.currentInput,
6729
- turnNumber: context.sessionTurnNumber ?? null,
6730
- iterationNumber: 0,
6731
- source: "user"
6732
- });
6733
- const inputEndTime = Date.now();
6734
- this.logger.action(
6672
+ await this.logger.timed(
6735
6673
  "memory-input",
6736
- `Added input entry to history`,
6737
6674
  0,
6738
- inputStartTime,
6739
- inputEndTime,
6740
- inputEndTime - inputStartTime
6675
+ // Kept in history even though the input also travels as its own message: history is what
6676
+ // later iterations and later turns read, and `autoCompact` anchors on `history[0]` as the
6677
+ // original input. `toContextParts` excludes this entry from the current turn's envelope so
6678
+ // the model does not see the same text twice.
6679
+ () => memoryManager.addToHistory({
6680
+ type: "input",
6681
+ content: this.currentInput,
6682
+ turnNumber: context.sessionTurnNumber ?? null,
6683
+ iterationNumber: 0,
6684
+ source: "user"
6685
+ }),
6686
+ () => `Added input entry to history`
6741
6687
  );
6742
6688
  flowLog("agent.initialize", {
6743
6689
  resourceId: this.config.resourceId,
@@ -6759,32 +6705,20 @@ var Agent = class {
6759
6705
  */
6760
6706
  async resolveInitialMemory(context) {
6761
6707
  if (this.initialMemory) {
6762
- const restoreStartTime = Date.now();
6763
- const memory = structuredClone(this.initialMemory);
6764
- const restoreEndTime = Date.now();
6765
- this.logger.action(
6708
+ return this.logger.timed(
6766
6709
  "memory-restore",
6767
- `Restored ${Object.keys(memory.sessionMemory).length} session memory entries`,
6768
6710
  0,
6769
- restoreStartTime,
6770
- restoreEndTime,
6771
- restoreEndTime - restoreStartTime
6711
+ () => structuredClone(this.initialMemory),
6712
+ (memory) => `Restored ${Object.keys(memory.sessionMemory).length} session memory entries`
6772
6713
  );
6773
- return memory;
6774
6714
  }
6775
6715
  if (this.definition.preloadMemory) {
6776
- const preloadStartTime = Date.now();
6777
- const memory = await this.definition.preloadMemory(context);
6778
- const preloadEndTime = Date.now();
6779
- this.logger.action(
6716
+ return this.logger.timed(
6780
6717
  "memory-preload",
6781
- `Preloaded ${Object.keys(memory.sessionMemory).length} session memory entries`,
6782
6718
  0,
6783
- preloadStartTime,
6784
- preloadEndTime,
6785
- preloadEndTime - preloadStartTime
6719
+ () => this.definition.preloadMemory(context),
6720
+ (memory) => `Preloaded ${Object.keys(memory.sessionMemory).length} session memory entries`
6786
6721
  );
6787
- return memory;
6788
6722
  }
6789
6723
  return { sessionMemory: {}, history: [] };
6790
6724
  }
@@ -6918,8 +6852,8 @@ var Agent = class {
6918
6852
  0
6919
6853
  );
6920
6854
  }
6921
- this.memoryManager.toSnapshot();
6922
- const snapshot = this.memoryManager.getSnapshot();
6855
+ const snapshot = this.memoryManager.snapshot();
6856
+ this.memorySnapshot = snapshot;
6923
6857
  const completionEndTime = Date.now();
6924
6858
  this.logger.lifecycle("completion", "completed", {
6925
6859
  startTime: completionStartTime,
@@ -7135,12 +7069,17 @@ Fix the errors and generate a valid output.
7135
7069
  `.trim();
7136
7070
  }
7137
7071
  /**
7138
- * Get memory snapshot after execution
7139
- * Delegates to MemoryManager.getSnapshot()
7140
- * @returns Memory snapshot (only available after execute() completes)
7072
+ * Get memory snapshot after execution.
7073
+ *
7074
+ * `undefined` until the `finally` around `iterate()` (or `complete()`) takes the first snapshot --
7075
+ * `session.ts` and the SDK worker both rely on this to distinguish "no memory produced yet" (a
7076
+ * throw during `initialize()`, before any iteration ran) from "memory exists".
7077
+ *
7078
+ * @returns Memory snapshot (only available after execute() completes, or after a mid-turn throw
7079
+ * past the point `iterate()` began)
7141
7080
  */
7142
7081
  getMemorySnapshot() {
7143
- return this.memoryManager.getSnapshot();
7082
+ return this.memorySnapshot;
7144
7083
  }
7145
7084
  /**
7146
7085
  * How the just-finished turn ended -- see `AgentStopReason`. Set once `iterate()` returns,
@@ -8208,28 +8147,42 @@ z.object({
8208
8147
  limit: z.number().int(),
8209
8148
  offset: z.number().int()
8210
8149
  });
8211
- var AcqArtifactOwnerKindSchema = z.enum(["company", "contact", "deal", "list", "list_member"]);
8150
+ var AcqArtifactOwnerKindSchema = z.enum(["company", "contact", "deal", "list", "list_member", "organization"]);
8212
8151
  z.object({
8213
8152
  ownerKind: AcqArtifactOwnerKindSchema,
8214
- ownerId: UuidSchema
8153
+ ownerId: UuidSchema.optional()
8215
8154
  }).strict();
8155
+ var PipelineIdSchema = z.string().trim().min(1).max(255);
8216
8156
  z.object({
8217
8157
  ownerKind: AcqArtifactOwnerKindSchema,
8218
- ownerId: UuidSchema,
8158
+ // Nullable + optional: an org-owned artifact (ownerKind: 'organization') has no
8159
+ // single owning entity row. See the comment on AcqArtifactOwnerKindSchema above.
8160
+ ownerId: UuidSchema.nullable().optional(),
8219
8161
  kind: z.string().trim().min(1).max(255),
8220
8162
  content: z.record(z.string(), z.unknown()),
8221
- sourceExecutionId: UuidSchema.optional()
8163
+ sourceExecutionId: UuidSchema.optional(),
8164
+ // Nullable + optional: acquisition's own artifacts (audits, proposals, ICP docs) predate the
8165
+ // pipeline concept and have none. `getActiveArtifact` filters on it, so any artifact meant to
8166
+ // be resolvable as "the active document for pipeline X" MUST supply it -- artifacts-platform-tool
8167
+ // .mdx Step 3 defect 1.
8168
+ pipelineId: PipelineIdSchema.nullable().optional()
8222
8169
  }).strict();
8223
8170
  var AcqArtifactResponseSchema = z.object({
8224
8171
  id: z.string(),
8225
8172
  organizationId: z.string(),
8226
8173
  ownerKind: z.string(),
8227
- ownerId: z.string(),
8174
+ // Nullable as of content-pipeline-foundation D14: an org-owned artifact has no owning entity row.
8175
+ // CreateArtifactRequestSchema already accepted a null ownerId; this response schema not doing so
8176
+ // was Step 3 defect 2 -- an org-owned artifact inserted fine and then failed serialization.
8177
+ ownerId: z.string().nullable(),
8228
8178
  kind: z.string(),
8179
+ pipelineId: z.string().nullable(),
8229
8180
  content: z.record(z.string(), z.unknown()),
8230
8181
  sourceExecutionId: z.string().nullable(),
8231
8182
  createdBy: z.string().nullable(),
8232
8183
  createdAt: z.string(),
8184
+ updatedAt: z.string(),
8185
+ isActive: z.boolean(),
8233
8186
  version: z.number().int()
8234
8187
  });
8235
8188
  z.object({
@@ -8695,6 +8648,25 @@ createAdapter("list", [
8695
8648
  "listPendingContactIds"
8696
8649
  ]);
8697
8650
 
8651
+ // src/worker/adapters/artifacts.ts
8652
+ createAdapter("artifacts", [
8653
+ "listArtifacts",
8654
+ "createArtifact",
8655
+ "getActive"
8656
+ ]);
8657
+
8658
+ // src/worker/adapters/content.ts
8659
+ createAdapter("content", [
8660
+ "createItem",
8661
+ "getItem",
8662
+ "listItems",
8663
+ "updateItem",
8664
+ "createAttempt",
8665
+ "listAttempts",
8666
+ "createDistribution",
8667
+ "updateDistribution"
8668
+ ]);
8669
+
8698
8670
  // src/worker/adapters/pdf.ts
8699
8671
  createAdapter("pdf", ["render", "renderToBuffer"]);
8700
8672
 
@@ -9021,9 +8993,23 @@ function compileOrganizationOntology(model) {
9021
8993
  addLegacyActionProjections(ontology, diagnostics, sourcesById, model.actions ?? {}, model.entities ?? {});
9022
8994
  return { ontology: sortResolvedOntologyIndex(ontology), diagnostics };
9023
8995
  }
8996
+
8997
+ // ../core/src/organization-model/readiness/profile-registry.ts
8998
+ var _builtInProfileValidators = /* @__PURE__ */ new Map();
8999
+ function getBuiltInReadinessProfile(profileId) {
9000
+ return _builtInProfileValidators.get(profileId);
9001
+ }
9002
+ var _interfaceMarkerResolvers = /* @__PURE__ */ new Map();
9003
+ function interfaceMarkerKey(systemPath, interfaceKey) {
9004
+ return `${systemPath}::${interfaceKey}`;
9005
+ }
9006
+ function resolveReadinessInterfaceMarker(model, systemPath, interfaceKey) {
9007
+ return _interfaceMarkerResolvers.get(interfaceMarkerKey(systemPath, interfaceKey))?.(model);
9008
+ }
9009
+
9010
+ // ../core/src/organization-model/domains/systems.ts
9024
9011
  var SystemKindSchema = z.enum(["product", "operational", "platform", "diagnostic"]).meta({ label: "System kind", color: "blue" });
9025
9012
  var SystemLifecycleSchema = z.enum(["draft", "beta", "active", "deprecated", "archived"]).meta({ label: "Lifecycle", color: "teal" });
9026
- var SystemStatusSchema = z.enum(["active", "deprecated", "archived"]).meta({ label: "Status", color: "teal" });
9027
9013
  var SystemIdSchema = ModelIdSchema;
9028
9014
  var SystemPathSchema = z.string().trim().min(1).regex(
9029
9015
  /^[a-z0-9][a-z0-9-]*(?:\.[a-z0-9][a-z0-9-]*)*$/,
@@ -9037,8 +9023,7 @@ z.string().trim().min(1).max(200).regex(
9037
9023
  var SystemUiSchema = z.object({
9038
9024
  path: PathSchema,
9039
9025
  surfaces: ReferenceIdsSchema,
9040
- icon: IconNameSchema.optional(),
9041
- order: z.number().int().optional()
9026
+ icon: IconNameSchema.optional()
9042
9027
  });
9043
9028
  var SystemInterfaceKeySchema = ModelIdSchema;
9044
9029
  var SystemInterfaceLifecycleSchema = z.enum(["draft", "active", "disabled", "deprecated", "archived"]).meta({ label: "System interface lifecycle", color: "teal" });
@@ -9067,17 +9052,23 @@ var SystemInterfaceResourceScopeSchema = z.array(ModelIdSchema).default([]);
9067
9052
  var SystemApiInterfaceReadinessContractSchema = z.object({
9068
9053
  /** Ontology IDs of object types the interface depends on. */
9069
9054
  requiredObjects: z.array(z.string().trim().min(1)).default([]),
9070
- /** Ontology IDs of catalog types the interface requires (must be non-empty). */
9071
- requiredCatalogs: z.array(z.string().trim().min(1)).default([]),
9072
- /** Optional ontology kind filters (reserved for future profile extensions). */
9073
- requiredKinds: z.array(z.string().trim().min(1)).optional()
9055
+ /**
9056
+ * Ontology IDs of catalog types the interface requires. Must declare at least one
9057
+ * entry a `readinessContract` with no `requiredCatalogs` asserts nothing at all,
9058
+ * so it has no `.default([])`; omitting the field is rejected the same as an
9059
+ * explicit empty array.
9060
+ */
9061
+ requiredCatalogs: z.array(z.string().trim().min(1)).min(1)
9074
9062
  }).strict();
9075
9063
  var SystemApiInterfaceSchema = z.object({
9076
9064
  lifecycle: SystemInterfaceLifecycleSchema.default("active"),
9077
9065
  /**
9078
9066
  * Open-string profile id. Built-in platform presets are looked up through
9079
9067
  * the profile registry; custom ids are validated structurally via
9080
- * `readinessContract`. Optional `profileForInterface` provides a default.
9068
+ * `readinessContract`. Optional at the schema layer, but readiness
9069
+ * computation rejects an interface that omits it with a
9070
+ * `missing-readiness-profile` diagnostic — there is no positional
9071
+ * fallback to `${systemPath}.${interfaceKey}`.
9081
9072
  */
9082
9073
  readinessProfile: SystemInterfaceReadinessProfileSchema.optional(),
9083
9074
  /**
@@ -9092,17 +9083,11 @@ var SystemApiInterfaceSchema = z.object({
9092
9083
  */
9093
9084
  readinessContract: SystemApiInterfaceReadinessContractSchema.optional()
9094
9085
  }).strict();
9095
- var _profileRegistry = new Map(
9096
- SYSTEM_INTERFACE_READINESS_PROFILES.map((profileId) => [
9097
- profileId,
9098
- { profileId, kind: "built-in" }
9099
- ])
9100
- );
9101
- function profileForInterface(systemPath, interfaceKey, readinessProfile) {
9102
- return readinessProfile ?? `${systemPath}.${interfaceKey}`;
9086
+ function isReservedPlatformProfileId(profileId) {
9087
+ return SYSTEM_INTERFACE_READINESS_PROFILES.includes(profileId);
9103
9088
  }
9104
9089
  function isBuiltInReadinessProfile(profileId) {
9105
- return _profileRegistry.get(profileId)?.kind === "built-in";
9090
+ return isReservedPlatformProfileId(profileId) || getBuiltInReadinessProfile(profileId) !== void 0;
9106
9091
  }
9107
9092
  z.object({
9108
9093
  systemPath: SystemPathSchema,
@@ -9134,7 +9119,7 @@ var SystemEntrySchema = z.object({
9134
9119
  parentSystemId: SystemIdSchema.optional(),
9135
9120
  /** Optional UI presence. Systems without UI omit this. */
9136
9121
  ui: SystemUiSchema.optional(),
9137
- /** Canonical lifecycle state. Replaces Feature.enabled/devOnly and System.status. */
9122
+ /** Canonical lifecycle state. `beta` is what gates a System to dev-mode viewers. */
9138
9123
  lifecycle: SystemLifecycleSchema.optional(),
9139
9124
  /** Optional role responsible for this system. */
9140
9125
  responsibleRoleId: ModelIdSchema.meta({ ref: "role" }).optional(),
@@ -9142,14 +9127,10 @@ var SystemEntrySchema = z.object({
9142
9127
  governedByKnowledge: z.array(ModelIdSchema.meta({ ref: "knowledge" })).default([]).optional(),
9143
9128
  /** Optional actions this system exposes or consumes. */
9144
9129
  actions: z.array(ActionRefSchema).optional(),
9145
- /** Optional operational policies that apply to this system. */
9146
- policies: z.array(ModelIdSchema.meta({ ref: "policy" })).default([]).optional(),
9147
9130
  /** Optional goals this system contributes to. */
9148
9131
  drivesGoals: z.array(ModelIdSchema.meta({ ref: "goal" })).default([]).optional(),
9149
9132
  /** Thin API runtime-boundary marker. Readiness is derived from scoped resources and topology. */
9150
9133
  apiInterface: SystemApiInterfaceSchema.optional(),
9151
- /** @deprecated Use lifecycle. Accepted for one publish cycle. */
9152
- status: SystemStatusSchema.optional(),
9153
9134
  /** @deprecated Use ui.path. Kept for one-cycle Feature compatibility. */
9154
9135
  path: PathSchema.optional(),
9155
9136
  /** @deprecated Use ui.icon. Kept for one-cycle Feature compatibility. */
@@ -9158,9 +9139,6 @@ var SystemEntrySchema = z.object({
9158
9139
  uiPosition: UiPositionSchema.optional(),
9159
9140
  /** @deprecated Use lifecycle. */
9160
9141
  enabled: z.boolean().optional(),
9161
- /** @deprecated Use lifecycle: "beta". */
9162
- devOnly: z.boolean().optional(),
9163
- requiresAdmin: z.boolean().optional(),
9164
9142
  /** Domain-map iteration order. Convention: multiples of 10 (10, 20, 30, ...) to allow easy insertion. */
9165
9143
  order: z.number(),
9166
9144
  /**
@@ -9187,372 +9165,14 @@ var SystemEntrySchema = z.object({
9187
9165
  }).strict().refine((system) => system.label !== void 0 || system.title !== void 0, {
9188
9166
  path: ["label"],
9189
9167
  message: "System must provide label or title"
9190
- }).transform((system) => {
9191
- const normalizedSystem = system.systems !== void 0 && system.subsystems === void 0 ? { ...system, subsystems: system.systems } : system;
9192
- if (normalizedSystem.status === void 0) return normalizedSystem;
9193
- console.warn("[organization-model] System.status is deprecated; use System.lifecycle instead.");
9194
- return normalizedSystem.lifecycle === void 0 ? { ...normalizedSystem, lifecycle: normalizedSystem.status } : normalizedSystem;
9195
- });
9168
+ }).transform(
9169
+ (system) => system.systems !== void 0 && system.subsystems === void 0 ? { ...system, subsystems: system.systems } : system
9170
+ );
9196
9171
  z.record(z.string(), SystemEntrySchema).refine((record) => Object.entries(record).every(([key, entry]) => entry.id === key), {
9197
9172
  message: "Each system entry id must match its map key"
9198
9173
  }).default({});
9199
9174
 
9200
- // ../core/src/organization-model/migration-helpers.ts
9201
- function catalogRecords(model) {
9202
- return Object.values(compileOrganizationOntology(model).ontology.catalogTypes);
9203
- }
9204
- function systemScope(id, fallback) {
9205
- return parseOntologyId(id).scope || fallback || "";
9206
- }
9207
- function entriesOf(catalog) {
9208
- return Object.entries(catalog.entries ?? {}).map(([id, value]) => [
9209
- id,
9210
- value && typeof value === "object" && !Array.isArray(value) ? value : {}
9211
- ]);
9212
- }
9213
- function stringValue(value) {
9214
- return typeof value === "string" ? value : void 0;
9215
- }
9216
- function stringArray(value) {
9217
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
9218
- }
9219
- function numberValue(value, fallback = 0) {
9220
- return typeof value === "number" ? value : fallback;
9221
- }
9222
- function appliesToLocalId(catalog) {
9223
- const appliesTo = catalog.appliesTo;
9224
- if (appliesTo === void 0) return void 0;
9225
- return parseOntologyId(appliesTo).localId;
9226
- }
9227
- function appliesToEntityKind(catalog) {
9228
- const id = appliesToLocalId(catalog);
9229
- if (id === "company" || id === "contact" || id === "project" || id === "milestone" || id === "task") return id;
9230
- if (id === "deal") return void 0;
9231
- return void 0;
9232
- }
9233
- function getLeadGenStageCatalog(model) {
9234
- const results = {};
9235
- for (const catalog of catalogRecords(model).filter(
9236
- (record) => record.kind === "stage" && (record.ownerSystemId ?? systemScope(record.id)) === "sales.lead-gen"
9237
- )) {
9238
- const catalogEntity = appliesToEntityKind(catalog);
9239
- if (catalogEntity !== "company" && catalogEntity !== "contact") continue;
9240
- for (const [entryId, entry] of entriesOf(catalog)) {
9241
- const entity = entry.entity === "contact" ? "contact" : entry.entity === "company" ? "company" : catalogEntity;
9242
- const additionalEntities = stringArray(entry.additionalEntities).filter(
9243
- (item) => item === "company" || item === "contact"
9244
- );
9245
- const recordEntity = entry.recordEntity === "company" || entry.recordEntity === "contact" ? entry.recordEntity : void 0;
9246
- const recordStageKey = stringValue(entry.recordStageKey);
9247
- const readinessTarget = entry.readinessTarget === true ? true : void 0;
9248
- results[entryId] = {
9249
- key: entryId,
9250
- label: stringValue(entry.label) ?? entryId,
9251
- description: stringValue(entry.description) ?? "",
9252
- order: numberValue(entry.order),
9253
- entity,
9254
- ...additionalEntities.length > 0 ? { additionalEntities } : {},
9255
- ...recordEntity ? { recordEntity } : {},
9256
- ...recordStageKey ? { recordStageKey } : {},
9257
- ...readinessTarget ? { readinessTarget } : {}
9258
- };
9259
- }
9260
- }
9261
- return Object.fromEntries(
9262
- Object.entries(results).sort(([, a3], [, b2]) => a3.order - b2.order || a3.key.localeCompare(b2.key))
9263
- );
9264
- }
9265
- z.object({
9266
- success: z.boolean(),
9267
- tool: z.string(),
9268
- method: z.string(),
9269
- result: z.unknown().optional(),
9270
- error: z.string().optional(),
9271
- durationMs: z.number().optional()
9272
- });
9273
- z.object({
9274
- credential: z.string().describe("Credential name registered for this integration")
9275
- });
9276
-
9277
- // ../core/src/execution/engine/llm/schema/compile.ts
9278
- function isPlainObject(value) {
9279
- return typeof value === "object" && value !== null && !Array.isArray(value);
9280
- }
9281
- var UNSUPPORTED_KEYWORDS = /* @__PURE__ */ new Set([
9282
- "minimum",
9283
- "maximum",
9284
- "exclusiveMinimum",
9285
- "exclusiveMaximum",
9286
- "multipleOf",
9287
- "minLength",
9288
- "maxLength",
9289
- "pattern",
9290
- "maxItems",
9291
- "uniqueItems",
9292
- "minProperties",
9293
- "maxProperties",
9294
- "patternProperties",
9295
- "propertyNames",
9296
- "contains",
9297
- "minContains",
9298
- "maxContains",
9299
- "dependentRequired",
9300
- "dependentSchemas",
9301
- "if",
9302
- "then",
9303
- "else",
9304
- "not",
9305
- "$id",
9306
- "$anchor"
9307
- ]);
9308
- var SUPPORTED_FORMATS = /* @__PURE__ */ new Set([
9309
- "date-time",
9310
- "time",
9311
- "date",
9312
- "duration",
9313
- "email",
9314
- "hostname",
9315
- "uri",
9316
- "ipv4",
9317
- "ipv6",
9318
- "uuid"
9319
- ]);
9320
- var MAX_SCHEMA_DEPTH = 32;
9321
- function convertNode(node, state, depth) {
9322
- if (depth > MAX_SCHEMA_DEPTH && state.dialect.strict !== "unsupported") {
9323
- state.blockers.push("depth>32");
9324
- return node;
9325
- }
9326
- if (Array.isArray(node)) {
9327
- return node.map((item) => convertNode(item, state, depth + 1));
9328
- }
9329
- if (!isPlainObject(node)) {
9330
- return node;
9331
- }
9332
- const strictEngaged = state.dialect.strict !== "unsupported";
9333
- const out = {};
9334
- for (const [key, value] of Object.entries(node)) {
9335
- if (key === "$ref" || key === "$defs" || key === "definitions") {
9336
- if (state.dialect.refs === "refuse") {
9337
- state.blockers.push(`unsupported:${key}`);
9338
- out[key] = value;
9339
- continue;
9340
- }
9341
- out[key] = value;
9342
- continue;
9343
- }
9344
- if (key === "$schema") {
9345
- if (!state.dialect.allowsSchemaKeyword) {
9346
- continue;
9347
- }
9348
- out.$schema = value;
9349
- continue;
9350
- }
9351
- if (key === "properties") {
9352
- if (!isPlainObject(value)) {
9353
- out.properties = value;
9354
- continue;
9355
- }
9356
- const properties = {};
9357
- for (const [propertyName, propertySchema] of Object.entries(value)) {
9358
- properties[propertyName] = convertNode(propertySchema, state, depth + 1);
9359
- }
9360
- out.properties = properties;
9361
- continue;
9362
- }
9363
- if (key === "items") {
9364
- out.items = convertNode(value, state, depth + 1);
9365
- continue;
9366
- }
9367
- if (strictEngaged) {
9368
- if (UNSUPPORTED_KEYWORDS.has(key)) {
9369
- continue;
9370
- }
9371
- if (key === "oneOf") {
9372
- out.anyOf = convertNode(value, state, depth + 1);
9373
- continue;
9374
- }
9375
- if (key === "format") {
9376
- if (typeof value === "string" && SUPPORTED_FORMATS.has(value)) {
9377
- out.format = value;
9378
- }
9379
- continue;
9380
- }
9381
- if (key === "minItems") {
9382
- const n2 = typeof value === "number" ? value : 0;
9383
- out.minItems = n2 > 1 ? 1 : n2;
9384
- continue;
9385
- }
9386
- if (key === "type" && Array.isArray(value)) {
9387
- out.anyOf = value.map((t) => ({ type: t }));
9388
- continue;
9389
- }
9390
- if (key === "additionalProperties") {
9391
- continue;
9392
- }
9393
- }
9394
- out[key] = convertNode(value, state, depth + 1);
9395
- }
9396
- const isObjectNode = out.type === "object" || isPlainObject(out.properties);
9397
- if (isObjectNode) {
9398
- const properties = isPlainObject(out.properties) ? out.properties : void 0;
9399
- const originalAdditionalProperties = node.additionalProperties;
9400
- if (strictEngaged) {
9401
- if (properties) {
9402
- const declared = Object.keys(properties);
9403
- const required = Array.isArray(out.required) ? out.required : [];
9404
- const optional = declared.filter((k2) => !required.includes(k2));
9405
- if (state.dialect.strict === "allRequired" && optional.length > 0) {
9406
- state.blockers.push(`optionalProperty:${optional[0]}`);
9407
- }
9408
- state.optionalProperties += optional.length;
9409
- }
9410
- if (originalAdditionalProperties !== void 0 && originalAdditionalProperties !== false && (!properties || Object.keys(properties).length === 0)) {
9411
- state.blockers.push("freeFormObject");
9412
- }
9413
- out.additionalProperties = false;
9414
- }
9415
- if (strictEngaged && (!properties || Object.keys(properties).length === 0)) {
9416
- out.properties = {};
9417
- }
9418
- }
9419
- return out;
9420
- }
9421
- function dedupe(values) {
9422
- return [...new Set(values)];
9423
- }
9424
- function compileSchema(schema, dialect) {
9425
- if (!isPlainObject(schema)) {
9426
- const strictEngaged = dialect.strict !== "unsupported";
9427
- return {
9428
- schema,
9429
- sendStrict: false,
9430
- status: strictEngaged ? "refused" : "notAttempted",
9431
- refusalReasons: strictEngaged ? ["notAnObject"] : []
9432
- };
9433
- }
9434
- const state = { dialect, blockers: [], optionalProperties: 0 };
9435
- const compiled = convertNode(schema, state, 0);
9436
- if (state.blockers.length === 0 && dialect.maxOptionalProperties !== void 0 && state.optionalProperties > dialect.maxOptionalProperties) {
9437
- state.blockers.push(`optionalPropertyLimit:${state.optionalProperties}>${dialect.maxOptionalProperties}`);
9438
- }
9439
- if (dialect.strict === "unsupported") {
9440
- return {
9441
- schema: compiled,
9442
- sendStrict: false,
9443
- status: "notAttempted",
9444
- refusalReasons: []
9445
- };
9446
- }
9447
- if (state.blockers.length > 0) {
9448
- return {
9449
- schema,
9450
- sendStrict: false,
9451
- status: "refused",
9452
- refusalReasons: dedupe(state.blockers)
9453
- };
9454
- }
9455
- return { schema: compiled, sendStrict: true, status: "applied", refusalReasons: [] };
9456
- }
9457
-
9458
- // ../core/src/execution/engine/llm/schema/dialect.ts
9459
- var ANTHROPIC_DIALECT = {
9460
- strict: "optionalAllowed",
9461
- // No placeholder of its own: an empty or absent `properties` becomes a bare `properties: {}`,
9462
- // synthesized directly by the walk for any dialect engaging strict.
9463
- // Refuses rather than inlining: detecting recursion through `$defs` is more machinery than the
9464
- // payoff justifies for a tool-input schema.
9465
- refs: "refuse",
9466
- allowsSchemaKeyword: false,
9467
- // Anthropic's published ceiling. Measured live before this was added: the Command Center
9468
- // assistant's iteration schema declares 33, so 8 of 8 iterations across a 3-turn session were
9469
- // 400'd and retried unstrict. `optionalAllowed` is still correct -- an optional property is
9470
- // representable in this grammar, there is just a cap on how many.
9471
- maxOptionalProperties: 24
9472
- };
9473
- var OPENAI_DIALECT = {
9474
- strict: "allRequired",
9475
- refs: "passthrough",
9476
- allowsSchemaKeyword: false
9477
- };
9478
- var OPENROUTER_DIALECT = {
9479
- strict: "allRequired",
9480
- refs: "refuse",
9481
- allowsSchemaKeyword: false
9482
- };
9483
- var PROVIDER_DIALECTS = {
9484
- anthropic: ANTHROPIC_DIALECT,
9485
- openai: OPENAI_DIALECT,
9486
- openrouter: OPENROUTER_DIALECT
9487
- };
9488
-
9489
- // ../core/src/business/acquisition/ontology-validation.ts
9490
- var LEAD_GEN_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[0];
9491
- var CRM_API_INTERFACE = SYSTEM_INTERFACE_PROFILES[1];
9492
- var LEAD_GEN_CRM_HANDOFF_INTERFACE = SYSTEM_INTERFACE_PROFILES[2];
9493
- LEAD_GEN_API_INTERFACE.readinessProfile;
9494
- CRM_API_INTERFACE.readinessProfile;
9495
- LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile;
9496
- var LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID = formatOntologyId({
9497
- scope: "sales.lead-gen",
9498
- kind: "object",
9499
- localId: "list"
9500
- });
9501
- var LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID = formatOntologyId({
9502
- scope: "sales.lead-gen",
9503
- kind: "object",
9504
- localId: "company"
9505
- });
9506
- var LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID = formatOntologyId({
9507
- scope: "sales.lead-gen",
9508
- kind: "object",
9509
- localId: "contact"
9510
- });
9511
- var LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID = formatOntologyId({
9512
- scope: "sales.lead-gen",
9513
- kind: "catalog",
9514
- localId: "build-template"
9515
- });
9516
- var LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
9517
- scope: "sales.lead-gen",
9518
- kind: "catalog",
9519
- localId: "company-stage"
9520
- });
9521
- var LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
9522
- scope: "sales.lead-gen",
9523
- kind: "catalog",
9524
- localId: "contact-stage"
9525
- });
9526
- var CRM_PIPELINE_CATALOG_ONTOLOGY_ID = formatOntologyId({
9527
- scope: "sales.crm",
9528
- kind: "catalog",
9529
- localId: "crm.pipeline"
9530
- });
9531
- var LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID = formatOntologyId({
9532
- scope: "sales.lead-gen",
9533
- kind: "catalog",
9534
- localId: "lead-gen.stage-catalog"
9535
- });
9536
- function createLeadGenStageCatalog(model) {
9537
- return {
9538
- id: LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID,
9539
- label: "Lead Gen Processing Stages",
9540
- ownerSystemId: "sales.lead-gen",
9541
- kind: "processing-stage-catalog",
9542
- entries: Object.fromEntries(
9543
- Object.entries(getLeadGenStageCatalog(model)).map(([key, entry]) => [
9544
- key,
9545
- {
9546
- ...entry
9547
- }
9548
- ])
9549
- ),
9550
- legacyCatalogKey: "LEAD_GEN_STAGE_CATALOG"
9551
- };
9552
- }
9553
- function isPlainRecord(value) {
9554
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9555
- }
9175
+ // ../core/src/organization-model/readiness/engine.ts
9556
9176
  function addReadinessIssue(issues, family, code, message, details = {}) {
9557
9177
  issues.push({
9558
9178
  family,
@@ -9565,16 +9185,26 @@ function formatInterfaceIdentity(systemPath, interfaceKey) {
9565
9185
  return `${systemPath}/${interfaceKey}`;
9566
9186
  }
9567
9187
  function readinessMarkerPath(context) {
9568
- return context.interfaceKey === "api" ? `systems.${context.systemPath}.apiInterface` : `systems.${context.systemPath}.derivedCrmHandoffReadiness`;
9188
+ return context.interfaceKey === "api" ? `systems.${context.systemPath}.apiInterface` : void 0;
9189
+ }
9190
+ function readinessMarkerFieldPath(context, suffix) {
9191
+ const base = readinessMarkerPath(context);
9192
+ return base === void 0 ? void 0 : `${base}${suffix}`;
9569
9193
  }
9570
9194
  function formatSupportedReadinessProfiles() {
9571
9195
  return SYSTEM_INTERFACE_PROFILES.map((p3) => `"${p3.readinessProfile}"`).join(", ");
9572
9196
  }
9197
+ function isPlainRecord(value) {
9198
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9199
+ }
9200
+ function getCatalogEntries(catalog) {
9201
+ return isPlainRecord(catalog.entries) ? catalog.entries : {};
9202
+ }
9573
9203
  function getActiveScopedResources(model, resourceIds, issues, context) {
9574
9204
  const resources = [];
9575
9205
  for (const [index2, resourceId] of resourceIds.entries()) {
9576
9206
  const resource = model.resources?.[resourceId];
9577
- const path = `${readinessMarkerPath(context)}.resourceIds.${index2}`;
9207
+ const path = readinessMarkerFieldPath(context, `.resourceIds.${index2}`);
9578
9208
  if (resource === void 0) {
9579
9209
  addReadinessIssue(
9580
9210
  issues,
@@ -9619,7 +9249,7 @@ function requireScopedBinding(issues, boundIds, bindingKey, ontologyId, context)
9619
9249
  "SYSTEM_INTERFACE_NOT_READY",
9620
9250
  "missing-resource-binding",
9621
9251
  `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" has no active scoped resource with ontology.${bindingKey} binding "${ontologyId}".`,
9622
- { path: `${readinessMarkerPath(context)}.resourceIds`, ref: ontologyId }
9252
+ { path: readinessMarkerFieldPath(context, ".resourceIds"), ref: ontologyId }
9623
9253
  );
9624
9254
  }
9625
9255
  function ontologyOwnerMatches(ontologyId, expectedSystemPath, catalog) {
@@ -9681,156 +9311,55 @@ function requireCatalogReadiness(issues, index2, catalogId, context) {
9681
9311
  }
9682
9312
  return catalog;
9683
9313
  }
9684
- function requireLeadGenInterfaceReadiness(issues, index2, resources, context) {
9314
+ function requireContractReadiness(issues, index2, resources, contract, context) {
9685
9315
  const reads = resourceBindingIds(resources, "reads");
9686
9316
  const catalogs = resourceBindingIds(resources, "usesCatalogs");
9687
- for (const objectId of [
9688
- LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID,
9689
- LEAD_GEN_COMPANY_OBJECT_ONTOLOGY_ID,
9690
- LEAD_GEN_CONTACT_OBJECT_ONTOLOGY_ID
9691
- ]) {
9317
+ for (const objectId of contract.requiredObjects) {
9692
9318
  requireObjectReadiness(issues, index2, objectId, context);
9693
9319
  requireScopedBinding(issues, reads, "reads", objectId, context);
9694
9320
  }
9695
- for (const catalogId of [
9696
- LEAD_GEN_BUILD_TEMPLATE_CATALOG_ONTOLOGY_ID,
9697
- LEAD_GEN_COMPANY_STAGE_CATALOG_ONTOLOGY_ID,
9698
- LEAD_GEN_CONTACT_STAGE_CATALOG_ONTOLOGY_ID
9699
- ]) {
9321
+ for (const catalogId of contract.requiredCatalogs) {
9700
9322
  requireCatalogReadiness(issues, index2, catalogId, context);
9701
9323
  requireScopedBinding(issues, catalogs, "usesCatalogs", catalogId, context);
9702
9324
  }
9703
- const templateStepCatalog = findLeadGenTemplateStepCatalog(index2);
9704
- if (templateStepCatalog === void 0) {
9705
- addReadinessIssue(
9706
- issues,
9707
- "SYSTEM_INTERFACE_NOT_READY",
9708
- "missing-template-step-catalog",
9709
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" is missing a lead-gen template-step catalog.`
9710
- );
9711
- } else {
9712
- requireCatalogReadiness(issues, index2, templateStepCatalog.id, context);
9713
- requireScopedBinding(issues, catalogs, "usesCatalogs", templateStepCatalog.id, context);
9714
- }
9715
- const leadGenStageCatalog = requireCatalogReadiness(issues, index2, LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID, context);
9716
- return leadGenStageCatalog;
9717
- }
9718
- function requireCrmInterfaceReadiness(issues, index2, resources, context) {
9719
- const catalogs = resourceBindingIds(resources, "usesCatalogs");
9720
- const crmPipelineCatalog = requireCatalogReadiness(issues, index2, CRM_PIPELINE_CATALOG_ONTOLOGY_ID, context);
9721
- requireScopedBinding(issues, catalogs, "usesCatalogs", CRM_PIPELINE_CATALOG_ONTOLOGY_ID, context);
9722
- return crmPipelineCatalog;
9723
- }
9724
- function findSystemInterfaceGrant(model, consumer, provider) {
9725
- return Object.values(model.topology?.relationships ?? {}).find((relationship) => {
9726
- const grant = relationship.metadata?.["systemInterfaceGrant"];
9727
- if (!isPlainRecord(grant) || !isPlainRecord(grant.consumer) || !isPlainRecord(grant.provider)) return false;
9728
- return grant.consumer.systemPath === consumer.systemPath && grant.consumer.interfaceKey === consumer.interfaceKey && grant.provider.systemPath === provider.systemPath && grant.provider.interfaceKey === provider.interfaceKey;
9729
- });
9730
- }
9731
- function requireHandoffBridgeReadiness(issues, model, context) {
9732
- const crmResult = computeInterfaceReadiness(model, CRM_API_INTERFACE);
9733
- if (!crmResult.ready) {
9734
- for (const issue of crmResult.issues) {
9735
- addReadinessIssue(
9736
- issues,
9737
- "SYSTEM_BRIDGE_NOT_READY",
9738
- issue.code,
9739
- `Provider interface ${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)} is not ready: ${issue.message}`,
9740
- { path: issue.path, ref: issue.ref }
9741
- );
9742
- }
9743
- }
9744
- const bridgeGrant = findSystemInterfaceGrant(model, context, CRM_API_INTERFACE);
9745
- if (bridgeGrant === void 0) {
9746
- addReadinessIssue(
9747
- issues,
9748
- "SYSTEM_BRIDGE_NOT_READY",
9749
- "missing-topology-grant",
9750
- `System Interface "${formatInterfaceIdentity(context.systemPath, context.interfaceKey)}" requires a scoped topology grant to "${formatInterfaceIdentity(CRM_API_INTERFACE.systemPath, CRM_API_INTERFACE.interfaceKey)}".`
9751
- );
9752
- }
9753
- return bridgeGrant;
9754
- }
9755
- function getLeadGenCrmHandoffResourceIds(model) {
9756
- return Object.values(model.resources ?? {}).filter(
9757
- (resource) => resource.systemPath === LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath && resource.ontology?.usesCatalogs?.includes(CRM_PIPELINE_CATALOG_ONTOLOGY_ID) === true
9758
- ).map((resource) => resource.id);
9759
9325
  }
9760
9326
  function getSystemInterfaceReadinessMarker(model, request) {
9761
9327
  const system = getSystem(model, request.systemPath);
9762
9328
  if (system === void 0) return void 0;
9763
- if (request.systemPath === LEAD_GEN_CRM_HANDOFF_INTERFACE.systemPath && request.interfaceKey === LEAD_GEN_CRM_HANDOFF_INTERFACE.interfaceKey) {
9764
- return {
9765
- lifecycle: "active",
9766
- readinessProfile: LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile,
9767
- resourceIds: getLeadGenCrmHandoffResourceIds(model)
9768
- };
9769
- }
9329
+ const registeredMarker = resolveReadinessInterfaceMarker(model, request.systemPath, request.interfaceKey);
9330
+ if (registeredMarker !== void 0) return registeredMarker;
9770
9331
  if (request.interfaceKey === "api" && system.apiInterface !== void 0) {
9771
9332
  return system.apiInterface;
9772
9333
  }
9773
9334
  return void 0;
9774
9335
  }
9775
- function mergeLeadGenDerivedCatalogs(model) {
9776
- const baseCatalogTypes = model.ontology?.catalogTypes ?? {};
9777
- const derivedCatalogTypes = {};
9778
- if (baseCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] === void 0) {
9779
- derivedCatalogTypes[LEAD_GEN_STAGE_CATALOG_ONTOLOGY_ID] = createLeadGenStageCatalog(model);
9780
- }
9781
- if (Object.keys(derivedCatalogTypes).length === 0) return model;
9782
- return {
9783
- ...model,
9784
- ontology: {
9785
- ...model.ontology ?? {},
9786
- catalogTypes: {
9787
- ...baseCatalogTypes,
9788
- ...derivedCatalogTypes
9789
- }
9790
- }
9791
- };
9792
- }
9793
- function compileBusinessOntology(model, contractId) {
9794
- const compilation = compileOrganizationOntology(mergeLeadGenDerivedCatalogs(model));
9336
+ function compileReadinessOntology(model, readinessProfile, prepareModel) {
9337
+ const preparedModel = prepareModel !== void 0 ? prepareModel(model) : model;
9338
+ const compilation = compileOrganizationOntology(preparedModel);
9795
9339
  if (compilation.diagnostics.length > 0) {
9796
9340
  const summary = compilation.diagnostics.map((diagnostic) => diagnostic.message).join("; ");
9797
- throw new Error(`${contractId} ontology validation index failed to compile: ${summary}`);
9798
- }
9799
- return {
9800
- ontology: compilation.ontology,
9801
- actionTypesByLegacyId: indexActionTypesByLegacyId(compilation.ontology.actionTypes)
9802
- };
9803
- }
9804
- function tryCompileBusinessOntology(model, readinessProfile, issues) {
9805
- try {
9806
- return compileBusinessOntology(model, readinessProfile);
9807
- } catch (error) {
9808
- addReadinessIssue(
9809
- issues,
9810
- "SYSTEM_INTERFACE_INVALID",
9811
- "ontology-compile-failed",
9812
- error instanceof Error ? error.message : String(error)
9813
- );
9814
- return void 0;
9815
- }
9816
- }
9817
- function requireContractReadiness(issues, index2, resources, contract, context) {
9818
- const reads = resourceBindingIds(resources, "reads");
9819
- const catalogs = resourceBindingIds(resources, "usesCatalogs");
9820
- for (const objectId of contract.requiredObjects) {
9821
- requireObjectReadiness(issues, index2, objectId, context);
9822
- requireScopedBinding(issues, reads, "reads", objectId, context);
9823
- }
9824
- for (const catalogId of contract.requiredCatalogs) {
9825
- requireCatalogReadiness(issues, index2, catalogId, context);
9826
- requireScopedBinding(issues, catalogs, "usesCatalogs", catalogId, context);
9341
+ throw new Error(`${readinessProfile} ontology validation index failed to compile: ${summary}`);
9342
+ }
9343
+ return { ontology: compilation.ontology };
9344
+ }
9345
+ function tryCompileReadinessOntology(model, readinessProfile, prepareModel, issues) {
9346
+ try {
9347
+ return compileReadinessOntology(model, readinessProfile, prepareModel);
9348
+ } catch (error) {
9349
+ addReadinessIssue(
9350
+ issues,
9351
+ "SYSTEM_INTERFACE_INVALID",
9352
+ "ontology-compile-failed",
9353
+ error instanceof Error ? error.message : String(error)
9354
+ );
9355
+ return void 0;
9827
9356
  }
9828
9357
  }
9829
9358
  function computeInterfaceReadiness(model, request) {
9830
9359
  const issues = [];
9831
9360
  const system = getSystem(model, request.systemPath);
9832
9361
  const systemInterface = getSystemInterfaceReadinessMarker(model, request);
9833
- const readinessProfile = systemInterface === void 0 ? void 0 : profileForInterface(request.systemPath, request.interfaceKey, systemInterface.readinessProfile);
9362
+ const readinessProfile = systemInterface?.readinessProfile;
9834
9363
  const scopedResourceIds = systemInterface?.resourceIds ?? [];
9835
9364
  if (system === void 0) {
9836
9365
  addReadinessIssue(
@@ -9870,25 +9399,48 @@ function computeInterfaceReadiness(model, request) {
9870
9399
  "SYSTEM_INTERFACE_DISABLED",
9871
9400
  "inactive-interface",
9872
9401
  `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" lifecycle is "${systemInterface.lifecycle}".`,
9873
- { path: `${readinessMarkerPath(request)}.lifecycle` }
9402
+ { path: readinessMarkerFieldPath(request, ".lifecycle") }
9403
+ );
9404
+ return {
9405
+ ready: false,
9406
+ systemPath: request.systemPath,
9407
+ interfaceKey: request.interfaceKey,
9408
+ readinessProfile,
9409
+ scopedResourceIds,
9410
+ issues
9411
+ };
9412
+ }
9413
+ if (readinessProfile === void 0) {
9414
+ addReadinessIssue(
9415
+ issues,
9416
+ "SYSTEM_INTERFACE_INVALID",
9417
+ "missing-readiness-profile",
9418
+ `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" declares an apiInterface but no readinessProfile. Declare a built-in profile (${formatSupportedReadinessProfiles()}) or a custom id paired with a readinessContract.`,
9419
+ { path: readinessMarkerFieldPath(request, ".readinessProfile") }
9874
9420
  );
9421
+ return {
9422
+ ready: false,
9423
+ systemPath: request.systemPath,
9424
+ interfaceKey: request.interfaceKey,
9425
+ scopedResourceIds,
9426
+ issues
9427
+ };
9875
9428
  }
9876
- const checkedReadinessProfile = readinessProfile ?? profileForInterface(request.systemPath, request.interfaceKey);
9877
- const isBuiltIn = isBuiltInReadinessProfile(checkedReadinessProfile);
9429
+ const isBuiltIn = isBuiltInReadinessProfile(readinessProfile);
9878
9430
  const readinessContract = systemInterface.readinessContract;
9879
9431
  if (!isBuiltIn && readinessContract === void 0) {
9880
9432
  addReadinessIssue(
9881
9433
  issues,
9882
9434
  "SYSTEM_INTERFACE_INVALID",
9883
9435
  "missing-readiness-contract",
9884
- `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" uses custom readiness profile "${checkedReadinessProfile}" but declares no readinessContract. Built-in profiles: ${formatSupportedReadinessProfiles()}.`,
9885
- { path: `${readinessMarkerPath(request)}.readinessContract`, ref: checkedReadinessProfile }
9436
+ `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" uses custom readiness profile "${readinessProfile}" but declares no readinessContract. Built-in profiles: ${formatSupportedReadinessProfiles()}.`,
9437
+ { path: readinessMarkerFieldPath(request, ".readinessContract"), ref: readinessProfile }
9886
9438
  );
9887
9439
  return {
9888
9440
  ready: false,
9889
9441
  systemPath: request.systemPath,
9890
9442
  interfaceKey: request.interfaceKey,
9891
- readinessProfile: checkedReadinessProfile,
9443
+ readinessProfile,
9892
9444
  scopedResourceIds,
9893
9445
  issues
9894
9446
  };
@@ -9899,20 +9451,15 @@ function computeInterfaceReadiness(model, request) {
9899
9451
  "SYSTEM_INTERFACE_NOT_READY",
9900
9452
  "missing-scoped-resources",
9901
9453
  `System Interface "${formatInterfaceIdentity(request.systemPath, request.interfaceKey)}" must scope at least one active resource.`,
9902
- { path: `${readinessMarkerPath(request)}.resourceIds` }
9454
+ { path: readinessMarkerFieldPath(request, ".resourceIds") }
9903
9455
  );
9904
9456
  }
9905
9457
  const resources = getActiveScopedResources(model, scopedResourceIds, issues, request);
9906
- const index2 = tryCompileBusinessOntology(model, checkedReadinessProfile, issues);
9458
+ const registration = getBuiltInReadinessProfile(readinessProfile);
9459
+ const index2 = tryCompileReadinessOntology(model, readinessProfile, registration?.prepareModel, issues);
9907
9460
  if (index2 !== void 0) {
9908
- if (checkedReadinessProfile === LEAD_GEN_API_INTERFACE.readinessProfile) {
9909
- requireLeadGenInterfaceReadiness(issues, index2, resources, request);
9910
- } else if (checkedReadinessProfile === CRM_API_INTERFACE.readinessProfile) {
9911
- requireCrmInterfaceReadiness(issues, index2, resources, request);
9912
- } else if (checkedReadinessProfile === LEAD_GEN_CRM_HANDOFF_INTERFACE.readinessProfile) {
9913
- requireLeadGenInterfaceReadiness(issues, index2, resources, request);
9914
- requireCrmInterfaceReadiness(issues, index2, resources, { ...request, allowForeignOwner: true });
9915
- requireHandoffBridgeReadiness(issues, model, request);
9461
+ if (registration !== void 0) {
9462
+ registration.validate(issues, index2, resources, model, request);
9916
9463
  } else if (readinessContract !== void 0) {
9917
9464
  requireContractReadiness(issues, index2, resources, readinessContract, request);
9918
9465
  }
@@ -9921,30 +9468,235 @@ function computeInterfaceReadiness(model, request) {
9921
9468
  ready: issues.length === 0,
9922
9469
  systemPath: request.systemPath,
9923
9470
  interfaceKey: request.interfaceKey,
9924
- readinessProfile: checkedReadinessProfile,
9471
+ readinessProfile,
9925
9472
  scopedResourceIds,
9926
9473
  issues
9927
9474
  };
9928
9475
  }
9929
- function findLeadGenTemplateStepCatalog(index2) {
9930
- return Object.values(index2.ontology.catalogTypes).find(
9931
- (catalog) => catalog.ownerSystemId === "sales.lead-gen" && catalog.kind === "template-step" && catalog.appliesTo === LEAD_GEN_LIST_OBJECT_ONTOLOGY_ID
9932
- );
9476
+ z.object({
9477
+ success: z.boolean(),
9478
+ tool: z.string(),
9479
+ method: z.string(),
9480
+ result: z.unknown().optional(),
9481
+ error: z.string().optional(),
9482
+ durationMs: z.number().optional()
9483
+ });
9484
+ z.object({
9485
+ credential: z.string().describe("Credential name registered for this integration")
9486
+ });
9487
+
9488
+ // ../core/src/execution/engine/llm/schema/compile.ts
9489
+ function isPlainObject(value) {
9490
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9933
9491
  }
9934
- function indexActionTypesByLegacyId(actionTypes) {
9935
- const byLegacyId = {};
9936
- for (const actionType of Object.values(actionTypes)) {
9937
- const legacyActionId = actionType["legacyActionId"];
9938
- if (typeof legacyActionId === "string") {
9939
- byLegacyId[legacyActionId] = actionType;
9492
+ var UNSUPPORTED_KEYWORDS = /* @__PURE__ */ new Set([
9493
+ "minimum",
9494
+ "maximum",
9495
+ "exclusiveMinimum",
9496
+ "exclusiveMaximum",
9497
+ "multipleOf",
9498
+ "minLength",
9499
+ "maxLength",
9500
+ "pattern",
9501
+ "maxItems",
9502
+ "uniqueItems",
9503
+ "minProperties",
9504
+ "maxProperties",
9505
+ "patternProperties",
9506
+ "propertyNames",
9507
+ "contains",
9508
+ "minContains",
9509
+ "maxContains",
9510
+ "dependentRequired",
9511
+ "dependentSchemas",
9512
+ "if",
9513
+ "then",
9514
+ "else",
9515
+ "not",
9516
+ "$id",
9517
+ "$anchor"
9518
+ ]);
9519
+ var SUPPORTED_FORMATS = /* @__PURE__ */ new Set([
9520
+ "date-time",
9521
+ "time",
9522
+ "date",
9523
+ "duration",
9524
+ "email",
9525
+ "hostname",
9526
+ "uri",
9527
+ "ipv4",
9528
+ "ipv6",
9529
+ "uuid"
9530
+ ]);
9531
+ var MAX_SCHEMA_DEPTH = 32;
9532
+ function convertNode(node, state, depth) {
9533
+ if (depth > MAX_SCHEMA_DEPTH && state.dialect.strict !== "unsupported") {
9534
+ state.blockers.push("depth>32");
9535
+ return node;
9536
+ }
9537
+ if (Array.isArray(node)) {
9538
+ return node.map((item) => convertNode(item, state, depth + 1));
9539
+ }
9540
+ if (!isPlainObject(node)) {
9541
+ return node;
9542
+ }
9543
+ const strictEngaged = state.dialect.strict !== "unsupported";
9544
+ const out = {};
9545
+ for (const [key, value] of Object.entries(node)) {
9546
+ if (key === "$ref" || key === "$defs" || key === "definitions") {
9547
+ if (state.dialect.refs === "refuse") {
9548
+ state.blockers.push(`unsupported:${key}`);
9549
+ out[key] = value;
9550
+ continue;
9551
+ }
9552
+ out[key] = value;
9553
+ continue;
9554
+ }
9555
+ if (key === "$schema") {
9556
+ if (!state.dialect.allowsSchemaKeyword) {
9557
+ continue;
9558
+ }
9559
+ out.$schema = value;
9560
+ continue;
9561
+ }
9562
+ if (key === "properties") {
9563
+ if (!isPlainObject(value)) {
9564
+ out.properties = value;
9565
+ continue;
9566
+ }
9567
+ const properties = {};
9568
+ for (const [propertyName, propertySchema] of Object.entries(value)) {
9569
+ properties[propertyName] = convertNode(propertySchema, state, depth + 1);
9570
+ }
9571
+ out.properties = properties;
9572
+ continue;
9573
+ }
9574
+ if (key === "items") {
9575
+ out.items = convertNode(value, state, depth + 1);
9576
+ continue;
9577
+ }
9578
+ if (strictEngaged) {
9579
+ if (UNSUPPORTED_KEYWORDS.has(key)) {
9580
+ continue;
9581
+ }
9582
+ if (key === "oneOf") {
9583
+ out.anyOf = convertNode(value, state, depth + 1);
9584
+ continue;
9585
+ }
9586
+ if (key === "format") {
9587
+ if (typeof value === "string" && SUPPORTED_FORMATS.has(value)) {
9588
+ out.format = value;
9589
+ }
9590
+ continue;
9591
+ }
9592
+ if (key === "minItems") {
9593
+ const n2 = typeof value === "number" ? value : 0;
9594
+ out.minItems = n2 > 1 ? 1 : n2;
9595
+ continue;
9596
+ }
9597
+ if (key === "type" && Array.isArray(value)) {
9598
+ out.anyOf = value.map((t) => ({ type: t }));
9599
+ continue;
9600
+ }
9601
+ if (key === "additionalProperties") {
9602
+ continue;
9603
+ }
9604
+ }
9605
+ out[key] = convertNode(value, state, depth + 1);
9606
+ }
9607
+ const isObjectNode = out.type === "object" || isPlainObject(out.properties);
9608
+ if (isObjectNode) {
9609
+ const properties = isPlainObject(out.properties) ? out.properties : void 0;
9610
+ const originalAdditionalProperties = node.additionalProperties;
9611
+ if (strictEngaged) {
9612
+ if (properties) {
9613
+ const declared = Object.keys(properties);
9614
+ const required = Array.isArray(out.required) ? out.required : [];
9615
+ const optional = declared.filter((k2) => !required.includes(k2));
9616
+ if (state.dialect.strict === "allRequired" && optional.length > 0) {
9617
+ state.blockers.push(`optionalProperty:${optional[0]}`);
9618
+ }
9619
+ state.optionalProperties += optional.length;
9620
+ }
9621
+ if (originalAdditionalProperties !== void 0 && originalAdditionalProperties !== false && (!properties || Object.keys(properties).length === 0)) {
9622
+ state.blockers.push("freeFormObject");
9623
+ }
9624
+ out.additionalProperties = false;
9625
+ }
9626
+ if (strictEngaged && (!properties || Object.keys(properties).length === 0)) {
9627
+ out.properties = {};
9940
9628
  }
9941
9629
  }
9942
- return byLegacyId;
9630
+ return out;
9943
9631
  }
9944
- function getCatalogEntries(catalog) {
9945
- return isPlainRecord(catalog.entries) ? catalog.entries : {};
9632
+ function dedupe(values) {
9633
+ return [...new Set(values)];
9634
+ }
9635
+ function compileSchema(schema, dialect) {
9636
+ if (!isPlainObject(schema)) {
9637
+ const strictEngaged = dialect.strict !== "unsupported";
9638
+ return {
9639
+ schema,
9640
+ sendStrict: false,
9641
+ status: strictEngaged ? "refused" : "notAttempted",
9642
+ refusalReasons: strictEngaged ? ["notAnObject"] : []
9643
+ };
9644
+ }
9645
+ const state = { dialect, blockers: [], optionalProperties: 0 };
9646
+ const compiled = convertNode(schema, state, 0);
9647
+ if (state.blockers.length === 0 && dialect.maxOptionalProperties !== void 0 && state.optionalProperties > dialect.maxOptionalProperties) {
9648
+ state.blockers.push(`optionalPropertyLimit:${state.optionalProperties}>${dialect.maxOptionalProperties}`);
9649
+ }
9650
+ if (dialect.strict === "unsupported") {
9651
+ return {
9652
+ schema: compiled,
9653
+ sendStrict: false,
9654
+ status: "notAttempted",
9655
+ refusalReasons: []
9656
+ };
9657
+ }
9658
+ if (state.blockers.length > 0) {
9659
+ return {
9660
+ schema,
9661
+ sendStrict: false,
9662
+ status: "refused",
9663
+ refusalReasons: dedupe(state.blockers)
9664
+ };
9665
+ }
9666
+ return { schema: compiled, sendStrict: true, status: "applied", refusalReasons: [] };
9946
9667
  }
9947
9668
 
9669
+ // ../core/src/execution/engine/llm/schema/dialect.ts
9670
+ var ANTHROPIC_DIALECT = {
9671
+ strict: "optionalAllowed",
9672
+ // No placeholder of its own: an empty or absent `properties` becomes a bare `properties: {}`,
9673
+ // synthesized directly by the walk for any dialect engaging strict.
9674
+ // Refuses rather than inlining: detecting recursion through `$defs` is more machinery than the
9675
+ // payoff justifies for a tool-input schema.
9676
+ refs: "refuse",
9677
+ allowsSchemaKeyword: false,
9678
+ // Anthropic's published ceiling. Measured live before this was added: the Command Center
9679
+ // assistant's iteration schema declares 33, so 8 of 8 iterations across a 3-turn session were
9680
+ // 400'd and retried unstrict. `optionalAllowed` is still correct -- an optional property is
9681
+ // representable in this grammar, there is just a cap on how many.
9682
+ maxOptionalProperties: 24
9683
+ };
9684
+ var OPENAI_DIALECT = {
9685
+ strict: "allRequired",
9686
+ refs: "passthrough",
9687
+ allowsSchemaKeyword: false
9688
+ };
9689
+ var OPENROUTER_DIALECT = {
9690
+ strict: "allRequired",
9691
+ refs: "refuse",
9692
+ allowsSchemaKeyword: false
9693
+ };
9694
+ var PROVIDER_DIALECTS = {
9695
+ anthropic: ANTHROPIC_DIALECT,
9696
+ openai: OPENAI_DIALECT,
9697
+ openrouter: OPENROUTER_DIALECT
9698
+ };
9699
+
9948
9700
  // ../core/src/platform/registry/validation.ts
9949
9701
  var RegistryValidationError = class extends Error {
9950
9702
  constructor(orgName, resourceId, field, message) {
@@ -10122,14 +9874,12 @@ function addTopologyIssues(issues, orgName, deployment, organizationModel, syste
10122
9874
  const relationships = organizationModel.topology?.relationships;
10123
9875
  if (relationships === void 0) return;
10124
9876
  const rolesById = new Set(Object.keys(organizationModel.roles ?? {}));
10125
- const policiesById = new Set(Object.keys(organizationModel.policies ?? {}));
10126
9877
  const triggerIds = new Set(deployment.triggers?.map((trigger) => trigger.resourceId) ?? []);
10127
9878
  const humanCheckpointIds = new Set(deployment.humanCheckpoints?.map((checkpoint) => checkpoint.resourceId) ?? []);
10128
9879
  const externalResourceIds = new Set(deployment.externalResources?.map((external) => external.resourceId) ?? []);
10129
9880
  const topologyRefExists = (ref) => {
10130
9881
  if (ref.kind === "system") return systemsById.has(ref.id);
10131
9882
  if (ref.kind === "resource") return omResourcesById.has(ref.id);
10132
- if (ref.kind === "policy") return policiesById.has(ref.id);
10133
9883
  if (ref.kind === "role") return rolesById.has(ref.id);
10134
9884
  if (ref.kind === "trigger") return triggerIds.has(ref.id);
10135
9885
  if (ref.kind === "humanCheckpoint") return humanCheckpointIds.has(ref.id);
@@ -10312,7 +10062,6 @@ function validateDeclaredSystemInterfaceReadiness(orgName, organizationModel) {
10312
10062
  message: `System Interface "${path}/${interfaceKey}" references unknown readiness profile "${readinessProfile}".`
10313
10063
  });
10314
10064
  }
10315
- continue;
10316
10065
  }
10317
10066
  const result = computeInterfaceReadiness(model, { systemPath: path, interfaceKey });
10318
10067
  for (const issue of result.issues) {
@@ -24542,14 +24291,14 @@ function keyToTestName(key) {
24542
24291
  }
24543
24292
  return key.replace(/ \d+$/, "");
24544
24293
  }
24545
- function getSnapshotData(content, options) {
24294
+ function getSnapshotData(content2, options) {
24546
24295
  const update = options.updateSnapshot;
24547
24296
  const data = /* @__PURE__ */ Object.create(null);
24548
24297
  let snapshotContents = "";
24549
24298
  let dirty = false;
24550
- if (content != null) {
24299
+ if (content2 != null) {
24551
24300
  try {
24552
- snapshotContents = content;
24301
+ snapshotContents = content2;
24553
24302
  const populate = new Function("exports", snapshotContents);
24554
24303
  populate(data);
24555
24304
  } catch {
@@ -24594,16 +24343,16 @@ function normalizeNewlines(string2) {
24594
24343
  }
24595
24344
  async function saveSnapshotFile(environment, snapshotData, snapshotPath) {
24596
24345
  const snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`);
24597
- const content = `${environment.getHeader()}
24346
+ const content2 = `${environment.getHeader()}
24598
24347
 
24599
24348
  ${snapshots.join("\n\n")}
24600
24349
  `;
24601
24350
  const oldContent = await environment.readSnapshotFile(snapshotPath);
24602
- const skipWriting = oldContent != null && oldContent === content;
24351
+ const skipWriting = oldContent != null && oldContent === content2;
24603
24352
  if (skipWriting) {
24604
24353
  return;
24605
24354
  }
24606
- await environment.saveSnapshotFile(snapshotPath, content);
24355
+ await environment.saveSnapshotFile(snapshotPath, content2);
24607
24356
  }
24608
24357
  function deepMergeArray(target = [], source = []) {
24609
24358
  const mergedOutput = Array.from(target);
@@ -24754,8 +24503,8 @@ var SnapshotState = class _SnapshotState {
24754
24503
  }
24755
24504
  static async create(testFilePath, options) {
24756
24505
  const snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath);
24757
- const content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath);
24758
- return new _SnapshotState(testFilePath, snapshotPath, content, options);
24506
+ const content2 = await options.snapshotEnvironment.readSnapshotFile(snapshotPath);
24507
+ return new _SnapshotState(testFilePath, snapshotPath, content2, options);
24759
24508
  }
24760
24509
  get environment() {
24761
24510
  return this._environment;
@@ -27984,6 +27733,20 @@ var mockList = (overrides) => createMockAdapter(
27984
27733
  ],
27985
27734
  overrides
27986
27735
  );
27736
+ var mockArtifacts = (overrides) => createMockAdapter(["listArtifacts", "createArtifact", "getActive"], overrides);
27737
+ var mockContent = (overrides) => createMockAdapter(
27738
+ [
27739
+ "createItem",
27740
+ "getItem",
27741
+ "listItems",
27742
+ "updateItem",
27743
+ "createAttempt",
27744
+ "listAttempts",
27745
+ "createDistribution",
27746
+ "updateDistribution"
27747
+ ],
27748
+ overrides
27749
+ );
27987
27750
  var mockPdf = (overrides) => createMockAdapter(["render", "renderToBuffer"], overrides);
27988
27751
  var mockApproval = (overrides) => createMockAdapter(["create", "deleteByMetadata"], overrides);
27989
27752
  var mockExecution = (overrides) => createMockAdapter(["trigger", "triggerAsync"], overrides);
@@ -28366,4 +28129,4 @@ chai/index.js:
28366
28129
  *)
28367
28130
  */
28368
28131
 
28369
- export { assertResourceRegistry, createMockAnymailfinder, createMockApify, createMockAttio, createMockDropbox, createMockGmail, createMockGoogleSheets, createMockInstantly, createMockMillionVerifier, createMockResend, createMockSignatureApi, createMockStripe, createMockTomba, mockAcqDb, mockApproval, mockCrm, mockEmail, mockExecution, mockList, mockLlm, mockNotifications, mockPdf, mockProjects, mockScheduler, mockStorage, runLinearWorkflow, runWorkflow };
28132
+ export { assertResourceRegistry, createMockAnymailfinder, createMockApify, createMockAttio, createMockDropbox, createMockGmail, createMockGoogleSheets, createMockInstantly, createMockMillionVerifier, createMockResend, createMockSignatureApi, createMockStripe, createMockTomba, mockAcqDb, mockApproval, mockArtifacts, mockContent, mockCrm, mockEmail, mockExecution, mockList, mockLlm, mockNotifications, mockPdf, mockProjects, mockScheduler, mockStorage, runLinearWorkflow, runWorkflow };