@terreno/ai 57.8.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 (425) hide show
  1. package/.cursorrules +2 -2
  2. package/README.md +2 -1
  3. package/bunfig.toml +1 -1
  4. package/dist/aiApp.d.ts +16 -5
  5. package/dist/aiApp.js +17 -7
  6. package/dist/harness/adminScreens.d.ts +6 -0
  7. package/dist/harness/adminScreens.js +11 -0
  8. package/dist/harness/agentLoop.d.ts +61 -0
  9. package/dist/harness/agentLoop.js +798 -0
  10. package/dist/harness/agentTaskNames.d.ts +4 -0
  11. package/dist/harness/agentTaskNames.js +7 -0
  12. package/dist/harness/approvalPolicy.d.ts +3 -0
  13. package/dist/harness/approvalPolicy.js +23 -0
  14. package/dist/harness/approvals.d.ts +101 -0
  15. package/dist/harness/approvals.js +468 -0
  16. package/dist/harness/commit.d.ts +238 -0
  17. package/dist/harness/commit.js +678 -0
  18. package/dist/harness/conversation.d.ts +75 -0
  19. package/dist/harness/conversation.js +397 -0
  20. package/dist/harness/defineAgent.d.ts +9 -0
  21. package/dist/harness/defineAgent.js +65 -0
  22. package/dist/harness/defineTask.d.ts +11 -0
  23. package/dist/harness/defineTask.js +59 -0
  24. package/dist/harness/defineTool.d.ts +7 -0
  25. package/dist/harness/defineTool.js +36 -0
  26. package/dist/harness/definitionError.d.ts +8 -0
  27. package/dist/harness/definitionError.js +15 -0
  28. package/dist/harness/errors.d.ts +127 -0
  29. package/dist/harness/errors.js +101 -0
  30. package/dist/harness/eventHub.d.ts +45 -0
  31. package/dist/harness/eventHub.js +135 -0
  32. package/dist/harness/events.d.ts +95 -0
  33. package/dist/harness/events.js +267 -0
  34. package/dist/harness/executionEnv.d.ts +31 -0
  35. package/dist/harness/executionEnv.js +2 -0
  36. package/dist/harness/extensions.d.ts +82 -0
  37. package/dist/harness/extensions.js +274 -0
  38. package/dist/harness/harness.d.ts +163 -0
  39. package/dist/harness/harness.js +520 -0
  40. package/dist/harness/harnessApp.d.ts +44 -0
  41. package/dist/harness/harnessApp.js +62 -0
  42. package/dist/harness/internalRuntime.d.ts +16 -0
  43. package/dist/harness/internalRuntime.js +18 -0
  44. package/dist/harness/leases.d.ts +35 -0
  45. package/dist/harness/leases.js +86 -0
  46. package/dist/harness/memo.d.ts +24 -0
  47. package/dist/harness/memo.js +78 -0
  48. package/dist/harness/modelCall.d.ts +45 -0
  49. package/dist/harness/modelCall.js +147 -0
  50. package/dist/harness/models/harnessApproval.d.ts +2 -0
  51. package/dist/harness/models/harnessApproval.js +100 -0
  52. package/dist/harness/models/harnessConversation.d.ts +2 -0
  53. package/dist/harness/models/harnessConversation.js +117 -0
  54. package/dist/harness/models/harnessEvent.d.ts +3 -0
  55. package/dist/harness/models/harnessEvent.js +73 -0
  56. package/dist/harness/models/harnessInboxEvent.d.ts +2 -0
  57. package/dist/harness/models/harnessInboxEvent.js +58 -0
  58. package/dist/harness/models/harnessMemo.d.ts +2 -0
  59. package/dist/harness/models/harnessMemo.js +42 -0
  60. package/dist/harness/models/harnessMessage.d.ts +2 -0
  61. package/dist/harness/models/harnessMessage.js +73 -0
  62. package/dist/harness/models/harnessOwner.d.ts +2 -0
  63. package/dist/harness/models/harnessOwner.js +36 -0
  64. package/dist/harness/models/harnessTask.d.ts +2 -0
  65. package/dist/harness/models/harnessTask.js +186 -0
  66. package/dist/harness/ownership.d.ts +89 -0
  67. package/dist/harness/ownership.js +438 -0
  68. package/dist/harness/registry.d.ts +29 -0
  69. package/dist/harness/registry.js +93 -0
  70. package/dist/harness/retryBackoff.d.ts +31 -0
  71. package/dist/harness/retryBackoff.js +50 -0
  72. package/dist/harness/routes/approvals.d.ts +13 -0
  73. package/dist/harness/routes/approvals.js +93 -0
  74. package/dist/harness/routes/conversations.d.ts +11 -0
  75. package/dist/harness/routes/conversations.js +66 -0
  76. package/dist/harness/routes/events.d.ts +19 -0
  77. package/dist/harness/routes/events.js +215 -0
  78. package/dist/harness/routes/tasks.d.ts +11 -0
  79. package/dist/harness/routes/tasks.js +108 -0
  80. package/dist/harness/runners/inProcessRunner.d.ts +57 -0
  81. package/dist/harness/runners/inProcessRunner.js +196 -0
  82. package/dist/harness/runtime.d.ts +34 -0
  83. package/dist/harness/runtime.js +551 -0
  84. package/dist/harness/subagent.d.ts +53 -0
  85. package/dist/harness/subagent.js +134 -0
  86. package/dist/harness/suspend.d.ts +8 -0
  87. package/dist/harness/suspend.js +16 -0
  88. package/dist/harness/transaction.d.ts +3 -0
  89. package/dist/harness/transaction.js +22 -0
  90. package/dist/harness/waits.d.ts +100 -0
  91. package/dist/harness/waits.js +214 -0
  92. package/dist/index.d.ts +19 -1
  93. package/dist/index.js +45 -2
  94. package/dist/models/aiDataset.d.ts +2 -0
  95. package/dist/models/aiDataset.js +67 -0
  96. package/dist/models/aiRequest.js +1 -1
  97. package/dist/models/gptHistory.js +88 -2
  98. package/dist/observability/adminScreens.d.ts +5 -0
  99. package/dist/observability/adminScreens.js +32 -0
  100. package/dist/observability/compileTemplate.d.ts +1 -0
  101. package/dist/observability/compileTemplate.js +13 -0
  102. package/dist/observability/datasetImport.d.ts +11 -0
  103. package/dist/observability/datasetImport.js +185 -0
  104. package/dist/observability/evaluate.d.ts +31 -0
  105. package/dist/observability/evaluate.js +200 -0
  106. package/dist/observability/evaluatorTemplates.d.ts +17 -0
  107. package/dist/observability/evaluatorTemplates.js +111 -0
  108. package/dist/observability/jsonPath.d.ts +2 -0
  109. package/dist/observability/jsonPath.js +57 -0
  110. package/dist/observability/local/datasetStore.d.ts +87 -0
  111. package/dist/observability/local/datasetStore.js +326 -0
  112. package/dist/observability/local/evaluatorStore.d.ts +44 -0
  113. package/dist/observability/local/evaluatorStore.js +182 -0
  114. package/dist/observability/local/experimentRunner.d.ts +96 -0
  115. package/dist/observability/local/experimentRunner.js +419 -0
  116. package/dist/observability/local/localPlugin.d.ts +22 -0
  117. package/dist/observability/local/localPlugin.js +76 -0
  118. package/dist/observability/local/models/obsDataset.d.ts +2 -0
  119. package/dist/observability/local/models/obsDataset.js +37 -0
  120. package/dist/observability/local/models/obsDatasetItem.d.ts +2 -0
  121. package/dist/observability/local/models/obsDatasetItem.js +76 -0
  122. package/dist/observability/local/models/obsEvaluator.d.ts +2 -0
  123. package/dist/observability/local/models/obsEvaluator.js +98 -0
  124. package/dist/observability/local/models/obsExperiment.d.ts +2 -0
  125. package/dist/observability/local/models/obsExperiment.js +87 -0
  126. package/dist/observability/local/models/obsExperimentItem.d.ts +2 -0
  127. package/dist/observability/local/models/obsExperimentItem.js +45 -0
  128. package/dist/observability/local/models/obsPrompt.d.ts +2 -0
  129. package/dist/observability/local/models/obsPrompt.js +42 -0
  130. package/dist/observability/local/models/obsPromptLabel.d.ts +2 -0
  131. package/dist/observability/local/models/obsPromptLabel.js +39 -0
  132. package/dist/observability/local/models/obsPromptVersion.d.ts +2 -0
  133. package/dist/observability/local/models/obsPromptVersion.js +96 -0
  134. package/dist/observability/local/models/obsReviewItem.d.ts +2 -0
  135. package/dist/observability/local/models/obsReviewItem.js +75 -0
  136. package/dist/observability/local/models/obsScore.d.ts +2 -0
  137. package/dist/observability/local/models/obsScore.js +58 -0
  138. package/dist/observability/local/models/obsSpan.d.ts +2 -0
  139. package/dist/observability/local/models/obsSpan.js +64 -0
  140. package/dist/observability/local/models/obsTrace.d.ts +2 -0
  141. package/dist/observability/local/models/obsTrace.js +93 -0
  142. package/dist/observability/local/promptStore.d.ts +180 -0
  143. package/dist/observability/local/promptStore.js +444 -0
  144. package/dist/observability/local/reviewStore.d.ts +50 -0
  145. package/dist/observability/local/reviewStore.js +203 -0
  146. package/dist/observability/local/traceStore.d.ts +103 -0
  147. package/dist/observability/local/traceStore.js +325 -0
  148. package/dist/observability/observabilityApp.d.ts +24 -0
  149. package/dist/observability/observabilityApp.js +157 -0
  150. package/dist/observability/observabilityAppRegistry.d.ts +14 -0
  151. package/dist/observability/observabilityAppRegistry.js +16 -0
  152. package/dist/observability/permissions.d.ts +7 -0
  153. package/dist/observability/permissions.js +60 -0
  154. package/dist/observability/reviewPanels.d.ts +18 -0
  155. package/dist/observability/reviewPanels.js +46 -0
  156. package/dist/observability/routes/datasets.d.ts +7 -0
  157. package/dist/observability/routes/datasets.js +149 -0
  158. package/dist/observability/routes/evaluators.d.ts +7 -0
  159. package/dist/observability/routes/evaluators.js +123 -0
  160. package/dist/observability/routes/experiments.d.ts +7 -0
  161. package/dist/observability/routes/experiments.js +95 -0
  162. package/dist/observability/routes/observabilityRouteAccess.d.ts +13 -0
  163. package/dist/observability/routes/observabilityRouteAccess.js +67 -0
  164. package/dist/observability/routes/prompts.d.ts +12 -0
  165. package/dist/observability/routes/prompts.js +172 -0
  166. package/dist/observability/routes/requestAiService.d.ts +13 -0
  167. package/dist/observability/routes/requestAiService.js +21 -0
  168. package/dist/observability/routes/review.d.ts +7 -0
  169. package/dist/observability/routes/review.js +79 -0
  170. package/dist/observability/routes/status.d.ts +5 -0
  171. package/dist/observability/routes/status.js +31 -0
  172. package/dist/observability/routes/testMultiStage.d.ts +9 -0
  173. package/dist/observability/routes/testMultiStage.js +67 -0
  174. package/dist/observability/routes/traces.d.ts +7 -0
  175. package/dist/observability/routes/traces.js +129 -0
  176. package/dist/observability/schemaValidation.d.ts +5 -0
  177. package/dist/observability/schemaValidation.js +26 -0
  178. package/dist/observability/sopThresholds.d.ts +2 -0
  179. package/dist/observability/sopThresholds.js +21 -0
  180. package/dist/observability/status.d.ts +23 -0
  181. package/dist/observability/status.js +34 -0
  182. package/dist/observability/testMultiStageSchemas.d.ts +10 -0
  183. package/dist/observability/testMultiStageSchemas.js +79 -0
  184. package/dist/observability/testMultiStageWorkflow.d.ts +20 -0
  185. package/dist/observability/testMultiStageWorkflow.js +218 -0
  186. package/dist/observability/types.d.ts +159 -0
  187. package/dist/observability/types.js +67 -0
  188. package/dist/routes/files.js +20 -7
  189. package/dist/routes/gpt.js +179 -488
  190. package/dist/routes/gptActions.d.ts +9 -0
  191. package/dist/routes/gptActions.js +212 -0
  192. package/dist/routes/gptDatasets.d.ts +5 -0
  193. package/dist/routes/gptDatasets.js +94 -0
  194. package/dist/routes/gptHistories.d.ts +3 -1
  195. package/dist/routes/gptHistories.js +188 -2
  196. package/dist/service/aiDatasets.d.ts +57 -0
  197. package/dist/service/aiDatasets.js +253 -0
  198. package/dist/service/aiService.d.ts +50 -1
  199. package/dist/service/aiService.js +431 -77
  200. package/dist/service/askFiles.d.ts +49 -0
  201. package/dist/service/askFiles.js +162 -0
  202. package/dist/service/asks.d.ts +76 -0
  203. package/dist/service/asks.js +284 -0
  204. package/dist/service/chatTurn.d.ts +128 -0
  205. package/dist/service/chatTurn.js +1674 -0
  206. package/dist/service/fileStorage.d.ts +4 -0
  207. package/dist/service/fileStorage.js +7 -2
  208. package/dist/service/fileUploadsGate.d.ts +8 -0
  209. package/dist/service/fileUploadsGate.js +18 -0
  210. package/dist/service/fillActionIds.d.ts +6 -0
  211. package/dist/service/fillActionIds.js +79 -0
  212. package/dist/service/gemini.d.ts +3 -3
  213. package/dist/service/gemini.js +3 -3
  214. package/dist/service/jsonFenceModel.d.ts +7 -0
  215. package/dist/service/jsonFenceModel.js +45 -0
  216. package/dist/service/prompts.d.ts +52 -0
  217. package/dist/service/prompts.js +96 -1
  218. package/dist/service/sanitizeHtml.d.ts +11 -0
  219. package/dist/service/sanitizeHtml.js +108 -0
  220. package/dist/service/vertex.d.ts +6 -6
  221. package/dist/service/vertex.js +5 -5
  222. package/dist/types/harness.d.ts +934 -0
  223. package/dist/types/harness.js +133 -0
  224. package/dist/types/index.d.ts +219 -13
  225. package/dist/types/index.js +2 -0
  226. package/dist/types/observability.d.ts +288 -0
  227. package/dist/types/observability.js +2 -0
  228. package/package.json +17 -5
  229. package/src/aiApp.test.ts +207 -1
  230. package/src/aiApp.ts +31 -8
  231. package/src/harness/adminScreens.test.ts +34 -0
  232. package/src/harness/adminScreens.ts +11 -0
  233. package/src/harness/agentLoop.test.ts +1034 -0
  234. package/src/harness/agentLoop.ts +1082 -0
  235. package/src/harness/agentRecovery.test.ts +380 -0
  236. package/src/harness/agentTaskNames.ts +4 -0
  237. package/src/harness/approvalPolicy.ts +28 -0
  238. package/src/harness/approvals.test.ts +1094 -0
  239. package/src/harness/approvals.ts +644 -0
  240. package/src/harness/commit.ts +1049 -0
  241. package/src/harness/conversation.ts +503 -0
  242. package/src/harness/defineAgent.test.ts +92 -0
  243. package/src/harness/defineAgent.ts +82 -0
  244. package/src/harness/defineTask.test.ts +59 -0
  245. package/src/harness/defineTask.ts +76 -0
  246. package/src/harness/defineTool.ts +45 -0
  247. package/src/harness/definitionError.ts +13 -0
  248. package/src/harness/errors.test.ts +90 -0
  249. package/src/harness/errors.ts +119 -0
  250. package/src/harness/eventHub.test.ts +124 -0
  251. package/src/harness/eventHub.ts +159 -0
  252. package/src/harness/events.test.ts +757 -0
  253. package/src/harness/events.ts +384 -0
  254. package/src/harness/executionEnv.ts +34 -0
  255. package/src/harness/extensions.test.ts +1218 -0
  256. package/src/harness/extensions.ts +382 -0
  257. package/src/harness/harness.test.ts +693 -0
  258. package/src/harness/harness.ts +767 -0
  259. package/src/harness/harnessApp.ts +76 -0
  260. package/src/harness/internalRuntime.ts +44 -0
  261. package/src/harness/leases.ts +132 -0
  262. package/src/harness/memo.ts +107 -0
  263. package/src/harness/modelCall.test.ts +134 -0
  264. package/src/harness/modelCall.ts +200 -0
  265. package/src/harness/models/harnessApproval.ts +109 -0
  266. package/src/harness/models/harnessConversation.ts +142 -0
  267. package/src/harness/models/harnessEvent.ts +92 -0
  268. package/src/harness/models/harnessInboxEvent.ts +73 -0
  269. package/src/harness/models/harnessMemo.ts +43 -0
  270. package/src/harness/models/harnessMessage.ts +85 -0
  271. package/src/harness/models/harnessModels.test.ts +60 -0
  272. package/src/harness/models/harnessOwner.ts +40 -0
  273. package/src/harness/models/harnessTask.ts +201 -0
  274. package/src/harness/ownership.test.ts +1087 -0
  275. package/src/harness/ownership.ts +618 -0
  276. package/src/harness/recovery.test.ts +912 -0
  277. package/src/harness/registry.ts +124 -0
  278. package/src/harness/retries.test.ts +292 -0
  279. package/src/harness/retryBackoff.test.ts +100 -0
  280. package/src/harness/retryBackoff.ts +77 -0
  281. package/src/harness/routes/approvals.ts +123 -0
  282. package/src/harness/routes/conversations.test.ts +518 -0
  283. package/src/harness/routes/conversations.ts +102 -0
  284. package/src/harness/routes/events.ts +280 -0
  285. package/src/harness/routes/tasks.test.ts +198 -0
  286. package/src/harness/routes/tasks.ts +146 -0
  287. package/src/harness/runners/inProcessRunner.test.ts +402 -0
  288. package/src/harness/runners/inProcessRunner.ts +220 -0
  289. package/src/harness/runtime.ts +714 -0
  290. package/src/harness/subagent.test.ts +696 -0
  291. package/src/harness/subagent.ts +192 -0
  292. package/src/harness/suspend.ts +13 -0
  293. package/src/harness/transaction.ts +17 -0
  294. package/src/harness/versioning.test.ts +288 -0
  295. package/src/harness/waits.test.ts +693 -0
  296. package/src/harness/waits.ts +356 -0
  297. package/src/index.test.ts +13 -0
  298. package/src/index.ts +70 -0
  299. package/src/isolated/adminScreensConfig.isolated.ts +143 -0
  300. package/src/models/aiDataset.test.ts +34 -0
  301. package/src/models/aiDataset.ts +78 -0
  302. package/src/models/aiRequest.test.ts +2 -2
  303. package/src/models/aiRequest.ts +2 -1
  304. package/src/models/gptHistory.test.ts +156 -0
  305. package/src/models/gptHistory.ts +106 -4
  306. package/src/observability/adminScreens.test.ts +71 -0
  307. package/src/observability/adminScreens.ts +42 -0
  308. package/src/observability/compileTemplate.test.ts +14 -0
  309. package/src/observability/compileTemplate.ts +10 -0
  310. package/src/observability/datasetImport.test.ts +95 -0
  311. package/src/observability/datasetImport.ts +220 -0
  312. package/src/observability/evaluate.test.ts +549 -0
  313. package/src/observability/evaluate.ts +254 -0
  314. package/src/observability/evaluatorTemplates.ts +124 -0
  315. package/src/observability/jsonPath.test.ts +52 -0
  316. package/src/observability/jsonPath.ts +60 -0
  317. package/src/observability/local/datasetStore.test.ts +230 -0
  318. package/src/observability/local/datasetStore.ts +452 -0
  319. package/src/observability/local/evaluatorStore.test.ts +138 -0
  320. package/src/observability/local/evaluatorStore.ts +224 -0
  321. package/src/observability/local/experimentRunner.test.ts +489 -0
  322. package/src/observability/local/experimentRunner.ts +548 -0
  323. package/src/observability/local/localPlugin.ts +88 -0
  324. package/src/observability/local/models/obsDataset.ts +38 -0
  325. package/src/observability/local/models/obsDatasetItem.ts +80 -0
  326. package/src/observability/local/models/obsEvaluator.ts +102 -0
  327. package/src/observability/local/models/obsExperiment.ts +91 -0
  328. package/src/observability/local/models/obsExperimentItem.ts +52 -0
  329. package/src/observability/local/models/obsPrompt.ts +43 -0
  330. package/src/observability/local/models/obsPromptLabel.ts +43 -0
  331. package/src/observability/local/models/obsPromptVersion.ts +107 -0
  332. package/src/observability/local/models/obsReviewItem.ts +79 -0
  333. package/src/observability/local/models/obsScore.ts +59 -0
  334. package/src/observability/local/models/obsSpan.ts +65 -0
  335. package/src/observability/local/models/obsTrace.ts +94 -0
  336. package/src/observability/local/obsModels.test.ts +119 -0
  337. package/src/observability/local/promptStore.test.ts +351 -0
  338. package/src/observability/local/promptStore.ts +665 -0
  339. package/src/observability/local/reviewStore.test.ts +164 -0
  340. package/src/observability/local/reviewStore.ts +264 -0
  341. package/src/observability/local/traceStore.test.ts +264 -0
  342. package/src/observability/local/traceStore.ts +440 -0
  343. package/src/observability/observabilityApp.test.ts +92 -0
  344. package/src/observability/observabilityApp.ts +185 -0
  345. package/src/observability/observabilityAppRegistry.test.ts +30 -0
  346. package/src/observability/observabilityAppRegistry.ts +35 -0
  347. package/src/observability/permissions.test.ts +96 -0
  348. package/src/observability/permissions.ts +78 -0
  349. package/src/observability/reviewPanels.test.ts +35 -0
  350. package/src/observability/reviewPanels.ts +64 -0
  351. package/src/observability/routes/datasets.test.ts +176 -0
  352. package/src/observability/routes/datasets.ts +252 -0
  353. package/src/observability/routes/evaluators.test.ts +119 -0
  354. package/src/observability/routes/evaluators.ts +207 -0
  355. package/src/observability/routes/experiments.test.ts +282 -0
  356. package/src/observability/routes/experiments.ts +152 -0
  357. package/src/observability/routes/observabilityRbac.test.ts +767 -0
  358. package/src/observability/routes/observabilityRouteAccess.ts +106 -0
  359. package/src/observability/routes/prompts.test.ts +320 -0
  360. package/src/observability/routes/prompts.ts +263 -0
  361. package/src/observability/routes/requestAiService.ts +36 -0
  362. package/src/observability/routes/review.test.ts +120 -0
  363. package/src/observability/routes/review.ts +125 -0
  364. package/src/observability/routes/status.test.ts +116 -0
  365. package/src/observability/routes/status.ts +47 -0
  366. package/src/observability/routes/testMultiStage.test.ts +214 -0
  367. package/src/observability/routes/testMultiStage.ts +96 -0
  368. package/src/observability/routes/traces.test.ts +167 -0
  369. package/src/observability/routes/traces.ts +172 -0
  370. package/src/observability/schemaValidation.ts +29 -0
  371. package/src/observability/sopThresholds.ts +20 -0
  372. package/src/observability/status.test.ts +38 -0
  373. package/src/observability/status.ts +56 -0
  374. package/src/observability/testMultiStageSchemas.ts +95 -0
  375. package/src/observability/testMultiStageWorkflow.test.ts +114 -0
  376. package/src/observability/testMultiStageWorkflow.ts +307 -0
  377. package/src/observability/types.ts +262 -0
  378. package/src/routes/files.test.ts +84 -9
  379. package/src/routes/files.ts +23 -7
  380. package/src/routes/gpt.test.ts +3279 -0
  381. package/src/routes/gpt.ts +214 -552
  382. package/src/routes/gptActions.test.ts +241 -0
  383. package/src/routes/gptActions.ts +255 -0
  384. package/src/routes/gptApprovals.test.ts +762 -0
  385. package/src/routes/gptDatasets.test.ts +86 -0
  386. package/src/routes/gptDatasets.ts +104 -0
  387. package/src/routes/gptFiles.test.ts +589 -0
  388. package/src/routes/gptHistories.test.ts +933 -0
  389. package/src/routes/gptHistories.ts +266 -5
  390. package/src/routes/routes.test.ts +676 -5
  391. package/src/service/aiDatasets.test.ts +123 -0
  392. package/src/service/aiDatasets.ts +316 -0
  393. package/src/service/aiService.test.ts +614 -0
  394. package/src/service/aiService.ts +575 -111
  395. package/src/service/askFiles.test.ts +96 -0
  396. package/src/service/askFiles.ts +222 -0
  397. package/src/service/asks.test.ts +946 -0
  398. package/src/service/asks.ts +423 -0
  399. package/src/service/chatTurn.ts +2287 -0
  400. package/src/service/fileStorage.test.ts +11 -0
  401. package/src/service/fileStorage.ts +10 -2
  402. package/src/service/fileUploadsGate.ts +23 -0
  403. package/src/service/fillActionIds.test.ts +65 -0
  404. package/src/service/fillActionIds.ts +98 -0
  405. package/src/service/gemini.test.ts +16 -10
  406. package/src/service/gemini.ts +3 -3
  407. package/src/service/jsonFenceModel.test.ts +47 -0
  408. package/src/service/jsonFenceModel.ts +53 -0
  409. package/src/service/prompts.test.ts +21 -0
  410. package/src/service/prompts.ts +147 -0
  411. package/src/service/sanitizeHtml.test.ts +61 -0
  412. package/src/service/sanitizeHtml.ts +109 -0
  413. package/src/service/vertex.test.ts +49 -49
  414. package/src/service/vertex.ts +7 -8
  415. package/src/tests/bunSetup.test.ts +7 -4
  416. package/src/tests/bunSetup.ts +7 -7
  417. package/src/tests/chatHarness.ts +478 -0
  418. package/src/tests/generateStream.ts +49 -0
  419. package/src/tests/harnessErrors.ts +22 -0
  420. package/src/tests/harnessStreaming.ts +227 -0
  421. package/src/tests/helpers.ts +9 -2
  422. package/src/types/harness.ts +1095 -0
  423. package/src/types/index.ts +237 -12
  424. package/src/types/observability.ts +344 -0
  425. package/src/types/sanitize-html.d.ts +25 -0
