@kortyx/runtime 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/index.d.ts +131 -11
  3. package/dist/index.js +1311 -25
  4. package/dist/index.js.map +1 -0
  5. package/package.json +6 -5
  6. package/dist/checkpointer.d.ts +0 -3
  7. package/dist/checkpointer.d.ts.map +0 -1
  8. package/dist/checkpointer.js +0 -20
  9. package/dist/framework/adapter.d.ts +0 -21
  10. package/dist/framework/adapter.d.ts.map +0 -1
  11. package/dist/framework/adapter.js +0 -74
  12. package/dist/framework/in-memory-checkpointer.d.ts +0 -9
  13. package/dist/framework/in-memory-checkpointer.d.ts.map +0 -1
  14. package/dist/framework/in-memory-checkpointer.js +0 -134
  15. package/dist/framework/pending-requests.d.ts +0 -33
  16. package/dist/framework/pending-requests.d.ts.map +0 -1
  17. package/dist/framework/pending-requests.js +0 -32
  18. package/dist/framework/redis/pending-request-store.d.ts +0 -8
  19. package/dist/framework/redis/pending-request-store.d.ts.map +0 -1
  20. package/dist/framework/redis/pending-request-store.js +0 -30
  21. package/dist/framework/redis/redis-checkpointer.d.ts +0 -13
  22. package/dist/framework/redis/redis-checkpointer.d.ts.map +0 -1
  23. package/dist/framework/redis/redis-checkpointer.js +0 -159
  24. package/dist/framework/redis/redis-client.d.ts +0 -13
  25. package/dist/framework/redis/redis-client.d.ts.map +0 -1
  26. package/dist/framework/redis/redis-client.js +0 -181
  27. package/dist/framework/redis/redis-store.d.ts +0 -20
  28. package/dist/framework/redis/redis-store.d.ts.map +0 -1
  29. package/dist/framework/redis/redis-store.js +0 -107
  30. package/dist/graph/create-langgraph.d.ts +0 -17
  31. package/dist/graph/create-langgraph.d.ts.map +0 -1
  32. package/dist/graph/create-langgraph.js +0 -312
  33. package/dist/index.d.ts.map +0 -1
  34. package/dist/interrupt/tokens.d.ts +0 -3
  35. package/dist/interrupt/tokens.d.ts.map +0 -1
  36. package/dist/interrupt/tokens.js +0 -11
  37. package/dist/node-loader.d.ts +0 -7
  38. package/dist/node-loader.d.ts.map +0 -1
  39. package/dist/node-loader.js +0 -58
  40. package/dist/node-registry.d.ts +0 -7
  41. package/dist/node-registry.d.ts.map +0 -1
  42. package/dist/node-registry.js +0 -27
  43. package/dist/registry/file-registry.d.ts +0 -9
  44. package/dist/registry/file-registry.d.ts.map +0 -1
  45. package/dist/registry/file-registry.js +0 -105
  46. package/dist/registry/in-memory-registry.d.ts +0 -6
  47. package/dist/registry/in-memory-registry.d.ts.map +0 -1
  48. package/dist/registry/in-memory-registry.js +0 -25
  49. package/dist/registry/interface.d.ts +0 -12
  50. package/dist/registry/interface.d.ts.map +0 -1
  51. package/dist/registry/interface.js +0 -2
  52. package/dist/state/build-initial-state.d.ts +0 -9
  53. package/dist/state/build-initial-state.d.ts.map +0 -1
  54. package/dist/state/build-initial-state.js +0 -18
package/dist/index.js CHANGED
@@ -1,26 +1,1312 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
15
8
  };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./checkpointer"), exports);
