@terreno/ai 57.9.0 → 57.10.1

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 (412) hide show
  1. package/README.md +1 -0
  2. package/bunfig.toml +1 -1
  3. package/dist/aiApp.d.ts +8 -2
  4. package/dist/aiApp.js +12 -6
  5. package/dist/harness/adminScreens.d.ts +6 -0
  6. package/dist/harness/adminScreens.js +11 -0
  7. package/dist/harness/agentLoop.d.ts +61 -0
  8. package/dist/harness/agentLoop.js +798 -0
  9. package/dist/harness/agentTaskNames.d.ts +4 -0
  10. package/dist/harness/agentTaskNames.js +7 -0
  11. package/dist/harness/approvalPolicy.d.ts +3 -0
  12. package/dist/harness/approvalPolicy.js +23 -0
  13. package/dist/harness/approvals.d.ts +101 -0
  14. package/dist/harness/approvals.js +468 -0
  15. package/dist/harness/commit.d.ts +238 -0
  16. package/dist/harness/commit.js +678 -0
  17. package/dist/harness/conversation.d.ts +75 -0
  18. package/dist/harness/conversation.js +397 -0
  19. package/dist/harness/defineAgent.d.ts +9 -0
  20. package/dist/harness/defineAgent.js +65 -0
  21. package/dist/harness/defineTask.d.ts +11 -0
  22. package/dist/harness/defineTask.js +59 -0
  23. package/dist/harness/defineTool.d.ts +7 -0
  24. package/dist/harness/defineTool.js +36 -0
  25. package/dist/harness/definitionError.d.ts +8 -0
  26. package/dist/harness/definitionError.js +15 -0
  27. package/dist/harness/errors.d.ts +127 -0
  28. package/dist/harness/errors.js +101 -0
  29. package/dist/harness/eventHub.d.ts +45 -0
  30. package/dist/harness/eventHub.js +135 -0
  31. package/dist/harness/events.d.ts +95 -0
  32. package/dist/harness/events.js +267 -0
  33. package/dist/harness/executionEnv.d.ts +31 -0
  34. package/dist/harness/executionEnv.js +2 -0
  35. package/dist/harness/extensions.d.ts +82 -0
  36. package/dist/harness/extensions.js +274 -0
  37. package/dist/harness/harness.d.ts +163 -0
  38. package/dist/harness/harness.js +520 -0
  39. package/dist/harness/harnessApp.d.ts +44 -0
  40. package/dist/harness/harnessApp.js +62 -0
  41. package/dist/harness/internalRuntime.d.ts +16 -0
  42. package/dist/harness/internalRuntime.js +18 -0
  43. package/dist/harness/leases.d.ts +35 -0
  44. package/dist/harness/leases.js +86 -0
  45. package/dist/harness/memo.d.ts +24 -0
  46. package/dist/harness/memo.js +78 -0
  47. package/dist/harness/modelCall.d.ts +45 -0
  48. package/dist/harness/modelCall.js +147 -0
  49. package/dist/harness/models/harnessApproval.d.ts +2 -0
  50. package/dist/harness/models/harnessApproval.js +100 -0
  51. package/dist/harness/models/harnessConversation.d.ts +2 -0
  52. package/dist/harness/models/harnessConversation.js +117 -0
  53. package/dist/harness/models/harnessEvent.d.ts +3 -0
  54. package/dist/harness/models/harnessEvent.js +73 -0
  55. package/dist/harness/models/harnessInboxEvent.d.ts +2 -0
  56. package/dist/harness/models/harnessInboxEvent.js +58 -0
  57. package/dist/harness/models/harnessMemo.d.ts +2 -0
  58. package/dist/harness/models/harnessMemo.js +42 -0
  59. package/dist/harness/models/harnessMessage.d.ts +2 -0
  60. package/dist/harness/models/harnessMessage.js +73 -0
  61. package/dist/harness/models/harnessOwner.d.ts +2 -0
  62. package/dist/harness/models/harnessOwner.js +36 -0
  63. package/dist/harness/models/harnessTask.d.ts +2 -0
  64. package/dist/harness/models/harnessTask.js +186 -0
  65. package/dist/harness/ownership.d.ts +89 -0
  66. package/dist/harness/ownership.js +438 -0
  67. package/dist/harness/registry.d.ts +29 -0
  68. package/dist/harness/registry.js +93 -0
  69. package/dist/harness/retryBackoff.d.ts +31 -0
  70. package/dist/harness/retryBackoff.js +50 -0
  71. package/dist/harness/routes/approvals.d.ts +13 -0
  72. package/dist/harness/routes/approvals.js +93 -0
  73. package/dist/harness/routes/conversations.d.ts +11 -0
  74. package/dist/harness/routes/conversations.js +66 -0
  75. package/dist/harness/routes/events.d.ts +19 -0
  76. package/dist/harness/routes/events.js +215 -0
  77. package/dist/harness/routes/tasks.d.ts +11 -0
  78. package/dist/harness/routes/tasks.js +108 -0
  79. package/dist/harness/runners/inProcessRunner.d.ts +57 -0
  80. package/dist/harness/runners/inProcessRunner.js +196 -0
  81. package/dist/harness/runtime.d.ts +34 -0
  82. package/dist/harness/runtime.js +551 -0
  83. package/dist/harness/subagent.d.ts +53 -0
  84. package/dist/harness/subagent.js +134 -0
  85. package/dist/harness/suspend.d.ts +8 -0
  86. package/dist/harness/suspend.js +16 -0
  87. package/dist/harness/transaction.d.ts +3 -0
  88. package/dist/harness/transaction.js +22 -0
  89. package/dist/harness/waits.d.ts +100 -0
  90. package/dist/harness/waits.js +214 -0
  91. package/dist/index.d.ts +19 -1
  92. package/dist/index.js +45 -2
  93. package/dist/models/aiDataset.d.ts +2 -0
  94. package/dist/models/aiDataset.js +67 -0
  95. package/dist/models/aiRequest.js +1 -1
  96. package/dist/models/gptHistory.js +73 -0
  97. package/dist/observability/adminScreens.d.ts +5 -0
  98. package/dist/observability/adminScreens.js +32 -0
  99. package/dist/observability/compileTemplate.d.ts +1 -0
  100. package/dist/observability/compileTemplate.js +13 -0
  101. package/dist/observability/datasetImport.d.ts +11 -0
  102. package/dist/observability/datasetImport.js +185 -0
  103. package/dist/observability/evaluate.d.ts +31 -0
  104. package/dist/observability/evaluate.js +200 -0
  105. package/dist/observability/evaluatorTemplates.d.ts +17 -0
  106. package/dist/observability/evaluatorTemplates.js +111 -0
  107. package/dist/observability/jsonPath.d.ts +2 -0
  108. package/dist/observability/jsonPath.js +57 -0
  109. package/dist/observability/local/datasetStore.d.ts +87 -0
  110. package/dist/observability/local/datasetStore.js +326 -0
  111. package/dist/observability/local/evaluatorStore.d.ts +44 -0
  112. package/dist/observability/local/evaluatorStore.js +182 -0
  113. package/dist/observability/local/experimentRunner.d.ts +96 -0
  114. package/dist/observability/local/experimentRunner.js +419 -0
  115. package/dist/observability/local/localPlugin.d.ts +22 -0
  116. package/dist/observability/local/localPlugin.js +76 -0
  117. package/dist/observability/local/models/obsDataset.d.ts +2 -0
  118. package/dist/observability/local/models/obsDataset.js +37 -0
  119. package/dist/observability/local/models/obsDatasetItem.d.ts +2 -0
  120. package/dist/observability/local/models/obsDatasetItem.js +76 -0
  121. package/dist/observability/local/models/obsEvaluator.d.ts +2 -0
  122. package/dist/observability/local/models/obsEvaluator.js +98 -0
  123. package/dist/observability/local/models/obsExperiment.d.ts +2 -0
  124. package/dist/observability/local/models/obsExperiment.js +87 -0
  125. package/dist/observability/local/models/obsExperimentItem.d.ts +2 -0
  126. package/dist/observability/local/models/obsExperimentItem.js +45 -0
  127. package/dist/observability/local/models/obsPrompt.d.ts +2 -0
  128. package/dist/observability/local/models/obsPrompt.js +42 -0
  129. package/dist/observability/local/models/obsPromptLabel.d.ts +2 -0
  130. package/dist/observability/local/models/obsPromptLabel.js +39 -0
  131. package/dist/observability/local/models/obsPromptVersion.d.ts +2 -0
  132. package/dist/observability/local/models/obsPromptVersion.js +96 -0
  133. package/dist/observability/local/models/obsReviewItem.d.ts +2 -0
  134. package/dist/observability/local/models/obsReviewItem.js +75 -0
  135. package/dist/observability/local/models/obsScore.d.ts +2 -0
  136. package/dist/observability/local/models/obsScore.js +58 -0
  137. package/dist/observability/local/models/obsSpan.d.ts +2 -0
  138. package/dist/observability/local/models/obsSpan.js +64 -0
  139. package/dist/observability/local/models/obsTrace.d.ts +2 -0
  140. package/dist/observability/local/models/obsTrace.js +93 -0
  141. package/dist/observability/local/promptStore.d.ts +180 -0
  142. package/dist/observability/local/promptStore.js +444 -0
  143. package/dist/observability/local/reviewStore.d.ts +50 -0
  144. package/dist/observability/local/reviewStore.js +203 -0
  145. package/dist/observability/local/traceStore.d.ts +103 -0
  146. package/dist/observability/local/traceStore.js +325 -0
  147. package/dist/observability/observabilityApp.d.ts +24 -0
  148. package/dist/observability/observabilityApp.js +157 -0
  149. package/dist/observability/observabilityAppRegistry.d.ts +14 -0
  150. package/dist/observability/observabilityAppRegistry.js +16 -0
  151. package/dist/observability/permissions.d.ts +7 -0
  152. package/dist/observability/permissions.js +60 -0
  153. package/dist/observability/reviewPanels.d.ts +18 -0
  154. package/dist/observability/reviewPanels.js +46 -0
  155. package/dist/observability/routes/datasets.d.ts +7 -0
  156. package/dist/observability/routes/datasets.js +149 -0
  157. package/dist/observability/routes/evaluators.d.ts +7 -0
  158. package/dist/observability/routes/evaluators.js +123 -0
  159. package/dist/observability/routes/experiments.d.ts +7 -0
  160. package/dist/observability/routes/experiments.js +95 -0
  161. package/dist/observability/routes/observabilityRouteAccess.d.ts +13 -0
  162. package/dist/observability/routes/observabilityRouteAccess.js +67 -0
  163. package/dist/observability/routes/prompts.d.ts +12 -0
  164. package/dist/observability/routes/prompts.js +172 -0
  165. package/dist/observability/routes/requestAiService.d.ts +13 -0
  166. package/dist/observability/routes/requestAiService.js +21 -0
  167. package/dist/observability/routes/review.d.ts +7 -0
  168. package/dist/observability/routes/review.js +79 -0
  169. package/dist/observability/routes/status.d.ts +5 -0
  170. package/dist/observability/routes/status.js +31 -0
  171. package/dist/observability/routes/testMultiStage.d.ts +9 -0
  172. package/dist/observability/routes/testMultiStage.js +67 -0
  173. package/dist/observability/routes/traces.d.ts +7 -0
  174. package/dist/observability/routes/traces.js +129 -0
  175. package/dist/observability/schemaValidation.d.ts +5 -0
  176. package/dist/observability/schemaValidation.js +26 -0
  177. package/dist/observability/sopThresholds.d.ts +2 -0
  178. package/dist/observability/sopThresholds.js +21 -0
  179. package/dist/observability/status.d.ts +23 -0
  180. package/dist/observability/status.js +34 -0
  181. package/dist/observability/testMultiStageSchemas.d.ts +10 -0
  182. package/dist/observability/testMultiStageSchemas.js +79 -0
  183. package/dist/observability/testMultiStageWorkflow.d.ts +20 -0
  184. package/dist/observability/testMultiStageWorkflow.js +218 -0
  185. package/dist/observability/types.d.ts +159 -0
  186. package/dist/observability/types.js +67 -0
  187. package/dist/routes/files.js +18 -7
  188. package/dist/routes/gpt.js +79 -689
  189. package/dist/routes/gptActions.d.ts +9 -0
  190. package/dist/routes/gptActions.js +212 -0
  191. package/dist/routes/gptDatasets.d.ts +5 -0
  192. package/dist/routes/gptDatasets.js +94 -0
  193. package/dist/routes/gptHistories.d.ts +3 -1
  194. package/dist/routes/gptHistories.js +188 -2
  195. package/dist/service/aiDatasets.d.ts +57 -0
  196. package/dist/service/aiDatasets.js +253 -0
  197. package/dist/service/aiService.d.ts +50 -1
  198. package/dist/service/aiService.js +426 -77
  199. package/dist/service/askFiles.d.ts +49 -0
  200. package/dist/service/askFiles.js +162 -0
  201. package/dist/service/asks.d.ts +76 -0
  202. package/dist/service/asks.js +284 -0
  203. package/dist/service/chatTurn.d.ts +128 -0
  204. package/dist/service/chatTurn.js +1674 -0
  205. package/dist/service/fileStorage.d.ts +4 -0
  206. package/dist/service/fileStorage.js +7 -2
  207. package/dist/service/fillActionIds.d.ts +6 -0
  208. package/dist/service/fillActionIds.js +79 -0
  209. package/dist/service/jsonFenceModel.d.ts +7 -0
  210. package/dist/service/jsonFenceModel.js +45 -0
  211. package/dist/service/prompts.d.ts +52 -0
  212. package/dist/service/prompts.js +96 -1
  213. package/dist/service/sanitizeHtml.d.ts +11 -0
  214. package/dist/service/sanitizeHtml.js +108 -0
  215. package/dist/types/harness.d.ts +934 -0
  216. package/dist/types/harness.js +133 -0
  217. package/dist/types/index.d.ts +192 -14
  218. package/dist/types/index.js +2 -0
  219. package/dist/types/observability.d.ts +288 -0
  220. package/dist/types/observability.js +2 -0
  221. package/package.json +17 -5
  222. package/src/aiApp.test.ts +207 -1
  223. package/src/aiApp.ts +19 -6
  224. package/src/harness/adminScreens.test.ts +34 -0
  225. package/src/harness/adminScreens.ts +11 -0
  226. package/src/harness/agentLoop.test.ts +1034 -0
  227. package/src/harness/agentLoop.ts +1082 -0
  228. package/src/harness/agentRecovery.test.ts +380 -0
  229. package/src/harness/agentTaskNames.ts +4 -0
  230. package/src/harness/approvalPolicy.ts +28 -0
  231. package/src/harness/approvals.test.ts +1094 -0
  232. package/src/harness/approvals.ts +644 -0
  233. package/src/harness/commit.ts +1049 -0
  234. package/src/harness/conversation.ts +503 -0
  235. package/src/harness/defineAgent.test.ts +92 -0
  236. package/src/harness/defineAgent.ts +82 -0
  237. package/src/harness/defineTask.test.ts +59 -0
  238. package/src/harness/defineTask.ts +76 -0
  239. package/src/harness/defineTool.ts +45 -0
  240. package/src/harness/definitionError.ts +13 -0
  241. package/src/harness/errors.test.ts +90 -0
  242. package/src/harness/errors.ts +119 -0
  243. package/src/harness/eventHub.test.ts +124 -0
  244. package/src/harness/eventHub.ts +159 -0
  245. package/src/harness/events.test.ts +757 -0
  246. package/src/harness/events.ts +384 -0
  247. package/src/harness/executionEnv.ts +34 -0
  248. package/src/harness/extensions.test.ts +1218 -0
  249. package/src/harness/extensions.ts +382 -0
  250. package/src/harness/harness.test.ts +693 -0
  251. package/src/harness/harness.ts +767 -0
  252. package/src/harness/harnessApp.ts +76 -0
  253. package/src/harness/internalRuntime.ts +44 -0
  254. package/src/harness/leases.ts +132 -0
  255. package/src/harness/memo.ts +107 -0
  256. package/src/harness/modelCall.test.ts +134 -0
  257. package/src/harness/modelCall.ts +200 -0
  258. package/src/harness/models/harnessApproval.ts +109 -0
  259. package/src/harness/models/harnessConversation.ts +142 -0
  260. package/src/harness/models/harnessEvent.ts +92 -0
  261. package/src/harness/models/harnessInboxEvent.ts +73 -0
  262. package/src/harness/models/harnessMemo.ts +43 -0
  263. package/src/harness/models/harnessMessage.ts +85 -0
  264. package/src/harness/models/harnessModels.test.ts +60 -0
  265. package/src/harness/models/harnessOwner.ts +40 -0
  266. package/src/harness/models/harnessTask.ts +201 -0
  267. package/src/harness/ownership.test.ts +1087 -0
  268. package/src/harness/ownership.ts +618 -0
  269. package/src/harness/recovery.test.ts +912 -0
  270. package/src/harness/registry.ts +124 -0
  271. package/src/harness/retries.test.ts +292 -0
  272. package/src/harness/retryBackoff.test.ts +100 -0
  273. package/src/harness/retryBackoff.ts +77 -0
  274. package/src/harness/routes/approvals.ts +123 -0
  275. package/src/harness/routes/conversations.test.ts +518 -0
  276. package/src/harness/routes/conversations.ts +102 -0
  277. package/src/harness/routes/events.ts +280 -0
  278. package/src/harness/routes/tasks.test.ts +198 -0
  279. package/src/harness/routes/tasks.ts +146 -0
  280. package/src/harness/runners/inProcessRunner.test.ts +402 -0
  281. package/src/harness/runners/inProcessRunner.ts +220 -0
  282. package/src/harness/runtime.ts +714 -0
  283. package/src/harness/subagent.test.ts +696 -0
  284. package/src/harness/subagent.ts +192 -0
  285. package/src/harness/suspend.ts +13 -0
  286. package/src/harness/transaction.ts +17 -0
  287. package/src/harness/versioning.test.ts +288 -0
  288. package/src/harness/waits.test.ts +693 -0
  289. package/src/harness/waits.ts +356 -0
  290. package/src/index.test.ts +13 -0
  291. package/src/index.ts +70 -0
  292. package/src/isolated/adminScreensConfig.isolated.ts +143 -0
  293. package/src/models/aiDataset.test.ts +34 -0
  294. package/src/models/aiDataset.ts +78 -0
  295. package/src/models/aiRequest.ts +2 -1
  296. package/src/models/gptHistory.test.ts +156 -0
  297. package/src/models/gptHistory.ts +89 -1
  298. package/src/observability/adminScreens.test.ts +71 -0
  299. package/src/observability/adminScreens.ts +42 -0
  300. package/src/observability/compileTemplate.test.ts +14 -0
  301. package/src/observability/compileTemplate.ts +10 -0
  302. package/src/observability/datasetImport.test.ts +95 -0
  303. package/src/observability/datasetImport.ts +220 -0
  304. package/src/observability/evaluate.test.ts +549 -0
  305. package/src/observability/evaluate.ts +254 -0
  306. package/src/observability/evaluatorTemplates.ts +124 -0
  307. package/src/observability/jsonPath.test.ts +52 -0
  308. package/src/observability/jsonPath.ts +60 -0
  309. package/src/observability/local/datasetStore.test.ts +230 -0
  310. package/src/observability/local/datasetStore.ts +452 -0
  311. package/src/observability/local/evaluatorStore.test.ts +138 -0
  312. package/src/observability/local/evaluatorStore.ts +224 -0
  313. package/src/observability/local/experimentRunner.test.ts +489 -0
  314. package/src/observability/local/experimentRunner.ts +548 -0
  315. package/src/observability/local/localPlugin.ts +88 -0
  316. package/src/observability/local/models/obsDataset.ts +38 -0
  317. package/src/observability/local/models/obsDatasetItem.ts +80 -0
  318. package/src/observability/local/models/obsEvaluator.ts +102 -0
  319. package/src/observability/local/models/obsExperiment.ts +91 -0
  320. package/src/observability/local/models/obsExperimentItem.ts +52 -0
  321. package/src/observability/local/models/obsPrompt.ts +43 -0
  322. package/src/observability/local/models/obsPromptLabel.ts +43 -0
  323. package/src/observability/local/models/obsPromptVersion.ts +107 -0
  324. package/src/observability/local/models/obsReviewItem.ts +79 -0
  325. package/src/observability/local/models/obsScore.ts +59 -0
  326. package/src/observability/local/models/obsSpan.ts +65 -0
  327. package/src/observability/local/models/obsTrace.ts +94 -0
  328. package/src/observability/local/obsModels.test.ts +119 -0
  329. package/src/observability/local/promptStore.test.ts +351 -0
  330. package/src/observability/local/promptStore.ts +665 -0
  331. package/src/observability/local/reviewStore.test.ts +164 -0
  332. package/src/observability/local/reviewStore.ts +264 -0
  333. package/src/observability/local/traceStore.test.ts +264 -0
  334. package/src/observability/local/traceStore.ts +440 -0
  335. package/src/observability/observabilityApp.test.ts +92 -0
  336. package/src/observability/observabilityApp.ts +185 -0
  337. package/src/observability/observabilityAppRegistry.test.ts +30 -0
  338. package/src/observability/observabilityAppRegistry.ts +35 -0
  339. package/src/observability/permissions.test.ts +96 -0
  340. package/src/observability/permissions.ts +78 -0
  341. package/src/observability/reviewPanels.test.ts +35 -0
  342. package/src/observability/reviewPanels.ts +64 -0
  343. package/src/observability/routes/datasets.test.ts +176 -0
  344. package/src/observability/routes/datasets.ts +252 -0
  345. package/src/observability/routes/evaluators.test.ts +119 -0
  346. package/src/observability/routes/evaluators.ts +207 -0
  347. package/src/observability/routes/experiments.test.ts +282 -0
  348. package/src/observability/routes/experiments.ts +152 -0
  349. package/src/observability/routes/observabilityRbac.test.ts +767 -0
  350. package/src/observability/routes/observabilityRouteAccess.ts +106 -0
  351. package/src/observability/routes/prompts.test.ts +320 -0
  352. package/src/observability/routes/prompts.ts +263 -0
  353. package/src/observability/routes/requestAiService.ts +36 -0
  354. package/src/observability/routes/review.test.ts +120 -0
  355. package/src/observability/routes/review.ts +125 -0
  356. package/src/observability/routes/status.test.ts +116 -0
  357. package/src/observability/routes/status.ts +47 -0
  358. package/src/observability/routes/testMultiStage.test.ts +214 -0
  359. package/src/observability/routes/testMultiStage.ts +96 -0
  360. package/src/observability/routes/traces.test.ts +167 -0
  361. package/src/observability/routes/traces.ts +172 -0
  362. package/src/observability/schemaValidation.ts +29 -0
  363. package/src/observability/sopThresholds.ts +20 -0
  364. package/src/observability/status.test.ts +38 -0
  365. package/src/observability/status.ts +56 -0
  366. package/src/observability/testMultiStageSchemas.ts +95 -0
  367. package/src/observability/testMultiStageWorkflow.test.ts +114 -0
  368. package/src/observability/testMultiStageWorkflow.ts +307 -0
  369. package/src/observability/types.ts +262 -0
  370. package/src/routes/files.test.ts +63 -9
  371. package/src/routes/files.ts +21 -7
  372. package/src/routes/gpt.test.ts +3279 -0
  373. package/src/routes/gpt.ts +91 -816
  374. package/src/routes/gptActions.test.ts +241 -0
  375. package/src/routes/gptActions.ts +255 -0
  376. package/src/routes/gptApprovals.test.ts +762 -0
  377. package/src/routes/gptDatasets.test.ts +86 -0
  378. package/src/routes/gptDatasets.ts +104 -0
  379. package/src/routes/gptFiles.test.ts +589 -0
  380. package/src/routes/gptHistories.test.ts +933 -0
  381. package/src/routes/gptHistories.ts +266 -5
  382. package/src/routes/routes.test.ts +222 -2
  383. package/src/service/aiDatasets.test.ts +123 -0
  384. package/src/service/aiDatasets.ts +316 -0
  385. package/src/service/aiService.test.ts +593 -0
  386. package/src/service/aiService.ts +568 -111
  387. package/src/service/askFiles.test.ts +96 -0
  388. package/src/service/askFiles.ts +222 -0
  389. package/src/service/asks.test.ts +946 -0
  390. package/src/service/asks.ts +423 -0
  391. package/src/service/chatTurn.ts +2287 -0
  392. package/src/service/fileStorage.test.ts +11 -0
  393. package/src/service/fileStorage.ts +10 -2
  394. package/src/service/fillActionIds.test.ts +65 -0
  395. package/src/service/fillActionIds.ts +98 -0
  396. package/src/service/jsonFenceModel.test.ts +47 -0
  397. package/src/service/jsonFenceModel.ts +53 -0
  398. package/src/service/prompts.test.ts +21 -0
  399. package/src/service/prompts.ts +147 -0
  400. package/src/service/sanitizeHtml.test.ts +61 -0
  401. package/src/service/sanitizeHtml.ts +109 -0
  402. package/src/tests/bunSetup.test.ts +7 -4
  403. package/src/tests/bunSetup.ts +7 -7
  404. package/src/tests/chatHarness.ts +478 -0
  405. package/src/tests/generateStream.ts +49 -0
  406. package/src/tests/harnessErrors.ts +22 -0
  407. package/src/tests/harnessStreaming.ts +227 -0
  408. package/src/tests/helpers.ts +9 -2
  409. package/src/types/harness.ts +1095 -0
  410. package/src/types/index.ts +209 -13
  411. package/src/types/observability.ts +344 -0
  412. package/src/types/sanitize-html.d.ts +25 -0
