@tanstack/ai 0.42.0 → 0.43.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/README.md +15 -1
  2. package/dist/esm/activities/chat/adapter.js +23 -16
  3. package/dist/esm/activities/chat/adapter.js.map +1 -1
  4. package/dist/esm/activities/chat/agent-loop-strategies.d.ts +5 -36
  5. package/dist/esm/activities/chat/agent-loop-strategies.js +75 -21
  6. package/dist/esm/activities/chat/agent-loop-strategies.js.map +1 -1
  7. package/dist/esm/activities/chat/cancel.d.ts +40 -0
  8. package/dist/esm/activities/chat/cancel.js +54 -0
  9. package/dist/esm/activities/chat/cancel.js.map +1 -0
  10. package/dist/esm/activities/chat/index.d.ts +28 -21
  11. package/dist/esm/activities/chat/index.js +2100 -1813
  12. package/dist/esm/activities/chat/index.js.map +1 -1
  13. package/dist/esm/activities/chat/mcp/manager.d.ts +2 -2
  14. package/dist/esm/activities/chat/mcp/manager.js +90 -77
  15. package/dist/esm/activities/chat/mcp/manager.js.map +1 -1
  16. package/dist/esm/activities/chat/mcp/types.d.ts +2 -2
  17. package/dist/esm/activities/chat/messages.js +397 -346
  18. package/dist/esm/activities/chat/messages.js.map +1 -1
  19. package/dist/esm/activities/chat/middleware/builder.js +17 -15
  20. package/dist/esm/activities/chat/middleware/builder.js.map +1 -1
  21. package/dist/esm/activities/chat/middleware/capabilities.js +78 -43
  22. package/dist/esm/activities/chat/middleware/capabilities.js.map +1 -1
  23. package/dist/esm/activities/chat/middleware/compose.d.ts +94 -1
  24. package/dist/esm/activities/chat/middleware/compose.js +623 -531
  25. package/dist/esm/activities/chat/middleware/compose.js.map +1 -1
  26. package/dist/esm/activities/chat/middleware/define.js +12 -5
  27. package/dist/esm/activities/chat/middleware/define.js.map +1 -1
  28. package/dist/esm/activities/chat/middleware/index.d.ts +5 -1
  29. package/dist/esm/activities/chat/middleware/locks.d.ts +50 -0
  30. package/dist/esm/activities/chat/middleware/locks.js +71 -0
  31. package/dist/esm/activities/chat/middleware/locks.js.map +1 -0
  32. package/dist/esm/activities/chat/middleware/pending-turn.d.ts +15 -0
  33. package/dist/esm/activities/chat/middleware/pending-turn.js +35 -0
  34. package/dist/esm/activities/chat/middleware/pending-turn.js.map +1 -0
  35. package/dist/esm/activities/chat/middleware/run-disconnect.d.ts +23 -0
  36. package/dist/esm/activities/chat/middleware/run-disconnect.js +42 -0
  37. package/dist/esm/activities/chat/middleware/run-disconnect.js.map +1 -0
  38. package/dist/esm/activities/chat/middleware/run-store.d.ts +283 -0
  39. package/dist/esm/activities/chat/middleware/run-store.js +176 -0
  40. package/dist/esm/activities/chat/middleware/run-store.js.map +1 -0
  41. package/dist/esm/activities/chat/middleware/sandbox-runtime.js +14 -8
  42. package/dist/esm/activities/chat/middleware/sandbox-runtime.js.map +1 -1
  43. package/dist/esm/activities/chat/middleware/tool-cache-middleware.js +79 -70
  44. package/dist/esm/activities/chat/middleware/tool-cache-middleware.js.map +1 -1
  45. package/dist/esm/activities/chat/middleware/types.d.ts +59 -2
  46. package/dist/esm/activities/chat/middleware/validate.js +23 -28
  47. package/dist/esm/activities/chat/middleware/validate.js.map +1 -1
  48. package/dist/esm/activities/chat/stream/json-parser.js +39 -25
  49. package/dist/esm/activities/chat/stream/json-parser.js.map +1 -1
  50. package/dist/esm/activities/chat/stream/message-updaters.js +275 -234
  51. package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
  52. package/dist/esm/activities/chat/stream/processor.d.ts +24 -4
  53. package/dist/esm/activities/chat/stream/processor.js +1341 -1542
  54. package/dist/esm/activities/chat/stream/processor.js.map +1 -1
  55. package/dist/esm/activities/chat/stream/strategies.js +69 -53
  56. package/dist/esm/activities/chat/stream/strategies.js.map +1 -1
  57. package/dist/esm/activities/chat/tools/approval-schema.d.ts +19 -0
  58. package/dist/esm/activities/chat/tools/approval-schema.js +117 -0
  59. package/dist/esm/activities/chat/tools/approval-schema.js.map +1 -0
  60. package/dist/esm/activities/chat/tools/lazy-tool-manager.js +164 -191
  61. package/dist/esm/activities/chat/tools/lazy-tool-manager.js.map +1 -1
  62. package/dist/esm/activities/chat/tools/lazy-tools.js +24 -12
  63. package/dist/esm/activities/chat/tools/lazy-tools.js.map +1 -1
  64. package/dist/esm/activities/chat/tools/schema-converter.js +293 -146
  65. package/dist/esm/activities/chat/tools/schema-converter.js.map +1 -1
  66. package/dist/esm/activities/chat/tools/tool-calls.d.ts +18 -2
  67. package/dist/esm/activities/chat/tools/tool-calls.js +522 -531
  68. package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -1
  69. package/dist/esm/activities/chat/tools/tool-definition.d.ts +75 -16
  70. package/dist/esm/activities/chat/tools/tool-definition.js +95 -23
  71. package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -1
  72. package/dist/esm/activities/error-payload.js +85 -47
  73. package/dist/esm/activities/error-payload.js.map +1 -1
  74. package/dist/esm/activities/generateAudio/adapter.js +22 -15
  75. package/dist/esm/activities/generateAudio/adapter.js.map +1 -1
  76. package/dist/esm/activities/generateAudio/index.d.ts +4 -0
  77. package/dist/esm/activities/generateAudio/index.js +141 -105
  78. package/dist/esm/activities/generateAudio/index.js.map +1 -1
  79. package/dist/esm/activities/generateImage/adapter.js +22 -15
  80. package/dist/esm/activities/generateImage/adapter.js.map +1 -1
  81. package/dist/esm/activities/generateImage/index.d.ts +4 -0
  82. package/dist/esm/activities/generateImage/index.js +155 -111
  83. package/dist/esm/activities/generateImage/index.js.map +1 -1
  84. package/dist/esm/activities/generateSpeech/adapter.js +22 -15
  85. package/dist/esm/activities/generateSpeech/adapter.js.map +1 -1
  86. package/dist/esm/activities/generateSpeech/index.d.ts +4 -0
  87. package/dist/esm/activities/generateSpeech/index.js +159 -110
  88. package/dist/esm/activities/generateSpeech/index.js.map +1 -1
  89. package/dist/esm/activities/generateTranscription/adapter.js +22 -15
  90. package/dist/esm/activities/generateTranscription/adapter.js.map +1 -1
  91. package/dist/esm/activities/generateTranscription/index.d.ts +4 -0
  92. package/dist/esm/activities/generateTranscription/index.js +159 -100
  93. package/dist/esm/activities/generateTranscription/index.js.map +1 -1
  94. package/dist/esm/activities/generateVideo/adapter.js +36 -29
  95. package/dist/esm/activities/generateVideo/adapter.js.map +1 -1
  96. package/dist/esm/activities/generateVideo/index.d.ts +143 -19
  97. package/dist/esm/activities/generateVideo/index.js +456 -279
  98. package/dist/esm/activities/generateVideo/index.js.map +1 -1
  99. package/dist/esm/activities/generateVideo/snap.js +60 -48
  100. package/dist/esm/activities/generateVideo/snap.js.map +1 -1
  101. package/dist/esm/activities/index.js +8 -34
  102. package/dist/esm/activities/middleware/index.d.ts +1 -1
  103. package/dist/esm/activities/middleware/run.d.ts +10 -0
  104. package/dist/esm/activities/middleware/run.js +53 -29
  105. package/dist/esm/activities/middleware/run.js.map +1 -1
  106. package/dist/esm/activities/middleware/types.d.ts +44 -6
  107. package/dist/esm/activities/stream-generation-result.d.ts +4 -1
  108. package/dist/esm/activities/stream-generation-result.js +79 -44
  109. package/dist/esm/activities/stream-generation-result.js.map +1 -1
  110. package/dist/esm/activities/summarize/adapter.js +22 -15
  111. package/dist/esm/activities/summarize/adapter.js.map +1 -1
  112. package/dist/esm/activities/summarize/chat-stream-summarize.js +252 -202
  113. package/dist/esm/activities/summarize/chat-stream-summarize.js.map +1 -1
  114. package/dist/esm/activities/summarize/index.d.ts +27 -0
  115. package/dist/esm/activities/summarize/index.js +268 -102
  116. package/dist/esm/activities/summarize/index.js.map +1 -1
  117. package/dist/esm/adapter-internals.d.ts +2 -1
  118. package/dist/esm/adapter-internals.js +4 -11
  119. package/dist/esm/client.d.ts +25 -3
  120. package/dist/esm/client.js +131 -64
  121. package/dist/esm/client.js.map +1 -1
  122. package/dist/esm/custom-events.d.ts +76 -0
  123. package/dist/esm/custom-events.js +37 -0
  124. package/dist/esm/custom-events.js.map +1 -0
  125. package/dist/esm/delivery-detach.d.ts +50 -0
  126. package/dist/esm/delivery-detach.js +71 -0
  127. package/dist/esm/delivery-detach.js.map +1 -0
  128. package/dist/esm/delivery-disconnect.d.ts +62 -0
  129. package/dist/esm/delivery-disconnect.js +81 -0
  130. package/dist/esm/delivery-disconnect.js.map +1 -0
  131. package/dist/esm/extend-adapter.js +19 -17
  132. package/dist/esm/extend-adapter.js.map +1 -1
  133. package/dist/esm/index.d.ts +24 -6
  134. package/dist/esm/index.js +30 -98
  135. package/dist/esm/interrupt-resume.d.ts +71 -0
  136. package/dist/esm/interrupt-resume.js +438 -0
  137. package/dist/esm/interrupt-resume.js.map +1 -0
  138. package/dist/esm/interrupt-serialization.d.ts +12 -0
  139. package/dist/esm/interrupt-serialization.js +178 -0
  140. package/dist/esm/interrupt-serialization.js.map +1 -0
  141. package/dist/esm/interrupts.d.ts +84 -0
  142. package/dist/esm/interrupts.js +31 -0
  143. package/dist/esm/interrupts.js.map +1 -0
  144. package/dist/esm/locks.d.ts +10 -0
  145. package/dist/esm/locks.js +2 -0
  146. package/dist/esm/logger/console-logger.js +101 -78
  147. package/dist/esm/logger/console-logger.js.map +1 -1
  148. package/dist/esm/logger/internal-logger.js +104 -89
  149. package/dist/esm/logger/internal-logger.js.map +1 -1
  150. package/dist/esm/logger/resolve.js +54 -49
  151. package/dist/esm/logger/resolve.js.map +1 -1
  152. package/dist/esm/logger/types.d.ts +1 -1
  153. package/dist/esm/middlewares/content-guard.js +142 -148
  154. package/dist/esm/middlewares/content-guard.js.map +1 -1
  155. package/dist/esm/middlewares/index.js +2 -6
  156. package/dist/esm/middlewares/otel.d.ts +3 -1
  157. package/dist/esm/middlewares/otel.js +599 -732
  158. package/dist/esm/middlewares/otel.js.map +1 -1
  159. package/dist/esm/middlewares/usage-attributes.js +47 -40
  160. package/dist/esm/middlewares/usage-attributes.js.map +1 -1
  161. package/dist/esm/realtime/event-emitter.js +24 -25
  162. package/dist/esm/realtime/event-emitter.js.map +1 -1
  163. package/dist/esm/realtime/index.d.ts +5 -9
  164. package/dist/esm/realtime/index.js +29 -6
  165. package/dist/esm/realtime/index.js.map +1 -1
  166. package/dist/esm/scope.d.ts +47 -0
  167. package/dist/esm/stream-durability.d.ts +171 -0
  168. package/dist/esm/stream-durability.js +295 -0
  169. package/dist/esm/stream-durability.js.map +1 -0
  170. package/dist/esm/stream-to-response.d.ts +178 -13
  171. package/dist/esm/stream-to-response.js +663 -115
  172. package/dist/esm/stream-to-response.js.map +1 -1
  173. package/dist/esm/strip-to-spec-middleware.js +30 -16
  174. package/dist/esm/strip-to-spec-middleware.js.map +1 -1
  175. package/dist/esm/system-prompts.js +27 -21
  176. package/dist/esm/system-prompts.js.map +1 -1
  177. package/dist/esm/tool-registry.js +72 -45
  178. package/dist/esm/tool-registry.js.map +1 -1
  179. package/dist/esm/tools/provider-tool.js +14 -5
  180. package/dist/esm/tools/provider-tool.js.map +1 -1
  181. package/dist/esm/types.d.ts +321 -42
  182. package/dist/esm/types.js +2 -0
  183. package/dist/esm/utilities/ag-ui-wire.js +79 -93
  184. package/dist/esm/utilities/ag-ui-wire.js.map +1 -1
  185. package/dist/esm/utilities/chat-params.d.ts +26 -4
  186. package/dist/esm/utilities/chat-params.js +218 -92
  187. package/dist/esm/utilities/chat-params.js.map +1 -1
  188. package/dist/esm/utilities/errors.js +28 -18
  189. package/dist/esm/utilities/errors.js.map +1 -1
  190. package/dist/esm/utilities/media-prompt.js +46 -41
  191. package/dist/esm/utilities/media-prompt.js.map +1 -1
  192. package/dist/esm/utilities/numbers.js +13 -10
  193. package/dist/esm/utilities/numbers.js.map +1 -1
  194. package/dist/esm/utilities/provider-executed.js +20 -11
  195. package/dist/esm/utilities/provider-executed.js.map +1 -1
  196. package/dist/esm/utilities/sampling-keys.js +31 -19
  197. package/dist/esm/utilities/sampling-keys.js.map +1 -1
  198. package/dist/esm/utilities/tool-result.js +42 -30
  199. package/dist/esm/utilities/tool-result.js.map +1 -1
  200. package/dist/esm/utilities/usage.js +27 -9
  201. package/dist/esm/utilities/usage.js.map +1 -1
  202. package/dist/esm/utils.js +26 -18
  203. package/dist/esm/utils.js.map +1 -1
  204. package/package.json +10 -6
  205. package/skills/ai-core/SKILL.md +69 -18
  206. package/skills/ai-core/adapter-configuration/SKILL.md +44 -21
  207. package/skills/ai-core/adapter-configuration/references/anthropic-adapter.md +1 -3
  208. package/skills/ai-core/adapter-configuration/references/byteplus-adapter.md +148 -0
  209. package/skills/ai-core/adapter-configuration/references/gemini-adapter.md +2 -6
  210. package/skills/ai-core/adapter-configuration/references/groq-adapter.md +2 -6
  211. package/skills/ai-core/adapter-configuration/references/openai-adapter.md +1 -3
  212. package/skills/ai-core/ag-ui-protocol/SKILL.md +1 -1
  213. package/skills/ai-core/chat-experience/SKILL.md +98 -11
  214. package/skills/ai-core/client-persistence/SKILL.md +277 -0
  215. package/skills/ai-core/custom-backend-integration/SKILL.md +1 -1
  216. package/skills/ai-core/debug-logging/SKILL.md +1 -1
  217. package/skills/ai-core/locks/SKILL.md +143 -0
  218. package/skills/ai-core/media-generation/SKILL.md +144 -12
  219. package/skills/ai-core/middleware/SKILL.md +258 -33
  220. package/skills/ai-core/structured-outputs/SKILL.md +1 -1
  221. package/skills/ai-core/tool-calling/SKILL.md +54 -61
  222. package/src/activities/chat/agent-loop-strategies.ts +5 -39
  223. package/src/activities/chat/cancel.ts +81 -0
  224. package/src/activities/chat/index.ts +1091 -200
  225. package/src/activities/chat/mcp/manager.ts +4 -4
  226. package/src/activities/chat/mcp/types.ts +2 -2
  227. package/src/activities/chat/messages.ts +5 -3
  228. package/src/activities/chat/middleware/builder.ts +1 -1
  229. package/src/activities/chat/middleware/compose.ts +186 -9
  230. package/src/activities/chat/middleware/index.ts +26 -0
  231. package/src/activities/chat/middleware/locks.ts +102 -0
  232. package/src/activities/chat/middleware/pending-turn.ts +47 -0
  233. package/src/activities/chat/middleware/run-disconnect.ts +62 -0
  234. package/src/activities/chat/middleware/run-store.ts +412 -0
  235. package/src/activities/chat/middleware/types.ts +62 -1
  236. package/src/activities/chat/stream/processor.ts +189 -5
  237. package/src/activities/chat/tools/approval-schema.ts +205 -0
  238. package/src/activities/chat/tools/tool-calls.ts +106 -13
  239. package/src/activities/chat/tools/tool-definition.ts +210 -39
  240. package/src/activities/generateAudio/index.ts +20 -3
  241. package/src/activities/generateImage/index.ts +20 -3
  242. package/src/activities/generateSpeech/index.ts +25 -3
  243. package/src/activities/generateTranscription/index.ts +26 -3
  244. package/src/activities/generateVideo/index.ts +345 -82
  245. package/src/activities/middleware/index.ts +2 -0
  246. package/src/activities/middleware/run.ts +31 -0
  247. package/src/activities/middleware/types.ts +49 -5
  248. package/src/activities/stream-generation-result.ts +30 -2
  249. package/src/activities/summarize/chat-stream-summarize.ts +5 -0
  250. package/src/activities/summarize/index.ts +200 -10
  251. package/src/adapter-internals.ts +10 -1
  252. package/src/client.ts +244 -0
  253. package/src/custom-events.ts +107 -0
  254. package/src/delivery-detach.ts +72 -0
  255. package/src/delivery-disconnect.ts +84 -0
  256. package/src/index.ts +138 -1
  257. package/src/interrupt-resume.ts +824 -0
  258. package/src/interrupt-serialization.ts +183 -0
  259. package/src/interrupts.ts +146 -0
  260. package/src/locks.ts +17 -0
  261. package/src/logger/types.ts +1 -1
  262. package/src/middlewares/otel.ts +23 -5
  263. package/src/realtime/index.ts +5 -9
  264. package/src/scope.ts +47 -0
  265. package/src/stream-durability.ts +598 -0
  266. package/src/stream-to-response.ts +1051 -95
  267. package/src/strip-to-spec-middleware.ts +3 -3
  268. package/src/types.ts +405 -45
  269. package/src/utilities/chat-params.ts +245 -55
  270. package/dist/esm/activities/index.js.map +0 -1
  271. package/dist/esm/adapter-internals.js.map +0 -1
  272. package/dist/esm/index.js.map +0 -1
  273. package/dist/esm/middlewares/index.js.map +0 -1
