@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,134 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.subagentResult = exports.startSubagentTurn = exports.serializeOutputSchema = exports.subagentContent = exports.HarnessSubagentError = void 0;
7
+ const ai_1 = require("ai");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const harness_1 = require("../types/harness");
10
+ const commit_1 = require("./commit");
11
+ const conversation_1 = require("./conversation");
12
+ const events_1 = require("./events");
13
+ /** A subagent run by `rt.runAgent` did not produce a usable answer. */
14
+ class HarnessSubagentError extends Error {
15
+ agentName;
16
+ conversationId;
17
+ /** Terminal status of the subagent's turn task. */
18
+ status;
19
+ turnTaskId;
20
+ constructor({ agentName, conversationId, message, outcome, }) {
21
+ super(message);
22
+ this.name = "HarnessSubagentError";
23
+ this.agentName = agentName;
24
+ this.conversationId = conversationId;
25
+ this.status = outcome.status;
26
+ this.turnTaskId = outcome.id;
27
+ }
28
+ }
29
+ exports.HarnessSubagentError = HarnessSubagentError;
30
+ /** The subagent's user message: strings as-is, anything else as JSON. */
31
+ const subagentContent = (input) => {
32
+ if (typeof input === "string") {
33
+ return input.trim() ? input : undefined;
34
+ }
35
+ if (input === undefined) {
36
+ return undefined;
37
+ }
38
+ return JSON.stringify(input);
39
+ };
40
+ exports.subagentContent = subagentContent;
41
+ /**
42
+ * Serialize `schema` as JSON Schema with the AI SDK's own converter, so the turn requests
43
+ * exactly the structure `Output.object` would. Stored as a string: JSON Schema keys such
44
+ * as `$schema` and `$ref` are not valid Mongo field names.
45
+ */
46
+ const serializeOutputSchema = async (schema) => {
47
+ const converted = await Promise.resolve((0, ai_1.asSchema)(schema).jsonSchema);
48
+ return JSON.stringify(converted);
49
+ };
50
+ exports.serializeOutputSchema = serializeOutputSchema;
51
+ /**
52
+ * Create the subagent's conversation, its user message, and its turn (a child task of
53
+ * `parent` with an `AGENT` span named after the agent) in one transaction. A re-run of
54
+ * the same phase attempt finds the turn created first, and with it the same conversation.
55
+ */
56
+ const startSubagentTurn = async ({ agent, callIndex, content, extensions, instructions, lease, models, outputSchema, parent, turn, }) => {
57
+ const key = `agent:${callIndex}`;
58
+ const newConversationId = new mongoose_1.default.Types.ObjectId();
59
+ const input = { conversationId: String(newConversationId) };
60
+ const turnTask = await (0, commit_1.createChildTaskRecords)({
61
+ definition: turn,
62
+ input,
63
+ key,
64
+ lease,
65
+ models,
66
+ options: {},
67
+ parent,
68
+ span: {
69
+ // The message itself is in the transcript; the span stays bounded.
70
+ input: { conversationId: input.conversationId, instructions, messageSeq: 1 },
71
+ kind: "AGENT",
72
+ name: agent.name,
73
+ },
74
+ writes: async ({ session, task }) => {
75
+ await models.conversation.create([
76
+ {
77
+ _id: newConversationId,
78
+ activeTurnTaskId: task._id,
79
+ agent: {
80
+ ...(0, conversation_1.conversationAgentSnapshot)({ agent, extensions }),
81
+ instructions: instructions ?? agent.instructions,
82
+ outputSchema,
83
+ },
84
+ ownerKey: `${parent.step ?? 0}:${parent.attempt ?? 0}:${key}`,
85
+ ownership: { id: parent._id, kind: "task" },
86
+ seq: 1,
87
+ status: harness_1.HARNESS_CONVERSATION_STATUSES.busy,
88
+ userId: parent.userId,
89
+ },
90
+ ], { session });
91
+ await (0, events_1.insertMessages)({
92
+ messages: [
93
+ {
94
+ conversationId: newConversationId,
95
+ parts: [{ text: content, type: "text" }],
96
+ role: harness_1.HARNESS_MESSAGE_ROLES.user,
97
+ seq: 1,
98
+ turnTaskId: task._id,
99
+ },
100
+ ],
101
+ models,
102
+ session,
103
+ });
104
+ },
105
+ });
106
+ // An existing turn carries the conversation created with it.
107
+ const { conversationId } = turnTask.input;
108
+ return { conversationId, turnTask };
109
+ };
110
+ exports.startSubagentTurn = startSubagentTurn;
111
+ /** The value `rt.runAgent` returns for a settled turn, or the error it throws. */
112
+ const subagentResult = ({ agent, conversationId, outcome, schema, }) => {
113
+ const fail = (message) => new HarnessSubagentError({ agentName: agent.name, conversationId, message, outcome });
114
+ if (outcome.status !== "completed") {
115
+ throw fail(`Subagent "${agent.name}" ${outcome.status}: ${outcome.error ?? "no error recorded"}`);
116
+ }
117
+ const result = outcome.result;
118
+ // A turn cut off by maxSteps ends on a tool round, so its text is not an answer.
119
+ if (result.finishReason !== "stop") {
120
+ throw fail(`Subagent "${agent.name}" finished (${result.finishReason}) without a final answer`);
121
+ }
122
+ if (!schema) {
123
+ return result.text;
124
+ }
125
+ if (result.output === undefined) {
126
+ throw fail(`Subagent "${agent.name}" answered without structured output`);
127
+ }
128
+ const parsed = schema.safeParse(result.output);
129
+ if (!parsed.success) {
130
+ throw fail(`Subagent "${agent.name}" output does not match its schema: ${parsed.error.message}`);
131
+ }
132
+ return parsed.data;
133
+ };
134
+ exports.subagentResult = subagentResult;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Unwinds a phase that committed `waiting`; the runner stops the task without failing it.
3
+ * Code that wraps user callbacks (hooks, tools) must rethrow it untouched.
4
+ */
5
+ export declare class HarnessSuspendSignal extends Error {
6
+ constructor(taskId: string);
7
+ }
8
+ export declare const isHarnessSuspendSignal: (error: unknown) => error is HarnessSuspendSignal;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isHarnessSuspendSignal = exports.HarnessSuspendSignal = void 0;
4
+ /**
5
+ * Unwinds a phase that committed `waiting`; the runner stops the task without failing it.
6
+ * Code that wraps user callbacks (hooks, tools) must rethrow it untouched.
7
+ */
8
+ class HarnessSuspendSignal extends Error {
9
+ constructor(taskId) {
10
+ super(`Harness task ${taskId} is waiting; the phase re-runs when the wait is satisfied`);
11
+ this.name = "HarnessSuspendSignal";
12
+ }
13
+ }
14
+ exports.HarnessSuspendSignal = HarnessSuspendSignal;
15
+ const isHarnessSuspendSignal = (error) => error instanceof HarnessSuspendSignal;
16
+ exports.isHarnessSuspendSignal = isHarnessSuspendSignal;
@@ -0,0 +1,3 @@
1
+ import { type ClientSession } from "mongoose";
2
+ /** Run `work` in one Mongo transaction; every write inside must pass `session`. */
3
+ export declare const inTransaction: <T>(work: (session: ClientSession) => Promise<T>) => Promise<T>;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.inTransaction = void 0;
7
+ const mongoose_1 = __importDefault(require("mongoose"));
8
+ /** Run `work` in one Mongo transaction; every write inside must pass `session`. */
9
+ const inTransaction = async (work) => {
10
+ const session = await mongoose_1.default.connection.startSession();
11
+ try {
12
+ let result;
13
+ await session.withTransaction(async () => {
14
+ result = await work(session);
15
+ });
16
+ return result;
17
+ }
18
+ finally {
19
+ await session.endSession();
20
+ }
21
+ };
22
+ exports.inTransaction = inTransaction;
@@ -0,0 +1,100 @@
1
+ import { Duration, type DurationLike } from "luxon";
2
+ import type mongoose from "mongoose";
3
+ import type { ClientSession } from "mongoose";
4
+ import type { HarnessInboxEventDocument, HarnessLeaseSettings, HarnessTaskDocument, HarnessTestHooks, HarnessWaitCall } from "../types/harness";
5
+ import { type HarnessCommitWrites, type HarnessModels } from "./commit";
6
+ /** One `rt.waitFor` or `rt.sleep` call. */
7
+ export interface WaitRequest {
8
+ /** Sleep length, or the event wait's timeout. */
9
+ duration?: Duration;
10
+ /** Event name; absent for a sleep. */
11
+ event?: string;
12
+ kind: "event" | "sleep";
13
+ /**
14
+ * Extra writes committed with a timeout resolution. Throw `HarnessWaitRaceError` from
15
+ * them when an event that should win landed concurrently: the call then resolves again.
16
+ */
17
+ timeoutWrites?: HarnessCommitWrites;
18
+ }
19
+ /**
20
+ * Thrown from `WaitRequest.timeoutWrites` when the timeout lost a race with a matching
21
+ * event; the timeout transaction rolls back and the call is resolved again.
22
+ */
23
+ export declare class HarnessWaitRaceError extends Error {
24
+ constructor();
25
+ }
26
+ /** What one wait call needs: its request, plus writes and work around parking on it. */
27
+ export interface WaitCallPlan {
28
+ /** Runs after the waiting commit, before the phase stops. */
29
+ afterPark?: () => Promise<void>;
30
+ /** Extra rows committed with the waiting commit. */
31
+ onPark?: HarnessCommitWrites;
32
+ request: WaitRequest;
33
+ }
34
+ /** A wait call either has its result, or must park the task on `entry`. */
35
+ export type WaitCallResult = {
36
+ isResolved: true;
37
+ payload?: unknown;
38
+ } | {
39
+ entry: HarnessWaitCall;
40
+ isResolved: false;
41
+ };
42
+ /** Names one wait call of the current phase visit: `<step>:<call index>`. */
43
+ export declare const waitCallKey: ({ index, task }: {
44
+ index: number;
45
+ task: HarnessTaskDocument;
46
+ }) => string;
47
+ /** A non-negative Luxon duration, or a definition error naming `label`. */
48
+ export declare const parseWaitDuration: (value: DurationLike, label: string) => Duration;
49
+ /**
50
+ * Resolve one wait call. A call this phase visit already resolved returns its recorded
51
+ * result. Otherwise an event wait takes the oldest undelivered event of its name; failing
52
+ * that, a passed `timeoutAt` resolves it (`undefined` for an event, done for a sleep).
53
+ * Each resolution is recorded on the task with a resume span in one fenced transaction.
54
+ * Otherwise returns the record to park the task on.
55
+ */
56
+ export declare const resolveWaitCall: (args: Parameters<typeof resolveWaitCallOnce>[0]) => Promise<WaitCallResult>;
57
+ declare const resolveWaitCallOnce: ({ callKey, label, lease, models, request, task, testHooks, }: {
58
+ callKey: string;
59
+ /** Task definition key, for error messages. */
60
+ label: string;
61
+ lease: HarnessLeaseSettings;
62
+ models: HarnessModels;
63
+ request: WaitRequest;
64
+ task: HarnessTaskDocument;
65
+ testHooks?: HarnessTestHooks;
66
+ }) => Promise<WaitCallResult>;
67
+ /**
68
+ * Inside `session`'s transaction: count the event on the task (`eventSeq`), insert it into
69
+ * the task's inbox, and, when the task is waiting on that event name, return it to
70
+ * `pending`. Throws when the task is terminal. Returns whether the task was woken.
71
+ */
72
+ export declare const appendInboxEvent: ({ event, models, payload, requestId, session, taskId, }: {
73
+ event: string;
74
+ models: HarnessModels;
75
+ payload: unknown;
76
+ requestId?: string;
77
+ session: ClientSession;
78
+ taskId: mongoose.Types.ObjectId;
79
+ }) => Promise<{
80
+ event: HarnessInboxEventDocument;
81
+ isWoken: boolean;
82
+ }>;
83
+ /**
84
+ * Append an event to a task's inbox and, when the task is waiting on that event name,
85
+ * return it to `pending`, in one transaction. The task row is written every time
86
+ * (`eventSeq`), so a concurrent `rt.waitFor` commit and this send conflict and one retries:
87
+ * neither can miss the other. A repeated `requestId` returns the event sent first.
88
+ * Throws when the task is terminal.
89
+ */
90
+ export declare const sendEventRecords: ({ event, models, payload, requestId, taskId, }: {
91
+ event: string;
92
+ models: HarnessModels;
93
+ payload: unknown;
94
+ requestId?: string;
95
+ taskId: mongoose.Types.ObjectId | string;
96
+ }) => Promise<{
97
+ event: HarnessInboxEventDocument;
98
+ isWoken: boolean;
99
+ }>;
100
+ export {};
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendEventRecords = exports.appendInboxEvent = exports.resolveWaitCall = exports.parseWaitDuration = exports.waitCallKey = exports.HarnessWaitRaceError = void 0;
4
+ const luxon_1 = require("luxon");
5
+ const harness_1 = require("../types/harness");
6
+ const commit_1 = require("./commit");
7
+ const definitionError_1 = require("./definitionError");
8
+ const errors_1 = require("./errors");
9
+ const transaction_1 = require("./transaction");
10
+ /** Most object keys a resume span lists for a delivered payload. */
11
+ const PAYLOAD_SUMMARY_KEYS = 20;
12
+ /**
13
+ * Thrown from `WaitRequest.timeoutWrites` when the timeout lost a race with a matching
14
+ * event; the timeout transaction rolls back and the call is resolved again.
15
+ */
16
+ class HarnessWaitRaceError extends Error {
17
+ constructor() {
18
+ super("A matching event raced the wait's timeout");
19
+ this.name = "HarnessWaitRaceError";
20
+ }
21
+ }
22
+ exports.HarnessWaitRaceError = HarnessWaitRaceError;
23
+ /** Times a call re-resolves after losing a timeout race before giving up. */
24
+ const MAX_WAIT_RACE_RETRIES = 3;
25
+ /** Names one wait call of the current phase visit: `<step>:<call index>`. */
26
+ const waitCallKey = ({ index, task }) => `${task.step ?? 0}:${index}`;
27
+ exports.waitCallKey = waitCallKey;
28
+ /** A non-negative Luxon duration, or a definition error naming `label`. */
29
+ const parseWaitDuration = (value, label) => {
30
+ let duration;
31
+ try {
32
+ duration = luxon_1.Duration.fromDurationLike(value);
33
+ }
34
+ catch (error) {
35
+ throw new definitionError_1.HarnessDefinitionError(`${label} must be a Luxon duration: ${error instanceof Error ? error.message : String(error)}`);
36
+ }
37
+ if (!duration.isValid || !(duration.toMillis() >= 0)) {
38
+ throw new definitionError_1.HarnessDefinitionError(`${label} must be a valid, non-negative duration`);
39
+ }
40
+ return duration;
41
+ };
42
+ exports.parseWaitDuration = parseWaitDuration;
43
+ /** Shape of a payload for the resume span, without its values. */
44
+ const summarizePayload = (payload) => {
45
+ if (payload === null) {
46
+ return { type: "null" };
47
+ }
48
+ if (Array.isArray(payload)) {
49
+ return { length: payload.length, type: "array" };
50
+ }
51
+ if (typeof payload === "string") {
52
+ return { length: payload.length, type: "string" };
53
+ }
54
+ if (typeof payload === "object") {
55
+ const keys = Object.keys(payload);
56
+ return { keyCount: keys.length, keys: keys.slice(0, PAYLOAD_SUMMARY_KEYS), type: "object" };
57
+ }
58
+ return { type: typeof payload };
59
+ };
60
+ const describeCall = (call) => {
61
+ const event = call.event ?? call.key;
62
+ return call.kind === harness_1.HARNESS_WAIT_KINDS.event ? `rt.waitFor("${event}")` : "rt.sleep";
63
+ };
64
+ const resumeSpanName = (request) => request.kind === harness_1.HARNESS_WAIT_KINDS.event ? `wait:${request.event}` : "sleep";
65
+ const resumeSpanInput = (entry) => ({
66
+ ...(entry.key === undefined ? {} : { event: entry.key }),
67
+ kind: entry.kind,
68
+ startedAt: entry.startedAt.toISOString(),
69
+ ...(entry.timeoutAt ? { timeoutAt: entry.timeoutAt.toISOString() } : {}),
70
+ });
71
+ /**
72
+ * Resolve one wait call. A call this phase visit already resolved returns its recorded
73
+ * result. Otherwise an event wait takes the oldest undelivered event of its name; failing
74
+ * that, a passed `timeoutAt` resolves it (`undefined` for an event, done for a sleep).
75
+ * Each resolution is recorded on the task with a resume span in one fenced transaction.
76
+ * Otherwise returns the record to park the task on.
77
+ */
78
+ const resolveWaitCall = async (args) => {
79
+ for (let attempt = 0;; attempt++) {
80
+ try {
81
+ return await resolveWaitCallOnce(args);
82
+ }
83
+ catch (error) {
84
+ if (!(error instanceof HarnessWaitRaceError) || attempt >= MAX_WAIT_RACE_RETRIES) {
85
+ throw error;
86
+ }
87
+ }
88
+ }
89
+ };
90
+ exports.resolveWaitCall = resolveWaitCall;
91
+ const resolveWaitCallOnce = async ({ callKey, label, lease, models, request, task, testHooks, }) => {
92
+ const recorded = task.waits?.[callKey];
93
+ if (recorded && (recorded.kind !== request.kind || recorded.key !== request.event)) {
94
+ throw new definitionError_1.HarnessDefinitionError(`${label}: wait call ${callKey} was ${describeCall(recorded)} on an earlier run and is ${describeCall(request)} now; run waits in the same order on every run of a phase`);
95
+ }
96
+ if (recorded?.resolution) {
97
+ if (recorded.resolution !== harness_1.HARNESS_WAIT_RESOLUTIONS.event) {
98
+ return { isResolved: true };
99
+ }
100
+ const delivered = await models.inbox.findExactlyOne({ _id: recorded.eventId });
101
+ return { isResolved: true, payload: delivered.payload };
102
+ }
103
+ const now = luxon_1.DateTime.now();
104
+ const entry = recorded ?? {
105
+ kind: request.kind,
106
+ ...(request.event === undefined ? {} : { key: request.event }),
107
+ startedAt: now.toJSDate(),
108
+ ...(request.duration ? { timeoutAt: now.plus(request.duration).toJSDate() } : {}),
109
+ };
110
+ const resolve = (resolved, output, writes) => (0, commit_1.commitWaitResolution)({
111
+ callKey,
112
+ entry: { ...entry, ...resolved, resolvedAt: now.toJSDate() },
113
+ lease,
114
+ models,
115
+ span: { input: resumeSpanInput(entry), name: resumeSpanName(request), output },
116
+ task,
117
+ testHooks,
118
+ writes,
119
+ });
120
+ if (request.kind === harness_1.HARNESS_WAIT_KINDS.event) {
121
+ const [buffered] = await models.inbox
122
+ .find({ consumedKey: { $exists: false }, name: request.event, taskId: task._id })
123
+ .sort({ seq: 1 })
124
+ .limit(1);
125
+ if (buffered) {
126
+ await resolve({ eventId: buffered._id, resolution: harness_1.HARNESS_WAIT_RESOLUTIONS.event }, {
127
+ event: request.event,
128
+ eventId: String(buffered._id),
129
+ payload: summarizePayload(buffered.payload),
130
+ seq: buffered.seq,
131
+ timedOut: false,
132
+ }, async ({ session }) => {
133
+ const claimed = await models.inbox.updateOne({ _id: buffered._id, consumedKey: { $exists: false } }, { $set: { consumedAt: now.toJSDate(), consumedKey: callKey } }, { session });
134
+ if (claimed.matchedCount === 0) {
135
+ throw new commit_1.HarnessCommitConflictError(String(task._id), task.phase);
136
+ }
137
+ });
138
+ return { isResolved: true, payload: buffered.payload };
139
+ }
140
+ }
141
+ if (entry.timeoutAt && now >= luxon_1.DateTime.fromJSDate(entry.timeoutAt)) {
142
+ const isEvent = request.kind === harness_1.HARNESS_WAIT_KINDS.event;
143
+ await resolve({ resolution: isEvent ? harness_1.HARNESS_WAIT_RESOLUTIONS.timeout : harness_1.HARNESS_WAIT_RESOLUTIONS.elapsed }, isEvent ? { event: request.event, timedOut: true } : { elapsed: true }, request.timeoutWrites);
144
+ return { isResolved: true };
145
+ }
146
+ return { entry, isResolved: false };
147
+ };
148
+ const assertSameEvent = (existing, event) => {
149
+ if (existing.name !== event) {
150
+ throw (0, errors_1.harnessError)({
151
+ detail: `requestId "${existing.requestId}" already sent event "${existing.name}" to task ${existing.taskId}, not "${event}"`,
152
+ kind: "requestIdConflict",
153
+ });
154
+ }
155
+ return existing;
156
+ };
157
+ /**
158
+ * Inside `session`'s transaction: count the event on the task (`eventSeq`), insert it into
159
+ * the task's inbox, and, when the task is waiting on that event name, return it to
160
+ * `pending`. Throws when the task is terminal. Returns whether the task was woken.
161
+ */
162
+ const appendInboxEvent = async ({ event, models, payload, requestId, session, taskId, }) => {
163
+ const counted = await models.task.findOneAndUpdate({ _id: taskId, status: { $nin: [...harness_1.HARNESS_TERMINAL_STATUSES] } }, { $inc: { eventSeq: 1 } }, { returnDocument: "after", session });
164
+ if (!counted) {
165
+ throw (0, errors_1.harnessError)({
166
+ detail: `Task ${taskId} is already terminal; it cannot receive event "${event}"`,
167
+ kind: "taskTerminal",
168
+ });
169
+ }
170
+ const [created] = await models.inbox.create([{ name: event, payload, requestId, seq: counted.eventSeq, taskId }], { session });
171
+ if (counted.status !== harness_1.HARNESS_TASK_STATUSES.waiting ||
172
+ counted.waiting?.kind !== harness_1.HARNESS_WAIT_KINDS.event ||
173
+ counted.waiting.key !== event) {
174
+ return { event: created, isWoken: false };
175
+ }
176
+ const woken = await models.task.updateOne({ _id: taskId, status: harness_1.HARNESS_TASK_STATUSES.waiting }, { $set: { status: harness_1.HARNESS_TASK_STATUSES.pending }, $unset: { waiting: 1 } }, { session });
177
+ return { event: created, isWoken: woken.modifiedCount > 0 };
178
+ };
179
+ exports.appendInboxEvent = appendInboxEvent;
180
+ /**
181
+ * Append an event to a task's inbox and, when the task is waiting on that event name,
182
+ * return it to `pending`, in one transaction. The task row is written every time
183
+ * (`eventSeq`), so a concurrent `rt.waitFor` commit and this send conflict and one retries:
184
+ * neither can miss the other. A repeated `requestId` returns the event sent first.
185
+ * Throws when the task is terminal.
186
+ */
187
+ const sendEventRecords = async ({ event, models, payload, requestId, taskId, }) => {
188
+ const task = await models.task.findExactlyOne({ _id: taskId });
189
+ if (requestId !== undefined) {
190
+ const existing = await models.inbox.findOneOrNone({ requestId, taskId: task._id });
191
+ if (existing) {
192
+ return { event: assertSameEvent(existing, event), isWoken: false };
193
+ }
194
+ }
195
+ const terminalError = (status) => (0, errors_1.harnessError)({
196
+ detail: `Task ${task._id} is already ${status}; it cannot receive event "${event}"`,
197
+ kind: "taskTerminal",
198
+ });
199
+ if (harness_1.HARNESS_TERMINAL_STATUSES.has(task.status)) {
200
+ throw terminalError(task.status);
201
+ }
202
+ try {
203
+ return await (0, transaction_1.inTransaction)((session) => (0, exports.appendInboxEvent)({ event, models, payload, requestId, session, taskId: task._id }));
204
+ }
205
+ catch (error) {
206
+ // A concurrent send with the same requestId won.
207
+ if (requestId !== undefined && (0, commit_1.isDuplicateKeyError)(error)) {
208
+ const existing = await models.inbox.findExactlyOne({ requestId, taskId: task._id });
209
+ return { event: assertSameEvent(existing, event), isWoken: false };
210
+ }
211
+ throw error;
212
+ }
213
+ };
214
+ exports.sendEventRecords = sendEventRecords;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export type { Ask, AskKind, AskResponse, AskValidationError, SimpleCard, SimpleCardButton, } from "@terreno/blocks";
1
2
  export type { FlexibleSchema, JSONValue } from "ai";
