@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,35 @@
1
+ import type mongoose from "mongoose";
2
+ import type { HarnessLeaseSettings, HarnessTestHooks } from "../types/harness";
3
+ import { type HarnessModels } from "./commit";
4
+ /**
5
+ * Take the owner lease when it is free or expired, or renew it when `lease.owner`
6
+ * already holds it. Returns false when another live owner holds it.
7
+ */
8
+ export declare const acquireOwnerLease: ({ lease, models, testHooks, }: {
9
+ lease: HarnessLeaseSettings;
10
+ models: HarnessModels;
11
+ testHooks?: HarnessTestHooks;
12
+ }) => Promise<boolean>;
13
+ /** Expire the owner lease now so a standby takes over without waiting it out. */
14
+ export declare const releaseOwnerLease: ({ lease, models, }: {
15
+ lease: HarnessLeaseSettings;
16
+ models: HarnessModels;
17
+ }) => Promise<void>;
18
+ export interface TaskHeartbeat {
19
+ /** Stop renewing and wait for a renewal in flight. */
20
+ stop: () => Promise<void>;
21
+ }
22
+ /**
23
+ * Renew one task lease every `lease.heartbeat` while a phase runs. Renewal is fenced on
24
+ * the lease token; once it no longer matches (another runner took the task) renewal
25
+ * stops, `onLost` fires, and the phase's eventual commit is rejected.
26
+ */
27
+ export declare const startTaskHeartbeat: ({ lease, models, onLost, taskId, testHooks, token, }: {
28
+ lease: HarnessLeaseSettings;
29
+ models: HarnessModels;
30
+ /** Called once when renewal finds the lease gone (taken over, aborted, or settled). */
31
+ onLost?: () => void;
32
+ taskId: mongoose.Types.ObjectId;
33
+ testHooks?: HarnessTestHooks;
34
+ token: string | undefined;
35
+ }) => TaskHeartbeat;
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startTaskHeartbeat = exports.releaseOwnerLease = exports.acquireOwnerLease = void 0;
4
+ const api_1 = require("@terreno/api");
5
+ const luxon_1 = require("luxon");
6
+ const harness_1 = require("../types/harness");
7
+ const commit_1 = require("./commit");
8
+ const errors_1 = require("./errors");
9
+ /** `HarnessOwner.key` of the lease every `InProcessRunner` competes for. */
10
+ const DEFAULT_OWNER_LEASE_KEY = "default";
11
+ /**
12
+ * Take the owner lease when it is free or expired, or renew it when `lease.owner`
13
+ * already holds it. Returns false when another live owner holds it.
14
+ */
15
+ const acquireOwnerLease = async ({ lease, models, testHooks, }) => {
16
+ if (testHooks?.isHeartbeatSuspended?.()) {
17
+ return false;
18
+ }
19
+ const now = luxon_1.DateTime.now();
20
+ try {
21
+ const held = await models.owner.findOneAndUpdate({
22
+ $or: [{ owner: lease.owner }, { expiresAt: { $lte: now.toJSDate() } }],
23
+ key: DEFAULT_OWNER_LEASE_KEY,
24
+ }, { $set: { expiresAt: now.plus(lease.duration).toJSDate(), owner: lease.owner } }, { returnDocument: "after", upsert: true });
25
+ return held?.owner === lease.owner;
26
+ }
27
+ catch (error) {
28
+ // A live owner's row exists, so the upsert collided with the unique key.
29
+ if ((0, commit_1.isDuplicateKeyError)(error)) {
30
+ return false;
31
+ }
32
+ throw error;
33
+ }
34
+ };
35
+ exports.acquireOwnerLease = acquireOwnerLease;
36
+ /** Expire the owner lease now so a standby takes over without waiting it out. */
37
+ const releaseOwnerLease = async ({ lease, models, }) => {
38
+ await models.owner.updateOne({ key: DEFAULT_OWNER_LEASE_KEY, owner: lease.owner }, { $set: { expiresAt: luxon_1.DateTime.now().toJSDate() } });
39
+ };
40
+ exports.releaseOwnerLease = releaseOwnerLease;
41
+ /**
42
+ * Renew one task lease every `lease.heartbeat` while a phase runs. Renewal is fenced on
43
+ * the lease token; once it no longer matches (another runner took the task) renewal
44
+ * stops, `onLost` fires, and the phase's eventual commit is rejected.
45
+ */
46
+ const startTaskHeartbeat = ({ lease, models, onLost, taskId, testHooks, token, }) => {
47
+ let isStopped = false;
48
+ let timer;
49
+ let inFlight = Promise.resolve();
50
+ const renew = async () => {
51
+ if (testHooks?.isHeartbeatSuspended?.()) {
52
+ schedule();
53
+ return;
54
+ }
55
+ try {
56
+ const result = await models.task.updateOne({ _id: taskId, "lease.token": token ?? null, status: harness_1.HARNESS_TASK_STATUSES.running }, { $set: { "lease.expiresAt": luxon_1.DateTime.now().plus(lease.duration).toJSDate() } });
57
+ if (result.matchedCount === 0) {
58
+ api_1.logger.warn(`Harness task ${taskId} lost its lease; the running phase cannot commit`);
59
+ isStopped = true;
60
+ onLost?.();
61
+ return;
62
+ }
63
+ }
64
+ catch (error) {
65
+ api_1.logger.warn(`Harness task ${taskId} lease renewal failed: ${(0, errors_1.errorMessage)(error)}`);
66
+ }
67
+ schedule();
68
+ };
69
+ const schedule = () => {
70
+ if (isStopped) {
71
+ return;
72
+ }
73
+ timer = setTimeout(() => {
74
+ inFlight = renew();
75
+ }, lease.heartbeat.toMillis());
76
+ };
77
+ schedule();
78
+ return {
79
+ stop: async () => {
80
+ isStopped = true;
81
+ clearTimeout(timer);
82
+ await inFlight;
83
+ },
84
+ };
85
+ };
86
+ exports.startTaskHeartbeat = startTaskHeartbeat;
@@ -0,0 +1,24 @@
1
+ import type mongoose from "mongoose";
2
+ import type { HarnessLeaseSettings, HarnessMemo } from "../types/harness";
3
+ import { type HarnessModels } from "./commit";
4
+ /** The run allowed to write: its task, phase, and lease token. */
5
+ export interface MemoFence {
6
+ phase: string;
7
+ taskId: mongoose.Types.ObjectId;
8
+ token: string | undefined;
9
+ }
10
+ /**
11
+ * Build a memo function scoped to `scopeTaskId`. Reads return the stored value. A write
12
+ * runs in its own transaction: it renews the fenced run's lease (so a run that lost its
13
+ * lease writes nothing and conflicts with a concurrent commit or takeover), then inserts
14
+ * the row only when the key is unset. The stored value is returned, so the first write
15
+ * wins across concurrent calls, replays, and processes.
16
+ */
17
+ export declare const createMemo: ({ assertWritable, fence, lease, models, scopeTaskId, }: {
18
+ /** Throws when the phase can no longer write (it already committed). */
19
+ assertWritable: () => void;
20
+ fence: MemoFence;
21
+ lease: HarnessLeaseSettings;
22
+ models: HarnessModels;
23
+ scopeTaskId: mongoose.Types.ObjectId;
24
+ }) => HarnessMemo;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMemo = void 0;
4
+ const luxon_1 = require("luxon");
5
+ const harness_1 = require("../types/harness");
6
+ const commit_1 = require("./commit");
7
+ const errors_1 = require("./errors");
8
+ const transaction_1 = require("./transaction");
9
+ /** JSON copy of a memo value; throws for values JSON cannot represent. */
10
+ const toMemoValue = (key, value) => {
11
+ let serialized;
12
+ try {
13
+ serialized = JSON.stringify(value);
14
+ }
15
+ catch (error) {
16
+ throw (0, errors_1.harnessError)({
17
+ cause: error,
18
+ detail: `memo "${key}": value is not JSON-serializable (${(0, errors_1.errorMessage)(error)})`,
19
+ kind: "invalidRequest",
20
+ });
21
+ }
22
+ if (serialized === undefined) {
23
+ throw (0, errors_1.harnessError)({
24
+ detail: `memo "${key}": value is not JSON-serializable`,
25
+ kind: "invalidRequest",
26
+ });
27
+ }
28
+ return JSON.parse(serialized);
29
+ };
30
+ /**
31
+ * Build a memo function scoped to `scopeTaskId`. Reads return the stored value. A write
32
+ * runs in its own transaction: it renews the fenced run's lease (so a run that lost its
33
+ * lease writes nothing and conflicts with a concurrent commit or takeover), then inserts
34
+ * the row only when the key is unset. The stored value is returned, so the first write
35
+ * wins across concurrent calls, replays, and processes.
36
+ */
37
+ const createMemo = ({ assertWritable, fence, lease, models, scopeTaskId, }) => {
38
+ const read = async (key) => {
39
+ const row = await models.memo.findOneOrNone({ key, taskId: scopeTaskId });
40
+ return row?.value;
41
+ };
42
+ const write = async (key, value) => {
43
+ assertWritable();
44
+ const stored = toMemoValue(key, value);
45
+ try {
46
+ await (0, transaction_1.inTransaction)(async (session) => {
47
+ const renewed = await models.task.updateOne({
48
+ _id: fence.taskId,
49
+ "lease.token": fence.token ?? null,
50
+ phase: fence.phase,
51
+ status: harness_1.HARNESS_TASK_STATUSES.running,
52
+ }, { $set: { "lease.expiresAt": luxon_1.DateTime.now().plus(lease.duration).toJSDate() } }, { session });
53
+ if (renewed.matchedCount === 0) {
54
+ throw new commit_1.HarnessCommitConflictError(String(fence.taskId), fence.phase);
55
+ }
56
+ await models.memo.updateOne({ key, taskId: scopeTaskId }, { $setOnInsert: { key, taskId: scopeTaskId, value: stored } }, { session, upsert: true });
57
+ });
58
+ }
59
+ catch (error) {
60
+ // A concurrent first write inserted the row between our read and upsert.
61
+ if (!(0, commit_1.isDuplicateKeyError)(error)) {
62
+ throw error;
63
+ }
64
+ }
65
+ return read(key);
66
+ };
67
+ const memo = async (key, ...rest) => {
68
+ if (typeof key !== "string" || !key.trim()) {
69
+ throw (0, errors_1.harnessError)({ detail: "memo requires a non-empty key", kind: "invalidRequest" });
70
+ }
71
+ if (rest.length === 0 || rest[0] === undefined) {
72
+ return read(key);
73
+ }
74
+ return write(key, rest[0]);
75
+ };
76
+ return memo;
77
+ };
78
+ exports.createMemo = createMemo;
@@ -0,0 +1,45 @@
1
+ import { type LanguageModel } from "ai";
2
+ import type { HarnessModelRef, HarnessModelResolver, HarnessRetryPolicy } from "../types/harness";
3
+ /** One try of one model, as recorded on the LLM span. */
4
+ export interface ModelCallAttempt {
5
+ attempt: number;
6
+ error?: string;
7
+ modelId: string;
8
+ provider: string;
9
+ /** Whether the failure allowed another try. */
10
+ retryable?: boolean;
11
+ statusCode?: number;
12
+ }
13
+ export interface ModelCallResult<T> {
14
+ attempts: ModelCallAttempt[];
15
+ /** The model that answered. */
16
+ model: HarnessModelRef;
17
+ result: T;
18
+ }
19
+ /** Every model (primary, then fallbacks) failed, or a failure was not retryable. */
20
+ export declare class HarnessModelCallError extends Error {
21
+ readonly attempts: ModelCallAttempt[];
22
+ constructor(message: string, attempts: ModelCallAttempt[], cause: unknown);
23
+ }
24
+ /**
25
+ * Whether a model call failure may succeed on another try: HTTP 429 and 5xx, and network
26
+ * failures. Every other HTTP status (400, 401, 404, ...) and any non-HTTP error fails at
27
+ * once, because repeating the same request cannot fix it.
28
+ */
29
+ export declare const isRetryableModelError: (error: unknown) => boolean;
30
+ /**
31
+ * Call `call` with the primary model, retrying 429 / 5xx / network failures with
32
+ * exponential backoff and equal jitter (`retry`, default 3 tries per model), then each
33
+ * fallback model in order with the same budget. A non-retryable failure, or an aborted
34
+ * `signal`, throws at once. Throws `HarnessModelCallError` (with every attempt) when no
35
+ * model answered.
36
+ */
37
+ export declare const callModelWithFallback: <T>({ call, models, random, resolveModel, retry, signal, }: {
38
+ call: (model: LanguageModel) => Promise<T>;
39
+ /** Primary first, then fallbacks. */
40
+ models: ReadonlyArray<HarnessModelRef>;
41
+ random?: () => number;
42
+ resolveModel: HarnessModelResolver;
43
+ retry?: HarnessRetryPolicy;
44
+ signal?: AbortSignal;
45
+ }) => Promise<ModelCallResult<T>>;
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.callModelWithFallback = exports.isRetryableModelError = exports.HarnessModelCallError = void 0;
4
+ const ai_1 = require("ai");
5
+ const harness_1 = require("../types/harness");
6
+ const retryBackoff_1 = require("./retryBackoff");
7
+ /** Every model (primary, then fallbacks) failed, or a failure was not retryable. */
8
+ class HarnessModelCallError extends Error {
9
+ attempts;
10
+ constructor(message, attempts, cause) {
11
+ super(message, { cause });
12
+ this.name = "HarnessModelCallError";
13
+ this.attempts = attempts;
14
+ }
15
+ }
16
+ exports.HarnessModelCallError = HarnessModelCallError;
17
+ /** Socket-level failures worth another try; providers wrap most of these in APICallError. */
18
+ const NETWORK_ERROR_CODES = new Set([
19
+ "ECONNREFUSED",
20
+ "ECONNRESET",
21
+ "EAI_AGAIN",
22
+ "ENOTFOUND",
23
+ "EPIPE",
24
+ "ETIMEDOUT",
25
+ "UND_ERR_CONNECT_TIMEOUT",
26
+ "UND_ERR_SOCKET",
27
+ ]);
28
+ const errorCode = (error) => {
29
+ if (typeof error !== "object" || error === null) {
30
+ return undefined;
31
+ }
32
+ const code = error.code;
33
+ if (typeof code === "string") {
34
+ return code;
35
+ }
36
+ return errorCode(error.cause);
37
+ };
38
+ const isNetworkError = (error) => {
39
+ const code = errorCode(error);
40
+ if (code && NETWORK_ERROR_CODES.has(code)) {
41
+ return true;
42
+ }
43
+ // fetch() reports a dropped connection as `TypeError: fetch failed`.
44
+ return error instanceof TypeError && /fetch failed|network/i.test(error.message);
45
+ };
46
+ /**
47
+ * Whether a model call failure may succeed on another try: HTTP 429 and 5xx, and network
48
+ * failures. Every other HTTP status (400, 401, 404, ...) and any non-HTTP error fails at
49
+ * once, because repeating the same request cannot fix it.
50
+ */
51
+ const isRetryableModelError = (error) => {
52
+ if (ai_1.APICallError.isInstance(error)) {
53
+ if (error.statusCode !== undefined) {
54
+ return error.statusCode === 429 || error.statusCode >= 500;
55
+ }
56
+ // No status: the request never got a response (the SDK marks these retryable).
57
+ return error.isRetryable;
58
+ }
59
+ return isNetworkError(error);
60
+ };
61
+ exports.isRetryableModelError = isRetryableModelError;
62
+ const describeError = (error) => error instanceof Error ? error.message : String(error);
63
+ const statusCodeOf = (error) => ai_1.APICallError.isInstance(error) ? error.statusCode : undefined;
64
+ /** Resolve after `ms`, or reject with the signal's reason as soon as it aborts. */
65
+ const abortableDelay = (ms, signal) => {
66
+ if (signal?.aborted) {
67
+ return Promise.reject(signal.reason);
68
+ }
69
+ return new Promise((resolve, reject) => {
70
+ const onAbort = () => {
71
+ clearTimeout(timer);
72
+ reject(signal?.reason);
73
+ };
74
+ const timer = setTimeout(() => {
75
+ signal?.removeEventListener("abort", onAbort);
76
+ resolve();
77
+ }, ms);
78
+ signal?.addEventListener("abort", onAbort, { once: true });
79
+ });
80
+ };
81
+ const label = (ref) => `${ref.provider}/${ref.modelId}`;
82
+ /**
83
+ * Call `call` with the primary model, retrying 429 / 5xx / network failures with
84
+ * exponential backoff and equal jitter (`retry`, default 3 tries per model), then each
85
+ * fallback model in order with the same budget. A non-retryable failure, or an aborted
86
+ * `signal`, throws at once. Throws `HarnessModelCallError` (with every attempt) when no
87
+ * model answered.
88
+ */
89
+ const callModelWithFallback = async ({ call, models, random, resolveModel, retry, signal, }) => {
90
+ const policy = {
91
+ backoffMs: retry?.backoffMs ?? harness_1.HARNESS_MODEL_RETRY_DEFAULTS.backoffMs,
92
+ maxAttempts: retry?.maxAttempts ?? harness_1.HARNESS_MODEL_RETRY_DEFAULTS.maxAttempts,
93
+ maxBackoffMs: retry?.maxBackoffMs ?? harness_1.HARNESS_MODEL_RETRY_DEFAULTS.maxBackoffMs,
94
+ };
95
+ const attempts = [];
96
+ let lastError;
97
+ for (const ref of models) {
98
+ let model;
99
+ try {
100
+ model = resolveModel(ref);
101
+ }
102
+ catch (error) {
103
+ // A model the resolver cannot build will not appear on retry.
104
+ attempts.push({
105
+ attempt: 1,
106
+ error: describeError(error),
107
+ modelId: ref.modelId,
108
+ provider: ref.provider,
109
+ retryable: false,
110
+ });
111
+ throw new HarnessModelCallError(`Model ${label(ref)} could not be resolved: ${describeError(error)}`, attempts, error);
112
+ }
113
+ for (let attempt = 1; attempt <= policy.maxAttempts; attempt++) {
114
+ if (signal?.aborted) {
115
+ throw signal.reason;
116
+ }
117
+ try {
118
+ const result = await call(model);
119
+ attempts.push({ attempt, modelId: ref.modelId, provider: ref.provider });
120
+ return { attempts, model: ref, result };
121
+ }
122
+ catch (error) {
123
+ if (signal?.aborted) {
124
+ throw signal.reason ?? error;
125
+ }
126
+ lastError = error;
127
+ const retryable = (0, exports.isRetryableModelError)(error);
128
+ attempts.push({
129
+ attempt,
130
+ error: describeError(error),
131
+ modelId: ref.modelId,
132
+ provider: ref.provider,
133
+ retryable,
134
+ statusCode: statusCodeOf(error),
135
+ });
136
+ if (!retryable) {
137
+ throw new HarnessModelCallError(`Model ${label(ref)} failed with a non-retryable error: ${describeError(error)}`, attempts, error);
138
+ }
139
+ if (attempt < policy.maxAttempts) {
140
+ await abortableDelay((0, retryBackoff_1.retryDelayMs)({ failedAttempts: attempt, policy, random }), signal);
141
+ }
142
+ }
143
+ }
144
+ }
145
+ throw new HarnessModelCallError(`Model call failed after ${attempts.length} attempts across ${models.map(label).join(", ")}: ${describeError(lastError)}`, attempts, lastError);
146
+ };
147
+ exports.callModelWithFallback = callModelWithFallback;
@@ -0,0 +1,2 @@
1
+ import { type HarnessApprovalModel } from "../../types/harness";
2
+ export declare const registerHarnessApproval: () => HarnessApprovalModel;
@@ -0,0 +1,100 @@
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.registerHarnessApproval = void 0;
7
+ const api_1 = require("@terreno/api");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const harness_1 = require("../../types/harness");
10
+ const harnessApprovalSchema = new mongoose_1.default.Schema({
11
+ callKey: {
12
+ description: "`<step>:<call index>` of the wait call that requested the approval",
13
+ required: true,
14
+ type: String,
15
+ },
16
+ decidedAt: { description: "When the approval was approved or rejected", type: Date },
17
+ decidedBy: {
18
+ description: "User who approved or rejected the approval",
19
+ ref: "User",
20
+ type: mongoose_1.default.Schema.Types.ObjectId,
21
+ },
22
+ definitionKey: {
23
+ description: "`name@version:key` of the requesting task definition and approval key",
24
+ required: true,
25
+ type: String,
26
+ },
27
+ event: {
28
+ description: "Inbox event name the decision sends to the waiting task",
29
+ required: true,
30
+ type: String,
31
+ },
32
+ expiresAt: {
33
+ description: "When the approval expires undecided; unset means it never expires",
34
+ type: Date,
35
+ },
36
+ extension: {
37
+ description: "Extension whose approvals policy names the approvers (hook approvals only)",
38
+ type: String,
39
+ },
40
+ key: {
41
+ description: "Approval key; selects the approvers policy of the definition or extension",
42
+ required: true,
43
+ type: String,
44
+ },
45
+ payload: {
46
+ description: "What the approver reviews (JSON)",
47
+ type: mongoose_1.default.Schema.Types.Mixed,
48
+ },
49
+ reason: { description: "Why the approver approved or rejected", type: String },
50
+ rootTaskId: {
51
+ description: "Root task of the requesting task's ownership tree",
52
+ ref: "HarnessTask",
53
+ required: true,
54
+ type: mongoose_1.default.Schema.Types.ObjectId,
55
+ },
56
+ status: {
57
+ default: harness_1.HARNESS_APPROVAL_STATUSES.pending,
58
+ description: "pending until approved, rejected, or expired",
59
+ enum: Object.values(harness_1.HARNESS_APPROVAL_STATUSES),
60
+ required: true,
61
+ type: String,
62
+ },
63
+ summary: { description: "Short explanation shown under the title", type: String },
64
+ taskId: {
65
+ description: "Task that requested the approval and waits for the decision",
66
+ ref: "HarnessTask",
67
+ required: true,
68
+ type: mongoose_1.default.Schema.Types.ObjectId,
69
+ },
70
+ title: { description: "What the approver is asked to approve", required: true, type: String },
71
+ traceId: {
72
+ description: "ObsTrace of the requesting task; the decision span lands in it",
73
+ ref: "ObsTrace",
74
+ required: true,
75
+ type: mongoose_1.default.Schema.Types.ObjectId,
76
+ },
77
+ }, {
78
+ // Keep empty objects: `{}` is a meaningful payload.
79
+ minimize: false,
80
+ strict: "throw",
81
+ toJSON: { virtuals: true },
82
+ toObject: { virtuals: true },
83
+ });
84
+ harnessApprovalSchema.plugin(api_1.createdUpdatedPlugin);
85
+ harnessApprovalSchema.plugin(api_1.findOneOrNone);
86
+ harnessApprovalSchema.plugin(api_1.findExactlyOne);
87
+ // One approval per wait call, so a re-run of the phase finds the approval it created.
88
+ harnessApprovalSchema.index({ callKey: 1, taskId: 1 }, { unique: true });
89
+ // The inbox scans pending approvals, oldest first; compound index field order is query-significant.
90
+ harnessApprovalSchema.index(Object.fromEntries([
91
+ ["status", 1],
92
+ ["created", 1],
93
+ ]));
94
+ const registerHarnessApproval = () => {
95
+ if (mongoose_1.default.models.HarnessApproval) {
96
+ return mongoose_1.default.models.HarnessApproval;
97
+ }
98
+ return mongoose_1.default.model("HarnessApproval", harnessApprovalSchema);
99
+ };
100
+ exports.registerHarnessApproval = registerHarnessApproval;
@@ -0,0 +1,2 @@
1
+ import { type HarnessConversationModel } from "../../types/harness";
2
+ export declare const registerHarnessConversation: () => HarnessConversationModel;
@@ -0,0 +1,117 @@
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.registerHarnessConversation = void 0;
7
+ const api_1 = require("@terreno/api");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const harness_1 = require("../../types/harness");
10
+ const modelRefSchema = {
11
+ modelId: { description: "Provider model id, for example claude-sonnet-5-5", type: String },
12
+ provider: { description: "Provider name the models resolver understands", type: String },
13
+ };
14
+ const harnessConversationSchema = new mongoose_1.default.Schema({
15
+ activeTurnTaskId: {
16
+ description: "Turn task running on this conversation while it is busy",
17
+ ref: "HarnessTask",
18
+ type: mongoose_1.default.Schema.Types.ObjectId,
19
+ },
20
+ agent: {
21
+ extensions: {
22
+ default: [],
23
+ description: "Extension names applied to this conversation's requests",
24
+ type: [String],
25
+ },
26
+ fallbackModels: {
27
+ default: [],
28
+ description: "Models tried in order after the primary model's retries run out",
29
+ type: [new mongoose_1.default.Schema(modelRefSchema, { _id: false, strict: "throw" })],
30
+ },
31
+ instructions: { description: "System prompt sent with every model request", type: String },
32
+ maxSteps: { description: "Model requests one turn may make", type: Number },
33
+ model: modelRefSchema,
34
+ name: { description: "Registered agent definition name", required: true, type: String },
35
+ outputSchema: {
36
+ description: "Serialized JSON Schema the final answer must match (subagent structured output)",
37
+ type: String,
38
+ },
39
+ tools: {
40
+ default: [],
41
+ description: "Tool names the model may call in this conversation",
42
+ type: [String],
43
+ },
44
+ },
45
+ ownerKey: {
46
+ description: "Deterministic key of the rt.runAgent call (phase visit, attempt, call index) that created this subagent conversation",
47
+ type: String,
48
+ },
49
+ ownership: {
50
+ id: {
51
+ description: "Owning task id for a subagent conversation; empty for root conversations",
52
+ ref: "HarnessTask",
53
+ type: mongoose_1.default.Schema.Types.ObjectId,
54
+ },
55
+ kind: {
56
+ default: "root",
57
+ description: "What owns this conversation: nothing (root) or a task (subagent)",
58
+ enum: ["root", "task"],
59
+ type: String,
60
+ },
61
+ },
62
+ queued: {
63
+ default: [],
64
+ description: "Submissions waiting on the active turn, oldest first: queued for a later turn, or steering the active one",
65
+ type: [
66
+ new mongoose_1.default.Schema({
67
+ content: {
68
+ description: "Submitted user content",
69
+ type: mongoose_1.default.Schema.Types.Mixed,
70
+ },
71
+ requestId: { description: "Caller idempotency key of the submission", type: String },
72
+ submittedAt: { description: "When the submission arrived", type: Date },
73
+ whenBusy: {
74
+ description: "queue: run as its own turn later; steer: join the active turn's next model request",
75
+ enum: Object.values(harness_1.HARNESS_WHEN_BUSY),
76
+ type: String,
77
+ },
78
+ }, { _id: false, strict: "throw" }),
79
+ ],
80
+ },
81
+ seq: {
82
+ default: 0,
83
+ description: "Highest message sequence number handed out; messages count up from 1",
84
+ type: Number,
85
+ },
86
+ status: {
87
+ default: harness_1.HARNESS_CONVERSATION_STATUSES.idle,
88
+ description: "idle, or busy while a turn task runs",
89
+ enum: Object.values(harness_1.HARNESS_CONVERSATION_STATUSES),
90
+ type: String,
91
+ },
92
+ userId: {
93
+ description: "User the conversation belongs to; turn tasks run as this user",
94
+ ref: "User",
95
+ type: mongoose_1.default.Schema.Types.ObjectId,
96
+ },
97
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
98
+ harnessConversationSchema.plugin(api_1.createdUpdatedPlugin);
99
+ harnessConversationSchema.plugin(api_1.isDeletedPlugin);
100
+ harnessConversationSchema.plugin(api_1.findOneOrNone);
101
+ harnessConversationSchema.plugin(api_1.findExactlyOne);
102
+ harnessConversationSchema.index({ created: -1, userId: 1 });
103
+ harnessConversationSchema.index({ "ownership.id": 1, "ownership.kind": 1 });
104
+ // The sweep finds busy conversations whose active turn already ended.
105
+ // biome-ignore assist/source/useSortedKeys: status leads; the sweep matches busy first
106
+ harnessConversationSchema.index({ status: 1, activeTurnTaskId: 1 });
107
+ // The queue sweep finds idle conversations that still have queued submissions.
108
+ harnessConversationSchema.index({ "queued.requestId": 1, status: 1 }, { partialFilterExpression: { "queued.requestId": { $exists: true } } });
109
+ // One subagent conversation per rt.runAgent call, however often the phase re-runs.
110
+ harnessConversationSchema.index({ ownerKey: 1, "ownership.id": 1 }, { partialFilterExpression: { ownerKey: { $type: "string" } }, unique: true });
111
+ const registerHarnessConversation = () => {
112
+ if (mongoose_1.default.models.HarnessConversation) {
113
+ return mongoose_1.default.models.HarnessConversation;
114
+ }
115
+ return mongoose_1.default.model("HarnessConversation", harnessConversationSchema);
116
+ };
117
+ exports.registerHarnessConversation = registerHarnessConversation;
@@ -0,0 +1,3 @@
1
+ import { type HarnessEventModel, type HarnessEventStreamModel } from "../../types/harness";
2
+ export declare const registerHarnessEvent: () => HarnessEventModel;
3
+ export declare const registerHarnessEventStream: () => HarnessEventStreamModel;