@@ -0,0 +1,81 @@
1
+ //#region src/delivery-disconnect.ts
2
+ /**
3
+ * The one-way channel from the durable DELIVERY sink back to the chat run: "your
4
+ * viewer is gone, but you are not."
5
+ *
6
+ * This is the MIRROR of `./delivery-detach.ts`. That module answers a question the
7
+ * sink asks the run (was this abort a detach?); this one delivers a fact the sink
8
+ * learns first and the run cannot observe at all — the response body was
9
+ * cancelled. Both are keyed weakly by the exact stream object `chat()` returned,
10
+ * for the same reason: passing that object to
11
+ * `toServerSentEventsResponse(stream, { durability })` is already mandatory, so it
12
+ * is the one seam an application cannot forget to wire.
13
+ *
14
+ * WHY THE RUN CANNOT JUST WATCH AN ABORT SIGNAL. Before this channel existed, the
15
+ * only way a disconnect reached a run's middleware was for the application to
16
+ * mirror `request.signal` into `chat()`'s `abortController` — which ABORTS THE RUN.
17
+ * For a durable run that is precisely wrong, and wrong in the most expensive
18
+ * direction: `chat()` returns at its `isCancelled()` check immediately after
19
+ * middleware setup, so the harness adapter's `chatStream` is never called and the
20
+ * agent in the freshly-created sandbox is NEVER LAUNCHED. The user re-attaches to
21
+ * an empty log belonging to a run that did nothing, and no takeover can recover it
22
+ * because there is no journal to replay. The application was forced to choose
23
+ * between "the middleware learns about the disconnect" and "the run survives it".
24
+ *
25
+ * So the disconnect travels as a NOTIFICATION rather than a cancellation. The run
26
+ * hands it to whatever subscribed through `RunDisconnectCapability` — bookkeeping
27
+ * only, no teardown — and keeps producing into its still-open durable log, which
28
+ * is exactly what a re-attaching client tails to catch up.
29
+ *
30
+ * DISPATCHED FROM THE TRANSPORT, NOT FROM THE RUN'S UNWINDING. That is what makes
31
+ * it prompt. A run suspended inside a minutes-wide `setup` (cloning a repo into a
32
+ * sandbox) cannot dispatch anything from its own `finally`, because the `finally`
33
+ * is reached only once the generator unwinds — which is what made `detachedSince`
34
+ * land three minutes late instead of immediately.
35
+ */
36
+ /**
37
+ * Per-stream disconnect handlers. Keyed weakly by the stream object, so a stream
38
+ * dropped without ever being consumed takes its entry with it.
39
+ */
40
+ var disconnectHandlers = /* @__PURE__ */ new WeakMap();
41
+ /**
42
+ * Publish `stream`'s disconnect handler. Called by `chat()` on the object it hands
43
+ * back, once per stream.
44
+ *
45
+ * Wired on BOTH streaming paths — `runStreamingText` and
46
+ * `runStreamingStructuredOutput` — since either can be handed to a durable
47
+ * transport helper, matching `publishRunDetachedSignal`.
48
+ *
49
+ * @internal
50
+ */
51
+ function publishRunDisconnectHandler(stream, onDisconnect) {
52
+ disconnectHandlers.set(stream, onDisconnect);
53
+ }
54
+ /**
55
+ * Tell the run behind `stream` that its delivery socket closed.
56
+ *
57
+ * A NO-OP for anything that never published a handler — a hand-rolled iterable, a
58
+ * `chat()` from an older build, a non-object source — so an unknown stream simply
59
+ * keeps today's behavior.
60
+ *
61
+ * NEVER THROWS and never returns a promise to await. This is called from
62
+ * `ReadableStream.cancel()`, whose rejection would surface as an unhandled error
63
+ * on a path where the consumer has already gone away; and the handler's own work
64
+ * is tracked by the run (which awaits it before finishing), not by this call. A
65
+ * throwing handler is swallowed for the same reason `wasRunDetached` swallows: the
66
+ * disconnect path has no second channel to report on.
67
+ *
68
+ * @internal
69
+ */
70
+ function notifyRunDisconnected(stream) {
71
+ if (typeof stream !== "object" || stream === null) return;
72
+ const handler = disconnectHandlers.get(stream);
73
+ if (handler === void 0) return;
74
+ try {
75
+ handler();
76
+ } catch {}
77
+ }
78
+ //#endregion
79
+ export { notifyRunDisconnected, publishRunDisconnectHandler };
80
+
81
+ //# sourceMappingURL=delivery-disconnect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delivery-disconnect.js","names":[],"sources":["../../src/delivery-disconnect.ts"],"sourcesContent":["/**\n * The one-way channel from the durable DELIVERY sink back to the chat run: \"your\n * viewer is gone, but you are not.\"\n *\n * This is the MIRROR of `./delivery-detach.ts`. That module answers a question the\n * sink asks the run (was this abort a detach?); this one delivers a fact the sink\n * learns first and the run cannot observe at all — the response body was\n * cancelled. Both are keyed weakly by the exact stream object `chat()` returned,\n * for the same reason: passing that object to\n * `toServerSentEventsResponse(stream, { durability })` is already mandatory, so it\n * is the one seam an application cannot forget to wire.\n *\n * WHY THE RUN CANNOT JUST WATCH AN ABORT SIGNAL. Before this channel existed, the\n * only way a disconnect reached a run's middleware was for the application to\n * mirror `request.signal` into `chat()`'s `abortController` — which ABORTS THE RUN.\n * For a durable run that is precisely wrong, and wrong in the most expensive\n * direction: `chat()` returns at its `isCancelled()` check immediately after\n * middleware setup, so the harness adapter's `chatStream` is never called and the\n * agent in the freshly-created sandbox is NEVER LAUNCHED. The user re-attaches to\n * an empty log belonging to a run that did nothing, and no takeover can recover it\n * because there is no journal to replay. The application was forced to choose\n * between \"the middleware learns about the disconnect\" and \"the run survives it\".\n *\n * So the disconnect travels as a NOTIFICATION rather than a cancellation. The run\n * hands it to whatever subscribed through `RunDisconnectCapability` — bookkeeping\n * only, no teardown — and keeps producing into its still-open durable log, which\n * is exactly what a re-attaching client tails to catch up.\n *\n * DISPATCHED FROM THE TRANSPORT, NOT FROM THE RUN'S UNWINDING. That is what makes\n * it prompt. A run suspended inside a minutes-wide `setup` (cloning a repo into a\n * sandbox) cannot dispatch anything from its own `finally`, because the `finally`\n * is reached only once the generator unwinds — which is what made `detachedSince`\n * land three minutes late instead of immediately.\n */\n\n/**\n * Per-stream disconnect handlers. Keyed weakly by the stream object, so a stream\n * dropped without ever being consumed takes its entry with it.\n */\nconst disconnectHandlers = new WeakMap<object, () => void>()\n\n/**\n * Publish `stream`'s disconnect handler. Called by `chat()` on the object it hands\n * back, once per stream.\n *\n * Wired on BOTH streaming paths — `runStreamingText` and\n * `runStreamingStructuredOutput` — since either can be handed to a durable\n * transport helper, matching `publishRunDetachedSignal`.\n *\n * @internal\n */\nexport function publishRunDisconnectHandler(\n stream: object,\n onDisconnect: () => void,\n): void {\n disconnectHandlers.set(stream, onDisconnect)\n}\n\n/**\n * Tell the run behind `stream` that its delivery socket closed.\n *\n * A NO-OP for anything that never published a handler — a hand-rolled iterable, a\n * `chat()` from an older build, a non-object source — so an unknown stream simply\n * keeps today's behavior.\n *\n * NEVER THROWS and never returns a promise to await. This is called from\n * `ReadableStream.cancel()`, whose rejection would surface as an unhandled error\n * on a path where the consumer has already gone away; and the handler's own work\n * is tracked by the run (which awaits it before finishing), not by this call. A\n * throwing handler is swallowed for the same reason `wasRunDetached` swallows: the\n * disconnect path has no second channel to report on.\n *\n * @internal\n */\nexport function notifyRunDisconnected(stream: unknown): void {\n if (typeof stream !== 'object' || stream === null) return\n const handler = disconnectHandlers.get(stream)\n if (handler === undefined) return\n try {\n handler()\n } catch {\n // Intentionally empty: see above.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,qCAAqB,IAAI,QAA4B;;;;;;;;;;;AAY3D,SAAgB,4BACd,QACA,cACM;CACN,mBAAmB,IAAI,QAAQ,YAAY;AAC7C;;;;;;;;;;;;;;;;;AAkBA,SAAgB,sBAAsB,QAAuB;CAC3D,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM;CACnD,MAAM,UAAU,mBAAmB,IAAI,MAAM;CAC7C,IAAI,YAAY,KAAA,GAAW;CAC3B,IAAI;EACF,QAAQ;CACV,QAAQ,CAER;AACF"}
@@ -1,21 +1,23 @@
1
+ //#region src/extend-adapter.ts
1
2
  function createModel(name, second) {
2
- if (Array.isArray(second)) {
3
- return { name, input: second, modelOptions: {} };
4
- }
5
- const caps = second;
6
- return {
7
- name,
8
- input: caps.input ?? ["text"],
9
- modelOptions: caps.modelOptions ?? {},
10
- features: caps.features,
11
- tools: caps.tools
12
- };
3
+ if (Array.isArray(second)) return {
4
+ name,
5
+ input: second,
6
+ modelOptions: {}
7
+ };
8
+ const caps = second;
9
+ return {
10
+ name,
11
+ input: caps.input ?? ["text"],
12
+ modelOptions: caps.modelOptions ?? {},
13
+ features: caps.features,
14
+ tools: caps.tools
15
+ };
13
16
  }