18
- __exportStar(require("./framework/adapter"), exports);
19
- __exportStar(require("./framework/pending-requests"), exports);
20
- __exportStar(require("./graph/create-langgraph"), exports);
21
- __exportStar(require("./interrupt/tokens"), exports);
22
- __exportStar(require("./node-registry"), exports);
23
- __exportStar(require("./registry/file-registry"), exports);
24
- __exportStar(require("./registry/in-memory-registry"), exports);
25
- __exportStar(require("./registry/interface"), exports);
26
- __exportStar(require("./state/build-initial-state"), exports);
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/index.ts
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ buildInitialGraphState: () => buildInitialGraphState,
23
+ clearRegisteredNodes: () => clearRegisteredNodes,
24
+ createFileWorkflowRegistry: () => createFileWorkflowRegistry,
25
+ createFrameworkAdapterFromEnv: () => createFrameworkAdapterFromEnv,
26
+ createInMemoryFrameworkAdapter: () => createInMemoryFrameworkAdapter,
27
+ createInMemoryPendingRequestStore: () => createInMemoryPendingRequestStore,
28
+ createInMemoryWorkflowRegistry: () => createInMemoryWorkflowRegistry,
29
+ createLangGraph: () => createLangGraph,
30
+ createRedisFrameworkAdapter: () => createRedisFrameworkAdapter,
31
+ getCheckpointer: () => getCheckpointer,
32
+ getRegisteredNode: () => getRegisteredNode,
33
+ listRegisteredNodes: () => listRegisteredNodes,
34
+ makeRequestId: () => makeRequestId,
35
+ makeResumeToken: () => makeResumeToken,
36
+ registerNode: () => registerNode,
37
+ resolveNode: () => resolveNode
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/framework/in-memory-checkpointer.ts
42
+ var import_langgraph_checkpoint = require("@langchain/langgraph-checkpoint");
43
+ var utf8Bytes = (s) => new Uint8Array(Buffer.from(s, "utf8"));
44
+ var utf8String = (u8) => typeof u8 === "string" ? u8 : Buffer.from(u8).toString("utf8");
45
+ var jsonSerde = {
46
+ async dumpsTyped(data) {
47
+ return ["json", utf8Bytes(JSON.stringify(data))];
48
+ },
49
+ async loadsTyped(_type, data) {
50
+ return JSON.parse(utf8String(data));
51
+ }
52
+ };
53
+ function createInMemoryCheckpointSaver(options) {
54
+ const maxWritesPerCheckpoint = options?.maxWritesPerCheckpoint ?? 2e3;
55
+ const latest = /* @__PURE__ */ new Map();
56
+ const checkpoints = /* @__PURE__ */ new Map();
57
+ const nsKey = (threadId, checkpointNs) => `${threadId}${checkpointNs}`;
58
+ const chkKey = (threadId, checkpointNs, checkpointId) => `${threadId}${checkpointNs}${checkpointId}`;
59
+ const saver = {
60
+ serde: jsonSerde,
61
+ async get(config) {
62
+ const value = await saver.getTuple(config);
63
+ return value ? value.checkpoint : void 0;
64
+ },
65
+ getNextVersion(current) {
66
+ if (typeof current === "string") {
67
+ throw new Error("Please override this method to use string versions.");
68
+ }
69
+ return current !== void 0 && typeof current === "number" ? current + 1 : 1;
70
+ },
71
+ async getTuple(config) {
72
+ const threadId = config.configurable?.thread_id;
73
+ const checkpointNs = config.configurable?.checkpoint_ns ?? "";
74
+ if (!threadId) return void 0;
75
+ const requested = (0, import_langgraph_checkpoint.getCheckpointId)(config);
76
+ const id = requested || latest.get(nsKey(threadId, checkpointNs));
77
+ if (!id) return void 0;
78
+ const stored = checkpoints.get(chkKey(threadId, checkpointNs, id));
79
+ if (!stored) return void 0;
80
+ const pendingWrites = Array.from(stored.writes.values());
81
+ const tuple = {
82
+ config: {
83
+ configurable: {
84
+ thread_id: threadId,
85
+ checkpoint_ns: checkpointNs,
86
+ checkpoint_id: id
87
+ }
88
+ },
89
+ checkpoint: stored.checkpoint,
90
+ metadata: stored.metadata,
91
+ pendingWrites
92
+ };
93
+ if (stored.parentCheckpointId) {
94
+ tuple.parentConfig = {
95
+ configurable: {
96
+ thread_id: threadId,
97
+ checkpoint_ns: checkpointNs,
98
+ checkpoint_id: stored.parentCheckpointId
99
+ }
100
+ };
101
+ }
102
+ return tuple;
103
+ },
104
+ async *list(_config, _options) {
105
+ },
106
+ async put(config, checkpoint, metadata, _newVersions) {
107
+ const threadId = config.configurable?.thread_id;
108
+ const checkpointNs = config.configurable?.checkpoint_ns ?? "";
109
+ if (!threadId) {
110
+ throw new Error(
111
+ 'Failed to put checkpoint: missing "thread_id" in config.configurable.'
112
+ );
113
+ }
114
+ const ns = nsKey(threadId, checkpointNs);
115
+ const prevId = latest.get(ns);
116
+ const prepared = (0, import_langgraph_checkpoint.copyCheckpoint)(checkpoint);
117
+ const entry = {
118
+ checkpoint: prepared,
119
+ metadata,
120
+ parentCheckpointId: config.configurable?.checkpoint_id,
121
+ writes: /* @__PURE__ */ new Map()
122
+ };
123
+ const id = checkpoint.id;
124
+ checkpoints.set(chkKey(threadId, checkpointNs, id), entry);
125
+ latest.set(ns, id);
126
+ if (prevId && prevId !== id) {
127
+ checkpoints.delete(chkKey(threadId, checkpointNs, prevId));
128
+ }
129
+ return {
130
+ configurable: {
131
+ thread_id: threadId,
132
+ checkpoint_ns: checkpointNs,
133
+ checkpoint_id: id
134
+ }
135
+ };
136
+ },
137
+ async putWrites(config, writes, taskId) {
138
+ const threadId = config.configurable?.thread_id;
139
+ const checkpointNs = config.configurable?.checkpoint_ns ?? "";
140
+ const checkpointId = config.configurable?.checkpoint_id;
141
+ if (!threadId || !checkpointId) return;
142
+ const stored = checkpoints.get(
143
+ chkKey(threadId, checkpointNs, checkpointId)
144
+ );
145
+ if (!stored) return;
146
+ for (let idx = 0; idx < writes.length; idx++) {
147
+ const [channel, value] = writes[idx];
148
+ const mappedIdx = import_langgraph_checkpoint.WRITES_IDX_MAP[channel] ?? idx;
149
+ const key = `${taskId},${mappedIdx}`;
150
+ if (mappedIdx >= 0 && stored.writes.has(key)) continue;
151
+ if (stored.writes.size >= maxWritesPerCheckpoint) break;
152
+ stored.writes.set(key, [taskId, channel, value]);
153
+ }
154
+ },
155
+ async deleteThread(threadId) {
156
+ for (const k of Array.from(latest.keys())) {
157
+ if (k.startsWith(`${threadId}`)) latest.delete(k);
158
+ }
159
+ for (const k of Array.from(checkpoints.keys())) {
160
+ if (k.startsWith(`${threadId}`)) checkpoints.delete(k);
161
+ }
162
+ }
163
+ };
164
+ return saver;
165
+ }
166
+
167
+ // src/checkpointer.ts
168
+ var MAX_CHECKPOINTERS = 200;
169
+ var map = /* @__PURE__ */ new Map();
170
+ function getCheckpointer(key) {
171
+ const k = key || "__default__";
172
+ const existing = map.get(k);
173
+ if (existing) return existing;
174
+ const saver = createInMemoryCheckpointSaver();
175
+ map.set(k, saver);
176
+ if (map.size > MAX_CHECKPOINTERS) {
177
+ const first = map.keys().next().value;
178
+ if (first) map.delete(first);
179
+ }
180
+ return saver;
181
+ }
182
+
183
+ // src/framework/pending-requests.ts
184
+ function createInMemoryPendingRequestStore() {
185
+ const store = /* @__PURE__ */ new Map();
186
+ const prune = () => {
187
+ const t = Date.now();
188
+ for (const [k, v] of store.entries()) {
189
+ if (t - v.createdAt > v.ttlMs) store.delete(k);
190
+ }
191
+ };
192
+ return {
193
+ async save(rec) {
194
+ prune();
195
+ store.set(rec.token, rec);
196
+ },
197
+ async get(token) {
198
+ prune();
199
+ return store.get(token) ?? null;
200
+ },
201
+ async delete(token) {
202
+ store.delete(token);
203
+ },
204
+ async update(token, patch) {
205
+ const prev = store.get(token);
206
+ if (!prev) return;
207
+ store.set(token, { ...prev, ...patch });
208
+ }
209
+ };
210
+ }
211
+
212
+ // src/framework/redis/pending-request-store.ts
213
+ function createRedisPendingRequestStore(options) {
214
+ const prefix = options.prefix ?? "kortyx:pending:";
215
+ const key = (token) => `${prefix}${token}`;
216
+ return {
217
+ async save(rec) {
218
+ await options.store.set(key(rec.token), JSON.stringify(rec), rec.ttlMs);
219
+ },
220
+ async get(token) {
221
+ const raw = await options.store.get(key(token));
222
+ if (!raw) return null;
223
+ return JSON.parse(raw);
224
+ },
225
+ async delete(token) {
226
+ await options.store.del(key(token));
227
+ },
228
+ async update(token, patch) {
229
+ const prevRaw = await options.store.get(key(token));
230
+ if (!prevRaw) return;
231
+ const prev = JSON.parse(prevRaw);
232
+ const next = { ...prev, ...patch };
233
+ const ttlLeft = Math.max(1, next.ttlMs - (Date.now() - next.createdAt));
234
+ await options.store.set(key(token), JSON.stringify(next), ttlLeft);
235
+ }
236
+ };
237
+ }
238
+
239
+ // src/framework/redis/redis-checkpointer.ts
240
+ var import_langgraph_checkpoint2 = require("@langchain/langgraph-checkpoint");
241
+ var utf8Bytes2 = (s) => new Uint8Array(Buffer.from(s, "utf8"));
242
+ var utf8String2 = (u8) => typeof u8 === "string" ? u8 : Buffer.from(u8).toString("utf8");
243
+ var jsonSerde2 = {
244
+ async dumpsTyped(data) {
245
+ return ["json", utf8Bytes2(JSON.stringify(data))];
246
+ },
247
+ async loadsTyped(_type, data) {
248
+ return JSON.parse(utf8String2(data));
249
+ }
250
+ };
251
+ var b64FromBytes = (u8) => Buffer.from(u8).toString("base64");
252
+ var bytesFromB64 = (s) => new Uint8Array(Buffer.from(s, "base64"));
253
+ function createRedisCheckpointSaver(options) {
254
+ const store = options.store;
255
+ const ttlMs = options.ttlMs;
256
+ const prefix = options.prefix ?? "kortyx:cp:";
257
+ const latestKey = (threadId, checkpointNs) => `${prefix}latest:${threadId}:${checkpointNs}`;
258
+ const checkpointKey = (threadId, checkpointNs, checkpointId) => `${prefix}chk:${threadId}:${checkpointNs}:${checkpointId}`;
259
+ const writesKey = (threadId, checkpointNs, checkpointId) => `${prefix}wr:${threadId}:${checkpointNs}:${checkpointId}`;
260
+ const serde = jsonSerde2;
261
+ const saver = {
262
+ serde,
263
+ async get(config) {
264
+ const value = await saver.getTuple(config);
265
+ return value ? value.checkpoint : void 0;
266
+ },
267
+ getNextVersion(current) {
268
+ if (typeof current === "string") {
269
+ throw new Error("Please override this method to use string versions.");
270
+ }
271
+ return current !== void 0 && typeof current === "number" ? current + 1 : 1;
272
+ },
273
+ async getTuple(config) {
274
+ const threadId = config.configurable?.thread_id;
275
+ const checkpointNs = config.configurable?.checkpoint_ns ?? "";
276
+ if (!threadId) return void 0;
277
+ const requested = (0, import_langgraph_checkpoint2.getCheckpointId)(config);
278
+ const checkpointId = requested || await store.get(latestKey(threadId, checkpointNs)) || "";
279
+ if (!checkpointId) return void 0;
280
+ const raw = await store.get(
281
+ checkpointKey(threadId, checkpointNs, checkpointId)
282
+ );
283
+ if (!raw) return void 0;
284
+ const parsed = JSON.parse(raw);
285
+ const checkpoint = await serde.loadsTyped(
286
+ "json",
287
+ bytesFromB64(parsed.checkpoint)
288
+ );
289
+ const metadata = await serde.loadsTyped(
290
+ "json",
291
+ bytesFromB64(parsed.metadata)
292
+ );
293
+ const writes = await store.hgetall(
294
+ writesKey(threadId, checkpointNs, checkpointId)
295
+ );
296
+ const pendingWrites = await Promise.all(
297
+ Object.values(writes).map(async (v) => {
298
+ const w = JSON.parse(v);
299
+ return [
300
+ w.taskId,
301
+ w.channel,
302
+ await serde.loadsTyped("json", bytesFromB64(w.value))
303
+ ];
304
+ })
305
+ );
306
+ const tuple = {
307
+ config: {
308
+ configurable: {
309
+ thread_id: threadId,
310
+ checkpoint_ns: checkpointNs,
311
+ checkpoint_id: checkpointId
312
+ }
313
+ },
314
+ checkpoint,
315
+ metadata,
316
+ pendingWrites
317
+ };
318
+ if (parsed.parentCheckpointId) {
319
+ tuple.parentConfig = {
320
+ configurable: {
321
+ thread_id: threadId,
322
+ checkpoint_ns: checkpointNs,
323
+ checkpoint_id: parsed.parentCheckpointId
324
+ }
325
+ };
326
+ }
327
+ return tuple;
328
+ },
329
+ async *list(_config, _options) {
330
+ },
331
+ async put(config, checkpoint, metadata, _newVersions) {
332
+ const threadId = config.configurable?.thread_id;
333
+ const checkpointNs = config.configurable?.checkpoint_ns ?? "";
334
+ if (!threadId) {
335
+ throw new Error(
336
+ 'Failed to put checkpoint: missing "thread_id" in config.configurable.'
337
+ );
338
+ }
339
+ const prevId = await store.get(latestKey(threadId, checkpointNs));
340
+ const prepared = (0, import_langgraph_checkpoint2.copyCheckpoint)(checkpoint);
341
+ const [[, chkBytes], [, metaBytes]] = await Promise.all([
342
+ serde.dumpsTyped(prepared),
343
+ serde.dumpsTyped(metadata)
344
+ ]);
345
+ const checkpointId = checkpoint.id;
346
+ const key = checkpointKey(threadId, checkpointNs, checkpointId);
347
+ const stored = {
348
+ checkpoint: b64FromBytes(chkBytes),
349
+ metadata: b64FromBytes(metaBytes),
350
+ parentCheckpointId: config.configurable?.checkpoint_id
351
+ };
352
+ await store.set(key, JSON.stringify(stored), ttlMs);
353
+ await store.set(latestKey(threadId, checkpointNs), checkpointId, ttlMs);
354
+ if (prevId && prevId !== checkpointId) {
355
+ await store.del(checkpointKey(threadId, checkpointNs, prevId));
356
+ await store.del(writesKey(threadId, checkpointNs, prevId));
357
+ }
358
+ return {
359
+ configurable: {
360
+ thread_id: threadId,
361
+ checkpoint_ns: checkpointNs,
362
+ checkpoint_id: checkpointId
363
+ }
364
+ };
365
+ },
366
+ async putWrites(config, writes, taskId) {
367
+ const threadId = config.configurable?.thread_id;
368
+ const checkpointNs = config.configurable?.checkpoint_ns;
369
+ const checkpointId = config.configurable?.checkpoint_id;
370
+ if (!threadId) {
371
+ throw new Error(
372
+ 'Failed to put writes: missing "thread_id" in config.configurable.'
373
+ );
374
+ }
375
+ if (!checkpointId) {
376
+ throw new Error(
377
+ 'Failed to put writes: missing "checkpoint_id" in config.configurable.'
378
+ );
379
+ }
380
+ const outer = writesKey(threadId, checkpointNs ?? "", checkpointId);
381
+ await store.expire(outer, ttlMs);
382
+ await Promise.all(
383
+ writes.map(async ([channel, value], idx) => {
384
+ const [, vBytes] = await serde.dumpsTyped(value);
385
+ const mappedIdx = import_langgraph_checkpoint2.WRITES_IDX_MAP[channel] ?? idx;
386
+ const innerKeyStr = `${taskId},${mappedIdx}`;
387
+ const payload = {
388
+ taskId,
389
+ channel,
390
+ value: b64FromBytes(vBytes)
391
+ };
392
+ const serialized = JSON.stringify(payload);
393
+ if (mappedIdx >= 0) {
394
+ await store.hsetnx(outer, innerKeyStr, serialized);
395
+ } else {
396
+ await store.hset(outer, innerKeyStr, serialized);
397
+ }
398
+ })
399
+ );
400
+ },
401
+ async deleteThread(threadId) {
402
+ const chkKeys = await store.scanKeys(`${prefix}chk:${threadId}:`);
403
+ const wrKeys = await store.scanKeys(`${prefix}wr:${threadId}:`);
404
+ const latestKeys = await store.scanKeys(`${prefix}latest:${threadId}:`);
405
+ await store.delRaw([...chkKeys, ...wrKeys, ...latestKeys]);
406
+ }
407
+ };
408
+ return saver;
409
+ }
410
+
411
+ // src/framework/redis/redis-client.ts
412
+ var import_node_net = require("net");
413
+ var import_node_tls = require("tls");
414
+ var encodeBulk = (s) => {
415
+ const b = Buffer.from(s, "utf8");
416
+ return Buffer.concat([
417
+ Buffer.from(`$${b.length}\r
418
+ `),
419
+ b,
420
+ Buffer.from("\r\n")
421
+ ]);
422
+ };
423
+ var encodeCommand = (cmd, args) => {
424
+ const parts = [cmd, ...args];
425
+ const bufs = [Buffer.from(`*${parts.length}\r
426
+ `)];
427
+ for (const p of parts) bufs.push(encodeBulk(p));
428
+ return Buffer.concat(bufs);
429
+ };
430
+ function readLine(buf, start) {
431
+ const idx = buf.indexOf("\r\n", start);
432
+ if (idx === -1) return null;
433
+ return { line: buf.slice(start, idx).toString("utf8"), next: idx + 2 };
434
+ }
435
+ function parseReply(buf, start) {
436
+ if (start >= buf.length) return null;
437
+ const byte = buf[start];
438
+ if (byte === void 0) return null;
439
+ const prefix = String.fromCharCode(byte);
440
+ if (prefix === "+" || prefix === "-" || prefix === ":") {
441
+ const line = readLine(buf, start + 1);
442
+ if (!line) return null;
443
+ if (prefix === "+") return { value: line.line, next: line.next };
444
+ if (prefix === ":")
445
+ return { value: Number.parseInt(line.line, 10), next: line.next };
446
+ return { value: { type: "error", message: line.line }, next: line.next };
447
+ }
448
+ if (prefix === "$") {
449
+ const line = readLine(buf, start + 1);
450
+ if (!line) return null;
451
+ const len = Number.parseInt(line.line, 10);
452
+ if (len === -1) return { value: null, next: line.next };
453
+ const end = line.next + len;
454
+ if (end + 2 > buf.length) return null;
455
+ const data = buf.slice(line.next, end).toString("utf8");
456
+ return { value: data, next: end + 2 };
457
+ }
458
+ if (prefix === "*") {
459
+ const line = readLine(buf, start + 1);
460
+ if (!line) return null;
461
+ const count = Number.parseInt(line.line, 10);
462
+ if (count === -1) return { value: null, next: line.next };
463
+ const items = [];
464
+ let cursor = line.next;
465
+ for (let i = 0; i < count; i++) {
466
+ const parsed = parseReply(buf, cursor);
467
+ if (!parsed) return null;
468
+ items.push(parsed.value);
469
+ cursor = parsed.next;
470
+ }
471
+ return { value: items, next: cursor };
472
+ }
473
+ return {
474
+ value: { type: "error", message: `Unknown RESP prefix: ${prefix}` },
475
+ next: buf.length
476
+ };
477
+ }
478
+ function createRedisClient(options) {
479
+ const resolvedOptions = {
480
+ connectTimeoutMs: options.connectTimeoutMs ?? 5e3,
481
+ url: options.url
482
+ };
483
+ let socket = null;
484
+ let buffer = Buffer.alloc(0);
485
+ const inflight = [];
486
+ let connecting = null;
487
+ let ready = false;
488
+ const drainReplies = () => {
489
+ while (inflight.length) {
490
+ const parsed = parseReply(buffer, 0);
491
+ if (!parsed) return;
492
+ const waiter = inflight.shift();
493
+ buffer = buffer.slice(parsed.next);
494
+ waiter.resolve(parsed.value);
495
+ }
496
+ };
497
+ const send = (cmd, args = []) => {
498
+ if (!socket) return Promise.reject(new Error("Redis socket not available"));
499
+ const payload = encodeCommand(cmd, args);
500
+ return new Promise((resolve2, reject) => {
501
+ inflight.push({ resolve: resolve2, reject });
502
+ socket.write(payload);
503
+ });
504
+ };
505
+ const ensureConnected = async () => {
506
+ if (ready) return;
507
+ if (connecting) return connecting;
508
+ connecting = (async () => {
509
+ const u = new URL(resolvedOptions.url);
510
+ const isTls = u.protocol === "rediss:";
511
+ const host = u.hostname || "127.0.0.1";
512
+ const port = u.port ? Number(u.port) : isTls ? 6380 : 6379;
513
+ const password = u.password ? decodeURIComponent(u.password) : "";
514
+ const db = u.pathname && u.pathname !== "/" ? Number(u.pathname.slice(1)) : 0;
515
+ const s = isTls ? (0, import_node_tls.connect)({ host, port, servername: host }) : (0, import_node_net.connect)({ host, port });
516
+ socket = s;
517
+ s.setNoDelay(true);
518
+ s.setKeepAlive(true);
519
+ s.on("data", (chunk) => {
520
+ buffer = Buffer.concat([buffer, chunk]);
521
+ drainReplies();
522
+ });
523
+ s.on("error", (err) => {
524
+ ready = false;
525
+ while (inflight.length) inflight.shift().reject(err);
526
+ });
527
+ s.on("close", () => {
528
+ ready = false;
529
+ while (inflight.length)
530
+ inflight.shift().reject(new Error("Redis socket closed"));
531
+ });
532
+ await new Promise((resolve2, reject) => {
533
+ const timer = setTimeout(
534
+ () => reject(new Error("Redis connect timeout")),
535
+ resolvedOptions.connectTimeoutMs
536
+ );
537
+ const onConnect = () => {
538
+ clearTimeout(timer);
539
+ resolve2();
540
+ };
541
+ s.once("connect", onConnect);
542
+ s.once?.("secureConnect", onConnect);
543
+ s.once("error", (e) => {
544
+ clearTimeout(timer);
545
+ reject(e);
546
+ });
547
+ });
548
+ if (password) {
549
+ const r = await send("AUTH", [password]);
550
+ if (typeof r === "object" && r && r.type === "error") {
551
+ throw new Error(`Redis AUTH failed: ${r.message}`);
552
+ }
553
+ }
554
+ if (db && Number.isFinite(db) && db > 0) {
555
+ const r = await send("SELECT", [String(db)]);
556
+ if (typeof r === "object" && r && r.type === "error") {
557
+ throw new Error(`Redis SELECT failed: ${r.message}`);
558
+ }
559
+ }
560
+ ready = true;
561
+ })();
562
+ try {
563
+ await connecting;
564
+ } finally {
565
+ connecting = null;
566
+ }
567
+ };
568
+ return {
569
+ async command(cmd, args = []) {
570
+ await ensureConnected();
571
+ return send(cmd, args);
572
+ }
573
+ };
574
+ }
575
+
576
+ // src/framework/redis/redis-store.ts
577
+ var isRedisError = (r) => Boolean(r) && typeof r === "object" && r.type === "error";
578
+ function createRedisFrameworkStore(options) {
579
+ const client = createRedisClient({ url: options.url });
580
+ const prefix = options.prefix ?? "kortyx:fw:";
581
+ const k = (key) => `${prefix}${key}`;
582
+ return {
583
+ async get(key) {
584
+ const r = await client.command("GET", [k(key)]);
585
+ if (r === null) return null;
586
+ if (typeof r === "string") return r;
587
+ if (isRedisError(r)) {
588
+ throw new Error(`Redis GET error: ${r.message}`);
589
+ }
590
+ return null;
591
+ },
592
+ async set(key, value, ttlMs) {
593
+ const args = [k(key), value, "PX", String(Math.max(1, ttlMs))];
594
+ const r = await client.command("SET", args);
595
+ if (isRedisError(r)) {
596
+ throw new Error(`Redis SET error: ${r.message}`);
597
+ }
598
+ },
599
+ async del(key) {
600
+ const r = await client.command("DEL", [k(key)]);
601
+ if (isRedisError(r)) {
602
+ throw new Error(`Redis DEL error: ${r.message}`);
603
+ }
604
+ },
605
+ async hset(key, field, value) {
606
+ const r = await client.command("HSET", [k(key), field, value]);
607
+ if (isRedisError(r)) {
608
+ throw new Error(`Redis HSET error: ${r.message}`);
609
+ }
610
+ },
611
+ async hsetnx(key, field, value) {
612
+ const r = await client.command("HSETNX", [k(key), field, value]);
613
+ if (isRedisError(r)) {
614
+ throw new Error(`Redis HSETNX error: ${r.message}`);
615
+ }
616
+ return typeof r === "number" ? r : 0;
617
+ },
618
+ async hgetall(key) {
619
+ const r = await client.command("HGETALL", [k(key)]);
620
+ if (isRedisError(r)) {
621
+ throw new Error(`Redis HGETALL error: ${r.message}`);
622
+ }
623
+ if (!Array.isArray(r)) return {};
624
+ const out = {};
625
+ for (let i = 0; i < r.length; i += 2) {
626
+ const kk = r[i];
627
+ const v = r[i + 1];
628
+ if (typeof kk === "string" && typeof v === "string") out[kk] = v;
629
+ }
630
+ return out;
631
+ },
632
+ async expire(key, ttlMs) {
633
+ const r = await client.command("PEXPIRE", [
634
+ k(key),
635
+ String(Math.max(1, ttlMs))
636
+ ]);
637
+ if (isRedisError(r)) {
638
+ throw new Error(`Redis PEXPIRE error: ${r.message}`);
639
+ }
640
+ },
641
+ async scanKeys(prefixKey) {
642
+ const fullPrefix = k(prefixKey);
643
+ let cursor = "0";
644
+ const keys = [];
645
+ do {
646
+ const r = await client.command("SCAN", [
647
+ cursor,
648
+ "MATCH",
649
+ `${fullPrefix}*`,
650
+ "COUNT",
651
+ "200"
652
+ ]);
653
+ if (!Array.isArray(r) || r.length < 2) break;
654
+ cursor = typeof r[0] === "string" ? r[0] : "0";
655
+ const batch = r[1];
656
+ if (Array.isArray(batch)) {
657
+ for (const key of batch) {
658
+ if (typeof key === "string") keys.push(key);
659
+ }
660
+ }
661
+ } while (cursor !== "0");
662
+ return keys;
663
+ },
664
+ async delRaw(keys) {
665
+ if (keys.length === 0) return;
666
+ const r = await client.command("DEL", keys);
667
+ if (isRedisError(r)) {
668
+ throw new Error(`Redis DEL error: ${r.message}`);
669
+ }
670
+ }
671
+ };
672
+ }
673
+
674
+ // src/framework/adapter.ts
675
+ function createInMemoryFrameworkAdapter(options) {
676
+ const ttlMs = options?.ttlMs ?? 15 * 60 * 1e3;
677
+ const checkpointer = createInMemoryCheckpointSaver();
678
+ return {
679
+ kind: "memory",
680
+ ttlMs,
681
+ pendingRequests: createInMemoryPendingRequestStore(),
682
+ checkpointer,
683
+ cleanupRun: async (runId) => {
684
+ try {
685
+ await checkpointer.deleteThread(runId);
686
+ } catch {
687
+ }
688
+ }
689
+ };
690
+ }
691
+ function createRedisFrameworkAdapter(options) {
692
+ const ttlMs = options.ttlMs ?? 15 * 60 * 1e3;
693
+ const store = createRedisFrameworkStore({
694
+ url: options.url,
695
+ prefix: options.prefix ?? "kortyx:fw:"
696
+ });
697
+ const cpPrefix = "kortyx:cp:";
698
+ return {
699
+ kind: "redis",
700
+ ttlMs,
701
+ pendingRequests: createRedisPendingRequestStore({
702
+ store,
703
+ prefix: "kortyx:pending:"
704
+ }),
705
+ checkpointer: createRedisCheckpointSaver({
706
+ store,
707
+ ttlMs,
708
+ prefix: cpPrefix
709
+ }),
710
+ cleanupRun: async (runId, namespaces) => {
711
+ const nsList = namespaces.length > 0 ? namespaces : [""];
712
+ await Promise.all(
713
+ nsList.map(async (checkpointNs) => {
714
+ const ns = String(checkpointNs ?? "");
715
+ const latestKey = `${cpPrefix}latest:${runId}:${ns}`;
716
+ const checkpointId = await store.get(latestKey) ?? "";
717
+ if (!checkpointId) return;
718
+ await Promise.all([
719
+ store.del(`${cpPrefix}chk:${runId}:${ns}:${checkpointId}`),
720
+ store.del(`${cpPrefix}wr:${runId}:${ns}:${checkpointId}`),
721
+ store.del(latestKey)
722
+ ]);
723
+ })
724
+ );
725
+ }
726
+ };
727
+ }
728
+ function createFrameworkAdapterFromEnv(env = process.env) {
729
+ const url = env.KORTYX_REDIS_URL || env.REDIS_URL || env.KORTYX_FRAMEWORK_REDIS_URL || "";
730
+ const ttlMsRaw = env.KORTYX_FRAMEWORK_TTL_MS || env.KORTYX_TTL_MS || "";
731
+ const ttlMs = ttlMsRaw ? Number(ttlMsRaw) : void 0;
732
+ if (url)
733
+ return createRedisFrameworkAdapter({ url, ...ttlMs ? { ttlMs } : {} });
734
+ return createInMemoryFrameworkAdapter({ ...ttlMs ? { ttlMs } : {} });
735
+ }
736
+
737
+ // src/graph/create-langgraph.ts
738
+ var import_hooks = require("@kortyx/hooks");
739
+ var import_internal = require("@kortyx/hooks/internal");
740
+ var import_utils = require("@kortyx/utils");
741
+ var import_langgraph = require("@langchain/langgraph");
742
+
743
+ // src/node-loader.ts
744
+ var import_node_path = require("path");
745
+ var import_node_url = require("url");
746
+
747
+ // src/node-registry.ts
748
+ var registry = /* @__PURE__ */ new Map();
749
+ function registerNode(id, fn) {
750
+ registry.set(id, fn);
751
+ }
752
+ function getRegisteredNode(id) {
753
+ return registry.get(id) ?? null;
754
+ }
755
+ function listRegisteredNodes() {
756
+ return [...registry.keys()].sort();
757
+ }
758
+ function clearRegisteredNodes() {
759
+ registry.clear();
760
+ }
761
+ function resolveNode(id) {
762
+ const fn = registry.get(id);
763
+ if (!fn) {
764
+ throw new Error(
765
+ `Node '${id}' is not registered. Call registerNode('${id}', fn) before running workflows that reference it.`
766
+ );
767
+ }
768
+ return fn;
769
+ }
770
+
771
+ // src/node-loader.ts
772
+ var dynamicImport = new Function(
773
+ "specifier",
774
+ // Avoid bundler static analysis of `import(...)` (e.g. Next.js/Turbopack).
775
+ // This is only used on the server.
776
+ "return import(specifier)"
777
+ );
778
+ function looksLikePath(specifier) {
779
+ if (specifier.startsWith("file:")) return true;
780
+ if (specifier.startsWith("./") || specifier.startsWith("../")) return true;
781
+ if (specifier.startsWith("/")) return true;
782
+ return specifier.includes("/");
783
+ }
784
+ function getWorkflowBaseDir(workflow, cwd) {
785
+ const meta = workflow?.metadata;
786
+ const filePath = meta?.__filePath;
787
+ if (typeof filePath === "string" && filePath.length > 0) {
788
+ return (0, import_node_path.dirname)(filePath);
789
+ }
790
+ return cwd;
791
+ }
792
+ function pickNodeExport(mod, exportName) {
793
+ if (exportName) {
794
+ const candidate = mod[exportName];
795
+ if (typeof candidate === "function") return candidate;
796
+ throw new Error(`Node export "${exportName}" not found or not a function.`);
797
+ }
798
+ const defaultExport = mod.default;
799
+ if (typeof defaultExport === "function") return defaultExport;
800
+ const fnExports = Object.entries(mod).filter(
801
+ ([, v]) => typeof v === "function"
802
+ );
803
+ if (fnExports.length === 1) return fnExports[0][1];
804
+ const names = fnExports.map(([k]) => k).sort();
805
+ throw new Error(
806
+ `Node module must export a default function or exactly one named function (found: ${names.join(", ") || "none"}).`
807
+ );
808
+ }
809
+ async function resolveNodeHandler(args) {
810
+ const { run, workflow } = args;
811
+ const cwd = args.cwd ?? process.cwd();
812
+ if (typeof run === "function") return run;
813
+ if (looksLikePath(run)) {
814
+ const [moduleRef, exportName] = run.split("#", 2);
815
+ const baseDir = getWorkflowBaseDir(workflow, cwd);
816
+ const specifier = moduleRef.startsWith("file:") ? moduleRef : (0, import_node_path.isAbsolute)(moduleRef) ? (0, import_node_url.pathToFileURL)(moduleRef).href : (0, import_node_url.pathToFileURL)((0, import_node_path.resolve)(baseDir, moduleRef)).href;
817
+ const mod = await dynamicImport(specifier);
818
+ return pickNodeExport(mod, exportName);
819
+ }
820
+ return resolveNode(run);
821
+ }
822
+
823
+ // src/graph/create-langgraph.ts
824
+ async function createLangGraph(workflow, config) {
825
+ const StateAnnotation = import_langgraph.Annotation.Root({
826
+ input: import_langgraph.Annotation,
827
+ output: import_langgraph.Annotation,
828
+ lastNode: import_langgraph.Annotation,
829
+ lastCondition: import_langgraph.Annotation,
830
+ lastIntent: import_langgraph.Annotation,
831
+ memory: (0, import_langgraph.Annotation)({
832
+ reducer: (l, r) => (0, import_utils.deepMergeWithArrayOverwrite)(l ?? {}, r ?? {}),
833
+ default: () => ({})
834
+ }),
835
+ config: import_langgraph.Annotation,
836
+ transitionTo: import_langgraph.Annotation,
837
+ data: (0, import_langgraph.Annotation)({
838
+ reducer: (l, r) => (0, import_utils.deepMergeWithArrayOverwrite)(l ?? {}, r ?? {}),
839
+ default: () => ({})
840
+ }),
841
+ conversationHistory: (0, import_langgraph.Annotation)({
842
+ reducer: (l, r) => [...l ?? [], ...r ?? []],
843
+ default: () => []
844
+ }),
845
+ awaitingHumanInput: import_langgraph.Annotation
846
+ });
847
+ const builder = new import_langgraph.StateGraph(StateAnnotation);
848
+ const edgeApi = builder;
849
+ const workflowName = workflow.id;
850
+ const runtimeConfig = config;
851
+ if (!runtimeConfig.emit) {
852
+ runtimeConfig.emit = () => {
853
+ };
854
+ }
855
+ const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
856
+ const toRecordInput = (value) => {
857
+ if (isRecord(value)) return value;
858
+ if (value === void 0) return {};
859
+ return { rawInput: value };
860
+ };
861
+ const buildNodeConfig = (params, nodeBehavior) => {
862
+ const model = isRecord(params?.model) ? params.model : void 0;
863
+ const tool = isRecord(params?.tool) ? params.tool : void 0;
864
+ const behaviorFromParams = isRecord(params?.behavior) ? params.behavior : void 0;
865
+ const behavior = {
866
+ ...behaviorFromParams ?? {},
867
+ ...nodeBehavior ?? {}
868
+ };
869
+ const options = params ?? void 0;
870
+ return {
871
+ ...model ? { model } : {},
872
+ ...tool ? { tool } : {},
873
+ ...Object.keys(behavior).length > 0 ? { behavior } : {},
874
+ ...options ? { options } : {}
875
+ };
876
+ };
877
+ for (const [nodeId, nodeDef] of Object.entries(workflow.nodes ?? {})) {
878
+ const resolvedRun = await resolveNodeHandler({
879
+ run: nodeDef.run,
880
+ workflow
881
+ });
882
+ const nodeParams = nodeDef.params ?? void 0;
883
+ const nodeConfig = buildNodeConfig(
884
+ nodeParams,
885
+ nodeDef.behavior ?? void 0
886
+ );
887
+ const behavior = nodeConfig.behavior ?? {};
888
+ builder.addNode(nodeId, async (state) => {
889
+ const ctx = {
890
+ graph: { name: workflowName, node: nodeId },
891
+ config: nodeConfig,
892
+ emit: (event, payload) => {
893
+ runtimeConfig.emit(event, payload);
894
+ },
895
+ error: (message) => {
896
+ runtimeConfig.emit("error", {
897
+ node: nodeId,
898
+ message
899
+ });
900
+ },
901
+ awaitInterrupt: (interruptConfig) => {
902
+ const { kind, question } = interruptConfig;
903
+ const isMulti = kind === "multi-choice" || interruptConfig.kind !== "text" && interruptConfig.multiple === true;
904
+ const payload = {
905
+ kind,
906
+ multiple: isMulti,
907
+ question,
908
+ ...interruptConfig.kind !== "text" ? { options: interruptConfig.options } : {},
909
+ ...typeof interruptConfig.id === "string" && interruptConfig.id.length > 0 ? { id: interruptConfig.id } : {},
910
+ ...typeof interruptConfig.schemaId === "string" && interruptConfig.schemaId.length > 0 ? { schemaId: interruptConfig.schemaId } : {},
911
+ ...typeof interruptConfig.schemaVersion === "string" && interruptConfig.schemaVersion.length > 0 ? { schemaVersion: interruptConfig.schemaVersion } : {},
912
+ ...interruptConfig.meta && typeof interruptConfig.meta === "object" && !Array.isArray(interruptConfig.meta) ? { meta: interruptConfig.meta } : {}
913
+ };
914
+ runtimeConfig.emit("interrupt", {
915
+ node: nodeId,
916
+ workflow: workflowName,
917
+ input: payload
918
+ });
919
+ const resumed = (0, import_langgraph.interrupt)(payload);
920
+ if (isMulti) {
921
+ if (Array.isArray(resumed)) {
922
+ return resumed.map(
923
+ (v) => typeof v === "string" ? v : v && typeof v.id === "string" ? v.id : ""
924
+ ).filter(Boolean);
925
+ }
926
+ if (typeof resumed === "string") return [resumed];
927
+ return [];
928
+ }
929
+ if (typeof resumed === "string") return resumed;
930
+ if (resumed && typeof resumed.id === "string")
931
+ return String(resumed.id);
932
+ return "";
933
+ },
934
+ speak: async (args) => {
935
+ const providerId = args.model?.provider ?? nodeConfig.model?.provider ?? "google";
936
+ const modelName = args.model?.name ?? nodeConfig.model?.name ?? "gemini-2.5-flash";
937
+ const temperature = args.model?.temperature ?? nodeConfig.model?.temperature ?? 0.3;
938
+ const getProvider = runtimeConfig.getProvider;
939
+ if (!getProvider) {
940
+ throw new Error(
941
+ "Runtime config is missing getProvider; wire a provider factory into @kortyx/runtime."
942
+ );
943
+ }
944
+ const result = await (0, import_internal.runReasonEngine)({
945
+ getProvider,
946
+ model: {
947
+ providerId,
948
+ modelId: modelName
949
+ },
950
+ input: args.user ?? "",
951
+ system: args.system,
952
+ temperature,
953
+ stream: true,
954
+ emit: true,
955
+ nodeId,
956
+ emitEvent: ctx.emit
957
+ });
958
+ return result.text;
959
+ }
960
+ };
961
+ if (behavior.checkpoint && config?.onCheckpoint) {
962
+ config.onCheckpoint({ nodeId, state });
963
+ }
964
+ const maxAttempts = behavior.retry?.maxAttempts ?? 1;
965
+ let attempt = 0;
966
+ let nodeResult;
967
+ let hookMemoryUpdates = null;
968
+ let retryHookMemory = null;
969
+ while (attempt < maxAttempts) {
970
+ try {
971
+ attempt++;
972
+ const attemptState = retryHookMemory && typeof retryHookMemory === "object" ? {
973
+ ...state,
974
+ memory: (0, import_utils.deepMergeWithArrayOverwrite)(
975
+ state.memory ?? {},
976
+ retryHookMemory
977
+ )
978
+ } : state;
979
+ const hookContext = {
980
+ node: ctx,
981
+ state: attemptState,
982
+ ...runtimeConfig.getProvider ? { getProvider: runtimeConfig.getProvider } : {},
983
+ ...runtimeConfig.memoryAdapter ? { memoryAdapter: runtimeConfig.memoryAdapter } : {}
984
+ };
985
+ const hookRun = await (0, import_hooks.runWithHookContext)(
986
+ hookContext,
987
+ async () => resolvedRun({
988
+ input: state.input,
989
+ params: nodeParams ?? {}
990
+ })
991
+ );
992
+ nodeResult = hookRun.result;
993
+ hookMemoryUpdates = hookRun.memoryUpdates;
994
+ break;
995
+ } catch (err) {
996
+ const patch = err?.__kortyxMemoryUpdates;
997
+ if (patch && typeof patch === "object") {
998
+ state.memory = (0, import_utils.deepMergeWithArrayOverwrite)(
999
+ state.memory ?? {},
1000
+ patch
1001
+ );
1002
+ retryHookMemory = (0, import_utils.deepMergeWithArrayOverwrite)(
1003
+ retryHookMemory ?? {},
1004
+ patch
1005
+ );
1006
+ }
1007
+ const hasMore = attempt < maxAttempts;
1008
+ const delayMs = behavior.retry?.delayMs ?? 0;
1009
+ if (hasMore && delayMs > 0) {
1010
+ await new Promise((r) => setTimeout(r, delayMs));
1011
+ continue;
1012
+ }
1013
+ if (!hasMore) throw err;
1014
+ }
1015
+ }
1016
+ const res = nodeResult ?? {};
1017
+ if (hookMemoryUpdates) {
1018
+ res.infra = {
1019
+ ...res.infra ?? {},
1020
+ memory: (0, import_utils.deepMergeWithArrayOverwrite)(
1021
+ (res.infra?.memory ?? {}) || {},
1022
+ hookMemoryUpdates
1023
+ )
1024
+ };
1025
+ }
1026
+ const uiMessage = res.ui?.message;
1027
+ const shouldRespond = typeof uiMessage === "string" && uiMessage.trim().length > 0;
1028
+ if (shouldRespond) {
1029
+ ctx.emit("message", { node: nodeId, content: uiMessage });
1030
+ }
1031
+ if (res.transitionTo) {
1032
+ ctx.emit("transition", {
1033
+ transitionTo: res.transitionTo,
1034
+ payload: res.data ?? {}
1035
+ });
1036
+ }
1037
+ const updates = {};
1038
+ if (typeof res.condition === "string")
1039
+ updates.lastCondition = res.condition;
1040
+ if (typeof res.intent === "string") updates.lastIntent = res.intent;
1041
+ if (res.data && typeof res.data === "object") {
1042
+ updates.input = (0, import_utils.deepMergeWithArrayOverwrite)(
1043
+ toRecordInput(state.input),
1044
+ res.data
1045
+ );
1046
+ updates.data = (0, import_utils.deepMergeWithArrayOverwrite)(
1047
+ state.data ?? {},
1048
+ res.data
1049
+ );
1050
+ }
1051
+ if (res.infra?.memory && typeof res.infra.memory === "object") {
1052
+ updates.memory = (0, import_utils.deepMergeWithArrayOverwrite)(
1053
+ state.memory ?? {},
1054
+ res.infra.memory
1055
+ );
1056
+ }
1057
+ if (res.ui) {
1058
+ updates.ui = {
1059
+ message: typeof res.ui.message === "string" ? res.ui.message : state.ui?.message ?? "",
1060
+ structured: (0, import_utils.deepMergeWithArrayOverwrite)(
1061
+ state.ui?.structured ?? {},
1062
+ res.ui.structured ?? {}
1063
+ )
1064
+ };
1065
+ }
1066
+ if (shouldRespond && uiMessage) {
1067
+ updates.conversationHistory = [
1068
+ ...state.conversationHistory ?? [],
1069
+ {
1070
+ node: nodeId,
1071
+ message: uiMessage,
1072
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1073
+ }
1074
+ ];
1075
+ }
1076
+ if (res.ui?.structured) {
1077
+ const payload = res.ui.structured;
1078
+ const inferredType = payload && typeof payload === "object" && "jobs" in payload ? "jobs" : typeof payload.summary === "string" || payload.topJobs ? "summary" : "generic";
1079
+ ctx.emit("structured_data", {
1080
+ node: nodeId,
1081
+ dataType: inferredType,
1082
+ data: payload
1083
+ });
1084
+ }
1085
+ return updates;
1086
+ });
1087
+ }
1088
+ const condGroups = {};
1089
+ const plainEdges = [];
1090
+ for (const edge of workflow.edges) {
1091
+ const [from, to, condition] = edge;
1092
+ if (condition && typeof condition.when === "string" && condition.when) {
1093
+ if (!condGroups[from]) condGroups[from] = [];
1094
+ condGroups[from].push({ when: condition.when, to });
1095
+ } else {
1096
+ plainEdges.push([from, to]);
1097
+ }
1098
+ }
1099
+ for (const [from, to] of plainEdges) {
1100
+ edgeApi.addEdge(from, to);
1101
+ }
1102
+ for (const [from, rules] of Object.entries(condGroups)) {
1103
+ const mapping = Object.fromEntries(
1104
+ rules.map((r) => [r.when, r.to])
1105
+ );
1106
+ const fallbackKey = `__default__:${from}`;
1107
+ mapping[fallbackKey] = "__end__";
1108
+ edgeApi.addConditionalEdges(
1109
+ from,
1110
+ (s) => {
1111
+ const trigger = s.lastCondition ?? s.lastIntent;
1112
+ if (trigger && Object.hasOwn(mapping, trigger)) {
1113
+ return trigger;
1114
+ }
1115
+ return fallbackKey;
1116
+ },
1117
+ mapping
1118
+ );
1119
+ }
1120
+ const sessionId = config?.session?.id ?? "__default__";
1121
+ const checkpointer = config.checkpointer ?? getCheckpointer(sessionId);
1122
+ const graph = builder.compile({ checkpointer });
1123
+ const runtimeGraph = graph;
1124
+ runtimeGraph.name = workflow.id;
1125
+ runtimeGraph.config = config;
1126
+ runtimeGraph.resume = async (state, input) => {
1127
+ const resumed = { ...state, input, awaitingHumanInput: false };
1128
+ return graph.invoke(resumed);
1129
+ };
1130
+ runtimeGraph.timeTravelTo = async (state, checkpointId) => {
1131
+ const checkpoints = state.memory?.checkpoints;
1132
+ const snapshot = checkpoints?.[checkpointId];
1133
+ if (!snapshot) throw new Error(`Checkpoint '${checkpointId}' not found`);
1134
+ return graph.invoke(
1135
+ snapshot.snapshot
1136
+ );
1137
+ };
1138
+ return runtimeGraph;
1139
+ }
1140
+
1141
+ // src/interrupt/tokens.ts
1142
+ var import_uuid = require("uuid");
1143
+ function makeResumeToken() {
1144
+ return (0, import_uuid.v7)();
1145
+ }
1146
+ function makeRequestId(prefix = "req") {
1147
+ return `${prefix}-${(0, import_uuid.v7)()}`;
1148
+ }
1149
+
1150
+ // src/registry/file-registry.ts
1151
+ var import_core = require("@kortyx/core");
1152
+ var import_promises = require("fs/promises");
1153
+ var import_path = require("path");
1154
+ var DEFAULT_EXTENSIONS = [
1155
+ ".workflow.ts",
1156
+ ".workflow.mts",
1157
+ ".workflow.js",
1158
+ ".workflow.mjs",
1159
+ ".workflow.json",
1160
+ ".workflow.yml",
1161
+ ".workflow.yaml"
1162
+ ];
1163
+ function isWorkflowFile(name, extensions) {
1164
+ return extensions.some((ext) => name.endsWith(ext));
1165
+ }
1166
+ function isDeclarativeWorkflowFile(name) {
1167
+ return name.endsWith(".workflow.json") || name.endsWith(".workflow.yml") || name.endsWith(".workflow.yaml");
1168
+ }
1169
+ function createFileWorkflowRegistry(options) {
1170
+ const workflowsDir = options.workflowsDir;
1171
+ const fallbackId = options.fallbackId ?? "general-chat";
1172
+ const extensions = options.extensions ?? DEFAULT_EXTENSIONS;
1173
+ const shouldCache = options.cache ?? true;
1174
+ let workflowCache = null;
1175
+ async function loadWorkflows() {
1176
+ if (shouldCache && workflowCache) return workflowCache;
1177
+ const files = await (0, import_promises.readdir)(workflowsDir, { withFileTypes: true });
1178
+ const workflowFiles = files.filter((entry) => entry.isFile()).map((entry) => entry.name).filter((file) => isWorkflowFile(file, extensions));
1179
+ const workflows = {};
1180
+ for (const file of workflowFiles) {
1181
+ try {
1182
+ const modulePath = (0, import_path.join)(workflowsDir, file);
1183
+ if (isDeclarativeWorkflowFile(file)) {
1184
+ const raw = await (0, import_promises.readFile)(modulePath, "utf8");
1185
+ const workflow = (0, import_core.loadWorkflow)(raw);
1186
+ workflow.metadata = {
1187
+ ...workflow.metadata ?? {},
1188
+ __filePath: modulePath
1189
+ };
1190
+ workflows[workflow.id] = workflow;
1191
+ continue;
1192
+ }
1193
+ const module2 = await import(modulePath);
1194
+ const workflowExport = Object.values(module2).find(
1195
+ (exp) => {
1196
+ const obj = exp;
1197
+ return exp !== null && typeof exp === "object" && typeof obj.id === "string" && typeof obj.nodes === "object" && obj.nodes !== null && Array.isArray(obj.edges);
1198
+ }
1199
+ );
1200
+ if (workflowExport) {
1201
+ workflowExport.metadata = {
1202
+ ...workflowExport.metadata ?? {},
1203
+ __filePath: modulePath
1204
+ };
1205
+ workflows[workflowExport.id] = workflowExport;
1206
+ }
1207
+ } catch (error) {
1208
+ console.warn(`Failed to load workflow from ${file}:`, error);
1209
+ }
1210
+ }
1211
+ if (shouldCache) workflowCache = workflows;
1212
+ return workflows;
1213
+ }
1214
+ async function list() {
1215
+ const workflows = await loadWorkflows();
1216
+ return Object.values(workflows);
1217
+ }
1218
+ async function get(id) {
1219
+ const workflows = await loadWorkflows();
1220
+ return workflows[id] ?? null;
1221
+ }
1222
+ async function select(id, selectOptions) {
1223
+ const workflows = await loadWorkflows();
1224
+ const fallback = selectOptions?.fallbackId ?? fallbackId;
1225
+ const selected = workflows[id] ?? (fallback ? workflows[fallback] : null);
1226
+ if (!selected) {
1227
+ throw new Error(
1228
+ `No workflow found for id "${id}" and no fallback "${fallback}" workflow available`
1229
+ );
1230
+ }
1231
+ return selected;
1232
+ }
1233
+ async function refresh() {
1234
+ workflowCache = null;
1235
+ await loadWorkflows();
1236
+ }
1237
+ return {
1238
+ list,
1239
+ get,
1240
+ select,
1241
+ refresh
1242
+ };
1243
+ }
1244
+
1245
+ // src/registry/in-memory-registry.ts
1246
+ function createInMemoryWorkflowRegistry(workflows, options) {
1247
+ const byId = /* @__PURE__ */ new Map();
1248
+ for (const wf of workflows) byId.set(wf.id, wf);
1249
+ const fallbackId = options?.fallbackId ?? "general-chat";
1250
+ return {
1251
+ async list() {
1252
+ return Array.from(byId.values());
1253
+ },
1254
+ async get(id) {
1255
+ return byId.get(id) ?? null;
1256
+ },
1257
+ async select(id, selectOptions) {
1258
+ const fallback = selectOptions?.fallbackId ?? fallbackId;
1259
+ const wf = byId.get(id) ?? (fallback ? byId.get(fallback) : void 0);
1260
+ if (!wf) {
1261
+ throw new Error(
1262
+ `Workflow "${id}" not found${fallback ? ` (fallback "${fallback}" missing too)` : ""}.`
1263
+ );
1264
+ }
1265
+ return wf;
1266
+ }
1267
+ };
1268
+ }
1269
+
1270
+ // src/state/build-initial-state.ts
1271
+ async function buildInitialGraphState({
1272
+ input,
1273
+ memory,
1274
+ config,
1275
+ defaultWorkflowId
1276
+ }) {
1277
+ const currentWorkflow = memory.currentWorkflow || defaultWorkflowId;
1278
+ if (!currentWorkflow) {
1279
+ throw new Error(
1280
+ "No workflow selected. Provide defaultWorkflowId (or set memory.currentWorkflow) before starting the graph."
1281
+ );
1282
+ }
1283
+ return {
1284
+ input,
1285
+ lastNode: "__start__",
1286
+ memory,
1287
+ config,
1288
+ conversationHistory: [],
1289
+ currentWorkflow,
1290
+ awaitingHumanInput: false
1291
+ };
1292
+ }
1293
+ // Annotate the CommonJS export names for ESM import in node:
1294
+ 0 && (module.exports = {
1295
+ buildInitialGraphState,
1296
+ clearRegisteredNodes,
1297
+ createFileWorkflowRegistry,
1298
+ createFrameworkAdapterFromEnv,
1299
+ createInMemoryFrameworkAdapter,
1300
+ createInMemoryPendingRequestStore,
1301
+ createInMemoryWorkflowRegistry,
1302
+ createLangGraph,
1303
+ createRedisFrameworkAdapter,
1304
+ getCheckpointer,
1305
+ getRegisteredNode,
1306
+ listRegisteredNodes,
1307
+ makeRequestId,
1308
+ makeResumeToken,
1309
+ registerNode,
1310
+ resolveNode
1311
+ });
1312
+ //# sourceMappingURL=index.js.map