@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,522 @@
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.Harness = exports.HarnessSubagentError = exports.InProcessRunner = exports.IN_PROCESS_RUNNER_ROLES = exports.isRetryableModelError = exports.HarnessModelCallError = exports.HarnessApp = exports.wrapTool = exports.section = exports.hook = exports.HarnessExtensionError = exports.defineExtension = exports.HARNESS_ERRORS = exports.HarnessDefinitionError = exports.defineTool = exports.defineTask = exports.defineAgent = exports.HarnessConversationOwnedError = exports.HarnessConversationHandle = exports.HarnessConversationBusyError = exports.HarnessCommitConflictError = exports.HarnessApprovalConflictError = exports.HARNESS_DEFAULT_APPROVERS = exports.approvalTaskInput = exports.approvalGate = exports.AGENT_TURN_TASK_NAME = exports.AGENT_TOOL_TASK_NAME = exports.harnessAdminScreens = exports.HARNESS_APPROVALS_SCREEN = exports.AI_HARNESS_GROUP = exports.HARNESS_WHEN_BUSY = exports.HARNESS_WAIT_RESOLUTIONS = exports.HARNESS_WAIT_POLICIES = exports.HARNESS_WAIT_KINDS = exports.HARNESS_TASK_STATUSES = exports.HARNESS_SUBMIT_DISPOSITIONS = exports.HARNESS_RETRY_DEFAULTS = exports.HARNESS_RESOLVE_ACTIONS = exports.HARNESS_MODEL_RETRY_DEFAULTS = exports.HARNESS_MESSAGE_ROLES = exports.HARNESS_INTERRUPT_ACTIONS = exports.HARNESS_HOOK_KINDS = exports.HARNESS_EVENT_TYPES = exports.HARNESS_CONVERSATION_STATUSES = exports.HARNESS_APPROVAL_STATUSES = exports.HARNESS_AGENT_DEFAULT_MAX_STEPS = void 0;
7
+ const luxon_1 = require("luxon");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const observabilityAppRegistry_1 = require("../observability/observabilityAppRegistry");
10
+ const harness_1 = require("../types/harness");
11
+ const agentLoop_1 = require("./agentLoop");
12
+ const approvals_1 = require("./approvals");
13
+ const commit_1 = require("./commit");
14
+ const conversation_1 = require("./conversation");
15
+ const defineAgent_1 = require("./defineAgent");
16
+ const defineTask_1 = require("./defineTask");
17
+ const errors_1 = require("./errors");
18
+ const events_1 = require("./events");
19
+ const leases_1 = require("./leases");
20
+ const harnessApproval_1 = require("./models/harnessApproval");
21
+ const harnessConversation_1 = require("./models/harnessConversation");
22
+ const harnessEvent_1 = require("./models/harnessEvent");
23
+ const harnessInboxEvent_1 = require("./models/harnessInboxEvent");
24
+ const harnessMemo_1 = require("./models/harnessMemo");
25
+ const harnessMessage_1 = require("./models/harnessMessage");
26
+ const harnessOwner_1 = require("./models/harnessOwner");
27
+ const harnessTask_1 = require("./models/harnessTask");
28
+ const ownership_1 = require("./ownership");
29
+ const registry_1 = require("./registry");
30
+ const inProcessRunner_1 = require("./runners/inProcessRunner");
31
+ const runtime_1 = require("./runtime");
32
+ const waits_1 = require("./waits");
33
+ var harness_2 = require("../types/harness");
34
+ Object.defineProperty(exports, "HARNESS_AGENT_DEFAULT_MAX_STEPS", { enumerable: true, get: function () { return harness_2.HARNESS_AGENT_DEFAULT_MAX_STEPS; } });
35
+ Object.defineProperty(exports, "HARNESS_APPROVAL_STATUSES", { enumerable: true, get: function () { return harness_2.HARNESS_APPROVAL_STATUSES; } });
36
+ Object.defineProperty(exports, "HARNESS_CONVERSATION_STATUSES", { enumerable: true, get: function () { return harness_2.HARNESS_CONVERSATION_STATUSES; } });
37
+ Object.defineProperty(exports, "HARNESS_EVENT_TYPES", { enumerable: true, get: function () { return harness_2.HARNESS_EVENT_TYPES; } });
38
+ Object.defineProperty(exports, "HARNESS_HOOK_KINDS", { enumerable: true, get: function () { return harness_2.HARNESS_HOOK_KINDS; } });
39
+ Object.defineProperty(exports, "HARNESS_INTERRUPT_ACTIONS", { enumerable: true, get: function () { return harness_2.HARNESS_INTERRUPT_ACTIONS; } });
40
+ Object.defineProperty(exports, "HARNESS_MESSAGE_ROLES", { enumerable: true, get: function () { return harness_2.HARNESS_MESSAGE_ROLES; } });
41
+ Object.defineProperty(exports, "HARNESS_MODEL_RETRY_DEFAULTS", { enumerable: true, get: function () { return harness_2.HARNESS_MODEL_RETRY_DEFAULTS; } });
42
+ Object.defineProperty(exports, "HARNESS_RESOLVE_ACTIONS", { enumerable: true, get: function () { return harness_2.HARNESS_RESOLVE_ACTIONS; } });
43
+ Object.defineProperty(exports, "HARNESS_RETRY_DEFAULTS", { enumerable: true, get: function () { return harness_2.HARNESS_RETRY_DEFAULTS; } });
44
+ Object.defineProperty(exports, "HARNESS_SUBMIT_DISPOSITIONS", { enumerable: true, get: function () { return harness_2.HARNESS_SUBMIT_DISPOSITIONS; } });
45
+ Object.defineProperty(exports, "HARNESS_TASK_STATUSES", { enumerable: true, get: function () { return harness_2.HARNESS_TASK_STATUSES; } });
46
+ Object.defineProperty(exports, "HARNESS_WAIT_KINDS", { enumerable: true, get: function () { return harness_2.HARNESS_WAIT_KINDS; } });
47
+ Object.defineProperty(exports, "HARNESS_WAIT_POLICIES", { enumerable: true, get: function () { return harness_2.HARNESS_WAIT_POLICIES; } });
48
+ Object.defineProperty(exports, "HARNESS_WAIT_RESOLUTIONS", { enumerable: true, get: function () { return harness_2.HARNESS_WAIT_RESOLUTIONS; } });
49
+ Object.defineProperty(exports, "HARNESS_WHEN_BUSY", { enumerable: true, get: function () { return harness_2.HARNESS_WHEN_BUSY; } });
50
+ var adminScreens_1 = require("./adminScreens");
51
+ Object.defineProperty(exports, "AI_HARNESS_GROUP", { enumerable: true, get: function () { return adminScreens_1.AI_HARNESS_GROUP; } });
52
+ Object.defineProperty(exports, "HARNESS_APPROVALS_SCREEN", { enumerable: true, get: function () { return adminScreens_1.HARNESS_APPROVALS_SCREEN; } });
53
+ Object.defineProperty(exports, "harnessAdminScreens", { enumerable: true, get: function () { return adminScreens_1.harnessAdminScreens; } });
54
+ var agentTaskNames_1 = require("./agentTaskNames");
55
+ Object.defineProperty(exports, "AGENT_TOOL_TASK_NAME", { enumerable: true, get: function () { return agentTaskNames_1.AGENT_TOOL_TASK_NAME; } });
56
+ Object.defineProperty(exports, "AGENT_TURN_TASK_NAME", { enumerable: true, get: function () { return agentTaskNames_1.AGENT_TURN_TASK_NAME; } });
57
+ var approvals_2 = require("./approvals");
58
+ Object.defineProperty(exports, "approvalGate", { enumerable: true, get: function () { return approvals_2.approvalGate; } });
59
+ Object.defineProperty(exports, "approvalTaskInput", { enumerable: true, get: function () { return approvals_2.approvalTaskInput; } });
60
+ Object.defineProperty(exports, "HARNESS_DEFAULT_APPROVERS", { enumerable: true, get: function () { return approvals_2.HARNESS_DEFAULT_APPROVERS; } });
61
+ Object.defineProperty(exports, "HarnessApprovalConflictError", { enumerable: true, get: function () { return approvals_2.HarnessApprovalConflictError; } });
62
+ var commit_2 = require("./commit");
63
+ Object.defineProperty(exports, "HarnessCommitConflictError", { enumerable: true, get: function () { return commit_2.HarnessCommitConflictError; } });
64
+ var conversation_2 = require("./conversation");
65
+ Object.defineProperty(exports, "HarnessConversationBusyError", { enumerable: true, get: function () { return conversation_2.HarnessConversationBusyError; } });
66
+ Object.defineProperty(exports, "HarnessConversationHandle", { enumerable: true, get: function () { return conversation_2.HarnessConversationHandle; } });
67
+ Object.defineProperty(exports, "HarnessConversationOwnedError", { enumerable: true, get: function () { return conversation_2.HarnessConversationOwnedError; } });
68
+ var defineAgent_2 = require("./defineAgent");
69
+ Object.defineProperty(exports, "defineAgent", { enumerable: true, get: function () { return defineAgent_2.defineAgent; } });
70
+ var defineTask_2 = require("./defineTask");
71
+ Object.defineProperty(exports, "defineTask", { enumerable: true, get: function () { return defineTask_2.defineTask; } });
72
+ var defineTool_1 = require("./defineTool");
73
+ Object.defineProperty(exports, "defineTool", { enumerable: true, get: function () { return defineTool_1.defineTool; } });
74
+ var definitionError_1 = require("./definitionError");
75
+ Object.defineProperty(exports, "HarnessDefinitionError", { enumerable: true, get: function () { return definitionError_1.HarnessDefinitionError; } });
76
+ var errors_2 = require("./errors");
77
+ Object.defineProperty(exports, "HARNESS_ERRORS", { enumerable: true, get: function () { return errors_2.HARNESS_ERRORS; } });
78
+ var extensions_1 = require("./extensions");
79
+ Object.defineProperty(exports, "defineExtension", { enumerable: true, get: function () { return extensions_1.defineExtension; } });
80
+ Object.defineProperty(exports, "HarnessExtensionError", { enumerable: true, get: function () { return extensions_1.HarnessExtensionError; } });
81
+ Object.defineProperty(exports, "hook", { enumerable: true, get: function () { return extensions_1.hook; } });
82
+ Object.defineProperty(exports, "section", { enumerable: true, get: function () { return extensions_1.section; } });
83
+ Object.defineProperty(exports, "wrapTool", { enumerable: true, get: function () { return extensions_1.wrapTool; } });
84
+ var harnessApp_1 = require("./harnessApp");
85
+ Object.defineProperty(exports, "HarnessApp", { enumerable: true, get: function () { return harnessApp_1.HarnessApp; } });
86
+ var modelCall_1 = require("./modelCall");
87
+ Object.defineProperty(exports, "HarnessModelCallError", { enumerable: true, get: function () { return modelCall_1.HarnessModelCallError; } });
88
+ Object.defineProperty(exports, "isRetryableModelError", { enumerable: true, get: function () { return modelCall_1.isRetryableModelError; } });
89
+ var inProcessRunner_2 = require("./runners/inProcessRunner");
90
+ Object.defineProperty(exports, "IN_PROCESS_RUNNER_ROLES", { enumerable: true, get: function () { return inProcessRunner_2.IN_PROCESS_RUNNER_ROLES; } });
91
+ Object.defineProperty(exports, "InProcessRunner", { enumerable: true, get: function () { return inProcessRunner_2.InProcessRunner; } });
92
+ var subagent_1 = require("./subagent");
93
+ Object.defineProperty(exports, "HarnessSubagentError", { enumerable: true, get: function () { return subagent_1.HarnessSubagentError; } });
94
+ /** How often an idle owner looks for queued submissions stranded by a crash. */
95
+ const QUEUE_SWEEP_INTERVAL = luxon_1.Duration.fromObject({ seconds: 1 });
96
+ const assertReplicaSet = async () => {
97
+ const db = mongoose_1.default.connection.db;
98
+ if (!db) {
99
+ throw (0, errors_1.harnessError)({
100
+ detail: "Harness.open requires a connected mongoose default connection",
101
+ kind: "configInvalid",
102
+ });
103
+ }
104
+ const hello = await db.command({ hello: 1 });
105
+ // Replica set members report setName; mongos ("isdbgrid") also supports transactions.
106
+ const isReplicaSet = typeof hello.setName === "string" && hello.setName.length > 0;
107
+ if (!isReplicaSet && hello.msg !== "isdbgrid") {
108
+ throw (0, errors_1.harnessError)({
109
+ detail: "Harness.open requires a MongoDB replica set: checkpoints and audit spans commit in one transaction",
110
+ kind: "replicaSetRequired",
111
+ });
112
+ }
113
+ };
114
+ const resolveObservabilityModels = () => {
115
+ const span = mongoose_1.default.models.ObsSpan;
116
+ const trace = mongoose_1.default.models.ObsTrace;
117
+ if (!span || !trace) {
118
+ throw (0, errors_1.harnessError)({
119
+ detail: "Harness.open requires the local observability plugin: call createLocalObservabilityPlugin() (or register ObservabilityApp with it) before opening the harness",
120
+ kind: "configInvalid",
121
+ });
122
+ }
123
+ return { span, trace };
124
+ };
125
+ /**
126
+ * Durable task engine. Owns the registry and Mongo storage; a pluggable runner decides
127
+ * who executes runnable tasks.
128
+ */
129
+ class Harness {
130
+ agents;
131
+ agentTasks;
132
+ definitions;
133
+ engine;
134
+ extensions;
135
+ isStarted = false;
136
+ nextQueueSweepAt = luxon_1.DateTime.fromMillis(0);
137
+ models;
138
+ runner;
139
+ testHooks;
140
+ constructor({ agents, agentTasks, definitions, env, extensions, models, runner, testHooks, }) {
141
+ this.agents = agents;
142
+ this.agentTasks = agentTasks;
143
+ this.definitions = definitions;
144
+ this.extensions = extensions;
145
+ this.models = models;
146
+ this.runner = runner;
147
+ this.testHooks = testHooks;
148
+ this.engine = {
149
+ agents,
150
+ controllers: new Map(),
151
+ definitions,
152
+ env,
153
+ extensions,
154
+ models,
155
+ testHooks,
156
+ wake: () => runner.wake(),
157
+ };
158
+ }
159
+ /**
160
+ * Validate the environment and build a harness. Throws when the local observability
161
+ * models are missing or the connection is not a replica set.
162
+ */
163
+ static async open(options) {
164
+ const { span, trace } = resolveObservabilityModels();
165
+ await assertReplicaSet();
166
+ const { agents, extensions, tasks } = (0, registry_1.splitRegistry)(options.registry);
167
+ if (agents.size > 0 && !options.models) {
168
+ throw (0, errors_1.harnessError)({
169
+ detail: "Harness.open: the registry lists agents; pass `models` to resolve them",
170
+ kind: "configInvalid",
171
+ });
172
+ }
173
+ const models = {
174
+ approval: (0, harnessApproval_1.registerHarnessApproval)(),
175
+ conversation: (0, harnessConversation_1.registerHarnessConversation)(),
176
+ event: (0, harnessEvent_1.registerHarnessEvent)(),
177
+ eventStream: (0, harnessEvent_1.registerHarnessEventStream)(),
178
+ inbox: (0, harnessInboxEvent_1.registerHarnessInboxEvent)(),
179
+ memo: (0, harnessMemo_1.registerHarnessMemo)(),
180
+ message: (0, harnessMessage_1.registerHarnessMessage)(),
181
+ owner: (0, harnessOwner_1.registerHarnessOwner)(),
182
+ span,
183
+ task: (0, harnessTask_1.registerHarnessTask)(),
184
+ trace,
185
+ };
186
+ const agentTasks = (0, agentLoop_1.createAgentTasks)({
187
+ agents,
188
+ extensions,
189
+ models,
190
+ priceMap: () => options.priceMap ?? (0, observabilityAppRegistry_1.getObservabilityApp)()?.priceMap,
191
+ random: options.testHooks?.random,
192
+ resolveModel: options.models,
193
+ streaming: (0, events_1.resolveStreamingOptions)(options.streaming),
194
+ });
195
+ // The built-in agent tasks are always registered, so in-flight turns resume anywhere.
196
+ const definitions = (0, registry_1.buildTaskRegistry)([
197
+ ...tasks,
198
+ agentTasks.turn,
199
+ agentTasks.tool,
200
+ ]);
201
+ // Transactions cannot create collections or indexes on every server version.
202
+ await Promise.all(Object.values(models).map((model) => model.init()));
203
+ return new Harness({
204
+ agents,
205
+ agentTasks,
206
+ definitions,
207
+ env: options.env,
208
+ extensions,
209
+ models,
210
+ runner: options.runner ?? new inProcessRunner_1.InProcessRunner(),
211
+ testHooks: options.testHooks,
212
+ });
213
+ }
214
+ /**
215
+ * Begin executing runnable tasks. First throws, claiming nothing, when any non-terminal
216
+ * task is pinned to a `name@version` missing from the registry. The runner recovers
217
+ * tasks whose lease expired once it owns execution (immediately, or on takeover when
218
+ * another owner holds the lease).
219
+ */
220
+ async start() {
221
+ if (this.isStarted) {
222
+ throw (0, errors_1.harnessError)({ detail: "Harness is already started", kind: "alreadyStarted" });
223
+ }
224
+ // Claimed before the first await so overlapping start() calls cannot both start the runner.
225
+ this.isStarted = true;
226
+ const { definitions, engine, models, testHooks } = this;
227
+ try {
228
+ await (0, registry_1.assertInFlightVersionsRegistered)({ definitions, models });
229
+ }
230
+ catch (error) {
231
+ this.isStarted = false;
232
+ throw error;
233
+ }
234
+ await this.runner.start({
235
+ acquireOwnerLease: (lease) => (0, leases_1.acquireOwnerLease)({ lease, models, testHooks }),
236
+ claimNext: (lease) => this.claimNextOrSweep(lease),
237
+ claimTask: (taskId, lease) => (0, runtime_1.claimTaskById)({ definitions, lease, models, taskId }),
238
+ listRunnable: (limit) => (0, runtime_1.listRunnableTasks)({ definitions, limit, models }),
239
+ recoverExpired: () => (0, runtime_1.recoverExpiredTasks)(engine),
240
+ releaseOwnerLease: (lease) => (0, leases_1.releaseOwnerLease)({ lease, models }),
241
+ runTask: (task, lease, options) => (0, runtime_1.runClaimedTask)({ engine, lease, maxPhases: options?.maxPhases, task }),
242
+ });
243
+ }
244
+ /**
245
+ * Claim the next runnable task. When there is none, at most once per
246
+ * `QUEUE_SWEEP_INTERVAL`, start queued submissions stranded on idle conversations (a
247
+ * process died between a turn's end and starting the next queued turn) and claim again.
248
+ */
249
+ async claimNextOrSweep(lease) {
250
+ const { definitions, engine, models } = this;
251
+ const task = await (0, runtime_1.claimNextTask)({ definitions, lease, models });
252
+ if (task || luxon_1.DateTime.now() < this.nextQueueSweepAt) {
253
+ return task;
254
+ }
255
+ this.nextQueueSweepAt = luxon_1.DateTime.now().plus(QUEUE_SWEEP_INTERVAL);
256
+ if ((await (0, ownership_1.sweepQueuedConversations)(engine)) === 0) {
257
+ return null;
258
+ }
259
+ return (0, runtime_1.claimNextTask)({ definitions, lease, models });
260
+ }
261
+ /** Stop claiming work and wait for every phase in flight to settle. */
262
+ async stop() {
263
+ if (!this.isStarted) {
264
+ return;
265
+ }
266
+ await this.runner.stop();
267
+ this.isStarted = false;
268
+ }
269
+ /**
270
+ * Create a root task pinned to `definition`'s `name@version`. With `requestId`, a
271
+ * repeated call returns the task created first.
272
+ */
273
+ async createTask(definition, input, options = {}) {
274
+ const registered = this.definitions.get(definition.key);
275
+ if (!registered) {
276
+ throw (0, errors_1.harnessError)({
277
+ detail: `${definition.key} is not in this harness registry`,
278
+ kind: "notRegistered",
279
+ });
280
+ }
281
+ const task = await (0, commit_1.createTaskRecords)({
282
+ definition: registered,
283
+ input,
284
+ models: this.models,
285
+ options,
286
+ });
287
+ this.runner.wake();
288
+ return task;
289
+ }
290
+ /**
291
+ * Abort a task and every non-terminal task it owns, deepest first. Each task's running
292
+ * phase (in this process, or elsewhere within one heartbeat) sees `rt.signal` abort; its
293
+ * `abort` handler runs; then it is committed `aborted` with an `abort` audit span. A
294
+ * failing handler is recorded on that span and the abort proceeds. Throws when `reason`
295
+ * is blank or the task is already terminal.
296
+ */
297
+ async abort(taskId, options) {
298
+ if (typeof options?.reason !== "string" || !options.reason.trim()) {
299
+ throw (0, errors_1.harnessError)({ detail: "abort requires a reason", kind: "invalidRequest" });
300
+ }
301
+ const task = await this.models.task.findExactlyOne({ _id: taskId });
302
+ if (harness_1.HARNESS_TERMINAL_STATUSES.has(task.status)) {
303
+ throw (0, errors_1.harnessError)({
304
+ detail: `Task ${taskId} is already ${task.status}`,
305
+ kind: "taskTerminal",
306
+ });
307
+ }
308
+ return (0, ownership_1.abortTaskTree)({
309
+ engine: this.engine,
310
+ reason: options.reason,
311
+ top: task,
312
+ userId: options.userId === undefined ? undefined : String(options.userId),
313
+ });
314
+ }
315
+ /**
316
+ * Send `event` with `payload` to a task. The event is stored durably first, so it is
317
+ * never lost: a task already waiting on `event` (`rt.waitFor`) goes back to `pending`
318
+ * and its `waitFor` returns `payload`; otherwise the event stays buffered until a
319
+ * `rt.waitFor(event)` takes it. Works while no runner is up. Delivery is FIFO per event
320
+ * name. With `requestId` (unique per task), a repeated send returns the event sent
321
+ * first. Throws when the task is terminal or `event` is blank.
322
+ */
323
+ async sendEvent(taskId, event, payload, options = {}) {
324
+ if (typeof event !== "string" || !event.trim()) {
325
+ throw (0, errors_1.harnessError)({ detail: "sendEvent requires an event name", kind: "invalidRequest" });
326
+ }
327
+ if (event.startsWith(approvals_1.HARNESS_RESERVED_EVENT_PREFIX)) {
328
+ throw (0, errors_1.harnessError)({
329
+ detail: `sendEvent: event names starting with "${approvals_1.HARNESS_RESERVED_EVENT_PREFIX}" are reserved for the harness (approval decisions use decideApproval)`,
330
+ kind: "invalidRequest",
331
+ });
332
+ }
333
+ const sent = await (0, waits_1.sendEventRecords)({
334
+ event,
335
+ models: this.models,
336
+ payload,
337
+ requestId: options.requestId,
338
+ taskId,
339
+ });
340
+ if (sent.isWoken) {
341
+ this.runner.wake();
342
+ }
343
+ return sent.event;
344
+ }
345
+ /**
346
+ * Approve or reject a pending approval as `userId`, without checking approvers (the
347
+ * `HarnessApp` routes check them first). In one transaction: the approval's status,
348
+ * `decidedBy`, `decidedAt`, `reason`; the event that wakes the waiting `rt.approval`;
349
+ * and the `approval:<key>` audit span. Throws `HarnessApprovalConflictError` when it is
350
+ * already decided or expired, or its task ended.
351
+ */
352
+ async decideApproval(approvalId, options) {
353
+ if (typeof options?.approved !== "boolean") {
354
+ throw (0, errors_1.harnessError)({
355
+ detail: "decideApproval requires approved: true or false",
356
+ kind: "invalidRequest",
357
+ });
358
+ }
359
+ if (!options.approved && !options.reason?.trim()) {
360
+ throw (0, errors_1.harnessError)({
361
+ detail: "decideApproval: a rejection requires a reason",
362
+ kind: "invalidRequest",
363
+ });
364
+ }
365
+ const { approval, isWoken } = await (0, approvals_1.decideApprovalRecords)({
366
+ approvalId,
367
+ models: this.models,
368
+ options,
369
+ });
370
+ if (isWoken) {
371
+ this.runner.wake();
372
+ }
373
+ return approval;
374
+ }
375
+ /**
376
+ * Whether `user` passes every approver of `approval` (its definition's or extension's
377
+ * `approvals[key]`, default `[Permissions.IsAdmin]`), called with `method`. False when
378
+ * this registry lacks the approval's `name@version` or extension.
379
+ */
380
+ async mayApprove({ approval, method = "update", user, }) {
381
+ return (0, approvals_1.userMayApprove)({ approval, method, registry: this.approvalRegistry(), user });
382
+ }
383
+ /** Pending, unexpired approvals of live tasks that `user` may approve, oldest first. */
384
+ async approvableApprovals({ user }) {
385
+ return (0, approvals_1.listApprovableApprovals)({ models: this.models, registry: this.approvalRegistry(), user });
386
+ }
387
+ approvalRegistry() {
388
+ return { definitions: this.definitions, extensions: this.extensions };
389
+ }
390
+ /**
391
+ * Decide what happens to an `interrupted` task: `retry` re-queues the same phase,
392
+ * `abort` runs its abort handler (after aborting every task it owns) and ends it
393
+ * `aborted`, `complete` ends it `completed` with `result`. The decision and its reason
394
+ * are audited in a `resolveInterrupted` span. Throws when the task is not
395
+ * `interrupted` or `reason` is empty.
396
+ */
397
+ async resolveInterrupted(taskId, options) {
398
+ if (!Object.values(harness_1.HARNESS_RESOLVE_ACTIONS).includes(options.action)) {
399
+ throw (0, errors_1.harnessError)({
400
+ detail: `resolveInterrupted action must be one of ${Object.values(harness_1.HARNESS_RESOLVE_ACTIONS).join(", ")}`,
401
+ kind: "invalidRequest",
402
+ });
403
+ }
404
+ if (typeof options.reason !== "string" || !options.reason.trim()) {
405
+ throw (0, errors_1.harnessError)({ detail: "resolveInterrupted requires a reason", kind: "invalidRequest" });
406
+ }
407
+ const task = await this.models.task.findExactlyOne({ _id: taskId });
408
+ if (task.status !== harness_1.HARNESS_TASK_STATUSES.interrupted) {
409
+ throw (0, errors_1.harnessError)({
410
+ detail: `Task ${taskId} is ${task.status}, not interrupted`,
411
+ kind: "taskNotInterrupted",
412
+ });
413
+ }
414
+ if (options.action === harness_1.HARNESS_RESOLVE_ACTIONS.retry && task.abortRequested?.at) {
415
+ throw (0, errors_1.harnessError)({
416
+ detail: `Task ${taskId} is being aborted; resolve it with abort, not retry`,
417
+ kind: "taskAborting",
418
+ });
419
+ }
420
+ if (options.action === harness_1.HARNESS_RESOLVE_ACTIONS.retry &&
421
+ !this.definitions.has((0, defineTask_1.taskDefinitionKey)(task))) {
422
+ throw (0, errors_1.harnessError)({
423
+ detail: `${(0, defineTask_1.taskDefinitionKey)(task)} is not in this harness registry; register it before retrying`,
424
+ kind: "notRegistered",
425
+ });
426
+ }
427
+ const decidedBy = options.userId === undefined ? undefined : String(options.userId);
428
+ if (options.action === harness_1.HARNESS_RESOLVE_ACTIONS.abort) {
429
+ return (0, ownership_1.abortTaskTree)({
430
+ engine: this.engine,
431
+ override: {
432
+ error: `Aborted after interruption: ${options.reason}`,
433
+ filter: { phase: task.phase, status: harness_1.HARNESS_TASK_STATUSES.interrupted },
434
+ output: { action: options.action, decidedBy, phase: task.phase, reason: options.reason },
435
+ spanName: "resolveInterrupted",
436
+ },
437
+ reason: options.reason,
438
+ top: task,
439
+ userId: decidedBy,
440
+ });
441
+ }
442
+ const resolved = await (0, commit_1.commitResolution)({
443
+ models: this.models,
444
+ options: { ...options, action: options.action },
445
+ task,
446
+ testHooks: this.testHooks,
447
+ });
448
+ if (options.action === harness_1.HARNESS_RESOLVE_ACTIONS.retry) {
449
+ this.runner.wake();
450
+ }
451
+ else {
452
+ await (0, ownership_1.settleTaskOwner)({ engine: this.engine, task: resolved });
453
+ }
454
+ return resolved;
455
+ }
456
+ /**
457
+ * Start a conversation with a registered agent. Its config (model, instructions,
458
+ * extension names, the tool names they resolve to, fallbacks, `maxSteps`) is
459
+ * snapshotted onto the conversation. `extensions` replaces the agent's extension list
460
+ * for this conversation; each must be registered.
461
+ */
462
+ async createConversation({ agent, extensions, userId, }) {
463
+ if (this.agents.get(agent?.name) !== agent) {
464
+ throw (0, errors_1.harnessError)({
465
+ detail: `Agent "${agent?.name}" is not in this harness registry`,
466
+ kind: "notRegistered",
467
+ });
468
+ }
469
+ const extensionNames = extensions?.map((entry) => (0, defineAgent_1.extensionName)("createConversation", entry));
470
+ if (extensionNames && new Set(extensionNames).size !== extensionNames.length) {
471
+ throw (0, errors_1.harnessError)({
472
+ detail: "createConversation: an extension is listed more than once",
473
+ kind: "invalidRequest",
474
+ });
475
+ }
476
+ for (const name of extensionNames ?? []) {
477
+ if (!this.extensions.has(name)) {
478
+ throw (0, errors_1.harnessError)({
479
+ detail: `Extension "${name}" is not in this harness registry`,
480
+ kind: "notRegistered",
481
+ });
482
+ }
483
+ }
484
+ const document = await this.models.conversation.create({
485
+ agent: (0, conversation_1.conversationAgentSnapshot)({ agent, extensionNames, extensions: this.extensions }),
486
+ ownership: { kind: "root" },
487
+ userId,
488
+ });
489
+ return new conversation_1.HarnessConversationHandle(this.conversationContext(), document);
490
+ }
491
+ /** Load a conversation. Throws when it does not exist. */
492
+ async conversation(conversationId) {
493
+ const document = await this.models.conversation.findExactlyOne({ _id: conversationId });
494
+ return new conversation_1.HarnessConversationHandle(this.conversationContext(), document);
495
+ }
496
+ conversationContext() {
497
+ return {
498
+ models: this.models,
499
+ turn: this.agentTasks.turn,
500
+ wake: () => this.runner.wake(),
501
+ };
502
+ }
503
+ /** Poll until the task is terminal; throws after `timeout` (default 30 seconds). */
504
+ async waitForTask(taskId, options = {}) {
505
+ const deadline = luxon_1.DateTime.now().plus(luxon_1.Duration.fromDurationLike(options.timeout ?? { seconds: 30 }));
506
+ const pollMs = luxon_1.Duration.fromDurationLike(options.pollInterval ?? { milliseconds: 50 }).toMillis();
507
+ for (;;) {
508
+ const task = await this.models.task.findExactlyOne({ _id: taskId });
509
+ if (harness_1.HARNESS_TERMINAL_STATUSES.has(task.status)) {
510
+ return task;
511
+ }
512
+ if (luxon_1.DateTime.now() >= deadline) {
513
+ throw (0, errors_1.harnessError)({
514
+ detail: `Timed out waiting for task ${taskId} (${(0, defineTask_1.taskDefinitionKey)(task)}) in status ${task.status}`,
515
+ kind: "waitTimedOut",
516
+ });
517
+ }
518
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
519
+ }
520
+ }
521
+ }
522
+ exports.Harness = Harness;
@@ -0,0 +1,44 @@
1
+ import type { AdminContribution, TerrenoPlugin } from "@terreno/api";
2
+ import type express from "express";
3
+ import type { DurationLike } from "luxon";
4
+ import { HarnessEventHub } from "./eventHub";
5
+ import type { Harness } from "./harness";
6
+ export interface HarnessAppOptions {
7
+ /** Prefix for every harness route. Default `/harness`. */
8
+ basePath?: string;
9
+ /** The opened harness whose registry resolves approvers and which wakes tasks. */
10
+ harness: Harness;
11
+ /** How often an idle SSE stream sends a heartbeat comment. Default 15 seconds. */
12
+ heartbeatInterval?: DurationLike;
13
+ }
14
+ /**
15
+ * TerrenoPlugin that mounts the harness HTTP API under `basePath`:
16
+ *
17
+ * - `GET /conversations`, `GET /conversations/:id`, `POST /conversations/:id/submit`
18
+ * - `GET /conversations/:id/events` and `GET /tasks/:id/events` (SSE)
19
+ * - `GET /tasks/:id`, `POST /tasks/:id/abort`, `POST /tasks/:id/resolveInterrupted`
20
+ * - `GET /approvals`, `GET /approvals/:id`, `POST /approvals/:id/approve` and `/reject`
21
+ *
22
+ * The SSE routes only read Mongo, so any instance serves any stream. All of an app's SSE
23
+ * connections share one change stream (`eventHub`), so viewers cost no pooled connections.
24
+ *
25
+ * With `AdminApp` registered on the same app, it adds the approvals inbox custom screen
26
+ * (`harness-approvals`, group "AI Harness") to the admin sidebar.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const harness = await Harness.open({registry: [intakeSummary]});
31
+ * await harness.start();
32
+ * new TerrenoApp({userModel: User}).register(new HarnessApp({harness})).start();
33
+ * ```
34
+ */
35
+ export declare class HarnessApp implements TerrenoPlugin {
36
+ private readonly basePath;
37
+ private readonly harness;
38
+ private readonly heartbeatInterval;
39
+ /** The one change stream every SSE connection of this app shares. */
40
+ readonly eventHub: HarnessEventHub;
41
+ constructor({ basePath, harness, heartbeatInterval }: HarnessAppOptions);
42
+ register(app: express.Application, openApi?: unknown): void;
43
+ adminContribution(): AdminContribution;
44
+ }
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HarnessApp = void 0;
4
+ const adminScreens_1 = require("./adminScreens");
5
+ const errors_1 = require("./errors");
6
+ const eventHub_1 = require("./eventHub");
7
+ const approvals_1 = require("./routes/approvals");
8
+ const conversations_1 = require("./routes/conversations");
9
+ const events_1 = require("./routes/events");
10
+ const tasks_1 = require("./routes/tasks");
11
+ /**
12
+ * TerrenoPlugin that mounts the harness HTTP API under `basePath`:
13
+ *
14
+ * - `GET /conversations`, `GET /conversations/:id`, `POST /conversations/:id/submit`
15
+ * - `GET /conversations/:id/events` and `GET /tasks/:id/events` (SSE)
16
+ * - `GET /tasks/:id`, `POST /tasks/:id/abort`, `POST /tasks/:id/resolveInterrupted`
17
+ * - `GET /approvals`, `GET /approvals/:id`, `POST /approvals/:id/approve` and `/reject`
18
+ *
19
+ * The SSE routes only read Mongo, so any instance serves any stream. All of an app's SSE
20
+ * connections share one change stream (`eventHub`), so viewers cost no pooled connections.
21
+ *
22
+ * With `AdminApp` registered on the same app, it adds the approvals inbox custom screen
23
+ * (`harness-approvals`, group "AI Harness") to the admin sidebar.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * const harness = await Harness.open({registry: [intakeSummary]});
28
+ * await harness.start();
29
+ * new TerrenoApp({userModel: User}).register(new HarnessApp({harness})).start();
30
+ * ```
31
+ */
32
+ class HarnessApp {
33
+ basePath;
34
+ harness;
35
+ heartbeatInterval;
36
+ /** The one change stream every SSE connection of this app shares. */
37
+ eventHub = new eventHub_1.HarnessEventHub();
38
+ constructor({ basePath = "/harness", harness, heartbeatInterval }) {
39
+ if (!harness) {
40
+ throw (0, errors_1.harnessError)({ detail: "HarnessApp requires an opened Harness", kind: "configInvalid" });
41
+ }
42
+ this.basePath = (0, approvals_1.assertValidBasePath)(basePath);
43
+ this.harness = harness;
44
+ this.heartbeatInterval = heartbeatInterval;
45
+ }
46
+ register(app, openApi) {
47
+ const { basePath, harness } = this;
48
+ // Before the routers, so `/:id/events` is never taken for a document route.
49
+ (0, events_1.addHarnessEventRoutes)(app, {
50
+ basePath,
51
+ heartbeatInterval: this.heartbeatInterval,
52
+ hub: this.eventHub,
53
+ });
54
+ (0, conversations_1.addHarnessConversationRoutes)(app, { basePath, harness, openApi });
55
+ (0, tasks_1.addHarnessTaskRoutes)(app, { basePath, harness, openApi });
56
+ (0, approvals_1.addHarnessApprovalRoutes)(app, { basePath, harness, openApi });
57
+ }
58
+ adminContribution() {
59
+ return { customScreens: (0, adminScreens_1.harnessAdminScreens)() };
60
+ }
61
+ }
62
+ exports.HarnessApp = HarnessApp;
@@ -0,0 +1,16 @@
1
+ import type mongoose from "mongoose";
2
+ import type { HarnessApprovalRequest, HarnessCommit, HarnessMemo, HarnessTaskRuntime } from "../types/harness";
3
+ import type { HarnessCommitWrites } from "./commit";
4
+ /** Key of the engine-only runtime surface; never part of the public `rt`. */
5
+ export declare const HARNESS_INTERNAL_RUNTIME: unique symbol;
6
+ /** Engine-only extras built-in tasks (the agent turn) need beyond the public runtime. */
7
+ export interface HarnessInternalRuntime {
8
+ /** `rt.approval` whose approvers come from `extension`'s `approvals` (tool hooks). */
9
+ approvalFor: (extension: string) => HarnessApprovalRequest;
10
+ /** `rt.commit` plus extra rows written in the same transaction. */
11
+ commitWithWrites: (next: HarnessCommit<unknown, unknown>, writes: HarnessCommitWrites) => Promise<void>;
12
+ /** A memo scoped to another task (the turn, for tool hooks), fenced on this run's lease. */
13
+ memoFor: (scopeTaskId: mongoose.Types.ObjectId | string) => HarnessMemo;
14
+ }
15
+ /** The internal surface of a runtime built by the engine. Throws for any other object. */
16
+ export declare const internalRuntime: (rt: HarnessTaskRuntime<unknown, unknown>) => HarnessInternalRuntime;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.internalRuntime = exports.HARNESS_INTERNAL_RUNTIME = void 0;
4
+ const errors_1 = require("./errors");
5
+ /** Key of the engine-only runtime surface; never part of the public `rt`. */
6
+ exports.HARNESS_INTERNAL_RUNTIME = Symbol("terreno.harness.internalRuntime");
7
+ /** The internal surface of a runtime built by the engine. Throws for any other object. */
8
+ const internalRuntime = (rt) => {
9
+ const internals = rt[exports.HARNESS_INTERNAL_RUNTIME];
10
+ if (!internals) {
11
+ throw (0, errors_1.harnessError)({
12
+ detail: "This runtime was not built by the harness engine",
13
+ kind: "internal",
14
+ });
15
+ }
16
+ return internals;
17
+ };
18
+ exports.internalRuntime = internalRuntime;