@wildo-ai/dev-companion 1.1.8 → 1.1.9

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 (325) hide show
  1. package/bin/companion-supervisor.d.mts +33 -0
  2. package/bin/companion-supervisor.mjs +174 -0
  3. package/bin/wildo-dev-companion-supervised.mjs +16 -0
  4. package/dist/esm/brand/models/logo-generation.actors-system.definitions.d.ts.map +1 -1
  5. package/dist/esm/brand/models/logo-generation.actors-system.definitions.js +8 -2
  6. package/dist/esm/brand/models/logo-generation.actors-system.definitions.js.map +1 -1
  7. package/dist/esm/brand/models/logo-judge.actors-system.definitions.d.ts.map +1 -1
  8. package/dist/esm/brand/models/logo-judge.actors-system.definitions.js +8 -2
  9. package/dist/esm/brand/models/logo-judge.actors-system.definitions.js.map +1 -1
  10. package/dist/esm/brand/services/brand-accept.companion.service.d.ts +1 -1
  11. package/dist/esm/brand/services/brand-accept.companion.service.d.ts.map +1 -1
  12. package/dist/esm/brand/services/brand-accept.companion.service.js +9 -11
  13. package/dist/esm/brand/services/brand-accept.companion.service.js.map +1 -1
  14. package/dist/esm/claude-cli/models/application-coding-run-checkpoint.models.d.ts +21 -0
  15. package/dist/esm/claude-cli/models/application-coding-run-checkpoint.models.d.ts.map +1 -1
  16. package/dist/esm/claude-cli/models/application-coding-run-checkpoint.models.js +33 -1
  17. package/dist/esm/claude-cli/models/application-coding-run-checkpoint.models.js.map +1 -1
  18. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts +41 -2
  19. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts.map +1 -1
  20. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js +43 -1
  21. package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js.map +1 -1
  22. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.d.ts +57 -1
  23. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.d.ts.map +1 -1
  24. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.js +75 -1
  25. package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.js.map +1 -1
  26. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts +90 -5
  27. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts.map +1 -1
  28. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js +242 -22
  29. package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js.map +1 -1
  30. package/dist/esm/companion-api/companion-api.schemas.d.ts +23 -2
  31. package/dist/esm/companion-api/companion-api.schemas.d.ts.map +1 -1
  32. package/dist/esm/companion-api/companion-api.schemas.js +13 -2
  33. package/dist/esm/companion-api/companion-api.schemas.js.map +1 -1
  34. package/dist/esm/companion-api/controllers/companion.controller.d.ts +63 -7
  35. package/dist/esm/companion-api/controllers/companion.controller.d.ts.map +1 -1
  36. package/dist/esm/companion-api/controllers/companion.controller.js +315 -39
  37. package/dist/esm/companion-api/controllers/companion.controller.js.map +1 -1
  38. package/dist/esm/core/config/primary-language.companion.utils.d.ts +5 -4
  39. package/dist/esm/core/config/primary-language.companion.utils.d.ts.map +1 -1
  40. package/dist/esm/core/config/primary-language.companion.utils.js +5 -4
  41. package/dist/esm/core/config/primary-language.companion.utils.js.map +1 -1
  42. package/dist/esm/core/context/application-module-generations.companion.d.ts +103 -0
  43. package/dist/esm/core/context/application-module-generations.companion.d.ts.map +1 -0
  44. package/dist/esm/core/context/application-module-generations.companion.js +313 -0
  45. package/dist/esm/core/context/application-module-generations.companion.js.map +1 -0
  46. package/dist/esm/core/context/companion-package-loaders.companion.d.ts +19 -19
  47. package/dist/esm/core/context/companion-package-loaders.companion.d.ts.map +1 -1
  48. package/dist/esm/core/context/companion-package-loaders.companion.js +52 -40
  49. package/dist/esm/core/context/companion-package-loaders.companion.js.map +1 -1
  50. package/dist/esm/core/inject/models/container.d.ts.map +1 -1
  51. package/dist/esm/core/inject/models/container.js +4 -0
  52. package/dist/esm/core/inject/models/container.js.map +1 -1
  53. package/dist/esm/core/inject/models/service-types.d.ts +4 -0
  54. package/dist/esm/core/inject/models/service-types.d.ts.map +1 -1
  55. package/dist/esm/core/inject/models/service-types.js +4 -0
  56. package/dist/esm/core/inject/models/service-types.js.map +1 -1
  57. package/dist/esm/core/introspection/resources/creation-console-answer.companion.d.ts +15 -1
  58. package/dist/esm/core/introspection/resources/creation-console-answer.companion.d.ts.map +1 -1
  59. package/dist/esm/core/introspection/resources/creation-console-answer.companion.js +38 -3
  60. package/dist/esm/core/introspection/resources/creation-console-answer.companion.js.map +1 -1
  61. package/dist/esm/core/introspection/resources/creation-console-projection.companion.d.ts +21 -0
  62. package/dist/esm/core/introspection/resources/creation-console-projection.companion.d.ts.map +1 -1
  63. package/dist/esm/core/introspection/resources/creation-console-projection.companion.js +64 -25
  64. package/dist/esm/core/introspection/resources/creation-console-projection.companion.js.map +1 -1
  65. package/dist/esm/core/introspection/resources/creation-home-projection.companion.d.ts.map +1 -1
  66. package/dist/esm/core/introspection/resources/creation-home-projection.companion.js +2 -0
  67. package/dist/esm/core/introspection/resources/creation-home-projection.companion.js.map +1 -1
  68. package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.d.ts +0 -28
  69. package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.d.ts.map +1 -1
  70. package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.js +192 -19
  71. package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.js.map +1 -1
  72. package/dist/esm/core/introspection/resources/creation-plane-projection.companion.service.d.ts.map +1 -1
  73. package/dist/esm/core/introspection/resources/creation-plane-projection.companion.service.js +27 -5
  74. package/dist/esm/core/introspection/resources/creation-plane-projection.companion.service.js.map +1 -1
  75. package/dist/esm/core/introspection/resources/launch-blockers.companion.d.ts +47 -0
  76. package/dist/esm/core/introspection/resources/launch-blockers.companion.d.ts.map +1 -0
  77. package/dist/esm/core/introspection/resources/launch-blockers.companion.js +98 -0
  78. package/dist/esm/core/introspection/resources/launch-blockers.companion.js.map +1 -0
  79. package/dist/esm/core/introspection/services/companion-introspection.companion.service.d.ts +6 -1
  80. package/dist/esm/core/introspection/services/companion-introspection.companion.service.d.ts.map +1 -1
  81. package/dist/esm/core/introspection/services/companion-introspection.companion.service.js +20 -1
  82. package/dist/esm/core/introspection/services/companion-introspection.companion.service.js.map +1 -1
  83. package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.d.ts +34 -8
  84. package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.d.ts.map +1 -1
  85. package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.js +61 -12
  86. package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.js.map +1 -1
  87. package/dist/esm/core/introspection/services/introspection-input-closure.companion.d.ts +44 -0
  88. package/dist/esm/core/introspection/services/introspection-input-closure.companion.d.ts.map +1 -0
  89. package/dist/esm/core/introspection/services/introspection-input-closure.companion.js +104 -0
  90. package/dist/esm/core/introspection/services/introspection-input-closure.companion.js.map +1 -0
  91. package/dist/esm/core/introspection/services/introspection-source-state.companion.service.d.ts +41 -22
  92. package/dist/esm/core/introspection/services/introspection-source-state.companion.service.d.ts.map +1 -1
  93. package/dist/esm/core/introspection/services/introspection-source-state.companion.service.js +64 -47
  94. package/dist/esm/core/introspection/services/introspection-source-state.companion.service.js.map +1 -1
  95. package/dist/esm/core/introspection/subprocess/expert-persona-brief.renderer.d.ts +7 -1
  96. package/dist/esm/core/introspection/subprocess/expert-persona-brief.renderer.d.ts.map +1 -1
  97. package/dist/esm/core/introspection/subprocess/expert-persona-brief.renderer.js +13 -4
  98. package/dist/esm/core/introspection/subprocess/expert-persona-brief.renderer.js.map +1 -1
  99. package/dist/esm/core/introspection/subprocess/specification-artifacts.behavior.d.ts.map +1 -1
  100. package/dist/esm/core/introspection/subprocess/specification-artifacts.behavior.js +7 -0
  101. package/dist/esm/core/introspection/subprocess/specification-artifacts.behavior.js.map +1 -1
  102. package/dist/esm/core/lock/wildo-saas-lock.schemas.d.ts +4 -4
  103. package/dist/esm/core/runtime/companion-env-file.d.ts +39 -9
  104. package/dist/esm/core/runtime/companion-env-file.d.ts.map +1 -1
  105. package/dist/esm/core/runtime/companion-env-file.js +75 -16
  106. package/dist/esm/core/runtime/companion-env-file.js.map +1 -1
  107. package/dist/esm/core/runtime/services/start-companion-application.service.d.ts +7 -3
  108. package/dist/esm/core/runtime/services/start-companion-application.service.d.ts.map +1 -1
  109. package/dist/esm/core/runtime/services/start-companion-application.service.js +29 -11
  110. package/dist/esm/core/runtime/services/start-companion-application.service.js.map +1 -1
  111. package/dist/esm/core/utils/bounded-concurrency.utils.d.ts +17 -0
  112. package/dist/esm/core/utils/bounded-concurrency.utils.d.ts.map +1 -0
  113. package/dist/esm/core/utils/bounded-concurrency.utils.js +37 -0
  114. package/dist/esm/core/utils/bounded-concurrency.utils.js.map +1 -0
  115. package/dist/esm/core/utils/derived-input-signature.companion.utils.d.ts +10 -1
  116. package/dist/esm/core/utils/derived-input-signature.companion.utils.d.ts.map +1 -1
  117. package/dist/esm/core/utils/derived-input-signature.companion.utils.js +9 -2
  118. package/dist/esm/core/utils/derived-input-signature.companion.utils.js.map +1 -1
  119. package/dist/esm/creation-conversation/creation-conversation.actors-system.definitions.d.ts.map +1 -1
  120. package/dist/esm/creation-conversation/creation-conversation.actors-system.definitions.js +2 -0
  121. package/dist/esm/creation-conversation/creation-conversation.actors-system.definitions.js.map +1 -1
  122. package/dist/esm/creation-conversation/creation-conversation.function-tools.d.ts.map +1 -1
  123. package/dist/esm/creation-conversation/creation-conversation.function-tools.js +66 -6
  124. package/dist/esm/creation-conversation/creation-conversation.function-tools.js.map +1 -1
  125. package/dist/esm/deliberations/models/deliberation-agents.actors-system.definitions.d.ts +0 -17
  126. package/dist/esm/deliberations/models/deliberation-agents.actors-system.definitions.d.ts.map +1 -1
  127. package/dist/esm/deliberations/models/deliberation-agents.actors-system.definitions.js +10 -4
  128. package/dist/esm/deliberations/models/deliberation-agents.actors-system.definitions.js.map +1 -1
  129. package/dist/esm/email/services/email-template.companion.service.d.ts +6 -1
  130. package/dist/esm/email/services/email-template.companion.service.d.ts.map +1 -1
  131. package/dist/esm/email/services/email-template.companion.service.js +4 -1
  132. package/dist/esm/email/services/email-template.companion.service.js.map +1 -1
  133. package/dist/esm/expert-personas/models/expert-persona-critique.actors-system.definitions.d.ts.map +1 -1
  134. package/dist/esm/expert-personas/models/expert-persona-critique.actors-system.definitions.js +8 -2
  135. package/dist/esm/expert-personas/models/expert-persona-critique.actors-system.definitions.js.map +1 -1
  136. package/dist/esm/expert-personas/models/expert-persona-derivation.actors-system.definitions.d.ts.map +1 -1
  137. package/dist/esm/expert-personas/models/expert-persona-derivation.actors-system.definitions.js +8 -2
  138. package/dist/esm/expert-personas/models/expert-persona-derivation.actors-system.definitions.js.map +1 -1
  139. package/dist/esm/expert-personas/services/expert-persona.companion.service.d.ts.map +1 -1
  140. package/dist/esm/expert-personas/services/expert-persona.companion.service.js +7 -7
  141. package/dist/esm/expert-personas/services/expert-persona.companion.service.js.map +1 -1
  142. package/dist/esm/i18n/composite_views/app.creation-conversation.en.d.ts.map +1 -1
  143. package/dist/esm/i18n/composite_views/app.creation-conversation.en.js +41 -1
  144. package/dist/esm/i18n/composite_views/app.creation-conversation.en.js.map +1 -1
  145. package/dist/esm/i18n/resources/workbenchAspects.en.d.ts.map +1 -1
  146. package/dist/esm/i18n/resources/workbenchAspects.en.js +7 -0
  147. package/dist/esm/i18n/resources/workbenchAspects.en.js.map +1 -1
  148. package/dist/esm/i18n/resources/workbenchBuildDispatchPlan.en.d.ts +5 -0
  149. package/dist/esm/i18n/resources/workbenchBuildDispatchPlan.en.d.ts.map +1 -1
  150. package/dist/esm/i18n/resources/workbenchBuildDispatchPlan.en.js +5 -0
  151. package/dist/esm/i18n/resources/workbenchBuildDispatchPlan.en.js.map +1 -1
  152. package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.d.ts +1 -1
  153. package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.d.ts.map +1 -1
  154. package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.js +2 -1
  155. package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.js.map +1 -1
  156. package/dist/esm/i18n/resources/workbenchDossierEntries.en.d.ts +46 -0
  157. package/dist/esm/i18n/resources/workbenchDossierEntries.en.d.ts.map +1 -1
  158. package/dist/esm/i18n/resources/workbenchDossierEntries.en.js +12 -0
  159. package/dist/esm/i18n/resources/workbenchDossierEntries.en.js.map +1 -1
  160. package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.d.ts +266 -0
  161. package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.d.ts.map +1 -1
  162. package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.js +91 -5
  163. package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.js.map +1 -1
  164. package/dist/esm/i18n/system_enums/application-creation.en.d.ts +41 -0
  165. package/dist/esm/i18n/system_enums/application-creation.en.d.ts.map +1 -1
  166. package/dist/esm/i18n/system_enums/application-creation.en.js +45 -1
  167. package/dist/esm/i18n/system_enums/application-creation.en.js.map +1 -1
  168. package/dist/esm/i18n/system_enums/localization.en.d.ts +82 -0
  169. package/dist/esm/i18n/system_enums/localization.en.d.ts.map +1 -0
  170. package/dist/esm/i18n/system_enums/localization.en.js +82 -0
  171. package/dist/esm/i18n/system_enums/localization.en.js.map +1 -0
  172. package/dist/esm/i18n/system_enums/risk-register.en.d.ts +1 -0
  173. package/dist/esm/i18n/system_enums/risk-register.en.d.ts.map +1 -1
  174. package/dist/esm/i18n/system_enums/risk-register.en.js +1 -0
  175. package/dist/esm/i18n/system_enums/risk-register.en.js.map +1 -1
  176. package/dist/esm/i18n/system_enums/workbench-dossier.en.d.ts +10 -0
  177. package/dist/esm/i18n/system_enums/workbench-dossier.en.d.ts.map +1 -1
  178. package/dist/esm/i18n/system_enums/workbench-dossier.en.js +13 -0
  179. package/dist/esm/i18n/system_enums/workbench-dossier.en.js.map +1 -1
  180. package/dist/esm/i18n-labelling/models/labelling-progress.models.d.ts +43 -0
  181. package/dist/esm/i18n-labelling/models/labelling-progress.models.d.ts.map +1 -0
  182. package/dist/esm/i18n-labelling/models/labelling-progress.models.js +34 -0
  183. package/dist/esm/i18n-labelling/models/labelling-progress.models.js.map +1 -0
  184. package/dist/esm/i18n-labelling/services/labellize-orchestrator.companion.service.d.ts +8 -0
  185. package/dist/esm/i18n-labelling/services/labellize-orchestrator.companion.service.d.ts.map +1 -1
  186. package/dist/esm/i18n-labelling/services/labellize-orchestrator.companion.service.js +97 -56
  187. package/dist/esm/i18n-labelling/services/labellize-orchestrator.companion.service.js.map +1 -1
  188. package/dist/esm/i18n-labelling/services/translate-orchestrator.companion.service.d.ts +18 -0
  189. package/dist/esm/i18n-labelling/services/translate-orchestrator.companion.service.d.ts.map +1 -1
  190. package/dist/esm/i18n-labelling/services/translate-orchestrator.companion.service.js +269 -153
  191. package/dist/esm/i18n-labelling/services/translate-orchestrator.companion.service.js.map +1 -1
  192. package/dist/esm/i18n-labelling/utils/labelling-concurrency.utils.d.ts +41 -0
  193. package/dist/esm/i18n-labelling/utils/labelling-concurrency.utils.d.ts.map +1 -0
  194. package/dist/esm/i18n-labelling/utils/labelling-concurrency.utils.js +47 -0
  195. package/dist/esm/i18n-labelling/utils/labelling-concurrency.utils.js.map +1 -0
  196. package/dist/esm/i18n-labelling/utils/per-unit-file.utils.d.ts +12 -0
  197. package/dist/esm/i18n-labelling/utils/per-unit-file.utils.d.ts.map +1 -1
  198. package/dist/esm/i18n-labelling/utils/per-unit-file.utils.js +10 -2
  199. package/dist/esm/i18n-labelling/utils/per-unit-file.utils.js.map +1 -1
  200. package/dist/esm/i18n-labelling/utils/staged-label-file-writer.utils.d.ts +89 -0
  201. package/dist/esm/i18n-labelling/utils/staged-label-file-writer.utils.d.ts.map +1 -0
  202. package/dist/esm/i18n-labelling/utils/staged-label-file-writer.utils.js +229 -0
  203. package/dist/esm/i18n-labelling/utils/staged-label-file-writer.utils.js.map +1 -0
  204. package/dist/esm/meta-workflows/models/build-task-rearm.models.d.ts +67 -1
  205. package/dist/esm/meta-workflows/models/build-task-rearm.models.d.ts.map +1 -1
  206. package/dist/esm/meta-workflows/models/build-task-rearm.models.js +64 -0
  207. package/dist/esm/meta-workflows/models/build-task-rearm.models.js.map +1 -1
  208. package/dist/esm/meta-workflows/models/creation-intervention.models.d.ts +308 -0
  209. package/dist/esm/meta-workflows/models/creation-intervention.models.d.ts.map +1 -0
  210. package/dist/esm/meta-workflows/models/creation-intervention.models.js +365 -0
  211. package/dist/esm/meta-workflows/models/creation-intervention.models.js.map +1 -0
  212. package/dist/esm/meta-workflows/models/generation-step-progress.models.d.ts +61 -0
  213. package/dist/esm/meta-workflows/models/generation-step-progress.models.d.ts.map +1 -0
  214. package/dist/esm/meta-workflows/models/generation-step-progress.models.js +58 -0
  215. package/dist/esm/meta-workflows/models/generation-step-progress.models.js.map +1 -0
  216. package/dist/esm/meta-workflows/models/meta-workflows-lane.models.d.ts +10 -6
  217. package/dist/esm/meta-workflows/models/meta-workflows-lane.models.d.ts.map +1 -1
  218. package/dist/esm/meta-workflows/models/meta-workflows-lane.models.js +11 -6
  219. package/dist/esm/meta-workflows/models/meta-workflows-lane.models.js.map +1 -1
  220. package/dist/esm/meta-workflows/models/playbook-run-checkpoint.models.d.ts +3 -0
  221. package/dist/esm/meta-workflows/models/playbook-run-checkpoint.models.d.ts.map +1 -1
  222. package/dist/esm/meta-workflows/models/playbook-run-checkpoint.models.js +8 -1
  223. package/dist/esm/meta-workflows/models/playbook-run-checkpoint.models.js.map +1 -1
  224. package/dist/esm/meta-workflows/models/playbook-run-record.models.d.ts +26 -0
  225. package/dist/esm/meta-workflows/models/playbook-run-record.models.d.ts.map +1 -1
  226. package/dist/esm/meta-workflows/models/playbook-run-record.models.js +66 -10
  227. package/dist/esm/meta-workflows/models/playbook-run-record.models.js.map +1 -1
  228. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.d.ts +13 -0
  229. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.d.ts.map +1 -0
  230. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.js +33 -0
  231. package/dist/esm/meta-workflows/services/application-assembly-checks.companion.utils.js.map +1 -0
  232. package/dist/esm/meta-workflows/services/application-assembly-repair.companion.utils.d.ts +145 -0
  233. package/dist/esm/meta-workflows/services/application-assembly-repair.companion.utils.d.ts.map +1 -0
  234. package/dist/esm/meta-workflows/services/application-assembly-repair.companion.utils.js +179 -0
  235. package/dist/esm/meta-workflows/services/application-assembly-repair.companion.utils.js.map +1 -0
  236. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts +376 -17
  237. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts.map +1 -1
  238. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js +805 -39
  239. package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js.map +1 -1
  240. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.d.ts +93 -7
  241. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.d.ts.map +1 -1
  242. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.js +142 -25
  243. package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.js.map +1 -1
  244. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.d.ts +120 -3
  245. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.d.ts.map +1 -1
  246. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.js +325 -16
  247. package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.js.map +1 -1
  248. package/dist/esm/meta-workflows/services/application-build-website-context.companion.service.d.ts.map +1 -1
  249. package/dist/esm/meta-workflows/services/application-build-website-context.companion.service.js +15 -6
  250. package/dist/esm/meta-workflows/services/application-build-website-context.companion.service.js.map +1 -1
  251. package/dist/esm/meta-workflows/services/application-maturity-executor.companion.service.d.ts.map +1 -1
  252. package/dist/esm/meta-workflows/services/application-maturity-executor.companion.service.js +10 -11
  253. package/dist/esm/meta-workflows/services/application-maturity-executor.companion.service.js.map +1 -1
  254. package/dist/esm/meta-workflows/services/capability-composition-executor.companion.service.d.ts.map +1 -1
  255. package/dist/esm/meta-workflows/services/capability-composition-executor.companion.service.js +10 -11
  256. package/dist/esm/meta-workflows/services/capability-composition-executor.companion.service.js.map +1 -1
  257. package/dist/esm/meta-workflows/services/creation-intervention-ledger.companion.service.d.ts +82 -0
  258. package/dist/esm/meta-workflows/services/creation-intervention-ledger.companion.service.d.ts.map +1 -0
  259. package/dist/esm/meta-workflows/services/creation-intervention-ledger.companion.service.js +291 -0
  260. package/dist/esm/meta-workflows/services/creation-intervention-ledger.companion.service.js.map +1 -0
  261. package/dist/esm/meta-workflows/services/creation-lane-preflight.companion.service.d.ts +60 -0
  262. package/dist/esm/meta-workflows/services/creation-lane-preflight.companion.service.d.ts.map +1 -0
  263. package/dist/esm/meta-workflows/services/creation-lane-preflight.companion.service.js +66 -0
  264. package/dist/esm/meta-workflows/services/creation-lane-preflight.companion.service.js.map +1 -0
  265. package/dist/esm/meta-workflows/services/creation-run-report.companion.service.d.ts +53 -0
  266. package/dist/esm/meta-workflows/services/creation-run-report.companion.service.d.ts.map +1 -0
  267. package/dist/esm/meta-workflows/services/creation-run-report.companion.service.js +164 -0
  268. package/dist/esm/meta-workflows/services/creation-run-report.companion.service.js.map +1 -0
  269. package/dist/esm/meta-workflows/services/dossier-write-queue.companion.utils.d.ts +37 -0
  270. package/dist/esm/meta-workflows/services/dossier-write-queue.companion.utils.d.ts.map +1 -0
  271. package/dist/esm/meta-workflows/services/dossier-write-queue.companion.utils.js +52 -0
  272. package/dist/esm/meta-workflows/services/dossier-write-queue.companion.utils.js.map +1 -0
  273. package/dist/esm/meta-workflows/services/dossier.companion.service.d.ts +74 -14
  274. package/dist/esm/meta-workflows/services/dossier.companion.service.d.ts.map +1 -1
  275. package/dist/esm/meta-workflows/services/dossier.companion.service.js +180 -28
  276. package/dist/esm/meta-workflows/services/dossier.companion.service.js.map +1 -1
  277. package/dist/esm/meta-workflows/services/foundation-executor.companion.service.d.ts +2 -3
  278. package/dist/esm/meta-workflows/services/foundation-executor.companion.service.d.ts.map +1 -1
  279. package/dist/esm/meta-workflows/services/foundation-executor.companion.service.js +2 -8
  280. package/dist/esm/meta-workflows/services/foundation-executor.companion.service.js.map +1 -1
  281. package/dist/esm/meta-workflows/services/interview-answer-proposal.companion.d.ts +67 -0
  282. package/dist/esm/meta-workflows/services/interview-answer-proposal.companion.d.ts.map +1 -0
  283. package/dist/esm/meta-workflows/services/interview-answer-proposal.companion.js +64 -0
  284. package/dist/esm/meta-workflows/services/interview-answer-proposal.companion.js.map +1 -0
  285. package/dist/esm/meta-workflows/services/playbook-instance.companion.service.d.ts.map +1 -1
  286. package/dist/esm/meta-workflows/services/playbook-instance.companion.service.js +11 -3
  287. package/dist/esm/meta-workflows/services/playbook-instance.companion.service.js.map +1 -1
  288. package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.d.ts +92 -4
  289. package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.d.ts.map +1 -1
  290. package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.js +328 -7
  291. package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.js.map +1 -1
  292. package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts +105 -6
  293. package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts.map +1 -1
  294. package/dist/esm/meta-workflows/services/playbook-run.companion.service.js +309 -39
  295. package/dist/esm/meta-workflows/services/playbook-run.companion.service.js.map +1 -1
  296. package/dist/esm/meta-workflows/services/playbook-spend-meter.companion.service.d.ts +62 -1
  297. package/dist/esm/meta-workflows/services/playbook-spend-meter.companion.service.d.ts.map +1 -1
  298. package/dist/esm/meta-workflows/services/playbook-spend-meter.companion.service.js +152 -2
  299. package/dist/esm/meta-workflows/services/playbook-spend-meter.companion.service.js.map +1 -1
  300. package/package.json +22 -18
  301. package/dist/esm/.tsbuildinfo +0 -1
  302. package/dist/esm/__tests__/asset-noop.d.ts +0 -3
  303. package/dist/esm/__tests__/asset-noop.d.ts.map +0 -1
  304. package/dist/esm/__tests__/asset-noop.js +0 -2
  305. package/dist/esm/__tests__/asset-noop.js.map +0 -1
  306. package/dist/esm/__tests__/chdir-dogfood-app.setup.d.ts +0 -2
  307. package/dist/esm/__tests__/chdir-dogfood-app.setup.d.ts.map +0 -1
  308. package/dist/esm/__tests__/chdir-dogfood-app.setup.js +0 -44
  309. package/dist/esm/__tests__/chdir-dogfood-app.setup.js.map +0 -1
  310. package/dist/esm/__tests__/internal-test-view.d.ts +0 -39
  311. package/dist/esm/__tests__/internal-test-view.d.ts.map +0 -1
  312. package/dist/esm/__tests__/internal-test-view.js +0 -2
  313. package/dist/esm/__tests__/internal-test-view.js.map +0 -1
  314. package/dist/esm/claude-cli/services/__tests__/support/in-memory-coding-actor-plane.d.ts +0 -50
  315. package/dist/esm/claude-cli/services/__tests__/support/in-memory-coding-actor-plane.d.ts.map +0 -1
  316. package/dist/esm/claude-cli/services/__tests__/support/in-memory-coding-actor-plane.js +0 -157
  317. package/dist/esm/claude-cli/services/__tests__/support/in-memory-coding-actor-plane.js.map +0 -1
  318. package/dist/esm/meta-workflows/services/__tests__/application-build-task-coding.companion.test-fixtures.d.ts +0 -8
  319. package/dist/esm/meta-workflows/services/__tests__/application-build-task-coding.companion.test-fixtures.d.ts.map +0 -1
  320. package/dist/esm/meta-workflows/services/__tests__/application-build-task-coding.companion.test-fixtures.js +0 -43
  321. package/dist/esm/meta-workflows/services/__tests__/application-build-task-coding.companion.test-fixtures.js.map +0 -1
  322. package/dist/esm/meta-workflows/services/__tests__/support/in-memory-actor-plane.d.ts +0 -79
  323. package/dist/esm/meta-workflows/services/__tests__/support/in-memory-actor-plane.d.ts.map +0 -1
  324. package/dist/esm/meta-workflows/services/__tests__/support/in-memory-actor-plane.js +0 -193
  325. package/dist/esm/meta-workflows/services/__tests__/support/in-memory-actor-plane.js.map +0 -1
