@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,75 @@
1
+ import { APIError } from "@terreno/api";
2
+ import type mongoose from "mongoose";
3
+ import type { HarnessAgentDefinition, HarnessConversationDocument, HarnessExtensionDefinition, HarnessMessageDocument, HarnessSendOptions, HarnessSubmitOptions, HarnessSubmitResult, HarnessTaskDefinition, HarnessTaskDocument } from "../types/harness";
4
+ import { type HarnessModels } from "./commit";
5
+ /** A turn is already running and the submission did not say what to do (`submit`). */
6
+ export declare class HarnessConversationBusyError extends APIError {
7
+ readonly activeTurnTaskId?: string;
8
+ readonly conversationId: string;
9
+ constructor(conversationId: string, activeTurnTaskId?: string);
10
+ }
11
+ /** A subagent conversation: only the `rt.runAgent` call that owns it runs its turns. */
12
+ export declare class HarnessConversationOwnedError extends APIError {
13
+ readonly conversationId: string;
14
+ constructor(conversationId: string, ownerTaskId: string);
15
+ }
16
+ /** What a conversation handle needs from its harness. */
17
+ export interface ConversationContext {
18
+ models: HarnessModels;
19
+ turn: HarnessTaskDefinition;
20
+ /** Tell the runner a new turn is runnable. */
21
+ wake: () => void;
22
+ }
23
+ /**
24
+ * Snapshot an agent's serializable config onto a new conversation: its extension names
25
+ * (the agent's, unless `extensionNames` replaces them) and every tool name they resolve to.
26
+ */
27
+ export declare const conversationAgentSnapshot: ({ agent, extensionNames, extensions, }: {
28
+ agent: HarnessAgentDefinition;
29
+ extensionNames?: ReadonlyArray<string>;
30
+ extensions: Map<string, HarnessExtensionDefinition>;
31
+ }) => HarnessConversationDocument["agent"];
32
+ /**
33
+ * Start the oldest queued submission as a new turn when the conversation is idle. Called
34
+ * whenever a turn ends and after every `send` that queues. Returns the started turn, or
35
+ * null when the conversation is busy or has nothing queued.
36
+ */
37
+ export declare const startNextQueuedTurn: ({ context, conversationId, }: {
38
+ context: ConversationContext;
39
+ conversationId: mongoose.Types.ObjectId | string;
40
+ }) => Promise<HarnessTaskDocument | null>;
41
+ /**
42
+ * A conversation: its stored config and transcript, plus `submit` / `send` to start a
43
+ * turn. Get one from `harness.createConversation` or `harness.conversation(id)`.
44
+ */
45
+ export declare class HarnessConversationHandle {
46
+ /** The conversation as loaded; call `harness.conversation(id)` again for a fresh copy. */
47
+ readonly document: HarnessConversationDocument;
48
+ private readonly context;
49
+ constructor(context: ConversationContext, document: HarnessConversationDocument);
50
+ get id(): string;
51
+ /** Every message, in `seq` order. */
52
+ messages(): Promise<HarnessMessageDocument[]>;
53
+ /**
54
+ * Append a user message and start a turn task, in one transaction. A repeated
55
+ * `requestId` returns the turn it started and appends nothing. Throws
56
+ * `HarnessConversationBusyError` while another turn is running (or submissions are
57
+ * queued); use `send` to queue or steer instead.
58
+ */
59
+ submit(options: HarnessSubmitOptions): Promise<HarnessTaskDocument>;
60
+ /**
61
+ * Submit a user message whatever the conversation is doing. Idle with nothing queued:
62
+ * start a turn now (`started`). Otherwise, by `whenBusy`: `queue` runs it as its own turn
63
+ * after the active turn and every earlier queued submission (`queued`); `steer` adds it
64
+ * to the active turn, whose next model request includes it (`steered`). A steer that
65
+ * arrives after the turn's last model request runs as the next turn instead. Idempotent
66
+ * on `requestId`: a repeat reports where the first submission is now and adds nothing.
67
+ */
68
+ send(options: HarnessSendOptions): Promise<HarnessSubmitResult>;
69
+ /** Where the submission with `requestId` is now, or null when there is none. */
70
+ private findSubmission;
71
+ /** Add a submission to the queue and announce it, unless its requestId is already there. */
72
+ private enqueue;
73
+ private load;
74
+ private result;
75
+ }
@@ -0,0 +1,397 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HarnessConversationHandle = exports.startNextQueuedTurn = exports.conversationAgentSnapshot = exports.HarnessConversationOwnedError = exports.HarnessConversationBusyError = 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
+ const events_1 = require("./events");
10
+ const extensions_1 = require("./extensions");
11
+ const transaction_1 = require("./transaction");
12
+ /** A turn is already running and the submission did not say what to do (`submit`). */
13
+ class HarnessConversationBusyError extends api_1.APIError {
14
+ activeTurnTaskId;
15
+ conversationId;
16
+ constructor(conversationId, activeTurnTaskId) {
17
+ super({
18
+ ...errors_1.HARNESS_ERRORS.conversationBusy,
19
+ detail: `Conversation ${conversationId} is busy with turn task ${activeTurnTaskId ?? "(unknown)"}; wait for it to finish, or send with whenBusy "queue" or "steer"`,
20
+ });
21
+ this.activeTurnTaskId = activeTurnTaskId;
22
+ this.conversationId = conversationId;
23
+ }
24
+ }
25
+ exports.HarnessConversationBusyError = HarnessConversationBusyError;
26
+ /** A subagent conversation: only the `rt.runAgent` call that owns it runs its turns. */
27
+ class HarnessConversationOwnedError extends api_1.APIError {
28
+ conversationId;
29
+ constructor(conversationId, ownerTaskId) {
30
+ super({
31
+ ...errors_1.HARNESS_ERRORS.conversationOwned,
32
+ detail: `Conversation ${conversationId} belongs to task ${ownerTaskId}; only rt.runAgent runs its turns`,
33
+ });
34
+ this.conversationId = conversationId;
35
+ }
36
+ }
37
+ exports.HarnessConversationOwnedError = HarnessConversationOwnedError;
38
+ /** Claims a submission tries before giving up on a conversation other writers keep winning. */
39
+ const SUBMIT_CLAIM_ATTEMPTS = 3;
40
+ /** Thrown inside the submit transaction when another submit claimed the conversation first. */
41
+ class LostClaimSignal extends Error {
42
+ constructor() {
43
+ super("Another submit claimed the conversation first");
44
+ this.name = "LostClaimSignal";
45
+ }
46
+ }
47
+ /** Turn `requestId`s are namespaced so two conversations can reuse a caller's key. */
48
+ const turnRequestId = (conversationId, requestId) => `harness-conversation:${conversationId}:${requestId}`;
49
+ /**
50
+ * Snapshot an agent's serializable config onto a new conversation: its extension names
51
+ * (the agent's, unless `extensionNames` replaces them) and every tool name they resolve to.
52
+ */
53
+ const conversationAgentSnapshot = ({ agent, extensionNames = agent.extensions, extensions, }) => ({
54
+ extensions: [...extensionNames],
55
+ fallbackModels: (agent.fallbackModels ?? []).map(({ modelId, provider }) => ({
56
+ modelId,
57
+ provider,
58
+ })),
59
+ instructions: agent.instructions,
60
+ maxSteps: agent.maxSteps,
61
+ model: { modelId: agent.model.modelId, provider: agent.model.provider },
62
+ name: agent.name,
63
+ tools: [...(0, extensions_1.resolveTools)(agent, (0, extensions_1.resolveExtensions)(extensions, extensionNames)).keys()],
64
+ });
65
+ exports.conversationAgentSnapshot = conversationAgentSnapshot;
66
+ const assertSubmission = ({ content, requestId }) => {
67
+ if (typeof content !== "string" || !content.trim()) {
68
+ throw (0, errors_1.harnessError)({ detail: "submit requires non-empty content", kind: "invalidRequest" });
69
+ }
70
+ if (typeof requestId !== "string" || !requestId.trim()) {
71
+ throw (0, errors_1.harnessError)({ detail: "submit requires a requestId", kind: "invalidRequest" });
72
+ }
73
+ };
74
+ /**
75
+ * Start a turn for one user message: create the turn task, claim the idle conversation,
76
+ * and insert the message, in one transaction. A direct start is fenced on an empty queue
77
+ * (queued submissions run first); a queued start on its entry being first in line, which
78
+ * it removes. Throws `LostClaimSignal` when another writer changed the conversation first.
79
+ */
80
+ const startTurnRecords = async ({ content, context, conversation, isQueued, requestId, }) => {
81
+ const { models, turn } = context;
82
+ const conversationId = conversation._id;
83
+ const input = { conversationId: String(conversationId) };
84
+ return (0, commit_1.createTaskRecords)({
85
+ definition: turn,
86
+ input,
87
+ models,
88
+ options: {
89
+ requestId: turnRequestId(String(conversationId), requestId),
90
+ userId: conversation.userId,
91
+ },
92
+ ownership: { id: conversationId, kind: "conversation" },
93
+ writes: async ({ session, task }) => {
94
+ const claimed = await models.conversation.findOneAndUpdate({
95
+ _id: conversationId,
96
+ status: harness_1.HARNESS_CONVERSATION_STATUSES.idle,
97
+ ...(isQueued ? { "queued.0.requestId": requestId } : { "queued.0": { $exists: false } }),
98
+ }, {
99
+ $inc: { seq: 1 },
100
+ $set: { activeTurnTaskId: task._id, status: harness_1.HARNESS_CONVERSATION_STATUSES.busy },
101
+ ...(isQueued ? { $pull: { queued: { requestId } } } : {}),
102
+ }, { returnDocument: "after", session });
103
+ if (!claimed) {
104
+ throw new LostClaimSignal();
105
+ }
106
+ await (0, events_1.insertMessages)({
107
+ messages: [
108
+ {
109
+ conversationId,
110
+ parts: [{ text: content, type: "text" }],
111
+ requestId,
112
+ role: harness_1.HARNESS_MESSAGE_ROLES.user,
113
+ seq: claimed.seq,
114
+ turnTaskId: task._id,
115
+ },
116
+ ],
117
+ models,
118
+ session,
119
+ });
120
+ },
121
+ });
122
+ };
123
+ /**
124
+ * Start the oldest queued submission as a new turn when the conversation is idle. Called
125
+ * whenever a turn ends and after every `send` that queues. Returns the started turn, or
126
+ * null when the conversation is busy or has nothing queued.
127
+ */
128
+ const startNextQueuedTurn = async ({ context, conversationId, }) => {
129
+ const { models, wake } = context;
130
+ for (let attempt = 1; attempt <= SUBMIT_CLAIM_ATTEMPTS; attempt++) {
131
+ const conversation = await models.conversation.findOneOrNone({ _id: conversationId });
132
+ const entry = conversation?.queued[0];
133
+ if (!conversation || conversation.status !== harness_1.HARNESS_CONVERSATION_STATUSES.idle || !entry) {
134
+ return null;
135
+ }
136
+ const requestId = entry.requestId ?? "";
137
+ // An entry whose message already exists was a duplicate append; drop it.
138
+ const delivered = requestId
139
+ ? await models.message.findOneOrNone({ conversationId: conversation._id, requestId })
140
+ : null;
141
+ if (!requestId || delivered) {
142
+ await models.conversation.updateOne({ _id: conversation._id, "queued.0.requestId": entry.requestId ?? null }, { $pop: { queued: -1 } });
143
+ continue;
144
+ }
145
+ try {
146
+ const task = await startTurnRecords({
147
+ content: String(entry.content ?? ""),
148
+ context,
149
+ conversation,
150
+ isQueued: true,
151
+ requestId,
152
+ });
153
+ wake();
154
+ return task;
155
+ }
156
+ catch (error) {
157
+ if (!(error instanceof LostClaimSignal)) {
158
+ throw error;
159
+ }
160
+ }
161
+ }
162
+ return null;
163
+ };
164
+ exports.startNextQueuedTurn = startNextQueuedTurn;
165
+ /**
166
+ * A conversation: its stored config and transcript, plus `submit` / `send` to start a
167
+ * turn. Get one from `harness.createConversation` or `harness.conversation(id)`.
168
+ */
169
+ class HarnessConversationHandle {
170
+ /** The conversation as loaded; call `harness.conversation(id)` again for a fresh copy. */
171
+ document;
172
+ context;
173
+ constructor(context, document) {
174
+ this.context = context;
175
+ this.document = document;
176
+ }
177
+ get id() {
178
+ return String(this.document._id);
179
+ }
180
+ /** Every message, in `seq` order. */
181
+ async messages() {
182
+ return this.context.models.message.find({ conversationId: this.document._id }).sort({ seq: 1 });
183
+ }
184
+ /**
185
+ * Append a user message and start a turn task, in one transaction. A repeated
186
+ * `requestId` returns the turn it started and appends nothing. Throws
187
+ * `HarnessConversationBusyError` while another turn is running (or submissions are
188
+ * queued); use `send` to queue or steer instead.
189
+ */
190
+ async submit(options) {
191
+ assertSubmission(options);
192
+ const { content, requestId } = options;
193
+ const { models, wake } = this.context;
194
+ const conversationId = this.document._id;
195
+ const findRepeat = () => models.task.findOneOrNone({
196
+ deleted: { $in: [false, true] },
197
+ requestId: turnRequestId(this.id, requestId),
198
+ });
199
+ // A lost claim means another submit won the conversation. That turn may already be
200
+ // over (fast models), so look again and retry instead of reporting a stale "busy".
201
+ for (let attempt = 1; attempt <= SUBMIT_CLAIM_ATTEMPTS; attempt++) {
202
+ const existing = await findRepeat();
203
+ if (existing) {
204
+ return existing;
205
+ }
206
+ const conversation = await this.load();
207
+ if (!(await releaseFinishedTurn({ conversation, models }))) {
208
+ throw new HarnessConversationBusyError(this.id, String(conversation.activeTurnTaskId));
209
+ }
210
+ if (conversation.queued.length > 0) {
211
+ await (0, exports.startNextQueuedTurn)({ context: this.context, conversationId });
212
+ continue;
213
+ }
214
+ try {
215
+ const task = await startTurnRecords({
216
+ content,
217
+ context: this.context,
218
+ conversation,
219
+ isQueued: false,
220
+ requestId,
221
+ });
222
+ wake();
223
+ return task;
224
+ }
225
+ catch (error) {
226
+ if (!(error instanceof LostClaimSignal)) {
227
+ throw error;
228
+ }
229
+ }
230
+ }
231
+ const current = await models.conversation.findExactlyOne({ _id: conversationId });
232
+ throw new HarnessConversationBusyError(this.id, current.activeTurnTaskId ? String(current.activeTurnTaskId) : undefined);
233
+ }
234
+ /**
235
+ * Submit a user message whatever the conversation is doing. Idle with nothing queued:
236
+ * start a turn now (`started`). Otherwise, by `whenBusy`: `queue` runs it as its own turn
237
+ * after the active turn and every earlier queued submission (`queued`); `steer` adds it
238
+ * to the active turn, whose next model request includes it (`steered`). A steer that
239
+ * arrives after the turn's last model request runs as the next turn instead. Idempotent
240
+ * on `requestId`: a repeat reports where the first submission is now and adds nothing.
241
+ */
242
+ async send(options) {
243
+ assertSubmission(options);
244
+ const { content, requestId, whenBusy } = options;
245
+ if (!Object.values(harness_1.HARNESS_WHEN_BUSY).includes(whenBusy)) {
246
+ throw (0, errors_1.harnessError)({
247
+ detail: `send whenBusy must be one of ${Object.values(harness_1.HARNESS_WHEN_BUSY).join(", ")}`,
248
+ kind: "invalidRequest",
249
+ });
250
+ }
251
+ const { models, wake } = this.context;
252
+ for (let attempt = 1; attempt <= SUBMIT_CLAIM_ATTEMPTS; attempt++) {
253
+ const repeat = await this.findSubmission(requestId);
254
+ if (repeat) {
255
+ return repeat;
256
+ }
257
+ const conversation = await this.load();
258
+ const isFree = await releaseFinishedTurn({ conversation, models });
259
+ if (isFree && conversation.queued.length === 0) {
260
+ try {
261
+ const task = await startTurnRecords({
262
+ content,
263
+ context: this.context,
264
+ conversation,
265
+ isQueued: false,
266
+ requestId,
267
+ });
268
+ wake();
269
+ return this.result(harness_1.HARNESS_SUBMIT_DISPOSITIONS.started, requestId, task._id);
270
+ }
271
+ catch (error) {
272
+ if (!(error instanceof LostClaimSignal)) {
273
+ throw error;
274
+ }
275
+ continue;
276
+ }
277
+ }
278
+ await this.enqueue({
279
+ content,
280
+ requestId,
281
+ // Behind a backlog on an idle conversation there is no turn to steer.
282
+ whenBusy: isFree ? harness_1.HARNESS_WHEN_BUSY.queue : whenBusy,
283
+ });
284
+ // The turn may have ended meanwhile; start the backlog if nothing runs it.
285
+ await (0, exports.startNextQueuedTurn)({ context: this.context, conversationId: conversation._id });
286
+ const recorded = await this.findSubmission(requestId);
287
+ if (recorded) {
288
+ return recorded;
289
+ }
290
+ }
291
+ const settled = await this.findSubmission(requestId);
292
+ if (!settled) {
293
+ throw (0, errors_1.harnessError)({
294
+ detail: `Conversation ${this.id}: could not record submission ${requestId}`,
295
+ kind: "internal",
296
+ });
297
+ }
298
+ return settled;
299
+ }
300
+ /** Where the submission with `requestId` is now, or null when there is none. */
301
+ async findSubmission(requestId) {
302
+ const { models } = this.context;
303
+ const message = await models.message.findOneOrNone({
304
+ conversationId: this.document._id,
305
+ requestId,
306
+ });
307
+ const key = turnRequestId(this.id, requestId);
308
+ if (message?.turnTaskId) {
309
+ const turn = await models.task.findOneOrNone({
310
+ _id: message.turnTaskId,
311
+ deleted: { $in: [false, true] },
312
+ });
313
+ const disposition = turn?.requestId === key
314
+ ? harness_1.HARNESS_SUBMIT_DISPOSITIONS.started
315
+ : harness_1.HARNESS_SUBMIT_DISPOSITIONS.steered;
316
+ return this.result(disposition, requestId, message.turnTaskId);
317
+ }
318
+ const conversation = await this.load();
319
+ const entry = conversation.queued.find((queued) => queued.requestId === requestId);
320
+ if (entry) {
321
+ const isSteering = entry.whenBusy === harness_1.HARNESS_WHEN_BUSY.steer &&
322
+ conversation.status === harness_1.HARNESS_CONVERSATION_STATUSES.busy;
323
+ return isSteering
324
+ ? this.result(harness_1.HARNESS_SUBMIT_DISPOSITIONS.steered, requestId, conversation.activeTurnTaskId)
325
+ : this.result(harness_1.HARNESS_SUBMIT_DISPOSITIONS.queued, requestId);
326
+ }
327
+ // A turn started by `submit` before messages carried their requestId.
328
+ const turn = await models.task.findOneOrNone({ deleted: { $in: [false, true] }, requestId: key });
329
+ return turn ? this.result(harness_1.HARNESS_SUBMIT_DISPOSITIONS.started, requestId, turn._id) : null;
330
+ }
331
+ /** Add a submission to the queue and announce it, unless its requestId is already there. */
332
+ async enqueue({ content, requestId, whenBusy, }) {
333
+ const { models } = this.context;
334
+ const conversationId = this.document._id;
335
+ await (0, transaction_1.inTransaction)(async (session) => {
336
+ if ((await models.message.countDocuments({ conversationId, requestId }, { session })) > 0) {
337
+ return;
338
+ }
339
+ const appended = await models.conversation.updateOne({ _id: conversationId, "queued.requestId": { $ne: requestId } }, {
340
+ $push: {
341
+ queued: { content, requestId, submittedAt: luxon_1.DateTime.now().toJSDate(), whenBusy },
342
+ },
343
+ }, { session });
344
+ if (appended.modifiedCount === 0) {
345
+ return;
346
+ }
347
+ await (0, events_1.appendEvents)({
348
+ events: [
349
+ { payload: { content, requestId, whenBusy }, type: harness_1.HARNESS_EVENT_TYPES.messageQueued },
350
+ ],
351
+ models,
352
+ session,
353
+ streamId: conversationId,
354
+ });
355
+ });
356
+ }
357
+ async load() {
358
+ const conversation = await this.context.models.conversation.findExactlyOne({
359
+ _id: this.document._id,
360
+ });
361
+ if (conversation.ownership?.kind === "task") {
362
+ throw new HarnessConversationOwnedError(this.id, String(conversation.ownership.id));
363
+ }
364
+ return conversation;
365
+ }
366
+ result(disposition, requestId, turnTaskId) {
367
+ return {
368
+ conversationId: this.id,
369
+ disposition,
370
+ requestId,
371
+ ...(turnTaskId ? { turnTaskId: String(turnTaskId) } : {}),
372
+ };
373
+ }
374
+ }
375
+ exports.HarnessConversationHandle = HarnessConversationHandle;
376
+ /**
377
+ * Whether the conversation can take a new turn. A `busy` conversation whose active turn
378
+ * is already terminal (or gone) is set back to `idle`: the runner releases conversations
379
+ * as turns finish, and this covers a release lost to a crash between the turn's commit
380
+ * and that write.
381
+ */
382
+ const releaseFinishedTurn = async ({ conversation, models, }) => {
383
+ if (conversation.status !== harness_1.HARNESS_CONVERSATION_STATUSES.busy) {
384
+ return true;
385
+ }
386
+ const activeId = conversation.activeTurnTaskId;
387
+ const active = activeId ? await models.task.findOneOrNone({ _id: activeId }) : null;
388
+ if (active && !harness_1.HARNESS_TERMINAL_STATUSES.has(active.status)) {
389
+ return false;
390
+ }
391
+ await models.conversation.updateOne({
392
+ _id: conversation._id,
393
+ activeTurnTaskId: activeId ?? null,
394
+ status: harness_1.HARNESS_CONVERSATION_STATUSES.busy,
395
+ }, { $set: { status: harness_1.HARNESS_CONVERSATION_STATUSES.idle }, $unset: { activeTurnTaskId: 1 } });
396
+ return true;
397
+ };
@@ -0,0 +1,9 @@
1
+ import type { HarnessAgentDefinition, HarnessAgentDefinitionInput, HarnessExtensionDefinition } from "../types/harness";
2
+ /** An extension reference (definition or name) as its name. */
3
+ export declare const extensionName: (owner: string, entry: HarnessExtensionDefinition | string) => string;
4
+ /**
5
+ * Declare an agent: a model, instructions, and tools. Running it runs the built-in
6
+ * `terreno.agent.turn` task on a conversation, one durable phase per model request and
7
+ * per batch of tool calls.
8
+ */
9
+ export declare const defineAgent: (definition: HarnessAgentDefinitionInput) => HarnessAgentDefinition;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineAgent = exports.extensionName = void 0;
4
+ const harness_1 = require("../types/harness");
5
+ const definitionError_1 = require("./definitionError");
6
+ const retryBackoff_1 = require("./retryBackoff");
7
+ const assertModelRef = (agent, label, ref) => {
8
+ if (!ref?.provider?.trim() || !ref.modelId?.trim()) {
9
+ throw new definitionError_1.HarnessDefinitionError(`defineAgent(${agent}): ${label} needs a provider and a modelId`);
10
+ }
11
+ };
12
+ /** An extension reference (definition or name) as its name. */
13
+ const extensionName = (owner, entry) => {
14
+ const name = typeof entry === "string" ? entry : entry?.kind === "extension" ? entry.name : "";
15
+ if (!name?.trim()) {
16
+ throw new definitionError_1.HarnessDefinitionError(`${owner}: every extension must be a defineExtension result or its name`);
17
+ }
18
+ return name;
19
+ };
20
+ exports.extensionName = extensionName;
21
+ /**
22
+ * Declare an agent: a model, instructions, and tools. Running it runs the built-in
23
+ * `terreno.agent.turn` task on a conversation, one durable phase per model request and
24
+ * per batch of tool calls.
25
+ */
26
+ const defineAgent = (definition) => {
27
+ const { name } = definition;
28
+ if (!name?.trim()) {
29
+ throw new definitionError_1.HarnessDefinitionError("defineAgent: name is required");
30
+ }
31
+ assertModelRef(name, "model", definition.model);
32
+ for (const fallback of definition.fallbackModels ?? []) {
33
+ assertModelRef(name, "each fallback model", fallback);
34
+ }
35
+ if (typeof definition.instructions !== "string") {
36
+ throw new definitionError_1.HarnessDefinitionError(`defineAgent(${name}): instructions must be a string`);
37
+ }
38
+ const maxSteps = definition.maxSteps ?? harness_1.HARNESS_AGENT_DEFAULT_MAX_STEPS;
39
+ if (!Number.isInteger(maxSteps) || maxSteps < 1) {
40
+ throw new definitionError_1.HarnessDefinitionError(`defineAgent(${name}): maxSteps must be a positive integer`);
41
+ }
42
+ if (definition.modelRetry !== undefined) {
43
+ (0, retryBackoff_1.assertValidRetryPolicy)(`defineAgent(${name})`, definition.modelRetry, "modelRetry");
44
+ }
45
+ const tools = definition.tools ?? [];
46
+ const toolNames = new Set();
47
+ for (const tool of tools) {
48
+ if (tool?.kind !== "tool") {
49
+ throw new definitionError_1.HarnessDefinitionError(`defineAgent(${name}): every tool must come from defineTool`);
50
+ }
51
+ if (toolNames.has(tool.name)) {
52
+ throw new definitionError_1.HarnessDefinitionError(`defineAgent(${name}): tool "${tool.name}" is listed more than once`);
53
+ }
54
+ toolNames.add(tool.name);
55
+ }
56
+ if (definition.output !== undefined && typeof definition.output.safeParse !== "function") {
57
+ throw new definitionError_1.HarnessDefinitionError(`defineAgent(${name}): output must be a zod schema`);
58
+ }
59
+ const extensions = (definition.extensions ?? []).map((entry) => (0, exports.extensionName)(`defineAgent(${name})`, entry));
60
+ if (new Set(extensions).size !== extensions.length) {
61
+ throw new definitionError_1.HarnessDefinitionError(`defineAgent(${name}): an extension is listed more than once`);
62
+ }
63
+ return Object.freeze({ ...definition, extensions, kind: "agent", maxSteps, tools });
64
+ };
65
+ exports.defineAgent = defineAgent;
@@ -0,0 +1,11 @@
1
+ import type { HarnessTaskDefinition, HarnessTaskDefinitionInput } from "../types/harness";
2
+ /** Registry key that pins a run to one definition version. */
3
+ export declare const taskDefinitionKey: ({ name, version }: {
4
+ name: string;
5
+ version: number;
6
+ }) => string;
7
+ /**
8
+ * Declare a durable, multi-phase task. Each phase does work and calls `rt.commit()`
9
+ * with the next phase or a terminal outcome; a committed phase is the resume point.
10
+ */
11
+ export declare const defineTask: <In, State, Out>(definition: HarnessTaskDefinitionInput<In, State, Out>) => HarnessTaskDefinition<In, State, Out>;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineTask = exports.taskDefinitionKey = void 0;
4
+ const approvalPolicy_1 = require("./approvalPolicy");
5
+ const definitionError_1 = require("./definitionError");
6
+ const retryBackoff_1 = require("./retryBackoff");
7
+ /** Registry key that pins a run to one definition version. */
8
+ const taskDefinitionKey = ({ name, version }) => `${name}@${version}`;
9
+ exports.taskDefinitionKey = taskDefinitionKey;
10
+ /**
11
+ * Declare a durable, multi-phase task. Each phase does work and calls `rt.commit()`
12
+ * with the next phase or a terminal outcome; a committed phase is the resume point.
13
+ */
14
+ const defineTask = (definition) => {
15
+ if (!definition.name?.trim()) {
16
+ throw new definitionError_1.HarnessDefinitionError("defineTask: name is required");
17
+ }
18
+ if (!Number.isInteger(definition.version) || definition.version < 1) {
19
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): version must be a positive integer`);
20
+ }
21
+ const phaseNames = Object.keys(definition.phases ?? {});
22
+ if (phaseNames.length === 0) {
23
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): at least one phase is required`);
24
+ }
25
+ for (const phaseName of phaseNames) {
26
+ const phase = definition.phases[phaseName];
27
+ if (typeof phase?.run !== "function") {
28
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): phase "${phaseName}" needs a run function`);
29
+ }
30
+ if (phase.replay !== undefined && phase.replay !== "safe" && phase.replay !== "never") {
31
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): phase "${phaseName}" replay must be "safe" or "never"`);
32
+ }
33
+ }
34
+ if (definition.retry !== undefined) {
35
+ (0, retryBackoff_1.assertValidRetryPolicy)(`defineTask(${definition.name})`, definition.retry);
36
+ }
37
+ if (definition.onInterrupt !== undefined &&
38
+ definition.onInterrupt !== "park" &&
39
+ definition.onInterrupt !== "fail") {
40
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): onInterrupt must be "park" or "fail"`);
41
+ }
42
+ if (definition.spanKind !== undefined &&
43
+ !["AGENT", "CHAIN", "TOOL"].includes(definition.spanKind)) {
44
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): spanKind must be AGENT, CHAIN, or TOOL`);
45
+ }
46
+ if (definition.spanName !== undefined && typeof definition.spanName !== "function") {
47
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): spanName must be a function`);
48
+ }
49
+ if (definition.abort !== undefined && typeof definition.abort !== "function") {
50
+ throw new definitionError_1.HarnessDefinitionError(`defineTask(${definition.name}): abort must be a function`);
51
+ }
52
+ (0, approvalPolicy_1.assertValidApprovalPolicies)(`defineTask(${definition.name})`, definition.approvals);
53
+ return Object.freeze({
54
+ ...definition,
55
+ key: (0, exports.taskDefinitionKey)(definition),
56
+ kind: "task",
57
+ });
58
+ };
59
+ exports.defineTask = defineTask;
@@ -0,0 +1,7 @@
1
+ import type { HarnessToolDefinition, HarnessToolDefinitionInput } from "../types/harness";
2
+ /**
3
+ * Declare a tool an agent may call. Each call runs as its own child task of the turn;
4
+ * `replay` (default `"never"`) decides whether an interrupted call is re-run or reported
5
+ * to the model as "interrupted, not retried".
6
+ */
7
+ export declare const defineTool: <Args, Result>(definition: HarnessToolDefinitionInput<Args, Result>) => HarnessToolDefinition<Args, Result>;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineTool = void 0;
4
+ const definitionError_1 = require("./definitionError");
5
+ /** Provider-safe tool names (the strictest common limit across providers). */
6
+ const TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
7
+ /**
8
+ * Declare a tool an agent may call. Each call runs as its own child task of the turn;
9
+ * `replay` (default `"never"`) decides whether an interrupted call is re-run or reported
10
+ * to the model as "interrupted, not retried".
11
+ */
12
+ const defineTool = (definition) => {
13
+ if (!TOOL_NAME_PATTERN.test(definition.name ?? "")) {
14
+ throw new definitionError_1.HarnessDefinitionError(`defineTool(${definition.name}): name must be 1-64 letters, digits, "_" or "-"`);
15
+ }
16
+ if (!definition.description?.trim()) {
17
+ throw new definitionError_1.HarnessDefinitionError(`defineTool(${definition.name}): description is required`);
18
+ }
19
+ if (typeof definition.parameters?.safeParse !== "function") {
20
+ throw new definitionError_1.HarnessDefinitionError(`defineTool(${definition.name}): parameters must be a zod schema`);
21
+ }
22
+ if (typeof definition.execute !== "function") {
23
+ throw new definitionError_1.HarnessDefinitionError(`defineTool(${definition.name}): execute must be a function`);
24
+ }
25
+ if (definition.replay !== undefined &&
26
+ definition.replay !== "safe" &&
27
+ definition.replay !== "never") {
28
+ throw new definitionError_1.HarnessDefinitionError(`defineTool(${definition.name}): replay must be "safe" or "never"`);
29
+ }
30
+ return Object.freeze({
31
+ ...definition,
32
+ kind: "tool",
33
+ replay: definition.replay ?? "never",
34
+ });
35
+ };
36
+ exports.defineTool = defineTool;