@kortyx/runtime 0.6.0 → 0.7.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.7.0](https://github.com/kortyx-io/kortyx/compare/runtime-v0.6.1...runtime-v0.7.0) (2026-03-08)
4
+
5
+
6
+ ### Features
7
+
8
+ * **runtime:** rename graph compiler API and remove LangGraph wording ([43ecfec](https://github.com/kortyx-io/kortyx/commit/43ecfec6f1235fad01344a52c68aeeb1a6636a52))
9
+
10
+ ## [0.6.1](https://github.com/kortyx-io/kortyx/compare/runtime-v0.6.0...runtime-v0.6.1) (2026-02-17)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * **release:** publish packages with pnpm and public access ([357e268](https://github.com/kortyx-io/kortyx/commit/357e2680469e729ea58d103915989142f668a39a))
16
+ * **release:** publish packages with pnpm and public access ([5ef7498](https://github.com/kortyx-io/kortyx/commit/5ef7498330129f376ca7197b70cb7b6a38138e8a))
17
+
3
18
  ## [0.6.0](https://github.com/kortyx-io/kortyx/compare/runtime-v0.5.1...runtime-v0.6.0) (2026-02-17)
4
19
 
5
20
 
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.d.ts CHANGED
@@ -68,7 +68,7 @@ type CreateRedisFrameworkAdapterOptions = {
68
68
  declare function createRedisFrameworkAdapter(options: CreateRedisFrameworkAdapterOptions): FrameworkAdapter;
69
69
  declare function createFrameworkAdapterFromEnv(env?: Record<string, string | undefined>): FrameworkAdapter;
70
70
 
71
- interface GraphRuntimeConfig {
71
+ interface ExecutionRuntimeConfig {
72
72
  emit?: (event: string, payload: unknown) => void;
73
73
  onCheckpoint?: (args: {
74
74
  nodeId: string;
@@ -83,7 +83,7 @@ interface GraphRuntimeConfig {
83
83
  getProvider?: GetProviderFn;
84
84
  [key: string]: unknown;
85
85
  }
86
- declare function createLangGraph(workflow: WorkflowDefinition, config: GraphRuntimeConfig): Promise<any>;
86
+ declare function createExecutionGraph(workflow: WorkflowDefinition, config: ExecutionRuntimeConfig): Promise<any>;
87
87
 
88
88
  declare function makeResumeToken(): string;
89
89
  declare function makeRequestId(prefix?: string): string;
@@ -128,4 +128,4 @@ interface InitialStateArgs<Config = unknown> {
128
128
  }
129
129
  declare function buildInitialGraphState<Config>({ input, memory, config, defaultWorkflowId, }: InitialStateArgs<Config>): Promise<GraphState>;
130
130
 
131
- export { type CreateInMemoryFrameworkAdapterOptions, type CreateRedisFrameworkAdapterOptions, type FileWorkflowRegistryOptions, type FrameworkAdapter, type GraphRuntimeConfig, type HumanInputKind, type HumanInputOption, type InitialStateArgs, type PendingRequestRecord, type PendingRequestStore, type WorkflowRegistry, buildInitialGraphState, clearRegisteredNodes, createFileWorkflowRegistry, createFrameworkAdapterFromEnv, createInMemoryFrameworkAdapter, createInMemoryPendingRequestStore, createInMemoryWorkflowRegistry, createLangGraph, createRedisFrameworkAdapter, getCheckpointer, getRegisteredNode, listRegisteredNodes, makeRequestId, makeResumeToken, registerNode, resolveNode };
131
+ export { type CreateInMemoryFrameworkAdapterOptions, type CreateRedisFrameworkAdapterOptions, type ExecutionRuntimeConfig, type FileWorkflowRegistryOptions, type FrameworkAdapter, type HumanInputKind, type HumanInputOption, type InitialStateArgs, type PendingRequestRecord, type PendingRequestStore, type WorkflowRegistry, buildInitialGraphState, clearRegisteredNodes, createExecutionGraph, createFileWorkflowRegistry, createFrameworkAdapterFromEnv, createInMemoryFrameworkAdapter, createInMemoryPendingRequestStore, createInMemoryWorkflowRegistry, createRedisFrameworkAdapter, getCheckpointer, getRegisteredNode, listRegisteredNodes, makeRequestId, makeResumeToken, registerNode, resolveNode };
package/dist/index.js CHANGED
@@ -21,12 +21,12 @@ var index_exports = {};
21
21
  __export(index_exports, {
22
22
  buildInitialGraphState: () => buildInitialGraphState,
23
23
  clearRegisteredNodes: () => clearRegisteredNodes,
24
+ createExecutionGraph: () => createExecutionGraph,
24
25
  createFileWorkflowRegistry: () => createFileWorkflowRegistry,
25
26
  createFrameworkAdapterFromEnv: () => createFrameworkAdapterFromEnv,
26
27
  createInMemoryFrameworkAdapter: () => createInMemoryFrameworkAdapter,
27
28
  createInMemoryPendingRequestStore: () => createInMemoryPendingRequestStore,
28
29
  createInMemoryWorkflowRegistry: () => createInMemoryWorkflowRegistry,
29
- createLangGraph: () => createLangGraph,
30
30
  createRedisFrameworkAdapter: () => createRedisFrameworkAdapter,
31
31
  getCheckpointer: () => getCheckpointer,
32
32
  getRegisteredNode: () => getRegisteredNode,
@@ -734,7 +734,7 @@ function createFrameworkAdapterFromEnv(env = process.env) {
734
734
  return createInMemoryFrameworkAdapter({ ...ttlMs ? { ttlMs } : {} });
735
735
  }
736
736
 
737
- // src/graph/create-langgraph.ts
737
+ // src/graph/create-execution-graph.ts
738
738
  var import_hooks = require("@kortyx/hooks");
739
739
  var import_internal = require("@kortyx/hooks/internal");
740
740
  var import_utils = require("@kortyx/utils");
@@ -820,8 +820,8 @@ async function resolveNodeHandler(args) {
820
820
  return resolveNode(run);
821
821
  }
822
822
 
823
- // src/graph/create-langgraph.ts
824
- async function createLangGraph(workflow, config) {
823
+ // src/graph/create-execution-graph.ts
824
+ async function createExecutionGraph(workflow, config) {
825
825
  const StateAnnotation = import_langgraph.Annotation.Root({
826
826
  input: import_langgraph.Annotation,
827
827
  output: import_langgraph.Annotation,
@@ -1294,12 +1294,12 @@ async function buildInitialGraphState({
1294
1294
  0 && (module.exports = {
1295
1295
  buildInitialGraphState,
1296
1296
  clearRegisteredNodes,
1297
+ createExecutionGraph,
1297
1298
  createFileWorkflowRegistry,
1298
1299
  createFrameworkAdapterFromEnv,
1299
1300
  createInMemoryFrameworkAdapter,
1300
1301
  createInMemoryPendingRequestStore,
1301
1302
  createInMemoryWorkflowRegistry,
1302
- createLangGraph,
1303
1303
  createRedisFrameworkAdapter,
1304
1304
  getCheckpointer,
1305
1305
  getRegisteredNode,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/framework/in-memory-checkpointer.ts","../src/checkpointer.ts","../src/framework/pending-requests.ts","../src/framework/redis/pending-request-store.ts","../src/framework/redis/redis-checkpointer.ts","../src/framework/redis/redis-client.ts","../src/framework/redis/redis-store.ts","../src/framework/adapter.ts","../src/graph/create-langgraph.ts","../src/node-loader.ts","../src/node-registry.ts","../src/interrupt/tokens.ts","../src/registry/file-registry.ts","../src/registry/in-memory-registry.ts","../src/state/build-initial-state.ts"],"sourcesContent":["// release-test: 2026-01-22\nexport * from \"./checkpointer\";\nexport * from \"./framework/adapter\";\nexport * from \"./framework/pending-requests\";\nexport * from \"./graph/create-langgraph\";\nexport * from \"./interrupt/tokens\";\nexport * from \"./node-registry\";\nexport * from \"./registry/file-registry\";\nexport * from \"./registry/in-memory-registry\";\nexport * from \"./registry/interface\";\nexport * from \"./state/build-initial-state\";\n","import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n type BaseCheckpointSaver,\n type Checkpoint,\n type CheckpointListOptions,\n type CheckpointMetadata,\n type CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n type PendingWrite,\n WRITES_IDX_MAP,\n} from \"@langchain/langgraph-checkpoint\";\n\ntype SerializerProtocol = {\n dumpsTyped: (data: any) => Promise<[string, Uint8Array]>;\n loadsTyped: (type: string, data: Uint8Array | string) => Promise<any>;\n};\n\ntype StoredCheckpoint = {\n checkpoint: Checkpoint;\n metadata: CheckpointMetadata;\n parentCheckpointId?: string | undefined;\n writes: Map<string, [string, string, unknown]>;\n};\n\nexport type InMemoryCheckpointSaverOptions = {\n /**\n * Maximum number of pending writes stored for a single checkpoint.\n * Prevents unbounded memory growth in dev servers.\n */\n maxWritesPerCheckpoint?: number;\n};\n\nconst utf8Bytes = (s: string) => new Uint8Array(Buffer.from(s, \"utf8\"));\nconst utf8String = (u8: Uint8Array | string) =>\n typeof u8 === \"string\" ? u8 : Buffer.from(u8).toString(\"utf8\");\n\nconst jsonSerde: SerializerProtocol = {\n async dumpsTyped(data: any) {\n return [\"json\", utf8Bytes(JSON.stringify(data))];\n },\n async loadsTyped(_type: string, data: Uint8Array | string) {\n return JSON.parse(utf8String(data));\n },\n};\n\nexport type InMemoryCheckpointSaver = BaseCheckpointSaver & {\n deleteThread: (threadId: string) => Promise<void>;\n};\n\n/**\n * Bounded in-memory checkpointer:\n * - Keeps only the latest checkpoint per (thread_id, checkpoint_ns)\n * - Keeps only a bounded number of pending writes for that checkpoint\n *\n * This is a safer dev default than LangGraph's MemorySaver, which can grow without bound.\n */\nexport function createInMemoryCheckpointSaver(\n options?: InMemoryCheckpointSaverOptions,\n): InMemoryCheckpointSaver {\n const maxWritesPerCheckpoint = options?.maxWritesPerCheckpoint ?? 2_000;\n\n // (threadId|ns) -> checkpointId\n const latest = new Map<string, string>();\n // (threadId|ns|id) -> stored\n const checkpoints = new Map<string, StoredCheckpoint>();\n\n const nsKey = (threadId: string, checkpointNs: string) =>\n `${threadId}\\u0001${checkpointNs}`;\n const chkKey = (\n threadId: string,\n checkpointNs: string,\n checkpointId: string,\n ) => `${threadId}\\u0001${checkpointNs}\\u0001${checkpointId}`;\n\n const saver: any = {\n serde: jsonSerde,\n\n async get(config: RunnableConfig) {\n const value = await saver.getTuple(config);\n return value ? value.checkpoint : undefined;\n },\n\n getNextVersion(current: number | string | undefined) {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return current !== undefined && typeof current === \"number\"\n ? current + 1\n : 1;\n },\n\n async getTuple(\n config: RunnableConfig,\n ): Promise<CheckpointTuple | undefined> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) return undefined;\n\n const requested = getCheckpointId(config);\n const id = requested || latest.get(nsKey(threadId, checkpointNs));\n if (!id) return undefined;\n\n const stored = checkpoints.get(chkKey(threadId, checkpointNs, id));\n if (!stored) return undefined;\n\n const pendingWrites = Array.from(stored.writes.values());\n const tuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: id,\n },\n },\n checkpoint: stored.checkpoint,\n metadata: stored.metadata,\n pendingWrites: pendingWrites as any,\n };\n\n if (stored.parentCheckpointId) {\n tuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: stored.parentCheckpointId,\n },\n };\n }\n\n return tuple;\n },\n\n async *list(_config: RunnableConfig, _options?: CheckpointListOptions) {\n // Not required for current runtime behavior.\n },\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n _newVersions: Record<string, number | string>,\n ): Promise<RunnableConfig> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) {\n throw new Error(\n 'Failed to put checkpoint: missing \"thread_id\" in config.configurable.',\n );\n }\n\n const ns = nsKey(threadId, checkpointNs);\n const prevId = latest.get(ns);\n\n const prepared = copyCheckpoint(checkpoint as any);\n const entry: StoredCheckpoint = {\n checkpoint: prepared as any,\n metadata,\n parentCheckpointId: config.configurable?.checkpoint_id as\n | string\n | undefined,\n writes: new Map(),\n };\n\n const id = checkpoint.id;\n checkpoints.set(chkKey(threadId, checkpointNs, id), entry);\n latest.set(ns, id);\n\n // Bounded: drop previous checkpoint + its writes\n if (prevId && prevId !== id) {\n checkpoints.delete(chkKey(threadId, checkpointNs, prevId));\n }\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: id,\n },\n };\n },\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string,\n ): Promise<void> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n const checkpointId = config.configurable?.checkpoint_id as\n | string\n | undefined;\n if (!threadId || !checkpointId) return;\n\n const stored = checkpoints.get(\n chkKey(threadId, checkpointNs, checkpointId),\n );\n if (!stored) return;\n\n for (let idx = 0; idx < writes.length; idx++) {\n const [channel, value] = writes[idx]!;\n const mappedIdx = WRITES_IDX_MAP[channel] ?? idx;\n const key = `${taskId},${mappedIdx}`;\n\n // HSETNX semantics for normal writes; always overwrite for special writes (negative mappedIdx)\n if (mappedIdx >= 0 && stored.writes.has(key)) continue;\n\n // Bound the number of writes to avoid unbounded growth in dev\n if (stored.writes.size >= maxWritesPerCheckpoint) break;\n\n stored.writes.set(key, [taskId, channel, value]);\n }\n },\n\n async deleteThread(threadId: string): Promise<void> {\n for (const k of Array.from(latest.keys())) {\n if (k.startsWith(`${threadId}\\u0001`)) latest.delete(k);\n }\n for (const k of Array.from(checkpoints.keys())) {\n if (k.startsWith(`${threadId}\\u0001`)) checkpoints.delete(k);\n }\n },\n };\n\n return saver as InMemoryCheckpointSaver;\n}\n","import type { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { createInMemoryCheckpointSaver } from \"./framework/in-memory-checkpointer\";\n\nconst MAX_CHECKPOINTERS = 200;\nconst map = new Map<string, BaseCheckpointSaver>();\n\nexport function getCheckpointer(key: string): BaseCheckpointSaver {\n const k = key || \"__default__\";\n const existing = map.get(k);\n if (existing) return existing;\n\n const saver = createInMemoryCheckpointSaver();\n map.set(k, saver);\n\n // Simple FIFO eviction to avoid unbounded growth in long-lived dev servers.\n if (map.size > MAX_CHECKPOINTERS) {\n const first = map.keys().next().value as string | undefined;\n if (first) map.delete(first);\n }\n\n return saver;\n}\n","import type { GraphState } from \"@kortyx/core\";\n\nexport type HumanInputKind = \"choice\" | \"multi-choice\" | \"text\";\n\nexport interface HumanInputOption {\n id: string;\n label: string;\n description?: string;\n value?: unknown;\n}\n\nexport interface PendingRequestRecord {\n token: string;\n requestId: string;\n sessionId?: string | undefined;\n /**\n * Framework run identifier used by the checkpointer (thread_id).\n * This must be stable across interrupt/resume, but should not be reused for new messages.\n */\n runId: string;\n workflow: string;\n node: string;\n state?: GraphState;\n schema: {\n kind: HumanInputKind;\n multiple: boolean;\n question?: string;\n id?: string;\n schemaId?: string;\n schemaVersion?: string;\n meta?: Record<string, unknown>;\n };\n options: HumanInputOption[];\n createdAt: number;\n ttlMs: number;\n}\n\nexport interface PendingRequestStore {\n save: (rec: PendingRequestRecord) => Promise<void>;\n get: (token: string) => Promise<PendingRequestRecord | null>;\n delete: (token: string) => Promise<void>;\n update: (\n token: string,\n patch: Partial<PendingRequestRecord>,\n ) => Promise<void>;\n}\n\nexport function createInMemoryPendingRequestStore(): PendingRequestStore {\n const store = new Map<string, PendingRequestRecord>();\n\n const prune = () => {\n const t = Date.now();\n for (const [k, v] of store.entries()) {\n if (t - v.createdAt > v.ttlMs) store.delete(k);\n }\n };\n\n return {\n async save(rec) {\n prune();\n store.set(rec.token, rec);\n },\n async get(token) {\n prune();\n return store.get(token) ?? null;\n },\n async delete(token) {\n store.delete(token);\n },\n async update(token, patch) {\n const prev = store.get(token);\n if (!prev) return;\n store.set(token, { ...prev, ...patch });\n },\n };\n}\n","import type {\n PendingRequestRecord,\n PendingRequestStore,\n} from \"../pending-requests\";\nimport type { RedisFrameworkStore } from \"./redis-store\";\n\nexport type RedisPendingRequestStoreOptions = {\n store: RedisFrameworkStore;\n prefix?: string;\n};\n\nexport function createRedisPendingRequestStore(\n options: RedisPendingRequestStoreOptions,\n): PendingRequestStore {\n const prefix = options.prefix ?? \"kortyx:pending:\";\n const key = (token: string) => `${prefix}${token}`;\n\n return {\n async save(rec: PendingRequestRecord) {\n await options.store.set(key(rec.token), JSON.stringify(rec), rec.ttlMs);\n },\n async get(token: string) {\n const raw = await options.store.get(key(token));\n if (!raw) return null;\n return JSON.parse(raw) as PendingRequestRecord;\n },\n async delete(token: string) {\n await options.store.del(key(token));\n },\n async update(token: string, patch: Partial<PendingRequestRecord>) {\n const prevRaw = await options.store.get(key(token));\n if (!prevRaw) return;\n const prev = JSON.parse(prevRaw) as PendingRequestRecord;\n const next = { ...prev, ...patch } as PendingRequestRecord;\n const ttlLeft = Math.max(1, next.ttlMs - (Date.now() - next.createdAt));\n await options.store.set(key(token), JSON.stringify(next), ttlLeft);\n },\n };\n}\n","import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n type BaseCheckpointSaver,\n type Checkpoint,\n type CheckpointListOptions,\n type CheckpointMetadata,\n type CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n type PendingWrite,\n WRITES_IDX_MAP,\n} from \"@langchain/langgraph-checkpoint\";\nimport type { RedisFrameworkStore } from \"./redis-store\";\n\ntype SerializerProtocol = {\n dumpsTyped: (data: any) => Promise<[string, Uint8Array]>;\n loadsTyped: (type: string, data: Uint8Array | string) => Promise<any>;\n};\n\ntype RedisCheckpointSaverOptions = {\n store: RedisFrameworkStore;\n prefix?: string;\n ttlMs: number;\n};\n\nconst utf8Bytes = (s: string) => new Uint8Array(Buffer.from(s, \"utf8\"));\nconst utf8String = (u8: Uint8Array | string) =>\n typeof u8 === \"string\" ? u8 : Buffer.from(u8).toString(\"utf8\");\n\nconst jsonSerde: SerializerProtocol = {\n async dumpsTyped(data: any) {\n return [\"json\", utf8Bytes(JSON.stringify(data))];\n },\n async loadsTyped(_type: string, data: Uint8Array | string) {\n return JSON.parse(utf8String(data));\n },\n};\n\nconst b64FromBytes = (u8: Uint8Array) => Buffer.from(u8).toString(\"base64\");\nconst bytesFromB64 = (s: string) => new Uint8Array(Buffer.from(s, \"base64\"));\n\ntype StoredCheckpoint = {\n checkpoint: string; // base64\n metadata: string; // base64\n parentCheckpointId?: string | undefined;\n};\n\ntype StoredWrite = {\n taskId: string;\n channel: string;\n value: string; // base64\n};\n\nexport type RedisCheckpointSaver = BaseCheckpointSaver & {\n deleteThread: (threadId: string) => Promise<void>;\n};\n\nexport function createRedisCheckpointSaver(\n options: RedisCheckpointSaverOptions,\n): RedisCheckpointSaver {\n const store = options.store;\n const ttlMs = options.ttlMs;\n const prefix = options.prefix ?? \"kortyx:cp:\";\n\n const latestKey = (threadId: string, checkpointNs: string) =>\n `${prefix}latest:${threadId}:${checkpointNs}`;\n const checkpointKey = (\n threadId: string,\n checkpointNs: string,\n checkpointId: string,\n ) => `${prefix}chk:${threadId}:${checkpointNs}:${checkpointId}`;\n const writesKey = (\n threadId: string,\n checkpointNs: string,\n checkpointId: string,\n ) => `${prefix}wr:${threadId}:${checkpointNs}:${checkpointId}`;\n\n const serde = jsonSerde;\n\n const saver: any = {\n serde,\n\n async get(config: RunnableConfig) {\n const value = await saver.getTuple(config);\n return value ? value.checkpoint : undefined;\n },\n\n getNextVersion(current: number | string | undefined) {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return current !== undefined && typeof current === \"number\"\n ? current + 1\n : 1;\n },\n\n async getTuple(\n config: RunnableConfig,\n ): Promise<CheckpointTuple | undefined> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) return undefined;\n\n const requested = getCheckpointId(config);\n const checkpointId =\n requested || (await store.get(latestKey(threadId, checkpointNs))) || \"\";\n if (!checkpointId) return undefined;\n\n const raw = await store.get(\n checkpointKey(threadId, checkpointNs, checkpointId),\n );\n if (!raw) return undefined;\n const parsed = JSON.parse(raw) as StoredCheckpoint;\n\n const checkpoint = (await serde.loadsTyped(\n \"json\",\n bytesFromB64(parsed.checkpoint),\n )) as Checkpoint;\n const metadata = (await serde.loadsTyped(\n \"json\",\n bytesFromB64(parsed.metadata),\n )) as CheckpointMetadata;\n\n const writes = await store.hgetall(\n writesKey(threadId, checkpointNs, checkpointId),\n );\n const pendingWrites = await Promise.all(\n Object.values(writes).map(async (v) => {\n const w = JSON.parse(v) as StoredWrite;\n return [\n w.taskId,\n w.channel,\n await serde.loadsTyped(\"json\", bytesFromB64(w.value)),\n ] as any;\n }),\n );\n\n const tuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: checkpointId,\n },\n },\n checkpoint,\n metadata,\n pendingWrites,\n };\n\n if (parsed.parentCheckpointId) {\n tuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: parsed.parentCheckpointId,\n },\n };\n }\n\n return tuple;\n },\n\n async *list(_config: RunnableConfig, _options?: CheckpointListOptions) {\n // Minimal implementation: list is not needed for core runtime behavior today.\n // If needed later (studio/time-travel), implement scanning by prefix.\n },\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n _newVersions: Record<string, number | string>,\n ): Promise<RunnableConfig> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) {\n throw new Error(\n 'Failed to put checkpoint: missing \"thread_id\" in config.configurable.',\n );\n }\n\n const prevId = await store.get(latestKey(threadId, checkpointNs));\n\n const prepared = copyCheckpoint(checkpoint as any);\n const [[, chkBytes], [, metaBytes]] = await Promise.all([\n serde.dumpsTyped(prepared),\n serde.dumpsTyped(metadata),\n ]);\n\n const checkpointId = checkpoint.id;\n const key = checkpointKey(threadId, checkpointNs, checkpointId);\n const stored: StoredCheckpoint = {\n checkpoint: b64FromBytes(chkBytes),\n metadata: b64FromBytes(metaBytes),\n parentCheckpointId: config.configurable?.checkpoint_id as\n | string\n | undefined,\n };\n\n await store.set(key, JSON.stringify(stored), ttlMs);\n await store.set(latestKey(threadId, checkpointNs), checkpointId, ttlMs);\n\n // Keep storage bounded: delete the previous checkpoint and its writes.\n if (prevId && prevId !== checkpointId) {\n await store.del(checkpointKey(threadId, checkpointNs, prevId));\n await store.del(writesKey(threadId, checkpointNs, prevId));\n }\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: checkpointId,\n },\n };\n },\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string,\n ): Promise<void> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs = config.configurable?.checkpoint_ns as\n | string\n | undefined;\n const checkpointId = config.configurable?.checkpoint_id as\n | string\n | undefined;\n if (!threadId) {\n throw new Error(\n 'Failed to put writes: missing \"thread_id\" in config.configurable.',\n );\n }\n if (!checkpointId) {\n throw new Error(\n 'Failed to put writes: missing \"checkpoint_id\" in config.configurable.',\n );\n }\n\n const outer = writesKey(threadId, checkpointNs ?? \"\", checkpointId);\n await store.expire(outer, ttlMs);\n\n await Promise.all(\n writes.map(async ([channel, value], idx) => {\n const [, vBytes] = await serde.dumpsTyped(value as any);\n const mappedIdx = WRITES_IDX_MAP[channel] ?? idx;\n const innerKeyStr = `${taskId},${mappedIdx}`;\n const payload: StoredWrite = {\n taskId,\n channel,\n value: b64FromBytes(vBytes),\n };\n const serialized = JSON.stringify(payload);\n if (mappedIdx >= 0) {\n await store.hsetnx(outer, innerKeyStr, serialized);\n } else {\n await store.hset(outer, innerKeyStr, serialized);\n }\n }),\n );\n },\n\n async deleteThread(threadId: string): Promise<void> {\n const chkKeys = await store.scanKeys(`${prefix}chk:${threadId}:`);\n const wrKeys = await store.scanKeys(`${prefix}wr:${threadId}:`);\n const latestKeys = await store.scanKeys(`${prefix}latest:${threadId}:`);\n await store.delRaw([...chkKeys, ...wrKeys, ...latestKeys]);\n },\n };\n\n return saver as RedisCheckpointSaver;\n}\n","import { connect as netConnect, type Socket } from \"node:net\";\nimport { type TLSSocket, connect as tlsConnect } from \"node:tls\";\n\nexport type RedisReply =\n | string\n | number\n | null\n | RedisReply[]\n | { type: \"error\"; message: string };\n\nexport type RedisClientOptions = {\n url: string;\n connectTimeoutMs?: number;\n};\n\nconst encodeBulk = (s: string) => {\n const b = Buffer.from(s, \"utf8\");\n return Buffer.concat([\n Buffer.from(`$${b.length}\\r\\n`),\n b,\n Buffer.from(\"\\r\\n\"),\n ]);\n};\n\nconst encodeCommand = (cmd: string, args: string[]) => {\n const parts = [cmd, ...args];\n const bufs: Buffer[] = [Buffer.from(`*${parts.length}\\r\\n`)];\n for (const p of parts) bufs.push(encodeBulk(p));\n return Buffer.concat(bufs);\n};\n\nfunction readLine(buf: Buffer, start: number) {\n const idx = buf.indexOf(\"\\r\\n\", start);\n if (idx === -1) return null;\n return { line: buf.slice(start, idx).toString(\"utf8\"), next: idx + 2 };\n}\n\nfunction parseReply(\n buf: Buffer,\n start: number,\n): { value: RedisReply; next: number } | null {\n if (start >= buf.length) return null;\n const byte = buf[start];\n if (byte === undefined) return null;\n const prefix = String.fromCharCode(byte);\n if (prefix === \"+\" || prefix === \"-\" || prefix === \":\") {\n const line = readLine(buf, start + 1);\n if (!line) return null;\n if (prefix === \"+\") return { value: line.line, next: line.next };\n if (prefix === \":\")\n return { value: Number.parseInt(line.line, 10), next: line.next };\n return { value: { type: \"error\", message: line.line }, next: line.next };\n }\n\n if (prefix === \"$\") {\n const line = readLine(buf, start + 1);\n if (!line) return null;\n const len = Number.parseInt(line.line, 10);\n if (len === -1) return { value: null, next: line.next };\n const end = line.next + len;\n if (end + 2 > buf.length) return null;\n const data = buf.slice(line.next, end).toString(\"utf8\");\n return { value: data, next: end + 2 };\n }\n\n if (prefix === \"*\") {\n const line = readLine(buf, start + 1);\n if (!line) return null;\n const count = Number.parseInt(line.line, 10);\n if (count === -1) return { value: null, next: line.next };\n const items: RedisReply[] = [];\n let cursor = line.next;\n for (let i = 0; i < count; i++) {\n const parsed = parseReply(buf, cursor);\n if (!parsed) return null;\n items.push(parsed.value);\n cursor = parsed.next;\n }\n return { value: items, next: cursor };\n }\n\n return {\n value: { type: \"error\", message: `Unknown RESP prefix: ${prefix}` },\n next: buf.length,\n };\n}\n\nexport type RedisClient = {\n command: (cmd: string, args?: string[]) => Promise<RedisReply>;\n};\n\nexport function createRedisClient(options: RedisClientOptions): RedisClient {\n const resolvedOptions: Required<\n Pick<RedisClientOptions, \"connectTimeoutMs\">\n > &\n Omit<RedisClientOptions, \"connectTimeoutMs\"> = {\n connectTimeoutMs: options.connectTimeoutMs ?? 5_000,\n url: options.url,\n };\n\n let socket: Socket | TLSSocket | null = null;\n let buffer = Buffer.alloc(0);\n const inflight: Array<{\n resolve: (v: RedisReply) => void;\n reject: (e: unknown) => void;\n }> = [];\n\n let connecting: Promise<void> | null = null;\n let ready = false;\n\n const drainReplies = () => {\n while (inflight.length) {\n const parsed = parseReply(buffer, 0);\n if (!parsed) return;\n const waiter = inflight.shift()!;\n buffer = buffer.slice(parsed.next);\n waiter.resolve(parsed.value);\n }\n };\n\n const send = (cmd: string, args: string[] = []): Promise<RedisReply> => {\n if (!socket) return Promise.reject(new Error(\"Redis socket not available\"));\n const payload = encodeCommand(cmd, args);\n return new Promise<RedisReply>((resolve, reject) => {\n inflight.push({ resolve, reject });\n socket!.write(payload);\n });\n };\n\n const ensureConnected = async () => {\n if (ready) return;\n if (connecting) return connecting;\n\n connecting = (async () => {\n const u = new URL(resolvedOptions.url);\n const isTls = u.protocol === \"rediss:\";\n const host = u.hostname || \"127.0.0.1\";\n const port = u.port ? Number(u.port) : isTls ? 6380 : 6379;\n const password = u.password ? decodeURIComponent(u.password) : \"\";\n const db =\n u.pathname && u.pathname !== \"/\" ? Number(u.pathname.slice(1)) : 0;\n\n const s = isTls\n ? tlsConnect({ host, port, servername: host })\n : netConnect({ host, port });\n socket = s;\n\n s.setNoDelay(true);\n s.setKeepAlive(true);\n\n s.on(\"data\", (chunk) => {\n buffer = Buffer.concat([buffer, chunk]);\n drainReplies();\n });\n\n s.on(\"error\", (err) => {\n ready = false;\n while (inflight.length) inflight.shift()!.reject(err);\n });\n\n s.on(\"close\", () => {\n ready = false;\n while (inflight.length)\n inflight.shift()!.reject(new Error(\"Redis socket closed\"));\n });\n\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(\"Redis connect timeout\")),\n resolvedOptions.connectTimeoutMs,\n );\n\n const onConnect = () => {\n clearTimeout(timer);\n resolve();\n };\n\n // net: \"connect\", tls: \"secureConnect\" (TLSSocket can also emit \"connect\")\n s.once(\"connect\", onConnect);\n (s as any).once?.(\"secureConnect\", onConnect);\n s.once(\"error\", (e) => {\n clearTimeout(timer);\n reject(e);\n });\n });\n\n if (password) {\n const r = await send(\"AUTH\", [password]);\n if (typeof r === \"object\" && r && (r as any).type === \"error\") {\n throw new Error(`Redis AUTH failed: ${(r as any).message}`);\n }\n }\n\n if (db && Number.isFinite(db) && db > 0) {\n const r = await send(\"SELECT\", [String(db)]);\n if (typeof r === \"object\" && r && (r as any).type === \"error\") {\n throw new Error(`Redis SELECT failed: ${(r as any).message}`);\n }\n }\n\n ready = true;\n })();\n\n try {\n await connecting;\n } finally {\n connecting = null;\n }\n };\n\n return {\n async command(cmd: string, args: string[] = []) {\n await ensureConnected();\n return send(cmd, args);\n },\n };\n}\n","import { createRedisClient, type RedisClient } from \"./redis-client\";\n\nexport type RedisFrameworkStoreOptions = {\n url: string;\n prefix?: string;\n};\n\nexport type FrameworkTtl = {\n ttlMs: number;\n};\n\nexport type RedisFrameworkStore = {\n get: (key: string) => Promise<string | null>;\n set: (key: string, value: string, ttlMs: number) => Promise<void>;\n del: (key: string) => Promise<void>;\n hset: (key: string, field: string, value: string) => Promise<void>;\n hsetnx: (key: string, field: string, value: string) => Promise<number>;\n hgetall: (key: string) => Promise<Record<string, string>>;\n expire: (key: string, ttlMs: number) => Promise<void>;\n scanKeys: (prefix: string) => Promise<string[]>;\n delRaw: (keys: string[]) => Promise<void>;\n};\n\ntype RedisErrorReply = { type: \"error\"; message: string };\nconst isRedisError = (r: unknown): r is RedisErrorReply =>\n Boolean(r) && typeof r === \"object\" && (r as any).type === \"error\";\n\nexport function createRedisFrameworkStore(\n options: RedisFrameworkStoreOptions,\n): RedisFrameworkStore {\n const client: RedisClient = createRedisClient({ url: options.url });\n const prefix = options.prefix ?? \"kortyx:fw:\";\n\n const k = (key: string) => `${prefix}${key}`;\n\n return {\n async get(key: string): Promise<string | null> {\n const r = await client.command(\"GET\", [k(key)]);\n if (r === null) return null;\n if (typeof r === \"string\") return r;\n if (isRedisError(r)) {\n throw new Error(`Redis GET error: ${r.message}`);\n }\n return null;\n },\n\n async set(key: string, value: string, ttlMs: number): Promise<void> {\n const args = [k(key), value, \"PX\", String(Math.max(1, ttlMs))];\n const r = await client.command(\"SET\", args);\n if (isRedisError(r)) {\n throw new Error(`Redis SET error: ${r.message}`);\n }\n },\n\n async del(key: string): Promise<void> {\n const r = await client.command(\"DEL\", [k(key)]);\n if (isRedisError(r)) {\n throw new Error(`Redis DEL error: ${r.message}`);\n }\n },\n\n async hset(key: string, field: string, value: string): Promise<void> {\n const r = await client.command(\"HSET\", [k(key), field, value]);\n if (isRedisError(r)) {\n throw new Error(`Redis HSET error: ${r.message}`);\n }\n },\n\n async hsetnx(key: string, field: string, value: string): Promise<number> {\n const r = await client.command(\"HSETNX\", [k(key), field, value]);\n if (isRedisError(r)) {\n throw new Error(`Redis HSETNX error: ${r.message}`);\n }\n return typeof r === \"number\" ? r : 0;\n },\n\n async hgetall(key: string): Promise<Record<string, string>> {\n const r = await client.command(\"HGETALL\", [k(key)]);\n if (isRedisError(r)) {\n throw new Error(`Redis HGETALL error: ${r.message}`);\n }\n if (!Array.isArray(r)) return {};\n const out: Record<string, string> = {};\n for (let i = 0; i < r.length; i += 2) {\n const kk = r[i];\n const v = r[i + 1];\n if (typeof kk === \"string\" && typeof v === \"string\") out[kk] = v;\n }\n return out;\n },\n\n async expire(key: string, ttlMs: number): Promise<void> {\n const r = await client.command(\"PEXPIRE\", [\n k(key),\n String(Math.max(1, ttlMs)),\n ]);\n if (isRedisError(r)) {\n throw new Error(`Redis PEXPIRE error: ${r.message}`);\n }\n },\n\n async scanKeys(prefixKey: string): Promise<string[]> {\n const fullPrefix = k(prefixKey);\n let cursor = \"0\";\n const keys: string[] = [];\n do {\n const r = await client.command(\"SCAN\", [\n cursor,\n \"MATCH\",\n `${fullPrefix}*`,\n \"COUNT\",\n \"200\",\n ]);\n if (!Array.isArray(r) || r.length < 2) break;\n cursor = typeof r[0] === \"string\" ? r[0] : \"0\";\n const batch = r[1];\n if (Array.isArray(batch)) {\n for (const key of batch) {\n if (typeof key === \"string\") keys.push(key);\n }\n }\n } while (cursor !== \"0\");\n return keys;\n },\n\n async delRaw(keys: string[]): Promise<void> {\n if (keys.length === 0) return;\n const r = await client.command(\"DEL\", keys);\n if (isRedisError(r)) {\n throw new Error(`Redis DEL error: ${r.message}`);\n }\n },\n };\n}\n","import type { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { createInMemoryCheckpointSaver } from \"./in-memory-checkpointer\";\nimport {\n createInMemoryPendingRequestStore,\n type PendingRequestStore,\n} from \"./pending-requests\";\nimport { createRedisPendingRequestStore } from \"./redis/pending-request-store\";\nimport { createRedisCheckpointSaver } from \"./redis/redis-checkpointer\";\nimport { createRedisFrameworkStore } from \"./redis/redis-store\";\n\nexport type FrameworkAdapter = {\n kind: \"memory\" | \"redis\";\n pendingRequests: PendingRequestStore;\n checkpointer: BaseCheckpointSaver;\n ttlMs: number;\n /**\n * Best-effort cleanup for ephemeral framework state for a single run.\n * Called when a workflow completes without pausing for an interrupt.\n */\n cleanupRun?: (runId: string, namespaces: string[]) => Promise<void>;\n};\n\nexport type CreateInMemoryFrameworkAdapterOptions = {\n ttlMs?: number;\n};\n\nexport function createInMemoryFrameworkAdapter(\n options?: CreateInMemoryFrameworkAdapterOptions,\n): FrameworkAdapter {\n const ttlMs = options?.ttlMs ?? 15 * 60 * 1000;\n const checkpointer = createInMemoryCheckpointSaver();\n return {\n kind: \"memory\",\n ttlMs,\n pendingRequests: createInMemoryPendingRequestStore(),\n checkpointer,\n cleanupRun: async (runId: string) => {\n try {\n await checkpointer.deleteThread(runId);\n } catch {\n // best-effort cleanup only\n }\n },\n };\n}\n\nexport type CreateRedisFrameworkAdapterOptions = {\n url: string;\n ttlMs?: number;\n prefix?: string;\n};\n\nexport function createRedisFrameworkAdapter(\n options: CreateRedisFrameworkAdapterOptions,\n): FrameworkAdapter {\n const ttlMs = options.ttlMs ?? 15 * 60 * 1000;\n const store = createRedisFrameworkStore({\n url: options.url,\n prefix: options.prefix ?? \"kortyx:fw:\",\n });\n const cpPrefix = \"kortyx:cp:\";\n return {\n kind: \"redis\",\n ttlMs,\n pendingRequests: createRedisPendingRequestStore({\n store,\n prefix: \"kortyx:pending:\",\n }),\n checkpointer: createRedisCheckpointSaver({\n store,\n ttlMs,\n prefix: cpPrefix,\n }),\n cleanupRun: async (runId: string, namespaces: string[]) => {\n // Avoid SCAN-based deletes in hot paths. We can deterministically delete\n // keys by reading the per-namespace latest pointer.\n const nsList = namespaces.length > 0 ? namespaces : [\"\"];\n await Promise.all(\n nsList.map(async (checkpointNs) => {\n const ns = String(checkpointNs ?? \"\");\n const latestKey = `${cpPrefix}latest:${runId}:${ns}`;\n const checkpointId = (await store.get(latestKey)) ?? \"\";\n if (!checkpointId) return;\n await Promise.all([\n store.del(`${cpPrefix}chk:${runId}:${ns}:${checkpointId}`),\n store.del(`${cpPrefix}wr:${runId}:${ns}:${checkpointId}`),\n store.del(latestKey),\n ]);\n }),\n );\n },\n };\n}\n\nexport function createFrameworkAdapterFromEnv(\n env: Record<string, string | undefined> = process.env,\n): FrameworkAdapter {\n const url =\n env.KORTYX_REDIS_URL ||\n env.REDIS_URL ||\n env.KORTYX_FRAMEWORK_REDIS_URL ||\n \"\";\n const ttlMsRaw = env.KORTYX_FRAMEWORK_TTL_MS || env.KORTYX_TTL_MS || \"\";\n const ttlMs = ttlMsRaw ? Number(ttlMsRaw) : undefined;\n\n if (url)\n return createRedisFrameworkAdapter({ url, ...(ttlMs ? { ttlMs } : {}) });\n\n // Dev fallback: in-memory. Not production-safe for resume across processes.\n return createInMemoryFrameworkAdapter({ ...(ttlMs ? { ttlMs } : {}) });\n}\n","import type {\n GraphState,\n NodeConfig,\n NodeContext,\n NodeResult,\n WorkflowDefinition,\n} from \"@kortyx/core\";\nimport { runWithHookContext } from \"@kortyx/hooks\";\nimport { runReasonEngine } from \"@kortyx/hooks/internal\";\nimport type { MemoryAdapter } from \"@kortyx/memory\";\nimport type { GetProviderFn } from \"@kortyx/providers\";\nimport { deepMergeWithArrayOverwrite } from \"@kortyx/utils\";\nimport { Annotation, interrupt, StateGraph } from \"@langchain/langgraph\";\nimport type { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { getCheckpointer } from \"../checkpointer\";\nimport { resolveNodeHandler } from \"../node-loader\";\n\nexport interface GraphRuntimeConfig {\n emit?: (event: string, payload: unknown) => void;\n onCheckpoint?: (args: { nodeId: string; state: GraphState }) => void;\n memoryAdapter?: MemoryAdapter;\n checkpointer?: BaseCheckpointSaver;\n /**\n * Provider factory used by ctx.speak to obtain a streaming model.\n * Use @kortyx/providers or implement your own GetProviderFn.\n */\n getProvider?: GetProviderFn;\n [key: string]: unknown;\n}\n\nexport async function createLangGraph(\n workflow: WorkflowDefinition,\n config: GraphRuntimeConfig,\n) {\n const StateAnnotation = Annotation.Root({\n input: Annotation<unknown>,\n output: Annotation<string>,\n lastNode: Annotation<string>,\n lastCondition: Annotation<string>,\n lastIntent: Annotation<string>,\n memory: Annotation<Record<string, unknown>>({\n reducer: (l, r) => deepMergeWithArrayOverwrite(l ?? {}, r ?? {}),\n default: () => ({}),\n }),\n config: Annotation<unknown>,\n transitionTo: Annotation<string | null>,\n data: Annotation<Record<string, unknown>>({\n reducer: (l, r) => deepMergeWithArrayOverwrite(l ?? {}, r ?? {}),\n default: () => ({}),\n }),\n conversationHistory: Annotation<\n Array<{ node: string; message: string; timestamp: string }>\n >({\n reducer: (l, r) => [...(l ?? []), ...(r ?? [])],\n default: () => [],\n }),\n awaitingHumanInput: Annotation<boolean>,\n });\n\n const builder = new StateGraph(StateAnnotation);\n const edgeApi = builder as unknown as {\n addEdge: (from: string, to: string) => void;\n addConditionalEdges: (\n from: string,\n fn: (s: GraphState) => string,\n mapping: Record<string, string>,\n ) => void;\n compile: () => any;\n };\n const workflowName = workflow.id;\n\n // Ensure an emit function exists so ctx.emit can always call without optional chaining\n type WithEmit = GraphRuntimeConfig & {\n emit: (event: string, payload: unknown) => void;\n };\n const runtimeConfig = config as WithEmit;\n if (!runtimeConfig.emit) {\n runtimeConfig.emit = () => {};\n }\n\n const isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\n const toRecordInput = (value: unknown): Record<string, unknown> => {\n if (isRecord(value)) return value;\n if (value === undefined) return {};\n return { rawInput: value };\n };\n\n const buildNodeConfig = (\n params: Record<string, unknown> | undefined,\n nodeBehavior: Record<string, unknown> | undefined,\n ): NodeConfig => {\n const model = isRecord(params?.model) ? (params!.model as any) : undefined;\n const tool = isRecord(params?.tool) ? (params!.tool as any) : undefined;\n const behaviorFromParams = isRecord(params?.behavior)\n ? (params!.behavior as any)\n : undefined;\n const behavior = {\n ...(behaviorFromParams ?? {}),\n ...(nodeBehavior ?? {}),\n } as any;\n const options = params ?? undefined;\n return {\n ...(model ? { model } : {}),\n ...(tool ? { tool } : {}),\n ...(Object.keys(behavior).length > 0 ? { behavior } : {}),\n ...(options ? { options } : {}),\n } as NodeConfig;\n };\n\n for (const [nodeId, nodeDef] of Object.entries(workflow.nodes ?? {})) {\n const resolvedRun = await resolveNodeHandler({\n run: nodeDef.run,\n workflow,\n });\n const nodeParams = (nodeDef.params ?? undefined) as\n | Record<string, unknown>\n | undefined;\n const nodeConfig: NodeConfig = buildNodeConfig(\n nodeParams,\n (nodeDef.behavior ?? undefined) as unknown as\n | Record<string, unknown>\n | undefined,\n );\n const behavior = nodeConfig.behavior ?? {};\n\n builder.addNode(nodeId, async (state: GraphState) => {\n const ctx = {\n graph: { name: workflowName, node: nodeId },\n config: nodeConfig,\n emit: (event: string, payload: unknown) => {\n runtimeConfig.emit(event, payload);\n },\n error: (message: string) => {\n runtimeConfig.emit(\"error\", {\n node: nodeId,\n message,\n });\n },\n awaitInterrupt: (interruptConfig: any) => {\n const { kind, question } = interruptConfig;\n const isMulti =\n kind === \"multi-choice\" ||\n (interruptConfig.kind !== \"text\" &&\n interruptConfig.multiple === true);\n const payload: any = {\n kind,\n multiple: isMulti,\n question,\n ...(interruptConfig.kind !== \"text\"\n ? { options: interruptConfig.options }\n : {}),\n ...(typeof interruptConfig.id === \"string\" &&\n interruptConfig.id.length > 0\n ? { id: interruptConfig.id }\n : {}),\n ...(typeof interruptConfig.schemaId === \"string\" &&\n interruptConfig.schemaId.length > 0\n ? { schemaId: interruptConfig.schemaId }\n : {}),\n ...(typeof interruptConfig.schemaVersion === \"string\" &&\n interruptConfig.schemaVersion.length > 0\n ? { schemaVersion: interruptConfig.schemaVersion }\n : {}),\n ...(interruptConfig.meta &&\n typeof interruptConfig.meta === \"object\" &&\n !Array.isArray(interruptConfig.meta)\n ? { meta: interruptConfig.meta }\n : {}),\n };\n runtimeConfig.emit(\"interrupt\", {\n node: nodeId,\n workflow: workflowName,\n input: payload,\n });\n const resumed = interrupt(payload) as unknown;\n if (isMulti) {\n if (Array.isArray(resumed)) {\n return (resumed as any[])\n .map((v) =>\n typeof v === \"string\"\n ? v\n : v && typeof (v as any).id === \"string\"\n ? (v as any).id\n : \"\",\n )\n .filter(Boolean) as string[];\n }\n if (typeof resumed === \"string\") return [resumed];\n return [];\n }\n if (typeof resumed === \"string\") return resumed;\n if (resumed && typeof (resumed as any).id === \"string\")\n return String((resumed as any).id);\n return \"\";\n },\n speak: async (\n args: Parameters<NodeContext[\"speak\"]>[0],\n ): Promise<string> => {\n const providerId =\n args.model?.provider ?? nodeConfig.model?.provider ?? \"google\";\n const modelName =\n args.model?.name ?? nodeConfig.model?.name ?? \"gemini-2.5-flash\";\n const temperature =\n args.model?.temperature ?? nodeConfig.model?.temperature ?? 0.3;\n\n const getProvider = runtimeConfig.getProvider;\n if (!getProvider) {\n throw new Error(\n \"Runtime config is missing getProvider; wire a provider factory into @kortyx/runtime.\",\n );\n }\n\n const result = await runReasonEngine({\n getProvider,\n model: {\n providerId,\n modelId: modelName,\n },\n input: args.user ?? \"\",\n system: args.system,\n temperature,\n stream: true,\n emit: true,\n nodeId,\n emitEvent: ctx.emit,\n });\n return result.text;\n },\n } satisfies NodeContext;\n\n if (behavior.checkpoint && config?.onCheckpoint) {\n config.onCheckpoint({ nodeId, state });\n }\n\n const maxAttempts = behavior.retry?.maxAttempts ?? 1;\n let attempt = 0;\n let nodeResult: NodeResult | undefined;\n let hookMemoryUpdates: Record<string, unknown> | null = null;\n let retryHookMemory: Record<string, unknown> | null = null;\n\n while (attempt < maxAttempts) {\n try {\n attempt++;\n const attemptState =\n retryHookMemory && typeof retryHookMemory === \"object\"\n ? ({\n ...state,\n memory: deepMergeWithArrayOverwrite(\n (state.memory ?? {}) as Record<string, unknown>,\n retryHookMemory,\n ),\n } as GraphState)\n : state;\n const hookContext = {\n node: ctx,\n state: attemptState,\n ...(runtimeConfig.getProvider\n ? { getProvider: runtimeConfig.getProvider }\n : {}),\n ...(runtimeConfig.memoryAdapter\n ? { memoryAdapter: runtimeConfig.memoryAdapter }\n : {}),\n };\n const hookRun = await runWithHookContext(hookContext, async () =>\n resolvedRun({\n input: state.input,\n params: (nodeParams ?? {}) as Record<string, unknown>,\n }),\n );\n nodeResult = hookRun.result as NodeResult;\n hookMemoryUpdates = hookRun.memoryUpdates;\n break;\n } catch (err) {\n const patch = (err as any)?.__kortyxMemoryUpdates as\n | Record<string, unknown>\n | null\n | undefined;\n if (patch && typeof patch === \"object\") {\n // Preserve hook memory even when execution pauses via interrupt.\n // Without this merge, checkpointed hook state (e.g. useReason drafts)\n // can be lost before resume.\n state.memory = deepMergeWithArrayOverwrite(\n (state.memory ?? {}) as Record<string, unknown>,\n patch,\n );\n retryHookMemory = deepMergeWithArrayOverwrite(\n (retryHookMemory ?? {}) as Record<string, unknown>,\n patch,\n );\n }\n const hasMore = attempt < maxAttempts;\n const delayMs = behavior.retry?.delayMs ?? 0;\n if (hasMore && delayMs > 0) {\n await new Promise((r) => setTimeout(r, delayMs));\n continue;\n }\n if (!hasMore) throw err;\n }\n }\n\n const res: NodeResult = (nodeResult ?? {}) as NodeResult;\n if (hookMemoryUpdates) {\n res.infra = {\n ...(res.infra ?? {}),\n memory: deepMergeWithArrayOverwrite(\n ((res.infra?.memory ?? {}) as Record<string, unknown>) || {},\n hookMemoryUpdates,\n ),\n };\n }\n const uiMessage = res.ui?.message;\n const shouldRespond =\n typeof uiMessage === \"string\" && uiMessage.trim().length > 0;\n\n if (shouldRespond) {\n ctx.emit(\"message\", { node: nodeId, content: uiMessage });\n }\n\n if (res.transitionTo) {\n ctx.emit(\"transition\", {\n transitionTo: res.transitionTo,\n payload: res.data ?? {},\n });\n }\n\n const updates: Record<string, unknown> = {};\n\n if (typeof res.condition === \"string\")\n updates.lastCondition = res.condition;\n if (typeof res.intent === \"string\") updates.lastIntent = res.intent;\n\n if (res.data && typeof res.data === \"object\") {\n // Treat node `data` as the flowing payload between nodes.\n // Accumulate by merging into the previous input (if any).\n updates.input = deepMergeWithArrayOverwrite(\n toRecordInput(state.input),\n res.data as Record<string, unknown>,\n );\n updates.data = deepMergeWithArrayOverwrite(\n (state.data ?? {}) as Record<string, unknown>,\n res.data as Record<string, unknown>,\n );\n }\n if (res.infra?.memory && typeof res.infra.memory === \"object\") {\n updates.memory = deepMergeWithArrayOverwrite(\n (state.memory ?? {}) as Record<string, unknown>,\n res.infra.memory as Record<string, unknown>,\n );\n }\n\n if (res.ui) {\n updates.ui = {\n message:\n typeof res.ui.message === \"string\"\n ? res.ui.message\n : (state.ui?.message ?? \"\"),\n structured: deepMergeWithArrayOverwrite(\n (state.ui?.structured ?? {}) as Record<string, unknown>,\n (res.ui.structured ?? {}) as Record<string, unknown>,\n ),\n };\n }\n\n if (shouldRespond && uiMessage) {\n updates.conversationHistory = [\n ...(state.conversationHistory ?? []),\n {\n node: nodeId,\n message: uiMessage,\n timestamp: new Date().toISOString(),\n },\n ];\n }\n\n if (res.ui?.structured) {\n const payload = res.ui.structured as Record<string, unknown>;\n const inferredType =\n payload && typeof payload === \"object\" && \"jobs\" in payload\n ? \"jobs\"\n : typeof (payload as { summary?: unknown }).summary === \"string\" ||\n (payload as { topJobs?: unknown }).topJobs\n ? \"summary\"\n : \"generic\";\n ctx.emit(\"structured_data\", {\n node: nodeId,\n dataType: inferredType,\n data: payload,\n });\n }\n\n return updates as any;\n });\n }\n\n type EdgeTriple = readonly [string, string, { when?: string }?];\n const condGroups: Record<string, Array<{ when: string; to: string }>> = {};\n const plainEdges: Array<[string, string]> = [];\n\n for (const edge of workflow.edges as unknown as EdgeTriple[]) {\n const [from, to, condition] = edge as unknown as EdgeTriple;\n if (condition && typeof condition.when === \"string\" && condition.when) {\n if (!condGroups[from]) condGroups[from] = [];\n condGroups[from].push({ when: condition.when, to });\n } else {\n plainEdges.push([from, to]);\n }\n }\n\n for (const [from, to] of plainEdges) {\n edgeApi.addEdge(from, to);\n }\n\n for (const [from, rules] of Object.entries(condGroups)) {\n const mapping: Record<string, string> = Object.fromEntries(\n rules.map((r) => [r.when, r.to]),\n );\n const fallbackKey = `__default__:${from}`;\n mapping[fallbackKey] = \"__end__\";\n edgeApi.addConditionalEdges(\n from,\n (s: GraphState) => {\n const trigger = s.lastCondition ?? s.lastIntent;\n if (trigger && Object.hasOwn(mapping, trigger as string)) {\n return trigger as string;\n }\n return fallbackKey;\n },\n mapping,\n );\n }\n\n const sessionId = (config as any)?.session?.id ?? \"__default__\";\n const checkpointer = config.checkpointer ?? getCheckpointer(sessionId);\n const graph = (builder as any).compile({ checkpointer });\n\n interface GraphExtensions {\n name: string;\n config: GraphRuntimeConfig;\n resume(state: GraphState, input: unknown): Promise<GraphState>;\n timeTravelTo(state: GraphState, checkpointId: string): Promise<GraphState>;\n }\n type RuntimeGraph = typeof graph & GraphExtensions;\n\n const runtimeGraph = graph as RuntimeGraph;\n runtimeGraph.name = workflow.id;\n runtimeGraph.config = config;\n\n runtimeGraph.resume = async (state: GraphState, input: unknown) => {\n const resumed = { ...state, input, awaitingHumanInput: false };\n return graph.invoke(resumed as any) as unknown as GraphState;\n };\n\n runtimeGraph.timeTravelTo = async (\n state: GraphState,\n checkpointId: string,\n ) => {\n const checkpoints = (\n state.memory as { checkpoints?: Record<string, { snapshot: unknown }> }\n )?.checkpoints;\n const snapshot = checkpoints?.[checkpointId];\n if (!snapshot) throw new Error(`Checkpoint '${checkpointId}' not found`);\n return graph.invoke(\n snapshot.snapshot as unknown as Partial<\n (typeof StateAnnotation)[\"State\"]\n >,\n ) as unknown as GraphState;\n };\n\n return runtimeGraph;\n}\n","import { dirname, isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { NodeFn, WorkflowDefinition } from \"@kortyx/core\";\nimport { resolveNode } from \"./node-registry\";\n\ntype LoadedNodeModule = Record<string, unknown>;\n\nconst dynamicImport = new Function(\n \"specifier\",\n // Avoid bundler static analysis of `import(...)` (e.g. Next.js/Turbopack).\n // This is only used on the server.\n \"return import(specifier)\",\n) as (specifier: string) => Promise<LoadedNodeModule>;\n\nfunction looksLikePath(specifier: string) {\n if (specifier.startsWith(\"file:\")) return true;\n if (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) return true;\n if (specifier.startsWith(\"/\")) return true;\n return specifier.includes(\"/\");\n}\n\nfunction getWorkflowBaseDir(\n workflow: WorkflowDefinition | undefined,\n cwd: string,\n): string {\n const meta = workflow?.metadata as Record<string, unknown> | undefined;\n const filePath = meta?.__filePath;\n if (typeof filePath === \"string\" && filePath.length > 0) {\n return dirname(filePath);\n }\n return cwd;\n}\n\nfunction pickNodeExport(mod: LoadedNodeModule, exportName?: string): NodeFn {\n if (exportName) {\n const candidate = mod[exportName];\n if (typeof candidate === \"function\") return candidate as NodeFn;\n throw new Error(`Node export \"${exportName}\" not found or not a function.`);\n }\n\n const defaultExport = mod.default;\n if (typeof defaultExport === \"function\") return defaultExport as NodeFn;\n\n const fnExports = Object.entries(mod).filter(\n ([, v]) => typeof v === \"function\",\n );\n if (fnExports.length === 1) return fnExports[0]![1] as NodeFn;\n\n const names = fnExports.map(([k]) => k).sort();\n throw new Error(\n `Node module must export a default function or exactly one named function (found: ${\n names.join(\", \") || \"none\"\n }).`,\n );\n}\n\nexport async function resolveNodeHandler(args: {\n run: string | NodeFn;\n workflow?: WorkflowDefinition;\n cwd?: string;\n}): Promise<NodeFn> {\n const { run, workflow } = args;\n const cwd = args.cwd ?? process.cwd();\n\n if (typeof run === \"function\") return run;\n\n // New DX: YAML/JSON specify module path (optionally with #exportName)\n if (looksLikePath(run)) {\n const [moduleRef, exportName] = run.split(\"#\", 2) as [\n string,\n string | undefined,\n ];\n const baseDir = getWorkflowBaseDir(workflow, cwd);\n\n const specifier = moduleRef.startsWith(\"file:\")\n ? moduleRef\n : isAbsolute(moduleRef)\n ? pathToFileURL(moduleRef).href\n : pathToFileURL(resolve(baseDir, moduleRef)).href;\n\n const mod = await dynamicImport(specifier);\n return pickNodeExport(mod, exportName);\n }\n\n // Back-compat: symbolic node registry name\n return resolveNode(run);\n}\n","import type { NodeFn } from \"@kortyx/core\";\n\nconst registry = new Map<string, NodeFn>();\n\nexport function registerNode(id: string, fn: NodeFn): void {\n registry.set(id, fn);\n}\n\nexport function getRegisteredNode(id: string): NodeFn | null {\n return registry.get(id) ?? null;\n}\n\nexport function listRegisteredNodes(): string[] {\n return [...registry.keys()].sort();\n}\n\nexport function clearRegisteredNodes(): void {\n registry.clear();\n}\n\nexport function resolveNode(id: string): NodeFn {\n const fn = registry.get(id);\n if (!fn) {\n throw new Error(\n `Node '${id}' is not registered. Call registerNode('${id}', fn) before running workflows that reference it.`,\n );\n }\n return fn;\n}\n","import { v7 as uuid } from \"uuid\";\n\nexport function makeResumeToken(): string {\n return uuid();\n}\n\nexport function makeRequestId(prefix = \"req\"): string {\n return `${prefix}-${uuid()}`;\n}\n","import type { WorkflowDefinition } from \"@kortyx/core\";\nimport { loadWorkflow } from \"@kortyx/core\";\nimport { readdir, readFile } from \"fs/promises\";\nimport { join } from \"path\";\nimport type { WorkflowRegistry } from \"./interface\";\n\nexport interface FileWorkflowRegistryOptions {\n workflowsDir: string;\n fallbackId?: string;\n cache?: boolean;\n extensions?: string[];\n}\n\ntype AnyWorkflow = WorkflowDefinition;\n\nconst DEFAULT_EXTENSIONS = [\n \".workflow.ts\",\n \".workflow.mts\",\n \".workflow.js\",\n \".workflow.mjs\",\n \".workflow.json\",\n \".workflow.yml\",\n \".workflow.yaml\",\n];\n\nfunction isWorkflowFile(name: string, extensions: string[]) {\n return extensions.some((ext) => name.endsWith(ext));\n}\n\nfunction isDeclarativeWorkflowFile(name: string) {\n return (\n name.endsWith(\".workflow.json\") ||\n name.endsWith(\".workflow.yml\") ||\n name.endsWith(\".workflow.yaml\")\n );\n}\n\nexport function createFileWorkflowRegistry(\n options: FileWorkflowRegistryOptions,\n): WorkflowRegistry {\n const workflowsDir = options.workflowsDir;\n const fallbackId = options.fallbackId ?? \"general-chat\";\n const extensions = options.extensions ?? DEFAULT_EXTENSIONS;\n const shouldCache = options.cache ?? true;\n\n let workflowCache: Record<string, AnyWorkflow> | null = null;\n\n async function loadWorkflows(): Promise<Record<string, AnyWorkflow>> {\n if (shouldCache && workflowCache) return workflowCache;\n\n const files = await readdir(workflowsDir, { withFileTypes: true });\n const workflowFiles = files\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name)\n .filter((file) => isWorkflowFile(file, extensions));\n\n const workflows: Record<string, AnyWorkflow> = {};\n\n for (const file of workflowFiles) {\n try {\n const modulePath = join(workflowsDir, file);\n\n // For declarative JSON/YAML workflows\n if (isDeclarativeWorkflowFile(file)) {\n const raw = await readFile(modulePath, \"utf8\");\n const workflow = loadWorkflow(raw) as unknown as AnyWorkflow;\n (workflow as any).metadata = {\n ...(((workflow as any).metadata ?? {}) as Record<string, unknown>),\n __filePath: modulePath,\n };\n workflows[workflow.id] = workflow;\n continue;\n }\n\n // For TS/JS module workflows\n const module = await import(modulePath);\n const workflowExport = Object.values(module).find(\n (exp): exp is AnyWorkflow => {\n const obj = exp as {\n id?: unknown;\n nodes?: unknown;\n edges?: unknown;\n };\n return (\n exp !== null &&\n typeof exp === \"object\" &&\n typeof obj.id === \"string\" &&\n typeof obj.nodes === \"object\" &&\n obj.nodes !== null &&\n Array.isArray(obj.edges)\n );\n },\n );\n\n if (workflowExport) {\n (workflowExport as any).metadata = {\n ...(((workflowExport as any).metadata ?? {}) as Record<\n string,\n unknown\n >),\n __filePath: modulePath,\n };\n workflows[workflowExport.id] = workflowExport;\n }\n } catch (error) {\n console.warn(`Failed to load workflow from ${file}:`, error);\n }\n }\n\n if (shouldCache) workflowCache = workflows;\n return workflows;\n }\n\n async function list(): Promise<AnyWorkflow[]> {\n const workflows = await loadWorkflows();\n return Object.values(workflows);\n }\n\n async function get(id: string): Promise<AnyWorkflow | null> {\n const workflows = await loadWorkflows();\n return workflows[id] ?? null;\n }\n\n async function select(\n id: string,\n selectOptions?: { fallbackId?: string },\n ): Promise<AnyWorkflow> {\n const workflows = await loadWorkflows();\n const fallback = selectOptions?.fallbackId ?? fallbackId;\n const selected = workflows[id] ?? (fallback ? workflows[fallback] : null);\n\n if (!selected) {\n throw new Error(\n `No workflow found for id \"${id}\" and no fallback \"${fallback}\" workflow available`,\n );\n }\n\n return selected;\n }\n\n async function refresh() {\n workflowCache = null;\n await loadWorkflows();\n }\n\n return {\n list,\n get,\n select,\n refresh,\n } satisfies WorkflowRegistry;\n}\n","import type { WorkflowDefinition } from \"@kortyx/core\";\nimport type { WorkflowRegistry } from \"./interface\";\n\nexport function createInMemoryWorkflowRegistry(\n workflows: WorkflowDefinition[],\n options?: { fallbackId?: string },\n): WorkflowRegistry {\n const byId = new Map<string, WorkflowDefinition>();\n for (const wf of workflows) byId.set(wf.id, wf);\n\n const fallbackId = options?.fallbackId ?? \"general-chat\";\n\n return {\n async list() {\n return Array.from(byId.values());\n },\n async get(id: string) {\n return byId.get(id) ?? null;\n },\n async select(id: string, selectOptions?: { fallbackId?: string }) {\n const fallback = selectOptions?.fallbackId ?? fallbackId;\n const wf = byId.get(id) ?? (fallback ? byId.get(fallback) : undefined);\n if (!wf) {\n throw new Error(\n `Workflow \"${id}\" not found${fallback ? ` (fallback \"${fallback}\" missing too)` : \"\"}.`,\n );\n }\n return wf;\n },\n };\n}\n","import type { GraphState, MemoryEnvelope } from \"@kortyx/core\";\n\n/**\n * Prepares the initial runtime graph state from chat context, memory, and runtime config.\n * This stays deliberately generic in the config type so apps can shape it.\n */\nexport interface InitialStateArgs<Config = unknown> {\n input: unknown;\n memory: MemoryEnvelope;\n config: Config;\n defaultWorkflowId?: string;\n}\n\nexport async function buildInitialGraphState<Config>({\n input,\n memory,\n config,\n defaultWorkflowId,\n}: InitialStateArgs<Config>): Promise<GraphState> {\n const currentWorkflow =\n (memory.currentWorkflow as any) || (defaultWorkflowId as any);\n if (!currentWorkflow) {\n throw new Error(\n \"No workflow selected. Provide defaultWorkflowId (or set memory.currentWorkflow) before starting the graph.\",\n );\n }\n\n return {\n input,\n lastNode: \"__start__\",\n memory,\n config: config as unknown,\n conversationHistory: [],\n currentWorkflow,\n awaitingHumanInput: false,\n } as GraphState;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,kCAUO;AAsBP,IAAM,YAAY,CAAC,MAAc,IAAI,WAAW,OAAO,KAAK,GAAG,MAAM,CAAC;AACtE,IAAM,aAAa,CAAC,OAClB,OAAO,OAAO,WAAW,KAAK,OAAO,KAAK,EAAE,EAAE,SAAS,MAAM;AAE/D,IAAM,YAAgC;AAAA,EACpC,MAAM,WAAW,MAAW;AAC1B,WAAO,CAAC,QAAQ,UAAU,KAAK,UAAU,IAAI,CAAC,CAAC;AAAA,EACjD;AAAA,EACA,MAAM,WAAW,OAAe,MAA2B;AACzD,WAAO,KAAK,MAAM,WA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;AACvB,oBAAgB;AAChB,UAAM,cAAc;AAAA,EACtB;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACpJO,SAAS,+BACd,WACA,SACkB;AAClB,QAAM,OAAO,oBAAI,IAAgC;AACjD,aAAW,MAAM,UAAW,MAAK,IAAI,GAAG,IAAI,EAAE;AAE9C,QAAM,aAAa,SAAS,cAAc;AAE1C,SAAO;AAAA,IACL,MAAM,OAAO;AACX,aAAO,MAAM,KAAK,KAAK,OAAO,CAAC;AAAA,IACjC;AAAA,IACA,MAAM,IAAI,IAAY;AACpB,aAAO,KAAK,IAAI,EAAE,KAAK;AAAA,IACzB;AAAA,IACA,MAAM,OAAO,IAAY,eAAyC;AAChE,YAAM,WAAW,eAAe,cAAc;AAC9C,YAAM,KAAK,KAAK,IAAI,EAAE,MAAM,WAAW,KAAK,IAAI,QAAQ,IAAI;AAC5D,UAAI,CAAC,IAAI;AACP,cAAM,IAAI;AAAA,UACR,aAAa,EAAE,cAAc,WAAW,eAAe,QAAQ,mBAAmB,EAAE;AAAA,QACtF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;ACjBA,eAAsB,uBAA+B;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAkD;AAChD,QAAM,kBACH,OAAO,mBAA4B;AACtC,MAAI,CAAC,iBAAiB;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,qBAAqB,CAAC;AAAA,IACtB;AAAA,IACA,oBAAoB;AAAA,EACtB;AACF;","names":["import_langgraph_checkpoint","utf8Bytes","utf8String","jsonSerde","resolve","tlsConnect","netConnect","uuid","module"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/framework/in-memory-checkpointer.ts","../src/checkpointer.ts","../src/framework/pending-requests.ts","../src/framework/redis/pending-request-store.ts","../src/framework/redis/redis-checkpointer.ts","../src/framework/redis/redis-client.ts","../src/framework/redis/redis-store.ts","../src/framework/adapter.ts","../src/graph/create-execution-graph.ts","../src/node-loader.ts","../src/node-registry.ts","../src/interrupt/tokens.ts","../src/registry/file-registry.ts","../src/registry/in-memory-registry.ts","../src/state/build-initial-state.ts"],"sourcesContent":["// release-test: 2026-01-22\nexport * from \"./checkpointer\";\nexport * from \"./framework/adapter\";\nexport * from \"./framework/pending-requests\";\nexport * from \"./graph/create-execution-graph\";\nexport * from \"./interrupt/tokens\";\nexport * from \"./node-registry\";\nexport * from \"./registry/file-registry\";\nexport * from \"./registry/in-memory-registry\";\nexport * from \"./registry/interface\";\nexport * from \"./state/build-initial-state\";\n","import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n type BaseCheckpointSaver,\n type Checkpoint,\n type CheckpointListOptions,\n type CheckpointMetadata,\n type CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n type PendingWrite,\n WRITES_IDX_MAP,\n} from \"@langchain/langgraph-checkpoint\";\n\ntype SerializerProtocol = {\n dumpsTyped: (data: any) => Promise<[string, Uint8Array]>;\n loadsTyped: (type: string, data: Uint8Array | string) => Promise<any>;\n};\n\ntype StoredCheckpoint = {\n checkpoint: Checkpoint;\n metadata: CheckpointMetadata;\n parentCheckpointId?: string | undefined;\n writes: Map<string, [string, string, unknown]>;\n};\n\nexport type InMemoryCheckpointSaverOptions = {\n /**\n * Maximum number of pending writes stored for a single checkpoint.\n * Prevents unbounded memory growth in dev servers.\n */\n maxWritesPerCheckpoint?: number;\n};\n\nconst utf8Bytes = (s: string) => new Uint8Array(Buffer.from(s, \"utf8\"));\nconst utf8String = (u8: Uint8Array | string) =>\n typeof u8 === \"string\" ? u8 : Buffer.from(u8).toString(\"utf8\");\n\nconst jsonSerde: SerializerProtocol = {\n async dumpsTyped(data: any) {\n return [\"json\", utf8Bytes(JSON.stringify(data))];\n },\n async loadsTyped(_type: string, data: Uint8Array | string) {\n return JSON.parse(utf8String(data));\n },\n};\n\nexport type InMemoryCheckpointSaver = BaseCheckpointSaver & {\n deleteThread: (threadId: string) => Promise<void>;\n};\n\n/**\n * Bounded in-memory checkpointer:\n * - Keeps only the latest checkpoint per (thread_id, checkpoint_ns)\n * - Keeps only a bounded number of pending writes for that checkpoint\n *\n * This is a safer dev default than the upstream in-memory saver, which can grow without bound.\n */\nexport function createInMemoryCheckpointSaver(\n options?: InMemoryCheckpointSaverOptions,\n): InMemoryCheckpointSaver {\n const maxWritesPerCheckpoint = options?.maxWritesPerCheckpoint ?? 2_000;\n\n // (threadId|ns) -> checkpointId\n const latest = new Map<string, string>();\n // (threadId|ns|id) -> stored\n const checkpoints = new Map<string, StoredCheckpoint>();\n\n const nsKey = (threadId: string, checkpointNs: string) =>\n `${threadId}\\u0001${checkpointNs}`;\n const chkKey = (\n threadId: string,\n checkpointNs: string,\n checkpointId: string,\n ) => `${threadId}\\u0001${checkpointNs}\\u0001${checkpointId}`;\n\n const saver: any = {\n serde: jsonSerde,\n\n async get(config: RunnableConfig) {\n const value = await saver.getTuple(config);\n return value ? value.checkpoint : undefined;\n },\n\n getNextVersion(current: number | string | undefined) {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return current !== undefined && typeof current === \"number\"\n ? current + 1\n : 1;\n },\n\n async getTuple(\n config: RunnableConfig,\n ): Promise<CheckpointTuple | undefined> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) return undefined;\n\n const requested = getCheckpointId(config);\n const id = requested || latest.get(nsKey(threadId, checkpointNs));\n if (!id) return undefined;\n\n const stored = checkpoints.get(chkKey(threadId, checkpointNs, id));\n if (!stored) return undefined;\n\n const pendingWrites = Array.from(stored.writes.values());\n const tuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: id,\n },\n },\n checkpoint: stored.checkpoint,\n metadata: stored.metadata,\n pendingWrites: pendingWrites as any,\n };\n\n if (stored.parentCheckpointId) {\n tuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: stored.parentCheckpointId,\n },\n };\n }\n\n return tuple;\n },\n\n async *list(_config: RunnableConfig, _options?: CheckpointListOptions) {\n // Not required for current runtime behavior.\n },\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n _newVersions: Record<string, number | string>,\n ): Promise<RunnableConfig> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) {\n throw new Error(\n 'Failed to put checkpoint: missing \"thread_id\" in config.configurable.',\n );\n }\n\n const ns = nsKey(threadId, checkpointNs);\n const prevId = latest.get(ns);\n\n const prepared = copyCheckpoint(checkpoint as any);\n const entry: StoredCheckpoint = {\n checkpoint: prepared as any,\n metadata,\n parentCheckpointId: config.configurable?.checkpoint_id as\n | string\n | undefined,\n writes: new Map(),\n };\n\n const id = checkpoint.id;\n checkpoints.set(chkKey(threadId, checkpointNs, id), entry);\n latest.set(ns, id);\n\n // Bounded: drop previous checkpoint + its writes\n if (prevId && prevId !== id) {\n checkpoints.delete(chkKey(threadId, checkpointNs, prevId));\n }\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: id,\n },\n };\n },\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string,\n ): Promise<void> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n const checkpointId = config.configurable?.checkpoint_id as\n | string\n | undefined;\n if (!threadId || !checkpointId) return;\n\n const stored = checkpoints.get(\n chkKey(threadId, checkpointNs, checkpointId),\n );\n if (!stored) return;\n\n for (let idx = 0; idx < writes.length; idx++) {\n const [channel, value] = writes[idx]!;\n const mappedIdx = WRITES_IDX_MAP[channel] ?? idx;\n const key = `${taskId},${mappedIdx}`;\n\n // HSETNX semantics for normal writes; always overwrite for special writes (negative mappedIdx)\n if (mappedIdx >= 0 && stored.writes.has(key)) continue;\n\n // Bound the number of writes to avoid unbounded growth in dev\n if (stored.writes.size >= maxWritesPerCheckpoint) break;\n\n stored.writes.set(key, [taskId, channel, value]);\n }\n },\n\n async deleteThread(threadId: string): Promise<void> {\n for (const k of Array.from(latest.keys())) {\n if (k.startsWith(`${threadId}\\u0001`)) latest.delete(k);\n }\n for (const k of Array.from(checkpoints.keys())) {\n if (k.startsWith(`${threadId}\\u0001`)) checkpoints.delete(k);\n }\n },\n };\n\n return saver as InMemoryCheckpointSaver;\n}\n","import type { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { createInMemoryCheckpointSaver } from \"./framework/in-memory-checkpointer\";\n\nconst MAX_CHECKPOINTERS = 200;\nconst map = new Map<string, BaseCheckpointSaver>();\n\nexport function getCheckpointer(key: string): BaseCheckpointSaver {\n const k = key || \"__default__\";\n const existing = map.get(k);\n if (existing) return existing;\n\n const saver = createInMemoryCheckpointSaver();\n map.set(k, saver);\n\n // Simple FIFO eviction to avoid unbounded growth in long-lived dev servers.\n if (map.size > MAX_CHECKPOINTERS) {\n const first = map.keys().next().value as string | undefined;\n if (first) map.delete(first);\n }\n\n return saver;\n}\n","import type { GraphState } from \"@kortyx/core\";\n\nexport type HumanInputKind = \"choice\" | \"multi-choice\" | \"text\";\n\nexport interface HumanInputOption {\n id: string;\n label: string;\n description?: string;\n value?: unknown;\n}\n\nexport interface PendingRequestRecord {\n token: string;\n requestId: string;\n sessionId?: string | undefined;\n /**\n * Framework run identifier used by the checkpointer (thread_id).\n * This must be stable across interrupt/resume, but should not be reused for new messages.\n */\n runId: string;\n workflow: string;\n node: string;\n state?: GraphState;\n schema: {\n kind: HumanInputKind;\n multiple: boolean;\n question?: string;\n id?: string;\n schemaId?: string;\n schemaVersion?: string;\n meta?: Record<string, unknown>;\n };\n options: HumanInputOption[];\n createdAt: number;\n ttlMs: number;\n}\n\nexport interface PendingRequestStore {\n save: (rec: PendingRequestRecord) => Promise<void>;\n get: (token: string) => Promise<PendingRequestRecord | null>;\n delete: (token: string) => Promise<void>;\n update: (\n token: string,\n patch: Partial<PendingRequestRecord>,\n ) => Promise<void>;\n}\n\nexport function createInMemoryPendingRequestStore(): PendingRequestStore {\n const store = new Map<string, PendingRequestRecord>();\n\n const prune = () => {\n const t = Date.now();\n for (const [k, v] of store.entries()) {\n if (t - v.createdAt > v.ttlMs) store.delete(k);\n }\n };\n\n return {\n async save(rec) {\n prune();\n store.set(rec.token, rec);\n },\n async get(token) {\n prune();\n return store.get(token) ?? null;\n },\n async delete(token) {\n store.delete(token);\n },\n async update(token, patch) {\n const prev = store.get(token);\n if (!prev) return;\n store.set(token, { ...prev, ...patch });\n },\n };\n}\n","import type {\n PendingRequestRecord,\n PendingRequestStore,\n} from \"../pending-requests\";\nimport type { RedisFrameworkStore } from \"./redis-store\";\n\nexport type RedisPendingRequestStoreOptions = {\n store: RedisFrameworkStore;\n prefix?: string;\n};\n\nexport function createRedisPendingRequestStore(\n options: RedisPendingRequestStoreOptions,\n): PendingRequestStore {\n const prefix = options.prefix ?? \"kortyx:pending:\";\n const key = (token: string) => `${prefix}${token}`;\n\n return {\n async save(rec: PendingRequestRecord) {\n await options.store.set(key(rec.token), JSON.stringify(rec), rec.ttlMs);\n },\n async get(token: string) {\n const raw = await options.store.get(key(token));\n if (!raw) return null;\n return JSON.parse(raw) as PendingRequestRecord;\n },\n async delete(token: string) {\n await options.store.del(key(token));\n },\n async update(token: string, patch: Partial<PendingRequestRecord>) {\n const prevRaw = await options.store.get(key(token));\n if (!prevRaw) return;\n const prev = JSON.parse(prevRaw) as PendingRequestRecord;\n const next = { ...prev, ...patch } as PendingRequestRecord;\n const ttlLeft = Math.max(1, next.ttlMs - (Date.now() - next.createdAt));\n await options.store.set(key(token), JSON.stringify(next), ttlLeft);\n },\n };\n}\n","import type { RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n type BaseCheckpointSaver,\n type Checkpoint,\n type CheckpointListOptions,\n type CheckpointMetadata,\n type CheckpointTuple,\n copyCheckpoint,\n getCheckpointId,\n type PendingWrite,\n WRITES_IDX_MAP,\n} from \"@langchain/langgraph-checkpoint\";\nimport type { RedisFrameworkStore } from \"./redis-store\";\n\ntype SerializerProtocol = {\n dumpsTyped: (data: any) => Promise<[string, Uint8Array]>;\n loadsTyped: (type: string, data: Uint8Array | string) => Promise<any>;\n};\n\ntype RedisCheckpointSaverOptions = {\n store: RedisFrameworkStore;\n prefix?: string;\n ttlMs: number;\n};\n\nconst utf8Bytes = (s: string) => new Uint8Array(Buffer.from(s, \"utf8\"));\nconst utf8String = (u8: Uint8Array | string) =>\n typeof u8 === \"string\" ? u8 : Buffer.from(u8).toString(\"utf8\");\n\nconst jsonSerde: SerializerProtocol = {\n async dumpsTyped(data: any) {\n return [\"json\", utf8Bytes(JSON.stringify(data))];\n },\n async loadsTyped(_type: string, data: Uint8Array | string) {\n return JSON.parse(utf8String(data));\n },\n};\n\nconst b64FromBytes = (u8: Uint8Array) => Buffer.from(u8).toString(\"base64\");\nconst bytesFromB64 = (s: string) => new Uint8Array(Buffer.from(s, \"base64\"));\n\ntype StoredCheckpoint = {\n checkpoint: string; // base64\n metadata: string; // base64\n parentCheckpointId?: string | undefined;\n};\n\ntype StoredWrite = {\n taskId: string;\n channel: string;\n value: string; // base64\n};\n\nexport type RedisCheckpointSaver = BaseCheckpointSaver & {\n deleteThread: (threadId: string) => Promise<void>;\n};\n\nexport function createRedisCheckpointSaver(\n options: RedisCheckpointSaverOptions,\n): RedisCheckpointSaver {\n const store = options.store;\n const ttlMs = options.ttlMs;\n const prefix = options.prefix ?? \"kortyx:cp:\";\n\n const latestKey = (threadId: string, checkpointNs: string) =>\n `${prefix}latest:${threadId}:${checkpointNs}`;\n const checkpointKey = (\n threadId: string,\n checkpointNs: string,\n checkpointId: string,\n ) => `${prefix}chk:${threadId}:${checkpointNs}:${checkpointId}`;\n const writesKey = (\n threadId: string,\n checkpointNs: string,\n checkpointId: string,\n ) => `${prefix}wr:${threadId}:${checkpointNs}:${checkpointId}`;\n\n const serde = jsonSerde;\n\n const saver: any = {\n serde,\n\n async get(config: RunnableConfig) {\n const value = await saver.getTuple(config);\n return value ? value.checkpoint : undefined;\n },\n\n getNextVersion(current: number | string | undefined) {\n if (typeof current === \"string\") {\n throw new Error(\"Please override this method to use string versions.\");\n }\n return current !== undefined && typeof current === \"number\"\n ? current + 1\n : 1;\n },\n\n async getTuple(\n config: RunnableConfig,\n ): Promise<CheckpointTuple | undefined> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) return undefined;\n\n const requested = getCheckpointId(config);\n const checkpointId =\n requested || (await store.get(latestKey(threadId, checkpointNs))) || \"\";\n if (!checkpointId) return undefined;\n\n const raw = await store.get(\n checkpointKey(threadId, checkpointNs, checkpointId),\n );\n if (!raw) return undefined;\n const parsed = JSON.parse(raw) as StoredCheckpoint;\n\n const checkpoint = (await serde.loadsTyped(\n \"json\",\n bytesFromB64(parsed.checkpoint),\n )) as Checkpoint;\n const metadata = (await serde.loadsTyped(\n \"json\",\n bytesFromB64(parsed.metadata),\n )) as CheckpointMetadata;\n\n const writes = await store.hgetall(\n writesKey(threadId, checkpointNs, checkpointId),\n );\n const pendingWrites = await Promise.all(\n Object.values(writes).map(async (v) => {\n const w = JSON.parse(v) as StoredWrite;\n return [\n w.taskId,\n w.channel,\n await serde.loadsTyped(\"json\", bytesFromB64(w.value)),\n ] as any;\n }),\n );\n\n const tuple: CheckpointTuple = {\n config: {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: checkpointId,\n },\n },\n checkpoint,\n metadata,\n pendingWrites,\n };\n\n if (parsed.parentCheckpointId) {\n tuple.parentConfig = {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: parsed.parentCheckpointId,\n },\n };\n }\n\n return tuple;\n },\n\n async *list(_config: RunnableConfig, _options?: CheckpointListOptions) {\n // Minimal implementation: list is not needed for core runtime behavior today.\n // If needed later (studio/time-travel), implement scanning by prefix.\n },\n\n async put(\n config: RunnableConfig,\n checkpoint: Checkpoint,\n metadata: CheckpointMetadata,\n _newVersions: Record<string, number | string>,\n ): Promise<RunnableConfig> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs =\n (config.configurable?.checkpoint_ns as string | undefined) ?? \"\";\n if (!threadId) {\n throw new Error(\n 'Failed to put checkpoint: missing \"thread_id\" in config.configurable.',\n );\n }\n\n const prevId = await store.get(latestKey(threadId, checkpointNs));\n\n const prepared = copyCheckpoint(checkpoint as any);\n const [[, chkBytes], [, metaBytes]] = await Promise.all([\n serde.dumpsTyped(prepared),\n serde.dumpsTyped(metadata),\n ]);\n\n const checkpointId = checkpoint.id;\n const key = checkpointKey(threadId, checkpointNs, checkpointId);\n const stored: StoredCheckpoint = {\n checkpoint: b64FromBytes(chkBytes),\n metadata: b64FromBytes(metaBytes),\n parentCheckpointId: config.configurable?.checkpoint_id as\n | string\n | undefined,\n };\n\n await store.set(key, JSON.stringify(stored), ttlMs);\n await store.set(latestKey(threadId, checkpointNs), checkpointId, ttlMs);\n\n // Keep storage bounded: delete the previous checkpoint and its writes.\n if (prevId && prevId !== checkpointId) {\n await store.del(checkpointKey(threadId, checkpointNs, prevId));\n await store.del(writesKey(threadId, checkpointNs, prevId));\n }\n\n return {\n configurable: {\n thread_id: threadId,\n checkpoint_ns: checkpointNs,\n checkpoint_id: checkpointId,\n },\n };\n },\n\n async putWrites(\n config: RunnableConfig,\n writes: PendingWrite[],\n taskId: string,\n ): Promise<void> {\n const threadId = config.configurable?.thread_id as string | undefined;\n const checkpointNs = config.configurable?.checkpoint_ns as\n | string\n | undefined;\n const checkpointId = config.configurable?.checkpoint_id as\n | string\n | undefined;\n if (!threadId) {\n throw new Error(\n 'Failed to put writes: missing \"thread_id\" in config.configurable.',\n );\n }\n if (!checkpointId) {\n throw new Error(\n 'Failed to put writes: missing \"checkpoint_id\" in config.configurable.',\n );\n }\n\n const outer = writesKey(threadId, checkpointNs ?? \"\", checkpointId);\n await store.expire(outer, ttlMs);\n\n await Promise.all(\n writes.map(async ([channel, value], idx) => {\n const [, vBytes] = await serde.dumpsTyped(value as any);\n const mappedIdx = WRITES_IDX_MAP[channel] ?? idx;\n const innerKeyStr = `${taskId},${mappedIdx}`;\n const payload: StoredWrite = {\n taskId,\n channel,\n value: b64FromBytes(vBytes),\n };\n const serialized = JSON.stringify(payload);\n if (mappedIdx >= 0) {\n await store.hsetnx(outer, innerKeyStr, serialized);\n } else {\n await store.hset(outer, innerKeyStr, serialized);\n }\n }),\n );\n },\n\n async deleteThread(threadId: string): Promise<void> {\n const chkKeys = await store.scanKeys(`${prefix}chk:${threadId}:`);\n const wrKeys = await store.scanKeys(`${prefix}wr:${threadId}:`);\n const latestKeys = await store.scanKeys(`${prefix}latest:${threadId}:`);\n await store.delRaw([...chkKeys, ...wrKeys, ...latestKeys]);\n },\n };\n\n return saver as RedisCheckpointSaver;\n}\n","import { connect as netConnect, type Socket } from \"node:net\";\nimport { type TLSSocket, connect as tlsConnect } from \"node:tls\";\n\nexport type RedisReply =\n | string\n | number\n | null\n | RedisReply[]\n | { type: \"error\"; message: string };\n\nexport type RedisClientOptions = {\n url: string;\n connectTimeoutMs?: number;\n};\n\nconst encodeBulk = (s: string) => {\n const b = Buffer.from(s, \"utf8\");\n return Buffer.concat([\n Buffer.from(`$${b.length}\\r\\n`),\n b,\n Buffer.from(\"\\r\\n\"),\n ]);\n};\n\nconst encodeCommand = (cmd: string, args: string[]) => {\n const parts = [cmd, ...args];\n const bufs: Buffer[] = [Buffer.from(`*${parts.length}\\r\\n`)];\n for (const p of parts) bufs.push(encodeBulk(p));\n return Buffer.concat(bufs);\n};\n\nfunction readLine(buf: Buffer, start: number) {\n const idx = buf.indexOf(\"\\r\\n\", start);\n if (idx === -1) return null;\n return { line: buf.slice(start, idx).toString(\"utf8\"), next: idx + 2 };\n}\n\nfunction parseReply(\n buf: Buffer,\n start: number,\n): { value: RedisReply; next: number } | null {\n if (start >= buf.length) return null;\n const byte = buf[start];\n if (byte === undefined) return null;\n const prefix = String.fromCharCode(byte);\n if (prefix === \"+\" || prefix === \"-\" || prefix === \":\") {\n const line = readLine(buf, start + 1);\n if (!line) return null;\n if (prefix === \"+\") return { value: line.line, next: line.next };\n if (prefix === \":\")\n return { value: Number.parseInt(line.line, 10), next: line.next };\n return { value: { type: \"error\", message: line.line }, next: line.next };\n }\n\n if (prefix === \"$\") {\n const line = readLine(buf, start + 1);\n if (!line) return null;\n const len = Number.parseInt(line.line, 10);\n if (len === -1) return { value: null, next: line.next };\n const end = line.next + len;\n if (end + 2 > buf.length) return null;\n const data = buf.slice(line.next, end).toString(\"utf8\");\n return { value: data, next: end + 2 };\n }\n\n if (prefix === \"*\") {\n const line = readLine(buf, start + 1);\n if (!line) return null;\n const count = Number.parseInt(line.line, 10);\n if (count === -1) return { value: null, next: line.next };\n const items: RedisReply[] = [];\n let cursor = line.next;\n for (let i = 0; i < count; i++) {\n const parsed = parseReply(buf, cursor);\n if (!parsed) return null;\n items.push(parsed.value);\n cursor = parsed.next;\n }\n return { value: items, next: cursor };\n }\n\n return {\n value: { type: \"error\", message: `Unknown RESP prefix: ${prefix}` },\n next: buf.length,\n };\n}\n\nexport type RedisClient = {\n command: (cmd: string, args?: string[]) => Promise<RedisReply>;\n};\n\nexport function createRedisClient(options: RedisClientOptions): RedisClient {\n const resolvedOptions: Required<\n Pick<RedisClientOptions, \"connectTimeoutMs\">\n > &\n Omit<RedisClientOptions, \"connectTimeoutMs\"> = {\n connectTimeoutMs: options.connectTimeoutMs ?? 5_000,\n url: options.url,\n };\n\n let socket: Socket | TLSSocket | null = null;\n let buffer = Buffer.alloc(0);\n const inflight: Array<{\n resolve: (v: RedisReply) => void;\n reject: (e: unknown) => void;\n }> = [];\n\n let connecting: Promise<void> | null = null;\n let ready = false;\n\n const drainReplies = () => {\n while (inflight.length) {\n const parsed = parseReply(buffer, 0);\n if (!parsed) return;\n const waiter = inflight.shift()!;\n buffer = buffer.slice(parsed.next);\n waiter.resolve(parsed.value);\n }\n };\n\n const send = (cmd: string, args: string[] = []): Promise<RedisReply> => {\n if (!socket) return Promise.reject(new Error(\"Redis socket not available\"));\n const payload = encodeCommand(cmd, args);\n return new Promise<RedisReply>((resolve, reject) => {\n inflight.push({ resolve, reject });\n socket!.write(payload);\n });\n };\n\n const ensureConnected = async () => {\n if (ready) return;\n if (connecting) return connecting;\n\n connecting = (async () => {\n const u = new URL(resolvedOptions.url);\n const isTls = u.protocol === \"rediss:\";\n const host = u.hostname || \"127.0.0.1\";\n const port = u.port ? Number(u.port) : isTls ? 6380 : 6379;\n const password = u.password ? decodeURIComponent(u.password) : \"\";\n const db =\n u.pathname && u.pathname !== \"/\" ? Number(u.pathname.slice(1)) : 0;\n\n const s = isTls\n ? tlsConnect({ host, port, servername: host })\n : netConnect({ host, port });\n socket = s;\n\n s.setNoDelay(true);\n s.setKeepAlive(true);\n\n s.on(\"data\", (chunk) => {\n buffer = Buffer.concat([buffer, chunk]);\n drainReplies();\n });\n\n s.on(\"error\", (err) => {\n ready = false;\n while (inflight.length) inflight.shift()!.reject(err);\n });\n\n s.on(\"close\", () => {\n ready = false;\n while (inflight.length)\n inflight.shift()!.reject(new Error(\"Redis socket closed\"));\n });\n\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(\"Redis connect timeout\")),\n resolvedOptions.connectTimeoutMs,\n );\n\n const onConnect = () => {\n clearTimeout(timer);\n resolve();\n };\n\n // net: \"connect\", tls: \"secureConnect\" (TLSSocket can also emit \"connect\")\n s.once(\"connect\", onConnect);\n (s as any).once?.(\"secureConnect\", onConnect);\n s.once(\"error\", (e) => {\n clearTimeout(timer);\n reject(e);\n });\n });\n\n if (password) {\n const r = await send(\"AUTH\", [password]);\n if (typeof r === \"object\" && r && (r as any).type === \"error\") {\n throw new Error(`Redis AUTH failed: ${(r as any).message}`);\n }\n }\n\n if (db && Number.isFinite(db) && db > 0) {\n const r = await send(\"SELECT\", [String(db)]);\n if (typeof r === \"object\" && r && (r as any).type === \"error\") {\n throw new Error(`Redis SELECT failed: ${(r as any).message}`);\n }\n }\n\n ready = true;\n })();\n\n try {\n await connecting;\n } finally {\n connecting = null;\n }\n };\n\n return {\n async command(cmd: string, args: string[] = []) {\n await ensureConnected();\n return send(cmd, args);\n },\n };\n}\n","import { createRedisClient, type RedisClient } from \"./redis-client\";\n\nexport type RedisFrameworkStoreOptions = {\n url: string;\n prefix?: string;\n};\n\nexport type FrameworkTtl = {\n ttlMs: number;\n};\n\nexport type RedisFrameworkStore = {\n get: (key: string) => Promise<string | null>;\n set: (key: string, value: string, ttlMs: number) => Promise<void>;\n del: (key: string) => Promise<void>;\n hset: (key: string, field: string, value: string) => Promise<void>;\n hsetnx: (key: string, field: string, value: string) => Promise<number>;\n hgetall: (key: string) => Promise<Record<string, string>>;\n expire: (key: string, ttlMs: number) => Promise<void>;\n scanKeys: (prefix: string) => Promise<string[]>;\n delRaw: (keys: string[]) => Promise<void>;\n};\n\ntype RedisErrorReply = { type: \"error\"; message: string };\nconst isRedisError = (r: unknown): r is RedisErrorReply =>\n Boolean(r) && typeof r === \"object\" && (r as any).type === \"error\";\n\nexport function createRedisFrameworkStore(\n options: RedisFrameworkStoreOptions,\n): RedisFrameworkStore {\n const client: RedisClient = createRedisClient({ url: options.url });\n const prefix = options.prefix ?? \"kortyx:fw:\";\n\n const k = (key: string) => `${prefix}${key}`;\n\n return {\n async get(key: string): Promise<string | null> {\n const r = await client.command(\"GET\", [k(key)]);\n if (r === null) return null;\n if (typeof r === \"string\") return r;\n if (isRedisError(r)) {\n throw new Error(`Redis GET error: ${r.message}`);\n }\n return null;\n },\n\n async set(key: string, value: string, ttlMs: number): Promise<void> {\n const args = [k(key), value, \"PX\", String(Math.max(1, ttlMs))];\n const r = await client.command(\"SET\", args);\n if (isRedisError(r)) {\n throw new Error(`Redis SET error: ${r.message}`);\n }\n },\n\n async del(key: string): Promise<void> {\n const r = await client.command(\"DEL\", [k(key)]);\n if (isRedisError(r)) {\n throw new Error(`Redis DEL error: ${r.message}`);\n }\n },\n\n async hset(key: string, field: string, value: string): Promise<void> {\n const r = await client.command(\"HSET\", [k(key), field, value]);\n if (isRedisError(r)) {\n throw new Error(`Redis HSET error: ${r.message}`);\n }\n },\n\n async hsetnx(key: string, field: string, value: string): Promise<number> {\n const r = await client.command(\"HSETNX\", [k(key), field, value]);\n if (isRedisError(r)) {\n throw new Error(`Redis HSETNX error: ${r.message}`);\n }\n return typeof r === \"number\" ? r : 0;\n },\n\n async hgetall(key: string): Promise<Record<string, string>> {\n const r = await client.command(\"HGETALL\", [k(key)]);\n if (isRedisError(r)) {\n throw new Error(`Redis HGETALL error: ${r.message}`);\n }\n if (!Array.isArray(r)) return {};\n const out: Record<string, string> = {};\n for (let i = 0; i < r.length; i += 2) {\n const kk = r[i];\n const v = r[i + 1];\n if (typeof kk === \"string\" && typeof v === \"string\") out[kk] = v;\n }\n return out;\n },\n\n async expire(key: string, ttlMs: number): Promise<void> {\n const r = await client.command(\"PEXPIRE\", [\n k(key),\n String(Math.max(1, ttlMs)),\n ]);\n if (isRedisError(r)) {\n throw new Error(`Redis PEXPIRE error: ${r.message}`);\n }\n },\n\n async scanKeys(prefixKey: string): Promise<string[]> {\n const fullPrefix = k(prefixKey);\n let cursor = \"0\";\n const keys: string[] = [];\n do {\n const r = await client.command(\"SCAN\", [\n cursor,\n \"MATCH\",\n `${fullPrefix}*`,\n \"COUNT\",\n \"200\",\n ]);\n if (!Array.isArray(r) || r.length < 2) break;\n cursor = typeof r[0] === \"string\" ? r[0] : \"0\";\n const batch = r[1];\n if (Array.isArray(batch)) {\n for (const key of batch) {\n if (typeof key === \"string\") keys.push(key);\n }\n }\n } while (cursor !== \"0\");\n return keys;\n },\n\n async delRaw(keys: string[]): Promise<void> {\n if (keys.length === 0) return;\n const r = await client.command(\"DEL\", keys);\n if (isRedisError(r)) {\n throw new Error(`Redis DEL error: ${r.message}`);\n }\n },\n };\n}\n","import type { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { createInMemoryCheckpointSaver } from \"./in-memory-checkpointer\";\nimport {\n createInMemoryPendingRequestStore,\n type PendingRequestStore,\n} from \"./pending-requests\";\nimport { createRedisPendingRequestStore } from \"./redis/pending-request-store\";\nimport { createRedisCheckpointSaver } from \"./redis/redis-checkpointer\";\nimport { createRedisFrameworkStore } from \"./redis/redis-store\";\n\nexport type FrameworkAdapter = {\n kind: \"memory\" | \"redis\";\n pendingRequests: PendingRequestStore;\n checkpointer: BaseCheckpointSaver;\n ttlMs: number;\n /**\n * Best-effort cleanup for ephemeral framework state for a single run.\n * Called when a workflow completes without pausing for an interrupt.\n */\n cleanupRun?: (runId: string, namespaces: string[]) => Promise<void>;\n};\n\nexport type CreateInMemoryFrameworkAdapterOptions = {\n ttlMs?: number;\n};\n\nexport function createInMemoryFrameworkAdapter(\n options?: CreateInMemoryFrameworkAdapterOptions,\n): FrameworkAdapter {\n const ttlMs = options?.ttlMs ?? 15 * 60 * 1000;\n const checkpointer = createInMemoryCheckpointSaver();\n return {\n kind: \"memory\",\n ttlMs,\n pendingRequests: createInMemoryPendingRequestStore(),\n checkpointer,\n cleanupRun: async (runId: string) => {\n try {\n await checkpointer.deleteThread(runId);\n } catch {\n // best-effort cleanup only\n }\n },\n };\n}\n\nexport type CreateRedisFrameworkAdapterOptions = {\n url: string;\n ttlMs?: number;\n prefix?: string;\n};\n\nexport function createRedisFrameworkAdapter(\n options: CreateRedisFrameworkAdapterOptions,\n): FrameworkAdapter {\n const ttlMs = options.ttlMs ?? 15 * 60 * 1000;\n const store = createRedisFrameworkStore({\n url: options.url,\n prefix: options.prefix ?? \"kortyx:fw:\",\n });\n const cpPrefix = \"kortyx:cp:\";\n return {\n kind: \"redis\",\n ttlMs,\n pendingRequests: createRedisPendingRequestStore({\n store,\n prefix: \"kortyx:pending:\",\n }),\n checkpointer: createRedisCheckpointSaver({\n store,\n ttlMs,\n prefix: cpPrefix,\n }),\n cleanupRun: async (runId: string, namespaces: string[]) => {\n // Avoid SCAN-based deletes in hot paths. We can deterministically delete\n // keys by reading the per-namespace latest pointer.\n const nsList = namespaces.length > 0 ? namespaces : [\"\"];\n await Promise.all(\n nsList.map(async (checkpointNs) => {\n const ns = String(checkpointNs ?? \"\");\n const latestKey = `${cpPrefix}latest:${runId}:${ns}`;\n const checkpointId = (await store.get(latestKey)) ?? \"\";\n if (!checkpointId) return;\n await Promise.all([\n store.del(`${cpPrefix}chk:${runId}:${ns}:${checkpointId}`),\n store.del(`${cpPrefix}wr:${runId}:${ns}:${checkpointId}`),\n store.del(latestKey),\n ]);\n }),\n );\n },\n };\n}\n\nexport function createFrameworkAdapterFromEnv(\n env: Record<string, string | undefined> = process.env,\n): FrameworkAdapter {\n const url =\n env.KORTYX_REDIS_URL ||\n env.REDIS_URL ||\n env.KORTYX_FRAMEWORK_REDIS_URL ||\n \"\";\n const ttlMsRaw = env.KORTYX_FRAMEWORK_TTL_MS || env.KORTYX_TTL_MS || \"\";\n const ttlMs = ttlMsRaw ? Number(ttlMsRaw) : undefined;\n\n if (url)\n return createRedisFrameworkAdapter({ url, ...(ttlMs ? { ttlMs } : {}) });\n\n // Dev fallback: in-memory. Not production-safe for resume across processes.\n return createInMemoryFrameworkAdapter({ ...(ttlMs ? { ttlMs } : {}) });\n}\n","import type {\n GraphState,\n NodeConfig,\n NodeContext,\n NodeResult,\n WorkflowDefinition,\n} from \"@kortyx/core\";\nimport { runWithHookContext } from \"@kortyx/hooks\";\nimport { runReasonEngine } from \"@kortyx/hooks/internal\";\nimport type { MemoryAdapter } from \"@kortyx/memory\";\nimport type { GetProviderFn } from \"@kortyx/providers\";\nimport { deepMergeWithArrayOverwrite } from \"@kortyx/utils\";\nimport { Annotation, interrupt, StateGraph } from \"@langchain/langgraph\";\nimport type { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { getCheckpointer } from \"../checkpointer\";\nimport { resolveNodeHandler } from \"../node-loader\";\n\nexport interface ExecutionRuntimeConfig {\n emit?: (event: string, payload: unknown) => void;\n onCheckpoint?: (args: { nodeId: string; state: GraphState }) => void;\n memoryAdapter?: MemoryAdapter;\n checkpointer?: BaseCheckpointSaver;\n /**\n * Provider factory used by ctx.speak to obtain a streaming model.\n * Use @kortyx/providers or implement your own GetProviderFn.\n */\n getProvider?: GetProviderFn;\n [key: string]: unknown;\n}\n\nexport async function createExecutionGraph(\n workflow: WorkflowDefinition,\n config: ExecutionRuntimeConfig,\n) {\n const StateAnnotation = Annotation.Root({\n input: Annotation<unknown>,\n output: Annotation<string>,\n lastNode: Annotation<string>,\n lastCondition: Annotation<string>,\n lastIntent: Annotation<string>,\n memory: Annotation<Record<string, unknown>>({\n reducer: (l, r) => deepMergeWithArrayOverwrite(l ?? {}, r ?? {}),\n default: () => ({}),\n }),\n config: Annotation<unknown>,\n transitionTo: Annotation<string | null>,\n data: Annotation<Record<string, unknown>>({\n reducer: (l, r) => deepMergeWithArrayOverwrite(l ?? {}, r ?? {}),\n default: () => ({}),\n }),\n conversationHistory: Annotation<\n Array<{ node: string; message: string; timestamp: string }>\n >({\n reducer: (l, r) => [...(l ?? []), ...(r ?? [])],\n default: () => [],\n }),\n awaitingHumanInput: Annotation<boolean>,\n });\n\n const builder = new StateGraph(StateAnnotation);\n const edgeApi = builder as unknown as {\n addEdge: (from: string, to: string) => void;\n addConditionalEdges: (\n from: string,\n fn: (s: GraphState) => string,\n mapping: Record<string, string>,\n ) => void;\n compile: () => any;\n };\n const workflowName = workflow.id;\n\n // Ensure an emit function exists so ctx.emit can always call without optional chaining\n type WithEmit = ExecutionRuntimeConfig & {\n emit: (event: string, payload: unknown) => void;\n };\n const runtimeConfig = config as WithEmit;\n if (!runtimeConfig.emit) {\n runtimeConfig.emit = () => {};\n }\n\n const isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\n const toRecordInput = (value: unknown): Record<string, unknown> => {\n if (isRecord(value)) return value;\n if (value === undefined) return {};\n return { rawInput: value };\n };\n\n const buildNodeConfig = (\n params: Record<string, unknown> | undefined,\n nodeBehavior: Record<string, unknown> | undefined,\n ): NodeConfig => {\n const model = isRecord(params?.model) ? (params!.model as any) : undefined;\n const tool = isRecord(params?.tool) ? (params!.tool as any) : undefined;\n const behaviorFromParams = isRecord(params?.behavior)\n ? (params!.behavior as any)\n : undefined;\n const behavior = {\n ...(behaviorFromParams ?? {}),\n ...(nodeBehavior ?? {}),\n } as any;\n const options = params ?? undefined;\n return {\n ...(model ? { model } : {}),\n ...(tool ? { tool } : {}),\n ...(Object.keys(behavior).length > 0 ? { behavior } : {}),\n ...(options ? { options } : {}),\n } as NodeConfig;\n };\n\n for (const [nodeId, nodeDef] of Object.entries(workflow.nodes ?? {})) {\n const resolvedRun = await resolveNodeHandler({\n run: nodeDef.run,\n workflow,\n });\n const nodeParams = (nodeDef.params ?? undefined) as\n | Record<string, unknown>\n | undefined;\n const nodeConfig: NodeConfig = buildNodeConfig(\n nodeParams,\n (nodeDef.behavior ?? undefined) as unknown as\n | Record<string, unknown>\n | undefined,\n );\n const behavior = nodeConfig.behavior ?? {};\n\n builder.addNode(nodeId, async (state: GraphState) => {\n const ctx = {\n graph: { name: workflowName, node: nodeId },\n config: nodeConfig,\n emit: (event: string, payload: unknown) => {\n runtimeConfig.emit(event, payload);\n },\n error: (message: string) => {\n runtimeConfig.emit(\"error\", {\n node: nodeId,\n message,\n });\n },\n awaitInterrupt: (interruptConfig: any) => {\n const { kind, question } = interruptConfig;\n const isMulti =\n kind === \"multi-choice\" ||\n (interruptConfig.kind !== \"text\" &&\n interruptConfig.multiple === true);\n const payload: any = {\n kind,\n multiple: isMulti,\n question,\n ...(interruptConfig.kind !== \"text\"\n ? { options: interruptConfig.options }\n : {}),\n ...(typeof interruptConfig.id === \"string\" &&\n interruptConfig.id.length > 0\n ? { id: interruptConfig.id }\n : {}),\n ...(typeof interruptConfig.schemaId === \"string\" &&\n interruptConfig.schemaId.length > 0\n ? { schemaId: interruptConfig.schemaId }\n : {}),\n ...(typeof interruptConfig.schemaVersion === \"string\" &&\n interruptConfig.schemaVersion.length > 0\n ? { schemaVersion: interruptConfig.schemaVersion }\n : {}),\n ...(interruptConfig.meta &&\n typeof interruptConfig.meta === \"object\" &&\n !Array.isArray(interruptConfig.meta)\n ? { meta: interruptConfig.meta }\n : {}),\n };\n runtimeConfig.emit(\"interrupt\", {\n node: nodeId,\n workflow: workflowName,\n input: payload,\n });\n const resumed = interrupt(payload) as unknown;\n if (isMulti) {\n if (Array.isArray(resumed)) {\n return (resumed as any[])\n .map((v) =>\n typeof v === \"string\"\n ? v\n : v && typeof (v as any).id === \"string\"\n ? (v as any).id\n : \"\",\n )\n .filter(Boolean) as string[];\n }\n if (typeof resumed === \"string\") return [resumed];\n return [];\n }\n if (typeof resumed === \"string\") return resumed;\n if (resumed && typeof (resumed as any).id === \"string\")\n return String((resumed as any).id);\n return \"\";\n },\n speak: async (\n args: Parameters<NodeContext[\"speak\"]>[0],\n ): Promise<string> => {\n const providerId =\n args.model?.provider ?? nodeConfig.model?.provider ?? \"google\";\n const modelName =\n args.model?.name ?? nodeConfig.model?.name ?? \"gemini-2.5-flash\";\n const temperature =\n args.model?.temperature ?? nodeConfig.model?.temperature ?? 0.3;\n\n const getProvider = runtimeConfig.getProvider;\n if (!getProvider) {\n throw new Error(\n \"Runtime config is missing getProvider; wire a provider factory into @kortyx/runtime.\",\n );\n }\n\n const result = await runReasonEngine({\n getProvider,\n model: {\n providerId,\n modelId: modelName,\n },\n input: args.user ?? \"\",\n system: args.system,\n temperature,\n stream: true,\n emit: true,\n nodeId,\n emitEvent: ctx.emit,\n });\n return result.text;\n },\n } satisfies NodeContext;\n\n if (behavior.checkpoint && config?.onCheckpoint) {\n config.onCheckpoint({ nodeId, state });\n }\n\n const maxAttempts = behavior.retry?.maxAttempts ?? 1;\n let attempt = 0;\n let nodeResult: NodeResult | undefined;\n let hookMemoryUpdates: Record<string, unknown> | null = null;\n let retryHookMemory: Record<string, unknown> | null = null;\n\n while (attempt < maxAttempts) {\n try {\n attempt++;\n const attemptState =\n retryHookMemory && typeof retryHookMemory === \"object\"\n ? ({\n ...state,\n memory: deepMergeWithArrayOverwrite(\n (state.memory ?? {}) as Record<string, unknown>,\n retryHookMemory,\n ),\n } as GraphState)\n : state;\n const hookContext = {\n node: ctx,\n state: attemptState,\n ...(runtimeConfig.getProvider\n ? { getProvider: runtimeConfig.getProvider }\n : {}),\n ...(runtimeConfig.memoryAdapter\n ? { memoryAdapter: runtimeConfig.memoryAdapter }\n : {}),\n };\n const hookRun = await runWithHookContext(hookContext, async () =>\n resolvedRun({\n input: state.input,\n params: (nodeParams ?? {}) as Record<string, unknown>,\n }),\n );\n nodeResult = hookRun.result as NodeResult;\n hookMemoryUpdates = hookRun.memoryUpdates;\n break;\n } catch (err) {\n const patch = (err as any)?.__kortyxMemoryUpdates as\n | Record<string, unknown>\n | null\n | undefined;\n if (patch && typeof patch === \"object\") {\n // Preserve hook memory even when execution pauses via interrupt.\n // Without this merge, checkpointed hook state (e.g. useReason drafts)\n // can be lost before resume.\n state.memory = deepMergeWithArrayOverwrite(\n (state.memory ?? {}) as Record<string, unknown>,\n patch,\n );\n retryHookMemory = deepMergeWithArrayOverwrite(\n (retryHookMemory ?? {}) as Record<string, unknown>,\n patch,\n );\n }\n const hasMore = attempt < maxAttempts;\n const delayMs = behavior.retry?.delayMs ?? 0;\n if (hasMore && delayMs > 0) {\n await new Promise((r) => setTimeout(r, delayMs));\n continue;\n }\n if (!hasMore) throw err;\n }\n }\n\n const res: NodeResult = (nodeResult ?? {}) as NodeResult;\n if (hookMemoryUpdates) {\n res.infra = {\n ...(res.infra ?? {}),\n memory: deepMergeWithArrayOverwrite(\n ((res.infra?.memory ?? {}) as Record<string, unknown>) || {},\n hookMemoryUpdates,\n ),\n };\n }\n const uiMessage = res.ui?.message;\n const shouldRespond =\n typeof uiMessage === \"string\" && uiMessage.trim().length > 0;\n\n if (shouldRespond) {\n ctx.emit(\"message\", { node: nodeId, content: uiMessage });\n }\n\n if (res.transitionTo) {\n ctx.emit(\"transition\", {\n transitionTo: res.transitionTo,\n payload: res.data ?? {},\n });\n }\n\n const updates: Record<string, unknown> = {};\n\n if (typeof res.condition === \"string\")\n updates.lastCondition = res.condition;\n if (typeof res.intent === \"string\") updates.lastIntent = res.intent;\n\n if (res.data && typeof res.data === \"object\") {\n // Treat node `data` as the flowing payload between nodes.\n // Accumulate by merging into the previous input (if any).\n updates.input = deepMergeWithArrayOverwrite(\n toRecordInput(state.input),\n res.data as Record<string, unknown>,\n );\n updates.data = deepMergeWithArrayOverwrite(\n (state.data ?? {}) as Record<string, unknown>,\n res.data as Record<string, unknown>,\n );\n }\n if (res.infra?.memory && typeof res.infra.memory === \"object\") {\n updates.memory = deepMergeWithArrayOverwrite(\n (state.memory ?? {}) as Record<string, unknown>,\n res.infra.memory as Record<string, unknown>,\n );\n }\n\n if (res.ui) {\n updates.ui = {\n message:\n typeof res.ui.message === \"string\"\n ? res.ui.message\n : (state.ui?.message ?? \"\"),\n structured: deepMergeWithArrayOverwrite(\n (state.ui?.structured ?? {}) as Record<string, unknown>,\n (res.ui.structured ?? {}) as Record<string, unknown>,\n ),\n };\n }\n\n if (shouldRespond && uiMessage) {\n updates.conversationHistory = [\n ...(state.conversationHistory ?? []),\n {\n node: nodeId,\n message: uiMessage,\n timestamp: new Date().toISOString(),\n },\n ];\n }\n\n if (res.ui?.structured) {\n const payload = res.ui.structured as Record<string, unknown>;\n const inferredType =\n payload && typeof payload === \"object\" && \"jobs\" in payload\n ? \"jobs\"\n : typeof (payload as { summary?: unknown }).summary === \"string\" ||\n (payload as { topJobs?: unknown }).topJobs\n ? \"summary\"\n : \"generic\";\n ctx.emit(\"structured_data\", {\n node: nodeId,\n dataType: inferredType,\n data: payload,\n });\n }\n\n return updates as any;\n });\n }\n\n type EdgeTriple = readonly [string, string, { when?: string }?];\n const condGroups: Record<string, Array<{ when: string; to: string }>> = {};\n const plainEdges: Array<[string, string]> = [];\n\n for (const edge of workflow.edges as unknown as EdgeTriple[]) {\n const [from, to, condition] = edge as unknown as EdgeTriple;\n if (condition && typeof condition.when === \"string\" && condition.when) {\n if (!condGroups[from]) condGroups[from] = [];\n condGroups[from].push({ when: condition.when, to });\n } else {\n plainEdges.push([from, to]);\n }\n }\n\n for (const [from, to] of plainEdges) {\n edgeApi.addEdge(from, to);\n }\n\n for (const [from, rules] of Object.entries(condGroups)) {\n const mapping: Record<string, string> = Object.fromEntries(\n rules.map((r) => [r.when, r.to]),\n );\n const fallbackKey = `__default__:${from}`;\n mapping[fallbackKey] = \"__end__\";\n edgeApi.addConditionalEdges(\n from,\n (s: GraphState) => {\n const trigger = s.lastCondition ?? s.lastIntent;\n if (trigger && Object.hasOwn(mapping, trigger as string)) {\n return trigger as string;\n }\n return fallbackKey;\n },\n mapping,\n );\n }\n\n const sessionId = (config as any)?.session?.id ?? \"__default__\";\n const checkpointer = config.checkpointer ?? getCheckpointer(sessionId);\n const graph = (builder as any).compile({ checkpointer });\n\n interface GraphExtensions {\n name: string;\n config: ExecutionRuntimeConfig;\n resume(state: GraphState, input: unknown): Promise<GraphState>;\n timeTravelTo(state: GraphState, checkpointId: string): Promise<GraphState>;\n }\n type RuntimeGraph = typeof graph & GraphExtensions;\n\n const runtimeGraph = graph as RuntimeGraph;\n runtimeGraph.name = workflow.id;\n runtimeGraph.config = config;\n\n runtimeGraph.resume = async (state: GraphState, input: unknown) => {\n const resumed = { ...state, input, awaitingHumanInput: false };\n return graph.invoke(resumed as any) as unknown as GraphState;\n };\n\n runtimeGraph.timeTravelTo = async (\n state: GraphState,\n checkpointId: string,\n ) => {\n const checkpoints = (\n state.memory as { checkpoints?: Record<string, { snapshot: unknown }> }\n )?.checkpoints;\n const snapshot = checkpoints?.[checkpointId];\n if (!snapshot) throw new Error(`Checkpoint '${checkpointId}' not found`);\n return graph.invoke(\n snapshot.snapshot as unknown as Partial<\n (typeof StateAnnotation)[\"State\"]\n >,\n ) as unknown as GraphState;\n };\n\n return runtimeGraph;\n}\n","import { dirname, isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { NodeFn, WorkflowDefinition } from \"@kortyx/core\";\nimport { resolveNode } from \"./node-registry\";\n\ntype LoadedNodeModule = Record<string, unknown>;\n\nconst dynamicImport = new Function(\n \"specifier\",\n // Avoid bundler static analysis of `import(...)` (e.g. Next.js/Turbopack).\n // This is only used on the server.\n \"return import(specifier)\",\n) as (specifier: string) => Promise<LoadedNodeModule>;\n\nfunction looksLikePath(specifier: string) {\n if (specifier.startsWith(\"file:\")) return true;\n if (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) return true;\n if (specifier.startsWith(\"/\")) return true;\n return specifier.includes(\"/\");\n}\n\nfunction getWorkflowBaseDir(\n workflow: WorkflowDefinition | undefined,\n cwd: string,\n): string {\n const meta = workflow?.metadata as Record<string, unknown> | undefined;\n const filePath = meta?.__filePath;\n if (typeof filePath === \"string\" && filePath.length > 0) {\n return dirname(filePath);\n }\n return cwd;\n}\n\nfunction pickNodeExport(mod: LoadedNodeModule, exportName?: string): NodeFn {\n if (exportName) {\n const candidate = mod[exportName];\n if (typeof candidate === \"function\") return candidate as NodeFn;\n throw new Error(`Node export \"${exportName}\" not found or not a function.`);\n }\n\n const defaultExport = mod.default;\n if (typeof defaultExport === \"function\") return defaultExport as NodeFn;\n\n const fnExports = Object.entries(mod).filter(\n ([, v]) => typeof v === \"function\",\n );\n if (fnExports.length === 1) return fnExports[0]![1] as NodeFn;\n\n const names = fnExports.map(([k]) => k).sort();\n throw new Error(\n `Node module must export a default function or exactly one named function (found: ${\n names.join(\", \") || \"none\"\n }).`,\n );\n}\n\nexport async function resolveNodeHandler(args: {\n run: string | NodeFn;\n workflow?: WorkflowDefinition;\n cwd?: string;\n}): Promise<NodeFn> {\n const { run, workflow } = args;\n const cwd = args.cwd ?? process.cwd();\n\n if (typeof run === \"function\") return run;\n\n // New DX: YAML/JSON specify module path (optionally with #exportName)\n if (looksLikePath(run)) {\n const [moduleRef, exportName] = run.split(\"#\", 2) as [\n string,\n string | undefined,\n ];\n const baseDir = getWorkflowBaseDir(workflow, cwd);\n\n const specifier = moduleRef.startsWith(\"file:\")\n ? moduleRef\n : isAbsolute(moduleRef)\n ? pathToFileURL(moduleRef).href\n : pathToFileURL(resolve(baseDir, moduleRef)).href;\n\n const mod = await dynamicImport(specifier);\n return pickNodeExport(mod, exportName);\n }\n\n // Back-compat: symbolic node registry name\n return resolveNode(run);\n}\n","import type { NodeFn } from \"@kortyx/core\";\n\nconst registry = new Map<string, NodeFn>();\n\nexport function registerNode(id: string, fn: NodeFn): void {\n registry.set(id, fn);\n}\n\nexport function getRegisteredNode(id: string): NodeFn | null {\n return registry.get(id) ?? null;\n}\n\nexport function listRegisteredNodes(): string[] {\n return [...registry.keys()].sort();\n}\n\nexport function clearRegisteredNodes(): void {\n registry.clear();\n}\n\nexport function resolveNode(id: string): NodeFn {\n const fn = registry.get(id);\n if (!fn) {\n throw new Error(\n `Node '${id}' is not registered. Call registerNode('${id}', fn) before running workflows that reference it.`,\n );\n }\n return fn;\n}\n","import { v7 as uuid } from \"uuid\";\n\nexport function makeResumeToken(): string {\n return uuid();\n}\n\nexport function makeRequestId(prefix = \"req\"): string {\n return `${prefix}-${uuid()}`;\n}\n","import type { WorkflowDefinition } from \"@kortyx/core\";\nimport { loadWorkflow } from \"@kortyx/core\";\nimport { readdir, readFile } from \"fs/promises\";\nimport { join } from \"path\";\nimport type { WorkflowRegistry } from \"./interface\";\n\nexport interface FileWorkflowRegistryOptions {\n workflowsDir: string;\n fallbackId?: string;\n cache?: boolean;\n extensions?: string[];\n}\n\ntype AnyWorkflow = WorkflowDefinition;\n\nconst DEFAULT_EXTENSIONS = [\n \".workflow.ts\",\n \".workflow.mts\",\n \".workflow.js\",\n \".workflow.mjs\",\n \".workflow.json\",\n \".workflow.yml\",\n \".workflow.yaml\",\n];\n\nfunction isWorkflowFile(name: string, extensions: string[]) {\n return extensions.some((ext) => name.endsWith(ext));\n}\n\nfunction isDeclarativeWorkflowFile(name: string) {\n return (\n name.endsWith(\".workflow.json\") ||\n name.endsWith(\".workflow.yml\") ||\n name.endsWith(\".workflow.yaml\")\n );\n}\n\nexport function createFileWorkflowRegistry(\n options: FileWorkflowRegistryOptions,\n): WorkflowRegistry {\n const workflowsDir = options.workflowsDir;\n const fallbackId = options.fallbackId ?? \"general-chat\";\n const extensions = options.extensions ?? DEFAULT_EXTENSIONS;\n const shouldCache = options.cache ?? true;\n\n let workflowCache: Record<string, AnyWorkflow> | null = null;\n\n async function loadWorkflows(): Promise<Record<string, AnyWorkflow>> {\n if (shouldCache && workflowCache) return workflowCache;\n\n const files = await readdir(workflowsDir, { withFileTypes: true });\n const workflowFiles = files\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name)\n .filter((file) => isWorkflowFile(file, extensions));\n\n const workflows: Record<string, AnyWorkflow> = {};\n\n for (const file of workflowFiles) {\n try {\n const modulePath = join(workflowsDir, file);\n\n // For declarative JSON/YAML workflows\n if (isDeclarativeWorkflowFile(file)) {\n const raw = await readFile(modulePath, \"utf8\");\n const workflow = loadWorkflow(raw) as unknown as AnyWorkflow;\n (workflow as any).metadata = {\n ...(((workflow as any).metadata ?? {}) as Record<string, unknown>),\n __filePath: modulePath,\n };\n workflows[workflow.id] = workflow;\n continue;\n }\n\n // For TS/JS module workflows\n const module = await import(modulePath);\n const workflowExport = Object.values(module).find(\n (exp): exp is AnyWorkflow => {\n const obj = exp as {\n id?: unknown;\n nodes?: unknown;\n edges?: unknown;\n };\n return (\n exp !== null &&\n typeof exp === \"object\" &&\n typeof obj.id === \"string\" &&\n typeof obj.nodes === \"object\" &&\n obj.nodes !== null &&\n Array.isArray(obj.edges)\n );\n },\n );\n\n if (workflowExport) {\n (workflowExport as any).metadata = {\n ...(((workflowExport as any).metadata ?? {}) as Record<\n string,\n unknown\n >),\n __filePath: modulePath,\n };\n workflows[workflowExport.id] = workflowExport;\n }\n } catch (error) {\n console.warn(`Failed to load workflow from ${file}:`, error);\n }\n }\n\n if (shouldCache) workflowCache = workflows;\n return workflows;\n }\n\n async function list(): Promise<AnyWorkflow[]> {\n const workflows = await loadWorkflows();\n return Object.values(workflows);\n }\n\n async function get(id: string): Promise<AnyWorkflow | null> {\n const workflows = await loadWorkflows();\n return workflows[id] ?? null;\n }\n\n async function select(\n id: string,\n selectOptions?: { fallbackId?: string },\n ): Promise<AnyWorkflow> {\n const workflows = await loadWorkflows();\n const fallback = selectOptions?.fallbackId ?? fallbackId;\n const selected = workflows[id] ?? (fallback ? workflows[fallback] : null);\n\n if (!selected) {\n throw new Error(\n `No workflow found for id \"${id}\" and no fallback \"${fallback}\" workflow available`,\n );\n }\n\n return selected;\n }\n\n async function refresh() {\n workflowCache = null;\n await loadWorkflows();\n }\n\n return {\n list,\n get,\n select,\n refresh,\n } satisfies WorkflowRegistry;\n}\n","import type { WorkflowDefinition } from \"@kortyx/core\";\nimport type { WorkflowRegistry } from \"./interface\";\n\nexport function createInMemoryWorkflowRegistry(\n workflows: WorkflowDefinition[],\n options?: { fallbackId?: string },\n): WorkflowRegistry {\n const byId = new Map<string, WorkflowDefinition>();\n for (const wf of workflows) byId.set(wf.id, wf);\n\n const fallbackId = options?.fallbackId ?? \"general-chat\";\n\n return {\n async list() {\n return Array.from(byId.values());\n },\n async get(id: string) {\n return byId.get(id) ?? null;\n },\n async select(id: string, selectOptions?: { fallbackId?: string }) {\n const fallback = selectOptions?.fallbackId ?? fallbackId;\n const wf = byId.get(id) ?? (fallback ? byId.get(fallback) : undefined);\n if (!wf) {\n throw new Error(\n `Workflow \"${id}\" not found${fallback ? ` (fallback \"${fallback}\" missing too)` : \"\"}.`,\n );\n }\n return wf;\n },\n };\n}\n","import type { GraphState, MemoryEnvelope } from \"@kortyx/core\";\n\n/**\n * Prepares the initial runtime graph state from chat context, memory, and runtime config.\n * This stays deliberately generic in the config type so apps can shape it.\n */\nexport interface InitialStateArgs<Config = unknown> {\n input: unknown;\n memory: MemoryEnvelope;\n config: Config;\n defaultWorkflowId?: string;\n}\n\nexport async function buildInitialGraphState<Config>({\n input,\n memory,\n config,\n defaultWorkflowId,\n}: InitialStateArgs<Config>): Promise<GraphState> {\n const currentWorkflow =\n (memory.currentWorkflow as any) || (defaultWorkflowId as any);\n if (!currentWorkflow) {\n throw new Error(\n \"No workflow selected. Provide defaultWorkflowId (or set memory.currentWorkflow) before starting the graph.\",\n );\n }\n\n return {\n input,\n lastNode: \"__start__\",\n memory,\n config: config as unknown,\n conversationHistory: [],\n currentWorkflow,\n awaitingHumanInput: false,\n } as GraphState;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,kCAUO;AAsBP,IAAM,YAAY,CAAC,MAAc,IAAI,WAAW,OAAO,KAAK,GAAG,MAAM,CAAC;AACtE,IAAM,aAAa,CAAC,OAClB,OAAO,OAAO,WAAW,KAAK,OAAO,KAAK,EAAE,EAAE,SAAS,MAAM;AAE/D,IAAM,YAAgC;AAAA,EACpC,MAAM,WAAW,MAAW;AAC1B,WAAO,CAAC,QAAQ,UAAU,KAAK,UAAU,IAAI,CAAC,CAAC;AAAA,EACjD;AAAA,EACA,MAAM,WAAW,OAAe,MAA2B;AACzD,WAAO,KAAK,MAAM,WAAW,IAAI,CAAC;AAAA,EACpC;AACF;AAaO,SAAS,8BACd,SACyB;AACzB,QAAM,yBAAyB,SAAS,0BAA0B;AAGlE,QAAM,SAAS,oBAAI,IAAoB;AAEvC,QAAM,cAAc,oBAAI,IAA8B;AA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OAAO,oBAAI,IAAgC;AACjD,aAAW,MAAM,UAAW,MAAK,IAAI,GAAG,IAAI,EAAE;AAE9C,QAAM,aAAa,SAAS,cAAc;AAE1C,SAAO;AAAA,IACL,MAAM,OAAO;AACX,aAAO,MAAM,KAAK,KAAK,OAAO,CAAC;AAAA,IACjC;AAAA,IACA,MAAM,IAAI,IAAY;AACpB,aAAO,KAAK,IAAI,EAAE,KAAK;AAAA,IACzB;AAAA,IACA,MAAM,OAAO,IAAY,eAAyC;AAChE,YAAM,WAAW,eAAe,cAAc;AAC9C,YAAM,KAAK,KAAK,IAAI,EAAE,MAAM,WAAW,KAAK,IAAI,QAAQ,IAAI;AAC5D,UAAI,CAAC,IAAI;AACP,cAAM,IAAI;AAAA,UACR,aAAa,EAAE,cAAc,WAAW,eAAe,QAAQ,mBAAmB,EAAE;AAAA,QACtF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;ACjBA,eAAsB,uBAA+B;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAkD;AAChD,QAAM,kBACH,OAAO,mBAA4B;AACtC,MAAI,CAAC,iBAAiB;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,qBAAqB,CAAC;AAAA,IACtB;AAAA,IACA,oBAAoB;AAAA,EACtB;AACF;","names":["import_langgraph_checkpoint","utf8Bytes","utf8String","jsonSerde","resolve","tlsConnect","netConnect","uuid","module"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kortyx/runtime",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "private": false,
5
5
  "description": "Runtime/orchestration wiring for Kortyx.",
6
6
  "keywords": [
@@ -31,24 +31,17 @@
31
31
  "README.md",
32
32
  "CHANGELOG.md"
33
33
  ],
34
- "scripts": {
35
- "build": "tsup",
36
- "dev": "tsc --watch",
37
- "lint": "biome check src",
38
- "test": "pnpm -s type-check",
39
- "type-check": "tsc --noEmit"
40
- },
41
34
  "dependencies": {
42
- "@kortyx/stream": "workspace:*",
43
- "@kortyx/core": "workspace:*",
44
- "@kortyx/hooks": "workspace:*",
45
- "@kortyx/memory": "workspace:*",
46
- "@kortyx/providers": "workspace:*",
47
- "@kortyx/utils": "workspace:*",
48
35
  "@langchain/core": "^1.0.1",
49
36
  "@langchain/langgraph": "^1.0.1",
50
37
  "@langchain/langgraph-checkpoint": "^1.0.0",
51
- "uuid": "^11.1.0"
38
+ "uuid": "^11.1.0",
39
+ "@kortyx/stream": "0.5.0",
40
+ "@kortyx/core": "0.4.1",
41
+ "@kortyx/memory": "0.3.1",
42
+ "@kortyx/hooks": "0.6.0",
43
+ "@kortyx/providers": "0.3.2",
44
+ "@kortyx/utils": "0.2.5"
52
45
  },
53
46
  "devDependencies": {
54
47
  "turbo": "^2.5.4",
@@ -60,5 +53,15 @@
60
53
  "type": "git",
61
54
  "url": "https://github.com/kortyx-io/kortyx.git",
62
55
  "directory": "packages/runtime"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "scripts": {
61
+ "build": "tsup",
62
+ "dev": "tsc --watch",
63
+ "lint": "biome check src",
64
+ "test": "pnpm -s type-check",
65
+ "type-check": "tsc --noEmit"
63
66
  }
64
- }
67
+ }