14
17
  function extendAdapter(factory, _customModels) {
15
- return factory;
18
+ return factory;
16
19
  }
17
- export {
18
- createModel,
19
- extendAdapter
20
- };
21
- //# sourceMappingURL=extend-adapter.js.map
20
+ //#endregion
21
+ export { createModel, extendAdapter };
22
+
23
+ //# sourceMappingURL=extend-adapter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"extend-adapter.js","sources":["../../src/extend-adapter.ts"],"sourcesContent":["import type { Modality } from './types'\n\n// ===========================\n// Extended Model Definition\n// ===========================\n\n/**\n * Definition for a custom model to add to an adapter.\n *\n * @template TName - The model name as a literal string type\n * @template TInput - Array of supported input modalities\n * @template TOptions - Provider options type for this model\n *\n * @example\n * ```typescript\n * const customModels = [\n * createModel('my-custom-model', ['text', 'image']),\n * ] as const\n * ```\n */\nexport interface ExtendedModelDef<\n TName extends string = string,\n TInput extends ReadonlyArray<Modality> = ReadonlyArray<Modality>,\n TOptions = unknown,\n TFeatures extends ReadonlyArray<string> = ReadonlyArray<string>,\n TTools extends ReadonlyArray<string> = ReadonlyArray<string>,\n> {\n /** The model name identifier */\n name: TName\n /** Supported input modalities for this model */\n input: TInput\n /** Type brand for provider options - use `{} as YourOptionsType` */\n modelOptions: TOptions\n /** Optional declared features (e.g. 'reasoning', 'structured_outputs') */\n features?: TFeatures\n /** Optional declared provider tools (e.g. 'web_search') */\n tools?: TTools\n}\n\n/** Capability bag accepted by the object form of `createModel`. */\nexport interface ModelCapabilities<\n TInput extends ReadonlyArray<Modality> = ReadonlyArray<Modality>,\n TFeatures extends ReadonlyArray<string> = ReadonlyArray<string>,\n TTools extends ReadonlyArray<string> = ReadonlyArray<string>,\n TOptions = unknown,\n> {\n input?: TInput\n features?: TFeatures\n tools?: TTools\n modelOptions?: TOptions\n}\n\n/**\n * Creates a custom model definition for use with `extendAdapter`.\n *\n * This is a helper function that provides proper type inference without\n * requiring manual `as const` casts on individual properties.\n *\n * @template TName - The model name (inferred from argument)\n * @template TInput - The input modalities array (inferred from argument)\n *\n * @param name - The model name identifier (literal string)\n * @param input - Array of supported input modalities\n * @returns A properly typed model definition for use with `extendAdapter`\n *\n * @example\n * ```typescript\n * import { extendAdapter, createModel } from '@tanstack/ai'\n * import { openaiText } from '@tanstack/ai-openai'\n *\n * // Define custom models with full type inference\n * const customModels = [\n * createModel('my-fine-tuned-gpt4', ['text', 'image']),\n * createModel('local-llama', ['text']),\n * ] as const\n *\n * const myOpenai = extendAdapter(openaiText, customModels)\n * ```\n *\n * @example\n * ```typescript\n * // Capabilities object form - declare features and provider tools\n * const reasoner = createModel('reasoner', {\n * input: ['text'],\n * features: ['reasoning', 'structured_outputs'],\n * tools: ['web_search'],\n * })\n * ```\n */\n// Overload 1 — legacy positional input array (unchanged behavior)\nexport function createModel<\n const TName extends string,\n const TInput extends ReadonlyArray<Modality>,\n>(name: TName, input: TInput): ExtendedModelDef<TName, TInput>\n// Overload 2 — capabilities object\nexport function createModel<\n const TName extends string,\n const TCaps extends ModelCapabilities,\n>(\n name: TName,\n capabilities: TCaps,\n): ExtendedModelDef<\n TName,\n TCaps['input'] extends ReadonlyArray<Modality>\n ? TCaps['input']\n : ReadonlyArray<Modality>,\n TCaps['modelOptions'],\n TCaps['features'] extends ReadonlyArray<string>\n ? TCaps['features']\n : ReadonlyArray<string>,\n TCaps['tools'] extends ReadonlyArray<string>\n ? TCaps['tools']\n : ReadonlyArray<string>\n>\n// Implementation\nexport function createModel(\n name: string,\n second: ReadonlyArray<Modality> | ModelCapabilities,\n): ExtendedModelDef {\n if (Array.isArray(second)) {\n return { name, input: second, modelOptions: {} }\n }\n const caps = second as ModelCapabilities\n return {\n name,\n input: caps.input ?? (['text'] as ReadonlyArray<Modality>),\n modelOptions: caps.modelOptions ?? {},\n features: caps.features,\n tools: caps.tools,\n }\n}\n\n// ===========================\n// Type Extraction Utilities\n// ===========================\n\n/**\n * Extract the model name union from an array of model definitions.\n */\ntype ExtractCustomModelNames<TDefs extends ReadonlyArray<ExtendedModelDef>> =\n TDefs[number]['name']\n\n// ===========================\n// Factory Type Inference\n// ===========================\n\n/**\n * The widest factory shape `extendAdapter` accepts: any function taking a\n * model as its first parameter. Parameters are contravariant, so `never`\n * params and an `unknown` return accept every factory without resorting\n * to `any`.\n */\ntype AnyAdapterFactory = (model: never, ...args: Array<never>) => unknown\n\n/**\n * Infer the model parameter type from an adapter factory function.\n * For generic functions like `<T extends Union>(model: T)`, this gets `T` which\n * TypeScript treats as the constraint union when used in parameter position.\n */\ntype InferFactoryModels<TFactory> = TFactory extends (\n model: infer TModel,\n ...args: Array<never>\n) => unknown\n ? TModel extends string\n ? TModel\n : string\n : string\n\n/**\n * Infer the adapter return type from a factory function.\n */\ntype InferAdapterReturn<TFactory> = TFactory extends (\n ...args: Array<never>\n) => infer TReturn\n ? TReturn\n : never\n\n/**\n * Extracts all parameter types after the model parameter from a factory,\n * preserving labels and optionality (e.g. `[apiKey: string, config?: C]`).\n * Note: overloaded factories resolve against their last overload (a\n * `Parameters` limitation).\n */\ntype InferRestArgs<TFactory extends AnyAdapterFactory> =\n Parameters<TFactory> extends [unknown?, ...infer TRest] ? TRest : []\n\n/**\n * The factory signature produced by `extendAdapter`: accepts both original\n * and custom model names while preserving all remaining parameters and the\n * return type of the original factory.\n */\ntype ExtendedFactory<\n TFactory extends AnyAdapterFactory,\n TDefs extends ReadonlyArray<ExtendedModelDef>,\n> = (\n model: InferFactoryModels<TFactory> | ExtractCustomModelNames<TDefs>,\n ...args: InferRestArgs<TFactory>\n) => InferAdapterReturn<TFactory>\n\n// ===========================\n// extendAdapter Function\n// ===========================\n\n/**\n * Extends an existing adapter factory with additional custom models.\n *\n * The extended adapter accepts both original models (with full original type inference)\n * and custom models (with types from your definitions).\n *\n * At runtime, this simply passes through to the original factory - no validation is performed.\n * The original factory's signature is fully preserved, including any config parameters.\n *\n * @param factory - The original adapter factory function (e.g., `openaiText`, `anthropicText`)\n * @param models - Array of custom model definitions with `name` and `input`\n * @returns A new factory function that accepts both original and custom models\n *\n * @example\n * ```typescript\n * import { extendAdapter, createModel } from '@tanstack/ai'\n * import { openaiText } from '@tanstack/ai-openai'\n *\n * // Define custom models\n * const customModels = [\n * createModel('my-fine-tuned-gpt4', ['text', 'image']),\n * createModel('local-llama', ['text']),\n * ] as const\n *\n * // Create extended adapter\n * const myOpenai = extendAdapter(openaiText, customModels)\n *\n * // Use with original models - full type inference preserved\n * const gpt4 = myOpenai('gpt-4o')\n *\n * // Use with custom models\n * const custom = myOpenai('my-fine-tuned-gpt4')\n *\n * // Type error: 'invalid-model' is not a valid model\n * // myOpenai('invalid-model')\n *\n * // Works with chat()\n * chat({\n * adapter: myOpenai('my-fine-tuned-gpt4'),\n * messages: [...]\n * })\n * ```\n */\nexport function extendAdapter<\n TFactory extends AnyAdapterFactory,\n const TDefs extends ReadonlyArray<ExtendedModelDef>,\n>(factory: TFactory, _customModels: TDefs): ExtendedFactory<TFactory, TDefs>\n// The implementation signature stays at the honest `AnyAdapterFactory` width;\n// the overload above performs the deliberate model-union widening.\nexport function extendAdapter(\n factory: AnyAdapterFactory,\n _customModels: ReadonlyArray<ExtendedModelDef>,\n): AnyAdapterFactory {\n // At runtime, we simply pass through to the original factory.\n // The _customModels parameter is only used for type inference.\n // No runtime validation - users are trusted to pass valid model names.\n return factory\n}\n"],"names":[],"mappings":"AAmHO,SAAS,YACd,MACA,QACkB;AAClB,MAAI,MAAM,QAAQ,MAAM,GAAG;AACzB,WAAO,EAAE,MAAM,OAAO,QAAQ,cAAc,CAAA,EAAC;AAAA,EAC/C;AACA,QAAM,OAAO;AACb,SAAO;AAAA,IACL;AAAA,IACA,OAAO,KAAK,SAAU,CAAC,MAAM;AAAA,IAC7B,cAAc,KAAK,gBAAgB,CAAA;AAAA,IACnC,UAAU,KAAK;AAAA,IACf,OAAO,KAAK;AAAA,EAAA;AAEhB;AA0HO,SAAS,cACd,SACA,eACmB;AAInB,SAAO;AACT;"}
1
+ {"version":3,"file":"extend-adapter.js","names":[],"sources":["../../src/extend-adapter.ts"],"sourcesContent":["import type { Modality } from './types'\n\n// ===========================\n// Extended Model Definition\n// ===========================\n\n/**\n * Definition for a custom model to add to an adapter.\n *\n * @template TName - The model name as a literal string type\n * @template TInput - Array of supported input modalities\n * @template TOptions - Provider options type for this model\n *\n * @example\n * ```typescript\n * const customModels = [\n * createModel('my-custom-model', ['text', 'image']),\n * ] as const\n * ```\n */\nexport interface ExtendedModelDef<\n TName extends string = string,\n TInput extends ReadonlyArray<Modality> = ReadonlyArray<Modality>,\n TOptions = unknown,\n TFeatures extends ReadonlyArray<string> = ReadonlyArray<string>,\n TTools extends ReadonlyArray<string> = ReadonlyArray<string>,\n> {\n /** The model name identifier */\n name: TName\n /** Supported input modalities for this model */\n input: TInput\n /** Type brand for provider options - use `{} as YourOptionsType` */\n modelOptions: TOptions\n /** Optional declared features (e.g. 'reasoning', 'structured_outputs') */\n features?: TFeatures\n /** Optional declared provider tools (e.g. 'web_search') */\n tools?: TTools\n}\n\n/** Capability bag accepted by the object form of `createModel`. */\nexport interface ModelCapabilities<\n TInput extends ReadonlyArray<Modality> = ReadonlyArray<Modality>,\n TFeatures extends ReadonlyArray<string> = ReadonlyArray<string>,\n TTools extends ReadonlyArray<string> = ReadonlyArray<string>,\n TOptions = unknown,\n> {\n input?: TInput\n features?: TFeatures\n tools?: TTools\n modelOptions?: TOptions\n}\n\n/**\n * Creates a custom model definition for use with `extendAdapter`.\n *\n * This is a helper function that provides proper type inference without\n * requiring manual `as const` casts on individual properties.\n *\n * @template TName - The model name (inferred from argument)\n * @template TInput - The input modalities array (inferred from argument)\n *\n * @param name - The model name identifier (literal string)\n * @param input - Array of supported input modalities\n * @returns A properly typed model definition for use with `extendAdapter`\n *\n * @example\n * ```typescript\n * import { extendAdapter, createModel } from '@tanstack/ai'\n * import { openaiText } from '@tanstack/ai-openai'\n *\n * // Define custom models with full type inference\n * const customModels = [\n * createModel('my-fine-tuned-gpt4', ['text', 'image']),\n * createModel('local-llama', ['text']),\n * ] as const\n *\n * const myOpenai = extendAdapter(openaiText, customModels)\n * ```\n *\n * @example\n * ```typescript\n * // Capabilities object form - declare features and provider tools\n * const reasoner = createModel('reasoner', {\n * input: ['text'],\n * features: ['reasoning', 'structured_outputs'],\n * tools: ['web_search'],\n * })\n * ```\n */\n// Overload 1 — legacy positional input array (unchanged behavior)\nexport function createModel<\n const TName extends string,\n const TInput extends ReadonlyArray<Modality>,\n>(name: TName, input: TInput): ExtendedModelDef<TName, TInput>\n// Overload 2 — capabilities object\nexport function createModel<\n const TName extends string,\n const TCaps extends ModelCapabilities,\n>(\n name: TName,\n capabilities: TCaps,\n): ExtendedModelDef<\n TName,\n TCaps['input'] extends ReadonlyArray<Modality>\n ? TCaps['input']\n : ReadonlyArray<Modality>,\n TCaps['modelOptions'],\n TCaps['features'] extends ReadonlyArray<string>\n ? TCaps['features']\n : ReadonlyArray<string>,\n TCaps['tools'] extends ReadonlyArray<string>\n ? TCaps['tools']\n : ReadonlyArray<string>\n>\n// Implementation\nexport function createModel(\n name: string,\n second: ReadonlyArray<Modality> | ModelCapabilities,\n): ExtendedModelDef {\n if (Array.isArray(second)) {\n return { name, input: second, modelOptions: {} }\n }\n const caps = second as ModelCapabilities\n return {\n name,\n input: caps.input ?? (['text'] as ReadonlyArray<Modality>),\n modelOptions: caps.modelOptions ?? {},\n features: caps.features,\n tools: caps.tools,\n }\n}\n\n// ===========================\n// Type Extraction Utilities\n// ===========================\n\n/**\n * Extract the model name union from an array of model definitions.\n */\ntype ExtractCustomModelNames<TDefs extends ReadonlyArray<ExtendedModelDef>> =\n TDefs[number]['name']\n\n// ===========================\n// Factory Type Inference\n// ===========================\n\n/**\n * The widest factory shape `extendAdapter` accepts: any function taking a\n * model as its first parameter. Parameters are contravariant, so `never`\n * params and an `unknown` return accept every factory without resorting\n * to `any`.\n */\ntype AnyAdapterFactory = (model: never, ...args: Array<never>) => unknown\n\n/**\n * Infer the model parameter type from an adapter factory function.\n * For generic functions like `<T extends Union>(model: T)`, this gets `T` which\n * TypeScript treats as the constraint union when used in parameter position.\n */\ntype InferFactoryModels<TFactory> = TFactory extends (\n model: infer TModel,\n ...args: Array<never>\n) => unknown\n ? TModel extends string\n ? TModel\n : string\n : string\n\n/**\n * Infer the adapter return type from a factory function.\n */\ntype InferAdapterReturn<TFactory> = TFactory extends (\n ...args: Array<never>\n) => infer TReturn\n ? TReturn\n : never\n\n/**\n * Extracts all parameter types after the model parameter from a factory,\n * preserving labels and optionality (e.g. `[apiKey: string, config?: C]`).\n * Note: overloaded factories resolve against their last overload (a\n * `Parameters` limitation).\n */\ntype InferRestArgs<TFactory extends AnyAdapterFactory> =\n Parameters<TFactory> extends [unknown?, ...infer TRest] ? TRest : []\n\n/**\n * The factory signature produced by `extendAdapter`: accepts both original\n * and custom model names while preserving all remaining parameters and the\n * return type of the original factory.\n */\ntype ExtendedFactory<\n TFactory extends AnyAdapterFactory,\n TDefs extends ReadonlyArray<ExtendedModelDef>,\n> = (\n model: InferFactoryModels<TFactory> | ExtractCustomModelNames<TDefs>,\n ...args: InferRestArgs<TFactory>\n) => InferAdapterReturn<TFactory>\n\n// ===========================\n// extendAdapter Function\n// ===========================\n\n/**\n * Extends an existing adapter factory with additional custom models.\n *\n * The extended adapter accepts both original models (with full original type inference)\n * and custom models (with types from your definitions).\n *\n * At runtime, this simply passes through to the original factory - no validation is performed.\n * The original factory's signature is fully preserved, including any config parameters.\n *\n * @param factory - The original adapter factory function (e.g., `openaiText`, `anthropicText`)\n * @param models - Array of custom model definitions with `name` and `input`\n * @returns A new factory function that accepts both original and custom models\n *\n * @example\n * ```typescript\n * import { extendAdapter, createModel } from '@tanstack/ai'\n * import { openaiText } from '@tanstack/ai-openai'\n *\n * // Define custom models\n * const customModels = [\n * createModel('my-fine-tuned-gpt4', ['text', 'image']),\n * createModel('local-llama', ['text']),\n * ] as const\n *\n * // Create extended adapter\n * const myOpenai = extendAdapter(openaiText, customModels)\n *\n * // Use with original models - full type inference preserved\n * const gpt4 = myOpenai('gpt-4o')\n *\n * // Use with custom models\n * const custom = myOpenai('my-fine-tuned-gpt4')\n *\n * // Type error: 'invalid-model' is not a valid model\n * // myOpenai('invalid-model')\n *\n * // Works with chat()\n * chat({\n * adapter: myOpenai('my-fine-tuned-gpt4'),\n * messages: [...]\n * })\n * ```\n */\nexport function extendAdapter<\n TFactory extends AnyAdapterFactory,\n const TDefs extends ReadonlyArray<ExtendedModelDef>,\n>(factory: TFactory, _customModels: TDefs): ExtendedFactory<TFactory, TDefs>\n// The implementation signature stays at the honest `AnyAdapterFactory` width;\n// the overload above performs the deliberate model-union widening.\nexport function extendAdapter(\n factory: AnyAdapterFactory,\n _customModels: ReadonlyArray<ExtendedModelDef>,\n): AnyAdapterFactory {\n // At runtime, we simply pass through to the original factory.\n // The _customModels parameter is only used for type inference.\n // No runtime validation - users are trusted to pass valid model names.\n return factory\n}\n"],"mappings":";AAmHA,SAAgB,YACd,MACA,QACkB;CAClB,IAAI,MAAM,QAAQ,MAAM,GACtB,OAAO;EAAE;EAAM,OAAO;EAAQ,cAAc,CAAC;CAAE;CAEjD,MAAM,OAAO;CACb,OAAO;EACL;EACA,OAAO,KAAK,SAAU,CAAC,MAAM;EAC7B,cAAc,KAAK,gBAAgB,CAAC;EACpC,UAAU,KAAK;EACf,OAAO,KAAK;CACd;AACF;AA0HA,SAAgB,cACd,SACA,eACmB;CAInB,OAAO;AACT"}
@@ -7,22 +7,38 @@ export { createVideoOptions } from './activities/generateVideo/index.js';
7
7
  export { createSpeechOptions } from './activities/generateSpeech/index.js';