2
3
  export { jsonSchema, Output } from "ai";
3
4
  export type { AIAdminAppOptions } from "./aiAdminApp";
@@ -11,17 +12,34 @@ export { compilePrompt, createPrompt, getPrompt, invalidatePromptCache } from ".
11
12
  export { initTracing, shutdownTracing } from "./langfuseTracing";
12
13
  export type { ChatMessage, GetPromptOptions, LangfuseAppOptions, LangfuseCachedPrompt, PaginatedResult, PreparePromptResult, PromptListItem, ScoreSubmission, ScoringFunction, TelemetrySettings, TraceListItem, } from "./langfuseTypes";
13
14
  export { createTelemetryConfig, preparePromptForAI } from "./langfuseVercelAi";
15
+ export { AIDataset } from "./models/aiDataset";
14
16
  export { AIRequest } from "./models/aiRequest";
15
17
  export { FileAttachment } from "./models/fileAttachment";
16
18
  export { GptHistory } from "./models/gptHistory";
17
19
  export { Project } from "./models/project";
20
+ export { AI_OBSERVABILITY_GROUP, observabilityAdminScreens } from "./observability/adminScreens";
21
+ export { LocalDatasetStore } from "./observability/local/datasetStore";
22
+ export { LocalEvaluatorStore } from "./observability/local/evaluatorStore";
23
+ export { LocalExperimentRunner } from "./observability/local/experimentRunner";
24
+ export { createLocalObservabilityBundle, createLocalObservabilityPlugin, } from "./observability/local/localPlugin";
25
+ export { LocalPromptStore } from "./observability/local/promptStore";
26
+ export { LocalReviewStore } from "./observability/local/reviewStore";
27
+ export { LocalScoreSink, LocalTraceSink, LocalTraceStore, MemoryScoreSink, MemoryTraceSink, } from "./observability/local/traceStore";
28
+ export { getObservabilityApp, ObservabilityApp, resetObservabilityApp, } from "./observability/observabilityApp";
29
+ export type { ObservabilityPluginStatus, ObservabilityStatus, PlaygroundAiSource, PlaygroundAiStatus, } from "./observability/status";
30
+ export { buildObservabilityStatus, buildPlaygroundAiStatus, isLocalObservabilityPluginOn, } from "./observability/status";
31
+ export type { ControlPrimary, ObservabilityAiServiceFactory, ObservabilityAppOptions, ObservabilityCapability, ObservabilityControlConfig, ObservabilityGenerateClient, ObservabilityPlugin, ObservabilityRequestAiServiceFactory, PromptRegistry, ReviewQueue, ScoreRecord, ScoreSink, SpanRecord, TraceExportResult, TraceRecord, TraceSink, } from "./observability/types";
32
+ export { DEFAULT_OBSERVABILITY_CONTROL, resolveObservabilityControl, validateObservabilityConfig, } from "./observability/types";
18
33
  export { addAiRequestsExplorerRoutes } from "./routes/aiRequestsExplorer";
