@langchain/langgraph-sdk 1.4.4 → 1.4.5

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 (196) hide show
  1. package/dist/_virtual/rolldown_runtime.cjs +29 -0
  2. package/dist/auth/error.cjs +79 -0
  3. package/dist/auth/error.cjs.map +1 -0
  4. package/dist/auth/error.d.cts +13 -0
  5. package/dist/auth/error.d.cts.map +1 -0
  6. package/dist/auth/error.d.ts +13 -0
  7. package/dist/auth/error.d.ts.map +1 -0
  8. package/dist/auth/error.js +78 -0
  9. package/dist/auth/error.js.map +1 -0
  10. package/dist/auth/index.cjs +39 -0
  11. package/dist/auth/index.cjs.map +1 -0
  12. package/dist/auth/index.d.cts +29 -0
  13. package/dist/auth/index.d.cts.map +1 -0
  14. package/dist/auth/index.d.ts +29 -0
  15. package/dist/auth/index.d.ts.map +1 -0
  16. package/dist/auth/index.js +37 -0
  17. package/dist/auth/index.js.map +1 -0
  18. package/dist/auth/types.d.cts +294 -0
  19. package/dist/auth/types.d.cts.map +1 -0
  20. package/dist/auth/types.d.ts +294 -0
  21. package/dist/auth/types.d.ts.map +1 -0
  22. package/dist/client.cjs +1210 -0
  23. package/dist/client.cjs.map +1 -0
  24. package/dist/client.d.cts +799 -0
  25. package/dist/client.d.cts.map +1 -0
  26. package/dist/client.d.ts +799 -0
  27. package/dist/client.d.ts.map +1 -0
  28. package/dist/client.js +1203 -0
  29. package/dist/client.js.map +1 -0
  30. package/dist/index.cjs +6 -0
  31. package/dist/index.d.cts +8 -0
  32. package/dist/index.d.ts +8 -0
  33. package/dist/index.js +4 -0
  34. package/dist/logging/index.cjs +35 -0
  35. package/dist/logging/index.cjs.map +1 -0
  36. package/dist/logging/index.d.cts +46 -0
  37. package/dist/logging/index.d.cts.map +1 -0
  38. package/dist/logging/index.d.ts +46 -0
  39. package/dist/logging/index.d.ts.map +1 -0
  40. package/dist/logging/index.js +34 -0
  41. package/dist/logging/index.js.map +1 -0
  42. package/dist/react/index.cjs +5 -0
  43. package/dist/react/index.d.cts +5 -0
  44. package/dist/react/index.d.ts +5 -0
  45. package/dist/react/index.js +4 -0
  46. package/dist/react/stream.cjs +18 -0
  47. package/dist/react/stream.cjs.map +1 -0
  48. package/dist/react/stream.custom.cjs +135 -0
  49. package/dist/react/stream.custom.cjs.map +1 -0
  50. package/dist/react/stream.custom.d.cts +40 -0
  51. package/dist/react/stream.custom.d.cts.map +1 -0
  52. package/dist/react/stream.custom.d.ts +40 -0
  53. package/dist/react/stream.custom.d.ts.map +1 -0
  54. package/dist/react/stream.custom.js +133 -0
  55. package/dist/react/stream.custom.js.map +1 -0
  56. package/dist/react/stream.d.cts +155 -0
  57. package/dist/react/stream.d.cts.map +1 -0
  58. package/dist/react/stream.d.ts +155 -0
  59. package/dist/react/stream.d.ts.map +1 -0
  60. package/dist/react/stream.js +17 -0
  61. package/dist/react/stream.js.map +1 -0
  62. package/dist/react/stream.lgp.cjs +448 -0
  63. package/dist/react/stream.lgp.cjs.map +1 -0
  64. package/dist/react/stream.lgp.js +447 -0
  65. package/dist/react/stream.lgp.js.map +1 -0
  66. package/dist/react/thread.cjs +21 -0
  67. package/dist/react/thread.cjs.map +1 -0
  68. package/dist/react/thread.js +20 -0
  69. package/dist/react/thread.js.map +1 -0
  70. package/dist/react/types.d.cts +152 -0
  71. package/dist/react/types.d.cts.map +1 -0
  72. package/dist/react/types.d.ts +152 -0
  73. package/dist/react/types.d.ts.map +1 -0
  74. package/dist/react-ui/client.cjs +138 -0
  75. package/dist/react-ui/client.cjs.map +1 -0
  76. package/dist/react-ui/client.d.cts +73 -0
  77. package/dist/react-ui/client.d.cts.map +1 -0
  78. package/dist/react-ui/client.d.ts +73 -0
  79. package/dist/react-ui/client.d.ts.map +1 -0
  80. package/dist/react-ui/client.js +132 -0
  81. package/dist/react-ui/client.js.map +1 -0
  82. package/dist/react-ui/index.cjs +14 -0
  83. package/dist/react-ui/index.cjs.map +1 -0
  84. package/dist/react-ui/index.d.cts +3 -0
  85. package/dist/react-ui/index.d.ts +3 -0
  86. package/dist/react-ui/index.js +9 -0
  87. package/dist/react-ui/index.js.map +1 -0
  88. package/dist/react-ui/server/index.cjs +5 -0
  89. package/dist/react-ui/server/index.d.cts +3 -0
  90. package/dist/react-ui/server/index.d.ts +3 -0
  91. package/dist/react-ui/server/index.js +4 -0
  92. package/dist/react-ui/server/server.cjs +57 -0
  93. package/dist/react-ui/server/server.cjs.map +1 -0
  94. package/dist/react-ui/server/server.d.cts +55 -0
  95. package/dist/react-ui/server/server.d.cts.map +1 -0
  96. package/dist/react-ui/server/server.d.ts +55 -0
  97. package/dist/react-ui/server/server.d.ts.map +1 -0
  98. package/dist/react-ui/server/server.js +56 -0
  99. package/dist/react-ui/server/server.js.map +1 -0
  100. package/dist/react-ui/types.cjs +38 -0
  101. package/dist/react-ui/types.cjs.map +1 -0
  102. package/dist/react-ui/types.d.cts +25 -0
  103. package/dist/react-ui/types.d.cts.map +1 -0
  104. package/dist/react-ui/types.d.ts +25 -0
  105. package/dist/react-ui/types.d.ts.map +1 -0
  106. package/dist/react-ui/types.js +35 -0
  107. package/dist/react-ui/types.js.map +1 -0
  108. package/dist/schema.d.cts +284 -0
  109. package/dist/schema.d.cts.map +1 -0
  110. package/dist/schema.d.ts +284 -0
  111. package/dist/schema.d.ts.map +1 -0
  112. package/dist/singletons/fetch.cjs +24 -0
  113. package/dist/singletons/fetch.cjs.map +1 -0
  114. package/dist/singletons/fetch.d.cts +14 -0
  115. package/dist/singletons/fetch.d.cts.map +1 -0
  116. package/dist/singletons/fetch.d.ts +14 -0
  117. package/dist/singletons/fetch.d.ts.map +1 -0
  118. package/dist/singletons/fetch.js +22 -0
  119. package/dist/singletons/fetch.js.map +1 -0
  120. package/dist/types.d.cts +187 -0
  121. package/dist/types.d.cts.map +1 -0
  122. package/dist/types.d.ts +187 -0
  123. package/dist/types.d.ts.map +1 -0
  124. package/dist/types.messages.d.cts +264 -0
  125. package/dist/types.messages.d.cts.map +1 -0
  126. package/dist/types.messages.d.ts +264 -0
  127. package/dist/types.messages.d.ts.map +1 -0
  128. package/dist/types.stream.d.cts +233 -0
  129. package/dist/types.stream.d.cts.map +1 -0
  130. package/dist/types.stream.d.ts +233 -0
  131. package/dist/types.stream.d.ts.map +1 -0
  132. package/dist/types.template.d.cts +19 -0
  133. package/dist/types.template.d.cts.map +1 -0
  134. package/dist/types.template.d.ts +19 -0
  135. package/dist/types.template.d.ts.map +1 -0
  136. package/dist/ui/branching.cjs +153 -0
  137. package/dist/ui/branching.cjs.map +1 -0
  138. package/dist/ui/branching.d.cts +19 -0
  139. package/dist/ui/branching.d.cts.map +1 -0
  140. package/dist/ui/branching.d.ts +19 -0
  141. package/dist/ui/branching.d.ts.map +1 -0
  142. package/dist/ui/branching.js +152 -0
  143. package/dist/ui/branching.js.map +1 -0
  144. package/dist/ui/errors.cjs +15 -0
  145. package/dist/ui/errors.cjs.map +1 -0
  146. package/dist/ui/errors.js +14 -0
  147. package/dist/ui/errors.js.map +1 -0
  148. package/dist/ui/manager.cjs +188 -0
  149. package/dist/ui/manager.cjs.map +1 -0
  150. package/dist/ui/manager.js +188 -0
  151. package/dist/ui/manager.js.map +1 -0
  152. package/dist/ui/messages.cjs +70 -0
  153. package/dist/ui/messages.cjs.map +1 -0
  154. package/dist/ui/messages.js +68 -0
  155. package/dist/ui/messages.js.map +1 -0
  156. package/dist/ui/types.d.cts +420 -0
  157. package/dist/ui/types.d.cts.map +1 -0
  158. package/dist/ui/types.d.ts +420 -0
  159. package/dist/ui/types.d.ts.map +1 -0
  160. package/dist/ui/utils.cjs +13 -0
  161. package/dist/ui/utils.cjs.map +1 -0
  162. package/dist/ui/utils.js +11 -0
  163. package/dist/ui/utils.js.map +1 -0
  164. package/dist/utils/async_caller.cjs +119 -0
  165. package/dist/utils/async_caller.cjs.map +1 -0
  166. package/dist/utils/async_caller.d.cts +51 -0
  167. package/dist/utils/async_caller.d.cts.map +1 -0
  168. package/dist/utils/async_caller.d.ts +51 -0
  169. package/dist/utils/async_caller.d.ts.map +1 -0
  170. package/dist/utils/async_caller.js +116 -0
  171. package/dist/utils/async_caller.js.map +1 -0
  172. package/dist/utils/env.cjs +13 -0
  173. package/dist/utils/env.cjs.map +1 -0
  174. package/dist/utils/env.js +12 -0
  175. package/dist/utils/env.js.map +1 -0
  176. package/dist/utils/error.cjs +17 -0
  177. package/dist/utils/error.cjs.map +1 -0
  178. package/dist/utils/error.js +16 -0
  179. package/dist/utils/error.js.map +1 -0
  180. package/dist/utils/signals.cjs +20 -0
  181. package/dist/utils/signals.cjs.map +1 -0
  182. package/dist/utils/signals.js +19 -0
  183. package/dist/utils/signals.js.map +1 -0
  184. package/dist/utils/sse.cjs +124 -0
  185. package/dist/utils/sse.cjs.map +1 -0
  186. package/dist/utils/sse.js +122 -0
  187. package/dist/utils/sse.js.map +1 -0
  188. package/dist/utils/stream.cjs +174 -0
  189. package/dist/utils/stream.cjs.map +1 -0
  190. package/dist/utils/stream.js +173 -0
  191. package/dist/utils/stream.js.map +1 -0
  192. package/dist/utils/tools.cjs +52 -0
  193. package/dist/utils/tools.cjs.map +1 -0
  194. package/dist/utils/tools.js +51 -0
  195. package/dist/utils/tools.js.map +1 -0
  196. package/package.json +1 -1