8
8
  export { createTranscriptionOptions } from './activities/generateTranscription/index.js';
9
9
  export type { AIAdapter, ImageAdapter, AnyImageAdapter, TextAdapter, AnyTextAdapter, AnySummarizeAdapter, SummarizeAdapter, AnyAudioAdapter, AudioAdapter, AnyTTSAdapter, TTSAdapter, AnyTranscriptionAdapter, TranscriptionAdapter, AnyVideoAdapter, VideoAdapter, } from './activities/index.js';
10
- export { toolDefinition, type ToolDefinition, type ToolDefinitionInstance, type ToolDefinitionConfig, type ServerTool, type ClientTool, type AnyClientTool, type InferToolName, type InferToolInput, type InferToolOutput, } from './activities/chat/tools/tool-definition.js';
10
+ export { toolDefinition, type ToolDefinition, type ToolDefinitionInstance, type ToolDefinitionConfig, type ServerTool, type AnyServerTool, type ClientTool, type AnyClientTool, type InferToolName, type InferToolInput, type InferToolOutput, type ApprovalCapabilityOf, type ApprovalSchemaConfig, type ApprovalSchemaOf, type InputSchemaOf, type OutputSchemaOf, type NoSchema, } from './activities/chat/tools/tool-definition.js';
11
+ export { hashSchemaInput, normalizeApprovalSchema, type NormalizedApprovalSchema, type NormalizedSchemaInput, } from './activities/chat/tools/approval-schema.js';
12
+ export { canonicalInterruptJson, cloneAndDeepFreezeJson, digestInterruptJson, } from './interrupt-serialization.js';
13
+ export { INTERRUPT_BINDING_METADATA_KEY, InterruptResumeValidationError, interruptItemError, readInterruptBinding, readUnopenedInterruptBinding, validateInterruptResumeBatch, withInterruptBinding, withoutInterruptBinding, type PendingInterruptResumeRecord, type ValidateInterruptResumeBatchInput, type ValidatedInterruptResumeBatch, } from './interrupt-resume.js';
11
14
  export type { MCPToolSource, ChatMCPOptions, MCPConnectionPolicy, } from './activities/chat/mcp/types.js';