@@ -0,0 +1,438 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sweepWaitingTasks = exports.settleTaskOwner = exports.sweepQueuedConversations = exports.checkTaskWait = exports.settleChildren = exports.childOutcomes = exports.abortTaskTree = exports.toTaskView = void 0;
4
+ const api_1 = require("@terreno/api");
5
+ const luxon_1 = require("luxon");
6
+ const harness_1 = require("../types/harness");
7
+ const agentTaskNames_1 = require("./agentTaskNames");
8
+ const commit_1 = require("./commit");
9
+ const conversation_1 = require("./conversation");
10
+ const defineTask_1 = require("./defineTask");
11
+ const errors_1 = require("./errors");
12
+ /** Most waiting tasks one sweep re-checks; the next sweep picks up the rest. */
13
+ const WAIT_SWEEP_BATCH_SIZE = 100;
14
+ const NON_TERMINAL_STATUSES = Object.values(harness_1.HARNESS_TASK_STATUSES).filter((status) => !harness_1.HARNESS_TERMINAL_STATUSES.has(status));
15
+ const toTaskView = (task) => {
16
+ return {
17
+ attempt: task.attempt,
18
+ id: String(task._id),
19
+ input: task.input,
20
+ name: task.name,
21
+ phase: task.phase,
22
+ state: task.state,
23
+ userId: task.userId ? String(task.userId) : undefined,
24
+ version: task.version,
25
+ };
26
+ };
27
+ exports.toTaskView = toTaskView;
28
+ const isTerminal = (task) => harness_1.HARNESS_TERMINAL_STATUSES.has(task.status);
29
+ const isFailure = (task) => task.status === harness_1.HARNESS_TASK_STATUSES.failed || task.status === harness_1.HARNESS_TASK_STATUSES.aborted;
30
+ /** Tasks owned by any of `ownerIds`, oldest first. */
31
+ const findOwnedTasks = (models, ownerIds) => {
32
+ return models.task
33
+ .find({ "ownership.id": { $in: ownerIds }, "ownership.kind": "task" })
34
+ .sort({ created: 1 });
35
+ };
36
+ /** Abort the in-process run of `task`, if this process is running it. */
37
+ const signalAbort = (engine, task, reason) => {
38
+ const controller = engine.controllers.get(String(task._id));
39
+ if (controller && !controller.signal.aborted) {
40
+ controller.abort(new Error(`Aborted: ${reason}`));
41
+ }
42
+ };
43
+ /** How often an abort re-checks a task whose handler another aborter is running. */
44
+ const ABORT_CLAIM_POLL = luxon_1.Duration.fromObject({ milliseconds: 50 });
45
+ /**
46
+ * Wait until this call may run `task`'s abort handler. Returns null when the claim is
47
+ * ours, or the task once it is terminal (aborted by another aborter, or finished on its
48
+ * own).
49
+ */
50
+ const awaitAbortClaim = async (engine, task) => {
51
+ for (;;) {
52
+ if (await (0, commit_1.claimAbortHandler)({ models: engine.models, taskId: task._id })) {
53
+ return null;
54
+ }
55
+ const current = await engine.models.task.findExactlyOne({ _id: task._id });
56
+ if (isTerminal(current)) {
57
+ return current;
58
+ }
59
+ await new Promise((resolve) => setTimeout(resolve, ABORT_CLAIM_POLL.toMillis()));
60
+ }
61
+ };
62
+ /**
63
+ * Fence every non-terminal task below `top` for abort and return them deepest first (and
64
+ * newest first within a level), so each is aborted only after everything it owns. Each
65
+ * level is fenced before its children are read, so no task in the tree can create a
66
+ * child the scan misses.
67
+ */
68
+ const fenceOwnedForAbort = async ({ engine, reason, top, userId, }) => {
69
+ const levels = [];
70
+ const seen = new Set([String(top._id)]);
71
+ let frontier = [top._id];
72
+ while (frontier.length > 0) {
73
+ const found = (await findOwnedTasks(engine.models, frontier)).filter((task) => !seen.has(String(task._id)));
74
+ const fenced = [];
75
+ for (const task of found) {
76
+ seen.add(String(task._id));
77
+ if (isTerminal(task)) {
78
+ continue;
79
+ }
80
+ const current = await (0, commit_1.fenceForAbort)({
81
+ models: engine.models,
82
+ reason,
83
+ taskId: task._id,
84
+ userId,
85
+ });
86
+ if (current) {
87
+ signalAbort(engine, current, reason);
88
+ fenced.push(current);
89
+ }
90
+ }
91
+ levels.push(fenced);
92
+ frontier = found.map((task) => task._id);
93
+ }
94
+ return levels.reverse().flatMap((level) => [...level].reverse());
95
+ };
96
+ /** Run `task`'s abort handler; a throw is captured, never rethrown. */
97
+ const runAbortHandler = async ({ engine, reason, task, userId, }) => {
98
+ const definition = engine.definitions.get((0, defineTask_1.taskDefinitionKey)(task));
99
+ if (!definition) {
100
+ return {
101
+ error: `${(0, defineTask_1.taskDefinitionKey)(task)} is not in this harness registry; no abort handler ran`,
102
+ status: "unregistered",
103
+ };
104
+ }
105
+ if (!definition.abort) {
106
+ return { status: "none" };
107
+ }
108
+ try {
109
+ await definition.abort((0, exports.toTaskView)(task), { reason, taskId: String(task._id), userId });
110
+ return { status: "ok" };
111
+ }
112
+ catch (error) {
113
+ api_1.logger.error(`Harness abort handler for task ${task._id} (${definition.key}) failed; aborting anyway: ${(0, errors_1.errorMessage)(error)}`);
114
+ return { error: (0, errors_1.errorMessage)(error), status: "error" };
115
+ }
116
+ };
117
+ const abortOne = async ({ engine, override, reason, requestedOn, task, userId, }) => {
118
+ const settledElsewhere = await awaitAbortClaim(engine, task);
119
+ if (settledElsewhere?.status === harness_1.HARNESS_TASK_STATUSES.aborted) {
120
+ return settledElsewhere;
121
+ }
122
+ // It completed or failed on its own before this abort could claim it.
123
+ if (settledElsewhere) {
124
+ throw new commit_1.HarnessCommitConflictError(String(task._id), task.phase);
125
+ }
126
+ const handler = await runAbortHandler({ engine, reason, task, userId });
127
+ const handlerFailed = handler.status === "error";
128
+ const handlerOutput = handler.error ? handler : { status: handler.status };
129
+ return (0, commit_1.commitAbort)({
130
+ error: override?.error ?? `Aborted: ${reason}`,
131
+ filter: override?.filter ?? { status: { $in: NON_TERMINAL_STATUSES } },
132
+ models: engine.models,
133
+ span: {
134
+ error: handlerFailed ? `Abort handler failed: ${handler.error}` : undefined,
135
+ name: override?.spanName ?? "abort",
136
+ output: override
137
+ ? { ...override.output, abortHandler: handlerOutput }
138
+ : { abortedBy: userId, abortHandler: handlerOutput, reason, requestedOn },
139
+ status: handlerFailed ? "error" : "ok",
140
+ },
141
+ task,
142
+ testHooks: engine.testHooks,
143
+ });
144
+ };
145
+ /**
146
+ * Abort `top` and every non-terminal task it owns. First, top-down, each task is fenced
147
+ * (no new claims; a running phase loses its lease token) and its in-process run is
148
+ * signalled. Then, bottom-up, each task's `abort` handler runs and the task is committed
149
+ * `aborted` with an audit span. A descendant that settled on its own before its fence is
150
+ * skipped. Afterwards `top`'s owner is re-checked, since an aborted child can settle a
151
+ * parent's wait. Throws `HarnessCommitConflictError` when `top` is already terminal.
152
+ */
153
+ const abortTaskTree = async ({ engine, override, reason, settleOwner = true, top, userId, }) => {
154
+ const requestedOn = String(top._id);
155
+ const fencedTop = await (0, commit_1.fenceForAbort)({ models: engine.models, reason, taskId: top._id, userId });
156
+ if (!fencedTop) {
157
+ throw new commit_1.HarnessCommitConflictError(requestedOn, top.phase);
158
+ }
159
+ signalAbort(engine, fencedTop, reason);
160
+ for (const task of await fenceOwnedForAbort({ engine, reason, top: fencedTop, userId })) {
161
+ try {
162
+ // Owners are aborted too, so only a subagent turn's conversation needs settling.
163
+ await releaseConversation({
164
+ engine,
165
+ task: await abortOne({ engine, reason, requestedOn, task, userId }),
166
+ });
167
+ }
168
+ catch (error) {
169
+ // It finished on its own between the scan and the abort commit.
170
+ if (!(error instanceof commit_1.HarnessCommitConflictError)) {
171
+ throw error;
172
+ }
173
+ }
174
+ }
175
+ const aborted = await abortOne({
176
+ engine,
177
+ override,
178
+ reason,
179
+ requestedOn,
180
+ task: fencedTop,
181
+ userId,
182
+ });
183
+ if (settleOwner) {
184
+ await (0, exports.settleTaskOwner)({ engine, task: aborted });
185
+ }
186
+ return aborted;
187
+ };
188
+ exports.abortTaskTree = abortTaskTree;
189
+ /** Settled children of a `waitForTasks` call, in the order their ids were passed. */
190
+ const childOutcomes = (ids, children) => {
191
+ const byId = new Map(children.map((child) => [String(child._id), child]));
192
+ return ids.map((id) => {
193
+ const child = byId.get(id);
194
+ if (!child) {
195
+ throw (0, errors_1.harnessError)({
196
+ detail: `Child task ${id} disappeared while its owner waited on it`,
197
+ kind: "notFound",
198
+ });
199
+ }
200
+ const outcome = {
201
+ id,
202
+ name: child.name,
203
+ status: child.status,
204
+ };
205
+ if (child.outcome?.error !== undefined) {
206
+ outcome.error = child.outcome.error;
207
+ }
208
+ if (child.outcome?.result !== undefined) {
209
+ outcome.result = child.outcome.result;
210
+ }
211
+ return outcome;
212
+ });
213
+ };
214
+ exports.childOutcomes = childOutcomes;
215
+ /**
216
+ * Settle a child wait under `policy`. Under `failFast`, the first failed or aborted child
217
+ * aborts every sibling still in flight (with the sibling's subtree) before the wait
218
+ * resolves. Returns the children as they now stand and whether the wait is satisfied.
219
+ */
220
+ const settleChildren = async ({ engine, ids, ownerId, policy, }) => {
221
+ let children = await engine.models.task.find({ _id: { $in: ids } });
222
+ if (children.every(isTerminal)) {
223
+ return { children, isSettled: true };
224
+ }
225
+ const failed = children.find(isFailure);
226
+ if (policy !== harness_1.HARNESS_WAIT_POLICIES.failFast || !failed) {
227
+ return { children, isSettled: false };
228
+ }
229
+ for (const sibling of children.filter((child) => !isTerminal(child))) {
230
+ try {
231
+ await (0, exports.abortTaskTree)({
232
+ engine,
233
+ reason: `Sibling task ${failed._id} ${failed.status} (failFast wait of ${ownerId})`,
234
+ settleOwner: false,
235
+ top: sibling,
236
+ });
237
+ }
238
+ catch (error) {
239
+ if (!(error instanceof commit_1.HarnessCommitConflictError)) {
240
+ throw error;
241
+ }
242
+ }
243
+ }
244
+ children = await engine.models.task.find({ _id: { $in: ids } });
245
+ return { children, isSettled: children.every(isTerminal) };
246
+ };
247
+ exports.settleChildren = settleChildren;
248
+ /**
249
+ * Wake `taskId` when it is `waiting` on child tasks that have now settled. Safe to call
250
+ * any number of times from anywhere: the wake itself is fenced on the wait.
251
+ */
252
+ const checkTaskWait = async ({ engine, taskId, }) => {
253
+ const task = await engine.models.task.findOneOrNone({ _id: taskId });
254
+ const waiting = task?.waiting;
255
+ if (!task ||
256
+ task.status !== harness_1.HARNESS_TASK_STATUSES.waiting ||
257
+ waiting?.kind !== harness_1.HARNESS_WAIT_KINDS.tasks) {
258
+ return false;
259
+ }
260
+ const { isSettled } = await (0, exports.settleChildren)({
261
+ engine,
262
+ ids: waiting.taskIds ?? [],
263
+ ownerId: task._id,
264
+ policy: waiting.policy ?? harness_1.HARNESS_WAIT_POLICIES.all,
265
+ });
266
+ if (!isSettled) {
267
+ return false;
268
+ }
269
+ const isWoken = await (0, commit_1.wakeWaitingTask)({
270
+ kind: harness_1.HARNESS_WAIT_KINDS.tasks,
271
+ models: engine.models,
272
+ taskId: task._id,
273
+ });
274
+ if (isWoken) {
275
+ engine.wake();
276
+ }
277
+ return isWoken;
278
+ };
279
+ exports.checkTaskWait = checkTaskWait;
280
+ /**
281
+ * Mark a conversation `idle` once its active turn task is terminal. Fenced on the turn,
282
+ * so a later turn is never released by an earlier one. `submit` also releases a
283
+ * conversation whose active turn is terminal, should this write be lost to a crash.
284
+ */
285
+ const releaseConversation = async ({ engine, task, }) => {
286
+ const conversationId = turnConversationId(task);
287
+ if (!conversationId) {
288
+ return;
289
+ }
290
+ try {
291
+ await engine.models.conversation.updateOne({ _id: conversationId, activeTurnTaskId: task._id, status: "busy" }, { $set: { status: "idle" }, $unset: { activeTurnTaskId: 1 } });
292
+ }
293
+ catch (error) {
294
+ api_1.logger.error(`Harness could not release conversation ${conversationId} after turn ${task._id}: ${(0, errors_1.errorMessage)(error)}`);
295
+ }
296
+ };
297
+ /**
298
+ * The conversation a turn task runs on: its owner for a root conversation's turn, its
299
+ * input for a subagent turn (owned by the task that called `rt.runAgent`).
300
+ */
301
+ const turnConversationId = (task) => {
302
+ if (task.ownership?.kind === "conversation" && task.ownership.id) {
303
+ return String(task.ownership.id);
304
+ }
305
+ if (task.name !== agentTaskNames_1.AGENT_TURN_TASK_NAME) {
306
+ return undefined;
307
+ }
308
+ const conversationId = task.input?.conversationId;
309
+ return typeof conversationId === "string" ? conversationId : undefined;
310
+ };
311
+ /** Registry key of the built-in agent turn. */
312
+ const AGENT_TURN_KEY = (0, defineTask_1.taskDefinitionKey)({ name: agentTaskNames_1.AGENT_TURN_TASK_NAME, version: 1 });
313
+ /**
314
+ * Run the conversation's next queued submission now that its turn ended. A failure here
315
+ * leaves the submission queued; the owner's queue sweep (or the next `send`) starts it.
316
+ */
317
+ const startQueuedTurn = async ({ conversationId, engine, }) => {
318
+ const turn = engine.definitions.get(AGENT_TURN_KEY);
319
+ if (!turn) {
320
+ return false;
321
+ }
322
+ try {
323
+ const started = await (0, conversation_1.startNextQueuedTurn)({
324
+ context: { models: engine.models, turn, wake: engine.wake },
325
+ conversationId,
326
+ });
327
+ return started !== null;
328
+ }
329
+ catch (error) {
330
+ api_1.logger.error(`Harness could not start the next queued turn of conversation ${conversationId}: ${(0, errors_1.errorMessage)(error)}`);
331
+ return false;
332
+ }
333
+ };
334
+ /**
335
+ * Free `busy` conversations whose active turn is terminal or gone. Every terminal turn
336
+ * commit frees its conversation in the same transaction; this repairs conversations left
337
+ * busy by data written before that, or by a write that failed. Fenced on the stale turn,
338
+ * so a conversation that moved on is untouched. Returns how many were freed.
339
+ */
340
+ const releaseStaleConversations = async (engine) => {
341
+ const { conversation, task } = engine.models;
342
+ const stale = await conversation.aggregate([
343
+ { $match: { status: "busy" } },
344
+ {
345
+ $lookup: {
346
+ as: "turn",
347
+ foreignField: "_id",
348
+ from: task.collection.name,
349
+ localField: "activeTurnTaskId",
350
+ pipeline: [{ $project: { status: 1 } }],
351
+ },
352
+ },
353
+ {
354
+ $match: {
355
+ $or: [{ "turn.0": { $exists: false } }, { "turn.status": { $in: [...harness_1.HARNESS_TERMINAL_STATUSES] } }],
356
+ },
357
+ },
358
+ { $limit: QUEUE_SWEEP_BATCH_SIZE },
359
+ { $project: { activeTurnTaskId: 1 } },
360
+ ]);
361
+ let released = 0;
362
+ for (const { _id, activeTurnTaskId } of stale) {
363
+ const result = await conversation.updateOne({ _id, activeTurnTaskId: activeTurnTaskId ?? null, status: "busy" }, { $set: { status: "idle" }, $unset: { activeTurnTaskId: 1 } });
364
+ released += result.modifiedCount;
365
+ }
366
+ return released;
367
+ };
368
+ /** Most idle conversations with a backlog one sweep starts. */
369
+ const QUEUE_SWEEP_BATCH_SIZE = 100;
370
+ /**
371
+ * Start the next queued submission of every conversation that still has one, after
372
+ * freeing conversations stuck `busy` on a finished turn. A turn frees its conversation in
373
+ * its terminal commit and starts the next queued turn right after; this covers a process
374
+ * that died between the two. Returns how many turns started.
375
+ */
376
+ const sweepQueuedConversations = async (engine) => {
377
+ await releaseStaleConversations(engine);
378
+ const stranded = await engine.models.conversation
379
+ .find({ "queued.requestId": { $exists: true }, status: "idle" })
380
+ .select({ _id: 1 })
381
+ .limit(QUEUE_SWEEP_BATCH_SIZE)
382
+ .lean();
383
+ let started = 0;
384
+ for (const { _id } of stranded) {
385
+ if (await startQueuedTurn({ conversationId: _id, engine })) {
386
+ started += 1;
387
+ }
388
+ }
389
+ return started;
390
+ };
391
+ exports.sweepQueuedConversations = sweepQueuedConversations;
392
+ /**
393
+ * Wake whatever owns a task that just settled: a waiting parent task re-checks its wait;
394
+ * a conversation whose turn ended goes back to `idle` and starts its next queued submission.
395
+ */
396
+ const settleTaskOwner = async ({ engine, task, }) => {
397
+ if (task.ownership?.kind === "conversation" && task.ownership.id) {
398
+ await releaseConversation({ engine, task });
399
+ await startQueuedTurn({ conversationId: task.ownership.id, engine });
400
+ return;
401
+ }
402
+ // A subagent turn frees its conversation, then wakes the task waiting on it.
403
+ await releaseConversation({ engine, task });
404
+ if (task.ownership?.kind !== "task" || !task.ownership.id) {
405
+ return;
406
+ }
407
+ try {
408
+ await (0, exports.checkTaskWait)({ engine, taskId: task.ownership.id });
409
+ }
410
+ catch (error) {
411
+ // The periodic wait sweep retries; the child's own outcome is already committed.
412
+ api_1.logger.error(`Harness could not wake owner ${task.ownership.id} of task ${task._id}: ${(0, errors_1.errorMessage)(error)}`);
413
+ }
414
+ };
415
+ exports.settleTaskOwner = settleTaskOwner;
416
+ /**
417
+ * Re-check tasks waiting on children. Covers wakes lost to a crash between a child's
418
+ * terminal commit and its owner check. Returns how many tasks were woken.
419
+ */
420
+ const sweepWaitingTasks = async (engine) => {
421
+ const waiting = await engine.models.task
422
+ .find({ status: harness_1.HARNESS_TASK_STATUSES.waiting, "waiting.kind": harness_1.HARNESS_WAIT_KINDS.tasks })
423
+ .sort({ updated: 1 })
424
+ .limit(WAIT_SWEEP_BATCH_SIZE);
425
+ let woken = 0;
426
+ for (const task of waiting) {
427
+ try {
428
+ if (await (0, exports.checkTaskWait)({ engine, taskId: task._id })) {
429
+ woken += 1;
430
+ }
431
+ }
432
+ catch (error) {
433
+ api_1.logger.error(`Harness could not re-check waiting task ${task._id}: ${(0, errors_1.errorMessage)(error)}`);
434
+ }
435
+ }
436
+ return woken;
437
+ };
438
+ exports.sweepWaitingTasks = sweepWaitingTasks;
@@ -0,0 +1,29 @@
1
+ import type { HarnessAgentDefinition, HarnessExtensionDefinition, HarnessTaskDefinition } from "../types/harness";
2
+ import type { HarnessModels } from "./commit";
3
+ /** Any task definition, whatever its input, state, and output types. */
4
+ export type AnyHarnessTaskDefinition = HarnessTaskDefinition<never, unknown, unknown>;
5
+ /** Anything `Harness.open({registry})` accepts. */
6
+ export type HarnessRegistryEntry = AnyHarnessTaskDefinition | HarnessAgentDefinition | HarnessExtensionDefinition;
7
+ /**
8
+ * Separate agents and extensions (each by unique name) from task definitions, and check
9
+ * that every extension an agent uses is registered.
10
+ */
11
+ export declare const splitRegistry: (registry: ReadonlyArray<HarnessRegistryEntry>) => {
12
+ agents: Map<string, HarnessAgentDefinition>;
13
+ extensions: Map<string, HarnessExtensionDefinition>;
14
+ tasks: AnyHarnessTaskDefinition[];
15
+ };
16
+ /**
17
+ * Index definitions by exact `name@version`. Several versions of one name may sit side by
18
+ * side so in-flight runs keep the handler they started on; one version listed twice throws.
19
+ */
20
+ export declare const buildTaskRegistry: (registry: ReadonlyArray<AnyHarnessTaskDefinition>) => Map<string, HarnessTaskDefinition>;
21
+ /**
22
+ * Throw before any claim when a non-terminal task (pending, running, waiting, interrupted,
23
+ * or being aborted) is pinned to a `name@version` this registry lacks, listing each one
24
+ * with its task count. Running such a process would strand those tasks silently.
25
+ */
26
+ export declare const assertInFlightVersionsRegistered: ({ definitions, models, }: {
27
+ definitions: Map<string, HarnessTaskDefinition>;
28
+ models: HarnessModels;
29
+ }) => Promise<void>;
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertInFlightVersionsRegistered = exports.buildTaskRegistry = exports.splitRegistry = void 0;
4
+ const harness_1 = require("../types/harness");
5
+ const defineTask_1 = require("./defineTask");
6
+ const errors_1 = require("./errors");
7
+ /**
8
+ * Separate agents and extensions (each by unique name) from task definitions, and check
9
+ * that every extension an agent uses is registered.
10
+ */
11
+ const splitRegistry = (registry) => {
12
+ const agents = new Map();
13
+ const extensions = new Map();
14
+ const tasks = [];
15
+ for (const entry of registry) {
16
+ if (entry.kind === "extension") {
17
+ if (extensions.has(entry.name)) {
18
+ throw (0, errors_1.harnessError)({
19
+ detail: `Harness registry lists extension "${entry.name}" more than once`,
20
+ kind: "configInvalid",
21
+ });
22
+ }
23
+ extensions.set(entry.name, entry);
24
+ continue;
25
+ }
26
+ if (entry.kind !== "agent") {
27
+ tasks.push(entry);
28
+ continue;
29
+ }
30
+ if (agents.has(entry.name)) {
31
+ throw (0, errors_1.harnessError)({
32
+ detail: `Harness registry lists agent "${entry.name}" more than once`,
33
+ kind: "configInvalid",
34
+ });
35
+ }
36
+ agents.set(entry.name, entry);
37
+ }
38
+ for (const agent of agents.values()) {
39
+ const missing = agent.extensions.find((name) => !extensions.has(name));
40
+ if (missing !== undefined) {
41
+ throw (0, errors_1.harnessError)({
42
+ detail: `Agent "${agent.name}" uses extension "${missing}", which is not in this harness registry`,
43
+ kind: "configInvalid",
44
+ });
45
+ }
46
+ }
47
+ return { agents, extensions, tasks };
48
+ };
49
+ exports.splitRegistry = splitRegistry;
50
+ /**
51
+ * Index definitions by exact `name@version`. Several versions of one name may sit side by
52
+ * side so in-flight runs keep the handler they started on; one version listed twice throws.
53
+ */
54
+ const buildTaskRegistry = (registry) => {
55
+ const definitions = new Map();
56
+ for (const definition of registry) {
57
+ if (definitions.has(definition.key)) {
58
+ throw (0, errors_1.harnessError)({
59
+ detail: `Harness registry lists ${definition.key} more than once`,
60
+ kind: "configInvalid",
61
+ });
62
+ }
63
+ definitions.set(definition.key, definition);
64
+ }
65
+ return definitions;
66
+ };
67
+ exports.buildTaskRegistry = buildTaskRegistry;
68
+ /**
69
+ * Throw before any claim when a non-terminal task (pending, running, waiting, interrupted,
70
+ * or being aborted) is pinned to a `name@version` this registry lacks, listing each one
71
+ * with its task count. Running such a process would strand those tasks silently.
72
+ */
73
+ const assertInFlightVersionsRegistered = async ({ definitions, models, }) => {
74
+ const counts = await models.task.aggregate([
75
+ { $match: { status: { $nin: [...harness_1.HARNESS_TERMINAL_STATUSES] } } },
76
+ { $group: { _id: { name: "$name", version: "$version" }, count: { $sum: 1 } } },
77
+ ]);
78
+ const missing = counts
79
+ .map(({ _id, count }) => ({ count, key: (0, defineTask_1.taskDefinitionKey)(_id) }))
80
+ .filter(({ key }) => !definitions.has(key))
81
+ .sort((a, b) => a.key.localeCompare(b.key));
82
+ if (missing.length === 0) {
83
+ return;
84
+ }
85
+ const listed = missing
86
+ .map(({ count, key }) => `${key} (${count} task${count === 1 ? "" : "s"})`)
87
+ .join(", ");
88
+ throw (0, errors_1.harnessError)({
89
+ detail: `Harness.start: in-flight tasks use task versions this registry does not register: ${listed}. Register those definitions (keep old versions until their tasks finish) or resolve the tasks first.`,
90
+ kind: "configInvalid",
91
+ });
92
+ };
93
+ exports.assertInFlightVersionsRegistered = assertInFlightVersionsRegistered;
@@ -0,0 +1,31 @@
1
+ import { DateTime } from "luxon";
2
+ import type { HarnessRetryPolicy } from "../types/harness";
3
+ export interface ResolvedRetryPolicy {
4
+ backoffMs: number;
5
+ maxAttempts: number;
6
+ maxBackoffMs: number;
7
+ }
8
+ /** Fill the fields a definition left out with `HARNESS_RETRY_DEFAULTS`. */
9
+ export declare const resolveRetryPolicy: (policy: HarnessRetryPolicy | undefined) => ResolvedRetryPolicy;
10
+ /**
11
+ * Throw when a retry policy cannot be applied. `scope` prefixes the message (for example
12
+ * `defineTask(name)`); `field` names the option (`retry`, `modelRetry`).
13
+ */
14
+ export declare const assertValidRetryPolicy: (scope: string, policy: HarnessRetryPolicy, field?: string) => void;
15
+ /**
16
+ * Delay before the next run after `failedAttempts` failures: exponential
17
+ * (`backoffMs * 2^(failedAttempts - 1)`, capped at `maxBackoffMs`) with equal jitter, so
18
+ * the result lies in `[delay / 2, delay]`. Spreading retries keeps a shared outage from
19
+ * waking every failed task at the same instant.
20
+ */
21
+ export declare const retryDelayMs: ({ failedAttempts, policy, random, }: {
22
+ failedAttempts: number;
23
+ policy: ResolvedRetryPolicy;
24
+ random?: () => number;
25
+ }) => number;
26
+ /** When the next run may start, measured from Luxon's clock (`DateTime.now()`). */
27
+ export declare const nextRetryAt: ({ failedAttempts, policy, random, }: {
28
+ failedAttempts: number;
29
+ policy: ResolvedRetryPolicy;
30
+ random?: () => number;
31
+ }) => DateTime;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.nextRetryAt = exports.retryDelayMs = exports.assertValidRetryPolicy = exports.resolveRetryPolicy = void 0;
4
+ const luxon_1 = require("luxon");
5
+ const harness_1 = require("../types/harness");
6
+ const definitionError_1 = require("./definitionError");
7
+ /** Fill the fields a definition left out with `HARNESS_RETRY_DEFAULTS`. */
8
+ const resolveRetryPolicy = (policy) => {
9
+ return {
10
+ backoffMs: policy?.backoffMs ?? harness_1.HARNESS_RETRY_DEFAULTS.backoffMs,
11
+ maxAttempts: policy?.maxAttempts ?? harness_1.HARNESS_RETRY_DEFAULTS.maxAttempts,
12
+ maxBackoffMs: policy?.maxBackoffMs ?? harness_1.HARNESS_RETRY_DEFAULTS.maxBackoffMs,
13
+ };
14
+ };
15
+ exports.resolveRetryPolicy = resolveRetryPolicy;
16
+ /**
17
+ * Throw when a retry policy cannot be applied. `scope` prefixes the message (for example
18
+ * `defineTask(name)`); `field` names the option (`retry`, `modelRetry`).
19
+ */
20
+ const assertValidRetryPolicy = (scope, policy, field = "retry") => {
21
+ const { backoffMs, maxAttempts, maxBackoffMs } = (0, exports.resolveRetryPolicy)(policy);
22
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
23
+ throw new definitionError_1.HarnessDefinitionError(`${scope}: ${field}.maxAttempts must be a positive integer`);
24
+ }
25
+ if (!Number.isFinite(backoffMs) || backoffMs < 0) {
26
+ throw new definitionError_1.HarnessDefinitionError(`${scope}: ${field}.backoffMs must be a non-negative number`);
27
+ }
28
+ if (!Number.isFinite(maxBackoffMs) || maxBackoffMs < backoffMs) {
29
+ throw new definitionError_1.HarnessDefinitionError(`${scope}: ${field}.maxBackoffMs must be at least ${field}.backoffMs`);
30
+ }
31
+ };
32
+ exports.assertValidRetryPolicy = assertValidRetryPolicy;
33
+ /**
34
+ * Delay before the next run after `failedAttempts` failures: exponential
35
+ * (`backoffMs * 2^(failedAttempts - 1)`, capped at `maxBackoffMs`) with equal jitter, so
36
+ * the result lies in `[delay / 2, delay]`. Spreading retries keeps a shared outage from
37
+ * waking every failed task at the same instant.
38
+ */
39
+ const retryDelayMs = ({ failedAttempts, policy, random = Math.random, }) => {
40
+ const exponent = Math.max(0, failedAttempts - 1);
41
+ const capped = Math.min(policy.maxBackoffMs, policy.backoffMs * 2 ** exponent);
42
+ const half = capped / 2;
43
+ return Math.round(half + random() * half);
44
+ };
45
+ exports.retryDelayMs = retryDelayMs;
46
+ /** When the next run may start, measured from Luxon's clock (`DateTime.now()`). */
47
+ const nextRetryAt = ({ failedAttempts, policy, random, }) => {
48
+ return luxon_1.DateTime.now().plus({ milliseconds: (0, exports.retryDelayMs)({ failedAttempts, policy, random }) });
49
+ };
50
+ exports.nextRetryAt = nextRetryAt;
@@ -0,0 +1,13 @@
1
+ import type express from "express";
2
+ import type { Harness } from "../harness";
3
+ /**
4
+ * Mount `/harness/approvals` on `router`: list and read the approvals the caller may
5
+ * decide, and `approve` / `reject` instance actions. Approvers come from `harness`'s
6
+ * registry at request time.
7
+ */
8
+ export declare const addHarnessApprovalRoutes: (router: express.Application, { basePath, harness, openApi }: {
9
+ basePath: string;
10
+ harness: Harness;
11
+ openApi?: unknown;
12
+ }) => void;
13
+ export declare const assertValidBasePath: (basePath: string) => string;