@treeseed/sdk 0.12.62 → 0.13.0-rc.10

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 (1108) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +33 -359
  3. package/dist/accounts/account-contracts.d.ts +170 -0
  4. package/dist/accounts/account-contracts.js +33 -0
  5. package/dist/agent-capacity/allocation.d.ts +186 -0
  6. package/dist/agent-capacity/allocation.js +226 -0
  7. package/dist/agent-capacity/artifact-mutation-receipt.d.ts +49 -0
  8. package/dist/agent-capacity/artifact-mutation-receipt.js +36 -0
  9. package/dist/agent-capacity/artifacts.d.ts +107 -0
  10. package/dist/agent-capacity/artifacts.js +39 -0
  11. package/dist/agent-capacity/authority/agent-authority-presets.d.ts +13 -0
  12. package/dist/agent-capacity/authority/agent-authority-presets.js +106 -0
  13. package/dist/agent-capacity/contracts/capacity/assignments/assignment-records.d.ts +269 -0
  14. package/dist/agent-capacity/contracts/capacity/assignments/assignment-records.js +10 -0
  15. package/dist/agent-capacity/contracts/capacity/communication/communication-records.d.ts +101 -0
  16. package/dist/agent-capacity/contracts/capacity/communication/communication-records.js +9 -0
  17. package/dist/agent-capacity/contracts/capacity/providers/supply-policy.d.ts +36 -0
  18. package/dist/agent-capacity/contracts/capacity/providers/supply-policy.js +4 -0
  19. package/dist/agent-capacity/contracts/capacity/workdays/workday-records.d.ts +188 -0
  20. package/dist/agent-capacity/contracts/configuration/configuration.d.ts +11 -0
  21. package/dist/agent-capacity/contracts/configuration/configuration.js +20 -0
  22. package/dist/agent-capacity/contracts/operations/research-workflow.d.ts +59 -0
  23. package/dist/agent-capacity/contracts/operations/research-workflow.js +16 -0
  24. package/dist/agent-capacity/contracts/operations/workflow-promotion.d.ts +24 -0
  25. package/dist/agent-capacity/contracts/projects/agents/project-agent-class.d.ts +37 -0
  26. package/dist/agent-capacity/contracts/runtime/runtime-observability.d.ts +335 -0
  27. package/dist/agent-capacity/contracts/support/agent-atlas.d.ts +185 -0
  28. package/dist/agent-capacity/contracts/support/agent-atlas.js +47 -0
  29. package/dist/agent-capacity/contracts/support/agent-lab-monitoring.d.ts +96 -0
  30. package/dist/agent-capacity/contracts/support/agent-lab-monitoring.js +14 -0
  31. package/dist/agent-capacity/contracts/support/authority/execution-mode.d.ts +10 -0
  32. package/dist/agent-capacity/contracts/support/authority/execution-mode.js +17 -0
  33. package/dist/agent-capacity/contracts/support/decision-work.d.ts +251 -0
  34. package/dist/agent-capacity/contracts/support/failure-records.d.ts +9 -0
  35. package/dist/agent-capacity/contracts/support/failure-records.js +0 -0
  36. package/dist/agent-capacity/contracts/support/financial-records.d.ts +124 -0
  37. package/dist/agent-capacity/contracts/support/financial-records.js +0 -0
  38. package/dist/agent-capacity/contracts/support/planning-records.d.ts +121 -0
  39. package/dist/agent-capacity/contracts/support/planning-records.js +0 -0
  40. package/dist/agent-capacity/contracts/support/research-citation.d.ts +15 -0
  41. package/dist/agent-capacity/contracts/support/research-citation.js +0 -0
  42. package/dist/agent-capacity/contracts/support/research-source-policy.d.ts +8 -0
  43. package/dist/agent-capacity/contracts/support/research-source-policy.js +0 -0
  44. package/dist/agent-capacity/contracts/support/time-capacity.d.ts +163 -0
  45. package/dist/agent-capacity/contracts/support/time-capacity.js +63 -0
  46. package/dist/agent-capacity/policy/capacity/allocations/allocation-hierarchy.d.ts +29 -0
  47. package/dist/agent-capacity/policy/capacity/allocations/allocation-hierarchy.js +110 -0
  48. package/dist/agent-capacity/validation/activity-profile.d.ts +12 -0
  49. package/dist/agent-capacity/validation/activity-profile.js +264 -0
  50. package/dist/agent-capacity/validation/agent-definition-schema.d.ts +9140 -0
  51. package/dist/agent-capacity/validation/agent-definition-schema.js +198 -0
  52. package/dist/agent-capacity/validation/agent-lab-forensics-schema.d.ts +234 -0
  53. package/dist/agent-capacity/validation/agent-lab-forensics-schema.js +104 -0
  54. package/dist/agent-capacity/validation/agent-signal.d.ts +30 -0
  55. package/dist/agent-capacity/validation/agent-signal.js +31 -0
  56. package/dist/agent-capacity/validation/allocation.d.ts +12 -0
  57. package/dist/agent-capacity/validation/allocation.js +115 -0
  58. package/dist/agent-capacity/validation/assignment-records.d.ts +16 -0
  59. package/dist/agent-capacity/validation/assignment-records.js +92 -0
  60. package/dist/agent-capacity/validation/configuration.d.ts +14 -0
  61. package/dist/agent-capacity/validation/configuration.js +23 -0
  62. package/dist/agent-capacity/validation/index.d.ts +11 -0
  63. package/dist/agent-capacity/validation/index.js +11 -0
  64. package/dist/agent-capacity/validation/proposal-type.d.ts +22 -0
  65. package/dist/agent-capacity/validation/proposal-type.js +21 -0
  66. package/dist/agent-capacity/validation/research/citation.d.ts +16 -0
  67. package/dist/agent-capacity/validation/research/citation.js +47 -0
  68. package/dist/agent-capacity/validation/research/source-policy.d.ts +11 -0
  69. package/dist/agent-capacity/validation/research/source-policy.js +26 -0
  70. package/dist/agent-capacity/validation/research/workflow.d.ts +10 -0
  71. package/dist/agent-capacity/validation/research/workflow.js +31 -0
  72. package/dist/agent-capacity/validation/workflow-promotion.d.ts +2 -0
  73. package/dist/agent-capacity/validation/workflow-promotion.js +34 -0
  74. package/dist/agent-capacity/workday.d.ts +52 -0
  75. package/dist/agent-capacity/workday.js +105 -0
  76. package/dist/ai-appliance/contracts.d.ts +90 -0
  77. package/dist/ai-appliance/contracts.js +16 -0
  78. package/dist/ai-appliance/validation.d.ts +4 -0
  79. package/dist/ai-appliance/validation.js +62 -0
  80. package/dist/capacity/agents/agent-capacity.d.ts +21 -0
  81. package/dist/capacity/agents/agent-capacity.js +20 -0
  82. package/dist/capacity/capacity-core/capacity-pagination.d.ts +18 -0
  83. package/dist/capacity/capacity-core/capacity-pagination.js +33 -0
  84. package/dist/capacity/providers/capacity-provider.d.ts +1 -0
  85. package/dist/capacity/providers/capacity-provider.js +1 -0
  86. package/dist/capacity-provider/client.d.ts +56 -0
  87. package/dist/capacity-provider/client.js +163 -0
  88. package/dist/capacity-provider/contracts/capacity-facts.d.ts +64 -0
  89. package/dist/capacity-provider/contracts/capacity-facts.js +0 -0
  90. package/dist/capacity-provider/contracts/governance.d.ts +399 -0
  91. package/dist/capacity-provider/contracts/governance.js +18 -0
  92. package/dist/capacity-provider/contracts/index.d.ts +2 -0
  93. package/dist/capacity-provider/contracts/index.js +2 -0
  94. package/dist/capacity-provider/index.d.ts +3 -0
  95. package/dist/capacity-provider/index.js +3 -0
  96. package/dist/capacity-provider/validation.d.ts +27 -0
  97. package/dist/capacity-provider/validation.js +184 -0
  98. package/dist/configuration/secrets-capability.d.ts +4 -0
  99. package/dist/configuration/secrets-capability.js +4 -0
  100. package/dist/content/contracts.d.ts +12 -0
  101. package/dist/content/contracts.js +0 -0
  102. package/dist/content/validation/agent-operational-content-schemas.d.ts +1351 -0
  103. package/dist/content/validation/agent-operational-content-schemas.js +146 -0
  104. package/dist/content/validation/auxiliary-content-schemas.d.ts +1715 -0
  105. package/dist/content/validation/auxiliary-content-schemas.js +173 -0
  106. package/dist/content/validation/content-model-schemas.d.ts +21728 -0
  107. package/dist/content/validation/content-model-schemas.js +271 -0
  108. package/dist/content/validation/index.d.ts +3 -0
  109. package/dist/content/validation/index.js +3 -0
  110. package/dist/content/validation/portable-content-data.d.ts +2101 -0
  111. package/dist/content/validation/portable-content-data.js +49 -0
  112. package/dist/entrypoints/clients/control-plane-client.d.ts +112 -0
  113. package/dist/entrypoints/clients/control-plane-client.js +180 -0
  114. package/dist/entrypoints/models/field-aliases.d.ts +11 -0
  115. package/dist/entrypoints/models/model-registry.d.ts +3 -0
  116. package/dist/entrypoints/models/model-registry.js +3 -0
  117. package/dist/entrypoints/models/sdk-fields.d.ts +11 -0
  118. package/dist/entrypoints/models/sdk-types.d.ts +10 -0
  119. package/dist/entrypoints/models/sdk-types.js +10 -0
  120. package/dist/feedback/contracts.d.ts +142 -0
  121. package/dist/feedback/contracts.js +18 -0
  122. package/dist/feedback/index.d.ts +1 -0
  123. package/dist/feedback/index.js +1 -0
  124. package/dist/governance/groups/contracts.d.ts +102 -0
  125. package/dist/governance/groups/contracts.js +6 -0
  126. package/dist/graph/context-query-contracts.d.ts +19 -1
  127. package/dist/graph/context-query-contracts.js +49 -8
  128. package/dist/knowledge/contracts.d.ts +173 -0
  129. package/dist/knowledge/contracts.js +16 -0
  130. package/dist/knowledge/index.d.ts +1 -0
  131. package/dist/knowledge/index.js +1 -0
  132. package/dist/model-registry/agent-operational-models.d.ts +4 -0
  133. package/dist/model-registry/agent-operational-models.js +38 -0
  134. package/dist/model-registry/build-builtin-model-registry.d.ts +2 -0
  135. package/dist/model-registry/build-builtin-model-registry.js +426 -0
  136. package/dist/model-registry/content-root.d.ts +9 -0
  137. package/dist/model-registry/content-root.js +33 -0
  138. package/dist/model-registry/discussion-models.d.ts +4 -0
  139. package/dist/model-registry/discussion-models.js +84 -0
  140. package/dist/model-registry/group-models.d.ts +2 -0
  141. package/dist/model-registry/group-models.js +52 -0
  142. package/dist/model-registry/knowledge-models.d.ts +2 -0
  143. package/dist/model-registry/knowledge-models.js +89 -0
  144. package/dist/model-registry/normalize-definition.d.ts +8 -0
  145. package/dist/model-registry/normalize-definition.js +69 -0
  146. package/dist/operator-contracts/canonical-command-tree.d.ts +3 -0
  147. package/dist/operator-contracts/canonical-command-tree.js +81 -0
  148. package/dist/operator-contracts/command-tree.d.ts +79 -0
  149. package/dist/operator-contracts/command-tree.js +53 -0
  150. package/dist/operator-contracts/control-plane-operation.d.ts +80 -0
  151. package/dist/operator-contracts/control-plane-operation.js +75 -0
  152. package/dist/operator-contracts/control-plane-operations.d.ts +546 -0
  153. package/dist/operator-contracts/control-plane-operations.js +352 -0
  154. package/dist/operator-contracts/index.d.ts +8 -0
  155. package/dist/operator-contracts/index.js +8 -0
  156. package/dist/operator-contracts/mcp.d.ts +78 -0
  157. package/dist/operator-contracts/mcp.js +23 -0
  158. package/dist/operator-contracts/oauth.d.ts +46 -0
  159. package/dist/operator-contracts/oauth.js +0 -0
  160. package/dist/operator-contracts/workday-lifecycle.d.ts +157 -0
  161. package/dist/operator-contracts/workday-lifecycle.js +65 -0
  162. package/dist/operator-contracts/workday-profile.d.ts +72 -0
  163. package/dist/operator-contracts/workday-profile.js +106 -0
  164. package/dist/projects/projects-core/project-workflow.d.ts +179 -0
  165. package/dist/projects/projects-core/project-workflow.js +66 -0
  166. package/dist/sdk-types/configuration/sdk-dispatch-credential-source.d.ts +201 -0
  167. package/dist/sdk-types/configuration/sdk-dispatch-credential-source.js +0 -0
  168. package/dist/sdk-types/control-plane/resource-requests.d.ts +124 -0
  169. package/dist/sdk-types/control-plane/resource-requests.js +0 -0
  170. package/dist/sdk-types/governance/commons/commons-question-input.d.ts +61 -0
  171. package/dist/sdk-types/governance/commons/commons-question-input.js +0 -0
  172. package/dist/sdk-types/support/planning-policy.d.ts +210 -0
  173. package/dist/sdk-types/support/planning-policy.js +0 -0
  174. package/dist/sdk-types/support/platform-contracts.d.ts +178 -0
  175. package/dist/sdk-types/support/platform-contracts.js +15 -0
  176. package/dist/sdk-types/support/sdk-model-names.d.ts +44 -0
  177. package/dist/sdk-types/support/sdk-model-names.js +80 -0
  178. package/dist/sdk-types/support/sdk-search-request.d.ts +182 -0
  179. package/dist/sdk-types/support/sdk-search-request.js +0 -0
  180. package/dist/sdk-types/support/task-planning.d.ts +189 -0
  181. package/dist/sdk-types/support/task-planning.js +0 -0
  182. package/dist/sdk-types/treedx/graph/sdk-graph-query-request.d.ts +157 -0
  183. package/dist/sdk-types/treedx/graph/sdk-graph-query-request.js +0 -0
  184. package/dist/secrets-capability/provider-operation-contracts.d.ts +90 -0
  185. package/dist/secrets-capability/provider-operation-contracts.js +10 -0
  186. package/dist/secrets-capability/service-provider-contracts.d.ts +92 -0
  187. package/dist/secrets-capability/service-provider-contracts.js +183 -0
  188. package/dist/secrets-capability/service-vault-contracts.d.ts +61 -0
  189. package/dist/secrets-capability/service-vault-contracts.js +39 -0
  190. package/dist/secrets-capability/workflow-operation-contracts.d.ts +95 -0
  191. package/dist/secrets-capability/workflow-operation-contracts.js +0 -0
  192. package/dist/standards/canonicalize.d.ts +10 -0
  193. package/dist/standards/canonicalize.js +43 -0
  194. package/dist/standards/compatibility-attestation.d.ts +23 -0
  195. package/dist/standards/compatibility-attestation.js +40 -0
  196. package/dist/standards/composition.d.ts +15 -0
  197. package/dist/standards/composition.js +14 -0
  198. package/dist/standards/contract-bundle.d.ts +8 -0
  199. package/dist/standards/contract-bundle.js +23 -0
  200. package/dist/standards/contracts.d.ts +39 -0
  201. package/dist/standards/contracts.js +0 -0
  202. package/dist/standards/errors.d.ts +6 -0
  203. package/dist/standards/errors.js +13 -0
  204. package/dist/standards/index.d.ts +8 -0
  205. package/dist/standards/index.js +8 -0
  206. package/dist/standards/mcp/compare.d.ts +2 -0
  207. package/dist/standards/mcp/compare.js +38 -0
  208. package/dist/standards/mcp/contracts.d.ts +34 -0
  209. package/dist/standards/mcp/contracts.js +0 -0
  210. package/dist/standards/mcp/index.d.ts +3 -0
  211. package/dist/standards/mcp/index.js +3 -0
  212. package/dist/standards/mcp/normalize.d.ts +4 -0
  213. package/dist/standards/mcp/normalize.js +30 -0
  214. package/dist/standards/openapi/compare.d.ts +2 -0
  215. package/dist/standards/openapi/compare.js +112 -0
  216. package/dist/standards/openapi/contracts.d.ts +24 -0
  217. package/dist/standards/openapi/contracts.js +0 -0
  218. package/dist/standards/openapi/index.d.ts +3 -0
  219. package/dist/standards/openapi/index.js +3 -0
  220. package/dist/standards/openapi/normalize.d.ts +2 -0
  221. package/dist/standards/openapi/normalize.js +57 -0
  222. package/dist/standards/package-manifest.d.ts +37 -0
  223. package/dist/standards/package-manifest.js +89 -0
  224. package/dist/standards/portfolio-entry.d.ts +12 -0
  225. package/dist/standards/portfolio-entry.js +11 -0
  226. package/dist/standards/typescript/compare.d.ts +2 -0
  227. package/dist/standards/typescript/compare.js +88 -0
  228. package/dist/standards/typescript/contracts.d.ts +44 -0
  229. package/dist/standards/typescript/contracts.js +0 -0
  230. package/dist/standards/typescript/extract.d.ts +10 -0
  231. package/dist/standards/typescript/extract.js +244 -0
  232. package/dist/standards/typescript/index.d.ts +3 -0
  233. package/dist/standards/typescript/index.js +3 -0
  234. package/dist/treedx/accounts/auth.d.ts +17 -0
  235. package/dist/treedx/accounts/auth.js +48 -0
  236. package/dist/treedx/client/accounts/contracts/auth-mode.d.ts +3 -0
  237. package/dist/treedx/client/accounts/contracts/auth-mode.js +6 -0
  238. package/dist/treedx/client/build/creation/build-context.d.ts +3 -0
  239. package/dist/treedx/client/build/creation/build-context.js +7 -0
  240. package/dist/treedx/client/build/creation/build-snapshot.d.ts +3 -0
  241. package/dist/treedx/client/build/creation/build-snapshot.js +8 -0
  242. package/dist/treedx/client/capacity/allocations/contracts/put-capability-grant.d.ts +3 -0
  243. package/dist/treedx/client/capacity/allocations/contracts/put-capability-grant.js +7 -0
  244. package/dist/treedx/client/capacity/allocations/queries/list-capability-grants.d.ts +6 -0
  245. package/dist/treedx/client/capacity/allocations/queries/list-capability-grants.js +10 -0
  246. package/dist/treedx/client/methods.d.ts +102 -0
  247. package/dist/treedx/client/methods.js +209 -0
  248. package/dist/treedx/client/persistence/contracts/restore-storage.d.ts +3 -0
  249. package/dist/treedx/client/persistence/contracts/restore-storage.js +6 -0
  250. package/dist/treedx/client/persistence/lifecycle/verify-storage-restore.d.ts +3 -0
  251. package/dist/treedx/client/persistence/lifecycle/verify-storage-restore.js +6 -0
  252. package/dist/treedx/client/repositories/creation/register-repository.d.ts +3 -0
  253. package/dist/treedx/client/repositories/creation/register-repository.js +7 -0
  254. package/dist/treedx/client/repositories/queries/get-repository.d.ts +3 -0
  255. package/dist/treedx/client/repositories/queries/get-repository.js +7 -0
  256. package/dist/treedx/client/repositories/queries/list-repository-paths.d.ts +3 -0
  257. package/dist/treedx/client/repositories/queries/list-repository-paths.js +7 -0
  258. package/dist/treedx/client/repositories/queries/list-repository-refs.d.ts +3 -0
  259. package/dist/treedx/client/repositories/queries/list-repository-refs.js +12 -0
  260. package/dist/treedx/client/repositories/queries/query-repository.d.ts +3 -0
  261. package/dist/treedx/client/repositories/queries/query-repository.js +7 -0
  262. package/dist/treedx/client/repositories/queries/read-repository-file.d.ts +3 -0
  263. package/dist/treedx/client/repositories/queries/read-repository-file.js +6 -0
  264. package/dist/treedx/client/repositories/queries/read-repository-files.d.ts +3 -0
  265. package/dist/treedx/client/repositories/queries/read-repository-files.js +7 -0
  266. package/dist/treedx/client/repositories/queries/search-repository-files.d.ts +3 -0
  267. package/dist/treedx/client/repositories/queries/search-repository-files.js +7 -0
  268. package/dist/treedx/client/support/contracts/treedx/artifacts/contracts/download-artifact.d.ts +3 -0
  269. package/dist/treedx/client/support/contracts/treedx/artifacts/contracts/download-artifact.js +9 -0
  270. package/dist/treedx/client/support/contracts/treedx/authorization/contracts/whoami.d.ts +3 -0
  271. package/dist/treedx/client/support/contracts/treedx/authorization/contracts/whoami.js +6 -0
  272. package/dist/treedx/client/support/contracts/treedx/graph/contracts/parse-context-dsl.d.ts +3 -0
  273. package/dist/treedx/client/support/contracts/treedx/graph/contracts/parse-context-dsl.js +7 -0
  274. package/dist/treedx/client/support/contracts/treedx/health/contracts/deep-health.d.ts +5 -0
  275. package/dist/treedx/client/support/contracts/treedx/health/contracts/deep-health.js +7 -0
  276. package/dist/treedx/client/support/contracts/treedx/health/contracts/health.d.ts +3 -0
  277. package/dist/treedx/client/support/contracts/treedx/health/contracts/health.js +6 -0
  278. package/dist/treedx/client/support/contracts/treedx/health/contracts/metrics.d.ts +3 -0
  279. package/dist/treedx/client/support/contracts/treedx/health/contracts/metrics.js +7 -0
  280. package/dist/treedx/client/support/contracts/treedx/health/contracts/prometheus-metrics.d.ts +2 -0
  281. package/dist/treedx/client/support/contracts/treedx/health/contracts/prometheus-metrics.js +19 -0
  282. package/dist/treedx/client/support/contracts/treedx/health/contracts/ready.d.ts +3 -0
  283. package/dist/treedx/client/support/contracts/treedx/health/contracts/ready.js +7 -0
  284. package/dist/treedx/client/support/contracts/treedx/health/contracts/status.d.ts +3 -0
  285. package/dist/treedx/client/support/contracts/treedx/health/contracts/status.js +6 -0
  286. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/commit.d.ts +3 -0
  287. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/commit.js +7 -0
  288. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/diff.d.ts +3 -0
  289. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/diff.js +6 -0
  290. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/fetch-remote.d.ts +3 -0
  291. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/fetch-remote.js +7 -0
  292. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/push.d.ts +6 -0
  293. package/dist/treedx/client/support/contracts/treedx/repositories/contracts/push.js +23 -0
  294. package/dist/treedx/client/support/contracts/treedx/search/contracts/compact-search-index.d.ts +3 -0
  295. package/dist/treedx/client/support/contracts/treedx/search/contracts/compact-search-index.js +8 -0
  296. package/dist/treedx/client/support/contracts/treedx/search/contracts/search.d.ts +3 -0
  297. package/dist/treedx/client/support/contracts/treedx/search/contracts/search.js +7 -0
  298. package/dist/treedx/client/support/contracts/treedx/storage/contracts/backup-storage.d.ts +3 -0
  299. package/dist/treedx/client/support/contracts/treedx/storage/contracts/backup-storage.js +8 -0
  300. package/dist/treedx/client/support/contracts/treedx/storage/contracts/compact-storage.d.ts +3 -0
  301. package/dist/treedx/client/support/contracts/treedx/storage/contracts/compact-storage.js +8 -0
  302. package/dist/treedx/client/support/contracts/treedx/transport/contracts/assert-binary-ok.d.ts +2 -0
  303. package/dist/treedx/client/support/contracts/treedx/transport/contracts/assert-binary-ok.js +15 -0
  304. package/dist/treedx/client/support/contracts/treedx/transport/contracts/fetch-with-timeout.d.ts +2 -0
  305. package/dist/treedx/client/support/contracts/treedx/transport/contracts/fetch-with-timeout.js +38 -0
  306. package/dist/treedx/client/support/contracts/treedx/transport/contracts/headers.d.ts +2 -0
  307. package/dist/treedx/client/support/contracts/treedx/transport/contracts/headers.js +15 -0
  308. package/dist/treedx/client/support/contracts/treedx/transport/contracts/parse-json-response.d.ts +2 -0
  309. package/dist/treedx/client/support/contracts/treedx/transport/contracts/parse-json-response.js +15 -0
  310. package/dist/treedx/client/support/contracts/treedx/transport/contracts/query.d.ts +2 -0
  311. package/dist/treedx/client/support/contracts/treedx/transport/contracts/query.js +14 -0
  312. package/dist/treedx/client/support/contracts/treedx/transport/contracts/repo-id.d.ts +2 -0
  313. package/dist/treedx/client/support/contracts/treedx/transport/contracts/repo-id.js +14 -0
  314. package/dist/treedx/client/support/contracts/treedx/transport/contracts/request.d.ts +6 -0
  315. package/dist/treedx/client/support/contracts/treedx/transport/contracts/request.js +41 -0
  316. package/dist/treedx/client/support/contracts/treedx/transport/contracts/throw-api-error.d.ts +2 -0
  317. package/dist/treedx/client/support/contracts/treedx/transport/contracts/throw-api-error.js +14 -0
  318. package/dist/treedx/client/support/contracts/treedx/workspaces/contracts/exec.d.ts +3 -0
  319. package/dist/treedx/client/support/contracts/treedx/workspaces/contracts/exec.js +7 -0
  320. package/dist/treedx/client/support/creation/apply-changeset.d.ts +3 -0
  321. package/dist/treedx/client/support/creation/apply-changeset.js +10 -0
  322. package/dist/treedx/client/support/creation/apply-storage-migration.d.ts +3 -0
  323. package/dist/treedx/client/support/creation/apply-storage-migration.js +7 -0
  324. package/dist/treedx/client/support/creation/create-migration.d.ts +6 -0
  325. package/dist/treedx/client/support/creation/create-migration.js +7 -0
  326. package/dist/treedx/client/support/creation/export-artifact.d.ts +3 -0
  327. package/dist/treedx/client/support/creation/export-artifact.js +8 -0
  328. package/dist/treedx/client/support/creation/plan-storage-migration.d.ts +3 -0
  329. package/dist/treedx/client/support/creation/plan-storage-migration.js +7 -0
  330. package/dist/treedx/client/support/creation/request-binary.d.ts +6 -0
  331. package/dist/treedx/client/support/creation/request-binary.js +42 -0
  332. package/dist/treedx/client/support/creation/write-file.d.ts +3 -0
  333. package/dist/treedx/client/support/creation/write-file.js +10 -0
  334. package/dist/treedx/client/support/creation/write-files.d.ts +3 -0
  335. package/dist/treedx/client/support/creation/write-files.js +12 -0
  336. package/dist/treedx/client/support/queries/treedx/artifacts/queries/get-artifact.d.ts +3 -0
  337. package/dist/treedx/client/support/queries/treedx/artifacts/queries/get-artifact.js +7 -0
  338. package/dist/treedx/client/support/queries/treedx/artifacts/queries/list-artifacts.d.ts +3 -0
  339. package/dist/treedx/client/support/queries/treedx/artifacts/queries/list-artifacts.js +7 -0
  340. package/dist/treedx/client/support/queries/treedx/authorization/queries/effective-scope.d.ts +3 -0
  341. package/dist/treedx/client/support/queries/treedx/authorization/queries/effective-scope.js +9 -0
  342. package/dist/treedx/client/support/queries/treedx/authorization/queries/list-capabilities.d.ts +4 -0
  343. package/dist/treedx/client/support/queries/treedx/authorization/queries/list-capabilities.js +6 -0
  344. package/dist/treedx/client/support/queries/treedx/federation/queries/get-placement.d.ts +3 -0
  345. package/dist/treedx/client/support/queries/treedx/federation/queries/get-placement.js +7 -0
  346. package/dist/treedx/client/support/queries/treedx/graph/queries/get-node.d.ts +3 -0
  347. package/dist/treedx/client/support/queries/treedx/graph/queries/get-node.js +7 -0
  348. package/dist/treedx/client/support/queries/treedx/graph/queries/get-related.d.ts +3 -0
  349. package/dist/treedx/client/support/queries/treedx/graph/queries/get-related.js +7 -0
  350. package/dist/treedx/client/support/queries/treedx/graph/queries/list-nodes.d.ts +3 -0
  351. package/dist/treedx/client/support/queries/treedx/graph/queries/list-nodes.js +7 -0
  352. package/dist/treedx/client/support/queries/treedx/repositories/queries/list-tree.d.ts +3 -0
  353. package/dist/treedx/client/support/queries/treedx/repositories/queries/list-tree.js +10 -0
  354. package/dist/treedx/client/support/queries/treedx/repositories/queries/read-file.d.ts +3 -0
  355. package/dist/treedx/client/support/queries/treedx/repositories/queries/read-file.js +9 -0
  356. package/dist/treedx/client/support/queries/treedx/search/queries/get-search-index-status.d.ts +3 -0
  357. package/dist/treedx/client/support/queries/treedx/search/queries/get-search-index-status.js +7 -0
  358. package/dist/treedx/client/support/queries/treedx/storage/queries/get-migration.d.ts +6 -0
  359. package/dist/treedx/client/support/queries/treedx/storage/queries/get-migration.js +7 -0
  360. package/dist/treedx/client/support/queries/treedx/storage/queries/get-snapshot.d.ts +6 -0
  361. package/dist/treedx/client/support/queries/treedx/storage/queries/get-snapshot.js +7 -0
  362. package/dist/treedx/client/support/queries/treedx/storage/queries/list-storage-migrations.d.ts +6 -0
  363. package/dist/treedx/client/support/queries/treedx/storage/queries/list-storage-migrations.js +6 -0
  364. package/dist/treedx/client/support/queries/treedx/transport/queries/list-audit-events.d.ts +15 -0
  365. package/dist/treedx/client/support/queries/treedx/transport/queries/list-audit-events.js +6 -0
  366. package/dist/treedx/client/support/queries/treedx/transport/queries/list-repositories.d.ts +3 -0
  367. package/dist/treedx/client/support/queries/treedx/transport/queries/list-repositories.js +7 -0
  368. package/dist/treedx/client/support/retirement/cleanup-artifacts.d.ts +3 -0
  369. package/dist/treedx/client/support/retirement/cleanup-artifacts.js +7 -0
  370. package/dist/treedx/client/support/retirement/delete-artifact.d.ts +3 -0
  371. package/dist/treedx/client/support/retirement/delete-artifact.js +7 -0
  372. package/dist/treedx/client/support/retirement/delete-file.d.ts +3 -0
  373. package/dist/treedx/client/support/retirement/delete-file.js +10 -0
  374. package/dist/treedx/client/support/retirement/rollback-storage-migration.d.ts +3 -0
  375. package/dist/treedx/client/support/retirement/rollback-storage-migration.js +7 -0
  376. package/dist/treedx/client/support/updates/patch-file.d.ts +3 -0
  377. package/dist/treedx/client/support/updates/patch-file.js +10 -0
  378. package/dist/treedx/client/support/updates/refresh-search-index.d.ts +3 -0
  379. package/dist/treedx/client/support/updates/refresh-search-index.js +8 -0
  380. package/dist/treedx/client/treedx/blobs/contracts/download-blob.d.ts +3 -0
  381. package/dist/treedx/client/treedx/blobs/contracts/download-blob.js +6 -0
  382. package/dist/treedx/client/treedx/blobs/creation/create-blob-upload.d.ts +3 -0
  383. package/dist/treedx/client/treedx/blobs/creation/create-blob-upload.js +8 -0
  384. package/dist/treedx/client/treedx/blobs/creation/request-blob-download.d.ts +3 -0
  385. package/dist/treedx/client/treedx/blobs/creation/request-blob-download.js +27 -0
  386. package/dist/treedx/client/treedx/blobs/creation/request-blob-upload.d.ts +3 -0
  387. package/dist/treedx/client/treedx/blobs/creation/request-blob-upload.js +41 -0
  388. package/dist/treedx/client/treedx/blobs/creation/upload-blob-part.d.ts +3 -0
  389. package/dist/treedx/client/treedx/blobs/creation/upload-blob-part.js +27 -0
  390. package/dist/treedx/client/treedx/blobs/creation/upload-blob.d.ts +3 -0
  391. package/dist/treedx/client/treedx/blobs/creation/upload-blob.js +6 -0
  392. package/dist/treedx/client/treedx/blobs/creation/write-blob.d.ts +3 -0
  393. package/dist/treedx/client/treedx/blobs/creation/write-blob.js +8 -0
  394. package/dist/treedx/client/treedx/blobs/lifecycle/complete-blob-upload.d.ts +3 -0
  395. package/dist/treedx/client/treedx/blobs/lifecycle/complete-blob-upload.js +8 -0
  396. package/dist/treedx/client/treedx/blobs/queries/read-blob.d.ts +3 -0
  397. package/dist/treedx/client/treedx/blobs/queries/read-blob.js +10 -0
  398. package/dist/treedx/client/treedx/blobs/retirement/abort-blob-upload.d.ts +3 -0
  399. package/dist/treedx/client/treedx/blobs/retirement/abort-blob-upload.js +7 -0
  400. package/dist/treedx/client/treedx/blobs/retirement/delete-blob.d.ts +3 -0
  401. package/dist/treedx/client/treedx/blobs/retirement/delete-blob.js +8 -0
  402. package/dist/treedx/client/treedx/federation/contracts/federated-query.d.ts +3 -0
  403. package/dist/treedx/client/treedx/federation/contracts/federated-query.js +7 -0
  404. package/dist/treedx/client/treedx/federation/creation/plan-federated-query.d.ts +3 -0
  405. package/dist/treedx/client/treedx/federation/creation/plan-federated-query.js +6 -0
  406. package/dist/treedx/client/treedx/federation/queries/check-mirror-health.d.ts +3 -0
  407. package/dist/treedx/client/treedx/federation/queries/check-mirror-health.js +7 -0
  408. package/dist/treedx/client/treedx/federation/updates/promote-mirror.d.ts +3 -0
  409. package/dist/treedx/client/treedx/federation/updates/promote-mirror.js +7 -0
  410. package/dist/treedx/client/treedx/federation/updates/sync-mirror.d.ts +3 -0
  411. package/dist/treedx/client/treedx/federation/updates/sync-mirror.js +7 -0
  412. package/dist/treedx/client/treedx/graph/contracts/federated-context.d.ts +3 -0
  413. package/dist/treedx/client/treedx/graph/contracts/federated-context.js +7 -0
  414. package/dist/treedx/client/treedx/graph/contracts/federated-graph.d.ts +3 -0
  415. package/dist/treedx/client/treedx/graph/contracts/federated-graph.js +7 -0
  416. package/dist/treedx/client/treedx/graph/contracts/graph-search.d.ts +3 -0
  417. package/dist/treedx/client/treedx/graph/contracts/graph-search.js +8 -0
  418. package/dist/treedx/client/treedx/graph/queries/get-graph-node.d.ts +3 -0
  419. package/dist/treedx/client/treedx/graph/queries/get-graph-node.js +10 -0
  420. package/dist/treedx/client/treedx/graph/queries/get-graph-refresh-job.d.ts +3 -0
  421. package/dist/treedx/client/treedx/graph/queries/get-graph-refresh-job.js +7 -0
  422. package/dist/treedx/client/treedx/graph/queries/get-subgraph.d.ts +3 -0
  423. package/dist/treedx/client/treedx/graph/queries/get-subgraph.js +7 -0
  424. package/dist/treedx/client/treedx/graph/queries/query-graph.d.ts +3 -0
  425. package/dist/treedx/client/treedx/graph/queries/query-graph.js +7 -0
  426. package/dist/treedx/client/treedx/graph/queries/search-graph-entities.d.ts +3 -0
  427. package/dist/treedx/client/treedx/graph/queries/search-graph-entities.js +6 -0
  428. package/dist/treedx/client/treedx/graph/queries/search-graph-files.d.ts +3 -0
  429. package/dist/treedx/client/treedx/graph/queries/search-graph-files.js +6 -0
  430. package/dist/treedx/client/treedx/graph/queries/search-graph-sections.d.ts +3 -0
  431. package/dist/treedx/client/treedx/graph/queries/search-graph-sections.js +6 -0
  432. package/dist/treedx/client/treedx/graph/updates/refresh-graph.d.ts +3 -0
  433. package/dist/treedx/client/treedx/graph/updates/refresh-graph.js +7 -0
  434. package/dist/treedx/client/treedx/search/contracts/federated-search.d.ts +3 -0
  435. package/dist/treedx/client/treedx/search/contracts/federated-search.js +7 -0
  436. package/dist/treedx/client/treedx/workspaces/creation/create-workspace.d.ts +3 -0
  437. package/dist/treedx/client/treedx/workspaces/creation/create-workspace.js +7 -0
  438. package/dist/treedx/client/treedx/workspaces/retirement/abandon-workspace.d.ts +3 -0
  439. package/dist/treedx/client/treedx/workspaces/retirement/abandon-workspace.js +12 -0
  440. package/dist/treedx/client/treedx/workspaces/retirement/close-workspace.d.ts +2 -0
  441. package/dist/treedx/client/treedx/workspaces/retirement/close-workspace.js +6 -0
  442. package/dist/treedx/generated/openapi-types.d.ts +104 -0
  443. package/dist/treedx/support/client.d.ts +251 -0
  444. package/dist/treedx/support/client.js +252 -0
  445. package/dist/treedx/support/errors.d.ts +13 -0
  446. package/dist/treedx/types/tree-dx-actor.d.ts +209 -0
  447. package/dist/treedx/types/tree-dx-actor.js +8 -0
  448. package/dist/treedx/types/tree-dx-artifact-list-response.d.ts +13 -0
  449. package/dist/treedx/types/tree-dx-artifact-list-response.js +0 -0
  450. package/dist/treedx/types/tree-dx-changeset.d.ts +51 -0
  451. package/dist/treedx/types/tree-dx-changeset.js +6 -0
  452. package/dist/treedx/types/tree-dx-context-request.d.ts +245 -0
  453. package/dist/treedx/types/tree-dx-context-request.js +0 -0
  454. package/dist/treedx/types/tree-dx-exec-result.d.ts +249 -0
  455. package/dist/treedx/types/tree-dx-exec-result.js +0 -0
  456. package/dist/treedx/types/tree-dx-list-tree-request.d.ts +222 -0
  457. package/dist/treedx/types/tree-dx-list-tree-request.js +0 -0
  458. package/dist/treedx/types/tree-dx-push-request.d.ts +229 -0
  459. package/dist/treedx/types/tree-dx-push-request.js +0 -0
  460. package/dist/treedx/types.d.ts +7 -1084
  461. package/dist/treedx/types.js +7 -8
  462. package/dist/types/agents/agent-activity-profile.d.ts +267 -0
  463. package/dist/types/agents/agent-activity-profile.js +0 -0
  464. package/dist/types/agents/agent-trigger-kinds.d.ts +189 -0
  465. package/dist/types/agents/agent-trigger-kinds.js +107 -0
  466. package/dist/types/agents/execution-run-ref.d.ts +136 -0
  467. package/dist/types/agents/execution-run-ref.js +0 -0
  468. package/dist/types/agents.d.ts +3 -493
  469. package/dist/types/agents.js +3 -95
  470. package/package.json +77 -362
  471. package/dist/agent-capacity.d.ts +0 -1100
  472. package/dist/agent-capacity.js +0 -1822
  473. package/dist/agent-tools.d.ts +0 -37
  474. package/dist/agent-tools.js +0 -301
  475. package/dist/api/app.d.ts +0 -8
  476. package/dist/api/app.js +0 -404
  477. package/dist/api/auth/d1-database.d.ts +0 -3
  478. package/dist/api/auth/d1-database.js +0 -20
  479. package/dist/api/auth/d1-provider.d.ts +0 -85
  480. package/dist/api/auth/d1-provider.js +0 -95
  481. package/dist/api/auth/d1-store.d.ts +0 -121
  482. package/dist/api/auth/d1-store.js +0 -990
  483. package/dist/api/auth/memory-provider.d.ts +0 -82
  484. package/dist/api/auth/memory-provider.js +0 -297
  485. package/dist/api/auth/rbac.d.ts +0 -22
  486. package/dist/api/auth/rbac.js +0 -162
  487. package/dist/api/auth/tokens.d.ts +0 -18
  488. package/dist/api/auth/tokens.js +0 -56
  489. package/dist/api/config.d.ts +0 -4
  490. package/dist/api/config.js +0 -149
  491. package/dist/api/http.d.ts +0 -28
  492. package/dist/api/http.js +0 -51
  493. package/dist/api/index.d.ts +0 -10
  494. package/dist/api/index.js +0 -29
  495. package/dist/api/operations-routes.d.ts +0 -11
  496. package/dist/api/operations-routes.js +0 -39
  497. package/dist/api/operations.d.ts +0 -3
  498. package/dist/api/operations.js +0 -26
  499. package/dist/api/providers.d.ts +0 -2
  500. package/dist/api/providers.js +0 -85
  501. package/dist/api/railway.d.ts +0 -53
  502. package/dist/api/railway.js +0 -71
  503. package/dist/api/sdk-dispatch.d.ts +0 -6
  504. package/dist/api/sdk-dispatch.js +0 -14
  505. package/dist/api/sdk-routes.d.ts +0 -11
  506. package/dist/api/sdk-routes.js +0 -29
  507. package/dist/api/templates.d.ts +0 -3
  508. package/dist/api/templates.js +0 -31
  509. package/dist/api/types.d.ts +0 -238
  510. package/dist/capacity-provider.d.ts +0 -494
  511. package/dist/capacity-provider.js +0 -727
  512. package/dist/capacity.d.ts +0 -483
  513. package/dist/capacity.js +0 -2331
  514. package/dist/cli-tools.d.ts +0 -3
  515. package/dist/cli-tools.js +0 -46
  516. package/dist/content-operations.d.ts +0 -97
  517. package/dist/content-operations.js +0 -250
  518. package/dist/content-store.d.ts +0 -25
  519. package/dist/content-store.js +0 -269
  520. package/dist/control-plane-client.d.ts +0 -203
  521. package/dist/control-plane-client.js +0 -540
  522. package/dist/control-plane.d.ts +0 -101
  523. package/dist/control-plane.js +0 -201
  524. package/dist/copilot.d.ts +0 -18
  525. package/dist/copilot.js +0 -90
  526. package/dist/d1-http.d.ts +0 -38
  527. package/dist/d1-http.js +0 -95
  528. package/dist/d1-store.d.ts +0 -336
  529. package/dist/d1-store.js +0 -1431
  530. package/dist/db/d1.d.ts +0 -246
  531. package/dist/db/d1.js +0 -8
  532. package/dist/db/index.d.ts +0 -3
  533. package/dist/db/index.js +0 -3
  534. package/dist/db/market-schema.d.ts +0 -83651
  535. package/dist/db/market-schema.js +0 -3725
  536. package/dist/db/node-sqlite.d.ts +0 -297
  537. package/dist/db/node-sqlite.js +0 -133
  538. package/dist/db/schema.d.ts +0 -483
  539. package/dist/db/schema.js +0 -29
  540. package/dist/dispatch.d.ts +0 -4
  541. package/dist/dispatch.js +0 -174
  542. package/dist/field-aliases.d.ts +0 -11
  543. package/dist/fixture-support.d.ts +0 -24
  544. package/dist/fixture-support.js +0 -385
  545. package/dist/frontmatter.d.ts +0 -6
  546. package/dist/frontmatter.js +0 -33
  547. package/dist/git-runtime.d.ts +0 -16
  548. package/dist/git-runtime.js +0 -69
  549. package/dist/governance.d.ts +0 -133
  550. package/dist/governance.js +0 -285
  551. package/dist/graph/build.d.ts +0 -19
  552. package/dist/graph/build.js +0 -949
  553. package/dist/graph/dsl.d.ts +0 -2
  554. package/dist/graph/dsl.js +0 -243
  555. package/dist/graph/query.d.ts +0 -47
  556. package/dist/graph/query.js +0 -447
  557. package/dist/graph/ranking.d.ts +0 -3
  558. package/dist/graph/ranking.js +0 -483
  559. package/dist/graph/schema.d.ts +0 -142
  560. package/dist/graph/schema.js +0 -137
  561. package/dist/graph.d.ts +0 -52
  562. package/dist/graph.js +0 -133
  563. package/dist/guarantees/index.d.ts +0 -512
  564. package/dist/guarantees/index.js +0 -1782
  565. package/dist/hosting/apps.d.ts +0 -12
  566. package/dist/hosting/apps.js +0 -107
  567. package/dist/hosting/builtins.d.ts +0 -25
  568. package/dist/hosting/builtins.js +0 -685
  569. package/dist/hosting/contracts.d.ts +0 -190
  570. package/dist/hosting/graph.d.ts +0 -110
  571. package/dist/hosting/graph.js +0 -993
  572. package/dist/hosting/index.d.ts +0 -4
  573. package/dist/hosting/index.js +0 -4
  574. package/dist/index.d.ts +0 -88
  575. package/dist/index.js +0 -757
  576. package/dist/local-dev/managed-dev.d.ts +0 -85
  577. package/dist/local-dev/managed-dev.js +0 -431
  578. package/dist/managed-dependencies.d.ts +0 -91
  579. package/dist/managed-dependencies.js +0 -1186
  580. package/dist/market-client.d.ts +0 -831
  581. package/dist/market-client.js +0 -1219
  582. package/dist/model-registry.d.ts +0 -8
  583. package/dist/model-registry.js +0 -674
  584. package/dist/operations/agent-tools.d.ts +0 -105
  585. package/dist/operations/agent-tools.js +0 -171
  586. package/dist/operations/providers/default.d.ts +0 -10
  587. package/dist/operations/providers/default.js +0 -1245
  588. package/dist/operations/repository-operations.d.ts +0 -158
  589. package/dist/operations/repository-operations.js +0 -851
  590. package/dist/operations/runtime.d.ts +0 -7
  591. package/dist/operations/runtime.js +0 -61
  592. package/dist/operations/services/bootstrap-runner.d.ts +0 -39
  593. package/dist/operations/services/bootstrap-runner.js +0 -191
  594. package/dist/operations/services/build-warning-policy.d.ts +0 -34
  595. package/dist/operations/services/build-warning-policy.js +0 -91
  596. package/dist/operations/services/commit-message-provider.d.ts +0 -65
  597. package/dist/operations/services/commit-message-provider.js +0 -496
  598. package/dist/operations/services/config-runtime.d.ts +0 -558
  599. package/dist/operations/services/config-runtime.js +0 -3494
  600. package/dist/operations/services/d1-migration.d.ts +0 -6
  601. package/dist/operations/services/d1-migration.js +0 -120
  602. package/dist/operations/services/deploy.d.ts +0 -645
  603. package/dist/operations/services/deploy.js +0 -3826
  604. package/dist/operations/services/deployment-readiness.d.ts +0 -30
  605. package/dist/operations/services/deployment-readiness.js +0 -217
  606. package/dist/operations/services/export-runtime.d.ts +0 -18
  607. package/dist/operations/services/export-runtime.js +0 -140
  608. package/dist/operations/services/git-remote-policy.d.ts +0 -9
  609. package/dist/operations/services/git-remote-policy.js +0 -63
  610. package/dist/operations/services/git-runner.d.ts +0 -68
  611. package/dist/operations/services/git-runner.js +0 -500
  612. package/dist/operations/services/git-workflow.d.ts +0 -255
  613. package/dist/operations/services/git-workflow.js +0 -845
  614. package/dist/operations/services/github-actions-verification.d.ts +0 -148
  615. package/dist/operations/services/github-actions-verification.js +0 -589
  616. package/dist/operations/services/github-api.d.ts +0 -279
  617. package/dist/operations/services/github-api.js +0 -936
  618. package/dist/operations/services/github-automation.d.ts +0 -230
  619. package/dist/operations/services/github-automation.js +0 -520
  620. package/dist/operations/services/github-credentials.d.ts +0 -13
  621. package/dist/operations/services/github-credentials.js +0 -59
  622. package/dist/operations/services/hosted-service-checks.d.ts +0 -82
  623. package/dist/operations/services/hosted-service-checks.js +0 -527
  624. package/dist/operations/services/hosting-audit.d.ts +0 -69
  625. package/dist/operations/services/hosting-audit.js +0 -638
  626. package/dist/operations/services/hub-launch.d.ts +0 -182
  627. package/dist/operations/services/hub-launch.js +0 -309
  628. package/dist/operations/services/hub-provider-launch.d.ts +0 -160
  629. package/dist/operations/services/hub-provider-launch.js +0 -1056
  630. package/dist/operations/services/key-agent.d.ts +0 -137
  631. package/dist/operations/services/key-agent.js +0 -641
  632. package/dist/operations/services/live-hosted-service-checks.d.ts +0 -30
  633. package/dist/operations/services/live-hosted-service-checks.js +0 -611
  634. package/dist/operations/services/local-cleanup.d.ts +0 -30
  635. package/dist/operations/services/local-cleanup.js +0 -77
  636. package/dist/operations/services/local-dev.d.ts +0 -8
  637. package/dist/operations/services/local-dev.js +0 -97
  638. package/dist/operations/services/managed-host-security.d.ts +0 -13
  639. package/dist/operations/services/managed-host-security.js +0 -56
  640. package/dist/operations/services/managed-repositories.d.ts +0 -37
  641. package/dist/operations/services/managed-repositories.js +0 -177
  642. package/dist/operations/services/market-packaging.d.ts +0 -59
  643. package/dist/operations/services/market-packaging.js +0 -234
  644. package/dist/operations/services/operations-runner-smoke.d.ts +0 -31
  645. package/dist/operations/services/operations-runner-smoke.js +0 -212
  646. package/dist/operations/services/package-adapters.d.ts +0 -184
  647. package/dist/operations/services/package-adapters.js +0 -912
  648. package/dist/operations/services/package-artifacts.d.ts +0 -37
  649. package/dist/operations/services/package-artifacts.js +0 -99
  650. package/dist/operations/services/package-reference-policy.d.ts +0 -64
  651. package/dist/operations/services/package-reference-policy.js +0 -364
  652. package/dist/operations/services/project-host-operations.d.ts +0 -153
  653. package/dist/operations/services/project-host-operations.js +0 -365
  654. package/dist/operations/services/project-platform.d.ts +0 -727
  655. package/dist/operations/services/project-platform.js +0 -1603
  656. package/dist/operations/services/project-web-monitor.d.ts +0 -15
  657. package/dist/operations/services/project-web-monitor.js +0 -377
  658. package/dist/operations/services/railway-api.d.ts +0 -494
  659. package/dist/operations/services/railway-api.js +0 -1874
  660. package/dist/operations/services/railway-cli.d.ts +0 -47
  661. package/dist/operations/services/railway-cli.js +0 -142
  662. package/dist/operations/services/railway-deploy.d.ts +0 -161
  663. package/dist/operations/services/railway-deploy.js +0 -1808
  664. package/dist/operations/services/railway-source-policy.d.ts +0 -25
  665. package/dist/operations/services/railway-source-policy.js +0 -111
  666. package/dist/operations/services/release-history.d.ts +0 -59
  667. package/dist/operations/services/release-history.js +0 -158
  668. package/dist/operations/services/release-proof-ledger.d.ts +0 -13
  669. package/dist/operations/services/release-proof-ledger.js +0 -81
  670. package/dist/operations/services/release-proof-planner.d.ts +0 -48
  671. package/dist/operations/services/release-proof-planner.js +0 -195
  672. package/dist/operations/services/release-proof-runner.d.ts +0 -16
  673. package/dist/operations/services/release-proof-runner.js +0 -169
  674. package/dist/operations/services/release-proof.d.ts +0 -81
  675. package/dist/operations/services/release-proof.js +0 -79
  676. package/dist/operations/services/repository-save-orchestrator.d.ts +0 -193
  677. package/dist/operations/services/repository-save-orchestrator.js +0 -2110
  678. package/dist/operations/services/runtime-paths.d.ts +0 -19
  679. package/dist/operations/services/runtime-paths.js +0 -54
  680. package/dist/operations/services/runtime-tools.d.ts +0 -35
  681. package/dist/operations/services/runtime-tools.js +0 -212
  682. package/dist/operations/services/save-deploy-preflight.d.ts +0 -32
  683. package/dist/operations/services/save-deploy-preflight.js +0 -82
  684. package/dist/operations/services/template-host-bindings.d.ts +0 -68
  685. package/dist/operations/services/template-host-bindings.js +0 -401
  686. package/dist/operations/services/template-registry.d.ts +0 -110
  687. package/dist/operations/services/template-registry.js +0 -595
  688. package/dist/operations/services/template-secret-sync.d.ts +0 -97
  689. package/dist/operations/services/template-secret-sync.js +0 -292
  690. package/dist/operations/services/verification-cache.d.ts +0 -25
  691. package/dist/operations/services/verification-cache.js +0 -71
  692. package/dist/operations/services/watch-dev.d.ts +0 -21
  693. package/dist/operations/services/watch-dev.js +0 -282
  694. package/dist/operations/services/workflow-timing.d.ts +0 -25
  695. package/dist/operations/services/workflow-timing.js +0 -79
  696. package/dist/operations/services/workspace-dependency-mode.d.ts +0 -74
  697. package/dist/operations/services/workspace-dependency-mode.js +0 -478
  698. package/dist/operations/services/workspace-preflight.d.ts +0 -40
  699. package/dist/operations/services/workspace-preflight.js +0 -172
  700. package/dist/operations/services/workspace-save-script.d.ts +0 -26
  701. package/dist/operations/services/workspace-save-script.js +0 -50
  702. package/dist/operations/services/workspace-save.d.ts +0 -76
  703. package/dist/operations/services/workspace-save.js +0 -453
  704. package/dist/operations/services/workspace-tools.d.ts +0 -17
  705. package/dist/operations/services/workspace-tools.js +0 -320
  706. package/dist/operations-registry.d.ts +0 -5
  707. package/dist/operations-registry.js +0 -98
  708. package/dist/operations-types.d.ts +0 -75
  709. package/dist/operations-types.js +0 -17
  710. package/dist/operations.d.ts +0 -17
  711. package/dist/operations.js +0 -114
  712. package/dist/platform/book-export.d.ts +0 -78
  713. package/dist/platform/book-export.js +0 -451
  714. package/dist/platform/books-data.d.ts +0 -28
  715. package/dist/platform/books-data.js +0 -111
  716. package/dist/platform/config.d.ts +0 -27
  717. package/dist/platform/config.js +0 -100
  718. package/dist/platform/content-runtime-source.d.ts +0 -54
  719. package/dist/platform/content-runtime-source.js +0 -169
  720. package/dist/platform/contracts.d.ts +0 -361
  721. package/dist/platform/deploy-config.d.ts +0 -17
  722. package/dist/platform/deploy-config.js +0 -731
  723. package/dist/platform/deploy-runtime.d.ts +0 -22
  724. package/dist/platform/deploy-runtime.js +0 -93
  725. package/dist/platform/desired-state.d.ts +0 -66
  726. package/dist/platform/desired-state.js +0 -1071
  727. package/dist/platform/env.yaml +0 -1126
  728. package/dist/platform/environment.d.ts +0 -159
  729. package/dist/platform/environment.js +0 -778
  730. package/dist/platform/local-content-materialization.d.ts +0 -9
  731. package/dist/platform/local-content-materialization.js +0 -212
  732. package/dist/platform/plugin.d.ts +0 -103
  733. package/dist/platform/plugin.js +0 -6
  734. package/dist/platform/plugins/constants.d.ts +0 -26
  735. package/dist/platform/plugins/constants.js +0 -33
  736. package/dist/platform/plugins/runtime.d.ts +0 -41
  737. package/dist/platform/plugins/runtime.js +0 -257
  738. package/dist/platform/plugins.d.ts +0 -6
  739. package/dist/platform/plugins.js +0 -42
  740. package/dist/platform/published-content-pipeline.d.ts +0 -84
  741. package/dist/platform/published-content-pipeline.js +0 -547
  742. package/dist/platform/published-content.d.ts +0 -224
  743. package/dist/platform/published-content.js +0 -611
  744. package/dist/platform/site-config-schema.d.ts +0 -1
  745. package/dist/platform/site-config-schema.js +0 -4
  746. package/dist/platform/tenant/runtime-config.d.ts +0 -154
  747. package/dist/platform/tenant/runtime-config.js +0 -69
  748. package/dist/platform/tenant-config.d.ts +0 -8
  749. package/dist/platform/tenant-config.js +0 -207
  750. package/dist/platform/utils/site-config-schema.d.ts +0 -154
  751. package/dist/platform/utils/site-config-schema.js +0 -450
  752. package/dist/platform-operation-store.d.ts +0 -94
  753. package/dist/platform-operation-store.js +0 -531
  754. package/dist/platform-operations.d.ts +0 -273
  755. package/dist/platform-operations.js +0 -440
  756. package/dist/plugin-default.d.ts +0 -28
  757. package/dist/plugin-default.js +0 -55
  758. package/dist/project-import.d.ts +0 -91
  759. package/dist/project-import.js +0 -257
  760. package/dist/project-workflow.d.ts +0 -233
  761. package/dist/project-workflow.js +0 -82
  762. package/dist/reconcile/bootstrap-systems.d.ts +0 -32
  763. package/dist/reconcile/bootstrap-systems.js +0 -175
  764. package/dist/reconcile/builtin-adapters.d.ts +0 -9
  765. package/dist/reconcile/builtin-adapters.js +0 -5545
  766. package/dist/reconcile/contracts.d.ts +0 -172
  767. package/dist/reconcile/desired-state.d.ts +0 -10
  768. package/dist/reconcile/desired-state.js +0 -322
  769. package/dist/reconcile/engine.d.ts +0 -118
  770. package/dist/reconcile/engine.js +0 -645
  771. package/dist/reconcile/errors.d.ts +0 -5
  772. package/dist/reconcile/errors.js +0 -13
  773. package/dist/reconcile/index.d.ts +0 -10
  774. package/dist/reconcile/index.js +0 -10
  775. package/dist/reconcile/live-acceptance.d.ts +0 -100
  776. package/dist/reconcile/live-acceptance.js +0 -2018
  777. package/dist/reconcile/platform.d.ts +0 -104
  778. package/dist/reconcile/platform.js +0 -100
  779. package/dist/reconcile/providers/docker-private.d.ts +0 -54
  780. package/dist/reconcile/providers/docker-private.js +0 -101
  781. package/dist/reconcile/providers/github-private.d.ts +0 -69
  782. package/dist/reconcile/providers/github-private.js +0 -145
  783. package/dist/reconcile/providers/local-private.d.ts +0 -28
  784. package/dist/reconcile/providers/local-private.js +0 -75
  785. package/dist/reconcile/providers/railway-iac.d.ts +0 -220
  786. package/dist/reconcile/providers/railway-iac.js +0 -621
  787. package/dist/reconcile/providers/release-private.d.ts +0 -89
  788. package/dist/reconcile/providers/release-private.js +0 -140
  789. package/dist/reconcile/registry.d.ts +0 -7
  790. package/dist/reconcile/registry.js +0 -79
  791. package/dist/reconcile/state.d.ts +0 -7
  792. package/dist/reconcile/state.js +0 -270
  793. package/dist/reconcile/units.d.ts +0 -6
  794. package/dist/reconcile/units.js +0 -72
  795. package/dist/remote.d.ts +0 -244
  796. package/dist/remote.js +0 -284
  797. package/dist/scenes/artifacts.d.ts +0 -16
  798. package/dist/scenes/artifacts.js +0 -61
  799. package/dist/scenes/auth.d.ts +0 -2
  800. package/dist/scenes/auth.js +0 -28
  801. package/dist/scenes/base-url.d.ts +0 -12
  802. package/dist/scenes/base-url.js +0 -123
  803. package/dist/scenes/builtin-plugins.d.ts +0 -2
  804. package/dist/scenes/builtin-plugins.js +0 -499
  805. package/dist/scenes/checkpoints.d.ts +0 -14
  806. package/dist/scenes/checkpoints.js +0 -33
  807. package/dist/scenes/device-matrix.d.ts +0 -2
  808. package/dist/scenes/device-matrix.js +0 -100
  809. package/dist/scenes/devices.d.ts +0 -11
  810. package/dist/scenes/devices.js +0 -40
  811. package/dist/scenes/diagnostics.d.ts +0 -5
  812. package/dist/scenes/diagnostics.js +0 -22
  813. package/dist/scenes/diagram-providers.d.ts +0 -2
  814. package/dist/scenes/diagram-providers.js +0 -181
  815. package/dist/scenes/diagram-validation.d.ts +0 -22
  816. package/dist/scenes/diagram-validation.js +0 -74
  817. package/dist/scenes/environment.d.ts +0 -2
  818. package/dist/scenes/environment.js +0 -65
  819. package/dist/scenes/evidence-bundle.d.ts +0 -5
  820. package/dist/scenes/evidence-bundle.js +0 -42
  821. package/dist/scenes/evidence-report.d.ts +0 -10
  822. package/dist/scenes/evidence-report.js +0 -73
  823. package/dist/scenes/evidence.d.ts +0 -16
  824. package/dist/scenes/evidence.js +0 -277
  825. package/dist/scenes/index.d.ts +0 -48
  826. package/dist/scenes/index.js +0 -312
  827. package/dist/scenes/inspect.d.ts +0 -9
  828. package/dist/scenes/inspect.js +0 -64
  829. package/dist/scenes/loader.d.ts +0 -3
  830. package/dist/scenes/loader.js +0 -38
  831. package/dist/scenes/logs.d.ts +0 -2
  832. package/dist/scenes/logs.js +0 -47
  833. package/dist/scenes/operations.d.ts +0 -3
  834. package/dist/scenes/operations.js +0 -128
  835. package/dist/scenes/phase0.d.ts +0 -9
  836. package/dist/scenes/phase0.js +0 -637
  837. package/dist/scenes/planner.d.ts +0 -12
  838. package/dist/scenes/planner.js +0 -166
  839. package/dist/scenes/playwright-adapter.d.ts +0 -2
  840. package/dist/scenes/playwright-adapter.js +0 -63
  841. package/dist/scenes/plugins.d.ts +0 -5
  842. package/dist/scenes/plugins.js +0 -115
  843. package/dist/scenes/progress.d.ts +0 -17
  844. package/dist/scenes/progress.js +0 -24
  845. package/dist/scenes/publish-destinations.d.ts +0 -12
  846. package/dist/scenes/publish-destinations.js +0 -99
  847. package/dist/scenes/publish-plan-report.d.ts +0 -10
  848. package/dist/scenes/publish-plan-report.js +0 -70
  849. package/dist/scenes/publish-plan.d.ts +0 -15
  850. package/dist/scenes/publish-plan.js +0 -248
  851. package/dist/scenes/publish-redaction.d.ts +0 -16
  852. package/dist/scenes/publish-redaction.js +0 -148
  853. package/dist/scenes/publish-release-record.d.ts +0 -13
  854. package/dist/scenes/publish-release-record.js +0 -34
  855. package/dist/scenes/publish-report.d.ts +0 -10
  856. package/dist/scenes/publish-report.js +0 -67
  857. package/dist/scenes/publish.d.ts +0 -16
  858. package/dist/scenes/publish.js +0 -298
  859. package/dist/scenes/registry.d.ts +0 -12
  860. package/dist/scenes/registry.js +0 -65
  861. package/dist/scenes/remotion-adapter.d.ts +0 -3
  862. package/dist/scenes/remotion-adapter.js +0 -94
  863. package/dist/scenes/remotion-composition-registry.d.ts +0 -2
  864. package/dist/scenes/remotion-composition-registry.js +0 -12
  865. package/dist/scenes/remotion-compositions.d.ts +0 -15
  866. package/dist/scenes/remotion-compositions.js +0 -464
  867. package/dist/scenes/remotion-diagrams.d.ts +0 -9
  868. package/dist/scenes/remotion-diagrams.js +0 -188
  869. package/dist/scenes/remotion-input.d.ts +0 -13
  870. package/dist/scenes/remotion-input.js +0 -291
  871. package/dist/scenes/remotion-visuals.d.ts +0 -29
  872. package/dist/scenes/remotion-visuals.js +0 -198
  873. package/dist/scenes/render-media-assets.d.ts +0 -9
  874. package/dist/scenes/render-media-assets.js +0 -117
  875. package/dist/scenes/render-report.d.ts +0 -10
  876. package/dist/scenes/render-report.js +0 -27
  877. package/dist/scenes/render.d.ts +0 -2
  878. package/dist/scenes/render.js +0 -218
  879. package/dist/scenes/reporter.d.ts +0 -3
  880. package/dist/scenes/reporter.js +0 -101
  881. package/dist/scenes/resume.d.ts +0 -2
  882. package/dist/scenes/resume.js +0 -79
  883. package/dist/scenes/runner.d.ts +0 -2
  884. package/dist/scenes/runner.js +0 -687
  885. package/dist/scenes/schema.d.ts +0 -6
  886. package/dist/scenes/schema.js +0 -1023
  887. package/dist/scenes/seed.d.ts +0 -2
  888. package/dist/scenes/seed.js +0 -83
  889. package/dist/scenes/segments.d.ts +0 -15
  890. package/dist/scenes/segments.js +0 -79
  891. package/dist/scenes/selectors.d.ts +0 -3
  892. package/dist/scenes/selectors.js +0 -21
  893. package/dist/scenes/timeline.d.ts +0 -11
  894. package/dist/scenes/timeline.js +0 -26
  895. package/dist/scenes/timeouts.d.ts +0 -6
  896. package/dist/scenes/timeouts.js +0 -17
  897. package/dist/scenes/training-captions.d.ts +0 -14
  898. package/dist/scenes/training-captions.js +0 -98
  899. package/dist/scenes/training-report.d.ts +0 -10
  900. package/dist/scenes/training-report.js +0 -78
  901. package/dist/scenes/training-transcript.d.ts +0 -24
  902. package/dist/scenes/training-transcript.js +0 -204
  903. package/dist/scenes/training.d.ts +0 -10
  904. package/dist/scenes/training.js +0 -134
  905. package/dist/scenes/types.d.ts +0 -1900
  906. package/dist/scenes/types.js +0 -8
  907. package/dist/scenes/visual-audit-contact-sheets.d.ts +0 -6
  908. package/dist/scenes/visual-audit-contact-sheets.js +0 -119
  909. package/dist/scenes/visual-audit-fixtures.d.ts +0 -25
  910. package/dist/scenes/visual-audit-fixtures.js +0 -247
  911. package/dist/scenes/visual-audit-report.d.ts +0 -11
  912. package/dist/scenes/visual-audit-report.js +0 -85
  913. package/dist/scenes/visual-audit-review.d.ts +0 -23
  914. package/dist/scenes/visual-audit-review.js +0 -829
  915. package/dist/scenes/visual-audit-routes.d.ts +0 -13
  916. package/dist/scenes/visual-audit-routes.js +0 -308
  917. package/dist/scenes/visual-audit.d.ts +0 -3
  918. package/dist/scenes/visual-audit.js +0 -596
  919. package/dist/scripts/aggregate-book.js +0 -16
  920. package/dist/scripts/assert-release-tag-version.js +0 -23
  921. package/dist/scripts/build-dist.js +0 -294
  922. package/dist/scripts/build-tenant-worker.js +0 -36
  923. package/dist/scripts/check-build-warnings.js +0 -51
  924. package/dist/scripts/cleanup-markdown.js +0 -377
  925. package/dist/scripts/cli-test-fixtures.js +0 -44
  926. package/dist/scripts/config-treeseed.js +0 -131
  927. package/dist/scripts/deployment-readiness.js +0 -20
  928. package/dist/scripts/generate-treedx-openapi-types.js +0 -186
  929. package/dist/scripts/install-managed-dependencies.js +0 -12
  930. package/dist/scripts/key-agent.js +0 -165
  931. package/dist/scripts/local-dev.js +0 -129
  932. package/dist/scripts/migrate-journey-csv-to-guarantees.js +0 -140
  933. package/dist/scripts/operations-runner-smoke.js +0 -16
  934. package/dist/scripts/package-tools.js +0 -85
  935. package/dist/scripts/patch-starlight-content-path.js +0 -173
  936. package/dist/scripts/prepare.js +0 -10
  937. package/dist/scripts/publish-package.js +0 -29
  938. package/dist/scripts/release-verify.js +0 -105
  939. package/dist/scripts/run-fixture-astro-command.js +0 -18
  940. package/dist/scripts/scaffold-site.js +0 -66
  941. package/dist/scripts/sync-template.js +0 -20
  942. package/dist/scripts/template-catalog.test.js +0 -86
  943. package/dist/scripts/template-command.js +0 -31
  944. package/dist/scripts/tenant-astro-command.js +0 -3
  945. package/dist/scripts/tenant-build.js +0 -48
  946. package/dist/scripts/tenant-check.js +0 -10
  947. package/dist/scripts/tenant-d1-migrate-local.js +0 -15
  948. package/dist/scripts/tenant-deploy.js +0 -220
  949. package/dist/scripts/tenant-destroy.js +0 -112
  950. package/dist/scripts/tenant-dev.js +0 -160
  951. package/dist/scripts/tenant-lint.js +0 -4
  952. package/dist/scripts/tenant-test.js +0 -4
  953. package/dist/scripts/tenant-workflow-action.js +0 -101
  954. package/dist/scripts/test-cloudflare-local.js +0 -209
  955. package/dist/scripts/test-scaffold.js +0 -300
  956. package/dist/scripts/test-smoke.js +0 -137
  957. package/dist/scripts/treeseed-assert-release-tag-version.js +0 -21
  958. package/dist/scripts/treeseed-build-dist.js +0 -131
  959. package/dist/scripts/treeseed-publish-package.js +0 -19
  960. package/dist/scripts/treeseed-release-verify.js +0 -131
  961. package/dist/scripts/validate-templates.js +0 -6
  962. package/dist/scripts/verify-driver.js +0 -45
  963. package/dist/scripts/workflow-commands.test.js +0 -31
  964. package/dist/scripts/workspace-command-e2e.js +0 -718
  965. package/dist/scripts/workspace-lint.js +0 -15
  966. package/dist/scripts/workspace-preflight.js +0 -22
  967. package/dist/scripts/workspace-publish-changed-packages.js +0 -16
  968. package/dist/scripts/workspace-release-test.js +0 -104
  969. package/dist/scripts/workspace-release-verify.js +0 -81
  970. package/dist/scripts/workspace-save.js +0 -64
  971. package/dist/scripts/workspace-start-warning.js +0 -3
  972. package/dist/scripts/workspace-test-unit.js +0 -4
  973. package/dist/scripts/workspace-test.js +0 -17
  974. package/dist/sdk-dispatch.d.ts +0 -12
  975. package/dist/sdk-dispatch.js +0 -126
  976. package/dist/sdk-fields.d.ts +0 -11
  977. package/dist/sdk-filters.d.ts +0 -4
  978. package/dist/sdk-filters.js +0 -74
  979. package/dist/sdk-types.d.ts +0 -3868
  980. package/dist/sdk-types.js +0 -542
  981. package/dist/sdk-version.d.ts +0 -2
  982. package/dist/sdk-version.js +0 -42
  983. package/dist/sdk.d.ts +0 -266
  984. package/dist/sdk.js +0 -825
  985. package/dist/secrets-capability.d.ts +0 -421
  986. package/dist/secrets-capability.js +0 -530
  987. package/dist/seeds/errors.d.ts +0 -5
  988. package/dist/seeds/errors.js +0 -22
  989. package/dist/seeds/index.d.ts +0 -20
  990. package/dist/seeds/index.js +0 -53
  991. package/dist/seeds/loader.d.ts +0 -8
  992. package/dist/seeds/loader.js +0 -32
  993. package/dist/seeds/normalize.d.ts +0 -13
  994. package/dist/seeds/normalize.js +0 -282
  995. package/dist/seeds/planner.d.ts +0 -10
  996. package/dist/seeds/planner.js +0 -149
  997. package/dist/seeds/schema.d.ts +0 -2
  998. package/dist/seeds/schema.js +0 -893
  999. package/dist/seeds/types.d.ts +0 -312
  1000. package/dist/seeds/types.js +0 -12
  1001. package/dist/service-credentials.d.ts +0 -54
  1002. package/dist/service-credentials.js +0 -112
  1003. package/dist/stores/cursor-store.d.ts +0 -10
  1004. package/dist/stores/cursor-store.js +0 -164
  1005. package/dist/stores/envelopes.d.ts +0 -116
  1006. package/dist/stores/envelopes.js +0 -219
  1007. package/dist/stores/helpers.d.ts +0 -12
  1008. package/dist/stores/helpers.js +0 -42
  1009. package/dist/stores/lease-store.d.ts +0 -18
  1010. package/dist/stores/lease-store.js +0 -189
  1011. package/dist/stores/message-store.d.ts +0 -12
  1012. package/dist/stores/message-store.js +0 -273
  1013. package/dist/stores/operational-store.d.ts +0 -55
  1014. package/dist/stores/operational-store.js +0 -861
  1015. package/dist/stores/project-workflow-store.d.ts +0 -56
  1016. package/dist/stores/project-workflow-store.js +0 -482
  1017. package/dist/stores/run-store.d.ts +0 -9
  1018. package/dist/stores/run-store.js +0 -75
  1019. package/dist/stores/subscription-store.d.ts +0 -8
  1020. package/dist/stores/subscription-store.js +0 -73
  1021. package/dist/template-catalog.d.ts +0 -13
  1022. package/dist/template-catalog.js +0 -151
  1023. package/dist/template-launch-requirements.d.ts +0 -118
  1024. package/dist/template-launch-requirements.js +0 -768
  1025. package/dist/template-launch-ui.d.ts +0 -85
  1026. package/dist/template-launch-ui.js +0 -189
  1027. package/dist/timing.d.ts +0 -20
  1028. package/dist/timing.js +0 -73
  1029. package/dist/treedx/adapters.d.ts +0 -6
  1030. package/dist/treedx/adapters.js +0 -36
  1031. package/dist/treedx/client.d.ts +0 -222
  1032. package/dist/treedx/client.js +0 -871
  1033. package/dist/treedx/errors.d.ts +0 -13
  1034. package/dist/treedx/federated-client.d.ts +0 -27
  1035. package/dist/treedx/federated-client.js +0 -158
  1036. package/dist/treedx/graph-adapter.d.ts +0 -33
  1037. package/dist/treedx/graph-adapter.js +0 -156
  1038. package/dist/treedx/index.d.ts +0 -14
  1039. package/dist/treedx/index.js +0 -48
  1040. package/dist/treedx/market-integration.d.ts +0 -27
  1041. package/dist/treedx/market-integration.js +0 -131
  1042. package/dist/treedx/ports.d.ts +0 -166
  1043. package/dist/treedx/ports.js +0 -231
  1044. package/dist/treedx/query-adapter.d.ts +0 -19
  1045. package/dist/treedx/query-adapter.js +0 -62
  1046. package/dist/treedx/registry-client.d.ts +0 -11
  1047. package/dist/treedx/registry-client.js +0 -19
  1048. package/dist/treedx/repository-adapter.d.ts +0 -45
  1049. package/dist/treedx/repository-adapter.js +0 -319
  1050. package/dist/treedx/sdk-integration.d.ts +0 -27
  1051. package/dist/treedx/sdk-integration.js +0 -63
  1052. package/dist/treedx/workspace-adapter.d.ts +0 -27
  1053. package/dist/treedx/workspace-adapter.js +0 -65
  1054. package/dist/treedx-backends.d.ts +0 -220
  1055. package/dist/treedx-backends.js +0 -634
  1056. package/dist/treedx-client.d.ts +0 -89
  1057. package/dist/treedx-client.js +0 -184
  1058. package/dist/treeseed/services/compose.yml +0 -6
  1059. package/dist/treeseed/template-catalog/catalog.fixture.json +0 -707
  1060. package/dist/types/cloudflare.d.ts +0 -54
  1061. package/dist/verification.d.ts +0 -31
  1062. package/dist/verification.js +0 -430
  1063. package/dist/workflow/operations.d.ts +0 -1516
  1064. package/dist/workflow/operations.js +0 -7001
  1065. package/dist/workflow/policy.d.ts +0 -12
  1066. package/dist/workflow/policy.js +0 -70
  1067. package/dist/workflow/runs.d.ts +0 -143
  1068. package/dist/workflow/runs.js +0 -720
  1069. package/dist/workflow/session.d.ts +0 -34
  1070. package/dist/workflow/session.js +0 -160
  1071. package/dist/workflow/worktrees.d.ts +0 -43
  1072. package/dist/workflow/worktrees.js +0 -307
  1073. package/dist/workflow-state.d.ts +0 -250
  1074. package/dist/workflow-state.js +0 -844
  1075. package/dist/workflow-support.d.ts +0 -28
  1076. package/dist/workflow-support.js +0 -390
  1077. package/dist/workflow.d.ts +0 -327
  1078. package/dist/workflow.js +0 -140
  1079. package/drizzle/d1/0000_treeseed_d1.sql +0 -19
  1080. package/drizzle/market/0000_market_control_plane.sql +0 -3223
  1081. package/drizzle/market/0001_capacity_budget_mode_default.sql +0 -4
  1082. package/drizzle/market/0002_user_email_addresses.sql +0 -26
  1083. package/drizzle/market/0003_project_team_slug_unique.sql +0 -4
  1084. package/drizzle/market/0004_treedx_market_integration.sql +0 -99
  1085. package/drizzle/market/0005_agent_capacity_coordination.sql +0 -145
  1086. package/drizzle/market/0006_provider_assignment_lifecycle.sql +0 -9
  1087. package/drizzle/market/0007_agent_architecture_gap_closure.sql +0 -157
  1088. package/drizzle/market/0008_agent_capacity_operational_closure.sql +0 -27
  1089. package/drizzle/market/0009_agent_capacity_runtime_hardening.sql +0 -29
  1090. package/drizzle/market/0010_secrets_capability_persistence.sql +0 -130
  1091. package/drizzle/market/0011_github_app_adapter.sql +0 -47
  1092. package/drizzle/market/0012_workday_test_runs.sql +0 -44
  1093. package/drizzle/market/0013_runtime_task_lifecycle.sql +0 -39
  1094. package/drizzle/market/0014_governance_pipeline.sql +0 -189
  1095. package/drizzle/market/0015_agent_decision_assignment_graphs.sql +0 -60
  1096. package/scripts/verify-driver.ts +0 -51
  1097. package/templates/github/deploy-web.workflow.yml +0 -168
  1098. package/templates/github/hosted-project.workflow.yml +0 -76
  1099. /package/dist/{api/types.js → agent-capacity/contracts/capacity/workdays/workday-records.js} +0 -0
  1100. /package/dist/{hosting/contracts.js → agent-capacity/contracts/operations/workflow-promotion.js} +0 -0
  1101. /package/dist/{platform/contracts.js → agent-capacity/contracts/projects/agents/project-agent-class.js} +0 -0
  1102. /package/dist/{reconcile/contracts.js → agent-capacity/contracts/runtime/runtime-observability.js} +0 -0
  1103. /package/dist/{types/cloudflare.js → agent-capacity/contracts/support/decision-work.js} +0 -0
  1104. /package/dist/{field-aliases.js → entrypoints/models/field-aliases.js} +0 -0
  1105. /package/dist/{sdk-fields.js → entrypoints/models/sdk-fields.js} +0 -0
  1106. /package/dist/{runtime.d.ts → runtime/runtime.d.ts} +0 -0
  1107. /package/dist/{runtime.js → runtime/runtime.js} +0 -0
  1108. /package/dist/treedx/{errors.js → support/errors.js} +0 -0