12
15
  export { MCPDuplicateToolNameError } from './activities/chat/mcp/manager.js';
13
- export { convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema, StandardSchemaValidationError, } from './activities/chat/tools/schema-converter.js';
14
- export { streamToText, toServerSentEventsStream, toServerSentEventsResponse, toHttpStream, toHttpResponse, } from './stream-to-response.js';
16
+ export { convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema, validateWithStandardSchema, StandardSchemaValidationError, } from './activities/chat/tools/schema-converter.js';
17
+ export { streamToText, toServerSentEventsStream, toServerSentEventsResponse, resumeServerSentEventsResponse, toHttpStream, toHttpResponse, resumeHttpResponse, resolveResumeRunId, RUN_ACCEPTED_EVENT, } from './stream-to-response.js';
18
+ export type { RunDriverOptions } from './stream-to-response.js';
19
+ export { memoryStream, replayRunStream } from './stream-durability.js';
20
+ export type { MemoryStreamInit, MemoryStreamOptions, StreamDurability, UpsertableStreamDurability, } from './stream-durability.js';
15
21
  export { ToolCallManager } from './activities/chat/tools/tool-calls.js';
16
22
  export { DISCOVERY_TOOL_NAME } from './activities/chat/tools/lazy-tool-manager.js';