@@ -6,6 +6,7 @@ import {FileAttachment} from "../models/fileAttachment";
6
6
  // Mock @google-cloud/storage so the service doesn't try to authenticate
7
7
  const bucketFileMock = {
8
8
  delete: mock(async (_opts?: Record<string, unknown>) => [undefined]),
9
+ download: mock(async () => [Buffer.from("stored bytes")]),
9
10
  getSignedUrl: mock(async () => ["https://example.com/signed-url"]),
10
11
  save: mock(async (_buffer: Buffer, _opts: Record<string, unknown>) => [undefined]),
11
12
  };
@@ -55,6 +56,16 @@ describe("FileStorageService", () => {
55
56
  const attachment = await FileAttachment.findOne({gcsKey: result.gcsKey});
56
57
  expect(attachment).toBeDefined();
57
58
  expect(attachment?.mimeType).toBe("text/plain");
59
+ expect(result.id).toBe(attachment?._id.toString() ?? "");
60
+ });
61
+ });
62
+
63
+ describe("download", () => {
64
+ it("returns the bytes of the bucket file", async () => {
65
+ const service = new FileStorageService({bucketName: "test-bucket"});
66
+ const bytes = await service.download("uploads/abc/file.txt");
67
+ expect(bytes.toString("utf8")).toBe("stored bytes");
68
+ expect(bucketObj.file).toHaveBeenCalledWith("uploads/abc/file.txt");
58
69
  });
59
70
  });