@@ -26,12 +26,22 @@ export interface PlaybookModelCallUsage {
26
26
  readonly inputTokens?: number;
27
27
  readonly outputTokens?: number;
28
28
  readonly totalTokens?: number;
29
+ /** Prompt-cache reads, inside `totalTokens` — see `PlaybookSpend.cacheReadTokens`. */
30
+ readonly cacheReadTokens?: number;
29
31
  readonly cost?: {
30
32
  readonly amount: number;
31
33
  readonly currency: string;
32
34
  };
33
35
  }
34
36
  export declare function readModelCallUsage(usage: unknown): PlaybookModelCallUsage;
37
+ /**
38
+ * What a measured unit of work IS to the scopes around it (#2232). A unit whose spend is ALSO recorded on its own
39
+ * build row is tallied apart in every enclosing scope, so a total over playbook runs and build rows counts it once.
40
+ */
41
+ export declare enum PlaybookSpendMeasuredUnit {
42
+ /** A build GENERATION STEP: its spend goes on its own row and into each enclosing scope's `generationSteps`. */
43
+ GENERATION_STEP = "generation_step"
44
+ }
35
45
  /** What the engine's provider-call recorder is to this meter: something that is told of every physical call. */
36
46
  export interface ProviderCallRecording {
37
47
  record(trace: AgentCallTrace): Promise<void>;
@@ -75,16 +85,67 @@ export interface ProviderCallRecording {
75
85
  * installed — the meter sees nothing, and "nothing" must not read as "spent nothing". So until the
76
86
  * decorator has been activated, every measurement answers NOT OBSERVED.
77
87
  */
88
+ /**
89
+ * The default SPEND-RATE runaway breaker, in USD per UTC hour — see
90
+ * {@link PlaybookSpendMeterCompanionService.assertSpendRateBelowRunawayBreaker}.
91
+ *
92
+ * Derived from measurement, not taste (2026-10-01): the busiest hour of a real first creation run
93
+ * (app-creation-test-004) reported $14.33, the market lane's six research agents; a coding build task has cost
94
+ * up to $21.15 a dispatch, and the build lane runs up to three at once, so a heavy legitimate build hour is on
95
+ * the order of $100–150. $500 an hour is far above both: only a loop reaches it.
96
+ */
97
+ export declare const PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD = 500;
98
+ /** The env override for {@link PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD}. */
99
+ export declare const PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_ENV = "WILDO_PLAYBOOK_SPEND_HOURLY_BREAKER_USD";
100
+ /** Refused because reported spend in the current hour reached the runaway breaker — a loop, not a budget. */
101
+ export declare class PlaybookSpendRunawayBreakerError extends Error {
102
+ readonly spentUsd: number;
103
+ readonly breakerUsd: number;
104
+ constructor(spentUsd: number, breakerUsd: number);
105
+ }
78
106
  export declare class PlaybookSpendMeterCompanionService implements PlaybookSpendMeterPort {
79
107
  private readonly scopes;
80
108
  private observing;
109
+ /** USD reported in the current UTC hour, by every call this process made — the breaker's tally. */
110
+ private hourlySpend;
111
+ /** The clock, replaceable in tests. */
112
+ protected now: () => Date;
81
113
  /** Called by the recorder decorator on activation: from now on a call this process makes is seen. */
82
114
  markObserving(): void;
83
115
  /** Whether model calls are actually reaching this meter. */
84
116
  isObserving(): boolean;
117
+ /**
118
+ * The SPEND-RATE runaway breaker (2026-10-01) — the money twin of the lane's call-rate breaker, and like it
119
+ * emphatically NOT a budget.
120
+ *
121
+ * Paul, 2026-10-01: "we need to do not stop things face to spending, else enormous amounts". Spending is the
122
+ * lane's normal state (and 2026-08-24: "we are here to spend"), so nothing is refused for ordinary cost and no
123
+ * per-run or per-day quota exists. What is refused is an ENORMOUS rate: reported USD within one UTC hour at or
124
+ * above {@link PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD}. A rate, never a running total, for the call
125
+ * breaker's reason: a legitimate heavy day accumulates slowly and cannot trip it; a loop trips within the hour.
126
+ *
127
+ * Why money and not only calls: the call breaker counts calls (1000/hour), and the expensive work is few
128
+ * calls — a research agent is ONE call at up to $4, a coding build task one dispatch at up to $21 — so a loop
129
+ * re-dispatching agents could spend hundreds of dollars an hour without tripping it.
130
+ *
131
+ * Checked BEFORE work starts (every playbook run, every structured generation), never mid-call: an agent
132
+ * already running finishes and its work is kept. Only reported USD counts — a structured generation reports
133
+ * tokens and no price, so a generation loop is the call breaker's to catch. The tally is a runtime cache:
134
+ * a restart resets it, which is the documented door beside the env override.
135
+ */
136
+ assertSpendRateBelowRunawayBreaker(): void;
137
+ /** USD reported in the current UTC hour, for a status read. */
138
+ spendThisHourUsd(): number;
85
139
  /** Credit one physical model call to every measurement open in the current async context. */
86
140
  observe(trace: AgentCallTrace): void;
87
- measure<T>(work: () => Promise<T>): Promise<PlaybookMeasuredWork<T>>;
141
+ /**
142
+ * Run `work` and report what the model calls inside it reported. `as` names a unit whose spend is also recorded
143
+ * on its own build row (a generation step): every enclosing scope then tallies it in its matching part, once the
144
+ * unit settles, so the scopes' totals still include it and a reader can leave it out of a sum with the rows.
145
+ */
146
+ measure<T>(work: () => Promise<T>, options?: {
147
+ readonly as?: PlaybookSpendMeasuredUnit;
148
+ }): Promise<PlaybookMeasuredWork<T>>;
88
149
  }
89
150
  /**
90
151
  * Decorate the engine's provider-call recorder so every physical model call is also told to the meter
@@ -1 +1 @@
1
- {"version":3,"file":"playbook-spend-meter.companion.service.d.ts","sourceRoot":"","sources":["../../../../../src/meta-workflows/services/playbook-spend-meter.companion.service.ts"],"names":[],"mappings":"AAIA,OAAO,EAAsB,KAAK,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAGL,KAAK,oBAAoB,EAEzB,KAAK,sBAAsB,EAC5B,MAAM,wCAAwC,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CACxE;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,sBAAsB,CAqBzE;AAaD,gHAAgH;AAChH,MAAM,WAAW,qBAAqB;IACpC,MAAM,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,qBACa,kCAAmC,YAAW,sBAAsB;IAC/E,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuC;IAC9D,OAAO,CAAC,SAAS,CAAS;IAE1B,qGAAqG;IAC9F,aAAa,IAAI,IAAI;IAI5B,4DAA4D;IACrD,WAAW,IAAI,OAAO;IAI7B,6FAA6F;IACtF,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IAY9B,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;CAWlF;AAeD;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,kBAAkB,EAAE,KAAK,EAAE,kCAAkC,GAAG,IAAI,CAcxH"}
1
+ {"version":3,"file":"playbook-spend-meter.companion.service.d.ts","sourceRoot":"","sources":["../../../../../src/meta-workflows/services/playbook-spend-meter.companion.service.ts"],"names":[],"mappings":"AAIA,OAAO,EAAsB,KAAK,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAIL,KAAK,oBAAoB,EAEzB,KAAK,sBAAsB,EAC5B,MAAM,wCAAwC,CAAC;AAIhD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CA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a,IAAI,IAAI;IAI5B,4DAA4D;IACrD,WAAW,IAAI,OAAO;IAI7B;;;;;;;;;;;;;;;;;;OAkBG;IACI,kCAAkC,IAAI,IAAI;IAQjD,+DAA+D;IACxD,gBAAgB,IAAI,MAAM;IAIjC,6FAA6F;IACtF,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI;IA8B3C;;;;OAIG;IACU,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,GAAE;QAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,yBAAyB,CAAA;KAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;CAwB7I;AAsCD;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,kBAAkB,EAAE,KAAK,EAAE,kCAAkC,GAAG,IAAI,CAcxH"}
@@ -8,6 +8,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
8
8
  import { injectable } from 'inversify';
9
9
  import { SAAS_SERVICE_TYPES } from '@wildo-ai/saas-backend-lib';
10
10
  import { PLAYBOOK_SPEND_NOT_OBSERVED, classifyPlaybookSpend, } from '@wildo-ai/application-creation-runtime';
11
+ import { isApplicationCodingAgentRef } from '../models/application-coding-agent.actors-system.definitions.js';
11
12
  export function readModelCallUsage(usage) {
12
13
  if (typeof usage !== 'object' || usage === null)
13
14
  return { fullyMeasured: false };
@@ -16,6 +17,9 @@ export function readModelCallUsage(usage) {
16
17
  const inputTokens = count(bag['promptTokens']) ?? count(bag['inputTokens']);
17
18
  const outputTokens = count(bag['completionTokens']) ?? count(bag['outputTokens']);
18
19
  const cachedTokens = (count(bag['cachedReadTokens']) ?? 0) + (count(bag['cachedWriteTokens']) ?? 0);
20
+ // An agent over ACP names it `cachedReadTokens`; a structured generation nests it under `inputTokenDetails`.
21
+ const inputDetails = typeof bag['inputTokenDetails'] === 'object' && bag['inputTokenDetails'] !== null ? bag['inputTokenDetails'] : {};
22
+ const cacheReadTokens = count(bag['cachedReadTokens']) ?? count(inputDetails['cacheReadTokens']);
19
23
  const totalTokens = count(bag['totalTokens'])
20
24
  ?? (inputTokens !== undefined && outputTokens !== undefined ? inputTokens + outputTokens + cachedTokens : undefined);
21
25
  const rawCost = bag['cost'];
@@ -28,9 +32,35 @@ export function readModelCallUsage(usage) {
28
32
  ...(inputTokens !== undefined ? { inputTokens } : {}),
29
33
  ...(outputTokens !== undefined ? { outputTokens } : {}),
30
34
  ...(totalTokens !== undefined ? { totalTokens } : {}),
35
+ ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),
31
36
  ...(cost ? { cost } : {}),
32
37
  };
33
38
  }
39
+ const emptyBuildRowTally = () => ({ runs: 0, runsWithoutReportedCost: 0, cost: {} });
40
+ /**
41
+ * Add one row's figures to a tally. `madeModelCalls` false (a generation step that called no model: migrations,
42
+ * an e-mail render) means there was nothing to price, so the row is not counted as unpriced.
43
+ */
44
+ function addToBuildRowTally(tally, row, madeModelCalls = true) {
45
+ tally.runs += 1;
46
+ if (madeModelCalls && Object.keys(row.cost ?? {}).length === 0)
47
+ tally.runsWithoutReportedCost += 1;
48
+ if (row.totalTokens !== undefined)
49
+ tally.totalTokens = (tally.totalTokens ?? 0) + row.totalTokens;
50
+ if (row.cacheReadTokens !== undefined)
51
+ tally.cacheReadTokens = (tally.cacheReadTokens ?? 0) + row.cacheReadTokens;
52
+ for (const [currency, amount] of Object.entries(row.cost ?? {}))
53
+ tally.cost[currency] = (tally.cost[currency] ?? 0) + amount;
54
+ }
55
+ /**
56
+ * What a measured unit of work IS to the scopes around it (#2232). A unit whose spend is ALSO recorded on its own
57
+ * build row is tallied apart in every enclosing scope, so a total over playbook runs and build rows counts it once.
58
+ */
59
+ export var PlaybookSpendMeasuredUnit;
60
+ (function (PlaybookSpendMeasuredUnit) {
61
+ /** A build GENERATION STEP: its spend goes on its own row and into each enclosing scope's `generationSteps`. */
62
+ PlaybookSpendMeasuredUnit["GENERATION_STEP"] = "generation_step";
63
+ })(PlaybookSpendMeasuredUnit || (PlaybookSpendMeasuredUnit = {}));
34
64
  /**
35
65
  * The companion's spend meter for the playbook lane (#1507) — the host half of
36
66
  * `PlaybookSpendMeterPort`.
@@ -70,9 +100,38 @@ export function readModelCallUsage(usage) {
70
100
  * installed — the meter sees nothing, and "nothing" must not read as "spent nothing". So until the
71
101
  * decorator has been activated, every measurement answers NOT OBSERVED.
72
102
  */
103
+ /**
104
+ * The default SPEND-RATE runaway breaker, in USD per UTC hour — see
105
+ * {@link PlaybookSpendMeterCompanionService.assertSpendRateBelowRunawayBreaker}.
106
+ *
107
+ * Derived from measurement, not taste (2026-10-01): the busiest hour of a real first creation run
108
+ * (app-creation-test-004) reported $14.33, the market lane's six research agents; a coding build task has cost
109
+ * up to $21.15 a dispatch, and the build lane runs up to three at once, so a heavy legitimate build hour is on
110
+ * the order of $100–150. $500 an hour is far above both: only a loop reaches it.
111
+ */
112
+ export const PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD = 500;
113
+ /** The env override for {@link PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD}. */
114
+ export const PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_ENV = 'WILDO_PLAYBOOK_SPEND_HOURLY_BREAKER_USD';
115
+ /** Refused because reported spend in the current hour reached the runaway breaker — a loop, not a budget. */
116
+ export class PlaybookSpendRunawayBreakerError extends Error {
117
+ spentUsd;
118
+ breakerUsd;
119
+ constructor(spentUsd, breakerUsd) {
120
+ super(`Playbook-lane spend runaway breaker tripped: ${Math.round(spentUsd * 100) / 100} USD reported by model calls within `
121
+ + `the current hour (breaker ${breakerUsd} USD). This detects a loop spending at machine speed, not a budget: `
122
+ + `work already done is kept, and nothing new starts until the hour turns. If this rate is intended, raise `
123
+ + `${PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_ENV}, or restart the companion to reset the in-memory tally.`);
124
+ this.spentUsd = spentUsd;
125
+ this.breakerUsd = breakerUsd;
126
+ }
127
+ }
73
128
  let PlaybookSpendMeterCompanionService = class PlaybookSpendMeterCompanionService {
74
129
  scopes = new AsyncLocalStorage();
75
130
  observing = false;
131
+ /** USD reported in the current UTC hour, by every call this process made — the breaker's tally. */
132
+ hourlySpend = { hour: '', usd: 0 };
133
+ /** The clock, replaceable in tests. */
134
+ now = () => new Date();
76
135
  /** Called by the recorder decorator on activation: from now on a call this process makes is seen. */
77
136
  markObserving() {
78
137
  this.observing = true;
@@ -81,9 +140,46 @@ let PlaybookSpendMeterCompanionService = class PlaybookSpendMeterCompanionServic
81
140
  isObserving() {
82
141
  return this.observing;
83
142
  }
143
+ /**
144
+ * The SPEND-RATE runaway breaker (2026-10-01) — the money twin of the lane's call-rate breaker, and like it
145
+ * emphatically NOT a budget.
146
+ *
147
+ * Paul, 2026-10-01: "we need to do not stop things face to spending, else enormous amounts". Spending is the
148
+ * lane's normal state (and 2026-08-24: "we are here to spend"), so nothing is refused for ordinary cost and no
149
+ * per-run or per-day quota exists. What is refused is an ENORMOUS rate: reported USD within one UTC hour at or
150
+ * above {@link PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD}. A rate, never a running total, for the call
151
+ * breaker's reason: a legitimate heavy day accumulates slowly and cannot trip it; a loop trips within the hour.
152
+ *
153
+ * Why money and not only calls: the call breaker counts calls (1000/hour), and the expensive work is few
154
+ * calls — a research agent is ONE call at up to $4, a coding build task one dispatch at up to $21 — so a loop
155
+ * re-dispatching agents could spend hundreds of dollars an hour without tripping it.
156
+ *
157
+ * Checked BEFORE work starts (every playbook run, every structured generation), never mid-call: an agent
158
+ * already running finishes and its work is kept. Only reported USD counts — a structured generation reports
159
+ * tokens and no price, so a generation loop is the call breaker's to catch. The tally is a runtime cache:
160
+ * a restart resets it, which is the documented door beside the env override.
161
+ */
162
+ assertSpendRateBelowRunawayBreaker() {
163
+ const hour = this.now().toISOString().slice(0, 13);
164
+ if (this.hourlySpend.hour !== hour)
165
+ return;
166
+ const configured = Number(process.env[PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_ENV]);
167
+ const breaker = Number.isFinite(configured) && configured > 0 ? configured : PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD;
168
+ if (this.hourlySpend.usd >= breaker)
169
+ throw new PlaybookSpendRunawayBreakerError(this.hourlySpend.usd, breaker);
170
+ }
171
+ /** USD reported in the current UTC hour, for a status read. */
172
+ spendThisHourUsd() {
173
+ return this.hourlySpend.hour === this.now().toISOString().slice(0, 13) ? this.hourlySpend.usd : 0;
174
+ }
84
175
  /** Credit one physical model call to every measurement open in the current async context. */
85
176
  observe(trace) {
86
177
  const usage = readModelCallUsage(trace.context?.usage);
178
+ // The breaker's tally sees every call this process makes, inside a measurement or not.
179
+ if (usage.cost?.currency === 'USD') {
180
+ const hour = this.now().toISOString().slice(0, 13);
181
+ this.hourlySpend = { hour, usd: (this.hourlySpend.hour === hour ? this.hourlySpend.usd : 0) + usage.cost.amount };
182
+ }
87
183
  for (let scope = this.scopes.getStore(); scope !== undefined; scope = scope.parent) {
88
184
  scope.modelCalls += 1;
89
185
  if (!usage.fullyMeasured)
@@ -94,12 +190,34 @@ let PlaybookSpendMeterCompanionService = class PlaybookSpendMeterCompanionServic
94
190
  scope.outputTokens = (scope.outputTokens ?? 0) + usage.outputTokens;
95
191
  if (usage.totalTokens !== undefined)
96
192
  scope.totalTokens = (scope.totalTokens ?? 0) + usage.totalTokens;
193
+ if (usage.cacheReadTokens !== undefined)
194
+ scope.cacheReadTokens = (scope.cacheReadTokens ?? 0) + usage.cacheReadTokens;
97
195
  if (usage.cost)
98
196
  scope.cost[usage.cost.currency] = (scope.cost[usage.cost.currency] ?? 0) + usage.cost.amount;
197
+ /*
198
+ * A coding run is ONE call on this seam (the engine traces the whole session once, with its merged
199
+ * usage), so a call by a coding agent IS a run. Tallied apart because the same run is also on its build
200
+ * task's row, and a total across both must not count it twice (`PlaybookSpend.codingRuns`).
201
+ */
202
+ if (isApplicationCodingAgentRef(trace.agentRef)) {
203
+ addToBuildRowTally(scope.codingRuns, {
204
+ ...(usage.totalTokens !== undefined ? { totalTokens: usage.totalTokens } : {}),
205
+ ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),
206
+ ...(usage.cost ? { cost: { [usage.cost.currency]: usage.cost.amount } } : {}),
207
+ });
208
+ }
99
209
  }
100
210
  }
101
- async measure(work) {
102
- const scope = { parent: this.scopes.getStore(), modelCalls: 0, callsNotFullyMeasured: 0, cost: {} };
211
+ /**
212
+ * Run `work` and report what the model calls inside it reported. `as` names a unit whose spend is also recorded
213
+ * on its own build row (a generation step): every enclosing scope then tallies it in its matching part, once the
214
+ * unit settles, so the scopes' totals still include it and a reader can leave it out of a sum with the rows.
215
+ */
216
+ async measure(work, options = {}) {
217
+ const scope = {
218
+ parent: this.scopes.getStore(), modelCalls: 0, callsNotFullyMeasured: 0, cost: {},
219
+ codingRuns: emptyBuildRowTally(), generationSteps: emptyBuildRowTally(),
220
+ };
103
221
  const settled = await this.scopes.run(scope, async () => {
104
222
  try {
105
223
  return { status: 'fulfilled', value: await work() };
@@ -108,6 +226,16 @@ let PlaybookSpendMeterCompanionService = class PlaybookSpendMeterCompanionServic
108
226
  return { status: 'rejected', reason };
109
227
  }
110
228
  });
229
+ /*
230
+ * A generation step never dispatches a coding agent (`isApplicationCodingAgentRef` is reached only by the coding
231
+ * dispatcher), so its calls are never also in an enclosing `codingRuns`; the two parts never overlap, and a total
232
+ * that subtracts both subtracts nothing twice. A step that did would need its coding part taken out of this tally.
233
+ */
234
+ if (options.as === PlaybookSpendMeasuredUnit.GENERATION_STEP) {
235
+ for (let enclosing = scope.parent; enclosing !== undefined; enclosing = enclosing.parent) {
236
+ addToBuildRowTally(enclosing.generationSteps, scope, scope.modelCalls > 0);
237
+ }
238
+ }
111
239
  return { settled, spend: this.observing ? spendOfScope(scope) : PLAYBOOK_SPEND_NOT_OBSERVED };
112
240
  }
113
241
  };
@@ -124,7 +252,29 @@ function spendOfScope(scope) {
124
252
  ...(scope.inputTokens !== undefined ? { inputTokens: scope.inputTokens } : {}),
125
253
  ...(scope.outputTokens !== undefined ? { outputTokens: scope.outputTokens } : {}),
126
254
  ...(scope.totalTokens !== undefined ? { totalTokens: scope.totalTokens } : {}),
255
+ ...(scope.cacheReadTokens !== undefined ? { cacheReadTokens: scope.cacheReadTokens } : {}),
127
256
  ...(Object.keys(scope.cost).length > 0 ? { cost: Object.fromEntries(Object.entries(scope.cost).map(([currency, amount]) => [currency, round(amount)])) } : {}),
257
+ /*
258
+ * Both parts ALWAYS stated once the meter observes, `runs: 0` included (#2232 review F5): an ABSENT part must mean "recorded
259
+ * before the part existed", which is what lets a total over these rows and the build rows tell a playbook that
260
+ * started no coding run from one whose coding runs it cannot see, and so name the second as possibly counted twice.
261
+ *
262
+ * A resumed coding run is not counted twice here either: the resume continues the SAME execution and row
263
+ * (`resumeActorExecution`) and arrives through its own request (`/creation/questions/answer`), so it is outside
264
+ * the async context of the run that parked it. That parking run's scope saw the first leg's cumulative cost; the
265
+ * row carries the session's final total, which the journey sums once.
266
+ */
267
+ codingRuns: buildRowPartOfTally(scope.codingRuns, round),
268
+ generationSteps: buildRowPartOfTally(scope.generationSteps, round),
269
+ };
270
+ }
271
+ function buildRowPartOfTally(part, round) {
272
+ return {
273
+ runs: part.runs,
274
+ runsWithoutReportedCost: part.runsWithoutReportedCost,
275
+ ...(part.totalTokens !== undefined ? { totalTokens: part.totalTokens } : {}),
276
+ ...(part.cacheReadTokens !== undefined ? { cacheReadTokens: part.cacheReadTokens } : {}),
277
+ ...(Object.keys(part.cost).length > 0 ? { cost: Object.fromEntries(Object.entries(part.cost).map(([currency, amount]) => [currency, round(amount)])) } : {}),
128
278
  };
129
279
  }
130
280
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"playbook-spend-meter.companion.service.js","sourceRoot":"","sources":["../../../../../src/meta-workflows/services/playbook-spend-meter.companion.service.ts"],"names":[],"mappings":";;;;;;AAAA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CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { injectable } from 'inversify';\n\nimport { SAAS_SERVICE_TYPES, type InversifyContainer } from '@wildo-ai/saas-backend-lib';\nimport type { AgentCallTrace } from '@wildo-ai/saas-models';\nimport {\n PLAYBOOK_SPEND_NOT_OBSERVED,\n classifyPlaybookSpend,\n type PlaybookMeasuredWork,\n type PlaybookSpend,\n type PlaybookSpendMeterPort,\n} from '@wildo-ai/application-creation-runtime';\n\n/**\n * What ONE model call reported, normalized across the two usage envelopes a call can carry (#1507).\n *\n * A structured generation reports `LLMProvider_Usage` (`promptTokens` / `completionTokens` /\n * `totalTokens`, and `tokenUsageComplete: false` when a dimension the operation needs was omitted); a\n * coding or research agent over ACP reports `CodingAgent_Usage` (`inputTokens` / `outputTokens` /\n * `totalTokens`, and a `cost` when the agent reports one — every field optional, because ACP guarantees\n * none of them). Both are read here by shape rather than parsed against either schema: the engine has\n * already parsed them against the right one before emitting the trace.\n *\n * `fullyMeasured` is false for a call that reported nothing, or reported incompletely: an all-zero\n * usage is absent (the rule `ExecutionTraceReadCompanionService.summarizeSessionUsage` applies to the\n * trace files), a provider's own `tokenUsageComplete: false` is incomplete, and so is a call that\n * reported INPUT tokens alone — a generation always produces output, so a usage without an output or\n * total figure (or a cost) is missing the half that says what the call produced.\n *\n * When no `totalTokens` is reported it is derived from every dimension reported, prompt-cache reads and\n * writes included: for a coding turn the cache read is typically the dominant term, and a total that\n * left it out would understate exactly the calls that cost most.\n */\nexport interface PlaybookModelCallUsage {\n readonly fullyMeasured: boolean;\n readonly inputTokens?: number;\n readonly outputTokens?: number;\n readonly totalTokens?: number;\n readonly cost?: { readonly amount: number; readonly currency: string };\n}\n\nexport function readModelCallUsage(usage: unknown): PlaybookModelCallUsage {\n if (typeof usage !== 'object' || usage === null) return { fullyMeasured: false };\n const bag = usage as Record<string, unknown>;\n const count = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined);\n const inputTokens = count(bag['promptTokens']) ?? count(bag['inputTokens']);\n const outputTokens = count(bag['completionTokens']) ?? count(bag['outputTokens']);\n const cachedTokens = (count(bag['cachedReadTokens']) ?? 0) + (count(bag['cachedWriteTokens']) ?? 0);\n const totalTokens = count(bag['totalTokens'])\n ?? (inputTokens !== undefined && outputTokens !== undefined ? inputTokens + outputTokens + cachedTokens : undefined);\n const rawCost = bag['cost'] as { amount?: unknown; currency?: unknown } | undefined;\n const cost = typeof rawCost === 'object' && rawCost !== null && count(rawCost.amount) !== undefined && typeof rawCost.currency === 'string' && rawCost.currency.length > 0\n ? { amount: rawCost.amount as number, currency: rawCost.currency }\n : undefined;\n const reportedWhatItProduced = (outputTokens ?? 0) > 0 || (totalTokens ?? 0) > 0 || cost !== undefined;\n return {\n fullyMeasured: reportedWhatItProduced && bag['tokenUsageComplete'] !== false,\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n ...(cost ? { cost } : {}),\n };\n}\n\n/** One open measurement. Scopes nest: a call is credited to its scope and to every scope around it. */\ninterface SpendScope {\n readonly parent: SpendScope | undefined;\n modelCalls: number;\n callsNotFullyMeasured: number;\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n readonly cost: Record<string, number>;\n}\n\n/** What the engine's provider-call recorder is to this meter: something that is told of every physical call. */\nexport interface ProviderCallRecording {\n record(trace: AgentCallTrace): Promise<void>;\n}\n\n/**\n * The companion's spend meter for the playbook lane (#1507) — the host half of\n * `PlaybookSpendMeterPort`.\n *\n * ## Where it listens\n *\n * At the ONE seam every physical model call already passes through: the engine's provider-call\n * recorder (`SAAS_SERVICE_TYPES.ProviderCallRecorder`), which `AgentsBackendService` calls for every\n * call — structured generation, the selector, the judge, deliberation, the research agent and the\n * coding agent alike — BEFORE its traceability gate. The embeddings and document-extraction services\n * call the same recorder, so an embedding or extraction made inside measured work is counted as a\n * model call too: it is a physical provider call that was paid for, and leaving it out would\n * understate the run. The trace sink was rejected for the reason the\n * recorder's own JSDoc gives: it only receives a trace when an observability provider raised the level,\n * so the meter would read zero on every quiet development machine. Instrumenting each call site was\n * rejected because there are more than twenty and the next one would be missed.\n *\n * The recorder is DECORATED through inversify's activation hook ({@link installPlaybookSpendMeter}), so\n * the durable provider-call record is written exactly as before and the meter is told first.\n *\n * ## How it attributes a call\n *\n * By async context. `measure` opens a scope in an `AsyncLocalStorage`; a call made anywhere inside the\n * work — however deep, including in a promise the work started and did not await — is credited to that\n * scope and every scope around it. That is what lets concurrent children of one iteration each carry\n * their own spend, and a lane carry its whole subtree, with no identifier threaded through twenty call\n * sites. Attribution happens inside `invokeAgent`'s own continuation, so a rate limiter, a retry or a\n * run fired and then awaited through a separate settlement is still credited. What this CANNOT see is\n * a model call made from an async context the measured work did not create — a timer or queue set up\n * by another request. No such path exists in the playbook lane (measured 2026-09-24); one added later\n * would go uncounted without marking anything, so `MEASURED` means \"every call this meter observed\n * reported its usage\", exactly as `PlaybookSpendMeasurement.MEASURED` defines it.\n *\n * ## When it cannot see at all\n *\n * If the recorder was never decorated — the engine bound none, or resolved it before the hook was\n * installed — the meter sees nothing, and \"nothing\" must not read as \"spent nothing\". So until the\n * decorator has been activated, every measurement answers NOT OBSERVED.\n */\n@injectable()\nexport class PlaybookSpendMeterCompanionService implements PlaybookSpendMeterPort {\n private readonly scopes = new AsyncLocalStorage<SpendScope>();\n private observing = false;\n\n /** Called by the recorder decorator on activation: from now on a call this process makes is seen. */\n public markObserving(): void {\n this.observing = true;\n }\n\n /** Whether model calls are actually reaching this meter. */\n public isObserving(): boolean {\n return this.observing;\n }\n\n /** Credit one physical model call to every measurement open in the current async context. */\n public observe(trace: AgentCallTrace): void {\n const usage = readModelCallUsage(trace.context?.usage);\n for (let scope = this.scopes.getStore(); scope !== undefined; scope = scope.parent) {\n scope.modelCalls += 1;\n if (!usage.fullyMeasured) scope.callsNotFullyMeasured += 1;\n if (usage.inputTokens !== undefined) scope.inputTokens = (scope.inputTokens ?? 0) + usage.inputTokens;\n if (usage.outputTokens !== undefined) scope.outputTokens = (scope.outputTokens ?? 0) + usage.outputTokens;\n if (usage.totalTokens !== undefined) scope.totalTokens = (scope.totalTokens ?? 0) + usage.totalTokens;\n if (usage.cost) scope.cost[usage.cost.currency] = (scope.cost[usage.cost.currency] ?? 0) + usage.cost.amount;\n }\n }\n\n public async measure<T>(work: () => Promise<T>): Promise<PlaybookMeasuredWork<T>> {\n const scope: SpendScope = { parent: this.scopes.getStore(), modelCalls: 0, callsNotFullyMeasured: 0, cost: {} };\n const settled = await this.scopes.run(scope, async (): Promise<PromiseSettledResult<T>> => {\n try {\n return { status: 'fulfilled', value: await work() };\n } catch (reason) {\n return { status: 'rejected', reason };\n }\n });\n return { settled, spend: this.observing ? spendOfScope(scope) : PLAYBOOK_SPEND_NOT_OBSERVED };\n }\n}\n\nfunction spendOfScope(scope: SpendScope): PlaybookSpend {\n const counts = { modelCalls: scope.modelCalls, callsNotFullyMeasured: scope.callsNotFullyMeasured, unobservedSegments: 0 };\n const round = (value: number): number => Math.round(value * 1e6) / 1e6;\n return {\n measurement: classifyPlaybookSpend(counts),\n ...counts,\n ...(scope.inputTokens !== undefined ? { inputTokens: scope.inputTokens } : {}),\n ...(scope.outputTokens !== undefined ? { outputTokens: scope.outputTokens } : {}),\n ...(scope.totalTokens !== undefined ? { totalTokens: scope.totalTokens } : {}),\n ...(Object.keys(scope.cost).length > 0 ? { cost: Object.fromEntries(Object.entries(scope.cost).map(([currency, amount]) => [currency, round(amount)])) } : {}),\n };\n}\n\n/**\n * Decorate the engine's provider-call recorder so every physical model call is also told to the meter\n * (#1507). Registered as an ACTIVATION, not a rebind: the engine's recorder stays the binding and keeps\n * writing its durable record — the meter is told first and cannot fail the call, because `observe` does\n * nothing that throws on a well-formed trace and is guarded besides.\n *\n * Must run before anything resolves `AgentsBackendService` — the same constraint the companion's trace\n * sink composition already lives under, and installed beside it. If it runs too late the meter simply\n * never starts observing, and says so (NOT OBSERVED) rather than reporting zero.\n */\nexport function installPlaybookSpendMeter(container: InversifyContainer, meter: PlaybookSpendMeterCompanionService): void {\n container.onActivation<ProviderCallRecording>(SAAS_SERVICE_TYPES.ProviderCallRecorder, (_context, recorder) => {\n meter.markObserving();\n return {\n record: async (trace: AgentCallTrace): Promise<void> => {\n try {\n meter.observe(trace);\n } catch {\n // Metering is a report: it must never turn a provider call, or its durable record, into a failure.\n }\n await recorder.record(trace);\n },\n };\n });\n}\n"]}
1
+ {"version":3,"file":"playbook-spend-meter.companion.service.js","sourceRoot":"","sources":["../../../../../src/meta-workflows/services/playbook-spend-meter.companion.service.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,EAAE,kBAAkB,EAA2B,MAAM,4BAA4B,CAAC;AAEzF,OAAO,EACL,2BAA2B,EAC3B,qBAAqB,GAKtB,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,2BAA2B,EAAE,MAAM,8DAA8D,CAAC;AAgC3G,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC;IACjF,MAAM,GAAG,GAAG,KAAgC,CAAC;IAC7C,MAAM,KAAK,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IAC9I,MAAM,WAAW,GAAG,KAAK,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,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,CAAC;gBACvB,CAAC;gBAAC,MAAM,CAAC;oBACP,mGAAmG;gBACrG,CAAC;gBACD,MAAM,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC/B,CAAC;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { injectable } from 'inversify';\n\nimport { SAAS_SERVICE_TYPES, type InversifyContainer } from '@wildo-ai/saas-backend-lib';\nimport type { AgentCallTrace } from '@wildo-ai/saas-models';\nimport {\n PLAYBOOK_SPEND_NOT_OBSERVED,\n classifyPlaybookSpend,\n type PlaybookSpendBuildRowPart,\n type PlaybookMeasuredWork,\n type PlaybookSpend,\n type PlaybookSpendMeterPort,\n} from '@wildo-ai/application-creation-runtime';\n\nimport { isApplicationCodingAgentRef } from '../models/application-coding-agent.actors-system.definitions';\n\n/**\n * What ONE model call reported, normalized across the two usage envelopes a call can carry (#1507).\n *\n * A structured generation reports `LLMProvider_Usage` (`promptTokens` / `completionTokens` /\n * `totalTokens`, and `tokenUsageComplete: false` when a dimension the operation needs was omitted); a\n * coding or research agent over ACP reports `CodingAgent_Usage` (`inputTokens` / `outputTokens` /\n * `totalTokens`, and a `cost` when the agent reports one — every field optional, because ACP guarantees\n * none of them). Both are read here by shape rather than parsed against either schema: the engine has\n * already parsed them against the right one before emitting the trace.\n *\n * `fullyMeasured` is false for a call that reported nothing, or reported incompletely: an all-zero\n * usage is absent (the rule `ExecutionTraceReadCompanionService.summarizeSessionUsage` applies to the\n * trace files), a provider's own `tokenUsageComplete: false` is incomplete, and so is a call that\n * reported INPUT tokens alone — a generation always produces output, so a usage without an output or\n * total figure (or a cost) is missing the half that says what the call produced.\n *\n * When no `totalTokens` is reported it is derived from every dimension reported, prompt-cache reads and\n * writes included: for a coding turn the cache read is typically the dominant term, and a total that\n * left it out would understate exactly the calls that cost most.\n */\nexport interface PlaybookModelCallUsage {\n readonly fullyMeasured: boolean;\n readonly inputTokens?: number;\n readonly outputTokens?: number;\n readonly totalTokens?: number;\n /** Prompt-cache reads, inside `totalTokens` — see `PlaybookSpend.cacheReadTokens`. */\n readonly cacheReadTokens?: number;\n readonly cost?: { readonly amount: number; readonly currency: string };\n}\n\nexport function readModelCallUsage(usage: unknown): PlaybookModelCallUsage {\n if (typeof usage !== 'object' || usage === null) return { fullyMeasured: false };\n const bag = usage as Record<string, unknown>;\n const count = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined);\n const inputTokens = count(bag['promptTokens']) ?? count(bag['inputTokens']);\n const outputTokens = count(bag['completionTokens']) ?? count(bag['outputTokens']);\n const cachedTokens = (count(bag['cachedReadTokens']) ?? 0) + (count(bag['cachedWriteTokens']) ?? 0);\n // An agent over ACP names it `cachedReadTokens`; a structured generation nests it under `inputTokenDetails`.\n const inputDetails = typeof bag['inputTokenDetails'] === 'object' && bag['inputTokenDetails'] !== null ? bag['inputTokenDetails'] as Record<string, unknown> : {};\n const cacheReadTokens = count(bag['cachedReadTokens']) ?? count(inputDetails['cacheReadTokens']);\n const totalTokens = count(bag['totalTokens'])\n ?? (inputTokens !== undefined && outputTokens !== undefined ? inputTokens + outputTokens + cachedTokens : undefined);\n const rawCost = bag['cost'] as { amount?: unknown; currency?: unknown } | undefined;\n const cost = typeof rawCost === 'object' && rawCost !== null && count(rawCost.amount) !== undefined && typeof rawCost.currency === 'string' && rawCost.currency.length > 0\n ? { amount: rawCost.amount as number, currency: rawCost.currency }\n : undefined;\n const reportedWhatItProduced = (outputTokens ?? 0) > 0 || (totalTokens ?? 0) > 0 || cost !== undefined;\n return {\n fullyMeasured: reportedWhatItProduced && bag['tokenUsageComplete'] !== false,\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),\n ...(cost ? { cost } : {}),\n };\n}\n\n/** One open measurement. Scopes nest: a call is credited to its scope and to every scope around it. */\ninterface SpendScope {\n readonly parent: SpendScope | undefined;\n modelCalls: number;\n callsNotFullyMeasured: number;\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n cacheReadTokens?: number;\n readonly cost: Record<string, number>;\n /** The coding runs among those calls (#2232) — see `PlaybookSpend.codingRuns`. */\n readonly codingRuns: BuildRowTally;\n /** The generation steps measured inside this scope (#2232) — see `PlaybookSpend.generationSteps`. */\n readonly generationSteps: BuildRowTally;\n}\n\n/** A running {@link PlaybookSpendBuildRowPart}. */\ninterface BuildRowTally { runs: number; runsWithoutReportedCost: number; totalTokens?: number; cacheReadTokens?: number; readonly cost: Record<string, number> }\n\nconst emptyBuildRowTally = (): BuildRowTally => ({ runs: 0, runsWithoutReportedCost: 0, cost: {} });\n\n/**\n * Add one row's figures to a tally. `madeModelCalls` false (a generation step that called no model: migrations,\n * an e-mail render) means there was nothing to price, so the row is not counted as unpriced.\n */\nfunction addToBuildRowTally(\n tally: BuildRowTally,\n row: { readonly totalTokens?: number; readonly cacheReadTokens?: number; readonly cost?: Readonly<Record<string, number>> },\n madeModelCalls = true,\n): void {\n tally.runs += 1;\n if (madeModelCalls && Object.keys(row.cost ?? {}).length === 0) tally.runsWithoutReportedCost += 1;\n if (row.totalTokens !== undefined) tally.totalTokens = (tally.totalTokens ?? 0) + row.totalTokens;\n if (row.cacheReadTokens !== undefined) tally.cacheReadTokens = (tally.cacheReadTokens ?? 0) + row.cacheReadTokens;\n for (const [currency, amount] of Object.entries(row.cost ?? {})) tally.cost[currency] = (tally.cost[currency] ?? 0) + amount;\n}\n\n/**\n * What a measured unit of work IS to the scopes around it (#2232). A unit whose spend is ALSO recorded on its own\n * build row is tallied apart in every enclosing scope, so a total over playbook runs and build rows counts it once.\n */\nexport enum PlaybookSpendMeasuredUnit {\n /** A build GENERATION STEP: its spend goes on its own row and into each enclosing scope's `generationSteps`. */\n GENERATION_STEP = 'generation_step',\n}\n\n/** What the engine's provider-call recorder is to this meter: something that is told of every physical call. */\nexport interface ProviderCallRecording {\n record(trace: AgentCallTrace): Promise<void>;\n}\n\n/**\n * The companion's spend meter for the playbook lane (#1507) — the host half of\n * `PlaybookSpendMeterPort`.\n *\n * ## Where it listens\n *\n * At the ONE seam every physical model call already passes through: the engine's provider-call\n * recorder (`SAAS_SERVICE_TYPES.ProviderCallRecorder`), which `AgentsBackendService` calls for every\n * call — structured generation, the selector, the judge, deliberation, the research agent and the\n * coding agent alike — BEFORE its traceability gate. The embeddings and document-extraction services\n * call the same recorder, so an embedding or extraction made inside measured work is counted as a\n * model call too: it is a physical provider call that was paid for, and leaving it out would\n * understate the run. The trace sink was rejected for the reason the\n * recorder's own JSDoc gives: it only receives a trace when an observability provider raised the level,\n * so the meter would read zero on every quiet development machine. Instrumenting each call site was\n * rejected because there are more than twenty and the next one would be missed.\n *\n * The recorder is DECORATED through inversify's activation hook ({@link installPlaybookSpendMeter}), so\n * the durable provider-call record is written exactly as before and the meter is told first.\n *\n * ## How it attributes a call\n *\n * By async context. `measure` opens a scope in an `AsyncLocalStorage`; a call made anywhere inside the\n * work — however deep, including in a promise the work started and did not await — is credited to that\n * scope and every scope around it. That is what lets concurrent children of one iteration each carry\n * their own spend, and a lane carry its whole subtree, with no identifier threaded through twenty call\n * sites. Attribution happens inside `invokeAgent`'s own continuation, so a rate limiter, a retry or a\n * run fired and then awaited through a separate settlement is still credited. What this CANNOT see is\n * a model call made from an async context the measured work did not create — a timer or queue set up\n * by another request. No such path exists in the playbook lane (measured 2026-09-24); one added later\n * would go uncounted without marking anything, so `MEASURED` means \"every call this meter observed\n * reported its usage\", exactly as `PlaybookSpendMeasurement.MEASURED` defines it.\n *\n * ## When it cannot see at all\n *\n * If the recorder was never decorated — the engine bound none, or resolved it before the hook was\n * installed — the meter sees nothing, and \"nothing\" must not read as \"spent nothing\". So until the\n * decorator has been activated, every measurement answers NOT OBSERVED.\n */\n/**\n * The default SPEND-RATE runaway breaker, in USD per UTC hour — see\n * {@link PlaybookSpendMeterCompanionService.assertSpendRateBelowRunawayBreaker}.\n *\n * Derived from measurement, not taste (2026-10-01): the busiest hour of a real first creation run\n * (app-creation-test-004) reported $14.33, the market lane's six research agents; a coding build task has cost\n * up to $21.15 a dispatch, and the build lane runs up to three at once, so a heavy legitimate build hour is on\n * the order of $100–150. $500 an hour is far above both: only a loop reaches it.\n */\nexport const PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD = 500;\n\n/** The env override for {@link PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD}. */\nexport const PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_ENV = 'WILDO_PLAYBOOK_SPEND_HOURLY_BREAKER_USD';\n\n/** Refused because reported spend in the current hour reached the runaway breaker — a loop, not a budget. */\nexport class PlaybookSpendRunawayBreakerError extends Error {\n public constructor(public readonly spentUsd: number, public readonly breakerUsd: number) {\n super(\n `Playbook-lane spend runaway breaker tripped: ${Math.round(spentUsd * 100) / 100} USD reported by model calls within `\n + `the current hour (breaker ${breakerUsd} USD). This detects a loop spending at machine speed, not a budget: `\n + `work already done is kept, and nothing new starts until the hour turns. If this rate is intended, raise `\n + `${PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_ENV}, or restart the companion to reset the in-memory tally.`,\n );\n }\n}\n\n@injectable()\nexport class PlaybookSpendMeterCompanionService implements PlaybookSpendMeterPort {\n private readonly scopes = new AsyncLocalStorage<SpendScope>();\n private observing = false;\n /** USD reported in the current UTC hour, by every call this process made — the breaker's tally. */\n private hourlySpend = { hour: '', usd: 0 };\n /** The clock, replaceable in tests. */\n protected now: () => Date = () => new Date();\n\n /** Called by the recorder decorator on activation: from now on a call this process makes is seen. */\n public markObserving(): void {\n this.observing = true;\n }\n\n /** Whether model calls are actually reaching this meter. */\n public isObserving(): boolean {\n return this.observing;\n }\n\n /**\n * The SPEND-RATE runaway breaker (2026-10-01) — the money twin of the lane's call-rate breaker, and like it\n * emphatically NOT a budget.\n *\n * Paul, 2026-10-01: \"we need to do not stop things face to spending, else enormous amounts\". Spending is the\n * lane's normal state (and 2026-08-24: \"we are here to spend\"), so nothing is refused for ordinary cost and no\n * per-run or per-day quota exists. What is refused is an ENORMOUS rate: reported USD within one UTC hour at or\n * above {@link PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD}. A rate, never a running total, for the call\n * breaker's reason: a legitimate heavy day accumulates slowly and cannot trip it; a loop trips within the hour.\n *\n * Why money and not only calls: the call breaker counts calls (1000/hour), and the expensive work is few\n * calls — a research agent is ONE call at up to $4, a coding build task one dispatch at up to $21 — so a loop\n * re-dispatching agents could spend hundreds of dollars an hour without tripping it.\n *\n * Checked BEFORE work starts (every playbook run, every structured generation), never mid-call: an agent\n * already running finishes and its work is kept. Only reported USD counts — a structured generation reports\n * tokens and no price, so a generation loop is the call breaker's to catch. The tally is a runtime cache:\n * a restart resets it, which is the documented door beside the env override.\n */\n public assertSpendRateBelowRunawayBreaker(): void {\n const hour = this.now().toISOString().slice(0, 13);\n if (this.hourlySpend.hour !== hour) return;\n const configured = Number(process.env[PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_ENV]);\n const breaker = Number.isFinite(configured) && configured > 0 ? configured : PLAYBOOK_SPEND_HOURLY_RUNAWAY_BREAKER_USD;\n if (this.hourlySpend.usd >= breaker) throw new PlaybookSpendRunawayBreakerError(this.hourlySpend.usd, breaker);\n }\n\n /** USD reported in the current UTC hour, for a status read. */\n public spendThisHourUsd(): number {\n return this.hourlySpend.hour === this.now().toISOString().slice(0, 13) ? this.hourlySpend.usd : 0;\n }\n\n /** Credit one physical model call to every measurement open in the current async context. */\n public observe(trace: AgentCallTrace): void {\n const usage = readModelCallUsage(trace.context?.usage);\n // The breaker's tally sees every call this process makes, inside a measurement or not.\n if (usage.cost?.currency === 'USD') {\n const hour = this.now().toISOString().slice(0, 13);\n this.hourlySpend = { hour, usd: (this.hourlySpend.hour === hour ? this.hourlySpend.usd : 0) + usage.cost.amount };\n }\n for (let scope = this.scopes.getStore(); scope !== undefined; scope = scope.parent) {\n scope.modelCalls += 1;\n if (!usage.fullyMeasured) scope.callsNotFullyMeasured += 1;\n if (usage.inputTokens !== undefined) scope.inputTokens = (scope.inputTokens ?? 0) + usage.inputTokens;\n if (usage.outputTokens !== undefined) scope.outputTokens = (scope.outputTokens ?? 0) + usage.outputTokens;\n if (usage.totalTokens !== undefined) scope.totalTokens = (scope.totalTokens ?? 0) + usage.totalTokens;\n if (usage.cacheReadTokens !== undefined) scope.cacheReadTokens = (scope.cacheReadTokens ?? 0) + usage.cacheReadTokens;\n if (usage.cost) scope.cost[usage.cost.currency] = (scope.cost[usage.cost.currency] ?? 0) + usage.cost.amount;\n /*\n * A coding run is ONE call on this seam (the engine traces the whole session once, with its merged\n * usage), so a call by a coding agent IS a run. Tallied apart because the same run is also on its build\n * task's row, and a total across both must not count it twice (`PlaybookSpend.codingRuns`).\n */\n if (isApplicationCodingAgentRef(trace.agentRef)) {\n addToBuildRowTally(scope.codingRuns, {\n ...(usage.totalTokens !== undefined ? { totalTokens: usage.totalTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cost ? { cost: { [usage.cost.currency]: usage.cost.amount } } : {}),\n });\n }\n }\n }\n\n /**\n * Run `work` and report what the model calls inside it reported. `as` names a unit whose spend is also recorded\n * on its own build row (a generation step): every enclosing scope then tallies it in its matching part, once the\n * unit settles, so the scopes' totals still include it and a reader can leave it out of a sum with the rows.\n */\n public async measure<T>(work: () => Promise<T>, options: { readonly as?: PlaybookSpendMeasuredUnit } = {}): Promise<PlaybookMeasuredWork<T>> {\n const scope: SpendScope = {\n parent: this.scopes.getStore(), modelCalls: 0, callsNotFullyMeasured: 0, cost: {},\n codingRuns: emptyBuildRowTally(), generationSteps: emptyBuildRowTally(),\n };\n const settled = await this.scopes.run(scope, async (): Promise<PromiseSettledResult<T>> => {\n try {\n return { status: 'fulfilled', value: await work() };\n } catch (reason) {\n return { status: 'rejected', reason };\n }\n });\n /*\n * A generation step never dispatches a coding agent (`isApplicationCodingAgentRef` is reached only by the coding\n * dispatcher), so its calls are never also in an enclosing `codingRuns`; the two parts never overlap, and a total\n * that subtracts both subtracts nothing twice. A step that did would need its coding part taken out of this tally.\n */\n if (options.as === PlaybookSpendMeasuredUnit.GENERATION_STEP) {\n for (let enclosing = scope.parent; enclosing !== undefined; enclosing = enclosing.parent) {\n addToBuildRowTally(enclosing.generationSteps, scope, scope.modelCalls > 0);\n }\n }\n return { settled, spend: this.observing ? spendOfScope(scope) : PLAYBOOK_SPEND_NOT_OBSERVED };\n }\n}\n\nfunction spendOfScope(scope: SpendScope): PlaybookSpend {\n const counts = { modelCalls: scope.modelCalls, callsNotFullyMeasured: scope.callsNotFullyMeasured, unobservedSegments: 0 };\n const round = (value: number): number => Math.round(value * 1e6) / 1e6;\n return {\n measurement: classifyPlaybookSpend(counts),\n ...counts,\n ...(scope.inputTokens !== undefined ? { inputTokens: scope.inputTokens } : {}),\n ...(scope.outputTokens !== undefined ? { outputTokens: scope.outputTokens } : {}),\n ...(scope.totalTokens !== undefined ? { totalTokens: scope.totalTokens } : {}),\n ...(scope.cacheReadTokens !== undefined ? { cacheReadTokens: scope.cacheReadTokens } : {}),\n ...(Object.keys(scope.cost).length > 0 ? { cost: Object.fromEntries(Object.entries(scope.cost).map(([currency, amount]) => [currency, round(amount)])) } : {}),\n /*\n * Both parts ALWAYS stated once the meter observes, `runs: 0` included (#2232 review F5): an ABSENT part must mean \"recorded\n * before the part existed\", which is what lets a total over these rows and the build rows tell a playbook that\n * started no coding run from one whose coding runs it cannot see, and so name the second as possibly counted twice.\n *\n * A resumed coding run is not counted twice here either: the resume continues the SAME execution and row\n * (`resumeActorExecution`) and arrives through its own request (`/creation/questions/answer`), so it is outside\n * the async context of the run that parked it. That parking run's scope saw the first leg's cumulative cost; the\n * row carries the session's final total, which the journey sums once.\n */\n codingRuns: buildRowPartOfTally(scope.codingRuns, round),\n generationSteps: buildRowPartOfTally(scope.generationSteps, round),\n };\n}\n\nfunction buildRowPartOfTally(part: BuildRowTally, round: (value: number) => number): PlaybookSpendBuildRowPart {\n return {\n runs: part.runs,\n runsWithoutReportedCost: part.runsWithoutReportedCost,\n ...(part.totalTokens !== undefined ? { totalTokens: part.totalTokens } : {}),\n ...(part.cacheReadTokens !== undefined ? { cacheReadTokens: part.cacheReadTokens } : {}),\n ...(Object.keys(part.cost).length > 0 ? { cost: Object.fromEntries(Object.entries(part.cost).map(([currency, amount]) => [currency, round(amount)])) } : {}),\n };\n}\n\n/**\n * Decorate the engine's provider-call recorder so every physical model call is also told to the meter\n * (#1507). Registered as an ACTIVATION, not a rebind: the engine's recorder stays the binding and keeps\n * writing its durable record — the meter is told first and cannot fail the call, because `observe` does\n * nothing that throws on a well-formed trace and is guarded besides.\n *\n * Must run before anything resolves `AgentsBackendService` — the same constraint the companion's trace\n * sink composition already lives under, and installed beside it. If it runs too late the meter simply\n * never starts observing, and says so (NOT OBSERVED) rather than reporting zero.\n */\nexport function installPlaybookSpendMeter(container: InversifyContainer, meter: PlaybookSpendMeterCompanionService): void {\n container.onActivation<ProviderCallRecording>(SAAS_SERVICE_TYPES.ProviderCallRecorder, (_context, recorder) => {\n meter.markObserving();\n return {\n record: async (trace: AgentCallTrace): Promise<void> => {\n try {\n meter.observe(trace);\n } catch {\n // Metering is a report: it must never turn a provider call, or its durable record, into a failure.\n }\n await recorder.record(trace);\n },\n };\n });\n}\n"]}
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@wildo-ai/dev-companion",
3
- "version": "1.1.8",
3
+ "version": "1.1.9",
4
4
  "description": "Wildo.ai Dev Companion — local development management and introspection service. Canonical source home; applications receive only the built dist below their .wildo-saas/wildo-dev-companion drop.",