19
34
  export { addFileRoutes } from "./routes/files";
20
35
  export { addGptRoutes } from "./routes/gpt";
21
36
  export { addGptHistoryRoutes } from "./routes/gptHistories";
22
37
  export { addMcpRoutes } from "./routes/mcp";
23
38
  export { addProjectRoutes } from "./routes/projects";
39
+ export type { RegisteredDataset } from "./service/aiDatasets";
40
+ export { configureAiDatasets, registerAiDataset } from "./service/aiDatasets";
24
41
  export { AIService, TemperaturePresets } from "./service/aiService";
42
+ export { createAskTools } from "./service/asks";
25
43
  export { FileStorageService } from "./service/fileStorage";
26
44
  export type { ListGeminiApiModelsOptions } from "./service/gemini";
27
45
  export { GEMINI_API_BASE_URL, listGeminiApiModels, normalizeGeminiModelId, } from "./service/gemini";
@@ -29,7 +47,7 @@ export { getMCPTools } from "./service/getMCPTools";
29
47
  export { MCPService } from "./service/mcpService";
30
48
  export type { ParseFailure, ParseResult, ParseSuccess } from "./service/parseAiJson";
31
49
  export { normalizeLlmJsonTextForStructuredOutput, parseAiJson, } from "./service/parseAiJson";
