@tambo-ai/client 0.0.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 (235) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -0
  3. package/dist/index.d.ts +43 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +78 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/mcp/elicitation.d.ts +59 -0
  8. package/dist/mcp/elicitation.d.ts.map +1 -0
  9. package/dist/mcp/elicitation.js +27 -0
  10. package/dist/mcp/elicitation.js.map +1 -0
  11. package/dist/mcp/index.d.ts +6 -0
  12. package/dist/mcp/index.d.ts.map +1 -0
  13. package/dist/mcp/index.js +14 -0
  14. package/dist/mcp/index.js.map +1 -0
  15. package/dist/mcp/mcp-client.d.ts +185 -0
  16. package/dist/mcp/mcp-client.d.ts.map +1 -0
  17. package/dist/mcp/mcp-client.js +219 -0
  18. package/dist/mcp/mcp-client.js.map +1 -0
  19. package/dist/mcp/mcp-constants.d.ts +19 -0
  20. package/dist/mcp/mcp-constants.d.ts.map +1 -0
  21. package/dist/mcp/mcp-constants.js +21 -0
  22. package/dist/mcp/mcp-constants.js.map +1 -0
  23. package/dist/model/component-metadata.d.ts +390 -0
  24. package/dist/model/component-metadata.d.ts.map +1 -0
  25. package/dist/model/component-metadata.js +3 -0
  26. package/dist/model/component-metadata.js.map +1 -0
  27. package/dist/model/mcp-server-info.d.ts +72 -0
  28. package/dist/model/mcp-server-info.d.ts.map +1 -0
  29. package/dist/model/mcp-server-info.js +29 -0
  30. package/dist/model/mcp-server-info.js.map +1 -0
  31. package/dist/schema/index.d.ts +5 -0
  32. package/dist/schema/index.d.ts.map +1 -0
  33. package/dist/schema/index.js +15 -0
  34. package/dist/schema/index.js.map +1 -0
  35. package/dist/schema/json-schema.d.ts +42 -0
  36. package/dist/schema/json-schema.d.ts.map +1 -0
  37. package/dist/schema/json-schema.js +114 -0
  38. package/dist/schema/json-schema.js.map +1 -0
  39. package/dist/schema/schema.d.ts +49 -0
  40. package/dist/schema/schema.d.ts.map +1 -0
  41. package/dist/schema/schema.js +129 -0
  42. package/dist/schema/schema.js.map +1 -0
  43. package/dist/schema/standard-schema.d.ts +22 -0
  44. package/dist/schema/standard-schema.d.ts.map +1 -0
  45. package/dist/schema/standard-schema.js +42 -0
  46. package/dist/schema/standard-schema.js.map +1 -0
  47. package/dist/schema/validate.d.ts +14 -0
  48. package/dist/schema/validate.d.ts.map +1 -0
  49. package/dist/schema/validate.js +148 -0
  50. package/dist/schema/validate.js.map +1 -0
  51. package/dist/tambo-client.d.ts +292 -0
  52. package/dist/tambo-client.d.ts.map +1 -0
  53. package/dist/tambo-client.js +508 -0
  54. package/dist/tambo-client.js.map +1 -0
  55. package/dist/tambo-stream.d.ts +112 -0
  56. package/dist/tambo-stream.d.ts.map +1 -0
  57. package/dist/tambo-stream.js +345 -0
  58. package/dist/tambo-stream.js.map +1 -0
  59. package/dist/types/auth.d.ts +24 -0
  60. package/dist/types/auth.d.ts.map +1 -0
  61. package/dist/types/auth.js +3 -0
  62. package/dist/types/auth.js.map +1 -0
  63. package/dist/types/event.d.ts +89 -0
  64. package/dist/types/event.d.ts.map +1 -0
  65. package/dist/types/event.js +57 -0
  66. package/dist/types/event.js.map +1 -0
  67. package/dist/types/message.d.ts +122 -0
  68. package/dist/types/message.d.ts.map +1 -0
  69. package/dist/types/message.js +10 -0
  70. package/dist/types/message.js.map +1 -0
  71. package/dist/types/thread.d.ts +58 -0
  72. package/dist/types/thread.d.ts.map +1 -0
  73. package/dist/types/thread.js +9 -0
  74. package/dist/types/thread.js.map +1 -0
  75. package/dist/types/tool-choice.d.ts +8 -0
  76. package/dist/types/tool-choice.d.ts.map +1 -0
  77. package/dist/types/tool-choice.js +3 -0
  78. package/dist/types/tool-choice.js.map +1 -0
  79. package/dist/utils/event-accumulator.d.ts +165 -0
  80. package/dist/utils/event-accumulator.d.ts.map +1 -0
  81. package/dist/utils/event-accumulator.js +1278 -0
  82. package/dist/utils/event-accumulator.js.map +1 -0
  83. package/dist/utils/json-patch.d.ts +18 -0
  84. package/dist/utils/json-patch.d.ts.map +1 -0
  85. package/dist/utils/json-patch.js +35 -0
  86. package/dist/utils/json-patch.js.map +1 -0
  87. package/dist/utils/keyed-throttle.d.ts +42 -0
  88. package/dist/utils/keyed-throttle.d.ts.map +1 -0
  89. package/dist/utils/keyed-throttle.js +86 -0
  90. package/dist/utils/keyed-throttle.js.map +1 -0
  91. package/dist/utils/registry-conversion.d.ts +53 -0
  92. package/dist/utils/registry-conversion.d.ts.map +1 -0
  93. package/dist/utils/registry-conversion.js +115 -0
  94. package/dist/utils/registry-conversion.js.map +1 -0
  95. package/dist/utils/send-message.d.ts +140 -0
  96. package/dist/utils/send-message.d.ts.map +1 -0
  97. package/dist/utils/send-message.js +183 -0
  98. package/dist/utils/send-message.js.map +1 -0
  99. package/dist/utils/stream-handler.d.ts +45 -0
  100. package/dist/utils/stream-handler.d.ts.map +1 -0
  101. package/dist/utils/stream-handler.js +47 -0
  102. package/dist/utils/stream-handler.js.map +1 -0
  103. package/dist/utils/thread-utils.d.ts +16 -0
  104. package/dist/utils/thread-utils.d.ts.map +1 -0
  105. package/dist/utils/thread-utils.js +34 -0
  106. package/dist/utils/thread-utils.js.map +1 -0
  107. package/dist/utils/tool-call-tracker.d.ts +74 -0
  108. package/dist/utils/tool-call-tracker.d.ts.map +1 -0
  109. package/dist/utils/tool-call-tracker.js +181 -0
  110. package/dist/utils/tool-call-tracker.js.map +1 -0
  111. package/dist/utils/tool-executor.d.ts +67 -0
  112. package/dist/utils/tool-executor.d.ts.map +1 -0
  113. package/dist/utils/tool-executor.js +160 -0
  114. package/dist/utils/tool-executor.js.map +1 -0
  115. package/dist/utils/unstrictify.d.ts +32 -0
  116. package/dist/utils/unstrictify.d.ts.map +1 -0
  117. package/dist/utils/unstrictify.js +160 -0
  118. package/dist/utils/unstrictify.js.map +1 -0
  119. package/esm/index.d.ts +43 -0
  120. package/esm/index.d.ts.map +1 -0
  121. package/esm/index.js +78 -0
  122. package/esm/index.js.map +1 -0
  123. package/esm/mcp/elicitation.d.ts +59 -0
  124. package/esm/mcp/elicitation.d.ts.map +1 -0
  125. package/esm/mcp/elicitation.js +27 -0
  126. package/esm/mcp/elicitation.js.map +1 -0
  127. package/esm/mcp/index.d.ts +6 -0
  128. package/esm/mcp/index.d.ts.map +1 -0
  129. package/esm/mcp/index.js +14 -0
  130. package/esm/mcp/index.js.map +1 -0
  131. package/esm/mcp/mcp-client.d.ts +185 -0
  132. package/esm/mcp/mcp-client.d.ts.map +1 -0
  133. package/esm/mcp/mcp-client.js +219 -0
  134. package/esm/mcp/mcp-client.js.map +1 -0
  135. package/esm/mcp/mcp-constants.d.ts +19 -0
  136. package/esm/mcp/mcp-constants.d.ts.map +1 -0
  137. package/esm/mcp/mcp-constants.js +21 -0
  138. package/esm/mcp/mcp-constants.js.map +1 -0
  139. package/esm/model/component-metadata.d.ts +390 -0
  140. package/esm/model/component-metadata.d.ts.map +1 -0
  141. package/esm/model/component-metadata.js +3 -0
  142. package/esm/model/component-metadata.js.map +1 -0
  143. package/esm/model/mcp-server-info.d.ts +72 -0
  144. package/esm/model/mcp-server-info.d.ts.map +1 -0
  145. package/esm/model/mcp-server-info.js +29 -0
  146. package/esm/model/mcp-server-info.js.map +1 -0
  147. package/esm/schema/index.d.ts +5 -0
  148. package/esm/schema/index.d.ts.map +1 -0
  149. package/esm/schema/index.js +15 -0
  150. package/esm/schema/index.js.map +1 -0
  151. package/esm/schema/json-schema.d.ts +42 -0
  152. package/esm/schema/json-schema.d.ts.map +1 -0
  153. package/esm/schema/json-schema.js +114 -0
  154. package/esm/schema/json-schema.js.map +1 -0
  155. package/esm/schema/schema.d.ts +49 -0
  156. package/esm/schema/schema.d.ts.map +1 -0
  157. package/esm/schema/schema.js +129 -0
  158. package/esm/schema/schema.js.map +1 -0
  159. package/esm/schema/standard-schema.d.ts +22 -0
  160. package/esm/schema/standard-schema.d.ts.map +1 -0
  161. package/esm/schema/standard-schema.js +42 -0
  162. package/esm/schema/standard-schema.js.map +1 -0
  163. package/esm/schema/validate.d.ts +14 -0
  164. package/esm/schema/validate.d.ts.map +1 -0
  165. package/esm/schema/validate.js +148 -0
  166. package/esm/schema/validate.js.map +1 -0
  167. package/esm/tambo-client.d.ts +292 -0
  168. package/esm/tambo-client.d.ts.map +1 -0
  169. package/esm/tambo-client.js +508 -0
  170. package/esm/tambo-client.js.map +1 -0
  171. package/esm/tambo-stream.d.ts +112 -0
  172. package/esm/tambo-stream.d.ts.map +1 -0
  173. package/esm/tambo-stream.js +345 -0
  174. package/esm/tambo-stream.js.map +1 -0
  175. package/esm/types/auth.d.ts +24 -0
  176. package/esm/types/auth.d.ts.map +1 -0
  177. package/esm/types/auth.js +3 -0
  178. package/esm/types/auth.js.map +1 -0
  179. package/esm/types/event.d.ts +89 -0
  180. package/esm/types/event.d.ts.map +1 -0
  181. package/esm/types/event.js +57 -0
  182. package/esm/types/event.js.map +1 -0
  183. package/esm/types/message.d.ts +122 -0
  184. package/esm/types/message.d.ts.map +1 -0
  185. package/esm/types/message.js +10 -0
  186. package/esm/types/message.js.map +1 -0
  187. package/esm/types/thread.d.ts +58 -0
  188. package/esm/types/thread.d.ts.map +1 -0
  189. package/esm/types/thread.js +9 -0
  190. package/esm/types/thread.js.map +1 -0
  191. package/esm/types/tool-choice.d.ts +8 -0
  192. package/esm/types/tool-choice.d.ts.map +1 -0
  193. package/esm/types/tool-choice.js +3 -0
  194. package/esm/types/tool-choice.js.map +1 -0
  195. package/esm/utils/event-accumulator.d.ts +165 -0
  196. package/esm/utils/event-accumulator.d.ts.map +1 -0
  197. package/esm/utils/event-accumulator.js +1278 -0
  198. package/esm/utils/event-accumulator.js.map +1 -0
  199. package/esm/utils/json-patch.d.ts +18 -0
  200. package/esm/utils/json-patch.d.ts.map +1 -0
  201. package/esm/utils/json-patch.js +35 -0
  202. package/esm/utils/json-patch.js.map +1 -0
  203. package/esm/utils/keyed-throttle.d.ts +42 -0
  204. package/esm/utils/keyed-throttle.d.ts.map +1 -0
  205. package/esm/utils/keyed-throttle.js +86 -0
  206. package/esm/utils/keyed-throttle.js.map +1 -0
  207. package/esm/utils/registry-conversion.d.ts +53 -0
  208. package/esm/utils/registry-conversion.d.ts.map +1 -0
  209. package/esm/utils/registry-conversion.js +115 -0
  210. package/esm/utils/registry-conversion.js.map +1 -0
  211. package/esm/utils/send-message.d.ts +140 -0
  212. package/esm/utils/send-message.d.ts.map +1 -0
  213. package/esm/utils/send-message.js +183 -0
  214. package/esm/utils/send-message.js.map +1 -0
  215. package/esm/utils/stream-handler.d.ts +45 -0
  216. package/esm/utils/stream-handler.d.ts.map +1 -0
  217. package/esm/utils/stream-handler.js +47 -0
  218. package/esm/utils/stream-handler.js.map +1 -0
  219. package/esm/utils/thread-utils.d.ts +16 -0
  220. package/esm/utils/thread-utils.d.ts.map +1 -0
  221. package/esm/utils/thread-utils.js +34 -0
  222. package/esm/utils/thread-utils.js.map +1 -0
  223. package/esm/utils/tool-call-tracker.d.ts +74 -0
  224. package/esm/utils/tool-call-tracker.d.ts.map +1 -0
  225. package/esm/utils/tool-call-tracker.js +181 -0
  226. package/esm/utils/tool-call-tracker.js.map +1 -0
  227. package/esm/utils/tool-executor.d.ts +67 -0
  228. package/esm/utils/tool-executor.d.ts.map +1 -0
  229. package/esm/utils/tool-executor.js +160 -0
  230. package/esm/utils/tool-executor.js.map +1 -0
  231. package/esm/utils/unstrictify.d.ts +32 -0
  232. package/esm/utils/unstrictify.d.ts.map +1 -0
  233. package/esm/utils/unstrictify.js +160 -0
  234. package/esm/utils/unstrictify.js.map +1 -0
  235. package/package.json +90 -0