17
23
  export type { ProviderTool } from './tools/provider-tool.js';
18
24
  export { brandProviderTool } from './tools/provider-tool.js';
19
- export { maxIterations, maxToolCalls, untilFinishReason, combineStrategies, } from './activities/chat/agent-loop-strategies.js';
25
+ export { maxIterations, untilFinishReason, combineStrategies, } from './activities/chat/agent-loop-strategies.js';
20
26
  export { createToolRegistry, createFrozenRegistry, type ToolRegistry, } from './tool-registry.js';
21
- export type { ChatMiddleware, ChatMiddlewareContext, ChatMiddlewarePhase, ChatMiddlewareConfig, StructuredOutputMiddlewareConfig, ToolCallHookContext, BeforeToolCallDecision, AfterToolCallInfo, IterationInfo, ToolPhaseCompleteInfo, UsageInfo, FinishInfo, AbortInfo, ErrorInfo, SandboxFileEvent, SandboxFileHookEvent, ChatSandboxHooks, } from './activities/chat/middleware/index.js';
22
- export type { GenerationMiddleware, GenerationMiddlewareContext, GenerationActivity, GenerationUsageInfo, GenerationFinishInfo, GenerationAbortInfo, GenerationErrorInfo, AnyGenerationMiddleware, } from './activities/middleware/index.js';
27
+ export type { ChatMiddleware, ChatMiddlewareContext, ChatMiddlewarePhase, ChatMiddlewareConfig, ChatResumeToolState, ChatResumeGenericResolution, StructuredOutputMiddlewareConfig, ToolCallHookContext, BeforeToolCallDecision, AfterToolCallInfo, IterationInfo, ToolPhaseCompleteInfo, UsageInfo, FinishInfo, AbortInfo, ErrorInfo, SandboxFileEvent, SandboxFileHookEvent, ChatSandboxHooks, } from './activities/chat/middleware/index.js';
28
+ export { INTERRUPT_BINDING_VERSION, canonicalizeInterruptResolutions, } from './interrupts.js';
29
+ export type { BatchInterruptError, BatchInterruptErrorCode, InterruptBinding, InterruptCorrelation, InterruptSubmissionError, ItemInterruptError, ItemInterruptErrorCode, ToolApprovalResolution, UnopenedInterruptBinding, } from './interrupts.js';
30
+ export type { GenerationMiddleware, GenerationMiddlewareContext, GenerationActivity, GenerationUsageInfo, GenerationFinishInfo, GenerationAbortInfo, GenerationErrorInfo, AnyGenerationMiddleware, GenerationResultTransform, GenerationResultTransformContext, } from './activities/middleware/index.js';
23
31
  export { createCapability, defineChatMiddleware, createChatMiddleware, } from './activities/chat/middleware/index.js';
24
32
  export type { Capability, CapabilityHandle, CapabilityContext, CapabilityGetter, CapabilityProvider, DefinedChatMiddleware, AnyChatMiddleware, } from './activities/chat/middleware/index.js';
33
+ export { isRunStatus, isTerminalRunStatus, defineRunStore, InMemoryRunStore, } from './activities/chat/middleware/index.js';
34
+ export type { RunStatus, TerminalRunStatus, RunRecord, RunError, RunStore, } from './activities/chat/middleware/index.js';
35
+ export { DetachableRunCapability, getDetachableRun, provideDetachableRun, } from './activities/chat/middleware/run-store.js';
36
+ export { RunDetachedCapability, getRunDetached, provideRunDetached, } from './activities/chat/middleware/run-store.js';
37
+ export { RUN_CANCEL_REASON, isCancelRequestedReason, requestRunCancel, wasCancelRequested, } from './activities/chat/cancel.js';
38
+ export { CUSTOM_EVENT, isCustomEvent } from './custom-events.js';
39
+ export type { WellKnownCustomEventName, FileChangedPayload, ProcessOutputPayload, PortOpenedPayload, ApprovalRequestedPayload, ApprovalResolvedPayload, ArtifactCreatedPayload, SandboxLifecyclePayload, } from './custom-events.js';
25
40
  export * from './types.js';