@@ -0,0 +1,1210 @@
1
+ const require_async_caller = require('./utils/async_caller.cjs');
2
+ const require_env = require('./utils/env.cjs');
3
+ const require_signals = require('./utils/signals.cjs');
4
+ const require_sse = require('./utils/sse.cjs');
5
+ const require_stream = require('./utils/stream.cjs');
6
+
7
+ //#region src/client.ts
8
+ function* iterateHeaders(headers) {
9
+ let iter;
10
+ let shouldClear = false;
11
+ if (headers instanceof Headers) {
12
+ const entries = [];
13
+ headers.forEach((value, name) => {
14
+ entries.push([name, value]);
15
+ });
16
+ iter = entries;
17
+ } else if (Array.isArray(headers)) iter = headers;
18
+ else {
19
+ shouldClear = true;
20
+ iter = Object.entries(headers ?? {});
21
+ }
22
+ for (const item of iter) {
23
+ const name = item[0];
24
+ if (typeof name !== "string") throw new TypeError(`Expected header name to be a string, got ${typeof name}`);
25
+ const values = Array.isArray(item[1]) ? item[1] : [item[1]];
26
+ let didClear = false;
27
+ for (const value of values) {
28
+ if (value === void 0) continue;
29
+ if (shouldClear && !didClear) {
30
+ didClear = true;
31
+ yield [name, null];
32
+ }
33
+ yield [name, value];
34
+ }
35
+ }
36
+ }
37
+ function mergeHeaders(...headerObjects) {
38
+ const outputHeaders = new Headers();
39
+ for (const headers of headerObjects) {
40
+ if (!headers) continue;
41
+ for (const [name, value] of iterateHeaders(headers)) if (value === null) outputHeaders.delete(name);
42
+ else outputHeaders.append(name, value);
43
+ }
44
+ const headerEntries = [];
45
+ outputHeaders.forEach((value, name) => {
46
+ headerEntries.push([name, value]);
47
+ });
48
+ return Object.fromEntries(headerEntries);
49
+ }
50
+ /**
51
+ * Get the API key from the environment.
52
+ * Precedence:
53
+ * 1. explicit argument (if string)
54
+ * 2. LANGGRAPH_API_KEY
55
+ * 3. LANGSMITH_API_KEY
56
+ * 4. LANGCHAIN_API_KEY
57
+ *
58
+ * @param apiKey - API key provided as an argument. If null, skips environment lookup. If undefined, tries environment.
59
+ * @returns The API key if found, otherwise undefined
60
+ */
61
+ function getApiKey(apiKey) {
62
+ if (apiKey === null) return;
63
+ if (apiKey) return apiKey;
64
+ for (const prefix of [
65
+ "LANGGRAPH",
66
+ "LANGSMITH",
67
+ "LANGCHAIN"
68
+ ]) {
69
+ const envKey = require_env.getEnvironmentVariable(`${prefix}_API_KEY`);
70
+ if (envKey) return envKey.trim().replace(/^["']|["']$/g, "");
71
+ }
72
+ }
73
+ const REGEX_RUN_METADATA = /(\/threads\/(?<thread_id>.+))?\/runs\/(?<run_id>.+)/;
74
+ function getRunMetadataFromResponse(response) {
75
+ const contentLocation = response.headers.get("Content-Location");
76
+ if (!contentLocation) return void 0;
77
+ const match = REGEX_RUN_METADATA.exec(contentLocation);
78
+ if (!match?.groups?.run_id) return void 0;
79
+ return {
80
+ run_id: match.groups.run_id,
81
+ thread_id: match.groups.thread_id || void 0
82
+ };
83
+ }
84
+ var BaseClient = class {
85
+ asyncCaller;
86
+ timeoutMs;
87
+ apiUrl;
88
+ defaultHeaders;
89
+ onRequest;
90
+ constructor(config) {
91
+ const callerOptions = {
92
+ maxRetries: 4,
93
+ maxConcurrency: 4,
94
+ ...config?.callerOptions
95
+ };
96
+ let defaultApiUrl = "http://localhost:8123";
97
+ if (!config?.apiUrl && typeof globalThis === "object" && globalThis != null) {
98
+ const fetchSmb = Symbol.for("langgraph_api:fetch");
99
+ const urlSmb = Symbol.for("langgraph_api:url");
100
+ const global = globalThis;
101
+ if (global[fetchSmb]) callerOptions.fetch ??= global[fetchSmb];
102
+ if (global[urlSmb]) defaultApiUrl = global[urlSmb];
103
+ }
104
+ this.asyncCaller = new require_async_caller.AsyncCaller(callerOptions);
105
+ this.timeoutMs = config?.timeoutMs;
106
+ this.apiUrl = config?.apiUrl?.replace(/\/$/, "") || defaultApiUrl;
107
+ this.defaultHeaders = config?.defaultHeaders || {};
108
+ this.onRequest = config?.onRequest;
109
+ const apiKey = getApiKey(config?.apiKey);
110
+ if (apiKey) this.defaultHeaders["x-api-key"] = apiKey;
111
+ }
112
+ prepareFetchOptions(path, options) {
113
+ const mutatedOptions = {
114
+ ...options,
115
+ headers: mergeHeaders(this.defaultHeaders, options?.headers)
116
+ };
117
+ if (mutatedOptions.json) {
118
+ mutatedOptions.body = JSON.stringify(mutatedOptions.json);
119
+ mutatedOptions.headers = mergeHeaders(mutatedOptions.headers, { "content-type": "application/json" });
120
+ delete mutatedOptions.json;
121
+ }
122
+ if (mutatedOptions.withResponse) delete mutatedOptions.withResponse;
123
+ let timeoutSignal = null;
124
+ if (typeof options?.timeoutMs !== "undefined") {
125
+ if (options.timeoutMs != null) timeoutSignal = AbortSignal.timeout(options.timeoutMs);
126
+ } else if (this.timeoutMs != null) timeoutSignal = AbortSignal.timeout(this.timeoutMs);
127
+ mutatedOptions.signal = require_signals.mergeSignals(timeoutSignal, mutatedOptions.signal);
128
+ const targetUrl = new URL(`${this.apiUrl}${path}`);
129
+ if (mutatedOptions.params) {
130
+ for (const [key, value] of Object.entries(mutatedOptions.params)) {
131
+ if (value == null) continue;
132
+ const strValue = typeof value === "string" || typeof value === "number" ? value.toString() : JSON.stringify(value);
133
+ targetUrl.searchParams.append(key, strValue);
134
+ }
135
+ delete mutatedOptions.params;
136
+ }
137
+ return [targetUrl, mutatedOptions];
138
+ }
139
+ async fetch(path, options) {
140
+ const [url, init] = this.prepareFetchOptions(path, options);
141
+ let finalInit = init;
142
+ if (this.onRequest) finalInit = await this.onRequest(url, init);
143
+ const response = await this.asyncCaller.fetch(url, finalInit);
144
+ const body = (() => {
145
+ if (response.status === 202 || response.status === 204) return;
146
+ return response.json();
147
+ })();
148
+ if (options?.withResponse) return [await body, response];
149
+ return body;
150
+ }
151
+ /**
152
+ * Protected helper for streaming with automatic retry logic.
153
+ * Handles both initial requests and reconnections with SSE.
154
+ */
155
+ async *streamWithRetry(config) {
156
+ const makeRequest = async (reconnectParams) => {
157
+ const requestEndpoint = reconnectParams?.reconnectPath || config.endpoint;
158
+ const isReconnect = !!reconnectParams?.lastEventId;
159
+ const method = isReconnect ? "GET" : config.method || "GET";
160
+ const requestHeaders = isReconnect && reconnectParams?.lastEventId ? {
161
+ ...config.headers,
162
+ "Last-Event-ID": reconnectParams.lastEventId
163
+ } : config.headers;
164
+ let [url, init] = this.prepareFetchOptions(requestEndpoint, {
165
+ method,
166
+ timeoutMs: null,
167
+ signal: config.signal,
168
+ headers: requestHeaders,
169
+ params: config.params,
170
+ json: isReconnect ? void 0 : config.json
171
+ });
172
+ if (this.onRequest != null) init = await this.onRequest(url, init);
173
+ const response = await this.asyncCaller.fetch(url, init);
174
+ if (!isReconnect && config.onInitialResponse) await config.onInitialResponse(response);
175
+ return {
176
+ response,
177
+ stream: (response.body || new ReadableStream({ start: (ctrl) => ctrl.close() })).pipeThrough(require_sse.BytesLineDecoder()).pipeThrough(require_sse.SSEDecoder())
178
+ };
179
+ };
180
+ yield* require_stream.streamWithRetry(makeRequest, {
181
+ maxRetries: config.maxRetries ?? 5,
182
+ signal: config.signal,
183
+ onReconnect: config.onReconnect
184
+ });
185
+ }
186
+ };
187
+ var CronsClient = class extends BaseClient {
188
+ /**
189
+ *
190
+ * @param threadId The ID of the thread.
191
+ * @param assistantId Assistant ID to use for this cron job.
192
+ * @param payload Payload for creating a cron job.
193
+ * @returns The created background run.
194
+ */
195
+ async createForThread(threadId, assistantId, payload) {
196
+ const json = {
197
+ schedule: payload?.schedule,
198
+ input: payload?.input,
199
+ config: payload?.config,
200
+ context: payload?.context,
201
+ metadata: payload?.metadata,
202
+ assistant_id: assistantId,
203
+ interrupt_before: payload?.interruptBefore,
204
+ interrupt_after: payload?.interruptAfter,
205
+ webhook: payload?.webhook,
206
+ multitask_strategy: payload?.multitaskStrategy,
207
+ if_not_exists: payload?.ifNotExists,
208
+ checkpoint_during: payload?.checkpointDuring,
209
+ durability: payload?.durability
210
+ };
211
+ return this.fetch(`/threads/${threadId}/runs/crons`, {
212
+ method: "POST",
213
+ json,
214
+ signal: payload?.signal
215
+ });
216
+ }
217
+ /**
218
+ *
219
+ * @param assistantId Assistant ID to use for this cron job.
220
+ * @param payload Payload for creating a cron job.
221
+ * @returns
222
+ */
223
+ async create(assistantId, payload) {
224
+ const json = {
225
+ schedule: payload?.schedule,
226
+ input: payload?.input,
227
+ config: payload?.config,
228
+ context: payload?.context,
229
+ metadata: payload?.metadata,
230
+ assistant_id: assistantId,
231
+ interrupt_before: payload?.interruptBefore,
232
+ interrupt_after: payload?.interruptAfter,
233
+ webhook: payload?.webhook,
234
+ multitask_strategy: payload?.multitaskStrategy,
235
+ if_not_exists: payload?.ifNotExists,
236
+ checkpoint_during: payload?.checkpointDuring,
237
+ durability: payload?.durability
238
+ };
239
+ return this.fetch(`/runs/crons`, {
240
+ method: "POST",
241
+ json,
242
+ signal: payload?.signal
243
+ });
244
+ }
245
+ /**
246
+ *
247
+ * @param cronId Cron ID of Cron job to delete.
248
+ */
249
+ async delete(cronId, options) {
250
+ await this.fetch(`/runs/crons/${cronId}`, {
251
+ method: "DELETE",
252
+ signal: options?.signal
253
+ });
254
+ }
255
+ /**
256
+ *
257
+ * @param query Query options.
258
+ * @returns List of crons.
259
+ */
260
+ async search(query) {
261
+ return this.fetch("/runs/crons/search", {
262
+ method: "POST",
263
+ json: {
264
+ assistant_id: query?.assistantId ?? void 0,
265
+ thread_id: query?.threadId ?? void 0,
266
+ limit: query?.limit ?? 10,
267
+ offset: query?.offset ?? 0,
268
+ sort_by: query?.sortBy ?? void 0,
269
+ sort_order: query?.sortOrder ?? void 0,
270
+ select: query?.select ?? void 0
271
+ },
272
+ signal: query?.signal
273
+ });
274
+ }
275
+ /**
276
+ * Count cron jobs matching filters.
277
+ *
278
+ * @param query.assistantId Assistant ID to filter by.
279
+ * @param query.threadId Thread ID to filter by.
280
+ * @returns Number of cron jobs matching the criteria.
281
+ */
282
+ async count(query) {
283
+ return this.fetch(`/runs/crons/count`, {
284
+ method: "POST",
285
+ json: {
286
+ assistant_id: query?.assistantId ?? void 0,
287
+ thread_id: query?.threadId ?? void 0
288
+ },
289
+ signal: query?.signal
290
+ });
291
+ }
292
+ };
293
+ var AssistantsClient = class extends BaseClient {
294
+ /**
295
+ * Get an assistant by ID.
296
+ *
297
+ * @param assistantId The ID of the assistant.
298
+ * @returns Assistant
299
+ */
300
+ async get(assistantId, options) {
301
+ return this.fetch(`/assistants/${assistantId}`, { signal: options?.signal });
302
+ }
303
+ /**
304
+ * Get the JSON representation of the graph assigned to a runnable
305
+ * @param assistantId The ID of the assistant.
306
+ * @param options.xray Whether to include subgraphs in the serialized graph representation. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
307
+ * @returns Serialized graph
308
+ */
309
+ async getGraph(assistantId, options) {
310
+ return this.fetch(`/assistants/${assistantId}/graph`, {
311
+ params: { xray: options?.xray },
312
+ signal: options?.signal
313
+ });
314
+ }
315
+ /**
316
+ * Get the state and config schema of the graph assigned to a runnable
317
+ * @param assistantId The ID of the assistant.
318
+ * @returns Graph schema
319
+ */
320
+ async getSchemas(assistantId, options) {
321
+ return this.fetch(`/assistants/${assistantId}/schemas`, { signal: options?.signal });
322
+ }
323
+ /**
324
+ * Get the schemas of an assistant by ID.
325
+ *
326
+ * @param assistantId The ID of the assistant to get the schema of.
327
+ * @param options Additional options for getting subgraphs, such as namespace or recursion extraction.
328
+ * @returns The subgraphs of the assistant.
329
+ */
330
+ async getSubgraphs(assistantId, options) {
331
+ if (options?.namespace) return this.fetch(`/assistants/${assistantId}/subgraphs/${options.namespace}`, {
332
+ params: { recurse: options?.recurse },
333
+ signal: options?.signal
334
+ });
335
+ return this.fetch(`/assistants/${assistantId}/subgraphs`, {
336
+ params: { recurse: options?.recurse },
337
+ signal: options?.signal
338
+ });
339
+ }
340
+ /**
341
+ * Create a new assistant.
342
+ * @param payload Payload for creating an assistant.
343
+ * @returns The created assistant.
344
+ */
345
+ async create(payload) {
346
+ return this.fetch("/assistants", {
347
+ method: "POST",
348
+ json: {
349
+ graph_id: payload.graphId,
350
+ config: payload.config,
351
+ context: payload.context,
352
+ metadata: payload.metadata,
353
+ assistant_id: payload.assistantId,
354
+ if_exists: payload.ifExists,
355
+ name: payload.name,
356
+ description: payload.description
357
+ },
358
+ signal: payload.signal
359
+ });
360
+ }
361
+ /**
362
+ * Update an assistant.
363
+ * @param assistantId ID of the assistant.
364
+ * @param payload Payload for updating the assistant.
365
+ * @returns The updated assistant.
366
+ */
367
+ async update(assistantId, payload) {
368
+ return this.fetch(`/assistants/${assistantId}`, {
369
+ method: "PATCH",
370
+ json: {
371
+ graph_id: payload.graphId,
372
+ config: payload.config,
373
+ context: payload.context,
374
+ metadata: payload.metadata,
375
+ name: payload.name,
376
+ description: payload.description
377
+ },
378
+ signal: payload.signal
379
+ });
380
+ }
381
+ /**
382
+ * Delete an assistant.
383
+ *
384
+ * @param assistantId ID of the assistant.
385
+ */
386
+ async delete(assistantId, options) {
387
+ return this.fetch(`/assistants/${assistantId}`, {
388
+ method: "DELETE",
389
+ signal: options?.signal
390
+ });
391
+ }
392
+ async search(query) {
393
+ const json = {
394
+ graph_id: query?.graphId ?? void 0,
395
+ name: query?.name ?? void 0,
396
+ metadata: query?.metadata ?? void 0,
397
+ limit: query?.limit ?? 10,
398
+ offset: query?.offset ?? 0,
399
+ sort_by: query?.sortBy ?? void 0,
400
+ sort_order: query?.sortOrder ?? void 0,
401
+ select: query?.select ?? void 0
402
+ };
403
+ const [assistants, response] = await this.fetch("/assistants/search", {
404
+ method: "POST",
405
+ json,
406
+ withResponse: true,
407
+ signal: query?.signal
408
+ });
409
+ if (query?.includePagination) return {
410
+ assistants,
411
+ next: response.headers.get("X-Pagination-Next")
412
+ };
413
+ return assistants;
414
+ }
415
+ /**
416
+ * Count assistants matching filters.
417
+ *
418
+ * @param query.metadata Metadata to filter by. Exact match for each key/value.
419
+ * @param query.graphId Optional graph id to filter by.
420
+ * @param query.name Optional name to filter by.
421
+ * @returns Number of assistants matching the criteria.
422
+ */
423
+ async count(query) {
424
+ return this.fetch(`/assistants/count`, {
425
+ method: "POST",
426
+ json: {
427
+ metadata: query?.metadata ?? void 0,
428
+ graph_id: query?.graphId ?? void 0,
429
+ name: query?.name ?? void 0
430
+ },
431
+ signal: query?.signal
432
+ });
433
+ }
434
+ /**
435
+ * List all versions of an assistant.
436
+ *
437
+ * @param assistantId ID of the assistant.
438
+ * @returns List of assistant versions.
439
+ */
440
+ async getVersions(assistantId, payload) {
441
+ return this.fetch(`/assistants/${assistantId}/versions`, {
442
+ method: "POST",
443
+ json: {
444
+ metadata: payload?.metadata ?? void 0,
445
+ limit: payload?.limit ?? 10,
446
+ offset: payload?.offset ?? 0
447
+ },
448
+ signal: payload?.signal
449
+ });
450
+ }
451
+ /**
452
+ * Change the version of an assistant.
453
+ *
454
+ * @param assistantId ID of the assistant.
455
+ * @param version The version to change to.
456
+ * @returns The updated assistant.
457
+ */
458
+ async setLatest(assistantId, version, options) {
459
+ return this.fetch(`/assistants/${assistantId}/latest`, {
460
+ method: "POST",
461
+ json: { version },
462
+ signal: options?.signal
463
+ });
464
+ }
465
+ };
466
+ var ThreadsClient = class extends BaseClient {
467
+ /**
468
+ * Get a thread by ID.
469
+ *
470
+ * @param threadId ID of the thread.
471
+ * @returns The thread.
472
+ */
473
+ async get(threadId, options) {
474
+ return this.fetch(`/threads/${threadId}`, { signal: options?.signal });
475
+ }
476
+ /**
477
+ * Create a new thread.
478
+ *
479
+ * @param payload Payload for creating a thread.
480
+ * @returns The created thread.
481
+ */
482
+ async create(payload) {
483
+ const ttlPayload = typeof payload?.ttl === "number" ? {
484
+ ttl: payload.ttl,
485
+ strategy: "delete"
486
+ } : payload?.ttl;
487
+ return this.fetch(`/threads`, {
488
+ method: "POST",
489
+ json: {
490
+ metadata: {
491
+ ...payload?.metadata,
492
+ graph_id: payload?.graphId
493
+ },
494
+ thread_id: payload?.threadId,
495
+ if_exists: payload?.ifExists,
496
+ supersteps: payload?.supersteps?.map((s) => ({ updates: s.updates.map((u) => ({
497
+ values: u.values,
498
+ command: u.command,
499
+ as_node: u.asNode
500
+ })) })),
501
+ ttl: ttlPayload
502
+ },
503
+ signal: payload?.signal
504
+ });
505
+ }
506
+ /**
507
+ * Copy an existing thread
508
+ * @param threadId ID of the thread to be copied
509
+ * @returns Newly copied thread
510
+ */
511
+ async copy(threadId, options) {
512
+ return this.fetch(`/threads/${threadId}/copy`, {
513
+ method: "POST",
514
+ signal: options?.signal
515
+ });
516
+ }
517
+ /**
518
+ * Update a thread.
519
+ *
520
+ * @param threadId ID of the thread.
521
+ * @param payload Payload for updating the thread.
522
+ * @returns The updated thread.
523
+ */
524
+ async update(threadId, payload) {
525
+ const ttlPayload = typeof payload?.ttl === "number" ? {
526
+ ttl: payload.ttl,
527
+ strategy: "delete"
528
+ } : payload?.ttl;
529
+ return this.fetch(`/threads/${threadId}`, {
530
+ method: "PATCH",
531
+ json: {
532
+ metadata: payload?.metadata,
533
+ ttl: ttlPayload
534
+ },
535
+ signal: payload?.signal
536
+ });
537
+ }
538
+ /**
539
+ * Delete a thread.
540
+ *
541
+ * @param threadId ID of the thread.
542
+ */
543
+ async delete(threadId, options) {
544
+ return this.fetch(`/threads/${threadId}`, {
545
+ method: "DELETE",
546
+ signal: options?.signal
547
+ });
548
+ }
549
+ /**
550
+ * List threads
551
+ *
552
+ * @param query Query options
553
+ * @returns List of threads
554
+ */
555
+ async search(query) {
556
+ return this.fetch("/threads/search", {
557
+ method: "POST",
558
+ json: {
559
+ metadata: query?.metadata ?? void 0,
560
+ ids: query?.ids ?? void 0,
561
+ limit: query?.limit ?? 10,
562
+ offset: query?.offset ?? 0,
563
+ status: query?.status,
564
+ sort_by: query?.sortBy,
565
+ sort_order: query?.sortOrder,
566
+ select: query?.select ?? void 0,
567
+ values: query?.values ?? void 0
568
+ },
569
+ signal: query?.signal
570
+ });
571
+ }
572
+ /**
573
+ * Count threads matching filters.
574
+ *
575
+ * @param query.metadata Thread metadata to filter on.
576
+ * @param query.values State values to filter on.
577
+ * @param query.status Thread status to filter on.
578
+ * @returns Number of threads matching the criteria.
579
+ */
580
+ async count(query) {
581
+ return this.fetch(`/threads/count`, {
582
+ method: "POST",
583
+ json: {
584
+ metadata: query?.metadata ?? void 0,
585
+ values: query?.values ?? void 0,
586
+ status: query?.status ?? void 0
587
+ },
588
+ signal: query?.signal
589
+ });
590
+ }
591
+ /**
592
+ * Get state for a thread.
593
+ *
594
+ * @param threadId ID of the thread.
595
+ * @returns Thread state.
596
+ */
597
+ async getState(threadId, checkpoint, options) {
598
+ if (checkpoint != null) {
599
+ if (typeof checkpoint !== "string") return this.fetch(`/threads/${threadId}/state/checkpoint`, {
600
+ method: "POST",
601
+ json: {
602
+ checkpoint,
603
+ subgraphs: options?.subgraphs
604
+ },
605
+ signal: options?.signal
606
+ });
607
+ return this.fetch(`/threads/${threadId}/state/${checkpoint}`, {
608
+ params: { subgraphs: options?.subgraphs },
609
+ signal: options?.signal
610
+ });
611
+ }
612
+ return this.fetch(`/threads/${threadId}/state`, {
613
+ params: { subgraphs: options?.subgraphs },
614
+ signal: options?.signal
615
+ });
616
+ }
617
+ /**
618
+ * Add state to a thread.
619
+ *
620
+ * @param threadId The ID of the thread.
621
+ * @returns
622
+ */
623
+ async updateState(threadId, options) {
624
+ return this.fetch(`/threads/${threadId}/state`, {
625
+ method: "POST",
626
+ json: {
627
+ values: options.values,
628
+ checkpoint_id: options.checkpointId,
629
+ checkpoint: options.checkpoint,
630
+ as_node: options?.asNode
631
+ },
632
+ signal: options?.signal
633
+ });
634
+ }
635
+ /**
636
+ * Patch the metadata of a thread.
637
+ *
638
+ * @param threadIdOrConfig Thread ID or config to patch the state of.
639
+ * @param metadata Metadata to patch the state with.
640
+ */
641
+ async patchState(threadIdOrConfig, metadata, options) {
642
+ let threadId;
643
+ if (typeof threadIdOrConfig !== "string") {
644
+ if (typeof threadIdOrConfig.configurable?.thread_id !== "string") throw new Error("Thread ID is required when updating state with a config.");
645
+ threadId = threadIdOrConfig.configurable.thread_id;
646
+ } else threadId = threadIdOrConfig;
647
+ return this.fetch(`/threads/${threadId}/state`, {
648
+ method: "PATCH",
649
+ json: { metadata },
650
+ signal: options?.signal
651
+ });
652
+ }
653
+ /**
654
+ * Get all past states for a thread.
655
+ *
656
+ * @param threadId ID of the thread.
657
+ * @param options Additional options.
658
+ * @returns List of thread states.
659
+ */
660
+ async getHistory(threadId, options) {
661
+ return this.fetch(`/threads/${threadId}/history`, {
662
+ method: "POST",
663
+ json: {
664
+ limit: options?.limit ?? 10,
665
+ before: options?.before,
666
+ metadata: options?.metadata,
667
+ checkpoint: options?.checkpoint
668
+ },
669
+ signal: options?.signal
670
+ });
671
+ }
672
+ async *joinStream(threadId, options) {
673
+ yield* this.streamWithRetry({
674
+ endpoint: `/threads/${threadId}/stream`,
675
+ method: "GET",
676
+ signal: options?.signal,
677
+ headers: options?.lastEventId ? { "Last-Event-ID": options.lastEventId } : void 0,
678
+ params: options?.streamMode ? { stream_mode: options.streamMode } : void 0
679
+ });
680
+ }
681
+ };
682
+ var RunsClient = class extends BaseClient {
683
+ /**
684
+ * Create a run and stream the results.
685
+ *
686
+ * @param threadId The ID of the thread.
687
+ * @param assistantId Assistant ID to use for this run.
688
+ * @param payload Payload for creating a run.
689
+ */
690
+ async *stream(threadId, assistantId, payload) {
691
+ const json = {
692
+ input: payload?.input,
693
+ command: payload?.command,
694
+ config: payload?.config,
695
+ context: payload?.context,
696
+ metadata: payload?.metadata,
697
+ stream_mode: payload?.streamMode,
698
+ stream_subgraphs: payload?.streamSubgraphs,
699
+ stream_resumable: payload?.streamResumable,
700
+ feedback_keys: payload?.feedbackKeys,
701
+ assistant_id: assistantId,
702
+ interrupt_before: payload?.interruptBefore,
703
+ interrupt_after: payload?.interruptAfter,
704
+ checkpoint: payload?.checkpoint,
705
+ checkpoint_id: payload?.checkpointId,
706
+ webhook: payload?.webhook,
707
+ multitask_strategy: payload?.multitaskStrategy,
708
+ on_completion: payload?.onCompletion,
709
+ on_disconnect: payload?.onDisconnect,
710
+ after_seconds: payload?.afterSeconds,
711
+ if_not_exists: payload?.ifNotExists,
712
+ checkpoint_during: payload?.checkpointDuring,
713
+ durability: payload?.durability
714
+ };
715
+ yield* this.streamWithRetry({
716
+ endpoint: threadId == null ? `/runs/stream` : `/threads/${threadId}/runs/stream`,
717
+ method: "POST",
718
+ json,
719
+ signal: payload?.signal,
720
+ onInitialResponse: (response) => {
721
+ const runMetadata = getRunMetadataFromResponse(response);
722
+ if (runMetadata) payload?.onRunCreated?.(runMetadata);
723
+ }
724
+ });
725
+ }
726
+ /**
727
+ * Create a run.
728
+ *
729
+ * @param threadId The ID of the thread.
730
+ * @param assistantId Assistant ID to use for this run.
731
+ * @param payload Payload for creating a run.
732
+ * @returns The created run.
733
+ */
734
+ async create(threadId, assistantId, payload) {
735
+ const json = {
736
+ input: payload?.input,
737
+ command: payload?.command,
738
+ config: payload?.config,
739
+ context: payload?.context,
740
+ metadata: payload?.metadata,
741
+ stream_mode: payload?.streamMode,
742
+ stream_subgraphs: payload?.streamSubgraphs,
743
+ stream_resumable: payload?.streamResumable,
744
+ assistant_id: assistantId,
745
+ interrupt_before: payload?.interruptBefore,
746
+ interrupt_after: payload?.interruptAfter,
747
+ webhook: payload?.webhook,
748
+ checkpoint: payload?.checkpoint,
749
+ checkpoint_id: payload?.checkpointId,
750
+ multitask_strategy: payload?.multitaskStrategy,
751
+ after_seconds: payload?.afterSeconds,
752
+ if_not_exists: payload?.ifNotExists,
753
+ checkpoint_during: payload?.checkpointDuring,
754
+ durability: payload?.durability,
755
+ langsmith_tracer: payload?._langsmithTracer ? {
756
+ project_name: payload?._langsmithTracer?.projectName,
757
+ example_id: payload?._langsmithTracer?.exampleId
758
+ } : void 0
759
+ };
760
+ const endpoint = threadId === null ? "/runs" : `/threads/${threadId}/runs`;
761
+ const [run, response] = await this.fetch(endpoint, {
762
+ method: "POST",
763
+ json,
764
+ signal: payload?.signal,
765
+ withResponse: true
766
+ });
767
+ const runMetadata = getRunMetadataFromResponse(response);
768
+ if (runMetadata) payload?.onRunCreated?.(runMetadata);
769
+ return run;
770
+ }
771
+ /**
772
+ * Create a batch of stateless background runs.
773
+ *
774
+ * @param payloads An array of payloads for creating runs.
775
+ * @returns An array of created runs.
776
+ */
777
+ async createBatch(payloads, options) {
778
+ const filteredPayloads = payloads.map((payload) => ({
779
+ ...payload,
780
+ assistant_id: payload.assistantId
781
+ })).map((payload) => {
782
+ return Object.fromEntries(Object.entries(payload).filter(([_, v]) => v !== void 0));
783
+ });
784
+ return this.fetch("/runs/batch", {
785
+ method: "POST",
786
+ json: filteredPayloads,
787
+ signal: options?.signal
788
+ });
789
+ }
790
+ /**
791
+ * Create a run and wait for it to complete.
792
+ *
793
+ * @param threadId The ID of the thread.
794
+ * @param assistantId Assistant ID to use for this run.
795
+ * @param payload Payload for creating a run.
796
+ * @returns The last values chunk of the thread.
797
+ */
798
+ async wait(threadId, assistantId, payload) {
799
+ const json = {
800
+ input: payload?.input,
801
+ command: payload?.command,
802
+ config: payload?.config,
803
+ context: payload?.context,
804
+ metadata: payload?.metadata,
805
+ assistant_id: assistantId,
806
+ interrupt_before: payload?.interruptBefore,
807
+ interrupt_after: payload?.interruptAfter,
808
+ checkpoint: payload?.checkpoint,
809
+ checkpoint_id: payload?.checkpointId,
810
+ webhook: payload?.webhook,
811
+ multitask_strategy: payload?.multitaskStrategy,
812
+ on_completion: payload?.onCompletion,
813
+ on_disconnect: payload?.onDisconnect,
814
+ after_seconds: payload?.afterSeconds,
815
+ if_not_exists: payload?.ifNotExists,
816
+ checkpoint_during: payload?.checkpointDuring,
817
+ durability: payload?.durability,
818
+ langsmith_tracer: payload?._langsmithTracer ? {
819
+ project_name: payload?._langsmithTracer?.projectName,
820
+ example_id: payload?._langsmithTracer?.exampleId
821
+ } : void 0
822
+ };
823
+ const endpoint = threadId == null ? `/runs/wait` : `/threads/${threadId}/runs/wait`;
824
+ const [run, response] = await this.fetch(endpoint, {
825
+ method: "POST",
826
+ json,
827
+ timeoutMs: null,
828
+ signal: payload?.signal,
829
+ withResponse: true
830
+ });
831
+ const runMetadata = getRunMetadataFromResponse(response);
832
+ if (runMetadata) payload?.onRunCreated?.(runMetadata);
833
+ if ((payload?.raiseError !== void 0 ? payload.raiseError : true) && "__error__" in run && typeof run.__error__ === "object" && run.__error__ && "error" in run.__error__ && "message" in run.__error__) throw new Error(`${run.__error__?.error}: ${run.__error__?.message}`);
834
+ return run;
835
+ }
836
+ /**
837
+ * List all runs for a thread.
838
+ *
839
+ * @param threadId The ID of the thread.
840
+ * @param options Filtering and pagination options.
841
+ * @returns List of runs.
842
+ */
843
+ async list(threadId, options) {
844
+ return this.fetch(`/threads/${threadId}/runs`, {
845
+ params: {
846
+ limit: options?.limit ?? 10,
847
+ offset: options?.offset ?? 0,
848
+ status: options?.status ?? void 0,
849
+ select: options?.select ?? void 0
850
+ },
851
+ signal: options?.signal
852
+ });
853
+ }
854
+ /**
855
+ * Get a run by ID.
856
+ *
857
+ * @param threadId The ID of the thread.
858
+ * @param runId The ID of the run.
859
+ * @returns The run.
860
+ */
861
+ async get(threadId, runId, options) {
862
+ return this.fetch(`/threads/${threadId}/runs/${runId}`, { signal: options?.signal });
863
+ }
864
+ /**
865
+ * Cancel a run.
866
+ *
867
+ * @param threadId The ID of the thread.
868
+ * @param runId The ID of the run.
869
+ * @param wait Whether to block when canceling
870
+ * @param action Action to take when cancelling the run. Possible values are `interrupt` or `rollback`. Default is `interrupt`.
871
+ * @returns
872
+ */
873
+ async cancel(threadId, runId, wait = false, action = "interrupt", options = {}) {
874
+ return this.fetch(`/threads/${threadId}/runs/${runId}/cancel`, {
875
+ method: "POST",
876
+ params: {
877
+ wait: wait ? "1" : "0",
878
+ action
879
+ },
880
+ signal: options?.signal
881
+ });
882
+ }
883
+ /**
884
+ * Block until a run is done.
885
+ *
886
+ * @param threadId The ID of the thread.
887
+ * @param runId The ID of the run.
888
+ * @returns
889
+ */
890
+ async join(threadId, runId, options) {
891
+ return this.fetch(`/threads/${threadId}/runs/${runId}/join`, {
892
+ timeoutMs: null,
893
+ signal: options?.signal
894
+ });
895
+ }
896
+ /**
897
+ * Stream output from a run in real-time, until the run is done.
898
+ *
899
+ * @param threadId The ID of the thread. Can be set to `null` | `undefined` for stateless runs.
900
+ * @param runId The ID of the run.
901
+ * @param options Additional options for controlling the stream behavior:
902
+ * - signal: An AbortSignal that can be used to cancel the stream request
903
+ * - lastEventId: The ID of the last event received. Can be used to reconnect to a stream without losing events.
904
+ * - cancelOnDisconnect: When true, automatically cancels the run if the client disconnects from the stream
905
+ * - streamMode: Controls what types of events to receive from the stream (can be a single mode or array of modes)
906
+ * Must be a subset of the stream modes passed when creating the run. Background runs default to having the union of all
907
+ * stream modes enabled.
908
+ * @returns An async generator yielding stream parts.
909
+ */
910
+ async *joinStream(threadId, runId, options) {
911
+ const opts = typeof options === "object" && options != null && options instanceof AbortSignal ? { signal: options } : options;
912
+ yield* this.streamWithRetry({
913
+ endpoint: threadId != null ? `/threads/${threadId}/runs/${runId}/stream` : `/runs/${runId}/stream`,
914
+ method: "GET",
915
+ signal: opts?.signal,
916
+ headers: opts?.lastEventId ? { "Last-Event-ID": opts.lastEventId } : void 0,
917
+ params: {
918
+ cancel_on_disconnect: opts?.cancelOnDisconnect ? "1" : "0",
919
+ stream_mode: opts?.streamMode
920
+ }
921
+ });
922
+ }
923
+ /**
924
+ * Delete a run.
925
+ *
926
+ * @param threadId The ID of the thread.
927
+ * @param runId The ID of the run.
928
+ * @returns
929
+ */
930
+ async delete(threadId, runId, options) {
931
+ return this.fetch(`/threads/${threadId}/runs/${runId}`, {
932
+ method: "DELETE",
933
+ signal: options?.signal
934
+ });
935
+ }
936
+ };
937
+ var StoreClient = class extends BaseClient {
938
+ /**
939
+ * Store or update an item.
940
+ *
941
+ * @param namespace A list of strings representing the namespace path.
942
+ * @param key The unique identifier for the item within the namespace.
943
+ * @param value A dictionary containing the item's data.
944
+ * @param options.index Controls search indexing - null (use defaults), false (disable), or list of field paths to index.
945
+ * @param options.ttl Optional time-to-live in minutes for the item, or null for no expiration.
946
+ * @returns Promise<void>
947
+ *
948
+ * @example
949
+ * ```typescript
950
+ * await client.store.putItem(
951
+ * ["documents", "user123"],
952
+ * "item456",
953
+ * { title: "My Document", content: "Hello World" },
954
+ * { ttl: 60 } // expires in 60 minutes
955
+ * );
956
+ * ```
957
+ */
958
+ async putItem(namespace, key, value, options) {
959
+ namespace.forEach((label) => {
960
+ if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
961
+ });
962
+ const payload = {
963
+ namespace,
964
+ key,
965
+ value,
966
+ index: options?.index,
967
+ ttl: options?.ttl
968
+ };
969
+ return this.fetch("/store/items", {
970
+ method: "PUT",
971
+ json: payload,
972
+ signal: options?.signal
973
+ });
974
+ }
975
+ /**
976
+ * Retrieve a single item.
977
+ *
978
+ * @param namespace A list of strings representing the namespace path.
979
+ * @param key The unique identifier for the item.
980
+ * @param options.refreshTtl Whether to refresh the TTL on this read operation. If null, uses the store's default behavior.
981
+ * @returns Promise<Item>
982
+ *
983
+ * @example
984
+ * ```typescript
985
+ * const item = await client.store.getItem(
986
+ * ["documents", "user123"],
987
+ * "item456",
988
+ * { refreshTtl: true }
989
+ * );
990
+ * console.log(item);
991
+ * // {
992
+ * // namespace: ["documents", "user123"],
993
+ * // key: "item456",
994
+ * // value: { title: "My Document", content: "Hello World" },
995
+ * // createdAt: "2024-07-30T12:00:00Z",
996
+ * // updatedAt: "2024-07-30T12:00:00Z"
997
+ * // }
998
+ * ```
999
+ */
1000
+ async getItem(namespace, key, options) {
1001
+ namespace.forEach((label) => {
1002
+ if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
1003
+ });
1004
+ const params = {
1005
+ namespace: namespace.join("."),
1006
+ key
1007
+ };
1008
+ if (options?.refreshTtl !== void 0) params.refresh_ttl = options.refreshTtl;
1009
+ const response = await this.fetch("/store/items", {
1010
+ params,
1011
+ signal: options?.signal
1012
+ });
1013
+ return response ? {
1014
+ ...response,
1015
+ createdAt: response.created_at,
1016
+ updatedAt: response.updated_at
1017
+ } : null;
1018
+ }
1019
+ /**
1020
+ * Delete an item.
1021
+ *
1022
+ * @param namespace A list of strings representing the namespace path.
1023
+ * @param key The unique identifier for the item.
1024
+ * @returns Promise<void>
1025
+ */
1026
+ async deleteItem(namespace, key, options) {
1027
+ namespace.forEach((label) => {
1028
+ if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`);
1029
+ });
1030
+ return this.fetch("/store/items", {
1031
+ method: "DELETE",
1032
+ json: {
1033
+ namespace,
1034
+ key
1035
+ },
1036
+ signal: options?.signal
1037
+ });
1038
+ }
1039
+ /**
1040
+ * Search for items within a namespace prefix.
1041
+ *
1042
+ * @param namespacePrefix List of strings representing the namespace prefix.
1043
+ * @param options.filter Optional dictionary of key-value pairs to filter results.
1044
+ * @param options.limit Maximum number of items to return (default is 10).
1045
+ * @param options.offset Number of items to skip before returning results (default is 0).
1046
+ * @param options.query Optional search query.
1047
+ * @param options.refreshTtl Whether to refresh the TTL on items returned by this search. If null, uses the store's default behavior.
1048
+ * @returns Promise<SearchItemsResponse>
1049
+ *
1050
+ * @example
1051
+ * ```typescript
1052
+ * const results = await client.store.searchItems(
1053
+ * ["documents"],
1054
+ * {
1055
+ * filter: { author: "John Doe" },
1056
+ * limit: 5,
1057
+ * refreshTtl: true
1058
+ * }
1059
+ * );
1060
+ * console.log(results);
1061
+ * // {
1062
+ * // items: [
1063
+ * // {
1064
+ * // namespace: ["documents", "user123"],
1065
+ * // key: "item789",
1066
+ * // value: { title: "Another Document", author: "John Doe" },
1067
+ * // createdAt: "2024-07-30T12:00:00Z",
1068
+ * // updatedAt: "2024-07-30T12:00:00Z"
1069
+ * // },
1070
+ * // // ... additional items ...
1071
+ * // ]
1072
+ * // }
1073
+ * ```
1074
+ */
1075
+ async searchItems(namespacePrefix, options) {
1076
+ const payload = {
1077
+ namespace_prefix: namespacePrefix,
1078
+ filter: options?.filter,
1079
+ limit: options?.limit ?? 10,
1080
+ offset: options?.offset ?? 0,
1081
+ query: options?.query,
1082
+ refresh_ttl: options?.refreshTtl
1083
+ };
1084
+ return { items: (await this.fetch("/store/items/search", {
1085
+ method: "POST",
1086
+ json: payload,
1087
+ signal: options?.signal
1088
+ })).items.map((item) => ({
1089
+ ...item,
1090
+ createdAt: item.created_at,
1091
+ updatedAt: item.updated_at
1092
+ })) };
1093
+ }
1094
+ /**
1095
+ * List namespaces with optional match conditions.
1096
+ *
1097
+ * @param options.prefix Optional list of strings representing the prefix to filter namespaces.
1098
+ * @param options.suffix Optional list of strings representing the suffix to filter namespaces.
1099
+ * @param options.maxDepth Optional integer specifying the maximum depth of namespaces to return.
1100
+ * @param options.limit Maximum number of namespaces to return (default is 100).
1101
+ * @param options.offset Number of namespaces to skip before returning results (default is 0).
1102
+ * @returns Promise<ListNamespaceResponse>
1103
+ */
1104
+ async listNamespaces(options) {
1105
+ const payload = {
1106
+ prefix: options?.prefix,
1107
+ suffix: options?.suffix,
1108
+ max_depth: options?.maxDepth,
1109
+ limit: options?.limit ?? 100,
1110
+ offset: options?.offset ?? 0
1111
+ };
1112
+ return this.fetch("/store/namespaces", {
1113
+ method: "POST",
1114
+ json: payload,
1115
+ signal: options?.signal
1116
+ });
1117
+ }
1118
+ };
1119
+ var UiClient = class UiClient extends BaseClient {
1120
+ static promiseCache = {};
1121
+ static getOrCached(key, fn) {
1122
+ if (UiClient.promiseCache[key] != null) return UiClient.promiseCache[key];
1123
+ const promise = fn();
1124
+ UiClient.promiseCache[key] = promise;
1125
+ return promise;
1126
+ }
1127
+ async getComponent(assistantId, agentName) {
1128
+ return UiClient.getOrCached(`${this.apiUrl}-${assistantId}-${agentName}`, async () => {
1129
+ let [url, init] = this.prepareFetchOptions(`/ui/${assistantId}`, {
1130
+ headers: {
1131
+ Accept: "text/html",
1132
+ "Content-Type": "application/json"
1133
+ },
1134
+ method: "POST",
1135
+ json: { name: agentName }
1136
+ });
1137
+ if (this.onRequest != null) init = await this.onRequest(url, init);
1138
+ return (await this.asyncCaller.fetch(url, init)).text();
1139
+ });
1140
+ }
1141
+ };
1142
+ var Client = class {
1143
+ /**
1144
+ * The client for interacting with assistants.
1145
+ */
1146
+ assistants;
1147
+ /**
1148
+ * The client for interacting with threads.
1149
+ */
1150
+ threads;
1151
+ /**
1152
+ * The client for interacting with runs.
1153
+ */
1154
+ runs;
1155
+ /**
1156
+ * The client for interacting with cron runs.
1157
+ */
1158
+ crons;
1159
+ /**
1160
+ * The client for interacting with the KV store.
1161
+ */
1162
+ store;
1163
+ /**
1164
+ * The client for interacting with the UI.
1165
+ * @internal Used by LoadExternalComponent and the API might change in the future.
1166
+ */
1167
+ "~ui";
1168
+ /**
1169
+ * @internal Used to obtain a stable key representing the client.
1170
+ */
1171
+ "~configHash";
1172
+ constructor(config) {
1173
+ this["~configHash"] = JSON.stringify({
1174
+ apiUrl: config?.apiUrl,
1175
+ apiKey: config?.apiKey,
1176
+ timeoutMs: config?.timeoutMs,
1177
+ defaultHeaders: config?.defaultHeaders,
1178
+ maxConcurrency: config?.callerOptions?.maxConcurrency,
1179
+ maxRetries: config?.callerOptions?.maxRetries,
1180
+ callbacks: {
1181
+ onFailedResponseHook: config?.callerOptions?.onFailedResponseHook != null,
1182
+ onRequest: config?.onRequest != null,
1183
+ fetch: config?.callerOptions?.fetch != null
1184
+ }
1185
+ });
1186
+ this.assistants = new AssistantsClient(config);
1187
+ this.threads = new ThreadsClient(config);
1188
+ this.runs = new RunsClient(config);
1189
+ this.crons = new CronsClient(config);
1190
+ this.store = new StoreClient(config);
1191
+ this["~ui"] = new UiClient(config);
1192
+ }
1193
+ };
1194
+ /**
1195
+ * @internal Used to obtain a stable key representing the client.
1196
+ */
1197
+ function getClientConfigHash(client) {
1198
+ return client["~configHash"];
1199
+ }
1200
+
1201
+ //#endregion
1202
+ exports.AssistantsClient = AssistantsClient;
1203
+ exports.Client = Client;
1204
+ exports.CronsClient = CronsClient;
1205
+ exports.RunsClient = RunsClient;
1206
+ exports.StoreClient = StoreClient;
1207
+ exports.ThreadsClient = ThreadsClient;
1208
+ exports.getApiKey = getApiKey;
1209
+ exports.getClientConfigHash = getClientConfigHash;
1210
+ //# sourceMappingURL=client.cjs.map