@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,49 @@
1
+ import { APIError } from "@terreno/api";
2
+ import { type AskFileRef, type AskResponse, type AskValidationError } from "@terreno/blocks";
3
+ import type { ToolResultPart } from "ai";
4
+ import type mongoose from "mongoose";
5
+ import type { AskFileDownloader } from "../types";
6
+ type ToolResultOutput = ToolResultPart["output"];
7
+ type ContentOutput = Extract<ToolResultOutput, {
8
+ type: "content";
9
+ }>;
10
+ /** A file of a `files` answer with its bytes loaded and checked. */
11
+ export interface ResolvedAskFile {
12
+ bytes: Uint8Array;
13
+ fileId?: string;
14
+ filename: string;
15
+ mimeType: string;
16
+ }
17
+ /** The 400 the answer path returns when an answer does not fit its ask. */
18
+ export declare const invalidAskResponseError: (fields: AskValidationError[]) => APIError;
19
+ /**
20
+ * Loads the bytes of every file in an accepted `files` answer: a data URL is decoded, and a
21
+ * `fileId` must name an upload of the caller. Each file's bytes must fit the cap and match its
22
+ * declared type. Throws a 400 with every file's errors in `meta.fields`.
23
+ */
24
+ export declare const resolveAskFiles: ({ files, fileStorageService, maxFileSizeBytes, userId, }: {
25
+ files: AskFileRef[];
26
+ fileStorageService: AskFileDownloader | undefined;
27
+ maxFileSizeBytes: number;
28
+ userId: mongoose.Types.ObjectId | undefined;
29
+ }) => Promise<ResolvedAskFile[]>;
30
+ /**
31
+ * The answer the conversation stores, logs, and replays on later turns: each file's `fileId`,
32
+ * filename, type, and real size, without the bytes of a data URL.
33
+ */
34
+ export declare const storedFilesAnswer: (files: ResolvedAskFile[]) => AskResponse;
35
+ /**
36
+ * The tool result the model sees for an accepted `files` answer: the stored answer as JSON, then
37
+ * each file after a line that names it. Images become `image-data` parts, PDFs `file-data` parts,
38
+ * and text, CSV, and JSON files text parts of at most 100 KB.
39
+ */
40
+ export declare const askFilesModelOutput: (files: ResolvedAskFile[]) => ContentOutput;
41
+ /**
42
+ * `toModelOutput` for the `ask_files` tool, for hosts that replay its result themselves: an
43
+ * accepted answer shows each data URL's file, and names uploads without loading them. Other
44
+ * answers stay JSON. The chat routes load uploads first and call `askFilesModelOutput`.
45
+ */
46
+ export declare const askFilesToolModelOutput: ({ output }: {
47
+ output: AskResponse;
48
+ }) => ToolResultOutput;
49
+ export {};
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.askFilesToolModelOutput = exports.askFilesModelOutput = exports.storedFilesAnswer = exports.resolveAskFiles = exports.invalidAskResponseError = void 0;
4
+ const api_1 = require("@terreno/api");
5
+ const blocks_1 = require("@terreno/blocks");
6
+ const fileAttachment_1 = require("../models/fileAttachment");
7
+ const prompts_1 = require("./prompts");
8
+ const OBJECT_ID_PATTERN = /^[0-9a-f]{24}$/i;
9
+ /** The 400 the answer path returns when an answer does not fit its ask. */
10
+ const invalidAskResponseError = (fields) => new api_1.APIError({
11
+ detail: "The answer does not match the ask. See fields.",
12
+ meta: { fields },
13
+ status: 400,
14
+ title: "Invalid askResponse",
15
+ });
16
+ exports.invalidAskResponseError = invalidAskResponseError;
17
+ const decodeDataUrl = (url) => {
18
+ const parsed = (0, blocks_1.parseAskDataUrl)(url);
19
+ return parsed ? new Uint8Array(Buffer.from(parsed.base64, "base64")) : undefined;
20
+ };
21
+ /** The bytes of the caller's own upload, or undefined when it is not theirs or cannot be loaded. */
22
+ const loadUpload = async ({ fileId, fileStorageService, userId, }) => {
23
+ if (!fileStorageService || !userId || !OBJECT_ID_PATTERN.test(fileId)) {
24
+ return undefined;
25
+ }
26
+ const attachment = await fileAttachment_1.FileAttachment.findOneOrNone({ _id: fileId, deleted: false, userId });
27
+ if (!attachment) {
28
+ return undefined;
29
+ }
30
+ try {
31
+ return new Uint8Array(await fileStorageService.download(attachment.gcsKey));
32
+ }
33
+ catch (error) {
34
+ api_1.logger.warn("Could not download an upload sent as an ask answer", {
35
+ error: error instanceof Error ? error.message : String(error),
36
+ fileId,
37
+ });
38
+ return undefined;
39
+ }
40
+ };
41
+ /**
42
+ * Loads the bytes of every file in an accepted `files` answer: a data URL is decoded, and a
43
+ * `fileId` must name an upload of the caller. Each file's bytes must fit the cap and match its
44
+ * declared type. Throws a 400 with every file's errors in `meta.fields`.
45
+ */
46
+ const resolveAskFiles = async ({ files, fileStorageService, maxFileSizeBytes, userId, }) => {
47
+ const loaded = await Promise.all(files.map(async (file, index) => {
48
+ const bytes = file.url !== undefined
49
+ ? decodeDataUrl(file.url)
50
+ : await loadUpload({ fileId: file.fileId ?? "", fileStorageService, userId });
51
+ if (!bytes) {
52
+ return { errors: [(0, blocks_1.fileNotOwnedError)({ index })] };
53
+ }
54
+ const resolved = {
55
+ bytes,
56
+ filename: file.filename,
57
+ mimeType: file.mimeType,
58
+ ...(file.fileId === undefined ? {} : { fileId: file.fileId }),
59
+ };
60
+ return {
61
+ errors: (0, blocks_1.checkAskFileBytes)({ bytes, index, maxFileSizeBytes, mimeType: file.mimeType }),
62
+ resolved,
63
+ };
64
+ }));
65
+ const errors = loaded.flatMap((result) => result.errors);
66
+ if (errors.length > 0) {
67
+ throw (0, exports.invalidAskResponseError)(errors);
68
+ }
69
+ return loaded.flatMap((result) => (result.resolved ? [result.resolved] : []));
70
+ };
71
+ exports.resolveAskFiles = resolveAskFiles;
72
+ const storedFile = ({ bytes, fileId, filename, mimeType }) => ({
73
+ ...(fileId === undefined ? {} : { fileId }),
74
+ filename,
75
+ mimeType,
76
+ size: bytes.length,
77
+ });
78
+ /**
79
+ * The answer the conversation stores, logs, and replays on later turns: each file's `fileId`,
80
+ * filename, type, and real size, without the bytes of a data URL.
81
+ */
82
+ const storedFilesAnswer = (files) => ({
83
+ action: "accept",
84
+ content: { files: files.map(storedFile) },
85
+ });
86
+ exports.storedFilesAnswer = storedFilesAnswer;
87
+ const decodeText = (bytes) => new TextDecoder("utf-8").decode(bytes);
88
+ /** The text parts of a text-like file: its text cut to 100 KB on a character boundary, and a note. */
89
+ const textParts = (bytes) => {
90
+ const { textMaxBytes } = blocks_1.ASK_LIMITS.files;
91
+ if (bytes.length <= textMaxBytes) {
92
+ return [{ text: decodeText(bytes), type: "text" }];
93
+ }
94
+ let end = textMaxBytes;
95
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80) {
96
+ end -= 1;
97
+ }
98
+ return [
99
+ { text: decodeText(bytes.subarray(0, end)), type: "text" },
100
+ { text: (0, prompts_1.truncatedAskFileNote)({ keptBytes: end, totalBytes: bytes.length }), type: "text" },
101
+ ];
102
+ };
103
+ const fileParts = (file) => {
104
+ const data = Buffer.from(file.bytes).toString("base64");
105
+ if (file.mimeType.startsWith("image/")) {
106
+ return [{ data, mediaType: file.mimeType, type: "image-data" }];
107
+ }
108
+ if (!(0, blocks_1.isTextFileMimeType)(file.mimeType)) {
109
+ return [{ data, filename: file.filename, mediaType: file.mimeType, type: "file-data" }];
110
+ }
111
+ return textParts(file.bytes);
112
+ };
113
+ /**
114
+ * The tool result the model sees for an accepted `files` answer: the stored answer as JSON, then
115
+ * each file after a line that names it. Images become `image-data` parts, PDFs `file-data` parts,
116
+ * and text, CSV, and JSON files text parts of at most 100 KB.
117
+ */
118
+ const askFilesModelOutput = (files) => ({
119
+ type: "content",
120
+ value: [
121
+ { text: JSON.stringify((0, exports.storedFilesAnswer)(files)), type: "text" },
122
+ ...files.flatMap((file, index) => [
123
+ {
124
+ text: (0, prompts_1.askFileHeading)({
125
+ count: files.length,
126
+ filename: file.filename,
127
+ mimeType: file.mimeType,
128
+ position: index + 1,
129
+ size: file.bytes.length,
130
+ }),
131
+ type: "text",
132
+ },
133
+ ...fileParts(file),
134
+ ]),
135
+ ],
136
+ });
137
+ exports.askFilesModelOutput = askFilesModelOutput;
138
+ /**
139
+ * `toModelOutput` for the `ask_files` tool, for hosts that replay its result themselves: an
140
+ * accepted answer shows each data URL's file, and names uploads without loading them. Other
141
+ * answers stay JSON. The chat routes load uploads first and call `askFilesModelOutput`.
142
+ */
143
+ const askFilesToolModelOutput = ({ output }) => {
144
+ if (output.action !== "accept") {
145
+ return { type: "json", value: output };
146
+ }
147
+ const refs = output.content.files ?? [];
148
+ const inline = refs.flatMap((ref) => {
149
+ const bytes = ref.url === undefined ? undefined : decodeDataUrl(ref.url);
150
+ return bytes ? [{ bytes, filename: ref.filename, mimeType: ref.mimeType }] : [];
151
+ });
152
+ const uploads = refs.filter((ref) => ref.url === undefined);
153
+ const { value } = (0, exports.askFilesModelOutput)(inline);
154
+ if (uploads.length === 0) {
155
+ return { type: "content", value };
156
+ }
157
+ return {
158
+ type: "content",
159
+ value: [...value, { text: (0, prompts_1.unloadedAskUploadsNote)(uploads), type: "text" }],
160
+ };
161
+ };
162
+ exports.askFilesToolModelOutput = askFilesToolModelOutput;
@@ -0,0 +1,76 @@
1
+ import { type Ask, type AskKind, type AskResponse, type AskSurface, type ConfirmAskInput } from "@terreno/blocks";
2
+ import { type ModelMessage, type Tool, type ToolResultPart } from "ai";
3
+ import type { AsksOptions } from "../types";
4
+ /** The per-file cap for `files` answers: `asks.maxFileSizeBytes`, or 10 MB. */
5
+ export declare const resolveMaxFileSizeBytes: (asks: boolean | AsksOptions | undefined) => number;
6
+ /** The kinds the `asks` route option enables; empty when asks are off. Throws on unknown kinds. */
7
+ export declare const resolveAskKinds: (asks: boolean | AsksOptions | undefined) => AskKind[];
8
+ export declare const askToolName: (kind: AskKind) => string;
9
+ /** The ask kind a tool name calls, or undefined when it is not one of the given kinds' tools. */
10
+ export declare const askKindFromToolName: (toolName: string, kinds?: readonly AskKind[]) => AskKind | undefined;
11
+ /**
12
+ * One tool per enabled kind the surface offers. Ask tools have no `execute`, so the AI SDK ends
13
+ * the step loop when the model calls one and the turn pauses until the user answers. On the
14
+ * compact surface each tool takes the kind's compact input schema, so an ask whose options do not
15
+ * fit a small screen's buttons goes back to the model as a tool error.
16
+ */
17
+ export declare const createAskTools: ({ kinds, surface, }: {
18
+ kinds: readonly AskKind[];
19
+ surface?: AskSurface;
20
+ }) => Record<string, Tool>;
21
+ /** Types the input of a valid ask call. The AI SDK has already checked it against the kind's schema. */
22
+ export declare const parseAsk: ({ input, kind }: {
23
+ input: unknown;
24
+ kind: AskKind;
25
+ }) => Ask;
26
+ /** Throws when a host tool name uses the `ask_` prefix that ask tools own. */
27
+ export declare const assertNoReservedToolNames: (tools: Record<string, Tool> | undefined) => void;
28
+ /** Drops tools resolved per request (request tools, MCP tools) whose names use the `ask_` prefix. */
29
+ export declare const withoutReservedToolNames: (tools: Record<string, Tool>) => Record<string, Tool>;
30
+ /** The asks section of the system prompt for the kinds offered on the surface. */
31
+ export declare const buildAsksSystemPrompt: ({ kinds, surface, }: {
32
+ kinds: readonly AskKind[];
33
+ surface?: AskSurface;
34
+ }) => string;
35
+ /**
36
+ * A plain JSON copy of AI SDK messages. It drops `undefined` fields, which MongoDB would store as
37
+ * null and the AI SDK would then reject when the messages are replayed. Tool results leave out
38
+ * `fileData`, as the stored rows do, so a generated file is not stored twice.
39
+ */
40
+ export declare const toStoredMessages: (messages: ModelMessage[]) => ModelMessage[];
41
+ /**
42
+ * The `confirm` input of the approval ask for one host tool call: the host's
43
+ * `asks.approvals[toolName]`, or the default when it has none, throws, or returns an input that
44
+ * is not a valid `confirm` input.
45
+ */
46
+ export declare const approvalAskInput: ({ asks, description, input, surface, toolName, }: {
47
+ asks: boolean | AsksOptions | undefined;
48
+ description?: string;
49
+ input: unknown;
50
+ surface: AskSurface;
51
+ toolName: string;
52
+ }) => ConfirmAskInput;
53
+ /**
54
+ * The reason each denied approval in the messages' last tool message gives, by the tool call it
55
+ * denied, so the turn can show why a tool did not run.
56
+ */
57
+ export declare const deniedApprovalReasons: (messages: ModelMessage[]) => Map<string, string | undefined>;
58
+ /**
59
+ * The paused turn's messages plus a result for every tool call its last step left without one:
60
+ * the user's answer for the pending ask, `cancel` for asks dropped because the model asked more
61
+ * than once, and an error for any other tool that did not run. A call waiting on approval gets a
62
+ * `tool-approval-response` instead of a result, so the AI SDK runs or denies it when the turn
63
+ * resumes: the user's answer decides the pending approval, `approvalId`, and every other
64
+ * approval in the step is denied with `one_ask_at_a_time`. The
65
+ * parts join the step's tool message, results in call order, so providers see one tool message
66
+ * per assistant message. `answerOutput` replaces the answer's JSON result, such as a `files`
67
+ * answer with its files.
68
+ */
69
+ export declare const completePausedTurn: ({ answer, answerOutput, approvalId, responseMessages, toolCallId, }: {
70
+ answer: AskResponse;
71
+ answerOutput?: ToolResultPart["output"];
72
+ /** Set when the pending ask is an approval: the approval request the answer decides. */
73
+ approvalId?: string;
74
+ responseMessages: ModelMessage[];
75
+ toolCallId: string;
76
+ }) => ModelMessage[];
@@ -0,0 +1,284 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.completePausedTurn = exports.deniedApprovalReasons = exports.approvalAskInput = exports.toStoredMessages = exports.buildAsksSystemPrompt = exports.withoutReservedToolNames = exports.assertNoReservedToolNames = exports.parseAsk = exports.createAskTools = exports.askKindFromToolName = exports.askToolName = exports.resolveAskKinds = exports.resolveMaxFileSizeBytes = void 0;
4
+ const api_1 = require("@terreno/api");
5
+ const blocks_1 = require("@terreno/blocks");
6
+ const ai_1 = require("ai");
7
+ const askFiles_1 = require("./askFiles");
8
+ const prompts_1 = require("./prompts");
9
+ const ASK_TOOL_PREFIX = "ask_";
10
+ const ASK_TOOL_DESCRIPTIONS = {
11
+ choice: prompts_1.ASK_CHOICE_TOOL_DESCRIPTION,
12
+ confirm: prompts_1.ASK_CONFIRM_TOOL_DESCRIPTION,
13
+ files: prompts_1.ASK_FILES_TOOL_DESCRIPTION,
14
+ form: prompts_1.ASK_FORM_TOOL_DESCRIPTION,
15
+ markdown: prompts_1.ASK_MARKDOWN_TOOL_DESCRIPTION,
16
+ };
17
+ const COMPACT_ASK_TOOL_DESCRIPTIONS = {
18
+ choice: prompts_1.COMPACT_ASK_CHOICE_TOOL_DESCRIPTION,
19
+ confirm: prompts_1.COMPACT_ASK_CONFIRM_TOOL_DESCRIPTION,
20
+ };
21
+ const askToolDescription = ({ kind, surface }) => surface === "compact" && (0, blocks_1.isCompactAskKind)(kind)
22
+ ? COMPACT_ASK_TOOL_DESCRIPTIONS[kind]
23
+ : ASK_TOOL_DESCRIPTIONS[kind];
24
+ /** The per-file cap for `files` answers: `asks.maxFileSizeBytes`, or 10 MB. */
25
+ const resolveMaxFileSizeBytes = (asks) => (typeof asks === "object" ? asks.maxFileSizeBytes : undefined) ??
26
+ blocks_1.ASK_LIMITS.files.defaultMaxFileSizeBytes;
27
+ exports.resolveMaxFileSizeBytes = resolveMaxFileSizeBytes;
28
+ /** The kinds the `asks` route option enables; empty when asks are off. Throws on unknown kinds. */
29
+ const resolveAskKinds = (asks) => {
30
+ if (!asks) {
31
+ return [];
32
+ }
33
+ const kinds = asks === true ? blocks_1.ASK_KINDS : (asks.kinds ?? blocks_1.ASK_KINDS);
34
+ const unknownKinds = kinds.filter((kind) => !blocks_1.ASK_KINDS.includes(kind));
35
+ if (unknownKinds.length > 0) {
36
+ throw new api_1.APIError({
37
+ detail: `Unknown ask kinds: ${unknownKinds.join(", ")}. Known kinds: ${blocks_1.ASK_KINDS.join(", ")}.`,
38
+ status: 500,
39
+ title: "The asks option lists unknown ask kinds",
40
+ });
41
+ }
42
+ return [...new Set(kinds)];
43
+ };
44
+ exports.resolveAskKinds = resolveAskKinds;
45
+ const askToolName = (kind) => `${ASK_TOOL_PREFIX}${kind}`;
46
+ exports.askToolName = askToolName;
47
+ /** The ask kind a tool name calls, or undefined when it is not one of the given kinds' tools. */
48
+ const askKindFromToolName = (toolName, kinds = blocks_1.ASK_KINDS) => kinds.find((kind) => (0, exports.askToolName)(kind) === toolName);
49
+ exports.askKindFromToolName = askKindFromToolName;
50
+ /**
51
+ * One tool per enabled kind the surface offers. Ask tools have no `execute`, so the AI SDK ends
52
+ * the step loop when the model calls one and the turn pauses until the user answers. On the
53
+ * compact surface each tool takes the kind's compact input schema, so an ask whose options do not
54
+ * fit a small screen's buttons goes back to the model as a tool error.
55
+ */
56
+ const createAskTools = ({ kinds, surface = "full", }) => Object.fromEntries((0, blocks_1.askKindsForSurface)({ kinds, surface }).map((kind) => [
57
+ (0, exports.askToolName)(kind),
58
+ (0, ai_1.tool)({
59
+ description: askToolDescription({ kind, surface }),
60
+ inputSchema: (0, blocks_1.askInputSchemaFor)({ kind, surface }),
61
+ outputSchema: blocks_1.askOutputSchemas[kind],
62
+ ...(kind === "files" ? { toModelOutput: askFiles_1.askFilesToolModelOutput } : {}),
63
+ }),
64
+ ]));
65
+ exports.createAskTools = createAskTools;
66
+ /** Types the input of a valid ask call. The AI SDK has already checked it against the kind's schema. */
67
+ const parseAsk = ({ input, kind }) => ({ input: blocks_1.askInputSchemas[kind].parse(input), kind });
68
+ exports.parseAsk = parseAsk;
69
+ const reservedToolNames = (tools) => Object.keys(tools).filter((name) => name.startsWith(ASK_TOOL_PREFIX));
70
+ /** Throws when a host tool name uses the `ask_` prefix that ask tools own. */
71
+ const assertNoReservedToolNames = (tools) => {
72
+ const reserved = reservedToolNames(tools ?? {});
73
+ if (reserved.length > 0) {
74
+ throw new api_1.APIError({
75
+ detail: `Tool names starting with "${ASK_TOOL_PREFIX}" are reserved for asks: ${reserved.join(", ")}.`,
76
+ status: 500,
77
+ title: "Host tool names use the prefix reserved for asks",
78
+ });
79
+ }
80
+ };
81
+ exports.assertNoReservedToolNames = assertNoReservedToolNames;
82
+ /** Drops tools resolved per request (request tools, MCP tools) whose names use the `ask_` prefix. */
83
+ const withoutReservedToolNames = (tools) => {
84
+ const reserved = reservedToolNames(tools);
85
+ if (reserved.length === 0) {
86
+ return tools;
87
+ }
88
+ api_1.logger.warn("Dropping tools whose names are reserved for asks", { tools: reserved });
89
+ return Object.fromEntries(Object.entries(tools).filter(([name]) => !name.startsWith(ASK_TOOL_PREFIX)));
90
+ };
91
+ exports.withoutReservedToolNames = withoutReservedToolNames;
92
+ /** The asks section of the system prompt for the kinds offered on the surface. */
93
+ const buildAsksSystemPrompt = ({ kinds, surface = "full", }) => `${prompts_1.TERRENO_ASKS_SYSTEM_PROMPT}\n\n${(0, blocks_1.askPromptSection)({ kinds, surface })}`;
94
+ exports.buildAsksSystemPrompt = buildAsksSystemPrompt;
95
+ /** A tool result part without the `fileData` a host tool returns for the client to download. */
96
+ const withoutFileData = (part) => {
97
+ const output = part.output;
98
+ const value = output?.type === "json" ? output.value : undefined;
99
+ if (typeof value !== "object" || value === null || !("fileData" in value)) {
100
+ return part;
101
+ }
102
+ const { fileData: _fileData, ...rest } = value;
103
+ return { ...part, output: { ...output, value: rest } };
104
+ };
105
+ /**
106
+ * A plain JSON copy of AI SDK messages. It drops `undefined` fields, which MongoDB would store as
107
+ * null and the AI SDK would then reject when the messages are replayed. Tool results leave out
108
+ * `fileData`, as the stored rows do, so a generated file is not stored twice.
109
+ */
110
+ const toStoredMessages = (messages) => JSON.parse(JSON.stringify(messages)).map((message) => message.role === "tool"
111
+ ? { ...message, content: message.content.map(withoutFileData) }
112
+ : message);
113
+ exports.toStoredMessages = toStoredMessages;
114
+ /** Why an approval was denied, as the model sees it in the tool's `execution-denied` result. */
115
+ const APPROVAL_DENIAL_REASONS = {
116
+ cancelled: "user_cancelled",
117
+ declined: "user_declined",
118
+ denied: "user_denied",
119
+ };
120
+ const truncate = (text, maxLength) => text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
121
+ /** "Allow <toolName>?" with the tool's description, and Allow / Deny buttons. */
122
+ const defaultApprovalAskInput = ({ description, toolName, }) => {
123
+ const question = `Allow ${toolName}?`;
124
+ const detail = description?.trim();
125
+ return {
126
+ confirmLabel: "Allow",
127
+ denyLabel: "Deny",
128
+ prompt: truncate(detail ? `${question} ${detail}` : question, blocks_1.ASK_LIMITS.promptMaxLength),
129
+ };
130
+ };
131
+ /**
132
+ * The `confirm` input of the approval ask for one host tool call: the host's
133
+ * `asks.approvals[toolName]`, or the default when it has none, throws, or returns an input that
134
+ * is not a valid `confirm` input.
135
+ */
136
+ const approvalAskInput = ({ asks, description, input, surface, toolName, }) => {
137
+ const fallback = defaultApprovalAskInput({ description, toolName });
138
+ const approval = typeof asks === "object" ? asks.approvals?.[toolName] : undefined;
139
+ if (!approval) {
140
+ return fallback;
141
+ }
142
+ try {
143
+ const parsed = (0, blocks_1.askInputSchemaFor)({ kind: "confirm", surface }).safeParse(approval(input));
144
+ if (parsed.success) {
145
+ return parsed.data;
146
+ }
147
+ api_1.logger.warn("asks.approvals returned an invalid confirm input; using the default approval", {
148
+ issues: parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`),
149
+ toolName,
150
+ });
151
+ }
152
+ catch (error) {
153
+ api_1.logger.warn("asks.approvals threw; using the default approval", {
154
+ error: error instanceof Error ? error.message : String(error),
155
+ toolName,
156
+ });
157
+ }
158
+ return fallback;
159
+ };
160
+ exports.approvalAskInput = approvalAskInput;
161
+ /** The approval an answer to an approval ask gives: only an accepted `{confirmed: true}` approves. */
162
+ const approvalResponseOf = (answer) => {
163
+ if (answer.action === "accept") {
164
+ return answer.content.confirmed
165
+ ? { approved: true }
166
+ : { approved: false, reason: APPROVAL_DENIAL_REASONS.denied };
167
+ }
168
+ if (answer.action === "decline") {
169
+ return { approved: false, reason: APPROVAL_DENIAL_REASONS.declined };
170
+ }
171
+ return { approved: false, reason: answer.reason ?? APPROVAL_DENIAL_REASONS.cancelled };
172
+ };
173
+ /**
174
+ * The reason each denied approval in the messages' last tool message gives, by the tool call it
175
+ * denied, so the turn can show why a tool did not run.
176
+ */
177
+ const deniedApprovalReasons = (messages) => {
178
+ const lastMessage = messages.at(-1);
179
+ if (lastMessage?.role !== "tool") {
180
+ return new Map();
181
+ }
182
+ const toolCallIds = new Map();
183
+ for (const message of messages) {
184
+ if (message.role !== "assistant" || typeof message.content === "string") {
185
+ continue;
186
+ }
187
+ for (const part of message.content) {
188
+ if (part.type === "tool-approval-request") {
189
+ toolCallIds.set(part.approvalId, part.toolCallId);
190
+ }
191
+ }
192
+ }
193
+ return new Map(lastMessage.content.flatMap((part) => {
194
+ const toolCallId = part.type === "tool-approval-response" && !part.approved
195
+ ? toolCallIds.get(part.approvalId)
196
+ : undefined;
197
+ return toolCallId && part.type === "tool-approval-response"
198
+ ? [[toolCallId, part.reason]]
199
+ : [];
200
+ }));
201
+ };
202
+ exports.deniedApprovalReasons = deniedApprovalReasons;
203
+ const outputForUnansweredCall = ({ answer, answerOutput, call, toolCallId, }) => {
204
+ if (call.toolCallId === toolCallId) {
205
+ return answerOutput ?? { type: "json", value: answer };
206
+ }
207
+ if ((0, exports.askKindFromToolName)(call.toolName)) {
208
+ return { type: "json", value: { action: "cancel", reason: blocks_1.ASK_CANCEL_REASONS.oneAskAtATime } };
209
+ }
210
+ return { type: "error-text", value: prompts_1.UNANSWERED_TOOL_CALL_RESULT };
211
+ };
212
+ /**
213
+ * The paused turn's messages plus a result for every tool call its last step left without one:
214
+ * the user's answer for the pending ask, `cancel` for asks dropped because the model asked more
215
+ * than once, and an error for any other tool that did not run. A call waiting on approval gets a
216
+ * `tool-approval-response` instead of a result, so the AI SDK runs or denies it when the turn
217
+ * resumes: the user's answer decides the pending approval, `approvalId`, and every other
218
+ * approval in the step is denied with `one_ask_at_a_time`. The
219
+ * parts join the step's tool message, results in call order, so providers see one tool message
220
+ * per assistant message. `answerOutput` replaces the answer's JSON result, such as a `files`
221
+ * answer with its files.
222
+ */
223
+ const completePausedTurn = ({ answer, answerOutput, approvalId, responseMessages, toolCallId, }) => {
224
+ const answeredIds = new Set();
225
+ const respondedApprovalIds = new Set();
226
+ for (const message of responseMessages) {
227
+ if (typeof message.content === "string" || message.role === "system") {
228
+ continue;
229
+ }
230
+ for (const part of message.content) {
231
+ if (part.type === "tool-result") {
232
+ answeredIds.add(part.toolCallId);
233
+ }
234
+ else if (part.type === "tool-approval-response") {
235
+ respondedApprovalIds.add(part.approvalId);
236
+ }
237
+ }
238
+ }
239
+ const lastAssistant = responseMessages.findLast((message) => message.role === "assistant");
240
+ const stepParts = lastAssistant && typeof lastAssistant.content !== "string" ? lastAssistant.content : [];
241
+ const stepApprovalRequests = stepParts.filter((part) => part.type === "tool-approval-request");
242
+ const awaitingApprovalIds = new Set(stepApprovalRequests.map((request) => request.toolCallId));
243
+ const approvalRequests = stepApprovalRequests.filter((request) => !respondedApprovalIds.has(request.approvalId));
244
+ const stepCalls = stepParts.filter((part) => part.type === "tool-call" && !part.providerExecuted);
245
+ const newResults = stepCalls
246
+ .filter((call) => !answeredIds.has(call.toolCallId) && !awaitingApprovalIds.has(call.toolCallId))
247
+ .map((call) => ({
248
+ output: outputForUnansweredCall({ answer, answerOutput, call, toolCallId }),
249
+ toolCallId: call.toolCallId,
250
+ toolName: call.toolName,
251
+ type: "tool-result",
252
+ }));
253
+ const approvalResponses = approvalRequests.map((request) => ({
254
+ approvalId: request.approvalId,
255
+ type: "tool-approval-response",
256
+ ...(approvalId !== undefined && request.approvalId === approvalId
257
+ ? approvalResponseOf(answer)
258
+ : { approved: false, reason: blocks_1.ASK_CANCEL_REASONS.oneAskAtATime }),
259
+ }));
260
+ if (newResults.length === 0 && approvalResponses.length === 0) {
261
+ return responseMessages;
262
+ }
263
+ const callOrder = new Map(stepCalls.map((call, index) => [call.toolCallId, index]));
264
+ const byCallOrder = (a, b) => (callOrder.get(a.toolCallId) ?? callOrder.size) -
265
+ (callOrder.get(b.toolCallId) ?? callOrder.size);
266
+ const lastMessage = responseMessages.at(-1);
267
+ if (lastMessage?.role === "tool") {
268
+ const existingResults = lastMessage.content.filter((part) => part.type === "tool-result");
269
+ const otherParts = lastMessage.content.filter((part) => part.type !== "tool-result");
270
+ return [
271
+ ...responseMessages.slice(0, -1),
272
+ {
273
+ ...lastMessage,
274
+ content: [
275
+ ...[...existingResults, ...newResults].sort(byCallOrder),
276
+ ...otherParts,
277
+ ...approvalResponses,
278
+ ],
279
+ },
280
+ ];
281
+ }
282
+ return [...responseMessages, { content: [...newResults, ...approvalResponses], role: "tool" }];
283
+ };
284
+ exports.completePausedTurn = completePausedTurn;