@retinue/agentkit 0.1.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 (405) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +310 -0
  3. package/dist/adapters/bullmq/consumer.d.ts +33 -0
  4. package/dist/adapters/bullmq/consumer.js +41 -0
  5. package/dist/adapters/bullmq/dispatcher.d.ts +74 -0
  6. package/dist/adapters/bullmq/dispatcher.js +160 -0
  7. package/dist/adapters/bullmq/export.d.ts +31 -0
  8. package/dist/adapters/bullmq/export.js +53 -0
  9. package/dist/adapters/bullmq/extraction.d.ts +42 -0
  10. package/dist/adapters/bullmq/extraction.js +63 -0
  11. package/dist/adapters/bullmq/index.d.ts +13 -0
  12. package/dist/adapters/bullmq/index.js +13 -0
  13. package/dist/adapters/bullmq/lock.d.ts +77 -0
  14. package/dist/adapters/bullmq/lock.js +126 -0
  15. package/dist/adapters/bullmq/queue.d.ts +50 -0
  16. package/dist/adapters/bullmq/queue.js +81 -0
  17. package/dist/adapters/memory/artifact-exports.d.ts +11 -0
  18. package/dist/adapters/memory/artifact-exports.js +102 -0
  19. package/dist/adapters/memory/artifacts.d.ts +15 -0
  20. package/dist/adapters/memory/artifacts.js +134 -0
  21. package/dist/adapters/memory/blobs.d.ts +7 -0
  22. package/dist/adapters/memory/blobs.js +27 -0
  23. package/dist/adapters/memory/evaluation.d.ts +18 -0
  24. package/dist/adapters/memory/evaluation.js +148 -0
  25. package/dist/adapters/memory/files.d.ts +27 -0
  26. package/dist/adapters/memory/files.js +0 -0
  27. package/dist/adapters/memory/flows.d.ts +16 -0
  28. package/dist/adapters/memory/flows.js +117 -0
  29. package/dist/adapters/memory/hitl.d.ts +9 -0
  30. package/dist/adapters/memory/hitl.js +130 -0
  31. package/dist/adapters/memory/idempotency.d.ts +13 -0
  32. package/dist/adapters/memory/idempotency.js +32 -0
  33. package/dist/adapters/memory/index.d.ts +39 -0
  34. package/dist/adapters/memory/index.js +107 -0
  35. package/dist/adapters/memory/knowledge.d.ts +43 -0
  36. package/dist/adapters/memory/knowledge.js +248 -0
  37. package/dist/adapters/memory/mcp.d.ts +9 -0
  38. package/dist/adapters/memory/mcp.js +37 -0
  39. package/dist/adapters/memory/message-store.d.ts +17 -0
  40. package/dist/adapters/memory/message-store.js +70 -0
  41. package/dist/adapters/memory/principal-memory.d.ts +7 -0
  42. package/dist/adapters/memory/principal-memory.js +83 -0
  43. package/dist/adapters/memory/runtime.d.ts +29 -0
  44. package/dist/adapters/memory/runtime.js +0 -0
  45. package/dist/adapters/memory/sessions.d.ts +29 -0
  46. package/dist/adapters/memory/sessions.js +0 -0
  47. package/dist/adapters/memory/skills.d.ts +10 -0
  48. package/dist/adapters/memory/skills.js +41 -0
  49. package/dist/adapters/memory/thread-summary.d.ts +7 -0
  50. package/dist/adapters/memory/thread-summary.js +29 -0
  51. package/dist/adapters/memory/usage-limits.d.ts +13 -0
  52. package/dist/adapters/memory/usage-limits.js +72 -0
  53. package/dist/adapters/memory/usage.d.ts +16 -0
  54. package/dist/adapters/memory/usage.js +279 -0
  55. package/dist/adapters/otel/index.d.ts +111 -0
  56. package/dist/adapters/otel/index.js +133 -0
  57. package/dist/adapters/postgres/artifact-exports.d.ts +12 -0
  58. package/dist/adapters/postgres/artifact-exports.js +117 -0
  59. package/dist/adapters/postgres/artifacts.d.ts +16 -0
  60. package/dist/adapters/postgres/artifacts.js +172 -0
  61. package/dist/adapters/postgres/checkpoint-store.d.ts +16 -0
  62. package/dist/adapters/postgres/checkpoint-store.js +34 -0
  63. package/dist/adapters/postgres/config.d.ts +15 -0
  64. package/dist/adapters/postgres/config.js +187 -0
  65. package/dist/adapters/postgres/conversation-store.d.ts +4 -0
  66. package/dist/adapters/postgres/conversation-store.js +82 -0
  67. package/dist/adapters/postgres/evaluation.d.ts +17 -0
  68. package/dist/adapters/postgres/evaluation.js +193 -0
  69. package/dist/adapters/postgres/file-content.d.ts +30 -0
  70. package/dist/adapters/postgres/file-content.js +111 -0
  71. package/dist/adapters/postgres/files.d.ts +19 -0
  72. package/dist/adapters/postgres/files.js +209 -0
  73. package/dist/adapters/postgres/flows.d.ts +20 -0
  74. package/dist/adapters/postgres/flows.js +206 -0
  75. package/dist/adapters/postgres/hitl.d.ts +5 -0
  76. package/dist/adapters/postgres/hitl.js +247 -0
  77. package/dist/adapters/postgres/index.d.ts +35 -0
  78. package/dist/adapters/postgres/index.js +35 -0
  79. package/dist/adapters/postgres/knowledge.d.ts +48 -0
  80. package/dist/adapters/postgres/knowledge.js +255 -0
  81. package/dist/adapters/postgres/memory.d.ts +14 -0
  82. package/dist/adapters/postgres/memory.js +194 -0
  83. package/dist/adapters/postgres/message-store.d.ts +11 -0
  84. package/dist/adapters/postgres/message-store.js +145 -0
  85. package/dist/adapters/postgres/migrations.d.ts +69 -0
  86. package/dist/adapters/postgres/migrations.js +1594 -0
  87. package/dist/adapters/postgres/pg-executor.d.ts +19 -0
  88. package/dist/adapters/postgres/pg-executor.js +32 -0
  89. package/dist/adapters/postgres/retention.d.ts +26 -0
  90. package/dist/adapters/postgres/retention.js +59 -0
  91. package/dist/adapters/postgres/rollups.d.ts +17 -0
  92. package/dist/adapters/postgres/rollups.js +267 -0
  93. package/dist/adapters/postgres/run-coordinator.d.ts +5 -0
  94. package/dist/adapters/postgres/run-coordinator.js +98 -0
  95. package/dist/adapters/postgres/run-event-log.d.ts +26 -0
  96. package/dist/adapters/postgres/run-event-log.js +30 -0
  97. package/dist/adapters/postgres/run-store.d.ts +4 -0
  98. package/dist/adapters/postgres/run-store.js +199 -0
  99. package/dist/adapters/postgres/schema.d.ts +39 -0
  100. package/dist/adapters/postgres/schema.js +70 -0
  101. package/dist/adapters/postgres/session-state.d.ts +7 -0
  102. package/dist/adapters/postgres/session-state.js +99 -0
  103. package/dist/adapters/postgres/sql.d.ts +8 -0
  104. package/dist/adapters/postgres/sql.js +2 -0
  105. package/dist/adapters/postgres/transaction.d.ts +37 -0
  106. package/dist/adapters/postgres/transaction.js +93 -0
  107. package/dist/adapters/postgres/unit-of-work.d.ts +18 -0
  108. package/dist/adapters/postgres/unit-of-work.js +8 -0
  109. package/dist/adapters/postgres/usage-limits.d.ts +15 -0
  110. package/dist/adapters/postgres/usage-limits.js +136 -0
  111. package/dist/adapters/postgres/usage.d.ts +15 -0
  112. package/dist/adapters/postgres/usage.js +226 -0
  113. package/dist/adapters/redis/index.d.ts +9 -0
  114. package/dist/adapters/redis/index.js +9 -0
  115. package/dist/adapters/redis/realtime.d.ts +74 -0
  116. package/dist/adapters/redis/realtime.js +112 -0
  117. package/dist/adapters/supabase/index.d.ts +88 -0
  118. package/dist/adapters/supabase/index.js +84 -0
  119. package/dist/adapters/supabase/realtime.d.ts +30 -0
  120. package/dist/adapters/supabase/realtime.js +53 -0
  121. package/dist/adapters/supabase/rls.d.ts +99 -0
  122. package/dist/adapters/supabase/rls.js +216 -0
  123. package/dist/adapters/supabase/storage.d.ts +50 -0
  124. package/dist/adapters/supabase/storage.js +207 -0
  125. package/dist/agents/agent.d.ts +66 -0
  126. package/dist/agents/agent.js +209 -0
  127. package/dist/agents/define.d.ts +21 -0
  128. package/dist/agents/define.js +63 -0
  129. package/dist/agents/engine.d.ts +98 -0
  130. package/dist/agents/engine.js +462 -0
  131. package/dist/agents/index.d.ts +50 -0
  132. package/dist/agents/index.js +17 -0
  133. package/dist/artifacts/index.d.ts +114 -0
  134. package/dist/artifacts/index.js +219 -0
  135. package/dist/authorization/index.d.ts +76 -0
  136. package/dist/authorization/index.js +76 -0
  137. package/dist/capabilities/index.d.ts +120 -0
  138. package/dist/capabilities/index.js +167 -0
  139. package/dist/capabilities/runtime.d.ts +89 -0
  140. package/dist/capabilities/runtime.js +84 -0
  141. package/dist/citations/index.d.ts +161 -0
  142. package/dist/citations/index.js +182 -0
  143. package/dist/context/assembler.d.ts +82 -0
  144. package/dist/context/assembler.js +129 -0
  145. package/dist/context/compaction.d.ts +45 -0
  146. package/dist/context/compaction.js +55 -0
  147. package/dist/context/index.d.ts +75 -0
  148. package/dist/context/index.js +17 -0
  149. package/dist/core/content-parts.d.ts +194 -0
  150. package/dist/core/content-parts.js +23 -0
  151. package/dist/core/context.d.ts +51 -0
  152. package/dist/core/context.js +9 -0
  153. package/dist/core/env.d.ts +25 -0
  154. package/dist/core/env.js +41 -0
  155. package/dist/core/errors.d.ts +30 -0
  156. package/dist/core/errors.js +65 -0
  157. package/dist/core/events.d.ts +139 -0
  158. package/dist/core/events.js +99 -0
  159. package/dist/core/ids.d.ts +52 -0
  160. package/dist/core/ids.js +13 -0
  161. package/dist/core/index.d.ts +9 -0
  162. package/dist/core/index.js +9 -0
  163. package/dist/core/tokens.d.ts +22 -0
  164. package/dist/core/tokens.js +22 -0
  165. package/dist/core/validation.d.ts +34 -0
  166. package/dist/core/validation.js +176 -0
  167. package/dist/documents/extraction.d.ts +121 -0
  168. package/dist/documents/extraction.js +293 -0
  169. package/dist/documents/index.d.ts +199 -0
  170. package/dist/documents/index.js +65 -0
  171. package/dist/documents/parsers/pdf.d.ts +47 -0
  172. package/dist/documents/parsers/pdf.js +508 -0
  173. package/dist/documents/parsers/text.d.ts +59 -0
  174. package/dist/documents/parsers/text.js +325 -0
  175. package/dist/documents/read-tool.d.ts +52 -0
  176. package/dist/documents/read-tool.js +109 -0
  177. package/dist/documents/render.d.ts +29 -0
  178. package/dist/documents/render.js +59 -0
  179. package/dist/documents/vision.d.ts +159 -0
  180. package/dist/documents/vision.js +214 -0
  181. package/dist/entries/adapters-bullmq.d.ts +8 -0
  182. package/dist/entries/adapters-bullmq.js +8 -0
  183. package/dist/entries/adapters-otel.d.ts +13 -0
  184. package/dist/entries/adapters-otel.js +13 -0
  185. package/dist/entries/adapters-postgres.d.ts +10 -0
  186. package/dist/entries/adapters-postgres.js +10 -0
  187. package/dist/entries/adapters-redis.d.ts +3 -0
  188. package/dist/entries/adapters-redis.js +3 -0
  189. package/dist/entries/context.d.ts +20 -0
  190. package/dist/entries/context.js +20 -0
  191. package/dist/entries/flows.d.ts +15 -0
  192. package/dist/entries/flows.js +15 -0
  193. package/dist/entries/hitl.d.ts +10 -0
  194. package/dist/entries/hitl.js +10 -0
  195. package/dist/entries/knowledge.d.ts +18 -0
  196. package/dist/entries/knowledge.js +19 -0
  197. package/dist/entries/mcp.d.ts +10 -0
  198. package/dist/entries/mcp.js +10 -0
  199. package/dist/entries/observability.d.ts +14 -0
  200. package/dist/entries/observability.js +16 -0
  201. package/dist/entries/persistence.d.ts +11 -0
  202. package/dist/entries/persistence.js +11 -0
  203. package/dist/entries/providers.d.ts +14 -0
  204. package/dist/entries/providers.js +14 -0
  205. package/dist/entries/runtime.d.ts +13 -0
  206. package/dist/entries/runtime.js +13 -0
  207. package/dist/entries/server.d.ts +24 -0
  208. package/dist/entries/server.js +24 -0
  209. package/dist/entries/tools.d.ts +21 -0
  210. package/dist/entries/tools.js +21 -0
  211. package/dist/entries/usage.d.ts +10 -0
  212. package/dist/entries/usage.js +10 -0
  213. package/dist/evaluation/gate.d.ts +168 -0
  214. package/dist/evaluation/gate.js +180 -0
  215. package/dist/evaluation/graders.d.ts +125 -0
  216. package/dist/evaluation/graders.js +203 -0
  217. package/dist/evaluation/index.d.ts +120 -0
  218. package/dist/evaluation/index.js +183 -0
  219. package/dist/evaluation/judge.d.ts +75 -0
  220. package/dist/evaluation/judge.js +111 -0
  221. package/dist/export/index.d.ts +162 -0
  222. package/dist/export/index.js +363 -0
  223. package/dist/export/markdown.d.ts +19 -0
  224. package/dist/export/markdown.js +29 -0
  225. package/dist/export/pdf.d.ts +73 -0
  226. package/dist/export/pdf.js +407 -0
  227. package/dist/files/context.d.ts +97 -0
  228. package/dist/files/context.js +185 -0
  229. package/dist/files/index.d.ts +210 -0
  230. package/dist/files/index.js +338 -0
  231. package/dist/files/read-tool.d.ts +81 -0
  232. package/dist/files/read-tool.js +163 -0
  233. package/dist/files/turn-parts.d.ts +96 -0
  234. package/dist/files/turn-parts.js +171 -0
  235. package/dist/flows/index.d.ts +270 -0
  236. package/dist/flows/index.js +62 -0
  237. package/dist/flows/interpreter.d.ts +146 -0
  238. package/dist/flows/interpreter.js +426 -0
  239. package/dist/flows/runner.d.ts +145 -0
  240. package/dist/flows/runner.js +270 -0
  241. package/dist/graphql/index.d.ts +8 -0
  242. package/dist/graphql/index.js +8 -0
  243. package/dist/graphql/resolvers.d.ts +237 -0
  244. package/dist/graphql/resolvers.js +253 -0
  245. package/dist/graphql/schema.d.ts +11 -0
  246. package/dist/graphql/schema.js +258 -0
  247. package/dist/graphql/sse.d.ts +77 -0
  248. package/dist/graphql/sse.js +100 -0
  249. package/dist/hitl/approved-execution.d.ts +127 -0
  250. package/dist/hitl/approved-execution.js +177 -0
  251. package/dist/hitl/index.d.ts +79 -0
  252. package/dist/hitl/index.js +12 -0
  253. package/dist/hitl/service.d.ts +221 -0
  254. package/dist/hitl/service.js +268 -0
  255. package/dist/idempotency/index.d.ts +70 -0
  256. package/dist/idempotency/index.js +59 -0
  257. package/dist/index.d.ts +103 -0
  258. package/dist/index.js +60 -0
  259. package/dist/knowledge/chunking.d.ts +57 -0
  260. package/dist/knowledge/chunking.js +158 -0
  261. package/dist/knowledge/index.d.ts +119 -0
  262. package/dist/knowledge/index.js +166 -0
  263. package/dist/knowledge/retrieval.d.ts +146 -0
  264. package/dist/knowledge/retrieval.js +170 -0
  265. package/dist/loadtest/harness.d.ts +168 -0
  266. package/dist/loadtest/harness.js +507 -0
  267. package/dist/loadtest/index.d.ts +13 -0
  268. package/dist/loadtest/index.js +13 -0
  269. package/dist/loadtest/injection.d.ts +89 -0
  270. package/dist/loadtest/injection.js +147 -0
  271. package/dist/loadtest/metrics.d.ts +197 -0
  272. package/dist/loadtest/metrics.js +160 -0
  273. package/dist/loadtest/runbooks.d.ts +28 -0
  274. package/dist/loadtest/runbooks.js +159 -0
  275. package/dist/loadtest/scenario.d.ts +104 -0
  276. package/dist/loadtest/scenario.js +208 -0
  277. package/dist/mcp/egress.d.ts +53 -0
  278. package/dist/mcp/egress.js +115 -0
  279. package/dist/mcp/index.d.ts +93 -0
  280. package/dist/mcp/index.js +33 -0
  281. package/dist/mcp/provider.d.ts +62 -0
  282. package/dist/mcp/provider.js +0 -0
  283. package/dist/models/index.d.ts +98 -0
  284. package/dist/models/index.js +74 -0
  285. package/dist/models/pricing.d.ts +24 -0
  286. package/dist/models/pricing.js +37 -0
  287. package/dist/models/provider-factory.d.ts +31 -0
  288. package/dist/models/provider-factory.js +67 -0
  289. package/dist/models/streaming.d.ts +145 -0
  290. package/dist/models/streaming.js +272 -0
  291. package/dist/models/vision.d.ts +38 -0
  292. package/dist/models/vision.js +62 -0
  293. package/dist/persistence/index.d.ts +1654 -0
  294. package/dist/persistence/index.js +226 -0
  295. package/dist/principal-memory/index.d.ts +106 -0
  296. package/dist/principal-memory/index.js +89 -0
  297. package/dist/retention/index.d.ts +89 -0
  298. package/dist/retention/index.js +70 -0
  299. package/dist/runtime/checkpoint.d.ts +37 -0
  300. package/dist/runtime/checkpoint.js +22 -0
  301. package/dist/runtime/index.d.ts +118 -0
  302. package/dist/runtime/index.js +69 -0
  303. package/dist/runtime/retry.d.ts +95 -0
  304. package/dist/runtime/retry.js +126 -0
  305. package/dist/runtime/serialization.d.ts +85 -0
  306. package/dist/runtime/serialization.js +95 -0
  307. package/dist/runtime/streaming.d.ts +54 -0
  308. package/dist/runtime/streaming.js +115 -0
  309. package/dist/runtime/worker.d.ts +130 -0
  310. package/dist/runtime/worker.js +405 -0
  311. package/dist/security/checklist.d.ts +53 -0
  312. package/dist/security/checklist.js +204 -0
  313. package/dist/security/findings.d.ts +56 -0
  314. package/dist/security/findings.js +168 -0
  315. package/dist/security/index.d.ts +14 -0
  316. package/dist/security/index.js +14 -0
  317. package/dist/security/prompt-safety.d.ts +100 -0
  318. package/dist/security/prompt-safety.js +133 -0
  319. package/dist/server/boot.d.ts +32 -0
  320. package/dist/server/boot.js +36 -0
  321. package/dist/server/cli-worker.d.ts +37 -0
  322. package/dist/server/cli-worker.js +151 -0
  323. package/dist/server/cli.d.ts +27 -0
  324. package/dist/server/cli.js +74 -0
  325. package/dist/server/config.d.ts +42 -0
  326. package/dist/server/config.js +127 -0
  327. package/dist/server/health.d.ts +59 -0
  328. package/dist/server/health.js +90 -0
  329. package/dist/server/host.d.ts +39 -0
  330. package/dist/server/host.js +124 -0
  331. package/dist/server/index.d.ts +15 -0
  332. package/dist/server/index.js +15 -0
  333. package/dist/server/main.d.ts +16 -0
  334. package/dist/server/main.js +31 -0
  335. package/dist/server/sse-route.d.ts +21 -0
  336. package/dist/server/sse-route.js +282 -0
  337. package/dist/skills/index.d.ts +67 -0
  338. package/dist/skills/index.js +31 -0
  339. package/dist/skills/resolver.d.ts +54 -0
  340. package/dist/skills/resolver.js +121 -0
  341. package/dist/teams/index.d.ts +93 -0
  342. package/dist/teams/index.js +207 -0
  343. package/dist/telemetry/index.d.ts +157 -0
  344. package/dist/telemetry/index.js +71 -0
  345. package/dist/telemetry/instrument.d.ts +108 -0
  346. package/dist/telemetry/instrument.js +232 -0
  347. package/dist/telemetry/log-events.d.ts +17 -0
  348. package/dist/telemetry/log-events.js +58 -0
  349. package/dist/telemetry/metrics.d.ts +123 -0
  350. package/dist/telemetry/metrics.js +135 -0
  351. package/dist/telemetry/noop.d.ts +39 -0
  352. package/dist/telemetry/noop.js +143 -0
  353. package/dist/telemetry/redaction.d.ts +64 -0
  354. package/dist/telemetry/redaction.js +153 -0
  355. package/dist/telemetry/spans.d.ts +56 -0
  356. package/dist/telemetry/spans.js +78 -0
  357. package/dist/telemetry/trace-context.d.ts +55 -0
  358. package/dist/telemetry/trace-context.js +60 -0
  359. package/dist/toolkit/compute.d.ts +53 -0
  360. package/dist/toolkit/compute.js +152 -0
  361. package/dist/toolkit/data.d.ts +98 -0
  362. package/dist/toolkit/data.js +235 -0
  363. package/dist/toolkit/http.d.ts +113 -0
  364. package/dist/toolkit/http.js +205 -0
  365. package/dist/toolkit/index.d.ts +21 -0
  366. package/dist/toolkit/index.js +17 -0
  367. package/dist/toolkit/web.d.ts +107 -0
  368. package/dist/toolkit/web.js +147 -0
  369. package/dist/tools/define.d.ts +25 -0
  370. package/dist/tools/define.js +45 -0
  371. package/dist/tools/delegating.d.ts +132 -0
  372. package/dist/tools/delegating.js +211 -0
  373. package/dist/tools/index.d.ts +129 -0
  374. package/dist/tools/index.js +33 -0
  375. package/dist/tools/library/compute.d.ts +11 -0
  376. package/dist/tools/library/compute.js +46 -0
  377. package/dist/tools/library/data.d.ts +16 -0
  378. package/dist/tools/library/data.js +92 -0
  379. package/dist/tools/library/http.d.ts +28 -0
  380. package/dist/tools/library/http.js +71 -0
  381. package/dist/tools/library/index.d.ts +97 -0
  382. package/dist/tools/library/index.js +134 -0
  383. package/dist/tools/library/knowledge.d.ts +39 -0
  384. package/dist/tools/library/knowledge.js +58 -0
  385. package/dist/tools/library/web.d.ts +19 -0
  386. package/dist/tools/library/web.js +65 -0
  387. package/dist/tools/meta-tools.d.ts +19 -0
  388. package/dist/tools/meta-tools.js +36 -0
  389. package/dist/tools/registry.d.ts +146 -0
  390. package/dist/tools/registry.js +291 -0
  391. package/dist/usage/index.d.ts +105 -0
  392. package/dist/usage/index.js +20 -0
  393. package/dist/usage/quota.d.ts +258 -0
  394. package/dist/usage/quota.js +510 -0
  395. package/dist/usage/recorder.d.ts +29 -0
  396. package/dist/usage/recorder.js +96 -0
  397. package/dist/usage/rollups.d.ts +121 -0
  398. package/dist/usage/rollups.js +157 -0
  399. package/dist/worker/export.d.ts +57 -0
  400. package/dist/worker/export.js +81 -0
  401. package/dist/worker/extraction.d.ts +57 -0
  402. package/dist/worker/extraction.js +84 -0
  403. package/dist/worker/main.d.ts +103 -0
  404. package/dist/worker/main.js +159 -0
  405. package/package.json +187 -0
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Default agent engine — `docs/03-intelligence-runtime.md`.
3
+ *
4
+ * The concrete model loop that plugs into the durable worker's `AgentEngine` slot. It resolves the
5
+ * agent's model, assembles the system prompt + history, exposes the authorized tools, and drives one
6
+ * turn through the neutral `streamModelTurn` primitive (which owns the AI SDK), mapping its chunks to
7
+ * the platform's typed `RunEvent`s. Transient provider failures are retried Claude-style — but only
8
+ * before any output has streamed, so a retry never duplicates a partial answer; tool side effects
9
+ * stay safe via the registry's idempotency keys.
10
+ *
11
+ * **Human-in-the-loop.** With `approvals` wired, the engine owns the two ends of the approval
12
+ * loop that `docs/04` describes and nothing implemented:
13
+ *
14
+ * 1. *Before the turn*, a decided approval is executed — the stored tool and the stored input, never a
15
+ * regenerated call — and the model is told what ran.
16
+ * 2. *During the turn*, every tool call is routed through the loop, so a gated call that has no
17
+ * approval raises a durable one and the run pauses into `waiting-for-approval` instead of looping
18
+ * on a refusal the model cannot resolve.
19
+ */
20
+ import type { ExecutionContext } from "../core/context.js";
21
+ import type { RunId, TenantId } from "../core/ids.js";
22
+ import type { ModelDefinition, ModelTurnRequest, ModelTurnTool, NeutralStreamChunk, NeutralUsage, ResolvedModel, TurnMessage } from "../models/index.js";
23
+ import { type AgentEngine, type RetryPolicy, type Run } from "../runtime/index.js";
24
+ import type { PendingQuestion, RunApprovals } from "../hitl/index.js";
25
+ import type { CitationEmitter } from "../citations/index.js";
26
+ import type { AgentManifest } from "./index.js";
27
+ /** A model resolved for a turn: the opaque handle plus what the engine needs to attribute usage. */
28
+ export type ResolvedModelInfo = {
29
+ readonly model: ResolvedModel;
30
+ readonly modelId: string;
31
+ readonly currency?: string;
32
+ /** Optional cost function (minor units) from the model's pricing, used to bill each turn. */
33
+ readonly price?: (usage: NeutralUsage) => number;
34
+ /**
35
+ * The definition this model resolved from, so its declared limits can actually be applied (#160).
36
+ *
37
+ * Optional for compatibility with existing resolvers, and absent means "no declared ceiling" rather than
38
+ * "unbounded by policy" — the agent's own limit still applies.
39
+ */
40
+ readonly definition?: ModelDefinition;
41
+ };
42
+ export type DefaultEngineDeps = {
43
+ /** Load the manifest the run executes (by agent id + version), so history is never rewritten. */
44
+ loadManifest: (input: {
45
+ agentId: string;
46
+ version: number;
47
+ context: ExecutionContext;
48
+ }) => Promise<AgentManifest>;
49
+ resolveModel: (manifest: AgentManifest, context: ExecutionContext) => ResolvedModelInfo;
50
+ /** Conversation history as neutral turn messages, oldest first. */
51
+ loadHistory: (context: ExecutionContext, run: Run) => Promise<readonly TurnMessage[]>;
52
+ /** The tools the model may call this turn (already permission-filtered / guarded on execute). */
53
+ buildTools?: (context: ExecutionContext, manifest: AgentManifest) => Promise<readonly ModelTurnTool[]>;
54
+ /** System prompt; defaults to the manifest instructions. */
55
+ systemPrompt?: (manifest: AgentManifest, context: ExecutionContext) => Promise<string> | string;
56
+ /**
57
+ * The approval loop. Absent means no HITL: tool calls go straight to `buildTools`' own `execute`,
58
+ * which is how every caller behaved before this existed.
59
+ *
60
+ * Present means the loop owns tool execution for the turn — deliberately, and not as a layer on top
61
+ * of the caller's `execute`. A gated call has to be *routed* through the loop rather than merely
62
+ * observed after the fact, because by the time a refusal has been thrown there is nothing left to
63
+ * pause on.
64
+ */
65
+ readonly approvals?: RunApprovals;
66
+ /**
67
+ * The question side of resumption — #163.
68
+ *
69
+ * Optional and symmetrical with `approvals`. Without it a run that parked on a question resumes with no idea
70
+ * it was answered, and the model asks the same question again — the person picks an option and gets the
71
+ * picker back. `approvals` has had a resume path from the start; this is the half that was missing.
72
+ */
73
+ readonly questions?: {
74
+ answered(input: {
75
+ tenantId: TenantId;
76
+ runId: RunId;
77
+ }): Promise<PendingQuestion | null>;
78
+ };
79
+ /**
80
+ * Turns a tool's citation candidates into citation parts — #165.
81
+ *
82
+ * Optional. `createCitationEmitter`, `CitationPart`, the frontend's renderer and the groundedness graders all
83
+ * existed, and **nothing put a citation into a run**: there was no path from a tool that read a passage to a
84
+ * part on the message. Supply this and a tool returning `{ citations: [...] }` produces citation parts;
85
+ * leave it out and the field is ignored, exactly as before.
86
+ *
87
+ * The emitter, not a raw mapper, because emission is where the access check lives: a citation carries an
88
+ * excerpt, so emitting one the reader may not see leaks the text and not merely the existence of the source.
89
+ */
90
+ readonly citations?: CitationEmitter;
91
+ readonly retry?: RetryPolicy;
92
+ readonly sleep?: (ms: number) => Promise<void>;
93
+ readonly now?: () => number;
94
+ /** The streaming primitive. Defaults to the models-layer `streamModelTurn`; overridden in tests. */
95
+ readonly streamTurn?: (req: ModelTurnRequest) => AsyncIterable<NeutralStreamChunk>;
96
+ };
97
+ export declare const createDefaultEngine: (deps: DefaultEngineDeps) => AgentEngine;
98
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1,462 @@
1
+ /**
2
+ * Default agent engine — `docs/03-intelligence-runtime.md`.
3
+ *
4
+ * The concrete model loop that plugs into the durable worker's `AgentEngine` slot. It resolves the
5
+ * agent's model, assembles the system prompt + history, exposes the authorized tools, and drives one
6
+ * turn through the neutral `streamModelTurn` primitive (which owns the AI SDK), mapping its chunks to
7
+ * the platform's typed `RunEvent`s. Transient provider failures are retried Claude-style — but only
8
+ * before any output has streamed, so a retry never duplicates a partial answer; tool side effects
9
+ * stay safe via the registry's idempotency keys.
10
+ *
11
+ * **Human-in-the-loop.** With `approvals` wired, the engine owns the two ends of the approval
12
+ * loop that `docs/04` describes and nothing implemented:
13
+ *
14
+ * 1. *Before the turn*, a decided approval is executed — the stored tool and the stored input, never a
15
+ * regenerated call — and the model is told what ran.
16
+ * 2. *During the turn*, every tool call is routed through the loop, so a gated call that has no
17
+ * approval raises a durable one and the run pauses into `waiting-for-approval` instead of looping
18
+ * on a refusal the model cannot resolve.
19
+ */
20
+ import { AgentPlatformError, isAgentPlatformError } from "../core/errors.js";
21
+ import { asId } from "../core/ids.js";
22
+ import { streamModelTurn } from "../models/index.js";
23
+ import { decideRetry, deriveRunMessageId, toPlatformError, DEFAULT_RETRY_POLICY, } from "../runtime/index.js";
24
+ import { isQuestionPending } from "../hitl/service.js";
25
+ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
26
+ /**
27
+ * Take citation candidates off a tool's result — #165.
28
+ *
29
+ * A recognised `citations` field, read and **removed** before the result reaches the model. Removed because the
30
+ * model does not need it: it has the tool's answer, and handing it a parallel list of chunk ids and excerpts
31
+ * invites it to paraphrase provenance in prose, which is the unverifiable thing citations exist to replace.
32
+ *
33
+ * A non-array `citations`, or one with unusable entries, is left alone rather than rejected — a tool whose real
34
+ * answer happens to have a field of that name is not misconfigured, and failing its call would be a worse
35
+ * outcome than ignoring a field.
36
+ */
37
+ const collectCitations = (result, into) => {
38
+ if (typeof result !== "object" || result === null || !("citations" in result))
39
+ return result;
40
+ const { citations, ...rest } = result;
41
+ if (!Array.isArray(citations))
42
+ return result;
43
+ const usable = citations.filter((c) => typeof c === "object" &&
44
+ c !== null &&
45
+ "origin" in c &&
46
+ typeof c.excerpt === "string" &&
47
+ typeof c.retrievedAt === "string");
48
+ if (usable.length === 0)
49
+ return result;
50
+ into.push(...usable);
51
+ return rest;
52
+ };
53
+ /**
54
+ * Recognise a parked question in whatever shape it reached us — #163.
55
+ *
56
+ * A tool's throw arrives as an `AgentPlatformError` when nothing is between the engine and the tool, and as a
57
+ * flattened `PlatformError` when the registry caught it. One reader for both, so the two paths cannot come to
58
+ * disagree about what a parked question looks like.
59
+ *
60
+ * Returns `null` for anything else, which the caller rethrows — a question is the one refusal that is not a
61
+ * failure, and everything else must stay one.
62
+ */
63
+ const questionMarker = (thrown, toolName) => {
64
+ const error = isAgentPlatformError(thrown)
65
+ ? { code: thrown.code, details: thrown.details }
66
+ : typeof thrown === "object" && thrown !== null && "code" in thrown
67
+ ? thrown
68
+ : null;
69
+ if (error === null || !isQuestionPending(error))
70
+ return null;
71
+ const interactionId = error.details?.["interactionId"];
72
+ // No id means no way to route the answer back, so it is a broken signal rather than a parked run. Rethrown
73
+ // as an ordinary failure: parking a run nobody can ever un-park is the worse outcome.
74
+ if (typeof interactionId !== "string" || interactionId === "")
75
+ return null;
76
+ return {
77
+ interactionId,
78
+ // Returned to the model in place of a result, mirroring the approval marker exactly.
79
+ marker: {
80
+ status: "question_pending",
81
+ interactionId,
82
+ message: `${toolName} has put a question to the person. The run is paused; do not retry or guess an answer.`,
83
+ },
84
+ };
85
+ };
86
+ export const createDefaultEngine = (deps) => {
87
+ const policy = deps.retry ?? DEFAULT_RETRY_POLICY;
88
+ const sleep = deps.sleep ?? defaultSleep;
89
+ const now = deps.now ?? Date.now;
90
+ const streamTurn = deps.streamTurn ?? streamModelTurn;
91
+ return {
92
+ async *run({ run, context, signal }) {
93
+ const manifest = await deps.loadManifest({ agentId: run.agentId, version: run.agentVersion, context });
94
+ const resolved = deps.resolveModel(manifest, context);
95
+ const system = (await (deps.systemPrompt?.(manifest, context) ?? manifest.instructions)) || undefined;
96
+ const history = await deps.loadHistory(context, run);
97
+ const declared = deps.buildTools ? await deps.buildTools(context, manifest) : [];
98
+ const maxSteps = manifest.limits?.maxSteps ?? 8;
99
+ const messageId = deriveRunMessageId(run.id);
100
+ // A decision taken while the run was parked. Executed before the model gets another turn, so the
101
+ // approved side effect happens even if the model would never ask for it again — and so the model
102
+ // sees the outcome in its history rather than re-requesting something already done.
103
+ const messages = [...history];
104
+ if (deps.approvals) {
105
+ const resumed = await deps.approvals.resume(context, run.id);
106
+ for (const event of approvalEvents(resumed, messageId, messages))
107
+ yield event;
108
+ }
109
+ // The answer to a question this run asked, if it was parked on one. Same shape as the approval
110
+ // resumption above: an event for the durable record, and a history line so the model stops asking.
111
+ if (deps.questions) {
112
+ const answered = await deps.questions.answered({ tenantId: context.tenantId, runId: run.id });
113
+ for (const event of questionEvents(answered, messages))
114
+ yield event;
115
+ }
116
+ /**
117
+ * The tools the model may call, with execution routed through the approval loop.
118
+ *
119
+ * The caller's own `execute` is replaced rather than wrapped: the loop calls the same registry,
120
+ * and running both would mean two executions of one call — the exact duplicate the approval
121
+ * exists to prevent.
122
+ */
123
+ let pendingApproval = null;
124
+ /**
125
+ * A question a tool put to a person this turn — #163.
126
+ *
127
+ * Tracked exactly like `pendingApproval`, and for the same reason: the run has to stop, and it has to
128
+ * stop on an *event* the worker understands rather than on an error the model would try to work around.
129
+ * Before this, `question.requested` was in the event union and handled by the worker, and no code path in
130
+ * the platform could produce one — so a tool that raised a question had it stored durably while the run
131
+ * carried on and completed. The person's answer arrived for a run that was already over.
132
+ */
133
+ let pendingQuestion = null;
134
+ /**
135
+ * Citation candidates a tool handed back this turn, waiting for the claims they ground — #165.
136
+ *
137
+ * Buffered rather than emitted on the spot, because `supports` names the *text parts* a citation grounds
138
+ * and those do not exist yet: the tool reads the passage, and only then does the model write the sentence
139
+ * the passage supports. Emitting at the tool call would produce citations supporting nothing.
140
+ */
141
+ const pendingCitations = [];
142
+ const approvals = deps.approvals;
143
+ /**
144
+ * Every tool is wrapped, whether or not an approval gate is configured.
145
+ *
146
+ * This used to wrap only when `deps.approvals` was set, which meant a deployment with no gate had no
147
+ * interception point at all — and a question raised by one of its tools could not be noticed. The gate
148
+ * decides *approvals*; parking a run on a question is not its business.
149
+ */
150
+ const tools = declared.map((t) => ({
151
+ ...t,
152
+ execute: async (input) => {
153
+ if (approvals === undefined) {
154
+ try {
155
+ return collectCitations(await t.execute(input), pendingCitations);
156
+ }
157
+ catch (thrown) {
158
+ const parked = questionMarker(thrown, t.name);
159
+ if (parked === null)
160
+ throw thrown;
161
+ pendingQuestion = parked.interactionId;
162
+ return parked.marker;
163
+ }
164
+ }
165
+ const outcome = await approvals.runTool(context, run.id, { name: t.name, input });
166
+ if (outcome.outcome === "approval-requested") {
167
+ pendingApproval = outcome.approval.id;
168
+ // Returned to the model, not thrown. The tool call is a real part of the record with a
169
+ // real result, and the run pauses on the event below rather than on an error the model
170
+ // would try to work around.
171
+ return {
172
+ status: "approval_required",
173
+ interactionId: outcome.approval.id,
174
+ summary: outcome.approval.summary,
175
+ message: `${t.name} needs human approval before it can run. The run is paused; do not retry.`,
176
+ };
177
+ }
178
+ if (!outcome.result.ok) {
179
+ // The registry flattens a delegate's throw into a result, so the question arrives here as a code.
180
+ const parked = questionMarker(outcome.result.error, t.name);
181
+ if (parked !== null) {
182
+ pendingQuestion = parked.interactionId;
183
+ return parked.marker;
184
+ }
185
+ throw new AgentPlatformError(outcome.result.error);
186
+ }
187
+ return collectCitations(outcome.result.data, pendingCitations);
188
+ },
189
+ }));
190
+ let attempt = 1;
191
+ for (;;) {
192
+ let emitted = 0;
193
+ const textParts = new Map();
194
+ const controller = new AbortController();
195
+ try {
196
+ /**
197
+ * Generation parameters, from the resolved definition with the agent as a **ceiling-respecting**
198
+ * override (#160).
199
+ *
200
+ * `maxOutputTokens` takes the *lower* of what the agent asks for and what the model's definition
201
+ * allows — otherwise the definition's limit still would not be a limit, only a default an agent could
202
+ * raise. That was the substance of the bug: the field existed, was set deliberately per model, and
203
+ * bounded nothing.
204
+ */
205
+ const limit = (() => {
206
+ const declared = resolved.definition?.limits?.maxOutputTokens;
207
+ const asked = manifest.limits?.maxOutputTokens;
208
+ if (declared === undefined)
209
+ return asked;
210
+ return asked === undefined ? declared : Math.min(asked, declared);
211
+ })();
212
+ const chunks = streamTurn({
213
+ model: resolved.model,
214
+ ...(system ? { system } : {}),
215
+ messages,
216
+ /**
217
+ * What the resolved model accepts — #185.
218
+ *
219
+ * Passed only when the definition says. `ResolvedModel.definition` is optional, and a caller that
220
+ * did not supply one has not told us the model is text-only — so the check is skipped rather than
221
+ * refusing every attachment from every host that has not been updated.
222
+ *
223
+ * `resolveModel` already refuses to hand out a model missing a *required* modality. This catches the
224
+ * case that one cannot see: a model resolved for a text conversation, and an image arriving later in
225
+ * it.
226
+ */
227
+ ...(resolved.definition === undefined
228
+ ? {}
229
+ : { modelModalities: resolved.definition.inputModalities }),
230
+ tools,
231
+ maxSteps,
232
+ abortSignal: controller.signal,
233
+ ...(limit === undefined ? {} : { maxOutputTokens: limit }),
234
+ ...(manifest.limits?.temperature === undefined ? {} : { temperature: manifest.limits.temperature }),
235
+ });
236
+ for await (const chunk of chunks) {
237
+ if (signal.isCancelled()) {
238
+ controller.abort();
239
+ return;
240
+ }
241
+ for (const event of mapChunk(chunk, messageId, resolved, textParts)) {
242
+ emitted += 1;
243
+ yield event;
244
+ }
245
+ // Raised by a tool call this turn. Stop here rather than letting the model keep going: the
246
+ // run is about to be parked, and anything it does now would be work nobody can act on.
247
+ if (pendingApproval !== null) {
248
+ controller.abort();
249
+ yield { type: "approval.requested", interactionId: asId(pendingApproval) };
250
+ return;
251
+ }
252
+ // The same stop, for a question rather than an approval. Checked separately rather than folded into
253
+ // one flag so the emitted event says which kind of answer the run is waiting for — the worker parks
254
+ // it in `waiting-for-question` or `waiting-for-approval` accordingly, and those resume differently.
255
+ if (pendingQuestion !== null) {
256
+ controller.abort();
257
+ yield { type: "question.requested", interactionId: asId(pendingQuestion) };
258
+ return;
259
+ }
260
+ }
261
+ /**
262
+ * Citations last, grounding the claims that were actually written — #165.
263
+ *
264
+ * Here rather than at the tool call because `supports` names text parts, and the model writes them
265
+ * after reading the passage. Every text part of the turn is named: without model-level markers there
266
+ * is no way to know which sentence a given passage supported, and claiming a narrower link would be
267
+ * inventing precision. `docs/06`'s renderer treats a text part as grounded exactly when some citation
268
+ * names it, so this says "these passages support this answer", which is true.
269
+ *
270
+ * After the stream, so a citation cannot appear above text the reader is already looking at — the
271
+ * append-only property `citationViewModel` depends on.
272
+ */
273
+ if (deps.citations !== undefined && pendingCitations.length > 0) {
274
+ const claims = [...textParts.values()].map((t) => t.partId);
275
+ if (claims.length > 0) {
276
+ const emittedCitations = await deps.citations.emit(context, pendingCitations.map((c) => ({ ...c, supports: claims })));
277
+ for (const part of emittedCitations.parts) {
278
+ yield { type: "part.added", messageId, part };
279
+ }
280
+ }
281
+ }
282
+ return; // turn complete
283
+ }
284
+ catch (thrown) {
285
+ const error = toPlatformError(thrown);
286
+ const decision = decideRetry({ error, attempt, policy });
287
+ // Only retry when nothing has streamed yet — otherwise a retry would duplicate output.
288
+ if (emitted > 0 || !decision.retry)
289
+ throw new AgentPlatformError(error, { cause: thrown });
290
+ yield {
291
+ type: "run.retry-pending",
292
+ attempt,
293
+ maxAttempts: policy.maxAttempts,
294
+ nextAttemptAt: new Date(now() + decision.delayMs).toISOString(),
295
+ error,
296
+ };
297
+ await sleep(decision.delayMs);
298
+ attempt += 1;
299
+ }
300
+ }
301
+ },
302
+ };
303
+ };
304
+ /**
305
+ * Turn an answered question into the event and the history line it deserves — #163.
306
+ *
307
+ * Deliberately the same shape as `approvalEvents`, for the same reason it exists: the executed call is stored
308
+ * as run *parts* and `loadHistory` reads conversation *messages*, so without a line here the model resumes
309
+ * knowing nothing. For a question the consequence was sharper than for an approval — it asked again, so the
310
+ * person answered, and got the same picker back.
311
+ *
312
+ * A `user`-role note, matching the approval line: a mid-conversation `system` message is handled
313
+ * inconsistently across providers, and this is not an instruction — it is the person's answer.
314
+ */
315
+ function* questionEvents(answered, messages) {
316
+ if (answered === null || answered.answers === undefined)
317
+ return;
318
+ yield { type: "question.answered", interactionId: answered.id };
319
+ for (const spec of answered.questions) {
320
+ const value = answered.answers[spec.key];
321
+ if (value === undefined)
322
+ continue;
323
+ // An array is rendered as a list rather than joined blind: a multi-select answer whose values contain
324
+ // commas would otherwise read as more choices than were made.
325
+ const rendered = Array.isArray(value) ? value.map((v) => `- ${v}`).join("\n") : String(value);
326
+ messages.push({
327
+ role: "user",
328
+ content: `[answer] ${spec.prompt}\n${rendered}`,
329
+ });
330
+ }
331
+ }
332
+ /**
333
+ * Turn a resumption outcome into the events and the history line it deserves.
334
+ *
335
+ * The events are the durable record — a client refreshing after an approval must see the call that
336
+ * ran. The history line is what stops the model asking again: the executed call is stored as run
337
+ * *parts*, and `loadHistory` reads conversation *messages*, so without a line here the model resumes
338
+ * with no idea the publish happened.
339
+ *
340
+ * It is a plain `user`-role note rather than a `system` one. A system message arriving mid-conversation
341
+ * is handled inconsistently across providers, and the note is not an instruction — it is something the
342
+ * model is being told about the world.
343
+ */
344
+ function* approvalEvents(resumed, messageId, messages) {
345
+ if (resumed.outcome === "none")
346
+ return;
347
+ const { approval } = resumed;
348
+ yield { type: "approval.decided", interactionId: approval.id };
349
+ if (resumed.outcome === "denied") {
350
+ messages.push({ role: "user", content: `[approval] ${approval.toolName} was denied. Do not attempt it again.` });
351
+ return;
352
+ }
353
+ if (resumed.outcome === "expired") {
354
+ messages.push({
355
+ role: "user",
356
+ content: `[approval] the approval for ${approval.toolName} expired before it could run. Ask again if it is still wanted.`,
357
+ });
358
+ return;
359
+ }
360
+ const toolCallId = asId(`approval:${approval.id}`);
361
+ const call = {
362
+ id: `${toolCallId}:call`,
363
+ type: "tool-call",
364
+ schemaVersion: 1,
365
+ createdAt: new Date(0).toISOString(),
366
+ toolCallId,
367
+ toolName: approval.toolName,
368
+ input: approval.normalizedInput,
369
+ };
370
+ yield { type: "tool.started", toolCallId, toolName: approval.toolName };
371
+ yield { type: "part.added", messageId, part: call };
372
+ const outcome = resumed.result.ok ? resumed.result.data : resumed.result.error;
373
+ const result = {
374
+ id: `${toolCallId}:result`,
375
+ type: "tool-result",
376
+ schemaVersion: 1,
377
+ createdAt: new Date(0).toISOString(),
378
+ toolCallId,
379
+ toolName: approval.toolName,
380
+ output: outcome,
381
+ truncated: false,
382
+ };
383
+ yield {
384
+ type: resumed.result.ok ? "tool.completed" : "tool.failed",
385
+ toolCallId,
386
+ toolName: approval.toolName,
387
+ };
388
+ yield { type: "part.added", messageId, part: result };
389
+ messages.push({
390
+ role: "user",
391
+ content: `[approval] ${approval.toolName} was approved and has now run. Result: ${JSON.stringify(outcome)}`,
392
+ });
393
+ }
394
+ /** Map one neutral chunk to zero or more engine events. Mutates `textParts` to accumulate deltas. */
395
+ function* mapChunk(chunk, messageId, resolved, textParts) {
396
+ switch (chunk.type) {
397
+ case "text-delta": {
398
+ const existing = textParts.get(chunk.id);
399
+ const text = (existing?.text ?? "") + chunk.text;
400
+ if (!existing) {
401
+ const partId = `${messageId}:text:${chunk.id}`;
402
+ textParts.set(chunk.id, { partId, text });
403
+ const part = { id: partId, type: "text", schemaVersion: 1, createdAt: new Date(0).toISOString(), text };
404
+ yield { type: "part.added", messageId, part };
405
+ }
406
+ else {
407
+ existing.text = text;
408
+ const part = { id: existing.partId, type: "text", schemaVersion: 1, createdAt: new Date(0).toISOString(), text };
409
+ yield { type: "part.updated", messageId, part };
410
+ }
411
+ return;
412
+ }
413
+ case "tool-call": {
414
+ const part = {
415
+ id: `${chunk.toolCallId}:call`,
416
+ type: "tool-call",
417
+ schemaVersion: 1,
418
+ createdAt: new Date(0).toISOString(),
419
+ toolCallId: asId(chunk.toolCallId),
420
+ toolName: chunk.toolName,
421
+ input: chunk.input,
422
+ };
423
+ yield { type: "tool.started", toolCallId: asId(chunk.toolCallId), toolName: chunk.toolName };
424
+ yield { type: "part.added", messageId, part };
425
+ return;
426
+ }
427
+ case "tool-result": {
428
+ const part = {
429
+ id: `${chunk.toolCallId}:result`,
430
+ type: "tool-result",
431
+ schemaVersion: 1,
432
+ createdAt: new Date(0).toISOString(),
433
+ toolCallId: asId(chunk.toolCallId),
434
+ toolName: chunk.toolName,
435
+ output: chunk.output,
436
+ truncated: false,
437
+ };
438
+ yield { type: "tool.completed", toolCallId: asId(chunk.toolCallId), toolName: chunk.toolName };
439
+ yield { type: "part.added", messageId, part };
440
+ return;
441
+ }
442
+ case "finish": {
443
+ yield {
444
+ type: "usage.updated",
445
+ inputTokens: chunk.usage.inputTokens,
446
+ outputTokens: chunk.usage.outputTokens,
447
+ cachedInputTokens: chunk.usage.cachedInputTokens,
448
+ ...(chunk.usage.reasoningTokens !== undefined ? { reasoningTokens: chunk.usage.reasoningTokens } : {}),
449
+ // Counted at the send site (`nonTextCounts`), carried through so the ledger records it (#185).
450
+ ...(chunk.usage.imageCount !== undefined ? { imageCount: chunk.usage.imageCount } : {}),
451
+ ...(chunk.usage.audioSeconds !== undefined ? { audioSeconds: chunk.usage.audioSeconds } : {}),
452
+ modelId: resolved.modelId,
453
+ currency: resolved.currency ?? "USD",
454
+ costMinorUnits: resolved.price ? resolved.price(chunk.usage) : 0,
455
+ };
456
+ return;
457
+ }
458
+ case "error":
459
+ throw chunk.error instanceof Error ? chunk.error : new Error(String(chunk.error));
460
+ }
461
+ }
462
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Agent manifests — `docs/03-intelligence-runtime.md`.
3
+ *
4
+ * Agents are declarative, stored, versioned and auditable. A run records the manifest
5
+ * version it executed, so editing an agent never rewrites history.
6
+ */
7
+ import type { ModelPolicy } from "../models/index.js";
8
+ import type { ExecutionLimits } from "../runtime/index.js";
9
+ export type ResponseFormat = {
10
+ readonly kind: "text";
11
+ } | {
12
+ readonly kind: "structured";
13
+ readonly schema: unknown;
14
+ };
15
+ export type ToolPolicy = {
16
+ /** Loaded into context up front. Keep small — everything else is discovered lazily. */
17
+ readonly preloaded: readonly string[];
18
+ readonly categories: readonly string[];
19
+ readonly excluded: readonly string[];
20
+ };
21
+ export type SkillPolicy = {
22
+ readonly assigned: readonly string[];
23
+ /** Whether tenant-authored skills may be layered over the built-in set. */
24
+ readonly allowTenantSkills: boolean;
25
+ };
26
+ export type AgentManifest = {
27
+ readonly id: string;
28
+ readonly version: number;
29
+ readonly name: string;
30
+ readonly description: string;
31
+ readonly instructions: string;
32
+ readonly modelPolicy: ModelPolicy;
33
+ readonly responseFormat: ResponseFormat;
34
+ readonly toolPolicy: ToolPolicy;
35
+ readonly skillPolicy: SkillPolicy;
36
+ readonly authorizationPolicyId: string;
37
+ readonly contextProviderIds: readonly string[];
38
+ readonly limits: ExecutionLimits;
39
+ };
40
+ export * from "./engine.js";
41
+ export * from "./define.js";
42
+ /**
43
+ * `agent.js` is deliberately absent — #196.
44
+ *
45
+ * It holds `createAgent`, which builds a provider factory from credentials and therefore needs the six
46
+ * `@ai-sdk/*` packages. Those are optional peers, so anything reachable from the package root must not import
47
+ * them: a consumer using OpenAI would otherwise get a resolution failure for Anthropic. It is exported from the
48
+ * `providers` entry, where the cost is visible in the import path.
49
+ */
50
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Agent manifests — `docs/03-intelligence-runtime.md`.
3
+ *
4
+ * Agents are declarative, stored, versioned and auditable. A run records the manifest
5
+ * version it executed, so editing an agent never rewrites history.
6
+ */
7
+ export * from "./engine.js";
8
+ export * from "./define.js";
9
+ /**
10
+ * `agent.js` is deliberately absent — #196.
11
+ *
12
+ * It holds `createAgent`, which builds a provider factory from credentials and therefore needs the six
13
+ * `@ai-sdk/*` packages. Those are optional peers, so anything reachable from the package root must not import
14
+ * them: a consumer using OpenAI would otherwise get a resolution failure for Anthropic. It is exported from the
15
+ * `providers` entry, where the cost is visible in the import path.
16
+ */
17
+ //# sourceMappingURL=index.js.map