@terreno/ai 57.9.0 → 57.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (412) hide show
  1. package/README.md +1 -0
  2. package/bunfig.toml +1 -1
  3. package/dist/aiApp.d.ts +8 -2
  4. package/dist/aiApp.js +12 -6
  5. package/dist/harness/adminScreens.d.ts +6 -0
  6. package/dist/harness/adminScreens.js +11 -0
  7. package/dist/harness/agentLoop.d.ts +61 -0
  8. package/dist/harness/agentLoop.js +798 -0
  9. package/dist/harness/agentTaskNames.d.ts +4 -0
  10. package/dist/harness/agentTaskNames.js +7 -0
  11. package/dist/harness/approvalPolicy.d.ts +3 -0
  12. package/dist/harness/approvalPolicy.js +23 -0
  13. package/dist/harness/approvals.d.ts +101 -0
  14. package/dist/harness/approvals.js +468 -0
  15. package/dist/harness/commit.d.ts +238 -0
  16. package/dist/harness/commit.js +678 -0
  17. package/dist/harness/conversation.d.ts +75 -0
  18. package/dist/harness/conversation.js +397 -0
  19. package/dist/harness/defineAgent.d.ts +9 -0
  20. package/dist/harness/defineAgent.js +65 -0
  21. package/dist/harness/defineTask.d.ts +11 -0
  22. package/dist/harness/defineTask.js +59 -0
  23. package/dist/harness/defineTool.d.ts +7 -0
  24. package/dist/harness/defineTool.js +36 -0
  25. package/dist/harness/definitionError.d.ts +8 -0
  26. package/dist/harness/definitionError.js +15 -0
  27. package/dist/harness/errors.d.ts +127 -0
  28. package/dist/harness/errors.js +101 -0
  29. package/dist/harness/eventHub.d.ts +45 -0
  30. package/dist/harness/eventHub.js +135 -0
  31. package/dist/harness/events.d.ts +95 -0
  32. package/dist/harness/events.js +267 -0
  33. package/dist/harness/executionEnv.d.ts +31 -0
  34. package/dist/harness/executionEnv.js +2 -0
  35. package/dist/harness/extensions.d.ts +82 -0
  36. package/dist/harness/extensions.js +274 -0
  37. package/dist/harness/harness.d.ts +163 -0
  38. package/dist/harness/harness.js +520 -0
  39. package/dist/harness/harnessApp.d.ts +44 -0
  40. package/dist/harness/harnessApp.js +62 -0
  41. package/dist/harness/internalRuntime.d.ts +16 -0
  42. package/dist/harness/internalRuntime.js +18 -0
  43. package/dist/harness/leases.d.ts +35 -0
  44. package/dist/harness/leases.js +86 -0
  45. package/dist/harness/memo.d.ts +24 -0
  46. package/dist/harness/memo.js +78 -0
  47. package/dist/harness/modelCall.d.ts +45 -0
  48. package/dist/harness/modelCall.js +147 -0
  49. package/dist/harness/models/harnessApproval.d.ts +2 -0
  50. package/dist/harness/models/harnessApproval.js +100 -0
  51. package/dist/harness/models/harnessConversation.d.ts +2 -0
  52. package/dist/harness/models/harnessConversation.js +117 -0
  53. package/dist/harness/models/harnessEvent.d.ts +3 -0
  54. package/dist/harness/models/harnessEvent.js +73 -0
  55. package/dist/harness/models/harnessInboxEvent.d.ts +2 -0
  56. package/dist/harness/models/harnessInboxEvent.js +58 -0
  57. package/dist/harness/models/harnessMemo.d.ts +2 -0
  58. package/dist/harness/models/harnessMemo.js +42 -0
  59. package/dist/harness/models/harnessMessage.d.ts +2 -0
  60. package/dist/harness/models/harnessMessage.js +73 -0
  61. package/dist/harness/models/harnessOwner.d.ts +2 -0
  62. package/dist/harness/models/harnessOwner.js +36 -0
  63. package/dist/harness/models/harnessTask.d.ts +2 -0
  64. package/dist/harness/models/harnessTask.js +186 -0
  65. package/dist/harness/ownership.d.ts +89 -0
  66. package/dist/harness/ownership.js +438 -0
  67. package/dist/harness/registry.d.ts +29 -0
  68. package/dist/harness/registry.js +93 -0
  69. package/dist/harness/retryBackoff.d.ts +31 -0
  70. package/dist/harness/retryBackoff.js +50 -0
  71. package/dist/harness/routes/approvals.d.ts +13 -0
  72. package/dist/harness/routes/approvals.js +93 -0
  73. package/dist/harness/routes/conversations.d.ts +11 -0
  74. package/dist/harness/routes/conversations.js +66 -0
  75. package/dist/harness/routes/events.d.ts +19 -0
  76. package/dist/harness/routes/events.js +215 -0
  77. package/dist/harness/routes/tasks.d.ts +11 -0
  78. package/dist/harness/routes/tasks.js +108 -0
  79. package/dist/harness/runners/inProcessRunner.d.ts +57 -0
  80. package/dist/harness/runners/inProcessRunner.js +196 -0
  81. package/dist/harness/runtime.d.ts +34 -0
  82. package/dist/harness/runtime.js +551 -0
  83. package/dist/harness/subagent.d.ts +53 -0
  84. package/dist/harness/subagent.js +134 -0
  85. package/dist/harness/suspend.d.ts +8 -0
  86. package/dist/harness/suspend.js +16 -0
  87. package/dist/harness/transaction.d.ts +3 -0
  88. package/dist/harness/transaction.js +22 -0
  89. package/dist/harness/waits.d.ts +100 -0
  90. package/dist/harness/waits.js +214 -0
  91. package/dist/index.d.ts +19 -1
  92. package/dist/index.js +45 -2
  93. package/dist/models/aiDataset.d.ts +2 -0
  94. package/dist/models/aiDataset.js +67 -0
  95. package/dist/models/aiRequest.js +1 -1
  96. package/dist/models/gptHistory.js +73 -0
  97. package/dist/observability/adminScreens.d.ts +5 -0
  98. package/dist/observability/adminScreens.js +32 -0
  99. package/dist/observability/compileTemplate.d.ts +1 -0
  100. package/dist/observability/compileTemplate.js +13 -0
  101. package/dist/observability/datasetImport.d.ts +11 -0
  102. package/dist/observability/datasetImport.js +185 -0
  103. package/dist/observability/evaluate.d.ts +31 -0
  104. package/dist/observability/evaluate.js +200 -0
  105. package/dist/observability/evaluatorTemplates.d.ts +17 -0
  106. package/dist/observability/evaluatorTemplates.js +111 -0
  107. package/dist/observability/jsonPath.d.ts +2 -0
  108. package/dist/observability/jsonPath.js +57 -0
  109. package/dist/observability/local/datasetStore.d.ts +87 -0
  110. package/dist/observability/local/datasetStore.js +326 -0
  111. package/dist/observability/local/evaluatorStore.d.ts +44 -0
  112. package/dist/observability/local/evaluatorStore.js +182 -0
  113. package/dist/observability/local/experimentRunner.d.ts +96 -0
  114. package/dist/observability/local/experimentRunner.js +419 -0
  115. package/dist/observability/local/localPlugin.d.ts +22 -0
  116. package/dist/observability/local/localPlugin.js +76 -0
  117. package/dist/observability/local/models/obsDataset.d.ts +2 -0
  118. package/dist/observability/local/models/obsDataset.js +37 -0
  119. package/dist/observability/local/models/obsDatasetItem.d.ts +2 -0
  120. package/dist/observability/local/models/obsDatasetItem.js +76 -0
  121. package/dist/observability/local/models/obsEvaluator.d.ts +2 -0
  122. package/dist/observability/local/models/obsEvaluator.js +98 -0
  123. package/dist/observability/local/models/obsExperiment.d.ts +2 -0
  124. package/dist/observability/local/models/obsExperiment.js +87 -0
  125. package/dist/observability/local/models/obsExperimentItem.d.ts +2 -0
  126. package/dist/observability/local/models/obsExperimentItem.js +45 -0
  127. package/dist/observability/local/models/obsPrompt.d.ts +2 -0
  128. package/dist/observability/local/models/obsPrompt.js +42 -0
  129. package/dist/observability/local/models/obsPromptLabel.d.ts +2 -0
  130. package/dist/observability/local/models/obsPromptLabel.js +39 -0
  131. package/dist/observability/local/models/obsPromptVersion.d.ts +2 -0
  132. package/dist/observability/local/models/obsPromptVersion.js +96 -0
  133. package/dist/observability/local/models/obsReviewItem.d.ts +2 -0
  134. package/dist/observability/local/models/obsReviewItem.js +75 -0
  135. package/dist/observability/local/models/obsScore.d.ts +2 -0
  136. package/dist/observability/local/models/obsScore.js +58 -0
  137. package/dist/observability/local/models/obsSpan.d.ts +2 -0
  138. package/dist/observability/local/models/obsSpan.js +64 -0
  139. package/dist/observability/local/models/obsTrace.d.ts +2 -0
  140. package/dist/observability/local/models/obsTrace.js +93 -0
  141. package/dist/observability/local/promptStore.d.ts +180 -0
  142. package/dist/observability/local/promptStore.js +444 -0
  143. package/dist/observability/local/reviewStore.d.ts +50 -0
  144. package/dist/observability/local/reviewStore.js +203 -0
  145. package/dist/observability/local/traceStore.d.ts +103 -0
  146. package/dist/observability/local/traceStore.js +325 -0
  147. package/dist/observability/observabilityApp.d.ts +24 -0
  148. package/dist/observability/observabilityApp.js +157 -0
  149. package/dist/observability/observabilityAppRegistry.d.ts +14 -0
  150. package/dist/observability/observabilityAppRegistry.js +16 -0
  151. package/dist/observability/permissions.d.ts +7 -0
  152. package/dist/observability/permissions.js +60 -0
  153. package/dist/observability/reviewPanels.d.ts +18 -0
  154. package/dist/observability/reviewPanels.js +46 -0
  155. package/dist/observability/routes/datasets.d.ts +7 -0
  156. package/dist/observability/routes/datasets.js +149 -0
  157. package/dist/observability/routes/evaluators.d.ts +7 -0
  158. package/dist/observability/routes/evaluators.js +123 -0
  159. package/dist/observability/routes/experiments.d.ts +7 -0
  160. package/dist/observability/routes/experiments.js +95 -0
  161. package/dist/observability/routes/observabilityRouteAccess.d.ts +13 -0
  162. package/dist/observability/routes/observabilityRouteAccess.js +67 -0
  163. package/dist/observability/routes/prompts.d.ts +12 -0
  164. package/dist/observability/routes/prompts.js +172 -0
  165. package/dist/observability/routes/requestAiService.d.ts +13 -0
  166. package/dist/observability/routes/requestAiService.js +21 -0
  167. package/dist/observability/routes/review.d.ts +7 -0
  168. package/dist/observability/routes/review.js +79 -0
  169. package/dist/observability/routes/status.d.ts +5 -0
  170. package/dist/observability/routes/status.js +31 -0
  171. package/dist/observability/routes/testMultiStage.d.ts +9 -0
  172. package/dist/observability/routes/testMultiStage.js +67 -0
  173. package/dist/observability/routes/traces.d.ts +7 -0
  174. package/dist/observability/routes/traces.js +129 -0
  175. package/dist/observability/schemaValidation.d.ts +5 -0
  176. package/dist/observability/schemaValidation.js +26 -0
  177. package/dist/observability/sopThresholds.d.ts +2 -0
  178. package/dist/observability/sopThresholds.js +21 -0
  179. package/dist/observability/status.d.ts +23 -0
  180. package/dist/observability/status.js +34 -0
  181. package/dist/observability/testMultiStageSchemas.d.ts +10 -0
  182. package/dist/observability/testMultiStageSchemas.js +79 -0
  183. package/dist/observability/testMultiStageWorkflow.d.ts +20 -0
  184. package/dist/observability/testMultiStageWorkflow.js +218 -0
  185. package/dist/observability/types.d.ts +159 -0
  186. package/dist/observability/types.js +67 -0
  187. package/dist/routes/files.js +18 -7
  188. package/dist/routes/gpt.js +79 -689
  189. package/dist/routes/gptActions.d.ts +9 -0
  190. package/dist/routes/gptActions.js +212 -0
  191. package/dist/routes/gptDatasets.d.ts +5 -0
  192. package/dist/routes/gptDatasets.js +94 -0
  193. package/dist/routes/gptHistories.d.ts +3 -1
  194. package/dist/routes/gptHistories.js +188 -2
  195. package/dist/service/aiDatasets.d.ts +57 -0
  196. package/dist/service/aiDatasets.js +253 -0
  197. package/dist/service/aiService.d.ts +50 -1
  198. package/dist/service/aiService.js +426 -77
  199. package/dist/service/askFiles.d.ts +49 -0
  200. package/dist/service/askFiles.js +162 -0
  201. package/dist/service/asks.d.ts +76 -0
  202. package/dist/service/asks.js +284 -0
  203. package/dist/service/chatTurn.d.ts +128 -0
  204. package/dist/service/chatTurn.js +1674 -0
  205. package/dist/service/fileStorage.d.ts +4 -0
  206. package/dist/service/fileStorage.js +7 -2
  207. package/dist/service/fillActionIds.d.ts +6 -0
  208. package/dist/service/fillActionIds.js +79 -0
  209. package/dist/service/jsonFenceModel.d.ts +7 -0
  210. package/dist/service/jsonFenceModel.js +45 -0
  211. package/dist/service/prompts.d.ts +52 -0
  212. package/dist/service/prompts.js +96 -1
  213. package/dist/service/sanitizeHtml.d.ts +11 -0
  214. package/dist/service/sanitizeHtml.js +108 -0
  215. package/dist/types/harness.d.ts +934 -0
  216. package/dist/types/harness.js +133 -0
  217. package/dist/types/index.d.ts +192 -14
  218. package/dist/types/index.js +2 -0
  219. package/dist/types/observability.d.ts +288 -0
  220. package/dist/types/observability.js +2 -0
  221. package/package.json +17 -5
  222. package/src/aiApp.test.ts +207 -1
  223. package/src/aiApp.ts +19 -6
  224. package/src/harness/adminScreens.test.ts +34 -0
  225. package/src/harness/adminScreens.ts +11 -0
  226. package/src/harness/agentLoop.test.ts +1034 -0
  227. package/src/harness/agentLoop.ts +1082 -0
  228. package/src/harness/agentRecovery.test.ts +380 -0
  229. package/src/harness/agentTaskNames.ts +4 -0
  230. package/src/harness/approvalPolicy.ts +28 -0
  231. package/src/harness/approvals.test.ts +1094 -0
  232. package/src/harness/approvals.ts +644 -0
  233. package/src/harness/commit.ts +1049 -0
  234. package/src/harness/conversation.ts +503 -0
  235. package/src/harness/defineAgent.test.ts +92 -0
  236. package/src/harness/defineAgent.ts +82 -0
  237. package/src/harness/defineTask.test.ts +59 -0
  238. package/src/harness/defineTask.ts +76 -0
  239. package/src/harness/defineTool.ts +45 -0
  240. package/src/harness/definitionError.ts +13 -0
  241. package/src/harness/errors.test.ts +90 -0
  242. package/src/harness/errors.ts +119 -0
  243. package/src/harness/eventHub.test.ts +124 -0
  244. package/src/harness/eventHub.ts +159 -0
  245. package/src/harness/events.test.ts +757 -0
  246. package/src/harness/events.ts +384 -0
  247. package/src/harness/executionEnv.ts +34 -0
  248. package/src/harness/extensions.test.ts +1218 -0
  249. package/src/harness/extensions.ts +382 -0
  250. package/src/harness/harness.test.ts +693 -0
  251. package/src/harness/harness.ts +767 -0
  252. package/src/harness/harnessApp.ts +76 -0
  253. package/src/harness/internalRuntime.ts +44 -0
  254. package/src/harness/leases.ts +132 -0
  255. package/src/harness/memo.ts +107 -0
  256. package/src/harness/modelCall.test.ts +134 -0
  257. package/src/harness/modelCall.ts +200 -0
  258. package/src/harness/models/harnessApproval.ts +109 -0
  259. package/src/harness/models/harnessConversation.ts +142 -0
  260. package/src/harness/models/harnessEvent.ts +92 -0
  261. package/src/harness/models/harnessInboxEvent.ts +73 -0
  262. package/src/harness/models/harnessMemo.ts +43 -0
  263. package/src/harness/models/harnessMessage.ts +85 -0
  264. package/src/harness/models/harnessModels.test.ts +60 -0
  265. package/src/harness/models/harnessOwner.ts +40 -0
  266. package/src/harness/models/harnessTask.ts +201 -0
  267. package/src/harness/ownership.test.ts +1087 -0
  268. package/src/harness/ownership.ts +618 -0
  269. package/src/harness/recovery.test.ts +912 -0
  270. package/src/harness/registry.ts +124 -0
  271. package/src/harness/retries.test.ts +292 -0
  272. package/src/harness/retryBackoff.test.ts +100 -0
  273. package/src/harness/retryBackoff.ts +77 -0
  274. package/src/harness/routes/approvals.ts +123 -0
  275. package/src/harness/routes/conversations.test.ts +518 -0
  276. package/src/harness/routes/conversations.ts +102 -0
  277. package/src/harness/routes/events.ts +280 -0
  278. package/src/harness/routes/tasks.test.ts +198 -0
  279. package/src/harness/routes/tasks.ts +146 -0
  280. package/src/harness/runners/inProcessRunner.test.ts +402 -0
  281. package/src/harness/runners/inProcessRunner.ts +220 -0
  282. package/src/harness/runtime.ts +714 -0
  283. package/src/harness/subagent.test.ts +696 -0
  284. package/src/harness/subagent.ts +192 -0
  285. package/src/harness/suspend.ts +13 -0
  286. package/src/harness/transaction.ts +17 -0
  287. package/src/harness/versioning.test.ts +288 -0
  288. package/src/harness/waits.test.ts +693 -0
  289. package/src/harness/waits.ts +356 -0
  290. package/src/index.test.ts +13 -0
  291. package/src/index.ts +70 -0
  292. package/src/isolated/adminScreensConfig.isolated.ts +143 -0
  293. package/src/models/aiDataset.test.ts +34 -0
  294. package/src/models/aiDataset.ts +78 -0
  295. package/src/models/aiRequest.ts +2 -1
  296. package/src/models/gptHistory.test.ts +156 -0
  297. package/src/models/gptHistory.ts +89 -1
  298. package/src/observability/adminScreens.test.ts +71 -0
  299. package/src/observability/adminScreens.ts +42 -0
  300. package/src/observability/compileTemplate.test.ts +14 -0
  301. package/src/observability/compileTemplate.ts +10 -0
  302. package/src/observability/datasetImport.test.ts +95 -0
  303. package/src/observability/datasetImport.ts +220 -0
  304. package/src/observability/evaluate.test.ts +549 -0
  305. package/src/observability/evaluate.ts +254 -0
  306. package/src/observability/evaluatorTemplates.ts +124 -0
  307. package/src/observability/jsonPath.test.ts +52 -0
  308. package/src/observability/jsonPath.ts +60 -0
  309. package/src/observability/local/datasetStore.test.ts +230 -0
  310. package/src/observability/local/datasetStore.ts +452 -0
  311. package/src/observability/local/evaluatorStore.test.ts +138 -0
  312. package/src/observability/local/evaluatorStore.ts +224 -0
  313. package/src/observability/local/experimentRunner.test.ts +489 -0
  314. package/src/observability/local/experimentRunner.ts +548 -0
  315. package/src/observability/local/localPlugin.ts +88 -0
  316. package/src/observability/local/models/obsDataset.ts +38 -0
  317. package/src/observability/local/models/obsDatasetItem.ts +80 -0
  318. package/src/observability/local/models/obsEvaluator.ts +102 -0
  319. package/src/observability/local/models/obsExperiment.ts +91 -0
  320. package/src/observability/local/models/obsExperimentItem.ts +52 -0
  321. package/src/observability/local/models/obsPrompt.ts +43 -0
  322. package/src/observability/local/models/obsPromptLabel.ts +43 -0
  323. package/src/observability/local/models/obsPromptVersion.ts +107 -0
  324. package/src/observability/local/models/obsReviewItem.ts +79 -0
  325. package/src/observability/local/models/obsScore.ts +59 -0
  326. package/src/observability/local/models/obsSpan.ts +65 -0
  327. package/src/observability/local/models/obsTrace.ts +94 -0
  328. package/src/observability/local/obsModels.test.ts +119 -0
  329. package/src/observability/local/promptStore.test.ts +351 -0
  330. package/src/observability/local/promptStore.ts +665 -0
  331. package/src/observability/local/reviewStore.test.ts +164 -0
  332. package/src/observability/local/reviewStore.ts +264 -0
  333. package/src/observability/local/traceStore.test.ts +264 -0
  334. package/src/observability/local/traceStore.ts +440 -0
  335. package/src/observability/observabilityApp.test.ts +92 -0
  336. package/src/observability/observabilityApp.ts +185 -0
  337. package/src/observability/observabilityAppRegistry.test.ts +30 -0
  338. package/src/observability/observabilityAppRegistry.ts +35 -0
  339. package/src/observability/permissions.test.ts +96 -0
  340. package/src/observability/permissions.ts +78 -0
  341. package/src/observability/reviewPanels.test.ts +35 -0
  342. package/src/observability/reviewPanels.ts +64 -0
  343. package/src/observability/routes/datasets.test.ts +176 -0
  344. package/src/observability/routes/datasets.ts +252 -0
  345. package/src/observability/routes/evaluators.test.ts +119 -0
  346. package/src/observability/routes/evaluators.ts +207 -0
  347. package/src/observability/routes/experiments.test.ts +282 -0
  348. package/src/observability/routes/experiments.ts +152 -0
  349. package/src/observability/routes/observabilityRbac.test.ts +767 -0
  350. package/src/observability/routes/observabilityRouteAccess.ts +106 -0
  351. package/src/observability/routes/prompts.test.ts +320 -0
  352. package/src/observability/routes/prompts.ts +263 -0
  353. package/src/observability/routes/requestAiService.ts +36 -0
  354. package/src/observability/routes/review.test.ts +120 -0
  355. package/src/observability/routes/review.ts +125 -0
  356. package/src/observability/routes/status.test.ts +116 -0
  357. package/src/observability/routes/status.ts +47 -0
  358. package/src/observability/routes/testMultiStage.test.ts +214 -0
  359. package/src/observability/routes/testMultiStage.ts +96 -0
  360. package/src/observability/routes/traces.test.ts +167 -0
  361. package/src/observability/routes/traces.ts +172 -0
  362. package/src/observability/schemaValidation.ts +29 -0
  363. package/src/observability/sopThresholds.ts +20 -0
  364. package/src/observability/status.test.ts +38 -0
  365. package/src/observability/status.ts +56 -0
  366. package/src/observability/testMultiStageSchemas.ts +95 -0
  367. package/src/observability/testMultiStageWorkflow.test.ts +114 -0
  368. package/src/observability/testMultiStageWorkflow.ts +307 -0
  369. package/src/observability/types.ts +262 -0
  370. package/src/routes/files.test.ts +63 -9
  371. package/src/routes/files.ts +21 -7
  372. package/src/routes/gpt.test.ts +3279 -0
  373. package/src/routes/gpt.ts +91 -816
  374. package/src/routes/gptActions.test.ts +241 -0
  375. package/src/routes/gptActions.ts +255 -0
  376. package/src/routes/gptApprovals.test.ts +762 -0
  377. package/src/routes/gptDatasets.test.ts +86 -0
  378. package/src/routes/gptDatasets.ts +104 -0
  379. package/src/routes/gptFiles.test.ts +589 -0
  380. package/src/routes/gptHistories.test.ts +933 -0
  381. package/src/routes/gptHistories.ts +266 -5
  382. package/src/routes/routes.test.ts +222 -2
  383. package/src/service/aiDatasets.test.ts +123 -0
  384. package/src/service/aiDatasets.ts +316 -0
  385. package/src/service/aiService.test.ts +593 -0
  386. package/src/service/aiService.ts +568 -111
  387. package/src/service/askFiles.test.ts +96 -0
  388. package/src/service/askFiles.ts +222 -0
  389. package/src/service/asks.test.ts +946 -0
  390. package/src/service/asks.ts +423 -0
  391. package/src/service/chatTurn.ts +2287 -0
  392. package/src/service/fileStorage.test.ts +11 -0
  393. package/src/service/fileStorage.ts +10 -2
  394. package/src/service/fillActionIds.test.ts +65 -0
  395. package/src/service/fillActionIds.ts +98 -0
  396. package/src/service/jsonFenceModel.test.ts +47 -0
  397. package/src/service/jsonFenceModel.ts +53 -0
  398. package/src/service/prompts.test.ts +21 -0
  399. package/src/service/prompts.ts +147 -0
  400. package/src/service/sanitizeHtml.test.ts +61 -0
  401. package/src/service/sanitizeHtml.ts +109 -0
  402. package/src/tests/bunSetup.test.ts +7 -4
  403. package/src/tests/bunSetup.ts +7 -7
  404. package/src/tests/chatHarness.ts +478 -0
  405. package/src/tests/generateStream.ts +49 -0
  406. package/src/tests/harnessErrors.ts +22 -0
  407. package/src/tests/harnessStreaming.ts +227 -0
  408. package/src/tests/helpers.ts +9 -2
  409. package/src/types/harness.ts +1095 -0
  410. package/src/types/index.ts +209 -13
  411. package/src/types/observability.ts +344 -0
  412. package/src/types/sanitize-html.d.ts +25 -0
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.eventBody = exports.HarnessDeltaWriter = exports.insertMessages = exports.appendTaskTransitionEvents = exports.appendTaskEvents = exports.taskStreamOf = exports.appendEvents = exports.resolveStreamingOptions = void 0;
4
+ const api_1 = require("@terreno/api");
5
+ const luxon_1 = require("luxon");
6
+ const harness_1 = require("../types/harness");
7
+ const agentTaskNames_1 = require("./agentTaskNames");
8
+ const errors_1 = require("./errors");
9
+ const transaction_1 = require("./transaction");
10
+ const resolveStreamingOptions = (options = {}) => {
11
+ const resolved = {
12
+ deltaFlushChars: options.deltaFlushChars ?? 200,
13
+ deltaFlushInterval: luxon_1.Duration.fromDurationLike(options.deltaFlushInterval ?? { milliseconds: 250 }),
14
+ deltaTtl: luxon_1.Duration.fromDurationLike(options.deltaTtl ?? { hours: 1 }),
15
+ };
16
+ if (!Number.isInteger(resolved.deltaFlushChars) || resolved.deltaFlushChars < 1) {
17
+ throw (0, errors_1.harnessError)({
18
+ detail: "Harness streaming.deltaFlushChars must be a positive integer",
19
+ kind: "configInvalid",
20
+ });
21
+ }
22
+ if (resolved.deltaFlushInterval.toMillis() <= 0 || resolved.deltaTtl.toMillis() <= 0) {
23
+ throw (0, errors_1.harnessError)({
24
+ detail: "Harness streaming.deltaFlushInterval and deltaTtl must be positive",
25
+ kind: "configInvalid",
26
+ });
27
+ }
28
+ return resolved;
29
+ };
30
+ exports.resolveStreamingOptions = resolveStreamingOptions;
31
+ /**
32
+ * Append `events` to `streamId` in order. The stream's counter hands out consecutive
33
+ * `seq`s in the same transaction, so concurrent writers to one stream serialize on it and
34
+ * a stream's events commit in `seq` order: a reader that has seen `seq` n has seen every
35
+ * earlier event. Without `session` the write runs in its own transaction.
36
+ */
37
+ const appendEvents = async ({ events, models, session, streamId, }) => {
38
+ if (events.length === 0) {
39
+ return;
40
+ }
41
+ const write = async (writeSession) => {
42
+ const counter = await models.eventStream.findOneAndUpdate({ _id: streamId }, { $inc: { seq: events.length } }, { returnDocument: "after", session: writeSession, upsert: true });
43
+ const first = (counter?.seq ?? events.length) - events.length + 1;
44
+ const created = luxon_1.DateTime.now().toJSDate();
45
+ await models.event.insertMany(events.map((event, index) => ({
46
+ created,
47
+ ...(event.expiresAt ? { expiresAt: event.expiresAt } : {}),
48
+ payload: event.payload,
49
+ seq: first + index,
50
+ streamId,
51
+ ...(event.taskId ? { taskId: event.taskId } : {}),
52
+ taskPath: event.taskPath ?? [],
53
+ type: event.type,
54
+ })), { ordered: true, session: writeSession });
55
+ };
56
+ if (session) {
57
+ await write(session);
58
+ return;
59
+ }
60
+ await (0, transaction_1.inTransaction)(write);
61
+ };
62
+ exports.appendEvents = appendEvents;
63
+ /** The stream a task's events go to (its tree's root task) and its path within the tree. */
64
+ const taskStreamOf = (task) => ({
65
+ streamId: task.rootTaskId ?? task._id,
66
+ taskPath: [...(task.ancestorIds ?? []), task._id],
67
+ });
68
+ exports.taskStreamOf = taskStreamOf;
69
+ /** Append task-stream events about `task` (its tree's stream, scoped to its path). */
70
+ const appendTaskEvents = async ({ events, models, session, task, }) => {
71
+ const { streamId, taskPath } = (0, exports.taskStreamOf)(task);
72
+ await (0, exports.appendEvents)({
73
+ events: events.map((event) => ({ ...event, taskId: task._id, taskPath })),
74
+ models,
75
+ session,
76
+ streamId,
77
+ });
78
+ };
79
+ exports.appendTaskEvents = appendTaskEvents;
80
+ const outcomeOf = (task) => task.outcome
81
+ ? {
82
+ error: task.outcome.error,
83
+ result: task.outcome.result,
84
+ status: task.outcome.status,
85
+ }
86
+ : undefined;
87
+ const conversationOf = (task) => {
88
+ const conversationId = task.input?.conversationId;
89
+ return typeof conversationId === "string" ? conversationId : undefined;
90
+ };
91
+ /** `turn.*` / `tool.*` conversation events for a built-in agent task, if it is one. */
92
+ const lifecycleEvent = (task, stage) => {
93
+ const conversationId = conversationOf(task);
94
+ if (!conversationId) {
95
+ return undefined;
96
+ }
97
+ const outcome = stage === "finished" ? outcomeOf(task) : undefined;
98
+ if (task.name === agentTaskNames_1.AGENT_TURN_TASK_NAME) {
99
+ return {
100
+ conversationId,
101
+ event: {
102
+ payload: { status: task.status, turnTaskId: String(task._id), ...(outcome ? { outcome } : {}) },
103
+ taskId: task._id,
104
+ type: stage === "started" ? harness_1.HARNESS_EVENT_TYPES.turnStarted : harness_1.HARNESS_EVENT_TYPES.turnFinished,
105
+ },
106
+ };
107
+ }
108
+ if (task.name === agentTaskNames_1.AGENT_TOOL_TASK_NAME) {
109
+ const input = task.input;
110
+ return {
111
+ conversationId,
112
+ event: {
113
+ payload: {
114
+ status: task.status,
115
+ taskId: String(task._id),
116
+ toolCallId: input.toolCallId,
117
+ toolName: input.toolName,
118
+ turnTaskId: task.ownership?.id ? String(task.ownership.id) : undefined,
119
+ ...(outcome ? { outcome } : {}),
120
+ },
121
+ taskId: task._id,
122
+ type: stage === "started" ? harness_1.HARNESS_EVENT_TYPES.toolStarted : harness_1.HARNESS_EVENT_TYPES.toolFinished,
123
+ },
124
+ };
125
+ }
126
+ return undefined;
127
+ };
128
+ /**
129
+ * Events for a committed task write, in the write's transaction: `task.status` when the
130
+ * task was created or its status or phase changed, plus `turn.*` / `tool.*` on the
131
+ * conversation stream when a built-in agent task starts or ends.
132
+ */
133
+ const appendTaskTransitionEvents = async ({ after, before, models, session, }) => {
134
+ const isCreated = before === undefined;
135
+ if (!isCreated && before.status === after.status && before.phase === after.phase) {
136
+ return;
137
+ }
138
+ await (0, exports.appendTaskEvents)({
139
+ events: [
140
+ {
141
+ payload: {
142
+ name: after.name,
143
+ phase: after.phase,
144
+ status: after.status,
145
+ taskId: String(after._id),
146
+ version: after.version,
147
+ ...(after.ownership?.kind === "task" && after.ownership.id
148
+ ? { parentTaskId: String(after.ownership.id) }
149
+ : {}),
150
+ ...(outcomeOf(after) ? { outcome: outcomeOf(after) } : {}),
151
+ },
152
+ type: harness_1.HARNESS_EVENT_TYPES.taskStatus,
153
+ },
154
+ ],
155
+ models,
156
+ session,
157
+ task: after,
158
+ });
159
+ const isFinished = harness_1.HARNESS_TERMINAL_STATUSES.has(after.status) &&
160
+ !(before && harness_1.HARNESS_TERMINAL_STATUSES.has(before.status));
161
+ const stage = isCreated ? "started" : isFinished ? "finished" : undefined;
162
+ const lifecycle = stage ? lifecycleEvent(after, stage) : undefined;
163
+ if (lifecycle) {
164
+ await (0, exports.appendEvents)({
165
+ events: [lifecycle.event],
166
+ models,
167
+ session,
168
+ streamId: lifecycle.conversationId,
169
+ });
170
+ }
171
+ };
172
+ exports.appendTaskTransitionEvents = appendTaskTransitionEvents;
173
+ /** Insert transcript messages of one conversation and their `message.created` events. */
174
+ const insertMessages = async ({ messages, models, session, }) => {
175
+ const first = messages[0];
176
+ if (!first) {
177
+ return [];
178
+ }
179
+ const created = await models.message.create([...messages], { ordered: true, session });
180
+ await (0, exports.appendEvents)({
181
+ events: created.map((message) => ({
182
+ payload: { message: message.toJSON() },
183
+ type: harness_1.HARNESS_EVENT_TYPES.messageCreated,
184
+ })),
185
+ models,
186
+ session,
187
+ streamId: first.conversationId,
188
+ });
189
+ return created;
190
+ };
191
+ exports.insertMessages = insertMessages;
192
+ /**
193
+ * Coalesces streamed model text into `delta` events: buffered text is written once
194
+ * `deltaFlushChars` characters accumulate or `deltaFlushInterval` passes. Writes run in
195
+ * order, outside any commit, and are best-effort: a failed write is logged and dropped,
196
+ * since the committed message is authoritative.
197
+ */
198
+ class HarnessDeltaWriter {
199
+ context;
200
+ buffer = "";
201
+ pending = Promise.resolve();
202
+ timer;
203
+ constructor(context) {
204
+ this.context = context;
205
+ }
206
+ push(text) {
207
+ if (!text) {
208
+ return;
209
+ }
210
+ this.buffer += text;
211
+ if (this.buffer.length >= this.context.options.deltaFlushChars) {
212
+ this.flush();
213
+ return;
214
+ }
215
+ if (!this.timer) {
216
+ this.timer = setTimeout(() => this.flush(), this.context.options.deltaFlushInterval.toMillis());
217
+ }
218
+ }
219
+ /** Write what is buffered and wait for every write so far. */
220
+ async close() {
221
+ this.flush();
222
+ await this.pending;
223
+ }
224
+ flush() {
225
+ clearTimeout(this.timer);
226
+ this.timer = undefined;
227
+ if (!this.buffer) {
228
+ return;
229
+ }
230
+ const text = this.buffer;
231
+ this.buffer = "";
232
+ const { models, options, source } = this.context;
233
+ this.pending = this.pending.then(async () => {
234
+ try {
235
+ await (0, exports.appendEvents)({
236
+ events: [
237
+ {
238
+ expiresAt: luxon_1.DateTime.now().plus(options.deltaTtl).toJSDate(),
239
+ payload: {
240
+ requestKey: source.requestKey,
241
+ step: source.step,
242
+ text,
243
+ turnTaskId: source.turnTaskId,
244
+ },
245
+ type: harness_1.HARNESS_EVENT_TYPES.delta,
246
+ },
247
+ ],
248
+ models,
249
+ streamId: source.conversationId,
250
+ });
251
+ }
252
+ catch (error) {
253
+ api_1.logger.warn(`Harness could not write a delta for turn ${source.turnTaskId}: ${(0, errors_1.errorMessage)(error)}`);
254
+ }
255
+ });
256
+ }
257
+ }
258
+ exports.HarnessDeltaWriter = HarnessDeltaWriter;
259
+ /** The JSON body of an event as sent over SSE (`data:`). */
260
+ const eventBody = (event) => ({
261
+ created: event.created.toISOString(),
262
+ payload: event.payload ?? null,
263
+ seq: event.seq,
264
+ ...(event.taskId ? { taskId: String(event.taskId) } : {}),
265
+ type: event.type,
266
+ });
267
+ exports.eventBody = eventBody;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Where an agent's coding tools read files, write files, and run commands. Phase 1 ships
3
+ * the interface only, so tools and tasks can be written against it; Node and remote
4
+ * sandbox implementations ship with coding agents.
5
+ */
6
+ export interface ExecutionEnv {
7
+ /** Run a command and wait for it to exit. */
8
+ exec(command: string, options?: ExecutionEnvExecOptions): Promise<ExecutionEnvExecResult>;
9
+ /** Read a UTF-8 file, relative to the environment's working directory. */
10
+ read(path: string, options?: ExecutionEnvCallOptions): Promise<string>;
11
+ /** Create or replace a UTF-8 file, relative to the environment's working directory. */
12
+ write(path: string, content: string, options?: ExecutionEnvCallOptions): Promise<void>;
13
+ }
14
+ export interface ExecutionEnvCallOptions {
15
+ /** Cancels the call; pass `rt.signal` or the tool api's `signal`. */
16
+ signal?: AbortSignal;
17
+ }
18
+ export interface ExecutionEnvExecOptions extends ExecutionEnvCallOptions {
19
+ args?: string[];
20
+ /** Working directory, relative to the environment's root. */
21
+ cwd?: string;
22
+ env?: Record<string, string>;
23
+ /** Written to the command's standard input. */
24
+ stdin?: string;
25
+ timeoutMs?: number;
26
+ }
27
+ export interface ExecutionEnvExecResult {
28
+ exitCode: number;
29
+ stderr: string;
30
+ stdout: string;
31
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,82 @@
1
+ import type { AnyHarnessToolDefinition, HarnessAgentDefinition, HarnessApprovalRequest, HarnessExtensionDefinition, HarnessExtensionDefinitionInput, HarnessHook, HarnessHookApi, HarnessHookHandlers, HarnessHookKind, HarnessModelRequest, HarnessSection, HarnessSectionInput, HarnessSystemPromptPart, HarnessToolCall, HarnessToolWrap } from "../types/harness";
2
+ /**
3
+ * A hook, a section, or a wrap threw. The step it ran in fails with this message: the
4
+ * turn for sections and `beforeModelRequest`, the tool call (reported to the model) for
5
+ * tool hooks and wraps.
6
+ */
7
+ export declare class HarnessExtensionError extends Error {
8
+ readonly extension: string;
9
+ constructor(extension: string, what: string, cause: unknown);
10
+ }
11
+ /** A named piece of the system prompt, rebuilt before every model request. */
12
+ export declare const section: (name: string, build: HarnessSection["build"]) => HarnessSection;
13
+ /** A hook of `kind` (`beforeModelRequest`, `beforeTool`, `afterTool`). */
14
+ export declare const hook: <K extends HarnessHookKind>(kind: K, run: HarnessHookHandlers[K]) => HarnessHook;
15
+ /**
16
+ * Decorate whichever tool named `toolOrName` wins (agent or extension). `wrap` receives
17
+ * the tool and returns the tool to use instead, with the same name.
18
+ */
19
+ export declare const wrapTool: (toolOrName: AnyHarnessToolDefinition | string, wrap: HarnessToolWrap["wrap"]) => HarnessToolWrap;
20
+ /**
21
+ * Declare an extension: prompt sections, tools, hooks, and tool wraps that agents and
22
+ * conversations use by name. List it in `Harness.open({registry})`.
23
+ */
24
+ export declare const defineExtension: (definition: HarnessExtensionDefinitionInput) => HarnessExtensionDefinition;
25
+ /** The extensions named by `names`, in order. Throws for a name the registry lacks. */
26
+ export declare const resolveExtensions: (extensions: Map<string, HarnessExtensionDefinition>, names: ReadonlyArray<string>) => HarnessExtensionDefinition[];
27
+ /**
28
+ * The tools a conversation can call, by name: the agent's tools, then each extension's
29
+ * in order (a later tool with the same name replaces an earlier one), then every wrap in
30
+ * extension order applied to the winning tool (the first extension's wrap is innermost).
31
+ */
32
+ export declare const resolveTools: (agent: HarnessAgentDefinition, extensions: ReadonlyArray<HarnessExtensionDefinition>) => Map<string, AnyHarnessToolDefinition>;
33
+ /** The effective system prompt, and what it was built from. */
34
+ export interface SystemPrompt {
35
+ hash: string;
36
+ sections: HarnessSystemPromptPart["sections"];
37
+ text: string;
38
+ }
39
+ export declare const hashText: (text: string) => string;
40
+ /** Agent instructions, then each non-empty section in extension and section order. */
41
+ export declare const buildSystemPrompt: ({ api, extensions, input, instructions, }: {
42
+ api: HarnessHookApi;
43
+ extensions: ReadonlyArray<HarnessExtensionDefinition>;
44
+ input: HarnessSectionInput;
45
+ instructions: string;
46
+ }) => Promise<SystemPrompt>;
47
+ /** Hooks a model request went through, with the extensions whose hooks rewrote it. */
48
+ export interface RewrittenRequest {
49
+ request: HarnessModelRequest;
50
+ rewrittenBy: string[];
51
+ }
52
+ /** Run every `beforeModelRequest` hook in order; each sees the previous one's result. */
53
+ export declare const runBeforeModelRequest: ({ api, extensions, request, }: {
54
+ api: HarnessHookApi;
55
+ extensions: ReadonlyArray<HarnessExtensionDefinition>;
56
+ request: HarnessModelRequest;
57
+ }) => Promise<RewrittenRequest>;
58
+ /** Result of the `beforeTool` hooks: the call is blocked, or runs with these args. */
59
+ export type BeforeToolOutcome = {
60
+ args: unknown;
61
+ blocked?: undefined;
62
+ } | {
63
+ blocked: string;
64
+ };
65
+ /**
66
+ * Run every `beforeTool` hook in order. The first `{block}` stops the rest. Each hook's
67
+ * `api.approval` resolves approvers from that hook's own extension. A hook waiting on an
68
+ * approval suspends the tool call (the suspend signal passes through untouched).
69
+ */
70
+ export declare const runBeforeTool: ({ api, approvalFor, call, extensions, }: {
71
+ api: HarnessHookApi;
72
+ approvalFor: (extension: string) => HarnessApprovalRequest;
73
+ call: HarnessToolCall;
74
+ extensions: ReadonlyArray<HarnessExtensionDefinition>;
75
+ }) => Promise<BeforeToolOutcome>;
76
+ /** Run every `afterTool` hook in order; each sees the previous one's result. */
77
+ export declare const runAfterTool: ({ api, call, extensions, result, }: {
78
+ api: HarnessHookApi;
79
+ call: HarnessToolCall;
80
+ extensions: ReadonlyArray<HarnessExtensionDefinition>;
81
+ result: unknown;
82
+ }) => Promise<unknown>;
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runAfterTool = exports.runBeforeTool = exports.runBeforeModelRequest = exports.buildSystemPrompt = exports.hashText = exports.resolveTools = exports.resolveExtensions = exports.defineExtension = exports.wrapTool = exports.hook = exports.section = exports.HarnessExtensionError = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const harness_1 = require("../types/harness");
6
+ const approvalPolicy_1 = require("./approvalPolicy");
7
+ const definitionError_1 = require("./definitionError");
8
+ const errors_1 = require("./errors");
9
+ const suspend_1 = require("./suspend");
10
+ /** A hook that parked its task (an approval wait) must stop the phase, not fail it. */
11
+ const rethrowSuspend = (error) => {
12
+ if ((0, suspend_1.isHarnessSuspendSignal)(error)) {
13
+ throw error;
14
+ }
15
+ };
16
+ /**
17
+ * A hook, a section, or a wrap threw. The step it ran in fails with this message: the
18
+ * turn for sections and `beforeModelRequest`, the tool call (reported to the model) for
19
+ * tool hooks and wraps.
20
+ */
21
+ class HarnessExtensionError extends Error {
22
+ extension;
23
+ constructor(extension, what, cause) {
24
+ super(`Extension "${extension}" ${what} failed: ${(0, errors_1.errorMessage)(cause)}`);
25
+ this.name = "HarnessExtensionError";
26
+ this.extension = extension;
27
+ }
28
+ }
29
+ exports.HarnessExtensionError = HarnessExtensionError;
30
+ /** A named piece of the system prompt, rebuilt before every model request. */
31
+ const section = (name, build) => {
32
+ if (!name?.trim()) {
33
+ throw new definitionError_1.HarnessDefinitionError("section: name is required");
34
+ }
35
+ if (typeof build !== "function") {
36
+ throw new definitionError_1.HarnessDefinitionError(`section(${name}): build must be a function`);
37
+ }
38
+ return Object.freeze({ build, kind: "section", name });
39
+ };
40
+ exports.section = section;
41
+ /** A hook of `kind` (`beforeModelRequest`, `beforeTool`, `afterTool`). */
42
+ const hook = (kind, run) => {
43
+ if (!Object.values(harness_1.HARNESS_HOOK_KINDS).includes(kind)) {
44
+ throw new definitionError_1.HarnessDefinitionError(`hook: kind must be one of ${Object.values(harness_1.HARNESS_HOOK_KINDS).join(", ")}, not "${kind}"`);
45
+ }
46
+ if (typeof run !== "function") {
47
+ throw new definitionError_1.HarnessDefinitionError(`hook(${kind}): handler must be a function`);
48
+ }
49
+ return Object.freeze({ hook: kind, kind: "hook", run });
50
+ };
51
+ exports.hook = hook;
52
+ /**
53
+ * Decorate whichever tool named `toolOrName` wins (agent or extension). `wrap` receives
54
+ * the tool and returns the tool to use instead, with the same name.
55
+ */
56
+ const wrapTool = (toolOrName, wrap) => {
57
+ const toolName = typeof toolOrName === "string" ? toolOrName : toolOrName?.name;
58
+ if (!toolName?.trim()) {
59
+ throw new definitionError_1.HarnessDefinitionError("wrapTool: a tool or tool name is required");
60
+ }
61
+ if (typeof wrap !== "function") {
62
+ throw new definitionError_1.HarnessDefinitionError(`wrapTool(${toolName}): wrap must be a function`);
63
+ }
64
+ return Object.freeze({ kind: "wrap", toolName, wrap });
65
+ };
66
+ exports.wrapTool = wrapTool;
67
+ /**
68
+ * Declare an extension: prompt sections, tools, hooks, and tool wraps that agents and
69
+ * conversations use by name. List it in `Harness.open({registry})`.
70
+ */
71
+ const defineExtension = (definition) => {
72
+ const { name } = definition;
73
+ if (!name?.trim()) {
74
+ throw new definitionError_1.HarnessDefinitionError("defineExtension: name is required");
75
+ }
76
+ const sections = definition.sections ?? [];
77
+ const sectionNames = new Set();
78
+ for (const entry of sections) {
79
+ if (entry?.kind !== "section") {
80
+ throw new definitionError_1.HarnessDefinitionError(`defineExtension(${name}): every section must come from section()`);
81
+ }
82
+ if (sectionNames.has(entry.name)) {
83
+ throw new definitionError_1.HarnessDefinitionError(`defineExtension(${name}): section "${entry.name}" is listed more than once`);
84
+ }
85
+ sectionNames.add(entry.name);
86
+ }
87
+ const tools = definition.tools ?? [];
88
+ const toolNames = new Set();
89
+ for (const tool of tools) {
90
+ if (tool?.kind !== "tool") {
91
+ throw new definitionError_1.HarnessDefinitionError(`defineExtension(${name}): every tool must come from defineTool`);
92
+ }
93
+ if (toolNames.has(tool.name)) {
94
+ throw new definitionError_1.HarnessDefinitionError(`defineExtension(${name}): tool "${tool.name}" is listed more than once`);
95
+ }
96
+ toolNames.add(tool.name);
97
+ }
98
+ const hooks = definition.hooks ?? [];
99
+ if (hooks.some((entry) => entry?.kind !== "hook")) {
100
+ throw new definitionError_1.HarnessDefinitionError(`defineExtension(${name}): every hook must come from hook()`);
101
+ }
102
+ const wraps = definition.wraps ?? [];
103
+ if (wraps.some((entry) => entry?.kind !== "wrap")) {
104
+ throw new definitionError_1.HarnessDefinitionError(`defineExtension(${name}): every wrap must come from wrapTool()`);
105
+ }
106
+ const approvals = Object.freeze({
107
+ ...(definition.approvals ?? {}),
108
+ });
109
+ (0, approvalPolicy_1.assertValidApprovalPolicies)(`defineExtension(${name})`, definition.approvals);
110
+ return Object.freeze({
111
+ approvals,
112
+ hooks,
113
+ kind: "extension",
114
+ name,
115
+ sections,
116
+ tools,
117
+ wraps,
118
+ });
119
+ };
120
+ exports.defineExtension = defineExtension;
121
+ /** The extensions named by `names`, in order. Throws for a name the registry lacks. */
122
+ const resolveExtensions = (extensions, names) => names.map((name) => {
123
+ const extension = extensions.get(name);
124
+ if (!extension) {
125
+ throw (0, errors_1.harnessError)({
126
+ detail: `Extension "${name}" is not in this harness registry`,
127
+ kind: "notRegistered",
128
+ });
129
+ }
130
+ return extension;
131
+ });
132
+ exports.resolveExtensions = resolveExtensions;
133
+ /**
134
+ * The tools a conversation can call, by name: the agent's tools, then each extension's
135
+ * in order (a later tool with the same name replaces an earlier one), then every wrap in
136
+ * extension order applied to the winning tool (the first extension's wrap is innermost).
137
+ */
138
+ const resolveTools = (agent, extensions) => {
139
+ const tools = new Map();
140
+ for (const tool of agent.tools) {
141
+ tools.set(tool.name, tool);
142
+ }
143
+ for (const extension of extensions) {
144
+ for (const tool of extension.tools) {
145
+ tools.set(tool.name, tool);
146
+ }
147
+ }
148
+ for (const extension of extensions) {
149
+ for (const { toolName, wrap } of extension.wraps) {
150
+ const winner = tools.get(toolName);
151
+ if (!winner) {
152
+ continue;
153
+ }
154
+ let wrapped;
155
+ try {
156
+ wrapped = wrap(winner);
157
+ }
158
+ catch (error) {
159
+ throw new HarnessExtensionError(extension.name, `wrap of tool "${toolName}"`, error);
160
+ }
161
+ if (wrapped?.kind !== "tool" || wrapped.name !== toolName) {
162
+ throw new definitionError_1.HarnessDefinitionError(`Extension "${extension.name}" wrap of tool "${toolName}" must return a defineTool tool named "${toolName}"`);
163
+ }
164
+ tools.set(toolName, wrapped);
165
+ }
166
+ }
167
+ return tools;
168
+ };
169
+ exports.resolveTools = resolveTools;
170
+ const hashText = (text) => (0, node_crypto_1.createHash)("sha256").update(text).digest("hex");
171
+ exports.hashText = hashText;
172
+ /** Agent instructions, then each non-empty section in extension and section order. */
173
+ const buildSystemPrompt = async ({ api, extensions, input, instructions, }) => {
174
+ const pieces = instructions ? [instructions] : [];
175
+ const sections = [];
176
+ for (const extension of extensions) {
177
+ for (const entry of extension.sections) {
178
+ let text;
179
+ try {
180
+ text = await entry.build(input, api);
181
+ }
182
+ catch (error) {
183
+ rethrowSuspend(error);
184
+ throw new HarnessExtensionError(extension.name, `section "${entry.name}"`, error);
185
+ }
186
+ if (text === undefined || text === null || !String(text).trim()) {
187
+ continue;
188
+ }
189
+ pieces.push(String(text));
190
+ sections.push({ extension: extension.name, name: entry.name });
191
+ }
192
+ }
193
+ const text = pieces.join("\n\n");
194
+ return { hash: (0, exports.hashText)(text), sections, text };
195
+ };
196
+ exports.buildSystemPrompt = buildSystemPrompt;
197
+ /** Hooks of `kind`, in extension order, each with the extension that declared it. */
198
+ const hooksOf = (extensions, kind) => extensions.flatMap((extension) => extension.hooks
199
+ .filter((entry) => entry.hook === kind)
200
+ .map((entry) => ({ extension: extension.name, run: entry.run })));
201
+ /** Run every `beforeModelRequest` hook in order; each sees the previous one's result. */
202
+ const runBeforeModelRequest = async ({ api, extensions, request, }) => {
203
+ let current = request;
204
+ const rewrittenBy = [];
205
+ for (const { extension, run } of hooksOf(extensions, harness_1.HARNESS_HOOK_KINDS.beforeModelRequest)) {
206
+ let next;
207
+ try {
208
+ next = await run(current, api);
209
+ }
210
+ catch (error) {
211
+ rethrowSuspend(error);
212
+ throw new HarnessExtensionError(extension, "beforeModelRequest hook", error);
213
+ }
214
+ if (next === undefined) {
215
+ continue;
216
+ }
217
+ if (typeof next?.system !== "string" || !Array.isArray(next.messages)) {
218
+ throw new definitionError_1.HarnessDefinitionError(`Extension "${extension}" beforeModelRequest hook must return {system, messages} or undefined`);
219
+ }
220
+ current = next;
221
+ rewrittenBy.push(extension);
222
+ }
223
+ return { request: current, rewrittenBy };
224
+ };
225
+ exports.runBeforeModelRequest = runBeforeModelRequest;
226
+ /**
227
+ * Run every `beforeTool` hook in order. The first `{block}` stops the rest. Each hook's
228
+ * `api.approval` resolves approvers from that hook's own extension. A hook waiting on an
229
+ * approval suspends the tool call (the suspend signal passes through untouched).
230
+ */
231
+ const runBeforeTool = async ({ api, approvalFor, call, extensions, }) => {
232
+ let { args } = call;
233
+ for (const { extension, run } of hooksOf(extensions, harness_1.HARNESS_HOOK_KINDS.beforeTool)) {
234
+ let decision;
235
+ try {
236
+ decision = await run({ ...call, args }, { ...api, approval: approvalFor(extension) });
237
+ }
238
+ catch (error) {
239
+ rethrowSuspend(error);
240
+ throw new HarnessExtensionError(extension, "beforeTool hook", error);
241
+ }
242
+ if (decision === undefined) {
243
+ continue;
244
+ }
245
+ if ("block" in decision) {
246
+ return { blocked: String(decision.block) };
247
+ }
248
+ if ("args" in decision) {
249
+ args = decision.args;
250
+ continue;
251
+ }
252
+ throw new definitionError_1.HarnessDefinitionError(`Extension "${extension}" beforeTool hook must return undefined, {block}, or {args}`);
253
+ }
254
+ return { args };
255
+ };
256
+ exports.runBeforeTool = runBeforeTool;
257
+ /** Run every `afterTool` hook in order; each sees the previous one's result. */
258
+ const runAfterTool = async ({ api, call, extensions, result, }) => {
259
+ let current = result;
260
+ for (const { extension, run } of hooksOf(extensions, harness_1.HARNESS_HOOK_KINDS.afterTool)) {
261
+ let next;
262
+ try {
263
+ next = await run(call, current, api);
264
+ }
265
+ catch (error) {
266
+ throw new HarnessExtensionError(extension, "afterTool hook", error);
267
+ }
268
+ if (next !== undefined) {
269
+ current = next;
270
+ }
271
+ }
272
+ return current;
273
+ };
274
+ exports.runAfterTool = runAfterTool;