@@ -0,0 +1,112 @@
1
+ /**
2
+ * TamboStream - Streaming response handler for Tambo AI
3
+ *
4
+ * Provides two consumption modes:
5
+ * 1. AsyncIterable: `for await (const { event, snapshot } of stream) { ... }`
6
+ * 2. Promise: `const thread = await stream.thread`
7
+ *
8
+ * The internal processing loop always runs (fire-and-forget in constructor).
9
+ * The `.thread` promise resolves when the loop completes.
10
+ */
11
+ import { type BaseEvent } from "@ag-ui/core";
12
+ import type TamboAI from "@tambo-ai/typescript-sdk";
13
+ import type { TamboThread } from "./types/thread.js";
14
+ import type { ToolChoice } from "./types/tool-choice.js";
15
+ import type { InputMessage } from "./types/message.js";
16
+ import type { ComponentRegistry, TamboToolRegistry } from "./model/component-metadata.js";
17
+ import type { StreamAction } from "./utils/event-accumulator.js";
18
+ /**
19
+ * Event yielded by the TamboStream async iterator.
20
+ */
21
+ export interface StreamEvent {
22
+ /** The raw AG-UI event. */
23
+ event: BaseEvent;
24
+ /** A snapshot of the thread state after this event was processed. */
25
+ snapshot: TamboThread;
26
+ }
27
+ /**
28
+ * Options for creating a TamboStream.
29
+ */
30
+ export interface TamboStreamOptions {
31
+ /** The Tambo API client. */
32
+ client: TamboAI;
33
+ /** The message to send. */
34
+ message: InputMessage;
35
+ /** Existing thread ID (undefined = create new). */
36
+ threadId: string | undefined;
37
+ /** User message text for optimistic display. */
38
+ userMessageText?: string;
39
+ /** Registered components. */
40
+ componentList: ComponentRegistry;
41
+ /** Registered tools. */
42
+ toolRegistry: TamboToolRegistry;
43
+ /** User key for auth. */
44
+ userKey: string | undefined;
45
+ /** Previous run ID for continuations. */
46
+ previousRunId: string | undefined;
47
+ /** Additional context merged into message. */
48
+ additionalContext?: Record<string, unknown>;
49
+ /** Tool choice mode. */
50
+ toolChoice?: ToolChoice;
51
+ /** Whether to auto-execute tools. */
52
+ autoExecuteTools: boolean;
53
+ /** Max tool execution rounds. */
54
+ maxSteps: number;
55
+ /** Enable debug logging. */
56
+ debug: boolean;
57
+ /** AbortSignal for cancellation. */
58
+ signal?: AbortSignal;
59
+ /** Dispatch function to update client state. */
60
+ dispatch: (action: StreamAction) => void;
61
+ /** Accessor for current thread state snapshot. */
62
+ getThreadSnapshot: (threadId: string) => TamboThread | undefined;
63
+ }
64
+ /**
65
+ * TamboStream handles streaming AI responses with tool execution.
66
+ *
67
+ * Supports two consumption modes:
68
+ * - Async iteration: `for await (const { event, snapshot } of stream) { ... }`
69
+ * - Promise-based: `const thread = await stream.thread`
70
+ *
71
+ * The processing loop runs automatically. The async iterator can only be
72
+ * iterated once (like ReadableStream).
73
+ */
74
+ export declare class TamboStream implements AsyncIterable<StreamEvent> {
75
+ private readonly options;
76
+ /** Promise that resolves to the final thread state when the stream completes. */
77
+ readonly thread: Promise<TamboThread>;
78
+ private eventQueue;
79
+ private resolveThread;
80
+ private rejectThread;
81
+ private streamError;
82
+ private abortController;
83
+ private consumed;
84
+ /**
85
+ * Create a new TamboStream.
86
+ * @param options - Configuration for the stream.
87
+ */
88
+ constructor(options: TamboStreamOptions);
89
+ /**
90
+ * Abort the stream. The `.thread` promise rejects with an AbortError.
91
+ * The async iterator ends cleanly.
92
+ */
93
+ abort(): void;
94
+ /**
95
+ * Returns an async iterator over stream events.
96
+ * Can only be iterated once.
97
+ * @returns An async iterator yielding StreamEvent pairs.
98
+ */
99
+ [Symbol.asyncIterator](): AsyncIterableIterator<StreamEvent>;
100
+ /**
101
+ * Main processing loop. Runs automatically in the constructor.
102
+ * Handles event streaming, tool execution, and stream stitching.
103
+ */
104
+ private processLoop;
105
+ /**
106
+ * Handle abort by transitioning thread to idle and rejecting the thread promise.
107
+ * @param threadId - The thread to clean up.
108
+ * @param dispatch - The dispatch function for state updates.
109
+ */
110
+ private handleAbort;
111
+ }
112
+ //# sourceMappingURL=tambo-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tambo-stream.d.ts","sourceRoot":"","sources":["../src/tambo-stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAa,KAAK,SAAS,EAAsB,MAAM,aAAa,CAAC;AAC5E,OAAO,KAAK,OAAO,MAAM,0BAA0B,CAAC;AAEpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAA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,MAAM,KAAK,WAAW,GAAG,SAAS,CAAC;CAClE;AA0ED;;;;;;;;;GASG;AACH,qBAAa,WAAY,YAAW,aAAa,CAAC,WAAW,CAAC;IAehD,OAAO,CAAC,QAAQ,CAAC,OAAO;IAdpC,iFAAiF;IACjF,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IAEtC,OAAO,CAAC,UAAU,CAAiC;IACnD,OAAO,CAAC,aAAa,CAAiC;IACtD,OAAO,CAAC,YAAY,CAA0B;IAC9C,OAAO,CAAC,WAAW,CAAsB;IACzC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,QAAQ,CAAS;IAEzB;;;OAGG;gBAC0B,OAAO,EAAE,kBAAkB;IA4BxD;;;OAGG;IACH,KAAK,IAAI,IAAI;IAIb;;;;OAIG;IACH,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,qBAAqB,CAAC,WAAW,CAAC;IAkB5D;;;OAGG;YACW,WAAW;IAuNzB;;;;OAIG;IACH,OAAO,CAAC,WAAW;CAsBpB"}
@@ -0,0 +1,345 @@
1
+ "use strict";
2
+ /**
3
+ * TamboStream - Streaming response handler for Tambo AI
4
+ *
5
+ * Provides two consumption modes:
6
+ * 1. AsyncIterable: `for await (const { event, snapshot } of stream) { ... }`
7
+ * 2. Promise: `const thread = await stream.thread`
8
+ *
9
+ * The internal processing loop always runs (fire-and-forget in constructor).
10
+ * The `.thread` promise resolves when the loop completes.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.TamboStream = void 0;
14
+ const core_1 = require("@ag-ui/core");
15
+ const event_1 = require("./types/event.js");
16
+ const stream_handler_1 = require("./utils/stream-handler.js");
17
+ const tool_call_tracker_1 = require("./utils/tool-call-tracker.js");
18
+ const tool_executor_1 = require("./utils/tool-executor.js");
19
+ const send_message_1 = require("./utils/send-message.js");
20
+ /**
21
+ * Internal event queue for bridging the processing loop and async iterator.
22
+ * Events are pushed by the processing loop and pulled by the iterator.
23
+ */
24
+ class EventQueue {
25
+ queue = [];
26
+ waiters = [];
27
+ done = false;
28
+ error = null;
29
+ /**
30
+ * Push an event into the queue.
31
+ * @param value - The event to push.
32
+ */
33
+ push(value) {
34
+ const waiter = this.waiters.shift();
35
+ if (waiter) {
36
+ waiter({ value, done: false });
37
+ }
38
+ else {
39
+ this.queue.push(value);
40
+ }
41
+ }
42
+ /**
43
+ * Close the queue normally.
44
+ */
45
+ close() {
46
+ this.done = true;
47
+ for (const waiter of this.waiters) {
48
+ waiter({ value: undefined, done: true });
49
+ }
50
+ this.waiters = [];
51
+ }
52
+ /**
53
+ * Close the queue with an error.
54
+ * @param err - The error to propagate to waiting consumers.
55
+ */
56
+ closeWithError(err) {
57
+ this.error = err;
58
+ this.done = true;
59
+ // Reject all waiters... but async iterator protocol uses throw, not reject.
60
+ // We'll store the error and throw it on next pull.
61
+ for (const waiter of this.waiters) {
62
+ waiter({ value: undefined, done: true });
63
+ }
64
+ this.waiters = [];
65
+ }
66
+ /**
67
+ * Pull the next event from the queue.
68
+ * @returns An iterator result with the next event or done signal.
69
+ */
70
+ async pull() {
71
+ if (this.error) {
72
+ const err = this.error;
73
+ this.error = null;
74
+ throw err;
75
+ }
76
+ const item = this.queue.shift();
77
+ if (item !== undefined) {
78
+ return { value: item, done: false };
79
+ }
80
+ if (this.done) {
81
+ return { value: undefined, done: true };
82
+ }
83
+ return await new Promise((resolve) => {
84
+ this.waiters.push(resolve);
85
+ });
86
+ }
87
+ }
88
+ /**
89
+ * TamboStream handles streaming AI responses with tool execution.
90
+ *
91
+ * Supports two consumption modes:
92
+ * - Async iteration: `for await (const { event, snapshot } of stream) { ... }`
93
+ * - Promise-based: `const thread = await stream.thread`
94
+ *
95
+ * The processing loop runs automatically. The async iterator can only be
96
+ * iterated once (like ReadableStream).
97
+ */
98
+ class TamboStream {
99
+ options;
100
+ /** Promise that resolves to the final thread state when the stream completes. */
101
+ thread;
102
+ eventQueue = new EventQueue();
103
+ resolveThread;
104
+ rejectThread;
105
+ streamError = null;
106
+ abortController;
107
+ consumed = false;
108
+ /**
109
+ * Create a new TamboStream.
110
+ * @param options - Configuration for the stream.
111
+ */
112
+ constructor(options) {
113
+ this.options = options;
114
+ this.abortController = new AbortController();
115
+ // Wire external signal to our internal abort controller
116
+ if (options.signal) {
117
+ if (options.signal.aborted) {
118
+ this.abortController.abort(options.signal.reason);
119
+ }
120
+ else {
121
+ options.signal.addEventListener("abort", () => {
122
+ this.abortController.abort(options.signal?.reason);
123
+ });
124
+ }
125
+ }
126
+ this.thread = new Promise((resolve, reject) => {
127
+ this.resolveThread = resolve;
128
+ this.rejectThread = reject;
129
+ });
130
+ // Fire-and-forget the processing loop
131
+ void this.processLoop().catch((err) => {
132
+ const error = err instanceof Error ? err : new Error(String(err));
133
+ this.streamError = error;
134
+ this.rejectThread(error);
135
+ this.eventQueue.closeWithError(error);
136
+ });
137
+ }
138
+ /**
139
+ * Abort the stream. The `.thread` promise rejects with an AbortError.
140
+ * The async iterator ends cleanly.
141
+ */
142
+ abort() {
143
+ this.abortController.abort(new Error("Stream aborted"));
144
+ }
145
+ /**
146
+ * Returns an async iterator over stream events.
147
+ * Can only be iterated once.
148
+ * @returns An async iterator yielding StreamEvent pairs.
149
+ */
150
+ [Symbol.asyncIterator]() {
151
+ if (this.consumed) {
152
+ throw new Error("TamboStream can only be iterated once");
153
+ }
154
+ this.consumed = true;
155
+ return {
156
+ next: async () => await this.eventQueue.pull(),
157
+ return: async () => {
158
+ this.eventQueue.close();
159
+ return { value: undefined, done: true };
160
+ },
161
+ [Symbol.asyncIterator]() {
162
+ return this;
163
+ },
164
+ };
165
+ }
166
+ /**
167
+ * Main processing loop. Runs automatically in the constructor.
168
+ * Handles event streaming, tool execution, and stream stitching.
169
+ */
170
+ async processLoop() {
171
+ const { client, message, threadId: initialThreadId, userMessageText, componentList, toolRegistry, userKey, previousRunId, additionalContext, toolChoice, autoExecuteTools, maxSteps, debug, dispatch, getThreadSnapshot, } = this.options;
172
+ // Generate user message ID if we have user text
173
+ const userMessageId = userMessageText
174
+ ? `user_msg_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`
175
+ : undefined;
176
+ // Dispatch user message immediately for optimistic display on existing threads
177
+ if (initialThreadId && userMessageText && userMessageId) {
178
+ (0, send_message_1.dispatchUserMessage)(dispatch, initialThreadId, userMessageId, userMessageText);
179
+ }
180
+ // Create the initial run stream
181
+ const { stream: initialStream, initialThreadId: streamThreadId } = await (0, send_message_1.createRunStream)({
182
+ client,
183
+ threadId: initialThreadId,
184
+ message,
185
+ componentList,
186
+ toolRegistry,
187
+ userKey,
188
+ previousRunId,
189
+ additionalContext,
190
+ toolChoice,
191
+ });
192
+ const toolTracker = new tool_call_tracker_1.ToolCallTracker(toolRegistry);
193
+ const throttledStreamable = (0, tool_executor_1.createThrottledStreamableExecutor)(toolTracker, toolRegistry);
194
+ let actualThreadId = streamThreadId;
195
+ let runId;
196
+ let currentStream = initialStream;
197
+ let stepCount = 0;
198
+ try {
199
+ while (true) {
200
+ // Check abort before processing each stream segment
201
+ if (this.abortController.signal.aborted) {
202
+ this.handleAbort(actualThreadId, dispatch);
203
+ return;
204
+ }
205
+ let pendingAwaitingInput;
206
+ for await (const event of (0, stream_handler_1.handleEventStream)(currentStream, { debug })) {
207
+ // Check abort on each event
208
+ if (this.abortController.signal.aborted) {
209
+ this.handleAbort(actualThreadId, dispatch);
210
+ return;
211
+ }
212
+ // Extract threadId and runId from RUN_STARTED
213
+ if (event.type === core_1.EventType.RUN_STARTED) {
214
+ runId = event.runId;
215
+ actualThreadId ??= event.threadId;
216
+ // For new threads: dispatch user message now that we have the real ID
217
+ if (!initialThreadId && userMessageText && userMessageId) {
218
+ (0, send_message_1.dispatchUserMessage)(dispatch, actualThreadId, userMessageId, userMessageText);
219
+ }
220
+ }
221
+ else if (!actualThreadId) {
222
+ throw new Error(`Expected first event to be RUN_STARTED with threadId, got: ${event.type}`);
223
+ }
224
+ toolTracker.handleEvent(event);
225
+ // Parse partial JSON for TOOL_CALL_ARGS
226
+ const parsedToolArgs = event.type === core_1.EventType.TOOL_CALL_ARGS
227
+ ? toolTracker.parsePartialArgs(event.toolCallId)
228
+ : undefined;
229
+ dispatch({
230
+ type: "EVENT",
231
+ event,
232
+ threadId: actualThreadId,
233
+ parsedToolArgs,
234
+ toolSchemas: toolTracker.toolSchemas,
235
+ });
236
+ // Schedule debounced streamable tool execution
237
+ if (parsedToolArgs && event.type === core_1.EventType.TOOL_CALL_ARGS) {
238
+ throttledStreamable.schedule(event.toolCallId, parsedToolArgs);
239
+ }
240
+ // Emit event to async iterator
241
+ const snapshot = getThreadSnapshot(actualThreadId);
242
+ if (snapshot) {
243
+ this.eventQueue.push({ event, snapshot });
244
+ }
245
+ // Handle awaiting_input for tool execution
246
+ if (event.type === core_1.EventType.CUSTOM) {
247
+ const customEvent = (0, event_1.asTamboCustomEvent)(event);
248
+ if (customEvent?.name === "tambo.run.awaiting_input") {
249
+ pendingAwaitingInput = customEvent;
250
+ break;
251
+ }
252
+ }
253
+ }
254
+ throttledStreamable.flush();
255
+ // Stream finished without awaiting_input - we're done
256
+ if (!pendingAwaitingInput) {
257
+ break;
258
+ }
259
+ // Don't execute tools if auto-execute is off
260
+ if (!autoExecuteTools) {
261
+ break;
262
+ }
263
+ // Check step limit
264
+ stepCount++;
265
+ if (stepCount >= maxSteps) {
266
+ console.warn(`[TamboStream] maxSteps (${maxSteps}) reached. Stream resolving with pending tool calls.`);
267
+ break;
268
+ }
269
+ // Execute tools and get continuation stream
270
+ if (!runId || !actualThreadId) {
271
+ throw new Error("Cannot continue run after awaiting_input: missing runId or threadId");
272
+ }
273
+ const { stream: continuationStream, toolResults } = await (0, send_message_1.executeToolsAndContinue)({
274
+ event: pendingAwaitingInput,
275
+ toolTracker,
276
+ toolRegistry,
277
+ componentList,
278
+ client,
279
+ threadId: actualThreadId,
280
+ runId,
281
+ userKey,
282
+ additionalContext,
283
+ toolChoice,
284
+ });
285
+ (0, send_message_1.dispatchToolResults)(dispatch, actualThreadId, toolResults);
286
+ currentStream = continuationStream;
287
+ }
288
+ // Stream completed successfully
289
+ const finalSnapshot = actualThreadId
290
+ ? getThreadSnapshot(actualThreadId)
291
+ : undefined;
292
+ if (finalSnapshot) {
293
+ this.resolveThread(finalSnapshot);
294
+ }
295
+ else {
296
+ this.rejectThread(new Error("Stream completed but no thread state found"));
297
+ }
298
+ this.eventQueue.close();
299
+ }
300
+ catch (error) {
301
+ // Dispatch synthetic RUN_ERROR to clean up thread state
302
+ if (actualThreadId) {
303
+ const errorMessage = error instanceof Error ? error.message : "Unknown streaming error";
304
+ const errorEvent = {
305
+ type: core_1.EventType.RUN_ERROR,
306
+ message: errorMessage,
307
+ };
308
+ dispatch({
309
+ type: "EVENT",
310
+ event: errorEvent,
311
+ threadId: actualThreadId,
312
+ });
313
+ }
314
+ const err = error instanceof Error ? error : new Error(String(error));
315
+ this.streamError = err;
316
+ this.rejectThread(err);
317
+ this.eventQueue.closeWithError(err);
318
+ }
319
+ }
320
+ /**
321
+ * Handle abort by transitioning thread to idle and rejecting the thread promise.
322
+ * @param threadId - The thread to clean up.
323
+ * @param dispatch - The dispatch function for state updates.
324
+ */
325
+ handleAbort(threadId, dispatch) {
326
+ if (threadId) {
327
+ const errorEvent = {
328
+ type: core_1.EventType.RUN_ERROR,
329
+ message: "Stream aborted",
330
+ };
331
+ dispatch({
332
+ type: "EVENT",
333
+ event: errorEvent,
334
+ threadId,
335
+ });
336
+ }
337
+ const abortError = new Error("Stream aborted");
338
+ abortError.name = "AbortError";
339
+ this.streamError = abortError;
340
+ this.rejectThread(abortError);
341
+ this.eventQueue.close(); // Iterator ends cleanly on abort
342
+ }
343
+ }
344
+ exports.TamboStream = TamboStream;
345
+ //# sourceMappingURL=tambo-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tambo-stream.js","sourceRoot":"","sources":["../src/tambo-stream.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;AAEH,sCAA4E;AAI5E,y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:\n * 1. AsyncIterable: `for await (const { event, snapshot } of stream) { ... }`\n * 2. Promise: `const thread = await stream.thread`\n *\n * The internal processing loop always runs (fire-and-forget in constructor).\n * The `.thread` promise resolves when the loop completes.\n */\n\nimport { EventType, type BaseEvent, type RunErrorEvent } from \"@ag-ui/core\";\nimport type TamboAI from \"@tambo-ai/typescript-sdk\";\n\nimport type { TamboThread } from \"./types/thread\";\nimport { asTamboCustomEvent, type RunAwaitingInputEvent } from \"./types/event\";\nimport type { ToolChoice } from \"./types/tool-choice\";\nimport type { InputMessage } from \"./types/message\";\nimport type {\n ComponentRegistry,\n TamboToolRegistry,\n} from \"./model/component-metadata\";\nimport type { StreamAction } from \"./utils/event-accumulator\";\nimport { handleEventStream } from \"./utils/stream-handler\";\nimport { ToolCallTracker } from \"./utils/tool-call-tracker\";\nimport { createThrottledStreamableExecutor } from \"./utils/tool-executor\";\nimport {\n createRunStream,\n dispatchUserMessage,\n dispatchToolResults,\n executeToolsAndContinue,\n type CreateRunStreamResult,\n} from \"./utils/send-message\";\n\n/**\n * Event yielded by the TamboStream async iterator.\n */\nexport interface StreamEvent {\n /** The raw AG-UI event. */\n event: BaseEvent;\n /** A snapshot of the thread state after this event was processed. */\n snapshot: TamboThread;\n}\n\n/**\n * Options for creating a TamboStream.\n */\nexport interface TamboStreamOptions {\n /** The Tambo API client. */\n client: TamboAI;\n /** The message to send. */\n message: InputMessage;\n /** Existing thread ID (undefined = create new). */\n threadId: string | undefined;\n /** User message text for optimistic display. */\n userMessageText?: string;\n /** Registered components. */\n componentList: ComponentRegistry;\n /** Registered tools. */\n toolRegistry: TamboToolRegistry;\n /** User key for auth. */\n userKey: string | undefined;\n /** Previous run ID for continuations. */\n previousRunId: string | undefined;\n /** Additional context merged into message. */\n additionalContext?: Record<string, unknown>;\n /** Tool choice mode. */\n toolChoice?: ToolChoice;\n /** Whether to auto-execute tools. */\n autoExecuteTools: boolean;\n /** Max tool execution rounds. */\n maxSteps: number;\n /** Enable debug logging. */\n debug: boolean;\n /** AbortSignal for cancellation. */\n signal?: AbortSignal;\n /** Dispatch function to update client state. */\n dispatch: (action: StreamAction) => void;\n /** Accessor for current thread state snapshot. */\n getThreadSnapshot: (threadId: string) => TamboThread | undefined;\n}\n\n/**\n * Internal event queue for bridging the processing loop and async iterator.\n * Events are pushed by the processing loop and pulled by the iterator.\n */\nclass EventQueue<T> {\n private queue: T[] = [];\n private waiters: ((value: IteratorResult<T>) => void)[] = [];\n private done = false;\n private error: Error | null = null;\n\n /**\n * Push an event into the queue.\n * @param value - The event to push.\n */\n push(value: T): void {\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter({ value, done: false });\n } else {\n this.queue.push(value);\n }\n }\n\n /**\n * Close the queue normally.\n */\n close(): void {\n this.done = true;\n for (const waiter of this.waiters) {\n waiter({ value: undefined as unknown as T, done: true });\n }\n this.waiters = [];\n }\n\n /**\n * Close the queue with an error.\n * @param err - The error to propagate to waiting consumers.\n */\n closeWithError(err: Error): void {\n this.error = err;\n this.done = true;\n // Reject all waiters... but async iterator protocol uses throw, not reject.\n // We'll store the error and throw it on next pull.\n for (const waiter of this.waiters) {\n waiter({ value: undefined as unknown as T, done: true });\n }\n this.waiters = [];\n }\n\n /**\n * Pull the next event from the queue.\n * @returns An iterator result with the next event or done signal.\n */\n async pull(): Promise<IteratorResult<T>> {\n if (this.error) {\n const err = this.error;\n this.error = null;\n throw err;\n }\n const item = this.queue.shift();\n if (item !== undefined) {\n return { value: item, done: false };\n }\n if (this.done) {\n return { value: undefined as unknown as T, done: true };\n }\n return await new Promise<IteratorResult<T>>((resolve) => {\n this.waiters.push(resolve);\n });\n }\n}\n\n/**\n * TamboStream handles streaming AI responses with tool execution.\n *\n * Supports two consumption modes:\n * - Async iteration: `for await (const { event, snapshot } of stream) { ... }`\n * - Promise-based: `const thread = await stream.thread`\n *\n * The processing loop runs automatically. The async iterator can only be\n * iterated once (like ReadableStream).\n */\nexport class TamboStream implements AsyncIterable<StreamEvent> {\n /** Promise that resolves to the final thread state when the stream completes. */\n readonly thread: Promise<TamboThread>;\n\n private eventQueue = new EventQueue<StreamEvent>();\n private resolveThread!: (thread: TamboThread) => void;\n private rejectThread!: (error: Error) => void;\n private streamError: Error | null = null;\n private abortController: AbortController;\n private consumed = false;\n\n /**\n * Create a new TamboStream.\n * @param options - Configuration for the stream.\n */\n constructor(private readonly options: TamboStreamOptions) {\n this.abortController = new AbortController();\n\n // Wire external signal to our internal abort controller\n if (options.signal) {\n if (options.signal.aborted) {\n this.abortController.abort(options.signal.reason);\n } else {\n options.signal.addEventListener(\"abort\", () => {\n this.abortController.abort(options.signal?.reason);\n });\n }\n }\n\n this.thread = new Promise<TamboThread>((resolve, reject) => {\n this.resolveThread = resolve;\n this.rejectThread = reject;\n });\n\n // Fire-and-forget the processing loop\n void this.processLoop().catch((err) => {\n const error = err instanceof Error ? err : new Error(String(err));\n this.streamError = error;\n this.rejectThread(error);\n this.eventQueue.closeWithError(error);\n });\n }\n\n /**\n * Abort the stream. The `.thread` promise rejects with an AbortError.\n * The async iterator ends cleanly.\n */\n abort(): void {\n this.abortController.abort(new Error(\"Stream aborted\"));\n }\n\n /**\n * Returns an async iterator over stream events.\n * Can only be iterated once.\n * @returns An async iterator yielding StreamEvent pairs.\n */\n [Symbol.asyncIterator](): AsyncIterableIterator<StreamEvent> {\n if (this.consumed) {\n throw new Error(\"TamboStream can only be iterated once\");\n }\n this.consumed = true;\n\n return {\n next: async () => await this.eventQueue.pull(),\n return: async () => {\n this.eventQueue.close();\n return { value: undefined as unknown as StreamEvent, done: true };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n }\n\n /**\n * Main processing loop. Runs automatically in the constructor.\n * Handles event streaming, tool execution, and stream stitching.\n */\n private async processLoop(): Promise<void> {\n const {\n client,\n message,\n threadId: initialThreadId,\n userMessageText,\n componentList,\n toolRegistry,\n userKey,\n previousRunId,\n additionalContext,\n toolChoice,\n autoExecuteTools,\n maxSteps,\n debug,\n dispatch,\n getThreadSnapshot,\n } = this.options;\n\n // Generate user message ID if we have user text\n const userMessageId = userMessageText\n ? `user_msg_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`\n : undefined;\n\n // Dispatch user message immediately for optimistic display on existing threads\n if (initialThreadId && userMessageText && userMessageId) {\n dispatchUserMessage(\n dispatch,\n initialThreadId,\n userMessageId,\n userMessageText,\n );\n }\n\n // Create the initial run stream\n const { stream: initialStream, initialThreadId: streamThreadId } =\n await createRunStream({\n client,\n threadId: initialThreadId,\n message,\n componentList,\n toolRegistry,\n userKey,\n previousRunId,\n additionalContext,\n toolChoice,\n });\n\n const toolTracker = new ToolCallTracker(toolRegistry);\n const throttledStreamable = createThrottledStreamableExecutor(\n toolTracker,\n toolRegistry,\n );\n\n let actualThreadId = streamThreadId;\n let runId: string | undefined;\n let currentStream: CreateRunStreamResult[\"stream\"] = initialStream;\n let stepCount = 0;\n\n try {\n while (true) {\n // Check abort before processing each stream segment\n if (this.abortController.signal.aborted) {\n this.handleAbort(actualThreadId, dispatch);\n return;\n }\n\n let pendingAwaitingInput: RunAwaitingInputEvent | undefined;\n\n for await (const event of handleEventStream(currentStream, { debug })) {\n // Check abort on each event\n if (this.abortController.signal.aborted) {\n this.handleAbort(actualThreadId, dispatch);\n return;\n }\n\n // Extract threadId and runId from RUN_STARTED\n if (event.type === EventType.RUN_STARTED) {\n runId = event.runId;\n actualThreadId ??= event.threadId;\n\n // For new threads: dispatch user message now that we have the real ID\n if (!initialThreadId && userMessageText && userMessageId) {\n dispatchUserMessage(\n dispatch,\n actualThreadId,\n userMessageId,\n userMessageText,\n );\n }\n } else if (!actualThreadId) {\n throw new Error(\n `Expected first event to be RUN_STARTED with threadId, got: ${event.type}`,\n );\n }\n\n toolTracker.handleEvent(event);\n\n // Parse partial JSON for TOOL_CALL_ARGS\n const parsedToolArgs =\n event.type === EventType.TOOL_CALL_ARGS\n ? toolTracker.parsePartialArgs(event.toolCallId)\n : undefined;\n\n dispatch({\n type: \"EVENT\",\n event,\n threadId: actualThreadId,\n parsedToolArgs,\n toolSchemas: toolTracker.toolSchemas,\n });\n\n // Schedule debounced streamable tool execution\n if (parsedToolArgs && event.type === EventType.TOOL_CALL_ARGS) {\n throttledStreamable.schedule(event.toolCallId, parsedToolArgs);\n }\n\n // Emit event to async iterator\n const snapshot = getThreadSnapshot(actualThreadId);\n if (snapshot) {\n this.eventQueue.push({ event, snapshot });\n }\n\n // Handle awaiting_input for tool execution\n if (event.type === EventType.CUSTOM) {\n const customEvent = asTamboCustomEvent(event);\n if (customEvent?.name === \"tambo.run.awaiting_input\") {\n pendingAwaitingInput = customEvent;\n break;\n }\n }\n }\n\n throttledStreamable.flush();\n\n // Stream finished without awaiting_input - we're done\n if (!pendingAwaitingInput) {\n break;\n }\n\n // Don't execute tools if auto-execute is off\n if (!autoExecuteTools) {\n break;\n }\n\n // Check step limit\n stepCount++;\n if (stepCount >= maxSteps) {\n console.warn(\n `[TamboStream] maxSteps (${maxSteps}) reached. Stream resolving with pending tool calls.`,\n );\n break;\n }\n\n // Execute tools and get continuation stream\n if (!runId || !actualThreadId) {\n throw new Error(\n \"Cannot continue run after awaiting_input: missing runId or threadId\",\n );\n }\n\n const { stream: continuationStream, toolResults } =\n await executeToolsAndContinue({\n event: pendingAwaitingInput,\n toolTracker,\n toolRegistry,\n componentList,\n client,\n threadId: actualThreadId,\n runId,\n userKey,\n additionalContext,\n toolChoice,\n });\n\n dispatchToolResults(dispatch, actualThreadId, toolResults);\n currentStream = continuationStream;\n }\n\n // Stream completed successfully\n const finalSnapshot = actualThreadId\n ? getThreadSnapshot(actualThreadId)\n : undefined;\n\n if (finalSnapshot) {\n this.resolveThread(finalSnapshot);\n } else {\n this.rejectThread(\n new Error(\"Stream completed but no thread state found\"),\n );\n }\n this.eventQueue.close();\n } catch (error) {\n // Dispatch synthetic RUN_ERROR to clean up thread state\n if (actualThreadId) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown streaming error\";\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: errorMessage,\n };\n dispatch({\n type: \"EVENT\",\n event: errorEvent,\n threadId: actualThreadId,\n });\n }\n\n const err = error instanceof Error ? error : new Error(String(error));\n this.streamError = err;\n this.rejectThread(err);\n this.eventQueue.closeWithError(err);\n }\n }\n\n /**\n * Handle abort by transitioning thread to idle and rejecting the thread promise.\n * @param threadId - The thread to clean up.\n * @param dispatch - The dispatch function for state updates.\n */\n private handleAbort(\n threadId: string | undefined,\n dispatch: (action: StreamAction) => void,\n ): void {\n if (threadId) {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: \"Stream aborted\",\n };\n dispatch({\n type: \"EVENT\",\n event: errorEvent,\n threadId,\n });\n }\n\n const abortError = new Error(\"Stream aborted\");\n abortError.name = \"AbortError\";\n this.streamError = abortError;\n this.rejectThread(abortError);\n this.eventQueue.close(); // Iterator ends cleanly on abort\n }\n}\n"]}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Authentication state for the SDK.
3
+ *
4
+ * Discriminated union tracking the current auth lifecycle:
5
+ * - `identified`: ready to make API calls (via userKey or successful token exchange)
6
+ * - `exchanging`: userToken provided, exchange in-flight
7
+ * - `error`: token exchange failed
8
+ * - `invalid`: both userKey AND userToken provided (must choose one)
9
+ * - `unauthenticated`: neither userKey nor userToken provided
10
+ */
11
+ export type TamboAuthState = {
12
+ status: "identified";
13
+ source: "userKey" | "tokenExchange";
14
+ } | {
15
+ status: "exchanging";
16
+ } | {
17
+ status: "error";
18
+ error: Error;
19
+ } | {
20
+ status: "invalid";
21
+ } | {
22
+ status: "unauthenticated";
23
+ };
24
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/types/auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,GACtB;IAAE,MAAM,EAAE,YAAY,CAAC;IAAC,MAAM,EAAE,SAAS,GAAG,eAAe,CAAA;CAAE,GAC7D;IAAE,MAAM,EAAE,YAAY,CAAA;CAAE,GACxB;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,GACjC;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IAAE,MAAM,EAAE,iBAAiB,CAAA;CAAE,CAAC"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Authentication state for the SDK.\n *\n * Discriminated union tracking the current auth lifecycle:\n * - `identified`: ready to make API calls (via userKey or successful token exchange)\n * - `exchanging`: userToken provided, exchange in-flight\n * - `error`: token exchange failed\n * - `invalid`: both userKey AND userToken provided (must choose one)\n * - `unauthenticated`: neither userKey nor userToken provided\n */\nexport type TamboAuthState =\n | { status: \"identified\"; source: \"userKey\" | \"tokenExchange\" }\n | { status: \"exchanging\" }\n | { status: \"error\"; error: Error }\n | { status: \"invalid\" }\n | { status: \"unauthenticated\" };\n"]}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Tambo-specific Custom Event Types for Streaming API
3
+ *
4
+ * Defines custom events specific to Tambo functionality.
5
+ * For standard AG-UI events, import directly from `@ag-ui/core`.
6
+ */
7
+ import type { CustomEvent } from "@ag-ui/core";
8
+ import type { Operation } from "fast-json-patch";
9
+ type TamboCustomEventEnvelope<TName extends string, TValue> = Omit<CustomEvent, "name" | "value"> & {
10
+ name: TName;
11
+ value: TValue;
12
+ };
13
+ /**
14
+ * Component start event (custom: tambo.component.start)
15
+ */
16
+ export type ComponentStartEvent = TamboCustomEventEnvelope<"tambo.component.start", {
17
+ messageId: string;
18
+ componentId: string;
19
+ componentName: string;
20
+ }>;
21
+ /**
22
+ * Component props delta event (custom: tambo.component.props_delta)
23
+ * Uses JSON Patch (RFC 6902) to update component props
24
+ */
25
+ export type ComponentPropsDeltaEvent = TamboCustomEventEnvelope<"tambo.component.props_delta", {
26
+ componentId: string;
27
+ operations: Operation[];
28
+ }>;
29
+ /**
30
+ * Component state delta event (custom: tambo.component.state_delta)
31
+ * Uses JSON Patch (RFC 6902) to update component state
32
+ */
33
+ export type ComponentStateDeltaEvent = TamboCustomEventEnvelope<"tambo.component.state_delta", {
34
+ componentId: string;
35
+ operations: Operation[];
36
+ }>;
37
+ /**
38
+ * Component end event (custom: tambo.component.end)
39
+ */
40
+ export type ComponentEndEvent = TamboCustomEventEnvelope<"tambo.component.end", {
41
+ componentId: string;
42
+ }>;
43
+ /**
44
+ * Pending tool call information from awaiting_input event
45
+ */
46
+ export interface PendingToolCall {
47
+ toolCallId: string;
48
+ toolName: string;
49
+ arguments: string;
50
+ }
51
+ /**
52
+ * Run awaiting input event (custom: tambo.run.awaiting_input)
53
+ * Signals that the run is paused waiting for client-side tool execution
54
+ */
55
+ export type RunAwaitingInputEvent = TamboCustomEventEnvelope<"tambo.run.awaiting_input", {
56
+ pendingToolCalls: PendingToolCall[];
57
+ }>;
58
+ /**
59
+ * Message parent event (custom: tambo.message.parent)
60
+ * Emitted when a message was created during the generation of another message
61
+ * (e.g., MCP sampling or elicitation).
62
+ */
63
+ export type MessageParentEvent = TamboCustomEventEnvelope<"tambo.message.parent", {
64
+ messageId: string;
65
+ parentMessageId: string;
66
+ }>;
67
+ /**
68
+ * Union type of Tambo-specific custom events
69
+ */
70
+ export type TamboCustomEvent = ComponentStartEvent | ComponentPropsDeltaEvent | ComponentStateDeltaEvent | ComponentEndEvent | RunAwaitingInputEvent | MessageParentEvent;
71
+ /**
72
+ * Type guard to check if an event is a Tambo custom event.
73
+ * Validates that the event has a name matching known Tambo custom event types.
74
+ * @param event - Event object to check
75
+ * @param event.name - Event name to match against known Tambo event types
76
+ * @returns True if event is a TamboCustomEvent
77
+ */
78
+ export declare function isTamboCustomEvent(event: {
79
+ name?: string;
80
+ }): event is TamboCustomEvent;
81
+ /**
82
+ * Casts a CustomEvent to the specific TamboCustomEvent type based on its name.
83
+ * Uses exhaustive type checking to ensure all event types are handled.
84
+ * @param event - The CustomEvent to cast
85
+ * @returns The properly typed TamboCustomEvent, or undefined if not a known Tambo event
86
+ */
87
+ export declare function asTamboCustomEvent(event: CustomEvent): TamboCustomEvent | undefined;
88
+ export {};
89
+ //# sourceMappingURL=event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../src/types/event.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,KAAK,wBAAwB,CAAC,KAAK,SAAS,MAAM,EAAE,MAAM,IAAI,IAAI,CAChE,WAAW,EACX,MAAM,GAAG,OAAO,CACjB,GAAG;IACF,IAAI,EAAE,KAAK,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,wBAAwB,CACxD,uBAAuB,EACvB;IACE,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;CACvB,CACF,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,wBAAwB,GAAG,wBAAwB,CAC7D,6BAA6B,EAC7B;IACE,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,SAAS,EAAE,CAAC;CACzB,CACF,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,wBAAwB,GAAG,wBAAwB,CAC7D,6BAA6B,EAC7B;IACE,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,SAAS,EAAE,CAAC;CACzB,CACF,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG,wBAAwB,CACtD,qBAAqB,EACrB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