package/dist/capacity.js DELETED
@@ -1,2331 +0,0 @@
1
- const ACTUAL_CREDIT_FORMULA_VERSION = "treeseed.actual-credits.v1";
2
- function finiteActualMetric(value) {
3
- if (typeof value === "number" && Number.isFinite(value)) return value;
4
- if (typeof value === "string" && value.trim()) {
5
- const parsed = Number(value);
6
- if (Number.isFinite(parsed)) return parsed;
7
- }
8
- return null;
9
- }
10
- function firstActualMetric(...values) {
11
- for (const value of values) {
12
- const next = finiteActualMetric(value);
13
- if (next !== null) return next;
14
- }
15
- return null;
16
- }
17
- function objectActualValue(value) {
18
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
19
- }
20
- function booleanActualFlag(value) {
21
- return value === true || value === "true" || value === 1 || value === "1";
22
- }
23
- function roundActualCredits(value) {
24
- if (!Number.isFinite(value) || value <= 0) return 0;
25
- return Math.round(value * 100) / 100;
26
- }
27
- function roundUpCreditComponent(value) {
28
- if (!Number.isFinite(value) || value <= 0) return 0;
29
- return Math.ceil(value * 100) / 100;
30
- }
31
- function stringActualValue(value, fallback = "") {
32
- return typeof value === "string" && value.trim() ? value.trim() : fallback;
33
- }
34
- function nativeUsageUnit(input) {
35
- const native = objectActualValue(input);
36
- const explicit = stringActualValue(native.nativeUnit, stringActualValue(native.native_unit));
37
- if (explicit) return explicit;
38
- if (firstActualMetric(native.wallMinutes, native.wall_minutes, native.durationMinutes, native.duration_minutes) !== null) return "wall_minute";
39
- if (firstActualMetric(native.quotaMinutes, native.quota_minutes) !== null) return "quota_minute";
40
- if (firstActualMetric(native.usd, native.costUsd, native.cost_usd) !== null) return "usd";
41
- if (firstActualMetric(native.inputTokens, native.input_tokens, native.outputTokens, native.output_tokens) !== null) return "token";
42
- return null;
43
- }
44
- function nativeUsageAmount(input, nativeUnit) {
45
- const native = objectActualValue(input);
46
- const unit = nativeUnit?.trim() || nativeUsageUnit(native);
47
- if (!unit) return null;
48
- if (unit === "wall_minute") {
49
- return firstActualMetric(native.wallMinutes, native.wall_minutes, native.durationMinutes, native.duration_minutes);
50
- }
51
- if (unit === "quota_minute") {
52
- return firstActualMetric(native.quotaMinutes, native.quota_minutes);
53
- }
54
- if (unit === "usd") {
55
- return firstActualMetric(native.usd, native.costUsd, native.cost_usd);
56
- }
57
- if (unit === "token") {
58
- const inputTokens = firstActualMetric(native.inputTokens, native.input_tokens) ?? 0;
59
- const outputTokens = firstActualMetric(native.outputTokens, native.output_tokens) ?? 0;
60
- const cachedInputTokens = firstActualMetric(native.cachedInputTokens, native.cached_input_tokens) ?? 0;
61
- const total = Math.max(0, inputTokens + outputTokens - cachedInputTokens);
62
- return total > 0 ? total : null;
63
- }
64
- return firstActualMetric(native.amount, native.value, native.nativeAmount, native.native_amount);
65
- }
66
- function conversionConfidence(input) {
67
- if (input.completedSampleCount < 5) return "low";
68
- if (input.completedSampleCount < 20) return "medium";
69
- const p50 = Math.max(1, input.nativeUnitsPerCreditP50 ?? 1);
70
- const spread = Math.sqrt(Math.max(0, input.ratioVariance)) / p50;
71
- return spread <= 0.5 ? "high" : "medium";
72
- }
73
- function selectCreditConversionProfile(input) {
74
- const taskSignature = input.taskSignature?.trim();
75
- const executionProfileId = input.executionProfileId?.trim() || DEFAULT_EXECUTION_PROFILE_ID;
76
- const executionProviderKind = input.executionProviderKind?.trim();
77
- const nativeUnit = input.nativeUnit?.trim();
78
- if (!taskSignature || !executionProviderKind || !nativeUnit) return null;
79
- return (input.profiles ?? []).find(
80
- (profile) => profile.taskSignature === taskSignature && (profile.executionProfileId || DEFAULT_EXECUTION_PROFILE_ID) === executionProfileId && profile.executionProviderKind === executionProviderKind && profile.nativeUnit === nativeUnit
81
- ) ?? null;
82
- }
83
- function buildCreditConversionProfileFromActuals(input) {
84
- const taskSignature = input.taskSignature;
85
- const executionProfileId = input.executionProfileId?.trim() || DEFAULT_EXECUTION_PROFILE_ID;
86
- const executionProviderKind = input.executionProviderKind.trim();
87
- const nativeUnit = input.nativeUnit.trim();
88
- const matching = input.actuals.filter(
89
- (actual) => actual.taskSignature === taskSignature && (actual.executionProfileId || DEFAULT_EXECUTION_PROFILE_ID) === executionProfileId
90
- );
91
- const completed = matching.filter((actual) => !isInterruptedUsageActual(actual));
92
- const interrupted = matching.filter((actual) => isInterruptedUsageActual(actual));
93
- const completedRatios = completed.map((actual) => {
94
- const amount = nativeUsageAmount(actual.nativeUsage, nativeUnit);
95
- const credits = finiteOrParsedNumber(actual.actualCredits);
96
- if (amount === null || amount <= 0 || credits === null || credits <= 0) return null;
97
- return {
98
- nativeUnitsPerCredit: amount / credits,
99
- creditsPerNativeUnit: credits / amount,
100
- actualCredits: credits,
101
- nativeAmount: amount
102
- };
103
- }).filter((value) => value !== null);
104
- const ratioP50 = estimateLearningPercentile(completedRatios.map((sample) => sample.nativeUnitsPerCredit), 50);
105
- const ratioP90 = estimateLearningPercentile(completedRatios.map((sample) => sample.nativeUnitsPerCredit), 90);
106
- const ratioVariance = estimateLearningVariance(completedRatios.map((sample) => sample.nativeUnitsPerCredit));
107
- const outlierLimit = ratioP90 === null ? null : Math.max(ratioP90 * 1.5, (ratioP50 ?? ratioP90) + Math.sqrt(ratioVariance));
108
- const filteredRatios = outlierLimit === null ? completedRatios : completedRatios.filter((sample) => sample.nativeUnitsPerCredit <= outlierLimit);
109
- const dates = matching.map((actual) => actual.createdAt).filter((value) => typeof value === "string" && value.length > 0).sort();
110
- const partialCredits = interrupted.reduce((total, actual) => total + Math.max(0, finiteOrParsedNumber(actual.actualCredits) ?? 0), 0);
111
- const partialNativeAmount = interrupted.reduce((total, actual) => total + Math.max(0, nativeUsageAmount(actual.nativeUsage, nativeUnit) ?? 0), 0);
112
- const updatedAt = input.now instanceof Date ? input.now.toISOString() : typeof input.now === "string" ? input.now : (/* @__PURE__ */ new Date()).toISOString();
113
- const nativeUnitsPerCreditP50 = estimateLearningPercentile(filteredRatios.map((sample) => sample.nativeUnitsPerCredit), 50);
114
- const nativeUnitsPerCreditP90 = estimateLearningPercentile(filteredRatios.map((sample) => sample.nativeUnitsPerCredit), 90);
115
- return {
116
- id: input.id ?? `${taskSignature}:${executionProfileId}:${executionProviderKind}:${nativeUnit}`,
117
- taskSignature,
118
- executionProfileId,
119
- executionProviderKind,
120
- nativeUnit,
121
- sampleCount: matching.length,
122
- completedSampleCount: completedRatios.length,
123
- interruptedSampleCount: interrupted.length,
124
- nativeUnitsPerCreditP50,
125
- nativeUnitsPerCreditP90,
126
- creditsPerNativeUnitP50: estimateLearningPercentile(filteredRatios.map((sample) => sample.creditsPerNativeUnit), 50),
127
- creditsPerNativeUnitP90: estimateLearningPercentile(filteredRatios.map((sample) => sample.creditsPerNativeUnit), 90),
128
- actualCreditsP50: estimateLearningPercentile(filteredRatios.map((sample) => sample.actualCredits), 50),
129
- actualCreditsP90: estimateLearningPercentile(filteredRatios.map((sample) => sample.actualCredits), 90),
130
- confidence: conversionConfidence({
131
- completedSampleCount: completedRatios.length,
132
- ratioVariance,
133
- nativeUnitsPerCreditP50
134
- }),
135
- formulaVersion: input.formulaVersion ?? ACTUAL_CREDIT_FORMULA_VERSION,
136
- metadata: {
137
- outlierCount: outlierLimit === null ? 0 : completedRatios.length - filteredRatios.length,
138
- ratioVariance,
139
- partialCredits,
140
- partialNativeAmount,
141
- firstSampleAt: dates[0] ?? null,
142
- lastSampleAt: dates.at(-1) ?? null
143
- },
144
- updatedAt
145
- };
146
- }
147
- function derivedConfidenceRank(value) {
148
- if (value === "high") return 3;
149
- if (value === "medium") return 2;
150
- return 1;
151
- }
152
- function derivedConfidenceFromRank(rank) {
153
- if (rank >= 3) return "high";
154
- if (rank >= 2) return "medium";
155
- return "low";
156
- }
157
- function lowerDerivedConfidence(value) {
158
- return derivedConfidenceFromRank(Math.min(derivedConfidenceRank(value), 2));
159
- }
160
- function nativeRemainingAmount(input, nativeUnit) {
161
- return nativeUsageAmount({
162
- ...input,
163
- nativeUnit
164
- }, nativeUnit);
165
- }
166
- function reservationNativeDebit(reservation, executionProvider, nativeUnit) {
167
- if (!["reserved", "consuming", "consumed", "failed", "overran_pending_approval"].includes(reservation.state)) {
168
- return { reserved: 0, consumed: 0, inferred: false };
169
- }
170
- const metadata = readRecord(reservation.metadata);
171
- const metadataNativeUnit = typeof metadata.nativeUnit === "string" && metadata.nativeUnit.trim() ? metadata.nativeUnit.trim() : typeof metadata.native_unit === "string" && metadata.native_unit.trim() ? metadata.native_unit.trim() : null;
172
- const directReserved = finiteOrParsedNumber(reservation.reservedNativeAmount);
173
- const directConsumed = finiteOrParsedNumber(reservation.consumedNativeAmount);
174
- if ((reservation.nativeUnit ?? null) === nativeUnit && (directReserved !== null || directConsumed !== null)) {
175
- return {
176
- reserved: ["reserved", "consuming"].includes(reservation.state) ? Math.max(directReserved ?? 0, directConsumed ?? 0) : 0,
177
- consumed: ["consumed", "failed", "overran_pending_approval"].includes(reservation.state) ? Math.max(directConsumed ?? 0, 0) : 0,
178
- inferred: false
179
- };
180
- }
181
- const metadataReserved = finiteOrParsedNumber(metadata.reservedNativeAmount) ?? finiteOrParsedNumber(metadata.reserved_native_amount);
182
- const metadataConsumed = finiteOrParsedNumber(metadata.consumedNativeAmount) ?? finiteOrParsedNumber(metadata.consumed_native_amount);
183
- if (metadataNativeUnit === nativeUnit && (metadataReserved !== null || metadataConsumed !== null)) {
184
- return {
185
- reserved: ["reserved", "consuming"].includes(reservation.state) ? Math.max(metadataReserved ?? 0, metadataConsumed ?? 0) : 0,
186
- consumed: ["consumed", "failed", "overran_pending_approval"].includes(reservation.state) ? Math.max(metadataConsumed ?? 0, 0) : 0,
187
- inferred: true
188
- };
189
- }
190
- if (nativeUnit === "usd" && reservation.reservedUsd !== null) {
191
- return {
192
- reserved: ["reserved", "consuming"].includes(reservation.state) ? Math.max(reservation.reservedUsd ?? 0, reservation.consumedUsd ?? 0) : 0,
193
- consumed: ["consumed", "failed", "overran_pending_approval"].includes(reservation.state) ? Math.max(reservation.consumedUsd ?? 0, 0) : 0,
194
- inferred: true
195
- };
196
- }
197
- if (reservation.reservedProviderUnits !== null && executionProvider.nativeUnit === nativeUnit) {
198
- return {
199
- reserved: ["reserved", "consuming"].includes(reservation.state) ? Math.max(reservation.reservedProviderUnits ?? 0, reservation.consumedProviderUnits ?? 0) : 0,
200
- consumed: ["consumed", "failed", "overran_pending_approval"].includes(reservation.state) ? Math.max(reservation.consumedProviderUnits ?? 0, 0) : 0,
201
- inferred: true
202
- };
203
- }
204
- return { reserved: 0, consumed: 0, inferred: false };
205
- }
206
- function roundDownCredits(value) {
207
- if (!Number.isFinite(value) || value <= 0) return 0;
208
- return Math.floor(value * 100) / 100;
209
- }
210
- function deriveAvailableCredits(input) {
211
- const executionProvider = input.executionProvider;
212
- const nativeUnit = input.nativeUnit?.trim() || input.nativeLimit?.nativeUnit || executionProvider.nativeUnit;
213
- const reasons = [];
214
- const configuredNativeLimit = finiteOrParsedNumber(input.nativeLimit?.limitAmount);
215
- const observationRemaining = nativeRemainingAmount(readRecord(input.latestObservation?.nativeRemaining), nativeUnit);
216
- let nativeBase = null;
217
- let nativeRemainingSource = "unknown";
218
- if (observationRemaining !== null) {
219
- nativeBase = Math.max(0, observationRemaining);
220
- nativeRemainingSource = "observation";
221
- reasons.push("observation_remaining");
222
- } else if (configuredNativeLimit !== null) {
223
- nativeBase = Math.max(0, configuredNativeLimit);
224
- nativeRemainingSource = "configured_limit";
225
- reasons.push(executionProvider.quotaVisibility === "opaque" ? "opaque_limit_fallback" : "configured_limit");
226
- } else {
227
- reasons.push("missing_native_limit");
228
- }
229
- const scopedReservations = (input.activeReservations ?? []).filter(
230
- (reservation) => reservation.executionProviderId ? reservation.executionProviderId === executionProvider.id : reservation.capacityProviderId === executionProvider.capacityProviderId
231
- );
232
- let activeReservedNativeAmount = 0;
233
- let activeConsumedNativeAmount = 0;
234
- let inferredReservationCount = 0;
235
- for (const reservation of scopedReservations) {
236
- const debit = reservationNativeDebit(reservation, executionProvider, nativeUnit);
237
- activeReservedNativeAmount += debit.reserved;
238
- activeConsumedNativeAmount += debit.consumed;
239
- if (debit.inferred && (debit.reserved > 0 || debit.consumed > 0)) inferredReservationCount += 1;
240
- }
241
- if (activeReservedNativeAmount > 0) reasons.push("active_native_reservations");
242
- if (inferredReservationCount > 0) reasons.push("inferred_legacy_native_reservations");
243
- const reserveBufferPercent = Math.max(0, finiteOrParsedNumber(input.nativeLimit?.reserveBufferPercent) ?? 0);
244
- const reserveBufferNativeAmount = configuredNativeLimit === null ? 0 : configuredNativeLimit * reserveBufferPercent / 100;
245
- if (reserveBufferNativeAmount > 0) reasons.push("reserve_buffer");
246
- const availableNativeAmount = Math.max(0, (nativeBase ?? 0) - activeReservedNativeAmount - reserveBufferNativeAmount);
247
- const profile = input.conversionProfile ?? null;
248
- let nativeUnitsPerCredit = profile?.nativeUnitsPerCreditP90 ?? null;
249
- let confidence = profile?.confidence ?? "low";
250
- if (nativeUnitsPerCredit !== null && nativeUnitsPerCredit > 0) {
251
- reasons.push("p90_conversion_profile");
252
- } else if (profile?.nativeUnitsPerCreditP50 !== null && profile?.nativeUnitsPerCreditP50 !== void 0 && profile.nativeUnitsPerCreditP50 > 0) {
253
- nativeUnitsPerCredit = profile.nativeUnitsPerCreditP50;
254
- confidence = lowerDerivedConfidence(profile.confidence);
255
- reasons.push("p50_conversion_fallback");
256
- } else {
257
- reasons.push("missing_conversion_profile");
258
- }
259
- if (nativeRemainingSource === "unknown") confidence = "low";
260
- const derivedAvailableCredits = nativeUnitsPerCredit !== null && nativeUnitsPerCredit > 0 ? roundDownCredits(availableNativeAmount / nativeUnitsPerCredit) : null;
261
- return {
262
- executionProviderId: executionProvider.id,
263
- capacityProviderId: executionProvider.capacityProviderId,
264
- executionProviderKind: executionProvider.kind,
265
- nativeUnit,
266
- scope: input.scope ?? input.nativeLimit?.scope ?? null,
267
- configuredNativeLimit,
268
- observedNativeRemaining: observationRemaining,
269
- nativeRemainingSource,
270
- activeReservedNativeAmount,
271
- activeConsumedNativeAmount,
272
- reserveBufferPercent,
273
- reserveBufferNativeAmount,
274
- availableNativeAmount,
275
- nativeUnitsPerCredit,
276
- conversionProfileId: profile?.id ?? null,
277
- conversionTaskSignature: profile?.taskSignature ?? null,
278
- conversionConfidence: profile?.confidence ?? null,
279
- derivedAvailableCredits,
280
- confidence,
281
- resetAt: input.latestObservation?.resetAt ?? input.nativeLimit?.resetAt ?? null,
282
- reasons: [...new Set(reasons)],
283
- metadata: {
284
- quotaVisibility: executionProvider.quotaVisibility,
285
- latestObservedAt: input.latestObservation?.observedAt ?? null,
286
- conversionFormulaVersion: profile?.formulaVersion ?? null
287
- }
288
- };
289
- }
290
- function calculateActualCredits(input) {
291
- const native = objectActualValue(input.nativeUsage);
292
- const metadata = objectActualValue(native.metadata);
293
- const wallMinutes = firstActualMetric(input.wallMinutes, native.wallMinutes, native.wall_minutes, native.durationMinutes, native.duration_minutes);
294
- const quotaMinutes = firstActualMetric(input.quotaMinutes, native.quotaMinutes, native.quota_minutes);
295
- const inputTokens = firstActualMetric(input.inputTokens, native.inputTokens, native.input_tokens);
296
- const outputTokens = firstActualMetric(input.outputTokens, native.outputTokens, native.output_tokens);
297
- const cachedInputTokens = firstActualMetric(input.cachedInputTokens, native.cachedInputTokens, native.cached_input_tokens);
298
- const usd = firstActualMetric(input.actualUsd, native.usd, native.costUsd, native.cost_usd);
299
- const filesOpened = firstActualMetric(input.filesOpened, native.filesOpened, native.files_opened);
300
- const filesChanged = firstActualMetric(input.filesChanged, native.filesChanged, native.files_changed);
301
- const diffLinesAdded = firstActualMetric(input.diffLinesAdded, native.diffLinesAdded, native.diff_lines_added);
302
- const diffLinesRemoved = firstActualMetric(input.diffLinesRemoved, native.diffLinesRemoved, native.diff_lines_removed);
303
- const testRuns = firstActualMetric(input.testRuns, native.testRuns, native.test_runs);
304
- const retryCount = firstActualMetric(input.retryCount, native.retryCount, native.retry_count);
305
- const nativeUnit = typeof native.nativeUnit === "string" ? native.nativeUnit : typeof native.native_unit === "string" ? native.native_unit : nativeUsageUnit(native) ?? (wallMinutes !== null ? "wall_minute" : quotaMinutes !== null ? "quota_minute" : usd !== null ? "usd" : Math.max(0, (inputTokens ?? 0) + (outputTokens ?? 0) - (cachedInputTokens ?? 0)) > 0 ? "token" : null);
306
- const observedAt = typeof native.observedAt === "string" ? native.observedAt : typeof native.observed_at === "string" ? native.observed_at : null;
307
- const partial = booleanActualFlag(native.partial) || booleanActualFlag(metadata.partial);
308
- const interrupted = booleanActualFlag(native.interrupted) || booleanActualFlag(metadata.interrupted);
309
- const legacyActualCredits = finiteActualMetric(input.legacyActualCredits);
310
- const reservedCredits = finiteActualMetric(input.reservedCredits);
311
- const components = {};
312
- if (wallMinutes !== null && wallMinutes > 0) {
313
- components.wallMinutes = Math.ceil(wallMinutes / 5);
314
- } else if (quotaMinutes !== null && quotaMinutes > 0) {
315
- components.quotaMinutes = Math.ceil(quotaMinutes / 5);
316
- }
317
- if (usd !== null && usd > 0) components.usd = roundUpCreditComponent(usd / 0.03);
318
- const billableTokens = Math.max(0, (inputTokens ?? 0) + (outputTokens ?? 0) - (cachedInputTokens ?? 0));
319
- if (billableTokens > 0) components.tokens = Math.ceil(billableTokens / 8e3);
320
- if (filesChanged !== null && filesChanged > 0) components.filesChanged = Math.ceil(filesChanged) * 2;
321
- if (testRuns !== null && testRuns > 0) components.testRuns = Math.ceil(testRuns);
322
- if (retryCount !== null && retryCount > 0) components.retryCount = Math.ceil(retryCount) * 3;
323
- const nativeUsage = {
324
- ...native,
325
- nativeUnit,
326
- wallMinutes,
327
- quotaMinutes,
328
- inputTokens,
329
- outputTokens,
330
- cachedInputTokens,
331
- usd,
332
- filesOpened,
333
- filesChanged,
334
- diffLinesAdded,
335
- diffLinesRemoved,
336
- testRuns,
337
- retryCount,
338
- partial,
339
- interrupted,
340
- source: typeof native.source === "string" ? native.source : input.source ?? null,
341
- observedAt,
342
- metadata
343
- };
344
- const componentTotal = Object.values(components).reduce((total, value) => total + value, 0);
345
- const conversionProfile = input.conversionProfile ?? null;
346
- const conversionProfileNativeAmount = conversionProfile ? nativeUsageAmount(nativeUsage, conversionProfile.nativeUnit) : null;
347
- const conversionProfileCredits = conversionProfileNativeAmount !== null && conversionProfileNativeAmount > 0 && conversionProfile.nativeUnitsPerCreditP50 !== null && conversionProfile.nativeUnitsPerCreditP50 > 0 ? roundActualCredits(conversionProfileNativeAmount / conversionProfile.nativeUnitsPerCreditP50) : null;
348
- if (legacyActualCredits !== null && input.actualCreditsOverride === true) {
349
- return {
350
- actualCredits: roundActualCredits(legacyActualCredits),
351
- formulaVersion: ACTUAL_CREDIT_FORMULA_VERSION,
352
- source: "legacy_override",
353
- nativeUsage,
354
- components,
355
- partial,
356
- interrupted,
357
- conversionProfileId: conversionProfile?.id ?? null,
358
- conversionConfidence: conversionProfile?.confidence ?? null
359
- };
360
- }
361
- if (conversionProfile?.confidence === "high" && conversionProfileCredits !== null) {
362
- return {
363
- actualCredits: conversionProfileCredits,
364
- formulaVersion: ACTUAL_CREDIT_FORMULA_VERSION,
365
- source: "conversion_profile",
366
- nativeUsage,
367
- components: {
368
- ...components,
369
- conversionProfile: conversionProfileCredits
370
- },
371
- partial,
372
- interrupted,
373
- conversionProfileId: conversionProfile.id ?? null,
374
- conversionConfidence: conversionProfile.confidence
375
- };
376
- }
377
- if (conversionProfile?.confidence === "medium" && conversionProfileCredits !== null && componentTotal > 0) {
378
- return {
379
- actualCredits: roundActualCredits((conversionProfileCredits + componentTotal) / 2),
380
- formulaVersion: ACTUAL_CREDIT_FORMULA_VERSION,
381
- source: "blended_conversion_profile",
382
- nativeUsage,
383
- components: {
384
- ...components,
385
- conversionProfile: conversionProfileCredits,
386
- bootstrap: roundActualCredits(componentTotal)
387
- },
388
- partial,
389
- interrupted,
390
- conversionProfileId: conversionProfile.id ?? null,
391
- conversionConfidence: conversionProfile.confidence
392
- };
393
- }
394
- if (componentTotal > 0) {
395
- return {
396
- actualCredits: roundActualCredits(componentTotal),
397
- formulaVersion: ACTUAL_CREDIT_FORMULA_VERSION,
398
- source: "central_calculator",
399
- nativeUsage,
400
- components,
401
- partial,
402
- interrupted,
403
- conversionProfileId: conversionProfile?.id ?? null,
404
- conversionConfidence: conversionProfile?.confidence ?? null
405
- };
406
- }
407
- if (legacyActualCredits !== null) {
408
- return {
409
- actualCredits: roundActualCredits(legacyActualCredits),
410
- formulaVersion: ACTUAL_CREDIT_FORMULA_VERSION,
411
- source: "legacy_fallback",
412
- nativeUsage,
413
- components,
414
- partial,
415
- interrupted,
416
- conversionProfileId: conversionProfile?.id ?? null,
417
- conversionConfidence: conversionProfile?.confidence ?? null
418
- };
419
- }
420
- if (reservedCredits !== null) {
421
- return {
422
- actualCredits: roundActualCredits(reservedCredits),
423
- formulaVersion: ACTUAL_CREDIT_FORMULA_VERSION,
424
- source: "reserved_fallback",
425
- nativeUsage,
426
- components,
427
- partial,
428
- interrupted,
429
- conversionProfileId: conversionProfile?.id ?? null,
430
- conversionConfidence: conversionProfile?.confidence ?? null
431
- };
432
- }
433
- return {
434
- actualCredits: 0,
435
- formulaVersion: ACTUAL_CREDIT_FORMULA_VERSION,
436
- source: "zero_fallback",
437
- nativeUsage,
438
- components,
439
- partial,
440
- interrupted,
441
- conversionProfileId: conversionProfile?.id ?? null,
442
- conversionConfidence: conversionProfile?.confidence ?? null
443
- };
444
- }
445
- const DEFAULT_EXECUTION_PROFILE_ID = "standard-code-model";
446
- function finiteNumber(value) {
447
- return typeof value === "number" && Number.isFinite(value) ? value : null;
448
- }
449
- function finiteOrParsedNumber(value) {
450
- if (typeof value === "number" && Number.isFinite(value)) return value;
451
- if (typeof value === "string" && value.trim()) {
452
- const parsed = Number.parseFloat(value);
453
- return Number.isFinite(parsed) ? parsed : null;
454
- }
455
- return null;
456
- }
457
- function stringValue(value) {
458
- return typeof value === "string" && value.trim() ? value.trim() : null;
459
- }
460
- function positiveNumber(value, fallback) {
461
- const parsed = finiteNumber(value);
462
- return parsed !== null && parsed > 0 ? parsed : fallback;
463
- }
464
- function nonNegativeNumber(value, fallback) {
465
- const parsed = finiteNumber(value);
466
- return parsed !== null && parsed >= 0 ? parsed : fallback;
467
- }
468
- function scarcityPenalty(level) {
469
- if (level === "high") return 35;
470
- if (level === "medium") return 15;
471
- return 0;
472
- }
473
- function metadataStatus(value) {
474
- const status = value?.status;
475
- return typeof status === "string" ? status : null;
476
- }
477
- function stringArray(value) {
478
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
479
- }
480
- function booleanValue(value) {
481
- return typeof value === "boolean" ? value : null;
482
- }
483
- function numberValue(value) {
484
- return typeof value === "number" && Number.isFinite(value) ? value : null;
485
- }
486
- function profileIdFrom(input) {
487
- if (!input) return DEFAULT_EXECUTION_PROFILE_ID;
488
- if (typeof input === "string") return input.trim() || DEFAULT_EXECUTION_PROFILE_ID;
489
- return input.id?.trim() || DEFAULT_EXECUTION_PROFILE_ID;
490
- }
491
- function metadataFlag(metadata, key) {
492
- return metadata?.[key] === true || metadata?.[key] === "true";
493
- }
494
- function numericActuals(values) {
495
- return values.map((value) => finiteOrParsedNumber(value)).filter((value) => value !== null && value >= 0).sort((left, right) => left - right);
496
- }
497
- function estimateLearningPercentile(values, percentile) {
498
- const sorted = numericActuals(values);
499
- if (sorted.length === 0) return null;
500
- const bounded = Math.min(100, Math.max(0, percentile));
501
- const index = Math.ceil(bounded / 100 * sorted.length) - 1;
502
- return sorted[Math.min(sorted.length - 1, Math.max(0, index))] ?? null;
503
- }
504
- function estimateLearningVariance(values) {
505
- const samples = numericActuals(values);
506
- if (samples.length <= 1) return 0;
507
- const mean = samples.reduce((total, value) => total + value, 0) / samples.length;
508
- return samples.reduce((total, value) => total + (value - mean) ** 2, 0) / samples.length;
509
- }
510
- function isInterruptedUsageActual(actual) {
511
- const metadata = actual.metadata ?? {};
512
- return metadataFlag(metadata, "interrupted") || metadataFlag(metadata, "partial");
513
- }
514
- function estimateProfileConfidenceScore(input) {
515
- const sampleCount = Math.max(0, Math.floor(finiteOrParsedNumber(input.sampleCount) ?? 0));
516
- const sampleScore = Math.min(1, sampleCount / 20);
517
- const p50 = Math.max(1, finiteOrParsedNumber(input.creditsP50) ?? 1);
518
- const variance = Math.max(0, finiteOrParsedNumber(input.creditsVariance) ?? 0);
519
- const varianceScore = 1 / (1 + Math.sqrt(variance) / p50);
520
- let ageScore = 1;
521
- if (input.lastSampleAt) {
522
- const now = input.now instanceof Date ? input.now : new Date(input.now ?? Date.now());
523
- const last = new Date(input.lastSampleAt);
524
- if (Number.isFinite(last.valueOf()) && Number.isFinite(now.valueOf())) {
525
- const days = Math.max(0, (now.valueOf() - last.valueOf()) / 864e5);
526
- ageScore = days > 90 ? 0.35 : days > 30 ? 0.7 : 1;
527
- }
528
- }
529
- return Math.max(0, Math.min(1, sampleScore * varianceScore * ageScore));
530
- }
531
- function estimateConfidenceFromProfile(profile, now) {
532
- if (!profile) return "medium";
533
- const confidenceScore = finiteOrParsedNumber(profile.confidenceScore) ?? estimateProfileConfidenceScore({
534
- sampleCount: profile.completedSampleCount ?? profile.sampleCount,
535
- creditsVariance: profile.creditsVariance,
536
- creditsP50: profile.creditsP50,
537
- lastSampleAt: profile.lastSampleAt ?? profile.updatedAt,
538
- now
539
- });
540
- if (confidenceScore >= 0.75) return "high";
541
- if (confidenceScore >= 0.35) return "medium";
542
- return "low";
543
- }
544
- function selectTaskEstimateProfile(input) {
545
- const taskSignature = input.taskSignature?.trim();
546
- if (!taskSignature) return null;
547
- const executionProfileId = input.executionProfileId?.trim() || profileIdFrom(input.executionProfile);
548
- const profiles = input.profiles ?? [];
549
- return profiles.find(
550
- (profile) => profile.taskSignature === taskSignature && (profile.executionProfileId || DEFAULT_EXECUTION_PROFILE_ID) === executionProfileId
551
- ) ?? profiles.find(
552
- (profile) => profile.taskSignature === taskSignature && (profile.executionProfileId || DEFAULT_EXECUTION_PROFILE_ID) === DEFAULT_EXECUTION_PROFILE_ID
553
- ) ?? null;
554
- }
555
- function buildTaskEstimateProfileFromActuals(input) {
556
- const taskSignature = input.taskSignature;
557
- const executionProfileId = input.executionProfileId?.trim() || DEFAULT_EXECUTION_PROFILE_ID;
558
- const matching = input.actuals.filter(
559
- (actual) => actual.taskSignature === taskSignature && (actual.executionProfileId || DEFAULT_EXECUTION_PROFILE_ID) === executionProfileId
560
- );
561
- const completed = matching.filter((actual) => !isInterruptedUsageActual(actual));
562
- const interrupted = matching.filter((actual) => isInterruptedUsageActual(actual));
563
- const credits = completed.map((actual) => actual.actualCredits);
564
- const creditsP50 = estimateLearningPercentile(credits, 50);
565
- const creditsP90 = estimateLearningPercentile(credits, 90);
566
- const creditsVariance = estimateLearningVariance(credits);
567
- const outlierLimit = creditsP90 === null ? null : Math.max(creditsP90 * 1.5, (creditsP50 ?? creditsP90) + Math.sqrt(creditsVariance));
568
- const lastCreatedAt = matching.map((actual) => actual.createdAt).filter((value) => typeof value === "string" && value.length > 0).sort();
569
- const partialCredits = interrupted.reduce((total, actual) => total + Math.max(0, finiteOrParsedNumber(actual.actualCredits) ?? 0), 0);
570
- const updatedAt = input.now instanceof Date ? input.now.toISOString() : typeof input.now === "string" ? input.now : (/* @__PURE__ */ new Date()).toISOString();
571
- return {
572
- taskSignature,
573
- executionProfileId,
574
- sampleCount: matching.length,
575
- completedSampleCount: completed.length,
576
- interruptedSampleCount: interrupted.length,
577
- inputTokensP50: estimateLearningPercentile(completed.map((actual) => actual.inputTokens), 50),
578
- inputTokensP90: estimateLearningPercentile(completed.map((actual) => actual.inputTokens), 90),
579
- outputTokensP50: estimateLearningPercentile(completed.map((actual) => actual.outputTokens), 50),
580
- outputTokensP90: estimateLearningPercentile(completed.map((actual) => actual.outputTokens), 90),
581
- quotaMinutesP50: estimateLearningPercentile(completed.map((actual) => actual.quotaMinutes), 50),
582
- quotaMinutesP90: estimateLearningPercentile(completed.map((actual) => actual.quotaMinutes), 90),
583
- filesChangedP50: estimateLearningPercentile(completed.map((actual) => actual.filesChanged), 50),
584
- filesChangedP90: estimateLearningPercentile(completed.map((actual) => actual.filesChanged), 90),
585
- creditsP50,
586
- creditsP90,
587
- creditsVariance,
588
- confidenceScore: estimateProfileConfidenceScore({
589
- sampleCount: completed.length,
590
- creditsVariance,
591
- creditsP50,
592
- lastSampleAt: lastCreatedAt.at(-1) ?? null,
593
- now: input.now
594
- }),
595
- outlierCount: outlierLimit === null ? 0 : credits.filter((value) => value > outlierLimit).length,
596
- partialCredits,
597
- firstSampleAt: lastCreatedAt[0] ?? null,
598
- lastSampleAt: lastCreatedAt.at(-1) ?? null,
599
- updatedAt
600
- };
601
- }
602
- const DEFAULT_EXECUTION_PROFILES = {
603
- "local-runner": {
604
- id: "local-runner",
605
- modelClass: "local",
606
- qualityWeight: 1,
607
- costMultiplier: 1,
608
- latencyClass: "low",
609
- concurrencyClass: "read_only",
610
- quotaBehavior: "compute_bound"
611
- },
612
- "local-fast-model": {
613
- id: "local-fast-model",
614
- modelClass: "local",
615
- qualityWeight: 0.65,
616
- costMultiplier: 0.35,
617
- latencyClass: "low",
618
- concurrencyClass: "read_only",
619
- quotaBehavior: "compute_bound"
620
- },
621
- "small-code-model": {
622
- id: "small-code-model",
623
- modelClass: "coding",
624
- qualityWeight: 0.75,
625
- costMultiplier: 0.5,
626
- latencyClass: "low",
627
- concurrencyClass: "repository_claim",
628
- quotaBehavior: "api_metered"
629
- },
630
- "standard-code-model": {
631
- id: "standard-code-model",
632
- modelClass: "coding",
633
- qualityWeight: 1,
634
- costMultiplier: 1,
635
- latencyClass: "medium",
636
- concurrencyClass: "repository_claim",
637
- quotaBehavior: "api_metered"
638
- },
639
- "large-reasoning-model": {
640
- id: "large-reasoning-model",
641
- modelClass: "reasoning",
642
- qualityWeight: 1.5,
643
- costMultiplier: 3,
644
- latencyClass: "high",
645
- concurrencyClass: "exclusive_project",
646
- quotaBehavior: "api_metered"
647
- },
648
- "long-context-architect": {
649
- id: "long-context-architect",
650
- modelClass: "reasoning",
651
- contextWindowTokens: 2e5,
652
- qualityWeight: 1.75,
653
- costMultiplier: 4,
654
- latencyClass: "high",
655
- concurrencyClass: "exclusive_project",
656
- quotaBehavior: "api_metered"
657
- },
658
- "cheap-review-model": {
659
- id: "cheap-review-model",
660
- modelClass: "review",
661
- qualityWeight: 0.8,
662
- costMultiplier: 0.6,
663
- latencyClass: "low",
664
- concurrencyClass: "read_only",
665
- quotaBehavior: "api_metered"
666
- },
667
- "human-review": {
668
- id: "human-review",
669
- modelClass: "human",
670
- qualityWeight: 2,
671
- costMultiplier: 10,
672
- latencyClass: "high",
673
- concurrencyClass: "human_attention",
674
- quotaBehavior: "attention_bound"
675
- }
676
- };
677
- const DEFAULT_TASK_ADMISSION_POLICY = {
678
- planningThresholdCredits: 20,
679
- approvalThresholdCredits: 50,
680
- reserveBufferPercent: 15,
681
- recoveryBudgetCredits: 0,
682
- maxDownstreamTasks: 4,
683
- maxPlanningDepth: 2,
684
- maxAdmittedPlanTasksPerCycle: 4,
685
- planningTaskSignature: "planner.dag_proposal",
686
- allowBackfill: true,
687
- maxAttentionLoad: null,
688
- reserveAttentionPercent: 0,
689
- maxContextTokens: null,
690
- maxContextSaturationPercent: 100,
691
- coordinationOverheadFactor: 1,
692
- predictiveReservePolicy: null,
693
- utilityPolicy: null
694
- };
695
- function normalizeExecutionProfile(input) {
696
- if (!input) return DEFAULT_EXECUTION_PROFILES["standard-code-model"];
697
- if (typeof input === "string") {
698
- return DEFAULT_EXECUTION_PROFILES[input] ?? {
699
- id: input,
700
- qualityWeight: 1,
701
- costMultiplier: 1,
702
- latencyClass: "medium",
703
- metadata: { source: "ad_hoc" }
704
- };
705
- }
706
- return {
707
- ...input,
708
- qualityWeight: positiveNumber(input.qualityWeight, 1),
709
- costMultiplier: positiveNumber(input.costMultiplier, 1),
710
- latencyClass: input.latencyClass || "medium"
711
- };
712
- }
713
- function normalizeTaskAdmissionPolicy(input = {}) {
714
- const reserveBufferPercent = nonNegativeNumber(input?.reserveBufferPercent, DEFAULT_TASK_ADMISSION_POLICY.reserveBufferPercent);
715
- return {
716
- ...DEFAULT_TASK_ADMISSION_POLICY,
717
- ...input ?? {},
718
- planningThresholdCredits: positiveNumber(input?.planningThresholdCredits, DEFAULT_TASK_ADMISSION_POLICY.planningThresholdCredits),
719
- approvalThresholdCredits: positiveNumber(input?.approvalThresholdCredits, DEFAULT_TASK_ADMISSION_POLICY.approvalThresholdCredits),
720
- reserveBufferPercent: Math.min(100, reserveBufferPercent),
721
- recoveryBudgetCredits: nonNegativeNumber(input?.recoveryBudgetCredits, DEFAULT_TASK_ADMISSION_POLICY.recoveryBudgetCredits),
722
- maxDownstreamTasks: Math.max(0, Math.floor(nonNegativeNumber(input?.maxDownstreamTasks, DEFAULT_TASK_ADMISSION_POLICY.maxDownstreamTasks))),
723
- maxPlanningDepth: Math.max(0, Math.floor(nonNegativeNumber(input?.maxPlanningDepth, DEFAULT_TASK_ADMISSION_POLICY.maxPlanningDepth))),
724
- maxAdmittedPlanTasksPerCycle: Math.max(1, Math.floor(nonNegativeNumber(input?.maxAdmittedPlanTasksPerCycle, DEFAULT_TASK_ADMISSION_POLICY.maxAdmittedPlanTasksPerCycle))),
725
- planningTaskSignature: typeof input?.planningTaskSignature === "string" && input.planningTaskSignature.trim() ? input.planningTaskSignature.trim() : DEFAULT_TASK_ADMISSION_POLICY.planningTaskSignature,
726
- allowBackfill: input?.allowBackfill ?? DEFAULT_TASK_ADMISSION_POLICY.allowBackfill,
727
- maxAttentionLoad: finiteOrParsedNumber(input?.maxAttentionLoad) ?? DEFAULT_TASK_ADMISSION_POLICY.maxAttentionLoad,
728
- reserveAttentionPercent: Math.min(100, nonNegativeNumber(input?.reserveAttentionPercent, DEFAULT_TASK_ADMISSION_POLICY.reserveAttentionPercent ?? 0)),
729
- maxContextTokens: finiteOrParsedNumber(input?.maxContextTokens) ?? DEFAULT_TASK_ADMISSION_POLICY.maxContextTokens,
730
- maxContextSaturationPercent: Math.min(100, positiveNumber(input?.maxContextSaturationPercent, DEFAULT_TASK_ADMISSION_POLICY.maxContextSaturationPercent ?? 100)),
731
- coordinationOverheadFactor: nonNegativeNumber(input?.coordinationOverheadFactor, DEFAULT_TASK_ADMISSION_POLICY.coordinationOverheadFactor ?? 1)
732
- };
733
- }
734
- function normalizeAttentionPolicy(input = {}) {
735
- return {
736
- maxAttentionLoad: finiteOrParsedNumber(input?.maxAttentionLoad) ?? null,
737
- reserveAttentionPercent: Math.min(100, nonNegativeNumber(input?.reserveAttentionPercent, 0)),
738
- maxContextTokens: finiteOrParsedNumber(input?.maxContextTokens) ?? null,
739
- maxContextSaturationPercent: Math.min(100, positiveNumber(input?.maxContextSaturationPercent, 100)),
740
- coordinationOverheadFactor: nonNegativeNumber(input?.coordinationOverheadFactor, 1)
741
- };
742
- }
743
- function normalizeUtilityPolicy(input = {}) {
744
- return {
745
- minimumUtilityScore: finiteOrParsedNumber(input?.minimumUtilityScore) ?? null,
746
- minimumUtilityPerCredit: finiteOrParsedNumber(input?.minimumUtilityPerCredit) ?? null,
747
- riskPenaltyFactor: nonNegativeNumber(input?.riskPenaltyFactor, 1),
748
- deadlineWindowHours: positiveNumber(input?.deadlineWindowHours, 72),
749
- maintenanceWeight: nonNegativeNumber(input?.maintenanceWeight, 1),
750
- priorityWeight: nonNegativeNumber(input?.priorityWeight, 1)
751
- };
752
- }
753
- function normalizePredictiveReservePolicy(input = {}) {
754
- const raw = readRecord(input);
755
- return {
756
- enabled: raw.enabled === true || raw.enabled === "true",
757
- baseReservePercent: Math.min(100, nonNegativeNumber(input?.baseReservePercent, 0)),
758
- maxReservePercent: Math.min(100, positiveNumber(input?.maxReservePercent, 50)),
759
- incidentReservePercent: Math.min(100, nonNegativeNumber(input?.incidentReservePercent, 15)),
760
- triggerBurstReservePercent: Math.min(100, nonNegativeNumber(input?.triggerBurstReservePercent, 10)),
761
- deploymentWindowReservePercent: Math.min(100, nonNegativeNumber(input?.deploymentWindowReservePercent, 10)),
762
- providerDegradationReservePercent: Math.min(100, nonNegativeNumber(input?.providerDegradationReservePercent, 10)),
763
- quotaPressureReservePercent: Math.min(100, nonNegativeNumber(input?.quotaPressureReservePercent, 10))
764
- };
765
- }
766
- function isoHoursUntil(value, now) {
767
- if (typeof value !== "string" || !value.trim()) return null;
768
- const target = new Date(value);
769
- if (!Number.isFinite(target.valueOf())) return null;
770
- return (target.valueOf() - now.valueOf()) / 36e5;
771
- }
772
- function riskPenalty(classification, policy) {
773
- if (classification?.risk === "high") return 20 * policy.riskPenaltyFactor;
774
- if (classification?.risk === "medium") return 8 * policy.riskPenaltyFactor;
775
- return 0;
776
- }
777
- function qualityScoreFromProfile(profile, confidence) {
778
- const confidenceWeight = confidence === "high" ? 1.1 : confidence === "low" ? 0.75 : 1;
779
- return Math.max(0, profile.qualityWeight * confidenceWeight);
780
- }
781
- function estimateUtilityForTask(input) {
782
- const policy = normalizeUtilityPolicy(input.utilityPolicy);
783
- const profile = normalizeExecutionProfile(input.executionProfile);
784
- const metadata = readRecord(input.metadata);
785
- const priority = Math.max(0, finiteOrParsedNumber(input.priority) ?? finiteOrParsedNumber(metadata.priority) ?? 0);
786
- const explicitUtility = finiteOrParsedNumber(input.utilityValue) ?? finiteOrParsedNumber(metadata.utilityValue);
787
- const maintenanceValue = Math.max(0, finiteOrParsedNumber(input.maintenanceValue) ?? finiteOrParsedNumber(metadata.maintenanceValue) ?? 0);
788
- const now = input.now instanceof Date ? input.now : new Date(input.now ?? Date.now());
789
- const hoursUntilDeadline = isoHoursUntil(input.deadlineAt ?? metadata.deadlineAt, now);
790
- const deadlinePressure = hoursUntilDeadline === null ? 0 : Math.max(0, Math.min(30, (policy.deadlineWindowHours - hoursUntilDeadline) / Math.max(1, policy.deadlineWindowHours) * 30));
791
- const successProbability = Math.max(0, Math.min(1, finiteOrParsedNumber(input.successProbability) ?? finiteOrParsedNumber(metadata.successProbability) ?? 1));
792
- const qualityScore = qualityScoreFromProfile(profile, input.classification?.confidence);
793
- const baseUtility = explicitUtility ?? priority * policy.priorityWeight + maintenanceValue * policy.maintenanceWeight;
794
- const risk = riskPenalty(input.classification, policy);
795
- const utilityScore = Math.max(0, (baseUtility + deadlinePressure) * successProbability * Math.max(0.1, qualityScore) - risk);
796
- const reservedCredits = Math.max(1, finiteOrParsedNumber(input.estimate?.reservedCredits) ?? 1);
797
- return {
798
- utilityValue: Math.max(0, baseUtility),
799
- maintenanceValue,
800
- deadlinePressure,
801
- successProbability,
802
- qualityScore,
803
- riskPenalty: risk,
804
- utilityScore,
805
- utilityPerCredit: utilityScore / reservedCredits,
806
- source: input.source ?? "capacity_utility_estimator",
807
- metadata
808
- };
809
- }
810
- function reserveSignalFlag(metadata, ...keys) {
811
- return keys.some((key) => metadata[key] === true || metadata[key] === "true");
812
- }
813
- function predictReserveForCapacityPlan(input) {
814
- const policy = normalizePredictiveReservePolicy(input.policy);
815
- const metadata = readRecord(input.metadata);
816
- const reasons = [];
817
- const signals = {};
818
- let reservePercent = policy.enabled ? policy.baseReservePercent : 0;
819
- const providerDegraded = input.plan?.providers.some((provider) => provider.status === "degraded" || metadataStatus(provider.metadata) === "degraded") ?? false;
820
- const quotaPressure = input.plan?.providers.some((provider) => {
821
- const pressure = readRecord(provider.metadata?.pressure);
822
- const quota = finiteOrParsedNumber(pressure.quotaRemainingPercent) ?? finiteOrParsedNumber(provider.metadata?.quotaRemainingPercent);
823
- return quota !== null && quota < 20;
824
- }) ?? false;
825
- if (policy.enabled && reserveSignalFlag(metadata, "incidentLikely", "likelyIncident")) {
826
- reservePercent += policy.incidentReservePercent;
827
- reasons.push("incident_reserve");
828
- signals.incidentLikely = true;
829
- }
830
- if (policy.enabled && reserveSignalFlag(metadata, "triggerBurstLikely", "expectedTriggerBurst")) {
831
- reservePercent += policy.triggerBurstReservePercent;
832
- reasons.push("trigger_burst_reserve");
833
- signals.triggerBurstLikely = true;
834
- }
835
- if (policy.enabled && reserveSignalFlag(metadata, "deploymentWindow", "deploymentWindowActive")) {
836
- reservePercent += policy.deploymentWindowReservePercent;
837
- reasons.push("deployment_window_reserve");
838
- signals.deploymentWindow = true;
839
- }
840
- if (policy.enabled && providerDegraded) {
841
- reservePercent += policy.providerDegradationReservePercent;
842
- reasons.push("provider_degradation_reserve");
843
- signals.providerDegraded = true;
844
- }
845
- if (policy.enabled && quotaPressure) {
846
- reservePercent += policy.quotaPressureReservePercent;
847
- reasons.push("quota_pressure_reserve");
848
- signals.quotaPressure = true;
849
- }
850
- const boundedPercent = Math.min(policy.maxReservePercent, Math.max(0, reservePercent));
851
- const budget = Math.max(0, finiteOrParsedNumber(input.dailyCreditBudget) ?? finiteOrParsedNumber(input.remainingCredits) ?? input.plan?.remaining.dailyCredits ?? 0);
852
- const reserveCredits = Math.ceil(budget * boundedPercent / 100);
853
- const remaining = Math.max(0, finiteOrParsedNumber(input.remainingCredits) ?? input.plan?.remaining.dailyCredits ?? budget);
854
- return {
855
- reservePercent: boundedPercent,
856
- reserveCredits,
857
- activelyAllocatableCredits: Math.max(0, remaining - reserveCredits),
858
- reasons,
859
- signals
860
- };
861
- }
862
- function normalizeHybridExecutionPlan(input) {
863
- const record = readRecord(input);
864
- const rawPhases = Array.isArray(record.phases) ? record.phases : [];
865
- const phases = rawPhases.map((phase, index) => {
866
- const entry = readRecord(phase);
867
- const kind = typeof entry.kind === "string" && entry.kind.trim() ? entry.kind.trim() : `phase_${index + 1}`;
868
- const executionProfileId = typeof entry.executionProfileId === "string" && entry.executionProfileId.trim() ? entry.executionProfileId.trim() : typeof entry.executionProfile === "string" && entry.executionProfile.trim() ? entry.executionProfile.trim() : DEFAULT_EXECUTION_PROFILE_ID;
869
- const mutationAllowed = entry.mutationAllowed === true || kind === "implementation" && entry.mutationAllowed !== false;
870
- return {
871
- id: typeof entry.id === "string" && entry.id.trim() ? entry.id.trim() : kind,
872
- kind,
873
- executionProfileId,
874
- taskSignature: typeof entry.taskSignature === "string" && entry.taskSignature.trim() ? entry.taskSignature.trim() : null,
875
- required: entry.required !== false,
876
- admissionRequired: entry.admissionRequired !== false,
877
- mutationAllowed,
878
- metadata: readRecord(entry.metadata)
879
- };
880
- });
881
- if (phases.length === 0) return null;
882
- return {
883
- schemaVersion: 1,
884
- planId: typeof record.planId === "string" && record.planId.trim() ? record.planId.trim() : "hybrid-execution-plan",
885
- phases,
886
- escalationPolicy: readRecord(record.escalationPolicy),
887
- metadata: readRecord(record.metadata)
888
- };
889
- }
890
- function normalizePlanningPolicy(input = {}) {
891
- const admissionPolicy = normalizeTaskAdmissionPolicy(input);
892
- return {
893
- maxDownstreamTasks: admissionPolicy.maxDownstreamTasks,
894
- maxPlanningDepth: admissionPolicy.maxPlanningDepth,
895
- maxAdmittedPlanTasksPerCycle: admissionPolicy.maxAdmittedPlanTasksPerCycle,
896
- planningTaskSignature: admissionPolicy.planningTaskSignature
897
- };
898
- }
899
- function stablePlanId(input) {
900
- const source = typeof input.sourceTaskId === "string" && input.sourceTaskId.trim() ? input.sourceTaskId.trim() : typeof input.parentTaskId === "string" && input.parentTaskId.trim() ? input.parentTaskId.trim() : "plan";
901
- return `${source}:proposal`;
902
- }
903
- function readRecord(value) {
904
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
905
- }
906
- function readPlanString(value) {
907
- return typeof value === "string" && value.trim() ? value.trim() : "";
908
- }
909
- function normalizePlannedTaskNode(value, index) {
910
- const input = readRecord(value);
911
- const payload = readRecord(input.payload);
912
- const type = readPlanString(input.type) || readPlanString(payload.type);
913
- if (!type) return null;
914
- const id = readPlanString(input.id) || `node-${index + 1}`;
915
- const p50 = finiteNumber(input.estimatedCreditsP50) ?? finiteNumber(payload.estimatedCreditsP50) ?? finiteNumber(input.estimatedCredits) ?? finiteNumber(payload.estimatedCredits) ?? null;
916
- const p90 = finiteNumber(input.estimatedCreditsP90) ?? finiteNumber(payload.estimatedCreditsP90) ?? p50;
917
- return {
918
- id,
919
- type,
920
- agentId: readPlanString(input.agentId) || readPlanString(payload.agentId) || null,
921
- title: readPlanString(input.title) || null,
922
- priority: finiteNumber(input.priority) ?? finiteNumber(payload.priority),
923
- taskSignature: readPlanString(input.taskSignature) || readPlanString(payload.taskSignature) || null,
924
- payload,
925
- estimatedCreditsP50: p50,
926
- estimatedCreditsP90: p90,
927
- risk: input.risk === "low" || input.risk === "medium" || input.risk === "high" ? input.risk : null,
928
- mutationScope: input.mutationScope === "none" || input.mutationScope === "repository_read" || input.mutationScope === "repository_write" || input.mutationScope === "production" ? input.mutationScope : null,
929
- confidence: input.confidence === "low" || input.confidence === "medium" || input.confidence === "high" ? input.confidence : null,
930
- expectedFanout: finiteNumber(input.expectedFanout) ?? finiteNumber(payload.expectedFanout),
931
- requiresApproval: typeof input.requiresApproval === "boolean" ? input.requiresApproval : null,
932
- requiresPlanning: typeof input.requiresPlanning === "boolean" ? input.requiresPlanning : null,
933
- dependsOn: Array.isArray(input.dependsOn) ? input.dependsOn.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : [],
934
- metadata: readRecord(input.metadata)
935
- };
936
- }
937
- function synthesizePlanEstimate(tasks) {
938
- const totalEstimatedCreditsP50 = tasks.reduce((total, task) => total + Math.max(0, Math.ceil(finiteNumber(task.estimatedCreditsP50) ?? finiteNumber(task.estimatedCreditsP90) ?? 1)), 0);
939
- const totalEstimatedCreditsP90 = tasks.reduce((total, task) => {
940
- const p50 = Math.max(1, Math.ceil(finiteNumber(task.estimatedCreditsP50) ?? 1));
941
- return total + Math.max(p50, Math.ceil(finiteNumber(task.estimatedCreditsP90) ?? p50));
942
- }, 0);
943
- return {
944
- totalEstimatedCreditsP50,
945
- totalEstimatedCreditsP90
946
- };
947
- }
948
- function rankPlannedTaskNodes(tasks) {
949
- const boundedness = (task) => {
950
- const fanout = Math.max(0, Math.floor(finiteNumber(task.expectedFanout) ?? 0));
951
- const riskPenalty2 = task.risk === "high" ? 3 : task.risk === "medium" ? 1 : 0;
952
- const mutationPenalty = task.mutationScope === "production" ? 4 : task.mutationScope === "repository_write" ? 2 : 0;
953
- return fanout + riskPenalty2 + mutationPenalty;
954
- };
955
- return [...tasks].sort((left, right) => {
956
- const priorityDelta = (finiteNumber(right.priority) ?? 0) - (finiteNumber(left.priority) ?? 0);
957
- if (priorityDelta !== 0) return priorityDelta;
958
- const boundedDelta = boundedness(left) - boundedness(right);
959
- if (boundedDelta !== 0) return boundedDelta;
960
- return String(left.id ?? left.type).localeCompare(String(right.id ?? right.type));
961
- });
962
- }
963
- function normalizeTaskPlanProposal(input, policyInput) {
964
- const policy = normalizePlanningPolicy(policyInput);
965
- const record = readRecord(input);
966
- const tasks = (Array.isArray(record.tasks) ? record.tasks : []).map((entry, index) => normalizePlannedTaskNode(entry, index)).filter((entry) => Boolean(entry));
967
- const estimate = synthesizePlanEstimate(tasks);
968
- const planningDepth = Math.max(0, Math.floor(finiteNumber(record.planningDepth) ?? 0));
969
- return {
970
- schemaVersion: 1,
971
- planId: readPlanString(record.planId) || stablePlanId(record),
972
- sourceTaskId: readPlanString(record.sourceTaskId) || null,
973
- parentTaskId: readPlanString(record.parentTaskId) || null,
974
- planningDepth,
975
- tasks,
976
- totalEstimatedCreditsP50: Math.max(0, Math.ceil(finiteNumber(record.totalEstimatedCreditsP50) ?? estimate.totalEstimatedCreditsP50)),
977
- totalEstimatedCreditsP90: Math.max(0, Math.ceil(finiteNumber(record.totalEstimatedCreditsP90) ?? estimate.totalEstimatedCreditsP90)),
978
- createdAt: readPlanString(record.createdAt) || null,
979
- metadata: readRecord(record.metadata)
980
- };
981
- }
982
- function validateTaskPlanProposal(input, policyInput) {
983
- const policy = normalizePlanningPolicy(policyInput);
984
- const reasons = [];
985
- if (input.planningDepth > policy.maxPlanningDepth) {
986
- reasons.push("planning_depth_exceeded");
987
- }
988
- if (input.tasks.length > policy.maxDownstreamTasks) {
989
- reasons.push("fanout_limit_exceeded");
990
- }
991
- const rejected = input.tasks.map((node) => {
992
- const nodeReasons = [];
993
- if (!node.type) nodeReasons.push("missing_type");
994
- if (Math.max(0, Math.floor(finiteNumber(node.expectedFanout) ?? 0)) > policy.maxDownstreamTasks) {
995
- nodeReasons.push("node_fanout_limit_exceeded");
996
- }
997
- return nodeReasons.length > 0 ? { node, reasons: nodeReasons } : null;
998
- }).filter((entry) => Boolean(entry));
999
- return {
1000
- ok: reasons.length === 0 && rejected.length === 0,
1001
- reasons,
1002
- rejected
1003
- };
1004
- }
1005
- function progressivelyAdmitPlanProposal(input) {
1006
- const policy = normalizePlanningPolicy(input.policy);
1007
- const proposal = normalizeTaskPlanProposal(input.proposal, policy);
1008
- const validation = validateTaskPlanProposal(proposal, policy);
1009
- const reasons = [...validation.reasons];
1010
- const admitted = [];
1011
- const deferred = [];
1012
- const rejected = [...validation.rejected];
1013
- if (!validation.ok) {
1014
- return {
1015
- proposal,
1016
- admitted,
1017
- deferred: proposal.tasks.filter((node) => !rejected.some((entry) => entry.node.id === node.id)),
1018
- rejected,
1019
- totalEstimatedCreditsP50: proposal.totalEstimatedCreditsP50,
1020
- totalEstimatedCreditsP90: proposal.totalEstimatedCreditsP90,
1021
- admittedCreditsP90: 0,
1022
- reasons
1023
- };
1024
- }
1025
- let availableCredits = Math.max(0, Math.floor(nonNegativeNumber(input.availableCredits, Number.POSITIVE_INFINITY)));
1026
- let remainingQueuedCredits = Math.max(0, Math.floor(nonNegativeNumber(input.remainingQueuedCredits, Number.POSITIVE_INFINITY)));
1027
- let remainingQueuedSlots = Math.max(0, Math.floor(nonNegativeNumber(input.remainingQueuedSlots, policy.maxAdmittedPlanTasksPerCycle)));
1028
- let admittedCreditsP90 = 0;
1029
- for (const task of rankPlannedTaskNodes(proposal.tasks)) {
1030
- if (admitted.length >= policy.maxAdmittedPlanTasksPerCycle || remainingQueuedSlots <= 0) {
1031
- deferred.push(task);
1032
- reasons.push("plan_cycle_limit_reached");
1033
- continue;
1034
- }
1035
- const p50 = Math.max(1, Math.ceil(finiteNumber(task.estimatedCreditsP50) ?? 1));
1036
- const p90 = Math.max(p50, Math.ceil(finiteNumber(task.estimatedCreditsP90) ?? p50));
1037
- if (p90 > availableCredits || p90 > remainingQueuedCredits) {
1038
- deferred.push(task);
1039
- reasons.push("insufficient_plan_budget");
1040
- continue;
1041
- }
1042
- admitted.push(task);
1043
- admittedCreditsP90 += p90;
1044
- availableCredits -= p90;
1045
- remainingQueuedCredits -= p90;
1046
- remainingQueuedSlots -= 1;
1047
- }
1048
- return {
1049
- proposal,
1050
- admitted,
1051
- deferred,
1052
- rejected,
1053
- totalEstimatedCreditsP50: proposal.totalEstimatedCreditsP50,
1054
- totalEstimatedCreditsP90: proposal.totalEstimatedCreditsP90,
1055
- admittedCreditsP90,
1056
- reasons: [...new Set(reasons)]
1057
- };
1058
- }
1059
- function computeWorkdayBudgetEnvelope(input) {
1060
- const dailyCreditBudget = Math.max(0, Math.floor(nonNegativeNumber(input.dailyCreditBudget, 0)));
1061
- const usedCredits = Math.max(0, Math.ceil(nonNegativeNumber(input.usedCredits, 0)));
1062
- const queuedCredits = Math.max(0, Math.ceil(nonNegativeNumber(input.queuedCredits, 0)));
1063
- const reservePercent = Math.min(100, Math.max(0, nonNegativeNumber(input.reserveBufferPercent, DEFAULT_TASK_ADMISSION_POLICY.reserveBufferPercent)));
1064
- const reserveBufferCredits = Math.ceil(dailyCreditBudget * reservePercent / 100);
1065
- const recoveryBudgetCredits = Math.ceil(nonNegativeNumber(input.recoveryBudgetCredits, DEFAULT_TASK_ADMISSION_POLICY.recoveryBudgetCredits));
1066
- const remainingCredits = Math.max(0, dailyCreditBudget - usedCredits - queuedCredits);
1067
- const activelyAllocatableCredits = Math.max(0, dailyCreditBudget - usedCredits - queuedCredits - reserveBufferCredits - recoveryBudgetCredits);
1068
- return {
1069
- dailyCreditBudget,
1070
- usedCredits,
1071
- queuedCredits,
1072
- reserveBufferCredits,
1073
- recoveryBudgetCredits,
1074
- activelyAllocatableCredits,
1075
- remainingCredits
1076
- };
1077
- }
1078
- function mutationRequiresRepositoryClaim(scope) {
1079
- return scope === "repository_write" || scope === "production";
1080
- }
1081
- function reservationDebit(reservation) {
1082
- if (reservation.state === "released" || reservation.state === "expired" || reservation.state === "cancelled") {
1083
- return 0;
1084
- }
1085
- if (reservation.state === "consumed" || reservation.state === "failed") {
1086
- return Math.max(0, reservation.consumedCredits);
1087
- }
1088
- return Math.max(reservation.reservedCredits, reservation.consumedCredits, 0);
1089
- }
1090
- function activeReservationDebit(reservation) {
1091
- if (reservation.state === "reserved" || reservation.state === "consuming") {
1092
- return Math.max(reservation.reservedCredits, reservation.consumedCredits, 0);
1093
- }
1094
- if (reservation.state === "consumed" || reservation.state === "failed") {
1095
- return Math.max(reservation.consumedCredits, 0);
1096
- }
1097
- return 0;
1098
- }
1099
- function metadataNumber(metadata, ...keys) {
1100
- for (const key of keys) {
1101
- const value = finiteOrParsedNumber(metadata?.[key]);
1102
- if (value !== null) return value;
1103
- }
1104
- return null;
1105
- }
1106
- function metadataBoolean(metadata, ...keys) {
1107
- for (const key of keys) {
1108
- const value = metadata?.[key];
1109
- if (value === true || value === "true" || value === 1 || value === "1") return true;
1110
- if (value === false || value === "false" || value === 0 || value === "0") return false;
1111
- }
1112
- return false;
1113
- }
1114
- function grantMatchesReservation(grant, reservation) {
1115
- if (grant.teamId !== reservation.teamId) return false;
1116
- if (grant.capacityProviderId !== reservation.capacityProviderId) return false;
1117
- if (grant.laneId && grant.laneId !== reservation.laneId) return false;
1118
- if (grant.projectId && grant.projectId !== reservation.projectId) return false;
1119
- return true;
1120
- }
1121
- function grantPortfolioAllocationPercent(grant) {
1122
- const metadata = readRecord(grant.metadata);
1123
- const value = finiteOrParsedNumber(grant.portfolioAllocationPercent) ?? metadataNumber(metadata, "portfolioAllocationPercent", "allocationPercent", "derivedAllocationPercent", "percentOfDerivedCapacity");
1124
- if (value === null) return null;
1125
- return Math.max(0, Math.min(100, value));
1126
- }
1127
- function grantReservePoolPercent(grant) {
1128
- const metadata = readRecord(grant.metadata);
1129
- const value = finiteOrParsedNumber(grant.reservePoolPercent) ?? metadataNumber(metadata, "reservePoolPercent", "minimumReservePercent", "reservePercent");
1130
- if (value === null) return 0;
1131
- return Math.max(0, Math.min(100, value));
1132
- }
1133
- function grantMaxDailyProjectCredits(grant) {
1134
- const metadata = readRecord(grant.metadata);
1135
- const value = finiteOrParsedNumber(grant.maxDailyProjectCredits) ?? metadataNumber(metadata, "maxDailyProjectCredits", "dailyProjectCreditCap");
1136
- if (value === null) return null;
1137
- return Math.max(0, value);
1138
- }
1139
- function grantEmergencyOverrideEnabled(grant) {
1140
- return grant.emergencyOverride === true || metadataBoolean(readRecord(grant.metadata), "emergencyOverride", "emergencyOverrideEnabled");
1141
- }
1142
- function routeEmergencyOverrideRequested(input) {
1143
- return metadataBoolean(readRecord(input.metadata), "emergencyOverride", "emergencyOverrideRequested");
1144
- }
1145
- function grantPortfolioCreditLimit(grant, derivedCapacity) {
1146
- const percent = grantPortfolioAllocationPercent(grant);
1147
- if (percent === null || !derivedCapacity || derivedCapacity.derivedAvailableCredits === null) return null;
1148
- return Math.max(0, derivedCapacity.derivedAvailableCredits * percent / 100);
1149
- }
1150
- function grantRemainingCredits(plan, grant, derivedCapacity, input) {
1151
- const staticLimit = grant.dailyCreditLimit ?? grant.monthlyCreditLimit;
1152
- const portfolioLimit = grantPortfolioCreditLimit(grant, derivedCapacity);
1153
- const maxDailyProjectCredits = grantMaxDailyProjectCredits(grant);
1154
- const limits = [staticLimit, portfolioLimit, maxDailyProjectCredits].filter((value) => value !== null && value !== void 0);
1155
- const limit = limits.length > 0 ? Math.min(...limits.map((value) => Number(value))) : null;
1156
- if (limit === null || limit === void 0) return null;
1157
- const reservePoolPercent = portfolioLimit !== null ? grantReservePoolPercent(grant) : 0;
1158
- const emergencyOverride = input ? routeEmergencyOverrideRequested(input) && grantEmergencyOverrideEnabled(grant) : false;
1159
- const reservePoolCredits = emergencyOverride ? 0 : limit * reservePoolPercent / 100;
1160
- const debits = plan.activeReservations.filter((reservation) => grantMatchesReservation(grant, reservation)).reduce((total, reservation) => total + reservationDebit(reservation), 0);
1161
- return Math.max(0, Number(limit) - reservePoolCredits - debits);
1162
- }
1163
- function providerIsEligible(provider, input) {
1164
- if (provider.status === "active") return true;
1165
- if (provider.status === "degraded" && input.allowDegradedProviders) return true;
1166
- return false;
1167
- }
1168
- function grantIsEligible(grant, input) {
1169
- if (grant.state !== "active") return false;
1170
- if (grant.teamId !== input.plan.teamId) return false;
1171
- if (grant.environment && grant.environment !== input.plan.environment) return false;
1172
- if (grant.projectId && grant.projectId !== input.plan.projectId) return false;
1173
- return true;
1174
- }
1175
- function lanePolicyReasons(lane, input) {
1176
- const reasons = [];
1177
- const laneStatus = metadataStatus(lane.metadata);
1178
- if (laneStatus && laneStatus !== "active") reasons.push(`lane_status:${laneStatus}`);
1179
- const policy = lane.routingPolicy ?? {};
1180
- const taskKinds = stringArray(policy.taskKinds);
1181
- const taskKind = input.taskKind ?? input.estimate.taskSignature;
1182
- if (taskKinds.length > 0 && !taskKinds.includes(taskKind)) reasons.push("task_kind_mismatch");
1183
- const requiredCapabilities = stringArray(policy.requiredCapabilities);
1184
- const missingCapabilities = (input.requiredCapabilities ?? []).filter((capability) => !requiredCapabilities.includes(capability));
1185
- if (requiredCapabilities.length > 0 && missingCapabilities.length > 0) {
1186
- reasons.push("capability_mismatch");
1187
- }
1188
- const allowedEnvironments = stringArray(policy.allowedEnvironments);
1189
- if (allowedEnvironments.length > 0 && !allowedEnvironments.includes(input.plan.environment)) {
1190
- reasons.push("environment_mismatch");
1191
- }
1192
- const maxCreditsPerTask = numberValue(policy.maxCreditsPerTask);
1193
- if (maxCreditsPerTask !== null && input.estimate.reservedCredits > maxCreditsPerTask) {
1194
- reasons.push("task_credit_limit_exceeded");
1195
- }
1196
- const approvalThreshold = numberValue(policy.requiresApprovalAboveCredits);
1197
- if (approvalThreshold !== null && input.estimate.reservedCredits > approvalThreshold) {
1198
- reasons.push("approval_required");
1199
- }
1200
- const repositoryMutationAllowed = booleanValue(policy.repositoryMutationAllowed);
1201
- if (input.repositoryMutation && repositoryMutationAllowed === false) {
1202
- reasons.push("repository_mutation_not_allowed");
1203
- }
1204
- const productionAllowed = booleanValue(policy.productionAllowed);
1205
- if (input.production && productionAllowed === false) {
1206
- reasons.push("production_not_allowed");
1207
- }
1208
- return reasons;
1209
- }
1210
- function reserveCreditsForEstimate(input) {
1211
- const executionProfile = input.executionProfile ? normalizeExecutionProfile(input.executionProfile) : input.executionProfileId ? normalizeExecutionProfile(input.executionProfileId) : null;
1212
- const selectedProfile = input.profile ?? selectTaskEstimateProfile({
1213
- profiles: input.profiles,
1214
- taskSignature: input.taskSignature ?? input.taskKind,
1215
- executionProfile,
1216
- executionProfileId: input.executionProfileId
1217
- });
1218
- const profileP50 = finiteNumber(selectedProfile?.creditsP50);
1219
- const profileP90 = finiteNumber(selectedProfile?.creditsP90);
1220
- const costMultiplier = positiveNumber(input.costMultiplier ?? executionProfile?.costMultiplier ?? 1, 1);
1221
- const p50 = Math.max(1, Math.ceil(
1222
- finiteNumber(input.estimatedCreditsP50) ?? profileP50 ?? finiteNumber(input.defaultCredits) ?? 1
1223
- ));
1224
- const p90 = Math.max(p50, Math.ceil(
1225
- finiteNumber(input.estimatedCreditsP90) ?? profileP90 ?? p50 * 2
1226
- ));
1227
- const profileConfidence = selectedProfile ? estimateConfidenceFromProfile(selectedProfile) : null;
1228
- const confidence = input.confidence ?? profileConfidence ?? "medium";
1229
- const baseReserved = confidence === "high" ? Math.max(p50, Math.ceil((p50 + p90) * 0.75)) : p90;
1230
- const reserved = Math.max(1, Math.ceil(baseReserved * costMultiplier));
1231
- return {
1232
- taskSignature: input.taskSignature ?? input.taskKind ?? "unknown",
1233
- confidence,
1234
- estimatedCreditsP50: p50,
1235
- estimatedCreditsP90: p90,
1236
- reservedCredits: reserved,
1237
- baseReservedCredits: baseReserved,
1238
- executionProfileId: executionProfile?.id ?? input.executionProfileId ?? selectedProfile?.executionProfileId ?? null,
1239
- costMultiplier
1240
- };
1241
- }
1242
- function estimateForClassification(input) {
1243
- const classification = input.classification ?? null;
1244
- return reserveCreditsForEstimate({
1245
- ...input,
1246
- taskSignature: input.taskSignature ?? classification?.taskSignature,
1247
- confidence: input.confidence ?? classification?.confidence
1248
- });
1249
- }
1250
- function decideTaskAdmission(input) {
1251
- const policy = normalizeTaskAdmissionPolicy(input.policy);
1252
- const budget = computeWorkdayBudgetEnvelope({
1253
- ...input.budget,
1254
- reserveBufferPercent: policy.reserveBufferPercent,
1255
- recoveryBudgetCredits: policy.recoveryBudgetCredits
1256
- });
1257
- const reasons = [];
1258
- const reservedCredits = Math.max(1, Math.ceil(input.estimate.reservedCredits));
1259
- const fanout = Math.max(0, Math.floor(input.classification.expectedFanout ?? 0));
1260
- const highRisk = input.classification.risk === "high" || input.classification.mutationScope === "production";
1261
- const requiresPlanning = input.classification.requiresPlanning || fanout > policy.maxDownstreamTasks || reservedCredits >= policy.planningThresholdCredits && (input.classification.confidence === "low" || fanout > 1 || highRisk);
1262
- const requiresApproval = input.classification.requiresApproval || highRisk || reservedCredits >= policy.approvalThresholdCredits;
1263
- let outcome = "admitted";
1264
- if (!input.classification.taskSignature || input.classification.taskSignature === "unknown") {
1265
- outcome = "rejected";
1266
- reasons.push("unknown_task_signature");
1267
- }
1268
- if (fanout > policy.maxDownstreamTasks) {
1269
- reasons.push("fanout_limit_exceeded");
1270
- }
1271
- if (requiresPlanning) {
1272
- outcome = "planning_required";
1273
- reasons.push("planning_required");
1274
- }
1275
- if (requiresApproval) {
1276
- outcome = "approval_required";
1277
- reasons.push("approval_required");
1278
- }
1279
- if (outcome === "admitted" && reservedCredits > budget.activelyAllocatableCredits) {
1280
- outcome = "budget_blocked";
1281
- reasons.push("insufficient_allocatable_budget");
1282
- }
1283
- return {
1284
- outcome,
1285
- taskSignature: input.classification.taskSignature,
1286
- estimatedCreditsP50: input.estimate.estimatedCreditsP50,
1287
- estimatedCreditsP90: input.estimate.estimatedCreditsP90,
1288
- reservedCredits,
1289
- baseReservedCredits: input.estimate.baseReservedCredits,
1290
- executionProfileId: input.estimate.executionProfileId ?? null,
1291
- costMultiplier: input.estimate.costMultiplier ?? null,
1292
- reasons: [...new Set(reasons)],
1293
- requiresApproval,
1294
- requiresPlanning,
1295
- budget,
1296
- policySnapshot: policy,
1297
- metadata: {
1298
- ...input.metadata ?? {},
1299
- source: input.source ?? null,
1300
- classification: input.classification
1301
- }
1302
- };
1303
- }
1304
- function shouldInterruptForCapacity(input) {
1305
- const reservedCredits = nonNegativeNumber(input.reservedCredits, 0);
1306
- const consumedCredits = nonNegativeNumber(input.consumedCredits, 0);
1307
- const threshold = Math.min(100, Math.max(1, nonNegativeNumber(input.reservationUsedPercentThreshold, 80)));
1308
- const usedPercent = reservedCredits > 0 ? consumedCredits / reservedCredits * 100 : 0;
1309
- const estimatedRemainingP50 = nonNegativeNumber(input.estimatedRemainingCreditsP50, 0);
1310
- const estimatedRemainingP90 = nonNegativeNumber(input.estimatedRemainingCreditsP90, estimatedRemainingP50);
1311
- const recoveryBudgetRemaining = input.recoveryBudgetRemainingCredits === void 0 || input.recoveryBudgetRemainingCredits === null ? null : nonNegativeNumber(input.recoveryBudgetRemainingCredits, 0);
1312
- const recoveryMinimum = nonNegativeNumber(input.recoveryBudgetMinimumCredits, 3);
1313
- const reasons = [];
1314
- if (input.providerAvailable === false) {
1315
- reasons.push("provider_unavailable");
1316
- }
1317
- if (reservedCredits > 0 && usedPercent >= threshold && estimatedRemainingP50 > Math.max(0, reservedCredits - consumedCredits)) {
1318
- reasons.push("reservation_exhaustion_risk");
1319
- }
1320
- if (recoveryBudgetRemaining !== null && recoveryBudgetRemaining < recoveryMinimum) {
1321
- reasons.push("recovery_budget_low");
1322
- }
1323
- return {
1324
- interrupt: reasons.length > 0,
1325
- reasons,
1326
- usedPercent,
1327
- estimatedRemainingP50,
1328
- estimatedRemainingP90,
1329
- remainingReservationCredits: Math.max(0, reservedCredits - consumedCredits)
1330
- };
1331
- }
1332
- function summarizeCapacityPlan(plan) {
1333
- const reservedCredits = plan.activeReservations.filter((reservation) => reservation.state === "reserved" || reservation.state === "consuming").reduce((total, reservation) => total + reservation.reservedCredits, 0);
1334
- const consumedCredits = plan.activeReservations.reduce((total, reservation) => total + reservation.consumedCredits, 0);
1335
- const grantedDailyCredits = plan.grants.filter((grant) => grant.state === "active").reduce((total, grant) => total + (grant.dailyCreditLimit ?? 0), 0);
1336
- return {
1337
- grantedDailyCredits,
1338
- reservedCredits,
1339
- consumedCredits,
1340
- remainingDailyCredits: grantedDailyCredits > 0 ? Math.max(0, grantedDailyCredits - reservedCredits - consumedCredits) : null,
1341
- providerCount: plan.providers.length,
1342
- laneCount: plan.lanes.length,
1343
- grantCount: plan.grants.length
1344
- };
1345
- }
1346
- function summarizeTeamCapacityPlan(plan) {
1347
- const dailyCredits = plan.grants.filter((grant) => grant.state === "active").reduce((total, grant) => total + (grant.dailyCreditLimit ?? 0), 0);
1348
- const monthlyCredits = plan.grants.filter((grant) => grant.state === "active").reduce((total, grant) => total + (grant.monthlyCreditLimit ?? 0), 0);
1349
- const dailyReservedCredits = plan.activeReservations.reduce((total, reservation) => total + activeReservationDebit(reservation), 0);
1350
- const dailyUsedCredits = plan.activeReservations.reduce((total, reservation) => total + Math.max(0, reservation.consumedCredits), 0);
1351
- return {
1352
- teamId: plan.teamId,
1353
- monthlyCredits: monthlyCredits > 0 ? monthlyCredits : null,
1354
- monthlyUsedCredits: dailyUsedCredits,
1355
- monthlyRemainingCredits: monthlyCredits > 0 ? Math.max(0, monthlyCredits - dailyUsedCredits) : null,
1356
- dailyCredits: dailyCredits > 0 ? dailyCredits : null,
1357
- dailyUsedCredits,
1358
- dailyReservedCredits,
1359
- dailyRemainingCredits: dailyCredits > 0 ? Math.max(0, dailyCredits - dailyReservedCredits - dailyUsedCredits) : null,
1360
- providerCount: plan.providers.length,
1361
- activeProviderCount: plan.providers.filter((provider) => provider.status === "active").length,
1362
- degradedProviderCount: plan.providers.filter((provider) => provider.status === "degraded").length,
1363
- grantCount: plan.grants.length,
1364
- blockedTaskCount: 0,
1365
- approvalRequiredCount: 0
1366
- };
1367
- }
1368
- function summarizeProjectCapacityPlan(plan, options = {}) {
1369
- const summary = summarizeTeamCapacityPlan(plan);
1370
- const reasons = [];
1371
- let readiness = "ready";
1372
- if (options.workPolicyEnabled === false) {
1373
- readiness = "paused_by_policy";
1374
- reasons.push("work_policy_disabled");
1375
- } else if (summary.activeProviderCount <= 0) {
1376
- readiness = "waiting_for_provider";
1377
- reasons.push("no_active_provider");
1378
- } else if (summary.dailyRemainingCredits !== null && summary.dailyRemainingCredits <= 0) {
1379
- readiness = "waiting_for_budget";
1380
- reasons.push("daily_budget_exhausted");
1381
- } else if ((options.approvalRequiredCount ?? 0) > 0) {
1382
- readiness = "needs_approval";
1383
- reasons.push("approval_required");
1384
- }
1385
- return {
1386
- ...summary,
1387
- projectId: plan.projectId,
1388
- environment: plan.environment,
1389
- readiness,
1390
- reasons,
1391
- blockedTaskCount: options.blockedTaskCount ?? summary.blockedTaskCount,
1392
- approvalRequiredCount: options.approvalRequiredCount ?? summary.approvalRequiredCount
1393
- };
1394
- }
1395
- function scoreCapacityLane(input) {
1396
- const reasons = [];
1397
- let agentFit = 0;
1398
- const profile = input.agentProfile;
1399
- if (profile) {
1400
- const preferred = profile.preferredLanes.find(
1401
- (preference) => preference.laneId === input.lane.id || preference.providerId === input.lane.capacityProviderId || preference.modelClass && preference.modelClass === input.lane.modelClass || preference.provider && preference.provider === input.lane.capacityProviderId
1402
- );
1403
- if (preferred) {
1404
- agentFit += Math.max(0, preferred.weight);
1405
- reasons.push("agent_preference");
1406
- }
1407
- if (profile.disallowedProviders?.includes(input.lane.capacityProviderId)) {
1408
- agentFit -= 1e3;
1409
- reasons.push("agent_disallowed_provider");
1410
- }
1411
- if (input.region && profile.disallowedRegions?.includes(input.region)) {
1412
- agentFit -= 1e3;
1413
- reasons.push("agent_disallowed_region");
1414
- }
1415
- }
1416
- if (input.modelClass && input.lane.modelClass === input.modelClass) {
1417
- agentFit += 20;
1418
- reasons.push("model_class_match");
1419
- }
1420
- const fairnessScore = Math.max(0, (input.grant?.priorityWeight ?? 1) * 10);
1421
- const scarcity = scarcityPenalty(input.lane.scarcityLevel);
1422
- const remaining = input.remainingCredits;
1423
- const costPenalty = remaining !== null && remaining !== void 0 && remaining <= 0 ? 500 : 0;
1424
- if (scarcity > 0) reasons.push(`scarcity:${input.lane.scarcityLevel}`);
1425
- if (costPenalty > 0) reasons.push("capacity_exhausted");
1426
- return {
1427
- laneId: input.lane.id,
1428
- capacityProviderId: input.lane.capacityProviderId,
1429
- score: agentFit + fairnessScore - scarcity - costPenalty,
1430
- agentFit,
1431
- scarcityPenalty: scarcity,
1432
- fairnessScore,
1433
- costPenalty,
1434
- reasons
1435
- };
1436
- }
1437
- function selectBestCapacityLane(candidates) {
1438
- const scored = candidates.map(scoreCapacityLane).sort((left, right) => right.score - left.score || left.laneId.localeCompare(right.laneId));
1439
- return {
1440
- selected: scored[0] ?? null,
1441
- scores: scored
1442
- };
1443
- }
1444
- function reservationHasCapacity(reservation) {
1445
- return reservation.state === "reserved" && reservation.reservedCredits > reservation.consumedCredits;
1446
- }
1447
- function createReservationReleaseEntry(input) {
1448
- const credits = Math.max(0, Number(input.credits ?? input.reservation.reservedCredits - input.reservation.consumedCredits));
1449
- return {
1450
- capacityProviderId: input.reservation.capacityProviderId,
1451
- laneId: input.reservation.laneId,
1452
- reservationId: input.reservation.id,
1453
- teamId: input.reservation.teamId,
1454
- projectId: input.reservation.projectId,
1455
- workDayId: input.reservation.workDayId,
1456
- taskId: input.reservation.taskId,
1457
- phase: "reservation_released",
1458
- credits: -credits,
1459
- source: input.source ?? "capacity_coordinator",
1460
- metadata: input.metadata ?? {}
1461
- };
1462
- }
1463
- function settleCapacityActuals(input) {
1464
- const consumedCredits = Math.max(0, Number(input.actualCredits ?? 0));
1465
- const releasedCredits = Math.max(0, input.reservation.reservedCredits - consumedCredits);
1466
- const overrunCredits = Math.max(0, consumedCredits - input.reservation.reservedCredits);
1467
- const base = {
1468
- capacityProviderId: input.reservation.capacityProviderId,
1469
- laneId: input.reservation.laneId,
1470
- reservationId: input.reservation.id,
1471
- teamId: input.teamId ?? input.reservation.teamId,
1472
- projectId: input.projectId ?? input.reservation.projectId,
1473
- workDayId: input.workDayId ?? input.reservation.workDayId,
1474
- taskId: input.taskId ?? input.reservation.taskId,
1475
- source: input.source ?? "capacity_coordinator",
1476
- metadata: input.metadata ?? {}
1477
- };
1478
- const consumeEntry = {
1479
- ...base,
1480
- phase: "task_completed_actual_settlement",
1481
- credits: consumedCredits,
1482
- providerUnits: input.actualProviderUnits ?? null,
1483
- usd: input.actualUsd ?? null
1484
- };
1485
- const releaseEntry = releasedCredits > 0 ? {
1486
- ...base,
1487
- phase: "reservation_released",
1488
- credits: -releasedCredits
1489
- } : null;
1490
- const overrunEntry = overrunCredits > 0 ? {
1491
- ...base,
1492
- phase: "overrun_hold",
1493
- credits: overrunCredits
1494
- } : null;
1495
- return {
1496
- reservationId: input.reservation.id,
1497
- state: overrunCredits > 0 ? "overran_pending_approval" : "consumed",
1498
- consumeEntry,
1499
- releaseEntry,
1500
- overrunEntry,
1501
- consumedCredits,
1502
- releasedCredits,
1503
- overrunCredits
1504
- };
1505
- }
1506
- function distinctProfiles(profiles) {
1507
- const seen = /* @__PURE__ */ new Set();
1508
- return profiles.filter((profile) => {
1509
- if (seen.has(profile.id)) return false;
1510
- seen.add(profile.id);
1511
- return true;
1512
- });
1513
- }
1514
- function executionProfilesForRoute(input) {
1515
- const explicitProfiles = Array.isArray(input.executionProfiles) && input.executionProfiles.length > 0 ? input.executionProfiles : null;
1516
- const preferred = stringArray(input.preferredExecutionProfiles);
1517
- const disallowed = new Set(stringArray(input.disallowedExecutionProfiles));
1518
- const rawProfiles = explicitProfiles ?? (preferred.length > 0 ? preferred : input.executionProfile ? [input.executionProfile] : input.estimate.executionProfileId ? [input.estimate.executionProfileId] : [DEFAULT_EXECUTION_PROFILE_ID]);
1519
- const profiles = distinctProfiles(rawProfiles.map((profile) => normalizeExecutionProfile(profile))).filter((profile) => !disallowed.has(profile.id));
1520
- return profiles.length > 0 ? profiles : [normalizeExecutionProfile(DEFAULT_EXECUTION_PROFILE_ID)];
1521
- }
1522
- function estimateForRouteProfile(input, profile) {
1523
- const selectedProfile = selectTaskEstimateProfile({
1524
- profiles: input.estimateProfiles ?? input.plan.estimateProfiles ?? null,
1525
- taskSignature: input.estimate.taskSignature,
1526
- executionProfile: profile,
1527
- executionProfileId: profile.id
1528
- });
1529
- return reserveCreditsForEstimate({
1530
- taskSignature: input.estimate.taskSignature,
1531
- taskKind: input.taskKind ?? input.estimate.taskSignature,
1532
- confidence: input.estimate.confidence ?? input.classification?.confidence ?? "medium",
1533
- estimatedCreditsP50: selectedProfile ? void 0 : input.estimate.estimatedCreditsP50,
1534
- estimatedCreditsP90: selectedProfile ? void 0 : input.estimate.estimatedCreditsP90,
1535
- defaultCredits: input.estimate.estimatedCreditsP50,
1536
- profiles: input.estimateProfiles ?? input.plan.estimateProfiles ?? null,
1537
- profile: selectedProfile,
1538
- executionProfile: profile,
1539
- executionProfileId: profile.id
1540
- });
1541
- }
1542
- function routeMinimumQuality(input) {
1543
- const explicit = finiteOrParsedNumber(input.minimumQualityWeight);
1544
- if (explicit !== null) return Math.max(0, explicit);
1545
- if (input.production || input.classification?.mutationScope === "production") return 1.5;
1546
- if (input.classification?.risk === "high" || input.classification?.requiresApproval) return 1.25;
1547
- if (input.classification?.confidence === "low") return 1.1;
1548
- return 0;
1549
- }
1550
- function routeRequiredContext(input) {
1551
- return Math.max(0, finiteOrParsedNumber(input.requiredContextTokens) ?? 0);
1552
- }
1553
- function reservationMetadata(reservation) {
1554
- return readRecord(reservation.metadata);
1555
- }
1556
- function attentionValueFromMetadata(metadata, ...keys) {
1557
- const estimate = readRecord(metadata.attentionEstimate);
1558
- for (const key of keys) {
1559
- const value = finiteOrParsedNumber(metadata[key]) ?? finiteOrParsedNumber(estimate[key]);
1560
- if (value !== null) return value;
1561
- }
1562
- return null;
1563
- }
1564
- function activeLaneReservations(plan, provider, lane) {
1565
- return plan.activeReservations.filter(
1566
- (reservation) => reservation.capacityProviderId === provider.id && (!lane || reservation.laneId === lane.id) && (reservation.state === "reserved" || reservation.state === "consuming")
1567
- );
1568
- }
1569
- function attentionLimitNumber(lane, provider, key) {
1570
- return finiteOrParsedNumber(lane.hardLimits?.[key]) ?? finiteOrParsedNumber(lane.routingPolicy?.[key]) ?? finiteOrParsedNumber(lane.metadata?.[key]) ?? finiteOrParsedNumber(readRecord(lane.metadata?.pressure)[key]) ?? finiteOrParsedNumber(provider.capacityModel?.[key]) ?? finiteOrParsedNumber(provider.metadata?.[key]) ?? finiteOrParsedNumber(readRecord(provider.metadata?.pressure)[key]);
1571
- }
1572
- function deriveAttentionWeight(classification, profile, contextTokens) {
1573
- let weight = 1;
1574
- const mutationScope = classification?.mutationScope ?? "repository_read";
1575
- if (mutationScope === "repository_read") weight = 1.5;
1576
- if (mutationScope === "repository_write") weight = 3;
1577
- if (mutationScope === "production") weight = 6;
1578
- if (classification?.risk === "medium") weight += 1;
1579
- if (classification?.risk === "high") weight += 3;
1580
- if (classification?.confidence === "low") weight += 1;
1581
- weight += Math.max(0, classification?.expectedFanout ?? 0) * 0.5;
1582
- if (profile.concurrencyClass === "human_attention" || profile.quotaBehavior === "attention_bound") weight += 5;
1583
- if (profile.concurrencyClass === "exclusive_project") weight += 3;
1584
- if (contextTokens >= 1e5) weight += 4;
1585
- else if (contextTokens >= 32e3) weight += 2;
1586
- return Math.max(0, weight);
1587
- }
1588
- function estimateAttentionForTask(input) {
1589
- const profile = normalizeExecutionProfile(input.executionProfile);
1590
- const policy = normalizeAttentionPolicy(input.attentionPolicy);
1591
- const requiredContextTokens = Math.max(0, finiteOrParsedNumber(input.requiredContextTokens) ?? 0);
1592
- const estimatedContextTokens = Math.max(requiredContextTokens, finiteOrParsedNumber(input.estimatedContextTokens) ?? requiredContextTokens);
1593
- const baseAttention = finiteOrParsedNumber(input.attentionWeight) ?? deriveAttentionWeight(input.classification, profile, estimatedContextTokens);
1594
- const coordinationWeight = finiteOrParsedNumber(input.coordinationWeight) ?? Math.max(0, input.classification?.expectedFanout ?? 0) * policy.coordinationOverheadFactor;
1595
- return {
1596
- attentionWeight: Math.max(0, Math.ceil(baseAttention * 100) / 100),
1597
- coordinationWeight: Math.max(0, Math.ceil(coordinationWeight * 100) / 100),
1598
- totalAttentionWeight: Math.max(0, Math.ceil((baseAttention + coordinationWeight) * 100) / 100),
1599
- estimatedContextTokens,
1600
- requiredContextTokens,
1601
- source: input.source ?? "capacity_attention_estimator",
1602
- metadata: input.metadata ?? {}
1603
- };
1604
- }
1605
- function attentionEstimateForRoute(input, profile) {
1606
- if (input.attentionEstimate) return input.attentionEstimate;
1607
- return estimateAttentionForTask({
1608
- classification: input.classification,
1609
- executionProfile: profile,
1610
- attentionPolicy: input.attentionPolicy,
1611
- attentionWeight: input.attentionWeight,
1612
- coordinationWeight: input.coordinationWeight,
1613
- estimatedContextTokens: input.estimatedContextTokens,
1614
- requiredContextTokens: input.requiredContextTokens,
1615
- source: input.source ?? "capacity_router"
1616
- });
1617
- }
1618
- function readPressureNumber(provider, lane, key) {
1619
- const laneValue = finiteOrParsedNumber(lane.metadata?.[key]);
1620
- if (laneValue !== null) return laneValue;
1621
- const providerValue = finiteOrParsedNumber(provider.metadata?.[key]);
1622
- if (providerValue !== null) return providerValue;
1623
- const lanePressure = readRecord(lane.metadata?.pressure);
1624
- const providerPressure = readRecord(provider.metadata?.pressure);
1625
- return finiteOrParsedNumber(lanePressure[key]) ?? finiteOrParsedNumber(providerPressure[key]);
1626
- }
1627
- function readPressureBoolean(provider, lane, key) {
1628
- const values = [
1629
- lane.metadata?.[key],
1630
- provider.metadata?.[key],
1631
- readRecord(lane.metadata?.pressure)[key],
1632
- readRecord(provider.metadata?.pressure)[key]
1633
- ];
1634
- return values.some((value) => value === true || value === "true");
1635
- }
1636
- function hardLimitNumber(lane, provider, ...keys) {
1637
- for (const key of keys) {
1638
- const value = finiteOrParsedNumber(lane.hardLimits?.[key]) ?? finiteOrParsedNumber(lane.routingPolicy?.[key]) ?? finiteOrParsedNumber(provider.capacityModel?.[key]) ?? finiteOrParsedNumber(provider.metadata?.[key]);
1639
- if (value !== null && value >= 0) return value;
1640
- }
1641
- return null;
1642
- }
1643
- function capacityRoutePressure(plan, provider, lane) {
1644
- const reservations = activeLaneReservations(plan, provider, lane);
1645
- const activeReservations = reservations.length;
1646
- const maxActiveReservations = hardLimitNumber(
1647
- lane,
1648
- provider,
1649
- "maxActiveReservations",
1650
- "maxConcurrentTasks",
1651
- "maxConcurrentWorkers"
1652
- ) ?? (provider.maxConcurrentWorkers > 0 ? provider.maxConcurrentWorkers : null);
1653
- const congestionRatio = maxActiveReservations && maxActiveReservations > 0 ? activeReservations / maxActiveReservations : 0;
1654
- const activeAttentionLoad = reservations.reduce((total, reservation) => {
1655
- const metadata = reservationMetadata(reservation);
1656
- return total + Math.max(0, attentionValueFromMetadata(metadata, "totalAttentionWeight", "attentionWeight") ?? 0);
1657
- }, 0);
1658
- const maxAttentionLoad = attentionLimitNumber(lane, provider, "maxAttentionLoad");
1659
- const activeContextTokens = reservations.reduce((total, reservation) => {
1660
- const metadata = reservationMetadata(reservation);
1661
- return total + Math.max(0, attentionValueFromMetadata(metadata, "estimatedContextTokens", "contextTokens", "requiredContextTokens") ?? 0);
1662
- }, 0);
1663
- const maxContextTokens = attentionLimitNumber(lane, provider, "maxContextTokens");
1664
- return {
1665
- activeReservations,
1666
- maxActiveReservations,
1667
- congestionRatio,
1668
- quotaRemainingPercent: readPressureNumber(provider, lane, "quotaRemainingPercent"),
1669
- sessionRemainingMinutes: readPressureNumber(provider, lane, "sessionRemainingMinutes"),
1670
- subscriptionSaturationPercent: readPressureNumber(provider, lane, "subscriptionSaturationPercent"),
1671
- providerUnavailable: readPressureBoolean(provider, lane, "providerUnavailable"),
1672
- activeAttentionLoad,
1673
- maxAttentionLoad,
1674
- attentionSaturationPercent: maxAttentionLoad && maxAttentionLoad > 0 ? activeAttentionLoad / maxAttentionLoad * 100 : null,
1675
- activeContextTokens,
1676
- maxContextTokens,
1677
- contextSaturationPercent: maxContextTokens && maxContextTokens > 0 ? activeContextTokens / maxContextTokens * 100 : null
1678
- };
1679
- }
1680
- function latencyPenalty(profile) {
1681
- if (profile.latencyClass === "high") return 12;
1682
- if (profile.latencyClass === "medium") return 5;
1683
- return 0;
1684
- }
1685
- function quotaPressurePenalty(pressure) {
1686
- let penalty = 0;
1687
- if (pressure.quotaRemainingPercent !== null) {
1688
- penalty += Math.max(0, 100 - pressure.quotaRemainingPercent) * 0.25;
1689
- }
1690
- if (pressure.subscriptionSaturationPercent !== null) {
1691
- penalty += Math.max(0, pressure.subscriptionSaturationPercent) * 0.35;
1692
- }
1693
- if (pressure.sessionRemainingMinutes !== null && pressure.sessionRemainingMinutes < 20) {
1694
- penalty += (20 - pressure.sessionRemainingMinutes) * 1.5;
1695
- }
1696
- return penalty;
1697
- }
1698
- function attentionPressurePenalty(pressure, estimate, policy) {
1699
- if (!pressure.maxAttentionLoad || pressure.maxAttentionLoad <= 0) return 0;
1700
- const allocatableLoad = Math.max(0, pressure.maxAttentionLoad * (1 - policy.reserveAttentionPercent / 100));
1701
- const projected = pressure.activeAttentionLoad + estimate.totalAttentionWeight;
1702
- const saturation = allocatableLoad > 0 ? projected / allocatableLoad : 1;
1703
- return Math.max(0, saturation) * 35;
1704
- }
1705
- function contextPressurePenalty(pressure, estimate, policy) {
1706
- const maxContextTokens = pressure.maxContextTokens ?? policy.maxContextTokens;
1707
- if (!maxContextTokens || maxContextTokens <= 0) return 0;
1708
- const projected = pressure.activeContextTokens + estimate.estimatedContextTokens;
1709
- const saturationPercent = projected / maxContextTokens * 100;
1710
- return Math.max(0, saturationPercent - 50) * 0.6;
1711
- }
1712
- function laneSupportsExecutionProfile(lane, profile) {
1713
- const allowedProfiles = stringArray(lane.routingPolicy?.executionProfiles);
1714
- if (allowedProfiles.length > 0 && !allowedProfiles.includes(profile.id)) return false;
1715
- const allowedModelClasses = stringArray(lane.routingPolicy?.modelClasses);
1716
- if (allowedModelClasses.length > 0 && profile.modelClass && !allowedModelClasses.includes(profile.modelClass)) return false;
1717
- return true;
1718
- }
1719
- function routeTrustScore(provider, lane, profile) {
1720
- const laneMetadata = readRecord(lane.metadata);
1721
- const providerMetadata = readRecord(provider.metadata);
1722
- const profileMetadata = readRecord(profile.metadata);
1723
- const trust = finiteOrParsedNumber(laneMetadata.trustScore) ?? finiteOrParsedNumber(providerMetadata.trustScore) ?? finiteOrParsedNumber(profileMetadata.trustScore) ?? 1;
1724
- const availability = finiteOrParsedNumber(laneMetadata.availabilityScore) ?? finiteOrParsedNumber(providerMetadata.availabilityScore) ?? 1;
1725
- return Math.max(0, Math.min(1, trust)) * Math.max(0, Math.min(1, availability));
1726
- }
1727
- function routeSuccessProbability(input) {
1728
- const laneMetadata = readRecord(input.lane.metadata);
1729
- const providerMetadata = readRecord(input.provider.metadata);
1730
- const profileMetadata = readRecord(input.profile.metadata);
1731
- const success = finiteOrParsedNumber(input.explicit) ?? finiteOrParsedNumber(laneMetadata.successProbability) ?? finiteOrParsedNumber(providerMetadata.successProbability) ?? finiteOrParsedNumber(profileMetadata.successProbability) ?? input.utilityEstimate.successProbability ?? 1;
1732
- return Math.max(0, Math.min(1, success));
1733
- }
1734
- function routePriceMultiplier(provider, lane, profile) {
1735
- const laneMetadata = readRecord(lane.metadata);
1736
- const providerMetadata = readRecord(provider.metadata);
1737
- const profileMetadata = readRecord(profile.metadata);
1738
- return Math.max(0.1, finiteOrParsedNumber(laneMetadata.priceMultiplier) ?? finiteOrParsedNumber(providerMetadata.priceMultiplier) ?? finiteOrParsedNumber(profileMetadata.priceMultiplier) ?? 1);
1739
- }
1740
- function capacityBudgetMode(provider) {
1741
- const mode = String(provider.creditBudgetMode ?? "derived").toLowerCase();
1742
- if (mode === "static" || mode === "hybrid" || mode === "derived") return mode;
1743
- return "derived";
1744
- }
1745
- function routeDerivedEntries(plan) {
1746
- const seen = /* @__PURE__ */ new Set();
1747
- const entries = [];
1748
- const add = (entry) => {
1749
- if (!entry) return;
1750
- const key = `${entry.executionProviderId}:${entry.nativeUnit}:${entry.scope ?? ""}`;
1751
- if (seen.has(key)) return;
1752
- seen.add(key);
1753
- entries.push(entry);
1754
- };
1755
- for (const entry of plan.derivedCapacity?.entries ?? []) add(entry);
1756
- for (const summary of plan.derivedCapacity?.providers ?? []) {
1757
- for (const entry of summary.entries ?? []) add(entry);
1758
- }
1759
- return entries;
1760
- }
1761
- function routeDerivedHints(provider, lane, profile) {
1762
- const providerMetadata = readRecord(provider.metadata);
1763
- const laneMetadata = readRecord(lane.metadata);
1764
- const profileMetadata = readRecord(profile.metadata);
1765
- return {
1766
- executionProviderId: stringValue(laneMetadata.executionProviderId) ?? stringValue(providerMetadata.executionProviderId) ?? stringValue(profileMetadata.executionProviderId),
1767
- executionProviderKind: stringValue(laneMetadata.executionProviderKind) ?? stringValue(laneMetadata.providerKind) ?? stringValue(providerMetadata.executionProviderKind) ?? stringValue(providerMetadata.providerKind) ?? stringValue(profileMetadata.executionProviderKind),
1768
- nativeUnit: stringValue(laneMetadata.nativeUnit) ?? stringValue(providerMetadata.nativeUnit) ?? stringValue(profileMetadata.nativeUnit)
1769
- };
1770
- }
1771
- function selectDerivedCapacityForRoute(plan, provider, lane, profile) {
1772
- const hints = routeDerivedHints(provider, lane, profile);
1773
- const entries = routeDerivedEntries(plan).filter((entry) => entry.capacityProviderId === provider.id || entry.capacityProviderId === null).filter((entry) => !hints.executionProviderId || entry.executionProviderId === hints.executionProviderId).filter((entry) => !hints.executionProviderKind || entry.executionProviderKind === hints.executionProviderKind).filter((entry) => !hints.nativeUnit || entry.nativeUnit === hints.nativeUnit);
1774
- return entries.sort((left, right) => {
1775
- const leftExact = (hints.executionProviderId && left.executionProviderId === hints.executionProviderId ? 20 : 0) + (hints.executionProviderKind && left.executionProviderKind === hints.executionProviderKind ? 10 : 0) + (hints.nativeUnit && left.nativeUnit === hints.nativeUnit ? 5 : 0);
1776
- const rightExact = (hints.executionProviderId && right.executionProviderId === hints.executionProviderId ? 20 : 0) + (hints.executionProviderKind && right.executionProviderKind === hints.executionProviderKind ? 10 : 0) + (hints.nativeUnit && right.nativeUnit === hints.nativeUnit ? 5 : 0);
1777
- return rightExact - leftExact || derivedConfidenceRank(right.confidence) - derivedConfidenceRank(left.confidence) || Number(left.derivedAvailableCredits ?? Number.POSITIVE_INFINITY) - Number(right.derivedAvailableCredits ?? Number.POSITIVE_INFINITY) || Number(left.availableNativeAmount ?? Number.POSITIVE_INFINITY) - Number(right.availableNativeAmount ?? Number.POSITIVE_INFINITY) || `${left.executionProviderId}:${left.nativeUnit}`.localeCompare(`${right.executionProviderId}:${right.nativeUnit}`);
1778
- })[0] ?? null;
1779
- }
1780
- function roundUpNativeAmount(value) {
1781
- if (!Number.isFinite(value) || value <= 0) return 0;
1782
- return Math.ceil(value * 1e3) / 1e3;
1783
- }
1784
- function nativePressureForRoute(entry, estimate) {
1785
- if (!entry) return null;
1786
- const reservedNativeAmount = entry.nativeUnitsPerCredit && entry.nativeUnitsPerCredit > 0 ? roundUpNativeAmount(estimate.reservedCredits * entry.nativeUnitsPerCredit) : null;
1787
- const pressureRatio = reservedNativeAmount !== null && entry.availableNativeAmount > 0 ? reservedNativeAmount / entry.availableNativeAmount : entry.availableNativeAmount <= 0 ? 1 : null;
1788
- return {
1789
- executionProviderId: entry.executionProviderId,
1790
- nativeUnit: entry.nativeUnit,
1791
- availableNativeAmount: entry.availableNativeAmount,
1792
- activeReservedNativeAmount: entry.activeReservedNativeAmount,
1793
- reserveBufferNativeAmount: entry.reserveBufferNativeAmount,
1794
- reservedNativeAmount,
1795
- pressureRatio,
1796
- confidence: entry.confidence,
1797
- reasons: entry.reasons
1798
- };
1799
- }
1800
- function derivedRouteBudget(input) {
1801
- const reasons = [];
1802
- const derivedCredits = input.derivedCapacity?.derivedAvailableCredits ?? null;
1803
- const confidenceRank = derivedConfidenceRank(input.derivedCapacity?.confidence);
1804
- const hasUsableDerived = Boolean(input.derivedCapacity && derivedCredits !== null && confidenceRank >= 2);
1805
- const portfolioPercent = grantPortfolioAllocationPercent(input.grant);
1806
- let remainingCredits = input.staticRemainingCredits;
1807
- let appliesDerived = false;
1808
- if (input.mode === "derived") {
1809
- appliesDerived = true;
1810
- if (!input.derivedCapacity) {
1811
- reasons.push("missing_derived_capacity", "insufficient_budget");
1812
- return { remainingCredits: null, appliesDerived, hasUsableDerived: false, reasons };
1813
- }
1814
- if (derivedCredits === null) {
1815
- reasons.push("missing_conversion_profile", "insufficient_budget");
1816
- return { remainingCredits: null, appliesDerived, hasUsableDerived: false, reasons };
1817
- }
1818
- if (confidenceRank < 2) {
1819
- reasons.push("derived_capacity_learning", "insufficient_budget");
1820
- return { remainingCredits: derivedCredits, appliesDerived, hasUsableDerived: false, reasons };
1821
- }
1822
- remainingCredits = input.staticRemainingCredits === null ? derivedCredits : Math.min(input.staticRemainingCredits, derivedCredits);
1823
- reasons.push("derived_capacity_available");
1824
- if (portfolioPercent !== null) reasons.push("portfolio_allocation_applied");
1825
- } else if (input.mode === "hybrid") {
1826
- if (hasUsableDerived) {
1827
- appliesDerived = true;
1828
- remainingCredits = input.staticRemainingCredits === null ? derivedCredits : Math.min(input.staticRemainingCredits, derivedCredits);
1829
- reasons.push("hybrid_derived_capacity_applied");
1830
- if (portfolioPercent !== null) reasons.push("portfolio_allocation_applied");
1831
- if (input.staticRemainingCredits !== null && input.staticRemainingCredits <= derivedCredits) {
1832
- reasons.push("hybrid_static_cap_applied");
1833
- }
1834
- } else if (input.derivedCapacity && derivedCredits !== null && confidenceRank < 2) {
1835
- reasons.push("derived_capacity_learning");
1836
- } else if (input.derivedCapacity && derivedCredits === null) {
1837
- reasons.push("missing_conversion_profile");
1838
- }
1839
- }
1840
- if (appliesDerived && hasUsableDerived && derivedCredits !== null && derivedCredits < input.estimate.reservedCredits) {
1841
- reasons.push("derived_capacity_exhausted");
1842
- if (input.grant.overflowPolicy === "approval_required") {
1843
- reasons.push("approval_required");
1844
- } else if (input.grant.overflowPolicy === "fallback_lane") {
1845
- reasons.push("fallback_lane_exhausted");
1846
- } else if (input.grant.overflowPolicy === "deny" || input.grant.overflowPolicy === "hard_grant" || input.mode === "derived") {
1847
- reasons.push("insufficient_budget");
1848
- } else {
1849
- reasons.push("soft_budget_pressure", "derived_capacity_pressure");
1850
- }
1851
- }
1852
- return { remainingCredits, appliesDerived, hasUsableDerived, reasons };
1853
- }
1854
- function routeScore(input) {
1855
- const reasons = [...input.baseScore.reasons];
1856
- const qualityFit = input.minimumQualityWeight > 0 ? input.profile.qualityWeight / input.minimumQualityWeight : input.profile.qualityWeight;
1857
- const qualityBonus = Math.min(50, Math.max(0, input.profile.qualityWeight * 20));
1858
- const costPenalty = Math.max(0, input.estimate.reservedCredits);
1859
- const latency = latencyPenalty(input.profile);
1860
- const congestion = input.pressure.congestionRatio * 45;
1861
- const quota = quotaPressurePenalty(input.pressure);
1862
- const attention = attentionPressurePenalty(input.pressure, input.attentionEstimate, input.attentionPolicy);
1863
- const context = contextPressurePenalty(input.pressure, input.attentionEstimate, input.attentionPolicy);
1864
- const priceMultiplier = routePriceMultiplier(input.provider, input.lane, input.profile);
1865
- const utilityBonus = input.utilityEstimate.utilityScore > 0 ? Math.min(100, input.utilityEstimate.utilityPerCredit * 18 * Math.max(0.1, input.trustScore) * Math.max(0.1, input.successProbability)) : 0;
1866
- const cooperativeBonus = input.cooperativeRouting ? input.trustScore * 20 + input.successProbability * 15 : 0;
1867
- const predictedReserveImpact = input.reservePrediction?.reserveCredits ?? 0;
1868
- const laneModelFit = input.profile.modelClass && input.lane.modelClass === input.profile.modelClass ? 15 : 0;
1869
- const riskBonus = input.minimumQualityWeight >= 1.25 && input.profile.qualityWeight >= input.minimumQualityWeight ? 10 : 0;
1870
- const nativePressurePenalty = input.nativePressure?.pressureRatio !== null && input.nativePressure?.pressureRatio !== void 0 ? Math.max(0, input.nativePressure.pressureRatio) * 35 : 0;
1871
- const score = input.baseScore.score + qualityBonus + laneModelFit + riskBonus + utilityBonus + cooperativeBonus - costPenalty - latency - congestion - quota - attention - context - nativePressurePenalty - Math.max(0, priceMultiplier - 1) * 8 - (input.reservePrediction && input.reservePrediction.reservePercent > 0 ? Math.min(20, predictedReserveImpact * 0.25) : 0);
1872
- if (laneModelFit > 0) reasons.push("execution_profile_model_class_match");
1873
- if (congestion > 0) reasons.push("lane_congestion_pressure");
1874
- if (quota > 0) reasons.push("quota_pressure");
1875
- if (attention > 0) reasons.push("attention_pressure");
1876
- if (context > 0) reasons.push("context_pressure");
1877
- if (nativePressurePenalty > 0) reasons.push("native_capacity_pressure");
1878
- if (utilityBonus > 0) reasons.push("utility_scored");
1879
- if (cooperativeBonus > 0) reasons.push("cooperative_route_scored");
1880
- if (predictedReserveImpact > 0) reasons.push("predictive_reserve_applied");
1881
- return {
1882
- ...input.baseScore,
1883
- score,
1884
- qualityFit,
1885
- latencyPenalty: latency,
1886
- quotaPressure: quota,
1887
- congestionPenalty: congestion,
1888
- attentionPenalty: attention,
1889
- contextPenalty: context,
1890
- nativePressurePenalty,
1891
- utilityScore: input.utilityEstimate.utilityScore,
1892
- utilityPerCredit: input.utilityEstimate.utilityPerCredit,
1893
- predictedReserveImpact,
1894
- trustScore: input.trustScore,
1895
- successProbability: input.successProbability,
1896
- costPenalty,
1897
- executionProfileId: input.profile.id,
1898
- reservedCredits: input.estimate.reservedCredits,
1899
- attentionEstimate: input.attentionEstimate,
1900
- reasons: [...new Set(reasons)]
1901
- };
1902
- }
1903
- function routeCandidateKey(candidate) {
1904
- return `${candidate.providerId}:${candidate.laneId}:${candidate.grantId}:${candidate.executionProfileId ?? DEFAULT_EXECUTION_PROFILE_ID}`;
1905
- }
1906
- function routeAndReserveCapacity(input) {
1907
- const providers = input.plan.providers.filter((provider2) => providerIsEligible(provider2, input));
1908
- const grants = input.plan.grants.filter((grant2) => grantIsEligible(grant2, input));
1909
- const candidates = [];
1910
- const executionProfiles = executionProfilesForRoute(input);
1911
- const minimumQualityWeight = routeMinimumQuality(input);
1912
- const requiredContextTokens = routeRequiredContext(input);
1913
- const attentionPolicy = normalizeAttentionPolicy(input.attentionPolicy);
1914
- const utilityPolicy = normalizeUtilityPolicy(input.utilityPolicy);
1915
- const predictiveReservePolicy = normalizePredictiveReservePolicy(input.predictiveReservePolicy);
1916
- const hybridExecutionPlan = normalizeHybridExecutionPlan(input.hybridExecutionPlan ?? readRecord(input.metadata).hybridExecutionPlan);
1917
- const preferredProfiles = new Set(stringArray(input.preferredExecutionProfiles));
1918
- const disallowedProfiles = new Set(stringArray(input.disallowedExecutionProfiles));
1919
- const cooperativeRouting = input.cooperativeRouting === true || readRecord(input.metadata).cooperativeRouting === true;
1920
- const trustRequirement = finiteOrParsedNumber(input.trustRequirement);
1921
- for (const grant2 of grants) {
1922
- const provider2 = providers.find((candidate) => candidate.id === grant2.capacityProviderId);
1923
- if (!provider2) continue;
1924
- const lanes = input.plan.lanes.filter(
1925
- (lane2) => lane2.capacityProviderId === provider2.id && (!grant2.laneId || grant2.laneId === lane2.id)
1926
- );
1927
- for (const lane2 of lanes) {
1928
- const pressure = capacityRoutePressure(input.plan, provider2, lane2);
1929
- for (const profile of executionProfiles) {
1930
- const estimate = estimateForRouteProfile(input, profile);
1931
- const derivedCapacityMode = capacityBudgetMode(provider2);
1932
- const derivedCapacity = derivedCapacityMode === "static" ? null : selectDerivedCapacityForRoute(input.plan, provider2, lane2, profile);
1933
- const staticRemainingCredits = grantRemainingCredits(input.plan, grant2, derivedCapacity, input);
1934
- const routeBudget = derivedRouteBudget({
1935
- mode: derivedCapacityMode,
1936
- staticRemainingCredits,
1937
- derivedCapacity,
1938
- estimate,
1939
- grant: grant2
1940
- });
1941
- const remainingCredits = routeBudget.remainingCredits;
1942
- const nativePressure = nativePressureForRoute(derivedCapacity, estimate);
1943
- const attentionEstimate = attentionEstimateForRoute(input, profile);
1944
- const utilityEstimate = input.utilityEstimate ?? estimateUtilityForTask({
1945
- classification: input.classification,
1946
- executionProfile: profile,
1947
- estimate,
1948
- utilityPolicy,
1949
- utilityValue: input.utilityValue,
1950
- maintenanceValue: input.maintenanceValue,
1951
- priority: finiteOrParsedNumber(readRecord(input.metadata).priority),
1952
- deadlineAt: input.deadlineAt ?? (typeof readRecord(input.metadata).deadlineAt === "string" ? readRecord(input.metadata).deadlineAt : null),
1953
- successProbability: input.successProbability,
1954
- metadata: input.metadata,
1955
- source: input.source ?? "capacity_router"
1956
- });
1957
- const reservePrediction = predictReserveForCapacityPlan({
1958
- plan: input.plan,
1959
- policy: predictiveReservePolicy,
1960
- remainingCredits,
1961
- metadata: input.metadata
1962
- });
1963
- const trustScore = routeTrustScore(provider2, lane2, profile);
1964
- const successProbability = routeSuccessProbability({
1965
- provider: provider2,
1966
- lane: lane2,
1967
- profile,
1968
- explicit: input.successProbability,
1969
- utilityEstimate
1970
- });
1971
- const estimateInput = { ...input, estimate };
1972
- const reasons = [...routeBudget.reasons, ...lanePolicyReasons(lane2, estimateInput)];
1973
- let spilloverReason = null;
1974
- if (trustRequirement !== null && trustScore < trustRequirement) reasons.push("trust_below_requirement");
1975
- if (utilityPolicy.minimumUtilityScore !== null && utilityEstimate.utilityScore < utilityPolicy.minimumUtilityScore) reasons.push("utility_below_minimum");
1976
- if (utilityPolicy.minimumUtilityPerCredit !== null && utilityEstimate.utilityPerCredit < utilityPolicy.minimumUtilityPerCredit) reasons.push("utility_per_credit_below_minimum");
1977
- if (predictiveReservePolicy.enabled && reservePrediction.reserveCredits > 0 && reservePrediction.activelyAllocatableCredits < estimate.reservedCredits && utilityEstimate.utilityScore < 50) {
1978
- reasons.push("predictive_reserve_blocked");
1979
- }
1980
- const routeMaxAttentionLoad = attentionPolicy.maxAttentionLoad ?? pressure.maxAttentionLoad;
1981
- if (routeMaxAttentionLoad !== null && routeMaxAttentionLoad > 0) {
1982
- const allocatableAttention = Math.max(0, routeMaxAttentionLoad * (1 - attentionPolicy.reserveAttentionPercent / 100));
1983
- const projectedAttention = pressure.activeAttentionLoad + attentionEstimate.totalAttentionWeight;
1984
- if (projectedAttention > allocatableAttention) reasons.push("attention_load_exceeded");
1985
- const availableAttention = Math.max(0, allocatableAttention - pressure.activeAttentionLoad);
1986
- const minimumAttentionAvailable = finiteOrParsedNumber(input.minimumAttentionAvailable);
1987
- if (minimumAttentionAvailable !== null && availableAttention < minimumAttentionAvailable) reasons.push("minimum_attention_unavailable");
1988
- }
1989
- const routeMaxContextTokens = attentionPolicy.maxContextTokens ?? pressure.maxContextTokens;
1990
- if (routeMaxContextTokens !== null && routeMaxContextTokens > 0) {
1991
- const projectedContextTokens = pressure.activeContextTokens + attentionEstimate.estimatedContextTokens;
1992
- const projectedSaturation = projectedContextTokens / routeMaxContextTokens * 100;
1993
- if (projectedContextTokens > routeMaxContextTokens || projectedSaturation > attentionPolicy.maxContextSaturationPercent) {
1994
- reasons.push("context_saturation_exceeded");
1995
- }
1996
- }
1997
- if (disallowedProfiles.has(profile.id)) reasons.push("execution_profile_disallowed");
1998
- if (preferredProfiles.size > 0 && !preferredProfiles.has(profile.id)) reasons.push("execution_profile_not_preferred");
1999
- if (!laneSupportsExecutionProfile(lane2, profile)) reasons.push("execution_profile_not_supported");
2000
- if (minimumQualityWeight > 0 && profile.qualityWeight < minimumQualityWeight) reasons.push("quality_below_minimum");
2001
- if (requiredContextTokens > 0 && profile.contextWindowTokens !== null && profile.contextWindowTokens !== void 0 && profile.contextWindowTokens < requiredContextTokens) {
2002
- reasons.push("context_window_too_small");
2003
- }
2004
- if (pressure.providerUnavailable) reasons.push("provider_unavailable");
2005
- if (pressure.maxActiveReservations !== null && pressure.congestionRatio >= 1) reasons.push("lane_congested");
2006
- if (pressure.quotaRemainingPercent !== null && pressure.quotaRemainingPercent <= 0) reasons.push("quota_exhausted");
2007
- if (pressure.sessionRemainingMinutes !== null && pressure.sessionRemainingMinutes <= 0) reasons.push("session_exhausted");
2008
- if (remainingCredits !== null && remainingCredits < estimate.reservedCredits) {
2009
- if (grantPortfolioAllocationPercent(grant2) !== null) reasons.push("portfolio_allocation_exhausted");
2010
- if (grant2.overflowPolicy === "approval_required") {
2011
- reasons.push("approval_required");
2012
- } else if (grant2.overflowPolicy === "fallback_lane") {
2013
- spilloverReason = "fallback_lane";
2014
- reasons.push("fallback_lane_exhausted");
2015
- } else if (grant2.overflowPolicy === "deny" || grant2.overflowPolicy === "hard_grant") {
2016
- reasons.push("insufficient_budget");
2017
- } else {
2018
- reasons.push("soft_budget_pressure");
2019
- }
2020
- }
2021
- const baseScore = scoreCapacityLane({
2022
- lane: lane2,
2023
- grant: grant2,
2024
- remainingCredits,
2025
- taskKind: input.taskKind ?? estimate.taskSignature,
2026
- requiredCapabilities: input.requiredCapabilities,
2027
- modelClass: input.modelClass ?? profile.modelClass ?? null
2028
- });
2029
- const score = routeScore({
2030
- provider: provider2,
2031
- lane: lane2,
2032
- grant: grant2,
2033
- estimate,
2034
- profile,
2035
- remainingCredits,
2036
- pressure,
2037
- minimumQualityWeight,
2038
- attentionEstimate,
2039
- attentionPolicy,
2040
- utilityEstimate,
2041
- reservePrediction,
2042
- trustScore,
2043
- successProbability,
2044
- cooperativeRouting,
2045
- baseScore,
2046
- nativePressure
2047
- });
2048
- candidates.push({
2049
- providerId: provider2.id,
2050
- laneId: lane2.id,
2051
- grantId: grant2.id,
2052
- executionProviderId: routeBudget.appliesDerived && routeBudget.hasUsableDerived ? derivedCapacity?.executionProviderId ?? null : null,
2053
- executionProfileId: profile.id,
2054
- nativeUnit: routeBudget.appliesDerived && routeBudget.hasUsableDerived ? derivedCapacity?.nativeUnit ?? null : null,
2055
- remainingCredits,
2056
- staticRemainingCredits,
2057
- derivedAvailableCredits: derivedCapacity?.derivedAvailableCredits ?? null,
2058
- reservedNativeAmount: routeBudget.appliesDerived && routeBudget.hasUsableDerived ? nativePressure?.reservedNativeAmount ?? null : null,
2059
- derivedCapacity: derivedCapacity ?? null,
2060
- derivedCapacityMode,
2061
- score,
2062
- eligible: reasons.filter(
2063
- (reason) => reason !== "soft_budget_pressure" && reason !== "execution_profile_not_preferred" && reason !== "derived_capacity_available" && reason !== "hybrid_derived_capacity_applied" && reason !== "hybrid_static_cap_applied" && reason !== "portfolio_allocation_applied" && reason !== "derived_capacity_learning" && reason !== "missing_conversion_profile"
2064
- ).length === 0,
2065
- reasons: [.../* @__PURE__ */ new Set([...reasons, ...score.reasons])],
2066
- estimate,
2067
- pressure,
2068
- nativePressure,
2069
- qualityFit: score.qualityFit,
2070
- attentionEstimate,
2071
- utilityEstimate,
2072
- reservePrediction,
2073
- trustScore,
2074
- successProbability,
2075
- spilloverReason
2076
- });
2077
- }
2078
- }
2079
- }
2080
- if (input.plan.providers.length === 0 || providers.length === 0) {
2081
- return {
2082
- ok: false,
2083
- code: "no_capacity_provider",
2084
- reason: "No active helper capacity provider is available.",
2085
- estimate: input.estimate,
2086
- candidates
2087
- };
2088
- }
2089
- if (grants.length === 0) {
2090
- return {
2091
- ok: false,
2092
- code: "no_capacity_grant",
2093
- reason: "No active capacity grant is available for this team, project, and environment.",
2094
- estimate: input.estimate,
2095
- candidates
2096
- };
2097
- }
2098
- const eligible = candidates.filter((candidate) => candidate.eligible).sort(
2099
- (left, right) => right.score.score - left.score.score || (left.estimate?.reservedCredits ?? Number.MAX_SAFE_INTEGER) - (right.estimate?.reservedCredits ?? Number.MAX_SAFE_INTEGER) || routeCandidateKey(left).localeCompare(routeCandidateKey(right))
2100
- );
2101
- const selected = eligible[0] ?? null;
2102
- if (!selected) {
2103
- const hasApprovalBlock = candidates.some((candidate) => candidate.reasons.includes("approval_required"));
2104
- const hasBudgetBlock = candidates.some((candidate) => candidate.reasons.includes("insufficient_budget"));
2105
- return {
2106
- ok: false,
2107
- code: hasApprovalBlock ? "approval_required" : hasBudgetBlock ? "insufficient_budget" : "no_eligible_lane",
2108
- reason: hasApprovalBlock ? "The requested helper task needs approval before capacity can be reserved." : hasBudgetBlock ? "The requested helper task is above the remaining approved budget." : "No provider lane matches the task policy and capability requirements.",
2109
- estimate: input.estimate,
2110
- candidates
2111
- };
2112
- }
2113
- const provider = providers.find((candidate) => candidate.id === selected.providerId);
2114
- const lane = input.plan.lanes.find((candidate) => candidate.id === selected.laneId);
2115
- const grant = grants.find((candidate) => candidate.id === selected.grantId);
2116
- const selectedEstimate = selected.estimate ?? input.estimate;
2117
- if (!provider || !lane || !grant) {
2118
- return {
2119
- ok: false,
2120
- code: "no_eligible_lane",
2121
- reason: "The selected capacity lane could not be resolved.",
2122
- estimate: input.estimate,
2123
- candidates
2124
- };
2125
- }
2126
- const candidatePayload = candidates.map((candidate) => ({
2127
- providerId: candidate.providerId,
2128
- laneId: candidate.laneId,
2129
- grantId: candidate.grantId,
2130
- executionProviderId: candidate.executionProviderId ?? null,
2131
- executionProfileId: candidate.executionProfileId ?? null,
2132
- nativeUnit: candidate.nativeUnit ?? null,
2133
- remainingCredits: candidate.remainingCredits,
2134
- staticRemainingCredits: candidate.staticRemainingCredits ?? null,
2135
- derivedAvailableCredits: candidate.derivedAvailableCredits ?? null,
2136
- reservedNativeAmount: candidate.reservedNativeAmount ?? null,
2137
- derivedCapacityMode: candidate.derivedCapacityMode ?? "derived",
2138
- eligible: candidate.eligible,
2139
- reasons: candidate.reasons,
2140
- score: candidate.score.score,
2141
- reservedCredits: candidate.estimate?.reservedCredits ?? null,
2142
- qualityFit: candidate.qualityFit ?? null,
2143
- attentionEstimate: candidate.attentionEstimate ?? null,
2144
- utilityEstimate: candidate.utilityEstimate ?? null,
2145
- reservePrediction: candidate.reservePrediction ?? null,
2146
- trustScore: candidate.trustScore ?? null,
2147
- successProbability: candidate.successProbability ?? null,
2148
- pressure: candidate.pressure ?? null,
2149
- nativePressure: candidate.nativePressure ?? null,
2150
- derivedCapacity: candidate.derivedCapacity ?? null,
2151
- spilloverReason: candidate.spilloverReason ?? null
2152
- }));
2153
- const scorePayload = Object.fromEntries(candidates.map((candidate) => [routeCandidateKey(candidate), candidate.score]));
2154
- const reservation = {
2155
- capacityProviderId: provider.id,
2156
- laneId: lane.id,
2157
- teamId: input.plan.teamId,
2158
- projectId: input.plan.projectId,
2159
- workDayId: input.workDayId ?? null,
2160
- taskId: input.taskId ?? null,
2161
- state: "reserved",
2162
- reservedCredits: selectedEstimate.reservedCredits,
2163
- executionProviderId: selected.executionProviderId ?? null,
2164
- nativeUnit: selected.nativeUnit ?? null,
2165
- reservedNativeAmount: selected.reservedNativeAmount ?? null,
2166
- metadata: {
2167
- ...input.metadata ?? {},
2168
- grantId: grant.id,
2169
- derivedCapacityMode: selected.derivedCapacityMode ?? "derived",
2170
- executionProviderId: selected.executionProviderId ?? null,
2171
- nativeUnit: selected.nativeUnit ?? null,
2172
- reservedNativeAmount: selected.reservedNativeAmount ?? null,
2173
- derivedAvailableCredits: selected.derivedAvailableCredits ?? null,
2174
- nativePressure: selected.nativePressure ?? null,
2175
- executionProfileId: selected.executionProfileId ?? selectedEstimate.executionProfileId ?? null,
2176
- taskSignature: selectedEstimate.taskSignature,
2177
- estimatedCreditsP50: selectedEstimate.estimatedCreditsP50,
2178
- estimatedCreditsP90: selectedEstimate.estimatedCreditsP90,
2179
- routingScore: selected.score.score,
2180
- attentionEstimate: selected.attentionEstimate ?? null,
2181
- utilityEstimate: selected.utilityEstimate ?? null,
2182
- reservePrediction: selected.reservePrediction ?? null,
2183
- hybridExecutionPlan,
2184
- routingCandidates: candidatePayload
2185
- }
2186
- };
2187
- const routingDecision = {
2188
- taskId: input.taskId ?? null,
2189
- workDayId: input.workDayId ?? null,
2190
- projectId: input.plan.projectId,
2191
- selectedProviderId: provider.id,
2192
- selectedLaneId: lane.id,
2193
- selectedModel: input.selectedModel ?? selected.executionProfileId ?? null,
2194
- decision: "selected",
2195
- reason: selected.score.reasons.length > 0 ? selected.score.reasons.join(",") : "best_eligible_lane",
2196
- candidates: candidatePayload,
2197
- scores: scorePayload,
2198
- metadata: {
2199
- ...input.metadata ?? {},
2200
- grantId: grant.id,
2201
- executionProfileId: selected.executionProfileId ?? selectedEstimate.executionProfileId ?? null,
2202
- remainingCreditsBefore: selected.remainingCredits,
2203
- staticRemainingCreditsBefore: selected.staticRemainingCredits ?? null,
2204
- derivedCapacityMode: selected.derivedCapacityMode ?? "derived",
2205
- executionProviderId: selected.executionProviderId ?? null,
2206
- nativeUnit: selected.nativeUnit ?? null,
2207
- reservedNativeAmount: selected.reservedNativeAmount ?? null,
2208
- derivedAvailableCreditsBefore: selected.derivedAvailableCredits ?? null,
2209
- nativePressure: selected.nativePressure ?? null,
2210
- reservedCredits: selectedEstimate.reservedCredits,
2211
- attentionEstimate: selected.attentionEstimate ?? null,
2212
- utilityEstimate: selected.utilityEstimate ?? null,
2213
- reservePrediction: selected.reservePrediction ?? null,
2214
- hybridExecutionPlan,
2215
- escalationPath: candidatePayload.filter((candidate) => candidate.eligible).sort((left, right) => Number(left.reservedCredits ?? 0) - Number(right.reservedCredits ?? 0)).map((candidate) => candidate.executionProfileId).filter((value, index, array) => typeof value === "string" && value && array.indexOf(value) === index)
2216
- }
2217
- };
2218
- const ledgerEntry = {
2219
- capacityProviderId: provider.id,
2220
- laneId: lane.id,
2221
- teamId: input.plan.teamId,
2222
- projectId: input.plan.projectId,
2223
- workDayId: input.workDayId ?? null,
2224
- taskId: input.taskId ?? null,
2225
- phase: "reservation_created",
2226
- credits: selectedEstimate.reservedCredits,
2227
- source: input.source ?? "capacity_coordinator",
2228
- metadata: {
2229
- ...input.metadata ?? {},
2230
- grantId: grant.id,
2231
- executionProfileId: selected.executionProfileId ?? selectedEstimate.executionProfileId ?? null,
2232
- derivedCapacityMode: selected.derivedCapacityMode ?? "derived",
2233
- executionProviderId: selected.executionProviderId ?? null,
2234
- nativeUnit: selected.nativeUnit ?? null,
2235
- reservedNativeAmount: selected.reservedNativeAmount ?? null,
2236
- derivedAvailableCredits: selected.derivedAvailableCredits ?? null,
2237
- nativePressure: selected.nativePressure ?? null,
2238
- taskSignature: selectedEstimate.taskSignature,
2239
- attentionEstimate: selected.attentionEstimate ?? null,
2240
- utilityEstimate: selected.utilityEstimate ?? null,
2241
- reservePrediction: selected.reservePrediction ?? null,
2242
- hybridExecutionPlan
2243
- }
2244
- };
2245
- return {
2246
- ok: true,
2247
- provider,
2248
- lane,
2249
- grant,
2250
- estimate: selectedEstimate,
2251
- remainingCreditsBefore: selected.remainingCredits,
2252
- reservation,
2253
- routingDecision,
2254
- ledgerEntry,
2255
- capacityMetadata: {
2256
- providerId: provider.id,
2257
- laneId: lane.id,
2258
- grantId: grant.id,
2259
- reservationId: reservation.id ?? null,
2260
- routingDecisionId: routingDecision.id ?? null,
2261
- estimatedCreditsP50: selectedEstimate.estimatedCreditsP50,
2262
- estimatedCreditsP90: selectedEstimate.estimatedCreditsP90,
2263
- reservedCredits: selectedEstimate.reservedCredits,
2264
- executionProfileId: selected.executionProfileId ?? selectedEstimate.executionProfileId ?? null,
2265
- executionProviderId: selected.executionProviderId ?? null,
2266
- nativeUnit: selected.nativeUnit ?? null,
2267
- reservedNativeAmount: selected.reservedNativeAmount ?? null,
2268
- derivedAvailableCredits: selected.derivedAvailableCredits ?? null,
2269
- derivedCapacityMode: selected.derivedCapacityMode ?? "derived",
2270
- nativePressure: selected.nativePressure ?? null,
2271
- costMultiplier: selectedEstimate.costMultiplier ?? null,
2272
- score: selected.score.score,
2273
- attentionEstimate: selected.attentionEstimate ?? null,
2274
- utilityEstimate: selected.utilityEstimate ?? null,
2275
- reservePrediction: selected.reservePrediction ?? null,
2276
- hybridExecutionPlan,
2277
- candidates: candidatePayload
2278
- },
2279
- candidates
2280
- };
2281
- }
2282
- export {
2283
- ACTUAL_CREDIT_FORMULA_VERSION,
2284
- DEFAULT_EXECUTION_PROFILES,
2285
- DEFAULT_EXECUTION_PROFILE_ID,
2286
- DEFAULT_TASK_ADMISSION_POLICY,
2287
- buildCreditConversionProfileFromActuals,
2288
- buildTaskEstimateProfileFromActuals,
2289
- calculateActualCredits,
2290
- capacityRoutePressure,
2291
- computeWorkdayBudgetEnvelope,
2292
- createReservationReleaseEntry,
2293
- decideTaskAdmission,
2294
- deriveAvailableCredits,
2295
- estimateAttentionForTask,
2296
- estimateConfidenceFromProfile,
2297
- estimateForClassification,
2298
- estimateLearningPercentile,
2299
- estimateLearningVariance,
2300
- estimateProfileConfidenceScore,
2301
- estimateUtilityForTask,
2302
- isInterruptedUsageActual,
2303
- mutationRequiresRepositoryClaim,
2304
- nativeUsageAmount,
2305
- nativeUsageUnit,
2306
- normalizeAttentionPolicy,
2307
- normalizeExecutionProfile,
2308
- normalizeHybridExecutionPlan,
2309
- normalizePlanningPolicy,
2310
- normalizePredictiveReservePolicy,
2311
- normalizeTaskAdmissionPolicy,
2312
- normalizeTaskPlanProposal,
2313
- normalizeUtilityPolicy,
2314
- predictReserveForCapacityPlan,
2315
- progressivelyAdmitPlanProposal,
2316
- rankPlannedTaskNodes,
2317
- reservationHasCapacity,
2318
- reserveCreditsForEstimate,
2319
- routeAndReserveCapacity,
2320
- scoreCapacityLane,
2321
- selectBestCapacityLane,
2322
- selectCreditConversionProfile,
2323
- selectTaskEstimateProfile,
2324
- settleCapacityActuals,
2325
- shouldInterruptForCapacity,
2326
- summarizeCapacityPlan,
2327
- summarizeProjectCapacityPlan,
2328
- summarizeTeamCapacityPlan,
2329
- synthesizePlanEstimate,
2330
- validateTaskPlanProposal
2331
- };