41
+ export type { Scope } from './scope.js';
26
42
  export { firstSentence, renderLazyCatalogEntry, } from './activities/chat/tools/lazy-tools.js';
27
43
  export { buildBaseUsage, type BaseUsageInput } from './utilities/usage.js';
28
44
  export { resolveMediaPrompt } from './utilities/media-prompt.js';
@@ -36,6 +52,8 @@ export { convertMessagesToModelMessages, generateMessageId, uiMessageToModelMess
36
52
  export { StreamProcessor, createReplayStream, ImmediateStrategy, PunctuationStrategy, BatchStrategy, WordBoundaryStrategy, CompositeStrategy, PartialJSONParser, defaultJSONParser, parsePartialJSON, } from './activities/chat/stream/index.js';
37
53
  export type { ChunkStrategy, ChunkRecording, InternalToolCallState, ProcessorResult, ProcessorState, StreamProcessorEvents, StreamProcessorOptions, ToolCallState, ToolResultState, JSONParser, } from './activities/chat/stream/index.js';
38
54
  export { chatParamsFromRequest, chatParamsFromRequestBody, mergeAgentTools, } from './utilities/chat-params.js';
55
+ export type { ClientToolDeclaration, MergedAgentTools, } from './utilities/chat-params.js';
56
+ export { generationParamsFromBody, generationParamsFromRequest } from './client.js';
39
57
  export { uiMessagesToWire } from './utilities/ag-ui-wire.js';
40
58
  export type { WireMessage } from './utilities/ag-ui-wire.js';
41
59
  export { isContentPart, isContentPartArray, normalizeToolResult, } from './utilities/tool-result.js';
package/dist/esm/index.js CHANGED
@@ -1,115 +1,47 @@
1
+ import { RUN_CANCEL_REASON, isCancelRequestedReason, requestRunCancel, wasCancelRequested } from "./activities/chat/cancel.js";
2
+ import { createCapability } from "./activities/chat/middleware/capabilities.js";
3
+ import { DetachableRunCapability, InMemoryRunStore, RunDetachedCapability, defineRunStore, getDetachableRun, getRunDetached, isRunStatus, isTerminalRunStatus, provideDetachableRun, provideRunDetached } from "./activities/chat/middleware/run-store.js";
4
+ import { memoryStream, replayRunStream, resolveResumeRunId } from "./stream-durability.js";
5
+ import { EventType } from "./types.js";
6
+ import { ConsoleLogger } from "./logger/console-logger.js";
7
+ import { RUN_ACCEPTED_EVENT, resumeHttpResponse, resumeServerSentEventsResponse, streamToText, toHttpResponse, toHttpStream, toServerSentEventsResponse, toServerSentEventsStream } from "./stream-to-response.js";
8
+ import { canonicalInterruptJson, cloneAndDeepFreezeJson, digestInterruptJson } from "./interrupt-serialization.js";
9
+ import { INTERRUPT_BINDING_VERSION, canonicalizeInterruptResolutions } from "./interrupts.js";
10
+ import { StandardSchemaValidationError, convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema, validateWithStandardSchema } from "./activities/chat/tools/schema-converter.js";
11
+ import { hashSchemaInput, normalizeApprovalSchema } from "./activities/chat/tools/approval-schema.js";
12
+ import { INTERRUPT_BINDING_METADATA_KEY, InterruptResumeValidationError, interruptItemError, readInterruptBinding, readUnopenedInterruptBinding, validateInterruptResumeBatch, withInterruptBinding, withoutInterruptBinding } from "./interrupt-resume.js";
13
+ import { isContentPart, isContentPartArray, normalizeToolResult } from "./utilities/tool-result.js";
14
+ import { getProviderExecutedMetadata, isProviderExecutedToolCall } from "./utilities/provider-executed.js";
15
+ import { firstSentence, renderLazyCatalogEntry } from "./activities/chat/tools/lazy-tools.js";
16
+ import { DISCOVERY_TOOL_NAME } from "./activities/chat/tools/lazy-tool-manager.js";
17
+ import { ToolCallManager } from "./activities/chat/tools/tool-calls.js";
18
+ import { combineStrategies, maxIterations, untilFinishReason } from "./activities/chat/agent-loop-strategies.js";
19
+ import { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages } from "./activities/chat/messages.js";
20
+ import { MCPDuplicateToolNameError } from "./activities/chat/mcp/manager.js";
1
21
  import { chat, createChatOptions } from "./activities/chat/index.js";
2
22
  import { createSummarizeOptions, summarize } from "./activities/summarize/index.js";
23
+ import { resolveMediaPrompt } from "./utilities/media-prompt.js";
3
24
  import { createImageOptions, generateImage } from "./activities/generateImage/index.js";
4
25
  import { createAudioOptions, generateAudio } from "./activities/generateAudio/index.js";
5
26
  import { createVideoOptions, generateVideo, getVideoJobStatus } from "./activities/generateVideo/index.js";
6
27
  import { createSpeechOptions, generateSpeech } from "./activities/generateSpeech/index.js";
7
28
  import { createTranscriptionOptions, generateTranscription } from "./activities/generateTranscription/index.js";
8
29
  import { toolDefinition } from "./activities/chat/tools/tool-definition.js";
9
- import { MCPDuplicateToolNameError } from "./activities/chat/mcp/manager.js";
10
- import { StandardSchemaValidationError, convertSchemaToJsonSchema, isStandardSchema, parseWithStandardSchema } from "./activities/chat/tools/schema-converter.js";
11
- import { streamToText, toHttpResponse, toHttpStream, toServerSentEventsResponse, toServerSentEventsStream } from "./stream-to-response.js";
12
- import { ToolCallManager } from "./activities/chat/tools/tool-calls.js";
13
- import { DISCOVERY_TOOL_NAME } from "./activities/chat/tools/lazy-tool-manager.js";
14
30
  import { brandProviderTool } from "./tools/provider-tool.js";
15
- import { combineStrategies, maxIterations, maxToolCalls, untilFinishReason } from "./activities/chat/agent-loop-strategies.js";
16
31
  import { createFrozenRegistry, createToolRegistry } from "./tool-registry.js";
17
- import { firstSentence, renderLazyCatalogEntry } from "./activities/chat/tools/lazy-tools.js";
32
+ import { defineChatMiddleware } from "./activities/chat/middleware/define.js";
33
+ import { createChatMiddleware } from "./activities/chat/middleware/builder.js";
34
+ import { CUSTOM_EVENT, isCustomEvent } from "./custom-events.js";
18
35
  import { buildBaseUsage } from "./utilities/usage.js";
19
- import { resolveMediaPrompt } from "./utilities/media-prompt.js";
20
36
  import { normalizeSystemPrompts } from "./system-prompts.js";
21
37
  import { detectImageMimeType } from "./utils.js";
38
+ import { createRealtimeEventEmitter } from "./realtime/event-emitter.js";
22
39
  import { realtimeToken } from "./realtime/index.js";
23
- import { convertMessagesToModelMessages, generateMessageId, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeToUIMessage, uiMessageToModelMessages } from "./activities/chat/messages.js";
40
+ import { PartialJSONParser, defaultJSONParser, parsePartialJSON } from "./activities/chat/stream/json-parser.js";
41
+ import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PunctuationStrategy, WordBoundaryStrategy } from "./activities/chat/stream/strategies.js";
42
+ import { StreamProcessor, createReplayStream } from "./activities/chat/stream/processor.js";
24
43
  import { chatParamsFromRequest, chatParamsFromRequestBody, mergeAgentTools } from "./utilities/chat-params.js";
25
44
  import { uiMessagesToWire } from "./utilities/ag-ui-wire.js";
26
- import { isContentPart, isContentPartArray, normalizeToolResult } from "./utilities/tool-result.js";
27
- import { getProviderExecutedMetadata, isProviderExecutedToolCall } from "./utilities/provider-executed.js";
45
+ import { generationParamsFromBody, generationParamsFromRequest } from "./client.js";
28
46
  import { createModel, extendAdapter } from "./extend-adapter.js";
