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