60
71
 
@@ -13,6 +13,8 @@ export interface UploadFileParams {
13
13
  export interface UploadFileResult {
14
14
  filename: string;
15
15
  gcsKey: string;
16
+ /** The `FileAttachment` id, sent as `fileId` in an answer to a `files` ask. */
17
+ id: string;
16
18
  mimeType: string;
17
19
  size: number;
18
20
  url: string;
@@ -44,7 +46,7 @@ export class FileStorageService {
44
46
 
45
47
  const url = `https://storage.googleapis.com/${this.bucketName}/${gcsKey}`;
46
48
 
47
- await FileAttachment.create({
49
+ const attachment = await FileAttachment.create({
48
50
  filename,
49
51
  gcsKey,
50
52
  mimeType,
@@ -53,7 +55,13 @@ export class FileStorageService {
53
55
  userId,
54
56
  });
55
57
 
56
- return {filename, gcsKey, mimeType, size: buffer.length, url};
58
+ return {filename, gcsKey, id: attachment._id.toString(), mimeType, size: buffer.length, url};
59
+ }
60
+
61
+ /** The bytes of an upload, so a `files` ask answer can reach the model. */
62
+ async download(gcsKey: string): Promise<Buffer> {
63
+ const [contents] = await this.bucket.file(gcsKey).download();
64
+ return contents;
57
65
  }
58
66
 
59
67
  async getSignedUrl(gcsKey: string): Promise<string> {
@@ -0,0 +1,23 @@
1
+ import {APIError} from "@terreno/api";
2
+ import type express from "express";
3
+
4
+ /** Static switch, or a per-request check (for example a feature flag). */
5
+ export type FileUploadsEnabled = boolean | ((req: express.Request) => boolean | Promise<boolean>);
6
+
7
+ /**
8
+ * Reject the request when file uploads are turned off.
9
+ * Missing or `true` leaves uploads enabled.
10
+ */
11
+ export const assertFileUploadsEnabled = async (
12
+ req: express.Request,
13
+ fileUploadsEnabled: FileUploadsEnabled | undefined
14
+ ): Promise<void> => {
15
+ if (fileUploadsEnabled === undefined || fileUploadsEnabled === true) {
16
+ return;
17
+ }
18
+ const allowed =
19
+ typeof fileUploadsEnabled === "function" ? await fileUploadsEnabled(req) : fileUploadsEnabled;
20
+ if (!allowed) {
21
+ throw new APIError({status: 403, title: "File uploads are disabled"});
22
+ }
23
+ };
@@ -0,0 +1,65 @@
1
+ import {describe, it} from "bun:test";
2
+ import {validateBlocks} from "@terreno/blocks";
3
+ import {assert} from "chai";
4
+
5
+ import {fillMissingActionIds} from "./fillActionIds";
6
+
7
+ const JOKE = `v: 1
8
+ blocks:
9
+ - type: text
10
+ markdown: Why did the developer quit? Because they couldn't find their MongoDB!
11
+ - type: actions
12
+ elements:
13
+ - type: button
14
+ id: list_todos_button
15
+ text: List all todos
16
+ action:
17
+ kind: reply
18
+ text: list all the todos
19
+ `;
20
+
21
+ describe("fillMissingActionIds", () => {
22
+ it("adds an actions id so a joke with a reply button validates", () => {
23
+ const filled = fillMissingActionIds(JOKE);
24
+ assert.isString(filled);
25
+ const checked = validateBlocks(JSON.parse(filled ?? ""));
26
+ assert.isTrue(checked.ok);
27
+ assert.include(filled, "MongoDB!");
28
+ assert.include(filled, '"id":"actions"');
29
+ });
30
+
31
+ it("leaves a document that already has action ids alone", () => {
32
+ const text = `v: 1
33
+ blocks:
34
+ - type: actions
35
+ id: row
36
+ elements:
37
+ - type: button
38
+ id: run_btn
39
+ text: Export
40
+ action:
41
+ kind: reply
42
+ text: Export
43
+ `;
44
+ assert.isUndefined(fillMissingActionIds(text));
45
+ });
46
+
47
+ it("does not reuse an id that a button already has", () => {
48
+ const text = `v: 1
49
+ blocks:
50
+ - type: card
51
+ children:
52
+ - type: actions
53
+ elements:
54
+ - type: button
55
+ id: actions
56
+ text: Again
57
+ action:
58
+ kind: reply
59
+ text: Again
60
+ `;
61
+ const filled = fillMissingActionIds(text);
62
+ assert.isString(filled);
63
+ assert.include(filled, '"id":"actions_2"');
64
+ });
65
+ });
@@ -0,0 +1,98 @@
1
+ import {type BlocksDocument, parseBlocks} from "@terreno/blocks";
2
+
3
+ const ACTION_ID = /^[a-z][a-z0-9_]{0,63}$/;
4
+
5
+ interface LooseElement {
6
+ id?: string;
7
+ }
8
+
9
+ interface LooseBlock {
10
+ children?: LooseBlock[];
11
+ elements?: LooseElement[];
12
+ id?: string;
13
+ type?: string;
14
+ }
15
+
16
+ interface LooseDocument {
17
+ blocks: LooseBlock[];
18
+ datasets?: BlocksDocument["datasets"];
19
+ v: 1;
20
+ }
21
+
22
+ const isLooseDocument = (value: unknown): value is LooseDocument => {
23
+ if (typeof value !== "object" || value === null) {
24
+ return false;
25
+ }
26
+ const doc = value as {blocks?: unknown; v?: unknown};
27
+ return doc.v === 1 && Array.isArray(doc.blocks);
28
+ };
29
+
30
+ const collectIds = (blocks: readonly LooseBlock[], ids: Set<string>): void => {
31
+ for (const block of blocks) {
32
+ if (typeof block.id === "string" && ACTION_ID.test(block.id)) {
33
+ ids.add(block.id);
34
+ }
35
+ if (block.type === "actions") {
36
+ for (const element of block.elements ?? []) {
37
+ if (typeof element.id === "string" && ACTION_ID.test(element.id)) {
38
+ ids.add(element.id);
39
+ }
40
+ }
41
+ }
42
+ if (block.type === "columns" || block.type === "card") {
43
+ collectIds(block.children ?? [], ids);
44
+ }
45
+ }
46
+ };
47
+
48
+ const nextActionId = (ids: Set<string>): string => {
49
+ if (!ids.has("actions")) {
50
+ return "actions";
51
+ }
52
+ let index = 2;
53
+ while (ids.has(`actions_${index}`)) {
54
+ index += 1;
55
+ }
56
+ return `actions_${index}`;
57
+ };
58
+
59
+ const assignIds = (blocks: LooseBlock[], ids: Set<string>): boolean => {
60
+ let changed = false;
61
+ for (const block of blocks) {
62
+ if (block.type === "actions" && typeof block.id !== "string") {
63
+ const id = nextActionId(ids);
64
+ block.id = id;
65
+ ids.add(id);
66
+ changed = true;
67
+ }
68
+ if (block.type === "columns" || block.type === "card") {
69
+ if (assignIds(block.children ?? [], ids)) {
70
+ changed = true;
71
+ }
72
+ }
73
+ }
74
+ return changed;
75
+ };
76
+
77
+ /**
78
+ * Gives each actions block that omitted `id` a unique one.
79
+ * Models often leave it off; the schema requires it, and the chat then shows the raw YAML.
80
+ * Returns the document as JSON, or undefined when nothing was missing.
81
+ */
82
+ export const fillMissingActionIds = (text: string): string | undefined => {
83
+ const parsed = parseBlocks(text);
84
+ if (!parsed.ok || !isLooseDocument(parsed.value)) {
85
+ return undefined;
86
+ }
87
+ const ids = new Set<string>();
88
+ collectIds(parsed.value.blocks, ids);
89
+ if (!assignIds(parsed.value.blocks, ids)) {
90
+ return undefined;
91
+ }
92
+ const ordered: BlocksDocument = {
93
+ v: 1,
94
+ ...(parsed.value.datasets !== undefined ? {datasets: parsed.value.datasets} : {}),
95
+ blocks: parsed.value.blocks as BlocksDocument["blocks"],
96
+ };
97
+ return JSON.stringify(ordered);
98
+ };
@@ -12,11 +12,11 @@ const jsonResponse = (body: unknown, ok = true, status = 200): Response =>
12
12
  describe("gemini model listing helpers", () => {
13
13
  describe("normalizeGeminiModelId", () => {
14
14
  it("strips the models/ prefix", () => {
15
- expect(normalizeGeminiModelId("models/gemini-2.5-flash")).toBe("gemini-2.5-flash");
15
+ expect(normalizeGeminiModelId("models/gemini-3.8-flash")).toBe("gemini-3.8-flash");
16
16
  });
17
17
 
18
18
  it("leaves a bare id unchanged", () => {
19
- expect(normalizeGeminiModelId("gemini-2.5-pro")).toBe("gemini-2.5-pro");
19
+ expect(normalizeGeminiModelId("gemini-3.1-pro-preview")).toBe("gemini-3.1-pro-preview");
20
20
  });
21
21
  });
22
22
 
@@ -30,29 +30,32 @@ describe("gemini model listing helpers", () => {
30
30
  const fetchImpl = mock(async () =>
31
31
  jsonResponse({
32
32
  models: [
33
- {name: "models/gemini-2.5-pro", supportedGenerationMethods: ["generateContent"]},
34
- {name: "models/gemini-2.5-flash", supportedGenerationMethods: ["generateContent"]},
33
+ {
34
+ name: "models/gemini-3.1-pro-preview",
35
+ supportedGenerationMethods: ["generateContent"],
36
+ },
37
+ {name: "models/gemini-3.8-flash", supportedGenerationMethods: ["generateContent"]},
35
38
  {name: "models/text-embedding-004", supportedGenerationMethods: ["embedContent"]},
36
39
  ],
37
40
  })
38
41
  ) as unknown as typeof fetch;
39
42
 
40
43
  const result = await listGeminiApiModels({apiKey: "key", fetchImpl});
41
- expect(result).toEqual(["gemini-2.5-pro", "gemini-2.5-flash"]);
44
+ expect(result).toEqual(["gemini-3.1-pro-preview", "gemini-3.8-flash"]);
42
45
  });
43
46
 
44
47
  it("returns every model when chatOnly is false", async () => {
45
48
  const fetchImpl = mock(async () =>
46
49
  jsonResponse({
47
50
  models: [
48
- {name: "models/gemini-2.5-flash", supportedGenerationMethods: ["generateContent"]},
51
+ {name: "models/gemini-3.8-flash", supportedGenerationMethods: ["generateContent"]},
49
52
  {name: "models/text-embedding-004", supportedGenerationMethods: ["embedContent"]},
50
53
  ],
51
54
  })
52
55
  ) as unknown as typeof fetch;
53
56
 
54
57
  const result = await listGeminiApiModels({apiKey: "key", chatOnly: false, fetchImpl});
55
- expect(result).toEqual(["gemini-2.5-flash", "text-embedding-004"]);
58
+ expect(result).toEqual(["gemini-3.8-flash", "text-embedding-004"]);
56
59
  });
57
60
 
58
61
  it("follows pagination via nextPageToken", async () => {
@@ -62,20 +65,23 @@ describe("gemini model listing helpers", () => {
62
65
  if (call === 1) {
63
66
  return jsonResponse({
64
67
  models: [
65
- {name: "models/gemini-2.5-pro", supportedGenerationMethods: ["generateContent"]},
68
+ {
69
+ name: "models/gemini-3.1-pro-preview",
70
+ supportedGenerationMethods: ["generateContent"],
71
+ },
66
72
  ],
67
73
  nextPageToken: "page2",
68
74
  });
69
75
  }
70
76
  return jsonResponse({
71
77
  models: [
72
- {name: "models/gemini-2.5-flash", supportedGenerationMethods: ["generateContent"]},
78
+ {name: "models/gemini-3.8-flash", supportedGenerationMethods: ["generateContent"]},
73
79
  ],
74
80
  });
75
81
  }) as unknown as typeof fetch;
76
82
 
77
83
  const result = await listGeminiApiModels({apiKey: "key", fetchImpl});
78
- expect(result).toEqual(["gemini-2.5-pro", "gemini-2.5-flash"]);
84
+ expect(result).toEqual(["gemini-3.1-pro-preview", "gemini-3.8-flash"]);
79
85
  expect(call).toBe(2);
80
86
  });
81
87
 
@@ -4,7 +4,7 @@ import {logger} from "@terreno/api";
4
4
  * Helper for listing models available to the Gemini Developer API (the API-key based
5
5
  * `generativelanguage.googleapis.com` service, distinct from Vertex / the Gemini Enterprise Agent
6
6
  * Platform). Used to drive model pickers from the live set of models Google actually exposes for a
7
- * given API key, so retired models (e.g. an old `gemini-2.0-flash`) never appear.
7
+ * given API key, so retired models (e.g. an old `gemini-2.5-flash`) never appear.
8
8
  */
9
9
 
10
10
  /** Default Gemini Developer API base URL. */
@@ -33,14 +33,14 @@ interface GeminiApiModel {
33
33
  supportedGenerationMethods?: string[];
34
34
  }
35
35
 
36
- /** Strip the "models/" resource prefix from a Gemini model name (e.g. "models/gemini-2.5-flash"). */
36
+ /** Strip the "models/" resource prefix from a Gemini model name (e.g. "models/gemini-3.8-flash"). */
37
37
  export const normalizeGeminiModelId = (name: string): string => {
38
38
  return name.trim().replace(/^models\//, "");
39
39
  };
40
40
 
41
41
  /**
42
42
  * List the models available to a Gemini Developer API key via the `models` REST endpoint. Returns
43
- * normalized model ids (e.g. "gemini-2.5-flash"). By default only chat-capable models (those
43
+ * normalized model ids (e.g. "gemini-3.8-flash"). By default only chat-capable models (those
44
44
  * supporting `generateContent`) are returned. Returns `undefined` when the listing could not be
45
45
  * retrieved (missing key, network error, non-200 response, etc.).
46
46
  */
@@ -0,0 +1,47 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import type {LanguageModel} from "ai";
3
+
4
+ import {withStrippedJsonFencesModel} from "./jsonFenceModel";
5
+
6
+ interface GenerateResult {
7
+ content?: Array<{text?: string; type: string}>;
8
+ }
9
+
10
+ const modelReturning = (result: GenerateResult | undefined) =>
11
+ ({
12
+ doGenerate: async () => result,
13
+ modelId: "mock-model",
14
+ provider: "mock",
15
+ }) as unknown as LanguageModel;
16
+
17
+ const generate = (model: LanguageModel): Promise<GenerateResult | undefined> =>
18
+ (model as unknown as {doGenerate: (options: unknown) => Promise<GenerateResult>}).doGenerate({});
19
+
20
+ describe("withStrippedJsonFencesModel", () => {
21
+ it("strips code fences from text parts and leaves other parts alone", async () => {
22
+ const toolCall = {input: "{}", toolCallId: "c1", toolName: "lookup", type: "tool-call"};
23
+ const wrapped = withStrippedJsonFencesModel(
24
+ modelReturning({content: [{text: '```json\n{"a": 1}\n```', type: "text"}, toolCall]})
25
+ );
26
+ expect(await generate(wrapped)).toEqual({
27
+ content: [{text: '{"a":1}', type: "text"}, toolCall],
28
+ });
29
+ // Other properties pass through.
30
+ expect((wrapped as unknown as {modelId: string}).modelId).toBe("mock-model");
31
+ });
32
+
33
+ it("returns a result without a content array unchanged", async () => {
34
+ expect(await generate(withStrippedJsonFencesModel(modelReturning({})))).toEqual({});
35
+ expect(await generate(withStrippedJsonFencesModel(modelReturning(undefined)))).toBeUndefined();
36
+ });
37
+
38
+ it("passes through string model ids and models without doGenerate", () => {
39
+ expect(withStrippedJsonFencesModel("provider/model" as LanguageModel)).toBe(
40
+ "provider/model" as LanguageModel
41
+ );
42
+ const noGenerate = {doGenerate: "not a function", modelId: "x"} as unknown as LanguageModel;
43
+ expect(
44
+ (withStrippedJsonFencesModel(noGenerate) as unknown as {doGenerate: string}).doGenerate
45
+ ).toBe("not a function");
46
+ });
47
+ });
@@ -0,0 +1,53 @@
1
+ import type {LanguageModel} from "ai";
2
+
3
+ import {normalizeLlmJsonTextForStructuredOutput} from "./parseAiJson";
4
+
5
+ /**
6
+ * Wraps a language model so non-streaming `doGenerate` text parts are normalized via
7
+ * {@link normalizeLlmJsonTextForStructuredOutput} (fences, preamble, balanced slice, light repairs)
8
+ * before Vercel `Output.*` parsing.
9
+ */
10
+ export const withStrippedJsonFencesModel = (model: LanguageModel): LanguageModel => {
11
+ if (typeof model === "string") {
12
+ return model;
13
+ }
14
+
15
+ return new Proxy(model, {
16
+ get(target, prop, receiver) {
17
+ if (prop === "doGenerate") {
18
+ const original = Reflect.get(target, prop, receiver);
19
+ if (typeof original !== "function") {
20
+ return original;
21
+ }
22
+
23
+ const boundGenerate = original as (options: unknown) => PromiseLike<{
24
+ content: Array<{text?: string; type: string; [key: string]: unknown}>;
25
+ [key: string]: unknown;
26
+ }>;
27
+
28
+ return async (options: unknown) => {
29
+ const result = await Promise.resolve(boundGenerate.call(target, options));
30
+ if (!result?.content || !Array.isArray(result.content)) {
31
+ return result;
32
+ }
33
+
34
+ return {
35
+ ...result,
36
+ content: result.content.map((part) => {
37
+ if (part.type !== "text" || typeof part.text !== "string") {
38
+ return part;
39
+ }
40
+
41
+ return {
42
+ ...part,
43
+ text: normalizeLlmJsonTextForStructuredOutput(part.text),
44
+ };
45
+ }),
46
+ };
47
+ };
48
+ }
49
+
50
+ return Reflect.get(target, prop, receiver);
51
+ },
52
+ }) as LanguageModel;
53
+ };
@@ -1,12 +1,15 @@
1
1
  import {describe, expect, it} from "bun:test";
2
2
 
3
3
  import {
4
+ askFileHeading,
4
5
  CONTENT_SUMMARY_PROMPT,
5
6
  DEFAULT_GPT_MEMORY,
6
7
  JSON_VALUE_SYSTEM_PROMPT,
7
8
  REMIX_PROMPT,
8
9
  TITLE_GENERATION_PROMPT,
9
10
  TRANSLATION_PROMPT,
11
+ truncatedAskFileNote,
12
+ unloadedAskUploadsNote,
10
13
  } from "./prompts";
11
14
 
12
15
  describe("AI prompt constants", () => {
@@ -19,4 +22,22 @@ describe("AI prompt constants", () => {
19
22
  expect(TITLE_GENERATION_PROMPT).toContain("3-6 words");
20
23
  expect(JSON_VALUE_SYSTEM_PROMPT).toContain("JSON value");
21
24
  });
25
+
26
+ it("words the lines around a files answer's files as the model reads them", () => {
27
+ expect(
28
+ askFileHeading({
29
+ count: 2,
30
+ filename: "day.csv",
31
+ mimeType: "text/csv",
32
+ position: 1,
33
+ size: 28,
34
+ })
35
+ ).toBe("File 1 of 2: day.csv (text/csv, 28 bytes)");
36
+ expect(truncatedAskFileNote({keptBytes: 102400, totalBytes: 150000})).toBe(
37
+ "[The file is cut to its first 102400 of 150000 bytes.]"
38
+ );
39
+ expect(unloadedAskUploadsNote([{fileId: "f1", filename: "a.png"}])).toBe(
40
+ 'Uploads not loaded here: [{"fileId":"f1","filename":"a.png"}]'
41
+ );
42
+ });
22
43
  });
@@ -1,3 +1,133 @@
1
+ import {blocksPromptSection} from "@terreno/blocks";
2
+
3
+ /**
4
+ * Whole-reply document instructions, with no host callbacks registered.
5
+ * `uiBlocksSystemPrompt` rebuilds this when the host lists callback names.
6
+ */
7
+ export const TERRENO_UI_BLOCKS_SYSTEM_PROMPT = blocksPromptSection();
8
+
9
+ /** Tells the model to return only a corrected document. The failed document and its errors are the user prompt. */
10
+ export const UI_BLOCKS_REPAIR_SYSTEM_PROMPT =
11
+ "The document you wrote failed validation. Reply with only the corrected document. Do not explain the changes.";
12
+
13
+ /** The blocks prompt for this host's callback names. */
14
+ export const uiBlocksSystemPrompt = (
15
+ hostActions: readonly string[],
16
+ allowHtml = false,
17
+ imageHosts: readonly string[] = []
18
+ ): string => {
19
+ if (hostActions.length === 0 && !allowHtml && imageHosts.length === 0) {
20
+ return TERRENO_UI_BLOCKS_SYSTEM_PROMPT;
21
+ }
22
+ return blocksPromptSection({allowHtml, hostActions, imageHosts});
23
+ };
24
+
25
+ /**
26
+ * Appended to the chat system prompt when a route enables asks. The enabled ask tools and their
27
+ * limits follow it at call time (`askPromptSection` from @terreno/blocks), so the numbers stay in
28
+ * one place.
29
+ */
30
+ export const TERRENO_ASKS_SYSTEM_PROMPT =
31
+ "You can ask the user a question inside the chat by calling an ask tool. The chat shows the " +
32
+ "ask as a control, the user answers it, and the answer comes back to you as the tool's result.\n\n" +
33
+ "When to ask:\n" +
34
+ "- When you need an answer that one of the ask tools listed below can collect, call that tool " +
35
+ "instead of asking in plain text.\n" +
36
+ "- Ask only when you cannot continue well without the answer. Do not ask for anything you can " +
37
+ "find out with another tool.\n" +
38
+ "- Call at most one ask tool per step, and do not call other tools in the same step.\n" +
39
+ "- Never ask for passwords, payment card numbers, API keys, or other secrets.\n\n" +
40
+ "How answers come back:\n" +
41
+ '- {"action": "accept", "content": {...}}: the user answered; content holds the answer.\n' +
42
+ '- {"action": "decline"}: the user skipped the question. Continue without the answer, or ' +
43
+ "explain what you need.\n" +
44
+ '- {"action": "cancel", "reason": "..."}: the ask was dropped. "user_sent_message" means the ' +
45
+ 'user typed a message instead, so respond to that message. "one_ask_at_a_time" means you ' +
46
+ "asked more than once in one step.\n" +
47
+ "After a decline or a cancel, do not ask the same question again unless the user asks you to.";
48
+
49
+ /**
50
+ * Appended to the chat system prompt when a request sends `surface: "compact"`, because the user
51
+ * reads replies and answers asks on a small screen. With asks on, the asks section before it
52
+ * offers only the compact ask tools.
53
+ */
54
+ export const COMPACT_SURFACE_SYSTEM_PROMPT =
55
+ "The user is on a small screen, such as a watch. Keep each reply to at most two short " +
56
+ "sentences, and ask only yes-or-no questions or questions with up to three short options.";
57
+
58
+ export const ASK_CHOICE_TOOL_DESCRIPTION =
59
+ "Ask the user to pick one or more options from a list you provide, optionally with an Other " +
60
+ "field for an answer of their own. The chat shows the options as a control and returns the " +
61
+ "user's answer as this tool's result. Use it instead of asking in plain text when the user must " +
62
+ "choose from options you can list.";
63
+
64
+ /** The compact surface offers only select one, so its tool description does not mention many or Other. */
65
+ export const COMPACT_ASK_CHOICE_TOOL_DESCRIPTION =
66
+ "Ask the user to pick one option from a list you provide. The chat shows the options as a " +
67
+ "control and returns the user's answer as this tool's result. Use it instead of asking in plain " +
68
+ "text when the user must choose between options you can list.";
69
+
70
+ export const ASK_CONFIRM_TOOL_DESCRIPTION =
71
+ "Ask the user to approve or deny one action you describe. The chat shows an approve button and " +
72
+ "a deny button and returns {confirmed: true} or {confirmed: false} as this tool's result. Call " +
73
+ "it before a tool that deletes data, sends something on the user's behalf, spends money, or " +
74
+ "cannot be undone.";
75
+
76
+ export const COMPACT_ASK_CONFIRM_TOOL_DESCRIPTION =
77
+ "Ask the user to approve or deny one action you describe, with two short buttons. The user's " +
78
+ "answer comes back as {confirmed: true} or {confirmed: false}. Call it before a tool that " +
79
+ "deletes data, sends something, spends money, or cannot be undone.";
80
+
81
+ export const ASK_MARKDOWN_TOOL_DESCRIPTION =
82
+ "Ask the user to edit a markdown draft you write, or to write one, and send it back. The chat " +
83
+ "shows a markdown editor with a preview and returns {markdown, changed} as this tool's result; " +
84
+ "changed is false when the user approved your draft as is. Use it when the user should review " +
85
+ "or rewrite text before you use it, such as an announcement, an email, or release notes.";
86
+
87
+ export const ASK_FORM_TOOL_DESCRIPTION =
88
+ "Ask the user to fill in a few typed fields and submit them at once, such as the details for " +
89
+ "an invoice or a booking. The chat shows one input per field and returns {values}, keyed by " +
90
+ "field id, as this tool's result. Use it when you need several values together; for one pick " +
91
+ "from a list, use a choice instead.";
92
+
93
+ export const ASK_FILES_TOOL_DESCRIPTION =
94
+ "Ask the user to upload one or more files, such as a photo of a receipt, a signed PDF, or a " +
95
+ "CSV export. The chat shows a file picker limited to the types in accept, and this tool's " +
96
+ "result lists each file's filename, mimeType, and size, followed by the files themselves: " +
97
+ "images and PDFs as they are, text, CSV, and JSON as text. Use it when you need the file's " +
98
+ "contents; ask for a typed value with a form instead.";
99
+
100
+ /** The line before each file of a `files` answer in the tool result the model sees. */
101
+ export const askFileHeading = ({
102
+ count,
103
+ filename,
104
+ mimeType,
105
+ position,
106
+ size,
107
+ }: {
108
+ count: number;
109
+ filename: string;
110
+ mimeType: string;
111
+ position: number;
112
+ size: number;
113
+ }): string => `File ${position} of ${count}: ${filename} (${mimeType}, ${size} bytes)`;
114
+
115
+ /** The note after a text file of a `files` answer that was cut to fit. */
116
+ export const truncatedAskFileNote = ({
117
+ keptBytes,
118
+ totalBytes,
119
+ }: {
120
+ keptBytes: number;
121
+ totalBytes: number;
122
+ }): string => `[The file is cut to its first ${keptBytes} of ${totalBytes} bytes.]`;
123
+
124
+ /** The note naming the uploads of a `files` answer that a host's own replay could not load. */
125
+ export const unloadedAskUploadsNote = (uploads: unknown[]): string =>
126
+ `Uploads not loaded here: ${JSON.stringify(uploads)}`;
127
+
128
+ /** Tool result for a call that was left without one when the turn paused for an ask. */
129
+ export const UNANSWERED_TOOL_CALL_RESULT = "This tool call did not run, so it has no result.";
130
+
1
131
  export const DEFAULT_GPT_MEMORY =
2
132
  "You are a helpful, friendly AI assistant. Provide clear, accurate, and concise responses. " +
3
133
  "When you don't know something, say so honestly rather than guessing.";
@@ -25,3 +155,20 @@ export const TITLE_GENERATION_PROMPT =
25
155
  export const JSON_VALUE_SYSTEM_PROMPT =
26
156
  "You respond with a single JSON value (object, array, string, number, boolean, or null) only. " +
27
157
  "No markdown code fences, no commentary before or after the JSON.";
158
+
159
+ /** Observability test-multi-stage workflow: first parallel-style LLM pass. */
160
+ export const OBS_TEST_MULTI_STAGE_CALL_1_SYSTEM =
161
+ "Summarize the user input in one short phrase. Return a JSON object that matches the output " +
162
+ 'schema {"phrase": string}. No markdown fences and no extra keys.';
163
+
164
+ /** Observability test-multi-stage workflow: second LLM pass over the same input. */
165
+ export const OBS_TEST_MULTI_STAGE_CALL_2_SYSTEM =
166
+ "Extract exactly two keywords from the user input. Return a JSON object that matches the output " +
167
+ 'schema {"keywords": [string, string]}. No markdown fences and no extra keys.';
168
+
169
+ /** Observability test-multi-stage workflow: final synthesis LLM pass. */
170
+ export const OBS_TEST_MULTI_STAGE_FINAL_SYSTEM =
171
+ "Combine the stage-one phrase, stage-two keywords, and text metrics into one concise sentence. " +
172
+ "Return a JSON object that matches the output schema " +
173
+ '{"sentence": string, "phrase": string, "keywords": string[], "metrics": object}. ' +
174
+ "Echo phrase, keywords, and metrics from the prompt. No markdown fences and no extra keys.";