29
- import { ConsoleLogger } from "./logger/console-logger.js";
30
- import { BatchStrategy, CompositeStrategy, ImmediateStrategy, PunctuationStrategy, WordBoundaryStrategy } from "./activities/chat/stream/strategies.js";
31
- import { EventType } from "@ag-ui/core";
32
- import { PartialJSONParser, defaultJSONParser, parsePartialJSON } from "./activities/chat/stream/json-parser.js";
33
- import { StreamProcessor, createReplayStream } from "./activities/chat/stream/processor.js";
34
- import { createCapability } from "./activities/chat/middleware/capabilities.js";
35
- import { createChatMiddleware } from "./activities/chat/middleware/builder.js";
36
- import { createRealtimeEventEmitter } from "./realtime/event-emitter.js";
37
- import { defineChatMiddleware } from "./activities/chat/middleware/define.js";
38
- export {
39
- BatchStrategy,
40
- CompositeStrategy,
41
- ConsoleLogger,
42
- DISCOVERY_TOOL_NAME,
43
- EventType,
44
- ImmediateStrategy,
45
- MCPDuplicateToolNameError,
46
- PartialJSONParser,
47
- PunctuationStrategy,
48
- StandardSchemaValidationError,
49
- StreamProcessor,
50
- ToolCallManager,
51
- WordBoundaryStrategy,
52
- brandProviderTool,
53
- buildBaseUsage,
54
- chat,
55
- chatParamsFromRequest,
56
- chatParamsFromRequestBody,
57
- combineStrategies,
58
- convertMessagesToModelMessages,
59
- convertSchemaToJsonSchema,
60
- createAudioOptions,
61
- createCapability,
62
- createChatMiddleware,
63
- createChatOptions,
64
- createFrozenRegistry,
65
- createImageOptions,
66
- createModel,
67
- createRealtimeEventEmitter,
68
- createReplayStream,
69
- createSpeechOptions,
70
- createSummarizeOptions,
71
- createToolRegistry,
72
- createTranscriptionOptions,
73
- createVideoOptions,
74
- defaultJSONParser,
75
- defineChatMiddleware,
76
- detectImageMimeType,
77
- extendAdapter,
78
- firstSentence,
79
- generateAudio,
80
- generateImage,
81
- generateMessageId,
82
- generateSpeech,
83
- generateTranscription,
84
- generateVideo,
85
- getProviderExecutedMetadata,
86
- getVideoJobStatus,
87
- isContentPart,
88
- isContentPartArray,
89
- isProviderExecutedToolCall,
90
- isStandardSchema,
91
- maxIterations,
92
- maxToolCalls,
93
- mergeAgentTools,
94
- modelMessageToUIMessage,
95
- modelMessagesToUIMessages,
96
- normalizeSystemPrompts,
97
- normalizeToUIMessage,
98
- normalizeToolResult,
99
- parsePartialJSON,
100
- parseWithStandardSchema,
101
- realtimeToken,
102
- renderLazyCatalogEntry,
103
- resolveMediaPrompt,
104
- streamToText,
105
- summarize,
106
- toHttpResponse,
107
- toHttpStream,
108
- toServerSentEventsResponse,
109
- toServerSentEventsStream,
110
- toolDefinition,
111
- uiMessageToModelMessages,
112
- uiMessagesToWire,
113
- untilFinishReason
114
- };
115
- //# sourceMappingURL=index.js.map
47
+ export { BatchStrategy, CUSTOM_EVENT, CompositeStrategy, ConsoleLogger, DISCOVERY_TOOL_NAME, DetachableRunCapability, EventType, INTERRUPT_BINDING_METADATA_KEY, INTERRUPT_BINDING_VERSION, ImmediateStrategy, InMemoryRunStore, InterruptResumeValidationError, MCPDuplicateToolNameError, PartialJSONParser, PunctuationStrategy, RUN_ACCEPTED_EVENT, RUN_CANCEL_REASON, RunDetachedCapability, StandardSchemaValidationError, StreamProcessor, ToolCallManager, WordBoundaryStrategy, brandProviderTool, buildBaseUsage, canonicalInterruptJson, canonicalizeInterruptResolutions, chat, chatParamsFromRequest, chatParamsFromRequestBody, cloneAndDeepFreezeJson, combineStrategies, convertMessagesToModelMessages, convertSchemaToJsonSchema, createAudioOptions, createCapability, createChatMiddleware, createChatOptions, createFrozenRegistry, createImageOptions, createModel, createRealtimeEventEmitter, createReplayStream, createSpeechOptions, createSummarizeOptions, createToolRegistry, createTranscriptionOptions, createVideoOptions, defaultJSONParser, defineChatMiddleware, defineRunStore, detectImageMimeType, digestInterruptJson, extendAdapter, firstSentence, generateAudio, generateImage, generateMessageId, generateSpeech, generateTranscription, generateVideo, generationParamsFromBody, generationParamsFromRequest, getDetachableRun, getProviderExecutedMetadata, getRunDetached, getVideoJobStatus, hashSchemaInput, interruptItemError, isCancelRequestedReason, isContentPart, isContentPartArray, isCustomEvent, isProviderExecutedToolCall, isRunStatus, isStandardSchema, isTerminalRunStatus, maxIterations, memoryStream, mergeAgentTools, modelMessageToUIMessage, modelMessagesToUIMessages, normalizeApprovalSchema, normalizeSystemPrompts, normalizeToUIMessage, normalizeToolResult, parsePartialJSON, parseWithStandardSchema, provideDetachableRun, provideRunDetached, readInterruptBinding, readUnopenedInterruptBinding, realtimeToken, renderLazyCatalogEntry, replayRunStream, requestRunCancel, resolveMediaPrompt, resolveResumeRunId, resumeHttpResponse, resumeServerSentEventsResponse, streamToText, summarize, toHttpResponse, toHttpStream, toServerSentEventsResponse, toServerSentEventsStream, toolDefinition, uiMessageToModelMessages, uiMessagesToWire, untilFinishReason, validateInterruptResumeBatch, validateWithStandardSchema, wasCancelRequested, withInterruptBinding, withoutInterruptBinding };
@@ -0,0 +1,71 @@
1
+ import { InterruptBinding, InterruptSubmissionError, ItemInterruptErrorCode, UnopenedInterruptBinding } from './interrupts.js';
2
+ import { ChatMiddlewareConfig, ChatResumeToolState } from './activities/chat/middleware/types.js';
3
+ import { Interrupt, RunAgentResumeItem } from './types.js';
4
+ /**
5
+ * The `Interrupt.metadata` key under which this package's resume binding
6
+ * travels.
7
+ *
8
+ * Exported so anything that produces an interrupt this package must later
9
+ * resume — an application middleware raising a generic pause, a future
10
+ * workflow-to-AG-UI projection — attaches the binding through
11
+ * {@link withInterruptBinding} rather than copying the string. Everything
12
+ * outside this key is the plain AG-UI envelope and is left untouched.
13
+ */
14
+ export declare const INTERRUPT_BINDING_METADATA_KEY = "tanstack:interruptBinding";
15
+ /** The persistence-neutral shape required to validate an interrupt resume. */
16
+ export interface PendingInterruptResumeRecord {
17
+ interruptId: string;
18
+ payload: unknown;
19
+ binding: InterruptBinding;
20
+ }
21
+ export interface ValidateInterruptResumeBatchInput {
22
+ threadId: string;
23
+ interruptedRunId: string;
24
+ generation: number;
25
+ pending: ReadonlyArray<PendingInterruptResumeRecord>;
26
+ resume?: ReadonlyArray<RunAgentResumeItem>;
27
+ tools: ChatMiddlewareConfig['tools'];
28
+ now?: number;
29
+ }
30
+ export interface ValidatedInterruptResumeBatch {
31
+ errors: ReadonlyArray<InterruptSubmissionError>;
32
+ resolutions?: ReadonlyArray<RunAgentResumeItem>;
33
+ canonicalResolutions?: string;
34
+ fingerprint?: string;
35
+ resumeToolState?: ChatResumeToolState;
36
+ }
37
+ export declare class InterruptResumeValidationError extends Error {
38
+ readonly errors: ReadonlyArray<InterruptSubmissionError>;
39
+ readonly name = "InterruptResumeValidationError";
40
+ constructor(errors: ReadonlyArray<InterruptSubmissionError>);
41
+ }
42
+ export declare function interruptItemError(input: Pick<ValidateInterruptResumeBatchInput, 'threadId' | 'interruptedRunId' | 'generation'>, interruptId: string, code: ItemInterruptErrorCode, message: string, options?: {
43
+ path?: ReadonlyArray<string | number>;
44
+ source?: 'client' | 'server';
45
+ retryable?: boolean;
46
+ }): InterruptSubmissionError;
47
+ /**
48
+ * Validate and translate a complete interrupt batch before any tool executes.
49
+ * Used by ephemeral chat resume; a durable layer may share the same validator.
50
+ */
51
+ export declare function validateInterruptResumeBatch(input: ValidateInterruptResumeBatchInput): Promise<ValidatedInterruptResumeBatch>;
52
+ export declare function readUnopenedInterruptBinding(descriptor: Interrupt): UnopenedInterruptBinding | undefined;
53
+ /**
54
+ * Attach a resume binding to an interrupt descriptor, under
55
+ * {@link INTERRUPT_BINDING_METADATA_KEY}.
56
+ *
57
+ * This is the supported way to make an interrupt resumable by this package.
58
+ * The descriptor keeps its AG-UI shape; only `metadata` gains the namespaced
59
+ * key. Pass the unopened form (no `interruptedRunId` / `generation`) when
60
+ * emitting from inside a run — those fields are stamped as the run finishes.
61
+ */
62
+ export declare function withInterruptBinding(descriptor: Interrupt, binding: UnopenedInterruptBinding | InterruptBinding): Interrupt;
63
+ /**
64
+ * Read the opened resume binding off a descriptor, or `undefined` when the
65
+ * descriptor carries no binding of a version we understand.
66
+ *
67
+ * `undefined` means "this interrupt is not ours to resume" — it is not a
68
+ * failure to recover from by inventing a binding.
69
+ */
70
+ export declare function readInterruptBinding(descriptor: Interrupt): InterruptBinding | undefined;
71
+ export declare function withoutInterruptBinding(descriptor: Interrupt): Interrupt;