@terreno/ai 57.9.0 → 57.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) 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 +133 -0
  28. package/dist/harness/errors.js +107 -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 +522 -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 +191 -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 +64 -0
  80. package/dist/harness/runners/inProcessRunner.js +227 -0
  81. package/dist/harness/runners/jobsRunner.d.ts +62 -0
  82. package/dist/harness/runners/jobsRunner.js +212 -0
  83. package/dist/harness/runtime.d.ts +52 -0
  84. package/dist/harness/runtime.js +604 -0
  85. package/dist/harness/subagent.d.ts +53 -0
  86. package/dist/harness/subagent.js +134 -0
  87. package/dist/harness/suspend.d.ts +8 -0
  88. package/dist/harness/suspend.js +16 -0
  89. package/dist/harness/transaction.d.ts +3 -0
  90. package/dist/harness/transaction.js +22 -0
  91. package/dist/harness/waits.d.ts +100 -0
  92. package/dist/harness/waits.js +214 -0
  93. package/dist/index.d.ts +19 -1
  94. package/dist/index.js +45 -2
  95. package/dist/models/aiDataset.d.ts +2 -0
  96. package/dist/models/aiDataset.js +67 -0
  97. package/dist/models/aiRequest.js +1 -1
  98. package/dist/models/gptHistory.js +73 -0
  99. package/dist/observability/adminScreens.d.ts +5 -0
  100. package/dist/observability/adminScreens.js +32 -0
  101. package/dist/observability/compileTemplate.d.ts +1 -0
  102. package/dist/observability/compileTemplate.js +13 -0
  103. package/dist/observability/datasetImport.d.ts +11 -0
  104. package/dist/observability/datasetImport.js +185 -0
  105. package/dist/observability/evaluate.d.ts +31 -0
  106. package/dist/observability/evaluate.js +200 -0
  107. package/dist/observability/evaluatorTemplates.d.ts +17 -0
  108. package/dist/observability/evaluatorTemplates.js +111 -0
  109. package/dist/observability/jsonPath.d.ts +2 -0
  110. package/dist/observability/jsonPath.js +57 -0
  111. package/dist/observability/local/datasetStore.d.ts +87 -0
  112. package/dist/observability/local/datasetStore.js +326 -0
  113. package/dist/observability/local/evaluatorStore.d.ts +44 -0
  114. package/dist/observability/local/evaluatorStore.js +182 -0
  115. package/dist/observability/local/experimentRunner.d.ts +96 -0
  116. package/dist/observability/local/experimentRunner.js +419 -0
  117. package/dist/observability/local/localPlugin.d.ts +22 -0
  118. package/dist/observability/local/localPlugin.js +76 -0
  119. package/dist/observability/local/models/obsDataset.d.ts +2 -0
  120. package/dist/observability/local/models/obsDataset.js +37 -0
  121. package/dist/observability/local/models/obsDatasetItem.d.ts +2 -0
  122. package/dist/observability/local/models/obsDatasetItem.js +76 -0
  123. package/dist/observability/local/models/obsEvaluator.d.ts +2 -0
  124. package/dist/observability/local/models/obsEvaluator.js +98 -0
  125. package/dist/observability/local/models/obsExperiment.d.ts +2 -0
  126. package/dist/observability/local/models/obsExperiment.js +87 -0
  127. package/dist/observability/local/models/obsExperimentItem.d.ts +2 -0
  128. package/dist/observability/local/models/obsExperimentItem.js +45 -0
  129. package/dist/observability/local/models/obsPrompt.d.ts +2 -0
  130. package/dist/observability/local/models/obsPrompt.js +42 -0
  131. package/dist/observability/local/models/obsPromptLabel.d.ts +2 -0
  132. package/dist/observability/local/models/obsPromptLabel.js +39 -0
  133. package/dist/observability/local/models/obsPromptVersion.d.ts +2 -0
  134. package/dist/observability/local/models/obsPromptVersion.js +96 -0
  135. package/dist/observability/local/models/obsReviewItem.d.ts +2 -0
  136. package/dist/observability/local/models/obsReviewItem.js +75 -0
  137. package/dist/observability/local/models/obsScore.d.ts +2 -0
  138. package/dist/observability/local/models/obsScore.js +58 -0
  139. package/dist/observability/local/models/obsSpan.d.ts +2 -0
  140. package/dist/observability/local/models/obsSpan.js +64 -0
  141. package/dist/observability/local/models/obsTrace.d.ts +2 -0
  142. package/dist/observability/local/models/obsTrace.js +93 -0
  143. package/dist/observability/local/promptStore.d.ts +180 -0
  144. package/dist/observability/local/promptStore.js +444 -0
  145. package/dist/observability/local/reviewStore.d.ts +50 -0
  146. package/dist/observability/local/reviewStore.js +203 -0
  147. package/dist/observability/local/traceStore.d.ts +103 -0
  148. package/dist/observability/local/traceStore.js +325 -0
  149. package/dist/observability/observabilityApp.d.ts +24 -0
  150. package/dist/observability/observabilityApp.js +157 -0
  151. package/dist/observability/observabilityAppRegistry.d.ts +14 -0
  152. package/dist/observability/observabilityAppRegistry.js +16 -0
  153. package/dist/observability/permissions.d.ts +7 -0
  154. package/dist/observability/permissions.js +60 -0
  155. package/dist/observability/reviewPanels.d.ts +18 -0
  156. package/dist/observability/reviewPanels.js +46 -0
  157. package/dist/observability/routes/datasets.d.ts +7 -0
  158. package/dist/observability/routes/datasets.js +149 -0
  159. package/dist/observability/routes/evaluators.d.ts +7 -0
  160. package/dist/observability/routes/evaluators.js +123 -0
  161. package/dist/observability/routes/experiments.d.ts +7 -0
  162. package/dist/observability/routes/experiments.js +95 -0
  163. package/dist/observability/routes/observabilityRouteAccess.d.ts +13 -0
  164. package/dist/observability/routes/observabilityRouteAccess.js +67 -0
  165. package/dist/observability/routes/prompts.d.ts +12 -0
  166. package/dist/observability/routes/prompts.js +172 -0
  167. package/dist/observability/routes/requestAiService.d.ts +13 -0
  168. package/dist/observability/routes/requestAiService.js +21 -0
  169. package/dist/observability/routes/review.d.ts +7 -0
  170. package/dist/observability/routes/review.js +79 -0
  171. package/dist/observability/routes/status.d.ts +5 -0
  172. package/dist/observability/routes/status.js +31 -0
  173. package/dist/observability/routes/testMultiStage.d.ts +9 -0
  174. package/dist/observability/routes/testMultiStage.js +67 -0
  175. package/dist/observability/routes/traces.d.ts +7 -0
  176. package/dist/observability/routes/traces.js +129 -0
  177. package/dist/observability/schemaValidation.d.ts +5 -0
  178. package/dist/observability/schemaValidation.js +26 -0
  179. package/dist/observability/sopThresholds.d.ts +2 -0
  180. package/dist/observability/sopThresholds.js +21 -0
  181. package/dist/observability/status.d.ts +23 -0
  182. package/dist/observability/status.js +34 -0
  183. package/dist/observability/testMultiStageSchemas.d.ts +10 -0
  184. package/dist/observability/testMultiStageSchemas.js +79 -0
  185. package/dist/observability/testMultiStageWorkflow.d.ts +20 -0
  186. package/dist/observability/testMultiStageWorkflow.js +218 -0
  187. package/dist/observability/types.d.ts +159 -0
  188. package/dist/observability/types.js +67 -0
  189. package/dist/routes/files.js +18 -7
  190. package/dist/routes/gpt.js +79 -689
  191. package/dist/routes/gptActions.d.ts +9 -0
  192. package/dist/routes/gptActions.js +212 -0
  193. package/dist/routes/gptDatasets.d.ts +5 -0
  194. package/dist/routes/gptDatasets.js +94 -0
  195. package/dist/routes/gptHistories.d.ts +3 -1
  196. package/dist/routes/gptHistories.js +188 -2
  197. package/dist/service/aiDatasets.d.ts +57 -0
  198. package/dist/service/aiDatasets.js +253 -0
  199. package/dist/service/aiService.d.ts +50 -1
  200. package/dist/service/aiService.js +426 -77
  201. package/dist/service/askFiles.d.ts +49 -0
  202. package/dist/service/askFiles.js +162 -0
  203. package/dist/service/asks.d.ts +76 -0
  204. package/dist/service/asks.js +284 -0
  205. package/dist/service/chatTurn.d.ts +128 -0
  206. package/dist/service/chatTurn.js +1674 -0
  207. package/dist/service/fileStorage.d.ts +4 -0
  208. package/dist/service/fileStorage.js +7 -2
  209. package/dist/service/fillActionIds.d.ts +6 -0
  210. package/dist/service/fillActionIds.js +79 -0
  211. package/dist/service/jsonFenceModel.d.ts +7 -0
  212. package/dist/service/jsonFenceModel.js +45 -0
  213. package/dist/service/prompts.d.ts +52 -0
  214. package/dist/service/prompts.js +96 -1
  215. package/dist/service/sanitizeHtml.d.ts +11 -0
  216. package/dist/service/sanitizeHtml.js +108 -0
  217. package/dist/types/harness.d.ts +952 -0
  218. package/dist/types/harness.js +133 -0
  219. package/dist/types/index.d.ts +192 -14
  220. package/dist/types/index.js +2 -0
  221. package/dist/types/observability.d.ts +288 -0
  222. package/dist/types/observability.js +2 -0
  223. package/package.json +28 -5
  224. package/src/aiApp.test.ts +207 -1
  225. package/src/aiApp.ts +19 -6
  226. package/src/harness/adminScreens.test.ts +34 -0
  227. package/src/harness/adminScreens.ts +11 -0
  228. package/src/harness/agentLoop.test.ts +1034 -0
  229. package/src/harness/agentLoop.ts +1082 -0
  230. package/src/harness/agentRecovery.test.ts +380 -0
  231. package/src/harness/agentTaskNames.ts +4 -0
  232. package/src/harness/approvalPolicy.ts +28 -0
  233. package/src/harness/approvals.test.ts +1094 -0
  234. package/src/harness/approvals.ts +644 -0
  235. package/src/harness/commit.ts +1049 -0
  236. package/src/harness/concurrency.test.ts +155 -0
  237. package/src/harness/conversation.ts +503 -0
  238. package/src/harness/defineAgent.test.ts +92 -0
  239. package/src/harness/defineAgent.ts +82 -0
  240. package/src/harness/defineTask.test.ts +59 -0
  241. package/src/harness/defineTask.ts +76 -0
  242. package/src/harness/defineTool.ts +45 -0
  243. package/src/harness/definitionError.ts +13 -0
  244. package/src/harness/errors.test.ts +90 -0
  245. package/src/harness/errors.ts +125 -0
  246. package/src/harness/eventHub.test.ts +124 -0
  247. package/src/harness/eventHub.ts +159 -0
  248. package/src/harness/events.test.ts +769 -0
  249. package/src/harness/events.ts +384 -0
  250. package/src/harness/executionEnv.ts +34 -0
  251. package/src/harness/extensions.test.ts +1218 -0
  252. package/src/harness/extensions.ts +382 -0
  253. package/src/harness/harness.test.ts +693 -0
  254. package/src/harness/harness.ts +778 -0
  255. package/src/harness/harnessApp.ts +76 -0
  256. package/src/harness/internalRuntime.ts +44 -0
  257. package/src/harness/leases.ts +132 -0
  258. package/src/harness/memo.ts +107 -0
  259. package/src/harness/modelCall.test.ts +134 -0
  260. package/src/harness/modelCall.ts +200 -0
  261. package/src/harness/models/harnessApproval.ts +109 -0
  262. package/src/harness/models/harnessConversation.ts +142 -0
  263. package/src/harness/models/harnessEvent.ts +92 -0
  264. package/src/harness/models/harnessInboxEvent.ts +73 -0
  265. package/src/harness/models/harnessMemo.ts +43 -0
  266. package/src/harness/models/harnessMessage.ts +85 -0
  267. package/src/harness/models/harnessModels.test.ts +60 -0
  268. package/src/harness/models/harnessOwner.ts +40 -0
  269. package/src/harness/models/harnessTask.ts +206 -0
  270. package/src/harness/ownership.test.ts +1087 -0
  271. package/src/harness/ownership.ts +618 -0
  272. package/src/harness/recovery.test.ts +907 -0
  273. package/src/harness/registry.ts +124 -0
  274. package/src/harness/retries.test.ts +292 -0
  275. package/src/harness/retryBackoff.test.ts +100 -0
  276. package/src/harness/retryBackoff.ts +77 -0
  277. package/src/harness/routes/approvals.ts +123 -0
  278. package/src/harness/routes/conversations.test.ts +518 -0
  279. package/src/harness/routes/conversations.ts +102 -0
  280. package/src/harness/routes/events.ts +280 -0
  281. package/src/harness/routes/tasks.test.ts +198 -0
  282. package/src/harness/routes/tasks.ts +146 -0
  283. package/src/harness/runners/inProcessRunner.test.ts +530 -0
  284. package/src/harness/runners/inProcessRunner.ts +260 -0
  285. package/src/harness/runners/jobsRunner.test.ts +709 -0
  286. package/src/harness/runners/jobsRunner.ts +252 -0
  287. package/src/harness/runtime.ts +802 -0
  288. package/src/harness/subagent.test.ts +696 -0
  289. package/src/harness/subagent.ts +192 -0
  290. package/src/harness/suspend.ts +13 -0
  291. package/src/harness/transaction.ts +17 -0
  292. package/src/harness/versioning.test.ts +288 -0
  293. package/src/harness/waits.test.ts +693 -0
  294. package/src/harness/waits.ts +356 -0
  295. package/src/index.test.ts +13 -0
  296. package/src/index.ts +70 -0
  297. package/src/isolated/adminScreensConfig.isolated.ts +143 -0
  298. package/src/models/aiDataset.test.ts +34 -0
  299. package/src/models/aiDataset.ts +78 -0
  300. package/src/models/aiRequest.ts +2 -1
  301. package/src/models/gptHistory.test.ts +156 -0
  302. package/src/models/gptHistory.ts +89 -1
  303. package/src/observability/adminScreens.test.ts +71 -0
  304. package/src/observability/adminScreens.ts +42 -0
  305. package/src/observability/compileTemplate.test.ts +14 -0
  306. package/src/observability/compileTemplate.ts +10 -0
  307. package/src/observability/datasetImport.test.ts +95 -0
  308. package/src/observability/datasetImport.ts +220 -0
  309. package/src/observability/evaluate.test.ts +549 -0
  310. package/src/observability/evaluate.ts +254 -0
  311. package/src/observability/evaluatorTemplates.ts +124 -0
  312. package/src/observability/jsonPath.test.ts +52 -0
  313. package/src/observability/jsonPath.ts +60 -0
  314. package/src/observability/local/datasetStore.test.ts +230 -0
  315. package/src/observability/local/datasetStore.ts +452 -0
  316. package/src/observability/local/evaluatorStore.test.ts +138 -0
  317. package/src/observability/local/evaluatorStore.ts +224 -0
  318. package/src/observability/local/experimentRunner.test.ts +489 -0
  319. package/src/observability/local/experimentRunner.ts +548 -0
  320. package/src/observability/local/localPlugin.ts +88 -0
  321. package/src/observability/local/models/obsDataset.ts +38 -0
  322. package/src/observability/local/models/obsDatasetItem.ts +80 -0
  323. package/src/observability/local/models/obsEvaluator.ts +102 -0
  324. package/src/observability/local/models/obsExperiment.ts +91 -0
  325. package/src/observability/local/models/obsExperimentItem.ts +52 -0
  326. package/src/observability/local/models/obsPrompt.ts +43 -0
  327. package/src/observability/local/models/obsPromptLabel.ts +43 -0
  328. package/src/observability/local/models/obsPromptVersion.ts +107 -0
  329. package/src/observability/local/models/obsReviewItem.ts +79 -0
  330. package/src/observability/local/models/obsScore.ts +59 -0
  331. package/src/observability/local/models/obsSpan.ts +65 -0
  332. package/src/observability/local/models/obsTrace.ts +94 -0
  333. package/src/observability/local/obsModels.test.ts +119 -0
  334. package/src/observability/local/promptStore.test.ts +351 -0
  335. package/src/observability/local/promptStore.ts +665 -0
  336. package/src/observability/local/reviewStore.test.ts +164 -0
  337. package/src/observability/local/reviewStore.ts +264 -0
  338. package/src/observability/local/traceStore.test.ts +264 -0
  339. package/src/observability/local/traceStore.ts +440 -0
  340. package/src/observability/observabilityApp.test.ts +92 -0
  341. package/src/observability/observabilityApp.ts +185 -0
  342. package/src/observability/observabilityAppRegistry.test.ts +30 -0
  343. package/src/observability/observabilityAppRegistry.ts +35 -0
  344. package/src/observability/permissions.test.ts +96 -0
  345. package/src/observability/permissions.ts +78 -0
  346. package/src/observability/reviewPanels.test.ts +35 -0
  347. package/src/observability/reviewPanels.ts +64 -0
  348. package/src/observability/routes/datasets.test.ts +176 -0
  349. package/src/observability/routes/datasets.ts +252 -0
  350. package/src/observability/routes/evaluators.test.ts +119 -0
  351. package/src/observability/routes/evaluators.ts +207 -0
  352. package/src/observability/routes/experiments.test.ts +282 -0
  353. package/src/observability/routes/experiments.ts +152 -0
  354. package/src/observability/routes/observabilityRbac.test.ts +767 -0
  355. package/src/observability/routes/observabilityRouteAccess.ts +106 -0
  356. package/src/observability/routes/prompts.test.ts +320 -0
  357. package/src/observability/routes/prompts.ts +263 -0
  358. package/src/observability/routes/requestAiService.ts +36 -0
  359. package/src/observability/routes/review.test.ts +120 -0
  360. package/src/observability/routes/review.ts +125 -0
  361. package/src/observability/routes/status.test.ts +116 -0
  362. package/src/observability/routes/status.ts +47 -0
  363. package/src/observability/routes/testMultiStage.test.ts +214 -0
  364. package/src/observability/routes/testMultiStage.ts +96 -0
  365. package/src/observability/routes/traces.test.ts +167 -0
  366. package/src/observability/routes/traces.ts +172 -0
  367. package/src/observability/schemaValidation.ts +29 -0
  368. package/src/observability/sopThresholds.ts +20 -0
  369. package/src/observability/status.test.ts +38 -0
  370. package/src/observability/status.ts +56 -0
  371. package/src/observability/testMultiStageSchemas.ts +95 -0
  372. package/src/observability/testMultiStageWorkflow.test.ts +114 -0
  373. package/src/observability/testMultiStageWorkflow.ts +307 -0
  374. package/src/observability/types.ts +262 -0
  375. package/src/routes/files.test.ts +63 -9
  376. package/src/routes/files.ts +21 -7
  377. package/src/routes/gpt.test.ts +3279 -0
  378. package/src/routes/gpt.ts +91 -816
  379. package/src/routes/gptActions.test.ts +241 -0
  380. package/src/routes/gptActions.ts +255 -0
  381. package/src/routes/gptApprovals.test.ts +762 -0
  382. package/src/routes/gptDatasets.test.ts +86 -0
  383. package/src/routes/gptDatasets.ts +104 -0
  384. package/src/routes/gptFiles.test.ts +589 -0
  385. package/src/routes/gptHistories.test.ts +933 -0
  386. package/src/routes/gptHistories.ts +266 -5
  387. package/src/routes/routes.test.ts +222 -2
  388. package/src/service/aiDatasets.test.ts +123 -0
  389. package/src/service/aiDatasets.ts +316 -0
  390. package/src/service/aiService.test.ts +593 -0
  391. package/src/service/aiService.ts +568 -111
  392. package/src/service/askFiles.test.ts +96 -0
  393. package/src/service/askFiles.ts +222 -0
  394. package/src/service/asks.test.ts +946 -0
  395. package/src/service/asks.ts +423 -0
  396. package/src/service/chatTurn.ts +2287 -0
  397. package/src/service/fileStorage.test.ts +11 -0
  398. package/src/service/fileStorage.ts +10 -2
  399. package/src/service/fillActionIds.test.ts +65 -0
  400. package/src/service/fillActionIds.ts +98 -0
  401. package/src/service/jsonFenceModel.test.ts +47 -0
  402. package/src/service/jsonFenceModel.ts +53 -0
  403. package/src/service/prompts.test.ts +21 -0
  404. package/src/service/prompts.ts +147 -0
  405. package/src/service/sanitizeHtml.test.ts +61 -0
  406. package/src/service/sanitizeHtml.ts +109 -0
  407. package/src/tests/bunSetup.test.ts +7 -4
  408. package/src/tests/bunSetup.ts +7 -7
  409. package/src/tests/chatHarness.ts +478 -0
  410. package/src/tests/generateStream.ts +49 -0
  411. package/src/tests/harnessErrors.ts +22 -0
  412. package/src/tests/harnessStreaming.ts +227 -0
  413. package/src/tests/helpers.ts +9 -2
  414. package/src/types/harness.ts +1119 -0
  415. package/src/types/index.ts +209 -13
  416. package/src/types/observability.ts +344 -0
  417. package/src/types/sanitize-html.d.ts +25 -0