32
- export { CONTENT_SUMMARY_PROMPT, DEFAULT_GPT_MEMORY, JSON_VALUE_SYSTEM_PROMPT, REMIX_PROMPT, TITLE_GENERATION_PROMPT, TRANSLATION_PROMPT, } from "./service/prompts";
50
+ export { COMPACT_SURFACE_SYSTEM_PROMPT, CONTENT_SUMMARY_PROMPT, DEFAULT_GPT_MEMORY, JSON_VALUE_SYSTEM_PROMPT, REMIX_PROMPT, TERRENO_ASKS_SYSTEM_PROMPT, TITLE_GENERATION_PROMPT, TRANSLATION_PROMPT, } from "./service/prompts";
33
51
  export type { CreateVertexProviderOptions, ListEnabledVertexModelsOptions, TerrenoVertexProvider, VerifyVertexModelsOptions, VertexLanguageModelProvider, VertexModelAvailability, } from "./service/vertex";
34
52
  export { assertVertexModelsEnabled, createVertexProvider, DEFAULT_VERTEX_LOCATION, isVertexModelAllowed, listEnabledVertexModels, normalizeVertexModelId, verifyVertexModelsEnabled, } from "./service/vertex";
35
53
  export type { WebSearchProvider, WebSearchResult } from "./service/webSearchTool";