5
5
  "author": "Wildo AI",
6
6
  "license": "SEE LICENSE IN LICENSE",
7
7
  "type": "module",
8
+ "bin": {
9
+ "wildo-dev-companion-supervised": "./bin/wildo-dev-companion-supervised.mjs"
10
+ },
8
11
  "exports": {
9
12
  ".": {
10
13
  "types": "./dist/esm/index.d.ts",
@@ -16,7 +19,8 @@
16
19
  "module": "./dist/esm/index.js",
17
20
  "types": "./dist/esm/index.d.ts",
18
21
  "files": [
19
- "dist/"
22
+ "dist/",
23
+ "bin/"
20
24
  ],
21
25
  "scripts": {
22
26
  "build": "tsc -p tsconfig.build.json && node ../../../scripts/run-tsc-alias-safe.mjs --project tsconfig.build.json --dist dist/esm",
@@ -32,22 +36,22 @@
32
36
  "dependencies": {
33
37
  "@react-email/components": "^1.0.8",
34
38
  "@react-email/render": "^2.0.4",
35
- "@wildo-ai/application-creation-runtime": "1.1.8",
36
- "@wildo-ai/external-connectors-models": "1.1.8",
37
- "@wildo-ai/framework-knowledge": "1.1.8",
38
- "@wildo-ai/platform-config-lib": "1.1.8",
39
- "@wildo-ai/platform-core-backend": "1.1.8",
40
- "@wildo-ai/platform-core-shared": "1.1.8",
41
- "@wildo-ai/platform-shared-lib": "1.1.8",
42
- "@wildo-ai/presets-components-models": "1.1.8",
43
- "@wildo-ai/saas-backend-lib": "1.1.8",
44
- "@wildo-ai/saas-frontend-lib": "1.1.8",
45
- "@wildo-ai/saas-models": "1.1.8",
46
- "@wildo-ai/saas-specifications": "1.1.8",
47
- "@wildo-ai/saas-technical-doc": "1.1.8",
48
- "@wildo-ai/saas-website": "1.1.8",
49
- "@wildo-ai/wildo-module-client": "1.1.8",
50
- "@wildo-ai/zod-decorators": "1.1.8",
39
+ "@wildo-ai/application-creation-runtime": "1.1.9",
40
+ "@wildo-ai/external-connectors-models": "1.1.9",
41
+ "@wildo-ai/framework-knowledge": "1.1.9",
42
+ "@wildo-ai/platform-config-lib": "1.1.9",
43
+ "@wildo-ai/platform-core-backend": "1.1.9",
44
+ "@wildo-ai/platform-core-shared": "1.1.9",
45
+ "@wildo-ai/platform-shared-lib": "1.1.9",
46
+ "@wildo-ai/presets-components-models": "1.1.9",
47
+ "@wildo-ai/saas-backend-lib": "1.1.9",
48
+ "@wildo-ai/saas-frontend-lib": "1.1.9",
49
+ "@wildo-ai/saas-models": "1.1.9",
50
+ "@wildo-ai/saas-specifications": "1.1.9",
51
+ "@wildo-ai/saas-technical-doc": "1.1.9",
52
+ "@wildo-ai/saas-website": "1.1.9",
53
+ "@wildo-ai/wildo-module-client": "1.1.9",
54
+ "@wildo-ai/zod-decorators": "1.1.9",
51
55
  "big.js": "^6.2.2",
52
56
  "cors": "^2.8.5",
53
57
  "date-fns": "^4.1.0",