@@ -0,0 +1,604 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runClaimedTask = exports.recoverExpiredTasks = exports.listRunnableTasks = exports.claimTaskById = exports.claimNextTask = void 0;
7
+ const api_1 = require("@terreno/api");
8
+ const luxon_1 = require("luxon");
9
+ const mongoose_1 = __importDefault(require("mongoose"));
10
+ const harness_1 = require("../types/harness");
11
+ const agentTaskNames_1 = require("./agentTaskNames");
12
+ const approvals_1 = require("./approvals");
13
+ const commit_1 = require("./commit");
14
+ const defineTask_1 = require("./defineTask");
15
+ const definitionError_1 = require("./definitionError");
16
+ const errors_1 = require("./errors");
17
+ const events_1 = require("./events");
18
+ const internalRuntime_1 = require("./internalRuntime");
19
+ const leases_1 = require("./leases");
20
+ const memo_1 = require("./memo");
21
+ const ownership_1 = require("./ownership");
22
+ const retryBackoff_1 = require("./retryBackoff");
23
+ const subagent_1 = require("./subagent");
24
+ const suspend_1 = require("./suspend");
25
+ const waits_1 = require("./waits");
26
+ /** Registry key of the built-in agent turn every subagent runs. */
27
+ const AGENT_TURN_KEY = (0, defineTask_1.taskDefinitionKey)({ name: agentTaskNames_1.AGENT_TURN_TASK_NAME, version: 1 });
28
+ /** Most expired tasks one recovery pass handles; the next pass picks up the rest. */
29
+ const RECOVERY_BATCH_SIZE = 100;
30
+ const assertValidNext = (definition, next) => {
31
+ if ("terminal" in next) {
32
+ const { status } = next.terminal;
33
+ if (status !== "completed" && status !== "failed") {
34
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: terminal status must be "completed" or "failed"`);
35
+ }
36
+ return;
37
+ }
38
+ if (!definition.phases[next.phase]) {
39
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.commit to unknown phase "${next.phase}"`);
40
+ }
41
+ };
42
+ const registeredFilter = (definitions) => {
43
+ return [...definitions.values()].map(({ name, version }) => ({ name, version }));
44
+ };
45
+ /**
46
+ * Mongo filter for a registered task a runner may claim now: `pending` and due, or
47
+ * `waiting` on an event or sleep whose `timeoutAt` passed, and not being aborted.
48
+ */
49
+ const runnableTaskFilter = (definitions, now) => ({
50
+ $and: [
51
+ { $or: registeredFilter(definitions) },
52
+ {
53
+ $or: [
54
+ {
55
+ $or: [{ runAt: { $exists: false } }, { runAt: null }, { runAt: { $lte: now.toJSDate() } }],
56
+ status: harness_1.HARNESS_TASK_STATUSES.pending,
57
+ },
58
+ // An event wait or sleep whose timeout passed resumes like a due retry.
59
+ {
60
+ status: harness_1.HARNESS_TASK_STATUSES.waiting,
61
+ "waiting.kind": { $in: [harness_1.HARNESS_WAIT_KINDS.event, harness_1.HARNESS_WAIT_KINDS.sleep] },
62
+ "waiting.timeoutAt": { $lte: now.toJSDate() },
63
+ },
64
+ ],
65
+ },
66
+ ],
67
+ // A task being aborted never starts another run.
68
+ "abortRequested.at": { $exists: false },
69
+ });
70
+ /** Move a runnable task to `running` under a fresh lease (owner, fencing token, expiry). */
71
+ const claimUpdate = (lease) => ({
72
+ $inc: { claims: 1 },
73
+ $set: { lease: (0, commit_1.newTaskLease)(lease), status: harness_1.HARNESS_TASK_STATUSES.running },
74
+ $unset: { waiting: 1 },
75
+ });
76
+ /**
77
+ * Atomically move the oldest runnable, registered task (`pending` and due, or `waiting` on
78
+ * an event or sleep whose `timeoutAt` passed) to `running` and give it a fresh lease (owner, fencing token, expiry) for the phase about to start.
79
+ */
80
+ const claimNextTask = async ({ definitions, lease, models, }) => {
81
+ if (definitions.size === 0) {
82
+ return null;
83
+ }
84
+ return models.task.findOneAndUpdate(runnableTaskFilter(definitions, luxon_1.DateTime.now()), claimUpdate(lease), { returnDocument: "after", sort: { created: 1 } });
85
+ };
86
+ exports.claimNextTask = claimNextTask;
87
+ /**
88
+ * Claim one task by id under the same rules as `claimNextTask`. Null when the task is not
89
+ * runnable now: unknown, not due, already claimed by another runner, terminal, or aborting.
90
+ */
91
+ const claimTaskById = async ({ definitions, lease, models, taskId, }) => {
92
+ if (definitions.size === 0 || !mongoose_1.default.isValidObjectId(taskId)) {
93
+ return null;
94
+ }
95
+ return models.task.findOneAndUpdate({ ...runnableTaskFilter(definitions, luxon_1.DateTime.now()), _id: toObjectId(taskId) }, claimUpdate(lease), { returnDocument: "after" });
96
+ };
97
+ exports.claimTaskById = claimTaskById;
98
+ /** Oldest runnable, registered tasks first, at most `limit`, without claiming them. */
99
+ const listRunnableTasks = async ({ definitions, limit, models, }) => {
100
+ if (definitions.size === 0) {
101
+ return [];
102
+ }
103
+ const tasks = await models.task
104
+ .find(runnableTaskFilter(definitions, luxon_1.DateTime.now()))
105
+ .select({ attempt: 1, claims: 1, phase: 1 })
106
+ .sort({ created: 1 })
107
+ .limit(limit);
108
+ return tasks.map((task) => ({
109
+ attempt: task.attempt ?? 0,
110
+ claims: task.claims ?? 0,
111
+ phase: task.phase,
112
+ taskId: String(task._id),
113
+ }));
114
+ };
115
+ exports.listRunnableTasks = listRunnableTasks;
116
+ /**
117
+ * Give a task that is still `running` under `task`'s lease back to the runners as
118
+ * `pending` at its current checkpoint. False when the lease moved on (aborted, recovered).
119
+ */
120
+ const releaseTask = async (models, task) => {
121
+ const result = await models.task.updateOne({
122
+ _id: task._id,
123
+ "lease.token": task.lease?.token ?? null,
124
+ status: harness_1.HARNESS_TASK_STATUSES.running,
125
+ }, { $set: { status: harness_1.HARNESS_TASK_STATUSES.pending }, $unset: { lease: 1 } });
126
+ return result.modifiedCount > 0;
127
+ };
128
+ /**
129
+ * Find `running` tasks whose lease expired (their runner died or froze mid-phase) and
130
+ * resolve each by its current phase's `replay`: `safe` goes back to `pending` at the same
131
+ * checkpoint; anything else is parked `interrupted`, or failed (owner woken) when the
132
+ * definition sets `onInterrupt: "fail"`. Tasks of unregistered versions are
133
+ * left for a runner that registers them. Then wake tasks whose child wait settled
134
+ * without a wake (a crash between a child's outcome and its owner check). Returns how
135
+ * many tasks became runnable.
136
+ */
137
+ const recoverExpiredTasks = async (engine) => {
138
+ const { definitions, models, testHooks } = engine;
139
+ if (definitions.size === 0) {
140
+ return 0;
141
+ }
142
+ const expired = await models.task
143
+ .find({ ...(0, commit_1.expiredLeaseFilter)(luxon_1.DateTime.now()), $and: [{ $or: registeredFilter(definitions) }] })
144
+ .sort({ created: 1 })
145
+ .limit(RECOVERY_BATCH_SIZE);
146
+ let runnable = 0;
147
+ for (const task of expired) {
148
+ const definition = definitions.get((0, defineTask_1.taskDefinitionKey)(task));
149
+ const action = interruptionAction(definition, task.phase);
150
+ try {
151
+ const recovered = await (0, commit_1.commitInterruption)({ action, models, task, testHooks });
152
+ api_1.logger.warn(`Harness task ${task._id} (${(0, defineTask_1.taskDefinitionKey)(task)}) was interrupted in phase "${task.phase}"; ${INTERRUPTION_LOG[action]}`);
153
+ if (action === "replay") {
154
+ runnable += 1;
155
+ }
156
+ if (action === "fail") {
157
+ await (0, ownership_1.settleTaskOwner)({ engine, task: recovered });
158
+ }
159
+ }
160
+ catch (error) {
161
+ // Another runner recovered it first, or its lease was renewed after the scan.
162
+ if (error instanceof commit_1.HarnessCommitConflictError) {
163
+ continue;
164
+ }
165
+ api_1.logger.error(`Harness could not recover task ${task._id}: ${(0, errors_1.errorMessage)(error)}`);
166
+ }
167
+ }
168
+ return runnable + (await (0, ownership_1.sweepWaitingTasks)(engine)) + (await (0, ownership_1.sweepQueuedConversations)(engine));
169
+ };
170
+ exports.recoverExpiredTasks = recoverExpiredTasks;
171
+ const INTERRUPTION_LOG = {
172
+ fail: "failed it (not retried)",
173
+ park: "parked as interrupted",
174
+ replay: "re-running it",
175
+ };
176
+ /** What recovery does with an expired task in `phase`, by its definition's policies. */
177
+ const interruptionAction = (definition, phase) => {
178
+ if (definition?.phases[phase]?.replay === "safe") {
179
+ return "replay";
180
+ }
181
+ return definition?.onInterrupt === "fail" ? "fail" : "park";
182
+ };
183
+ /**
184
+ * Run a claimed task's phases in order until it stops: terminal, `pending` for a retry,
185
+ * `waiting`, or aborted. A phase that throws is retried under the task's `retry` policy
186
+ * and fails the task once attempts run out. When a commit transaction fails, or the lease
187
+ * was lost, the task is left at its last checkpoint and expired-lease recovery decides
188
+ * what happens next. A terminal task re-checks the task that owns it.
189
+ */
190
+ const runClaimedTask = async ({ engine, lease, maxPhases, task, }) => {
191
+ const definition = engine.definitions.get((0, defineTask_1.taskDefinitionKey)(task));
192
+ if (!definition) {
193
+ throw (0, errors_1.harnessError)({
194
+ detail: `No registered task definition for ${(0, defineTask_1.taskDefinitionKey)(task)}`,
195
+ kind: "notRegistered",
196
+ });
197
+ }
198
+ const taskId = String(task._id);
199
+ const controller = new AbortController();
200
+ engine.controllers.set(taskId, controller);
201
+ try {
202
+ let current = task;
203
+ let phasesRun = 0;
204
+ while (current.status === harness_1.HARNESS_TASK_STATUSES.running && !controller.signal.aborted) {
205
+ if (maxPhases !== undefined && phasesRun >= maxPhases) {
206
+ if (!(await releaseTask(engine.models, current))) {
207
+ api_1.logger.info(`Harness task ${taskId} lost its lease before hand-off; stopping`);
208
+ }
209
+ return;
210
+ }
211
+ // An abort from another process may have fenced the task since the last commit.
212
+ if (phasesRun > 0 && !(await holdsLease(engine.models, current))) {
213
+ api_1.logger.info(`Harness task ${taskId} lost its lease between phases; stopping`);
214
+ return;
215
+ }
216
+ phasesRun += 1;
217
+ const result = await runPhase({ controller, definition, engine, lease, task: current });
218
+ if (!result) {
219
+ return;
220
+ }
221
+ current = result;
222
+ }
223
+ if (harness_1.HARNESS_TERMINAL_STATUSES.has(current.status)) {
224
+ await (0, ownership_1.settleTaskOwner)({ engine, task: current });
225
+ }
226
+ }
227
+ finally {
228
+ engine.controllers.delete(taskId);
229
+ }
230
+ };
231
+ exports.runClaimedTask = runClaimedTask;
232
+ /** Whether `task`'s current lease token is still the one stored. */
233
+ const holdsLease = async (models, task) => {
234
+ const held = await models.task.countDocuments({
235
+ _id: task._id,
236
+ "lease.token": task.lease?.token ?? null,
237
+ status: harness_1.HARNESS_TASK_STATUSES.running,
238
+ });
239
+ return held > 0;
240
+ };
241
+ const toObjectId = (id) => {
242
+ return typeof id === "string" ? new mongoose_1.default.Types.ObjectId(id) : id;
243
+ };
244
+ const runPhase = async ({ controller, definition, engine, lease, task, }) => {
245
+ const { models, testHooks } = engine;
246
+ const taskId = String(task._id);
247
+ const phaseStartedAt = luxon_1.DateTime.now();
248
+ let committed = null;
249
+ let commitStarted = false;
250
+ let commitFailure;
251
+ let childIndex = 0;
252
+ let agentIndex = 0;
253
+ let waitIndex = 0;
254
+ const heartbeat = (0, leases_1.startTaskHeartbeat)({
255
+ lease,
256
+ models,
257
+ onLost: () => controller.abort(new Error("Task lease lost")),
258
+ taskId: task._id,
259
+ testHooks,
260
+ token: task.lease?.token,
261
+ });
262
+ const assertOpen = (method) => {
263
+ if (commitStarted) {
264
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: ${method} called after the phase "${task.phase}" committed or started waiting`);
265
+ }
266
+ };
267
+ /** Run one fenced write that ends the phase; record its failure for the caller. */
268
+ const settlePhase = async (write) => {
269
+ commitStarted = true;
270
+ // The commit decides the lease's fate: renewed under a new token, cleared, or
271
+ // (on failure) left to expire for recovery.
272
+ await heartbeat.stop();
273
+ try {
274
+ committed = await write();
275
+ }
276
+ catch (error) {
277
+ commitFailure = error;
278
+ throw error;
279
+ }
280
+ };
281
+ const commitWithWrites = async (next, writes) => {
282
+ if (commitStarted) {
283
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.commit called more than once in phase "${task.phase}"`);
284
+ }
285
+ assertValidNext(definition, next);
286
+ await settlePhase(() => (0, commit_1.commitPhase)({ lease, models, next, phaseStartedAt, task, testHooks, writes }));
287
+ };
288
+ const commit = (next) => commitWithWrites(next);
289
+ const createTask = async (childDefinition, input, options = {}) => {
290
+ assertOpen("rt.createTask");
291
+ const registered = engine.definitions.get(childDefinition.key);
292
+ if (!registered) {
293
+ throw new definitionError_1.HarnessDefinitionError(`${childDefinition.key} is not in this harness registry`);
294
+ }
295
+ const key = options.key ?? String(childIndex);
296
+ childIndex += 1;
297
+ const child = await (0, commit_1.createChildTaskRecords)({
298
+ definition: registered,
299
+ input,
300
+ key,
301
+ lease,
302
+ models,
303
+ options,
304
+ parent: task,
305
+ });
306
+ engine.wake();
307
+ return String(child._id);
308
+ };
309
+ const waitForTasks = async (ids, options = {}) => {
310
+ assertOpen("rt.waitForTasks");
311
+ const policy = options.policy ?? harness_1.HARNESS_WAIT_POLICIES.all;
312
+ if (!Object.values(harness_1.HARNESS_WAIT_POLICIES).includes(policy)) {
313
+ throw new definitionError_1.HarnessDefinitionError(`rt.waitForTasks policy must be one of ${Object.values(harness_1.HARNESS_WAIT_POLICIES).join(", ")}`);
314
+ }
315
+ const childIds = [...new Set(ids.map(String))].map(toObjectId);
316
+ const owned = await models.task.countDocuments({
317
+ _id: { $in: childIds },
318
+ "ownership.id": task._id,
319
+ "ownership.kind": "task",
320
+ });
321
+ if (owned !== childIds.length) {
322
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.waitForTasks only waits on tasks this task created with rt.createTask`);
323
+ }
324
+ const { children, isSettled } = await (0, ownership_1.settleChildren)({
325
+ engine,
326
+ ids: childIds,
327
+ ownerId: task._id,
328
+ policy,
329
+ });
330
+ if (isSettled) {
331
+ return (0, ownership_1.childOutcomes)(ids.map(String), children);
332
+ }
333
+ await settlePhase(async () => {
334
+ const parked = await (0, commit_1.commitWaiting)({
335
+ models,
336
+ phaseStartedAt,
337
+ task,
338
+ testHooks,
339
+ waiting: { kind: harness_1.HARNESS_WAIT_KINDS.tasks, policy, taskIds: childIds },
340
+ });
341
+ return parked.task;
342
+ });
343
+ // A child may have settled between the check above and the waiting commit.
344
+ await (0, ownership_1.checkTaskWait)({ engine, taskId: task._id });
345
+ throw new suspend_1.HarnessSuspendSignal(taskId);
346
+ };
347
+ /**
348
+ * Shared by `rt.waitFor`, `rt.sleep`, and `rt.approval`: resolve the call now, or park the
349
+ * task on it. `plan` builds the request from the call's key.
350
+ */
351
+ const waitCall = async (method, plan) => {
352
+ assertOpen(method);
353
+ // Taken before any await, so the call's key depends only on its order in the phase.
354
+ const callKey = (0, waits_1.waitCallKey)({ index: waitIndex, task });
355
+ waitIndex += 1;
356
+ const { afterPark, onPark, request } = plan(callKey);
357
+ let result;
358
+ try {
359
+ result = await (0, waits_1.resolveWaitCall)({
360
+ callKey,
361
+ label: definition.key,
362
+ lease,
363
+ models,
364
+ request,
365
+ task,
366
+ testHooks,
367
+ });
368
+ }
369
+ catch (error) {
370
+ // A lost lease ends the run like a failed commit: nothing more may be written.
371
+ if (error instanceof commit_1.HarnessCommitConflictError) {
372
+ commitStarted = true;
373
+ commitFailure = error;
374
+ }
375
+ throw error;
376
+ }
377
+ if (result.isResolved) {
378
+ return result.payload;
379
+ }
380
+ const { entry } = result;
381
+ let isWoken = false;
382
+ await settlePhase(async () => {
383
+ const parked = await (0, commit_1.commitWaiting)({
384
+ models,
385
+ phaseStartedAt,
386
+ task,
387
+ testHooks,
388
+ waitCall: { entry, key: callKey },
389
+ waiting: { key: entry.key, kind: entry.kind, timeoutAt: entry.timeoutAt },
390
+ writes: onPark,
391
+ });
392
+ isWoken = parked.isWoken;
393
+ return parked.task;
394
+ });
395
+ // An event buffered before the wait committed sent the task straight back to pending.
396
+ if (isWoken) {
397
+ engine.wake();
398
+ }
399
+ await afterPark?.();
400
+ throw new suspend_1.HarnessSuspendSignal(taskId);
401
+ };
402
+ const requestApproval = async (key, options, extension) => {
403
+ assertOpen("rt.approval");
404
+ const timeout = (0, approvals_1.parseApprovalRequest)({ key, label: definition.key, options });
405
+ let approval;
406
+ await waitCall("rt.approval", (callKey) => {
407
+ approval = (0, approvals_1.approvalWaitPlan)({ callKey, extension, key, models, options, task, timeout });
408
+ return approval;
409
+ });
410
+ return approval.result();
411
+ };
412
+ const waitFor = async (event, options = {}) => {
413
+ if (typeof event !== "string" || !event.trim()) {
414
+ assertOpen("rt.waitFor");
415
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.waitFor requires an event name`);
416
+ }
417
+ const timeout = options?.timeout === undefined
418
+ ? undefined
419
+ : (0, waits_1.parseWaitDuration)(options.timeout, `${definition.key}: rt.waitFor timeout`);
420
+ return waitCall("rt.waitFor", () => ({
421
+ request: { duration: timeout, event, kind: harness_1.HARNESS_WAIT_KINDS.event },
422
+ }));
423
+ };
424
+ const sleep = async (duration) => {
425
+ const length = (0, waits_1.parseWaitDuration)(duration, `${definition.key}: rt.sleep duration`);
426
+ await waitCall("rt.sleep", () => ({
427
+ request: { duration: length, kind: harness_1.HARNESS_WAIT_KINDS.sleep },
428
+ }));
429
+ };
430
+ const runAgent = async (agent, options) => {
431
+ assertOpen("rt.runAgent");
432
+ if (!options || typeof options !== "object") {
433
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.runAgent requires {input}`);
434
+ }
435
+ // Taken before any await, so the call's key depends only on its order in the phase.
436
+ const callIndex = agentIndex;
437
+ agentIndex += 1;
438
+ if (!agent?.name || engine.agents.get(agent.name) !== agent) {
439
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.runAgent agent "${agent?.name}" is not in this harness registry`);
440
+ }
441
+ const content = (0, subagent_1.subagentContent)(options.input);
442
+ if (content === undefined) {
443
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.runAgent requires non-empty input`);
444
+ }
445
+ const turn = engine.definitions.get(AGENT_TURN_KEY);
446
+ if (!turn) {
447
+ throw (0, errors_1.harnessError)({ detail: `${AGENT_TURN_KEY} is not registered`, kind: "notRegistered" });
448
+ }
449
+ const schema = (options.output ?? agent.output);
450
+ let outputSchema;
451
+ if (schema) {
452
+ try {
453
+ outputSchema = await (0, subagent_1.serializeOutputSchema)(schema);
454
+ }
455
+ catch (error) {
456
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.runAgent output for "${agent.name}" cannot be expressed as JSON Schema: ${(0, errors_1.errorMessage)(error)}`);
457
+ }
458
+ }
459
+ const { conversationId, turnTask } = await (0, subagent_1.startSubagentTurn)({
460
+ agent,
461
+ callIndex,
462
+ content,
463
+ extensions: engine.extensions,
464
+ instructions: options.instructions,
465
+ lease,
466
+ models,
467
+ outputSchema,
468
+ parent: task,
469
+ turn,
470
+ });
471
+ engine.wake();
472
+ const [outcome] = await waitForTasks([turnTask._id]);
473
+ return (0, subagent_1.subagentResult)({
474
+ agent,
475
+ conversationId,
476
+ outcome: outcome,
477
+ schema,
478
+ });
479
+ };
480
+ const failOrRetry = async ({ error, isRetryable, }) => {
481
+ await heartbeat.stop();
482
+ const policy = (0, retryBackoff_1.resolveRetryPolicy)(task.retry);
483
+ const failedAttempts = task.attempt + 1;
484
+ try {
485
+ if (isRetryable && failedAttempts < policy.maxAttempts) {
486
+ const runAt = (0, retryBackoff_1.nextRetryAt)({ failedAttempts, policy, random: testHooks?.random });
487
+ const retried = await (0, commit_1.commitRetry)({
488
+ error,
489
+ failedAttempts,
490
+ maxAttempts: policy.maxAttempts,
491
+ models,
492
+ phaseStartedAt,
493
+ runAt,
494
+ task,
495
+ testHooks,
496
+ });
497
+ api_1.logger.warn(`Harness task ${taskId} phase "${task.phase}" failed (attempt ${failedAttempts} of ${policy.maxAttempts}); retrying at ${runAt.toISO()}: ${error}`);
498
+ return retried;
499
+ }
500
+ return await (0, commit_1.commitPhase)({
501
+ failedAttempts: isRetryable ? failedAttempts : undefined,
502
+ lease,
503
+ models,
504
+ next: { terminal: { error, status: "failed" } },
505
+ phaseStartedAt,
506
+ task,
507
+ testHooks,
508
+ });
509
+ }
510
+ catch (commitError) {
511
+ api_1.logger.error(`Harness task ${taskId} could not record failure of phase "${task.phase}": ${(0, errors_1.errorMessage)(commitError)}`);
512
+ return null;
513
+ }
514
+ };
515
+ const memoFor = (scopeTaskId) => (0, memo_1.createMemo)({
516
+ assertWritable: () => assertOpen("rt.memo"),
517
+ fence: { phase: task.phase, taskId: task._id, token: task.lease?.token },
518
+ lease,
519
+ models,
520
+ scopeTaskId: toObjectId(scopeTaskId),
521
+ });
522
+ const output = async (text) => {
523
+ assertOpen("rt.output");
524
+ if (typeof text !== "string") {
525
+ throw new definitionError_1.HarnessDefinitionError(`${definition.key}: rt.output takes a string`);
526
+ }
527
+ if (!text) {
528
+ return;
529
+ }
530
+ await (0, events_1.appendTaskEvents)({
531
+ events: [
532
+ {
533
+ payload: { attempt: task.attempt, phase: task.phase, text },
534
+ type: harness_1.HARNESS_EVENT_TYPES.output,
535
+ },
536
+ ],
537
+ models,
538
+ task,
539
+ });
540
+ };
541
+ const phase = definition.phases[task.phase];
542
+ if (!phase) {
543
+ return failOrRetry({
544
+ error: `${definition.key}: unknown phase "${task.phase}"`,
545
+ isRetryable: false,
546
+ });
547
+ }
548
+ const rt = {
549
+ [internalRuntime_1.HARNESS_INTERNAL_RUNTIME]: {
550
+ approvalFor: (extension) => (key, options) => requestApproval(key, options, extension),
551
+ commitWithWrites,
552
+ memoFor,
553
+ },
554
+ approval: (key, options) => requestApproval(key, options),
555
+ commit,
556
+ createTask: createTask,
557
+ env: engine.env,
558
+ memo: memoFor(task._id),
559
+ output,
560
+ runAgent: runAgent,
561
+ signal: controller.signal,
562
+ sleep,
563
+ taskId,
564
+ waitFor: waitFor,
565
+ waitForTasks,
566
+ };
567
+ let thrown;
568
+ try {
569
+ await phase.run((0, ownership_1.toTaskView)(task), rt);
570
+ }
571
+ catch (error) {
572
+ thrown = { error };
573
+ }
574
+ await heartbeat.stop();
575
+ if (commitFailure !== undefined && controller.signal.aborted) {
576
+ api_1.logger.info(`Harness task ${taskId} phase "${task.phase}" was aborted; its commit was discarded`);
577
+ return null;
578
+ }
579
+ if (commitFailure !== undefined) {
580
+ api_1.logger.error(`Harness task ${taskId} phase "${task.phase}" commit failed; task stays at its last checkpoint: ${(0, errors_1.errorMessage)(commitFailure)}`);
581
+ return null;
582
+ }
583
+ if (committed) {
584
+ if (thrown && !(thrown.error instanceof suspend_1.HarnessSuspendSignal)) {
585
+ api_1.logger.warn(`Harness task ${taskId} phase "${task.phase}" threw after committing; keeping the checkpoint: ${(0, errors_1.errorMessage)(thrown.error)}`);
586
+ }
587
+ return committed;
588
+ }
589
+ // Aborted (or taken over) mid-phase: the abort already settled the task; record nothing.
590
+ if (controller.signal.aborted) {
591
+ api_1.logger.info(`Harness task ${taskId} phase "${task.phase}" stopped after its abort signal`);
592
+ return null;
593
+ }
594
+ if (thrown) {
595
+ return failOrRetry({
596
+ error: (0, errors_1.errorMessage)(thrown.error),
597
+ isRetryable: !(thrown.error instanceof definitionError_1.HarnessDefinitionError),
598
+ });
599
+ }
600
+ return failOrRetry({
601
+ error: `${definition.key}: phase "${task.phase}" returned without calling rt.commit`,
602
+ isRetryable: false,
603
+ });
604
+ };
@@ -0,0 +1,53 @@
1
+ import type { z } from "@terreno/api";
2
+ import type { HarnessAgentDefinition, HarnessChildOutcome, HarnessExtensionDefinition, HarnessLeaseSettings, HarnessTaskDefinition, HarnessTaskDocument } from "../types/harness";
3
+ import { type HarnessModels } from "./commit";
4
+ /** A subagent run by `rt.runAgent` did not produce a usable answer. */
5
+ export declare class HarnessSubagentError extends Error {
6
+ readonly agentName: string;
7
+ readonly conversationId: string;
8
+ /** Terminal status of the subagent's turn task. */
9
+ readonly status: HarnessChildOutcome["status"];
10
+ readonly turnTaskId: string;
11
+ constructor({ agentName, conversationId, message, outcome, }: {
12
+ agentName: string;
13
+ conversationId: string;
14
+ message: string;
15
+ outcome: HarnessChildOutcome;
16
+ });
17
+ }
18
+ /** The subagent's user message: strings as-is, anything else as JSON. */
19
+ export declare const subagentContent: (input: unknown) => string | undefined;
20
+ /**
21
+ * Serialize `schema` as JSON Schema with the AI SDK's own converter, so the turn requests
22
+ * exactly the structure `Output.object` would. Stored as a string: JSON Schema keys such
23
+ * as `$schema` and `$ref` are not valid Mongo field names.
24
+ */
25
+ export declare const serializeOutputSchema: (schema: z.ZodType) => Promise<string>;
26
+ /**
27
+ * Create the subagent's conversation, its user message, and its turn (a child task of
28
+ * `parent` with an `AGENT` span named after the agent) in one transaction. A re-run of
29
+ * the same phase attempt finds the turn created first, and with it the same conversation.
30
+ */
31
+ export declare const startSubagentTurn: ({ agent, callIndex, content, extensions, instructions, lease, models, outputSchema, parent, turn, }: {
32
+ agent: HarnessAgentDefinition;
33
+ callIndex: number;
34
+ content: string;
35
+ /** Registered extensions, for the conversation's tool snapshot. */
36
+ extensions: Map<string, HarnessExtensionDefinition>;
37
+ instructions?: string;
38
+ lease: HarnessLeaseSettings;
39
+ models: HarnessModels;
40
+ outputSchema?: string;
41
+ parent: HarnessTaskDocument;
42
+ turn: HarnessTaskDefinition;
43
+ }) => Promise<{
44
+ conversationId: string;
45
+ turnTask: HarnessTaskDocument;
46
+ }>;
47
+ /** The value `rt.runAgent` returns for a settled turn, or the error it throws. */
48
+ export declare const subagentResult: <Result>({ agent, conversationId, outcome, schema, }: {
49
+ agent: HarnessAgentDefinition;
50
+ conversationId: string;
51
+ outcome: HarnessChildOutcome;
52
+ schema?: z.ZodType<Result>;
53
+ }) => Result;