package/dist/index.js CHANGED
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.DEFAULT_VERTEX_LOCATION = exports.createVertexProvider = exports.assertVertexModelsEnabled = exports.TRANSLATION_PROMPT = exports.TITLE_GENERATION_PROMPT = exports.REMIX_PROMPT = exports.JSON_VALUE_SYSTEM_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.parseAiJson = exports.normalizeLlmJsonTextForStructuredOutput = exports.MCPService = exports.getMCPTools = exports.normalizeGeminiModelId = exports.listGeminiApiModels = exports.GEMINI_API_BASE_URL = exports.FileStorageService = exports.TemperaturePresets = exports.AIService = exports.addProjectRoutes = exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = exports.addAiRequestsExplorerRoutes = exports.Project = exports.GptHistory = exports.FileAttachment = exports.AIRequest = exports.preparePromptForAI = exports.createTelemetryConfig = exports.shutdownTracing = exports.initTracing = exports.invalidatePromptCache = exports.getPrompt = exports.createPrompt = exports.compilePrompt = exports.shutdownLangfuseClient = exports.isLangfuseInitialized = exports.initLangfuseClient = exports.getLangfuseClient = exports.setCached = exports.LangfuseCache = exports.invalidateCache = exports.getCached = exports.LangfuseApp = exports.AiApp = exports.AIAdminApp = exports.Output = exports.jsonSchema = void 0;
18
- exports.verifyVertexModelsEnabled = exports.normalizeVertexModelId = exports.listEnabledVertexModels = exports.isVertexModelAllowed = void 0;
17
+ exports.addAiRequestsExplorerRoutes = exports.validateObservabilityConfig = exports.resolveObservabilityControl = exports.DEFAULT_OBSERVABILITY_CONTROL = exports.isLocalObservabilityPluginOn = exports.buildPlaygroundAiStatus = exports.buildObservabilityStatus = exports.resetObservabilityApp = exports.ObservabilityApp = exports.getObservabilityApp = exports.MemoryTraceSink = exports.MemoryScoreSink = exports.LocalTraceStore = exports.LocalTraceSink = exports.LocalScoreSink = exports.LocalReviewStore = exports.LocalPromptStore = exports.createLocalObservabilityPlugin = exports.createLocalObservabilityBundle = exports.LocalExperimentRunner = exports.LocalEvaluatorStore = exports.LocalDatasetStore = exports.observabilityAdminScreens = exports.AI_OBSERVABILITY_GROUP = exports.Project = exports.GptHistory = exports.FileAttachment = exports.AIRequest = exports.AIDataset = exports.preparePromptForAI = exports.createTelemetryConfig = exports.shutdownTracing = exports.initTracing = exports.invalidatePromptCache = exports.getPrompt = exports.createPrompt = exports.compilePrompt = exports.shutdownLangfuseClient = exports.isLangfuseInitialized = exports.initLangfuseClient = exports.getLangfuseClient = exports.setCached = exports.LangfuseCache = exports.invalidateCache = exports.getCached = exports.LangfuseApp = exports.AiApp = exports.AIAdminApp = exports.Output = exports.jsonSchema = void 0;
18
+ exports.verifyVertexModelsEnabled = exports.normalizeVertexModelId = exports.listEnabledVertexModels = exports.isVertexModelAllowed = exports.DEFAULT_VERTEX_LOCATION = exports.createVertexProvider = exports.assertVertexModelsEnabled = exports.TRANSLATION_PROMPT = exports.TITLE_GENERATION_PROMPT = exports.TERRENO_ASKS_SYSTEM_PROMPT = exports.REMIX_PROMPT = exports.JSON_VALUE_SYSTEM_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.COMPACT_SURFACE_SYSTEM_PROMPT = exports.parseAiJson = exports.normalizeLlmJsonTextForStructuredOutput = exports.MCPService = exports.getMCPTools = exports.normalizeGeminiModelId = exports.listGeminiApiModels = exports.GEMINI_API_BASE_URL = exports.FileStorageService = exports.createAskTools = exports.TemperaturePresets = exports.AIService = exports.registerAiDataset = exports.configureAiDatasets = exports.addProjectRoutes = exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = void 0;
19
19
  var ai_1 = require("ai");
20
20
  Object.defineProperty(exports, "jsonSchema", { enumerable: true, get: function () { return ai_1.jsonSchema; } });
21
21
  Object.defineProperty(exports, "Output", { enumerable: true, get: function () { return ai_1.Output; } });
@@ -46,6 +46,8 @@ Object.defineProperty(exports, "shutdownTracing", { enumerable: true, get: funct
46
46
  var langfuseVercelAi_1 = require("./langfuseVercelAi");
47
47
  Object.defineProperty(exports, "createTelemetryConfig", { enumerable: true, get: function () { return langfuseVercelAi_1.createTelemetryConfig; } });
48
48
  Object.defineProperty(exports, "preparePromptForAI", { enumerable: true, get: function () { return langfuseVercelAi_1.preparePromptForAI; } });
49
+ var aiDataset_1 = require("./models/aiDataset");
50
+ Object.defineProperty(exports, "AIDataset", { enumerable: true, get: function () { return aiDataset_1.AIDataset; } });
49
51
  var aiRequest_1 = require("./models/aiRequest");
50
52
  Object.defineProperty(exports, "AIRequest", { enumerable: true, get: function () { return aiRequest_1.AIRequest; } });
51
53
  var fileAttachment_1 = require("./models/fileAttachment");
@@ -54,6 +56,40 @@ var gptHistory_1 = require("./models/gptHistory");
54
56
  Object.defineProperty(exports, "GptHistory", { enumerable: true, get: function () { return gptHistory_1.GptHistory; } });
55
57
  var project_1 = require("./models/project");
56
58
  Object.defineProperty(exports, "Project", { enumerable: true, get: function () { return project_1.Project; } });
59
+ var adminScreens_1 = require("./observability/adminScreens");
60
+ Object.defineProperty(exports, "AI_OBSERVABILITY_GROUP", { enumerable: true, get: function () { return adminScreens_1.AI_OBSERVABILITY_GROUP; } });
61
+ Object.defineProperty(exports, "observabilityAdminScreens", { enumerable: true, get: function () { return adminScreens_1.observabilityAdminScreens; } });
62
+ var datasetStore_1 = require("./observability/local/datasetStore");
63
+ Object.defineProperty(exports, "LocalDatasetStore", { enumerable: true, get: function () { return datasetStore_1.LocalDatasetStore; } });
64
+ var evaluatorStore_1 = require("./observability/local/evaluatorStore");
65
+ Object.defineProperty(exports, "LocalEvaluatorStore", { enumerable: true, get: function () { return evaluatorStore_1.LocalEvaluatorStore; } });
66
+ var experimentRunner_1 = require("./observability/local/experimentRunner");
67
+ Object.defineProperty(exports, "LocalExperimentRunner", { enumerable: true, get: function () { return experimentRunner_1.LocalExperimentRunner; } });
68
+ var localPlugin_1 = require("./observability/local/localPlugin");
69
+ Object.defineProperty(exports, "createLocalObservabilityBundle", { enumerable: true, get: function () { return localPlugin_1.createLocalObservabilityBundle; } });
70
+ Object.defineProperty(exports, "createLocalObservabilityPlugin", { enumerable: true, get: function () { return localPlugin_1.createLocalObservabilityPlugin; } });
71
+ var promptStore_1 = require("./observability/local/promptStore");
72
+ Object.defineProperty(exports, "LocalPromptStore", { enumerable: true, get: function () { return promptStore_1.LocalPromptStore; } });
73
+ var reviewStore_1 = require("./observability/local/reviewStore");
74
+ Object.defineProperty(exports, "LocalReviewStore", { enumerable: true, get: function () { return reviewStore_1.LocalReviewStore; } });
75
+ var traceStore_1 = require("./observability/local/traceStore");
76
+ Object.defineProperty(exports, "LocalScoreSink", { enumerable: true, get: function () { return traceStore_1.LocalScoreSink; } });
77
+ Object.defineProperty(exports, "LocalTraceSink", { enumerable: true, get: function () { return traceStore_1.LocalTraceSink; } });
78
+ Object.defineProperty(exports, "LocalTraceStore", { enumerable: true, get: function () { return traceStore_1.LocalTraceStore; } });
79
+ Object.defineProperty(exports, "MemoryScoreSink", { enumerable: true, get: function () { return traceStore_1.MemoryScoreSink; } });
80
+ Object.defineProperty(exports, "MemoryTraceSink", { enumerable: true, get: function () { return traceStore_1.MemoryTraceSink; } });
81
+ var observabilityApp_1 = require("./observability/observabilityApp");
82
+ Object.defineProperty(exports, "getObservabilityApp", { enumerable: true, get: function () { return observabilityApp_1.getObservabilityApp; } });
83
+ Object.defineProperty(exports, "ObservabilityApp", { enumerable: true, get: function () { return observabilityApp_1.ObservabilityApp; } });
84
+ Object.defineProperty(exports, "resetObservabilityApp", { enumerable: true, get: function () { return observabilityApp_1.resetObservabilityApp; } });
85
+ var status_1 = require("./observability/status");
86
+ Object.defineProperty(exports, "buildObservabilityStatus", { enumerable: true, get: function () { return status_1.buildObservabilityStatus; } });
87
+ Object.defineProperty(exports, "buildPlaygroundAiStatus", { enumerable: true, get: function () { return status_1.buildPlaygroundAiStatus; } });
88
+ Object.defineProperty(exports, "isLocalObservabilityPluginOn", { enumerable: true, get: function () { return status_1.isLocalObservabilityPluginOn; } });
89
+ var types_1 = require("./observability/types");
90
+ Object.defineProperty(exports, "DEFAULT_OBSERVABILITY_CONTROL", { enumerable: true, get: function () { return types_1.DEFAULT_OBSERVABILITY_CONTROL; } });
91
+ Object.defineProperty(exports, "resolveObservabilityControl", { enumerable: true, get: function () { return types_1.resolveObservabilityControl; } });
92
+ Object.defineProperty(exports, "validateObservabilityConfig", { enumerable: true, get: function () { return types_1.validateObservabilityConfig; } });
57
93
  var aiRequestsExplorer_1 = require("./routes/aiRequestsExplorer");
58
94
  Object.defineProperty(exports, "addAiRequestsExplorerRoutes", { enumerable: true, get: function () { return aiRequestsExplorer_1.addAiRequestsExplorerRoutes; } });
59
95
  var files_1 = require("./routes/files");
@@ -66,9 +102,14 @@ var mcp_1 = require("./routes/mcp");
66
102
  Object.defineProperty(exports, "addMcpRoutes", { enumerable: true, get: function () { return mcp_1.addMcpRoutes; } });
67
103
  var projects_1 = require("./routes/projects");
68
104
  Object.defineProperty(exports, "addProjectRoutes", { enumerable: true, get: function () { return projects_1.addProjectRoutes; } });
105
+ var aiDatasets_1 = require("./service/aiDatasets");
106
+ Object.defineProperty(exports, "configureAiDatasets", { enumerable: true, get: function () { return aiDatasets_1.configureAiDatasets; } });
107
+ Object.defineProperty(exports, "registerAiDataset", { enumerable: true, get: function () { return aiDatasets_1.registerAiDataset; } });
69
108
  var aiService_1 = require("./service/aiService");
70
109
  Object.defineProperty(exports, "AIService", { enumerable: true, get: function () { return aiService_1.AIService; } });
71
110
  Object.defineProperty(exports, "TemperaturePresets", { enumerable: true, get: function () { return aiService_1.TemperaturePresets; } });
111
+ var asks_1 = require("./service/asks");
112
+ Object.defineProperty(exports, "createAskTools", { enumerable: true, get: function () { return asks_1.createAskTools; } });
72
113
  var fileStorage_1 = require("./service/fileStorage");
73
114
  Object.defineProperty(exports, "FileStorageService", { enumerable: true, get: function () { return fileStorage_1.FileStorageService; } });
74
115
  var gemini_1 = require("./service/gemini");
@@ -83,10 +124,12 @@ var parseAiJson_1 = require("./service/parseAiJson");
83
124
  Object.defineProperty(exports, "normalizeLlmJsonTextForStructuredOutput", { enumerable: true, get: function () { return parseAiJson_1.normalizeLlmJsonTextForStructuredOutput; } });
84
125
  Object.defineProperty(exports, "parseAiJson", { enumerable: true, get: function () { return parseAiJson_1.parseAiJson; } });
85
126
  var prompts_1 = require("./service/prompts");
127
+ Object.defineProperty(exports, "COMPACT_SURFACE_SYSTEM_PROMPT", { enumerable: true, get: function () { return prompts_1.COMPACT_SURFACE_SYSTEM_PROMPT; } });
86
128
  Object.defineProperty(exports, "CONTENT_SUMMARY_PROMPT", { enumerable: true, get: function () { return prompts_1.CONTENT_SUMMARY_PROMPT; } });
87
129
  Object.defineProperty(exports, "DEFAULT_GPT_MEMORY", { enumerable: true, get: function () { return prompts_1.DEFAULT_GPT_MEMORY; } });
88
130
  Object.defineProperty(exports, "JSON_VALUE_SYSTEM_PROMPT", { enumerable: true, get: function () { return prompts_1.JSON_VALUE_SYSTEM_PROMPT; } });
89
131
  Object.defineProperty(exports, "REMIX_PROMPT", { enumerable: true, get: function () { return prompts_1.REMIX_PROMPT; } });
132
+ Object.defineProperty(exports, "TERRENO_ASKS_SYSTEM_PROMPT", { enumerable: true, get: function () { return prompts_1.TERRENO_ASKS_SYSTEM_PROMPT; } });
90
133
  Object.defineProperty(exports, "TITLE_GENERATION_PROMPT", { enumerable: true, get: function () { return prompts_1.TITLE_GENERATION_PROMPT; } });
91
134
  Object.defineProperty(exports, "TRANSLATION_PROMPT", { enumerable: true, get: function () { return prompts_1.TRANSLATION_PROMPT; } });
92
135
  var vertex_1 = require("./service/vertex");