@kortyx/runtime 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.8.1](https://github.com/kortyx-io/kortyx/compare/runtime-v0.8.0...runtime-v0.8.1) (2026-04-12)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **agent:** support sequential interrupts across resume ([f56b092](https://github.com/kortyx-io/kortyx/commit/f56b092e2738c084695ba9d1eed3fbfb3d400dc8))
9
+ * **agent:** support sequential interrupts across resume ([b22d84e](https://github.com/kortyx-io/kortyx/commit/b22d84e3a805f2bc350b49ad7d9b68c1124439de))
10
+
11
+ ## [0.8.0](https://github.com/kortyx-io/kortyx/compare/runtime-v0.7.0...runtime-v0.8.0) (2026-03-11)
12
+
13
+
14
+ ### ⚠ BREAKING CHANGES
15
+
16
+ * remove @kortyx/memory and clarify runtime persistence
17
+
18
+ ### Bug Fixes
19
+
20
+ * **dx:** simplify streamChat API route surface and docs ([6ac69da](https://github.com/kortyx-io/kortyx/commit/6ac69da30945e48d251b3f16b979177cf5a4d108))
21
+ * remove @kortyx/memory and clarify runtime persistence ([613574d](https://github.com/kortyx-io/kortyx/commit/613574d535de680a7b9671e801613a8222052dd5))
22
+
3
23
  ## [0.7.0](https://github.com/kortyx-io/kortyx/compare/runtime-v0.6.1...runtime-v0.7.0) (2026-03-08)
4
24
 
5
25
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { BaseCheckpointSaver } from '@langchain/langgraph-checkpoint';
2
- import { GraphState, WorkflowDefinition, NodeFn, MemoryEnvelope } from '@kortyx/core';
3
- import { MemoryAdapter } from '@kortyx/memory';
2
+ import { GraphState, WorkflowDefinition, NodeFn, RuntimeEnvelope } from '@kortyx/core';
4
3
  import { GetProviderFn } from '@kortyx/providers';
5
4
 
6
5
  declare function getCheckpointer(key: string): BaseCheckpointSaver;
@@ -46,7 +45,7 @@ interface PendingRequestStore {
46
45
  declare function createInMemoryPendingRequestStore(): PendingRequestStore;
47
46
 
48
47
  type FrameworkAdapter = {
49
- kind: "memory" | "redis";
48
+ kind: "in-memory" | "redis";
50
49
  pendingRequests: PendingRequestStore;
51
50
  checkpointer: BaseCheckpointSaver;
52
51
  ttlMs: number;
@@ -68,13 +67,25 @@ type CreateRedisFrameworkAdapterOptions = {
68
67
  declare function createRedisFrameworkAdapter(options: CreateRedisFrameworkAdapterOptions): FrameworkAdapter;
69
68
  declare function createFrameworkAdapterFromEnv(env?: Record<string, string | undefined>): FrameworkAdapter;
70
69
 
70
+ interface CompiledGraphBase {
71
+ invoke(state: unknown): Promise<unknown>;
72
+ streamEvents(state: GraphState, options?: {
73
+ version?: string;
74
+ configurable?: Record<string, unknown>;
75
+ }): AsyncIterable<unknown> | AsyncGenerator<unknown>;
76
+ }
77
+ interface GraphExtensions {
78
+ name: string;
79
+ config: ExecutionRuntimeConfig;
80
+ resume(state: GraphState, input: unknown): Promise<GraphState>;
81
+ timeTravelTo(state: GraphState, checkpointId: string): Promise<GraphState>;
82
+ }
71
83
  interface ExecutionRuntimeConfig {
72
84
  emit?: (event: string, payload: unknown) => void;
73
85
  onCheckpoint?: (args: {
74
86
  nodeId: string;
75
87
  state: GraphState;
76
88
  }) => void;
77
- memoryAdapter?: MemoryAdapter;
78
89
  checkpointer?: BaseCheckpointSaver;
79
90
  /**
80
91
  * Provider factory used by ctx.speak to obtain a streaming model.
@@ -83,7 +94,7 @@ interface ExecutionRuntimeConfig {
83
94
  getProvider?: GetProviderFn;
84
95
  [key: string]: unknown;
85
96
  }
86
- declare function createExecutionGraph(workflow: WorkflowDefinition, config: ExecutionRuntimeConfig): Promise<any>;
97
+ declare function createExecutionGraph(workflow: WorkflowDefinition, config: ExecutionRuntimeConfig): Promise<CompiledGraphBase & GraphExtensions>;
87
98
 
88
99
  declare function makeResumeToken(): string;
89
100
  declare function makeRequestId(prefix?: string): string;
@@ -117,15 +128,15 @@ declare function createInMemoryWorkflowRegistry(workflows: WorkflowDefinition[],
117
128
  }): WorkflowRegistry;
118
129
 
119
130
  /**
120
- * Prepares the initial runtime graph state from chat context, memory, and runtime config.
131
+ * Prepares the initial graph state from chat context, runtime state, and runtime config.
121
132
  * This stays deliberately generic in the config type so apps can shape it.
122
133
  */
123
134
  interface InitialStateArgs<Config = unknown> {
124
135
  input: unknown;
125
- memory: MemoryEnvelope;
136
+ runtime: RuntimeEnvelope;
126
137
  config: Config;
127
138
  defaultWorkflowId?: string;
128
139
  }
129
- declare function buildInitialGraphState<Config>({ input, memory, config, defaultWorkflowId, }: InitialStateArgs<Config>): Promise<GraphState>;
140
+ declare function buildInitialGraphState<Config>({ input, runtime, config, defaultWorkflowId, }: InitialStateArgs<Config>): Promise<GraphState>;
130
141
 
131
142
  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
@@ -676,7 +676,7 @@ function createInMemoryFrameworkAdapter(options) {
676
676
  const ttlMs = options?.ttlMs ?? 15 * 60 * 1e3;
677
677
  const checkpointer = createInMemoryCheckpointSaver();
678
678
  return {
679
- kind: "memory",
679
+ kind: "in-memory",
680
680
  ttlMs,
681
681
  pendingRequests: createInMemoryPendingRequestStore(),
682
682
  checkpointer,
@@ -828,7 +828,7 @@ async function createExecutionGraph(workflow, config) {
828
828
  lastNode: import_langgraph.Annotation,
829
829
  lastCondition: import_langgraph.Annotation,
830
830
  lastIntent: import_langgraph.Annotation,
831
- memory: (0, import_langgraph.Annotation)({
831
+ runtime: (0, import_langgraph.Annotation)({
832
832
  reducer: (l, r) => (0, import_utils.deepMergeWithArrayOverwrite)(l ?? {}, r ?? {}),
833
833
  default: () => ({})
834
834
  }),
@@ -901,34 +901,47 @@ async function createExecutionGraph(workflow, config) {
901
901
  awaitInterrupt: (interruptConfig) => {
902
902
  const { kind, question } = interruptConfig;
903
903
  const isMulti = kind === "multi-choice" || interruptConfig.kind !== "text" && interruptConfig.multiple === true;
904
- const payload = {
905
- kind,
906
- multiple: isMulti,
907
- question,
908
- ...interruptConfig.kind !== "text" ? { options: interruptConfig.options } : {},
904
+ const sharedInterruptFields = {
909
905
  ...typeof interruptConfig.id === "string" && interruptConfig.id.length > 0 ? { id: interruptConfig.id } : {},
910
906
  ...typeof interruptConfig.schemaId === "string" && interruptConfig.schemaId.length > 0 ? { schemaId: interruptConfig.schemaId } : {},
911
907
  ...typeof interruptConfig.schemaVersion === "string" && interruptConfig.schemaVersion.length > 0 ? { schemaVersion: interruptConfig.schemaVersion } : {},
912
908
  ...interruptConfig.meta && typeof interruptConfig.meta === "object" && !Array.isArray(interruptConfig.meta) ? { meta: interruptConfig.meta } : {}
913
909
  };
914
- runtimeConfig.emit("interrupt", {
915
- node: nodeId,
916
- workflow: workflowName,
917
- input: payload
918
- });
919
- const resumed = (0, import_langgraph.interrupt)(payload);
910
+ const payload = interruptConfig.kind === "text" ? {
911
+ kind: "text",
912
+ ...question ? { question } : {},
913
+ ...sharedInterruptFields
914
+ } : {
915
+ kind: interruptConfig.kind,
916
+ multiple: isMulti,
917
+ question: interruptConfig.question,
918
+ options: interruptConfig.options,
919
+ ...sharedInterruptFields
920
+ };
921
+ let resumed;
922
+ try {
923
+ resumed = (0, import_langgraph.interrupt)(payload);
924
+ } catch (error) {
925
+ runtimeConfig.emit("interrupt", {
926
+ node: nodeId,
927
+ workflow: workflowName,
928
+ input: payload
929
+ });
930
+ throw error;
931
+ }
920
932
  if (isMulti) {
921
933
  if (Array.isArray(resumed)) {
922
934
  return resumed.map(
923
- (v) => typeof v === "string" ? v : v && typeof v.id === "string" ? v.id : ""
935
+ (v) => typeof v === "string" ? v : v && typeof v === "object" && "id" in v && typeof v.id === "string" ? v.id : ""
924
936
  ).filter(Boolean);
925
937
  }
926
938
  if (typeof resumed === "string") return [resumed];
927
939
  return [];
928
940
  }
929
941
  if (typeof resumed === "string") return resumed;
930
- if (resumed && typeof resumed.id === "string")
942
+ if (resumed && typeof resumed === "object" && "id" in resumed && typeof resumed.id === "string") {
931
943
  return String(resumed.id);
944
+ }
932
945
  return "";
933
946
  },
934
947
  speak: async (args) => {
@@ -964,23 +977,22 @@ async function createExecutionGraph(workflow, config) {
964
977
  const maxAttempts = behavior.retry?.maxAttempts ?? 1;
965
978
  let attempt = 0;
966
979
  let nodeResult;
967
- let hookMemoryUpdates = null;
968
- let retryHookMemory = null;
980
+ let hookRuntimeUpdates = null;
981
+ let retryHookRuntime = null;
969
982
  while (attempt < maxAttempts) {
970
983
  try {
971
984
  attempt++;
972
- const attemptState = retryHookMemory && typeof retryHookMemory === "object" ? {
985
+ const attemptState = retryHookRuntime && typeof retryHookRuntime === "object" ? {
973
986
  ...state,
974
- memory: (0, import_utils.deepMergeWithArrayOverwrite)(
975
- state.memory ?? {},
976
- retryHookMemory
987
+ runtime: (0, import_utils.deepMergeWithArrayOverwrite)(
988
+ state.runtime ?? {},
989
+ retryHookRuntime
977
990
  )
978
991
  } : state;
979
992
  const hookContext = {
980
993
  node: ctx,
981
994
  state: attemptState,
982
- ...runtimeConfig.getProvider ? { getProvider: runtimeConfig.getProvider } : {},
983
- ...runtimeConfig.memoryAdapter ? { memoryAdapter: runtimeConfig.memoryAdapter } : {}
995
+ ...runtimeConfig.getProvider ? { getProvider: runtimeConfig.getProvider } : {}
984
996
  };
985
997
  const hookRun = await (0, import_hooks.runWithHookContext)(
986
998
  hookContext,
@@ -990,17 +1002,17 @@ async function createExecutionGraph(workflow, config) {
990
1002
  })
991
1003
  );
992
1004
  nodeResult = hookRun.result;
993
- hookMemoryUpdates = hookRun.memoryUpdates;
1005
+ hookRuntimeUpdates = hookRun.runtimeUpdates;
994
1006
  break;
995
1007
  } catch (err) {
996
- const patch = err?.__kortyxMemoryUpdates;
1008
+ const patch = err?.__kortyxHookStatePatch;
997
1009
  if (patch && typeof patch === "object") {
998
- state.memory = (0, import_utils.deepMergeWithArrayOverwrite)(
999
- state.memory ?? {},
1010
+ state.runtime = (0, import_utils.deepMergeWithArrayOverwrite)(
1011
+ state.runtime ?? {},
1000
1012
  patch
1001
1013
  );
1002
- retryHookMemory = (0, import_utils.deepMergeWithArrayOverwrite)(
1003
- retryHookMemory ?? {},
1014
+ retryHookRuntime = (0, import_utils.deepMergeWithArrayOverwrite)(
1015
+ retryHookRuntime ?? {},
1004
1016
  patch
1005
1017
  );
1006
1018
  }
@@ -1014,12 +1026,12 @@ async function createExecutionGraph(workflow, config) {
1014
1026
  }
1015
1027
  }
1016
1028
  const res = nodeResult ?? {};
1017
- if (hookMemoryUpdates) {
1029
+ if (hookRuntimeUpdates) {
1018
1030
  res.infra = {
1019
1031
  ...res.infra ?? {},
1020
- memory: (0, import_utils.deepMergeWithArrayOverwrite)(
1021
- (res.infra?.memory ?? {}) || {},
1022
- hookMemoryUpdates
1032
+ runtime: (0, import_utils.deepMergeWithArrayOverwrite)(
1033
+ (res.infra?.runtime ?? {}) || {},
1034
+ hookRuntimeUpdates
1023
1035
  )
1024
1036
  };
1025
1037
  }
@@ -1048,10 +1060,10 @@ async function createExecutionGraph(workflow, config) {
1048
1060
  res.data
1049
1061
  );
1050
1062
  }
1051
- if (res.infra?.memory && typeof res.infra.memory === "object") {
1052
- updates.memory = (0, import_utils.deepMergeWithArrayOverwrite)(
1053
- state.memory ?? {},
1054
- res.infra.memory
1063
+ if (res.infra?.runtime && typeof res.infra.runtime === "object") {
1064
+ updates.runtime = (0, import_utils.deepMergeWithArrayOverwrite)(
1065
+ state.runtime ?? {},
1066
+ res.infra.runtime
1055
1067
  );
1056
1068
  }
1057
1069
  if (res.ui) {
@@ -1117,18 +1129,18 @@ async function createExecutionGraph(workflow, config) {
1117
1129
  mapping
1118
1130
  );
1119
1131
  }
1120
- const sessionId = config?.session?.id ?? "__default__";
1132
+ const sessionId = typeof config.session === "object" && config.session && "id" in config.session && typeof config.session.id === "string" ? config.session.id : "__default__";
1121
1133
  const checkpointer = config.checkpointer ?? getCheckpointer(sessionId);
1122
- const graph = builder.compile({ checkpointer });
1134
+ const graph = edgeApi.compile({ checkpointer });
1123
1135
  const runtimeGraph = graph;
1124
1136
  runtimeGraph.name = workflow.id;
1125
1137
  runtimeGraph.config = config;
1126
1138
  runtimeGraph.resume = async (state, input) => {
1127
1139
  const resumed = { ...state, input, awaitingHumanInput: false };
1128
- return graph.invoke(resumed);
1140
+ return await graph.invoke(resumed);
1129
1141
  };
1130
1142
  runtimeGraph.timeTravelTo = async (state, checkpointId) => {
1131
- const checkpoints = state.memory?.checkpoints;
1143
+ const checkpoints = state.runtime?.checkpoints;
1132
1144
  const snapshot = checkpoints?.[checkpointId];
1133
1145
  if (!snapshot) throw new Error(`Checkpoint '${checkpointId}' not found`);
1134
1146
  return graph.invoke(
@@ -1270,20 +1282,20 @@ function createInMemoryWorkflowRegistry(workflows, options) {
1270
1282
  // src/state/build-initial-state.ts
1271
1283
  async function buildInitialGraphState({
1272
1284
  input,
1273
- memory,
1285
+ runtime,
1274
1286
  config,
1275
1287
  defaultWorkflowId
1276
1288
  }) {
1277
- const currentWorkflow = memory.currentWorkflow || defaultWorkflowId;
1289
+ const currentWorkflow = runtime.requestedWorkflow || defaultWorkflowId;
1278
1290
  if (!currentWorkflow) {
1279
1291
  throw new Error(
1280
- "No workflow selected. Provide defaultWorkflowId (or set memory.currentWorkflow) before starting the graph."
1292
+ "No workflow selected. Provide defaultWorkflowId (or set runtime.requestedWorkflow) before starting the graph."
1281
1293
  );
1282
1294
  }
1283
1295
  return {
1284
1296
  input,
1285
1297
  lastNode: "__start__",
1286
- memory,
1298
+ runtime,
1287
1299
  config,
1288
1300
  conversationHistory: [],
1289
1301
  currentWorkflow,
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-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,I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A6B,EAAE,sBAAsB,QAAQ;AAAA,MAC/D;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,iBAAe,UAAU;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: \"in-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: \"in-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 InterruptInput,\n InterruptResult,\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 { 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\ninterface CompiledGraphBase {\n invoke(state: unknown): Promise<unknown>;\n streamEvents(\n state: GraphState,\n options?: { version?: string; configurable?: Record<string, unknown> },\n ): AsyncIterable<unknown> | AsyncGenerator<unknown>;\n}\n\ninterface 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\ninterface InterruptResultWithId {\n id: string;\n}\n\ninterface HookPatchError {\n __kortyxHookStatePatch?: Record<string, unknown> | null;\n}\n\nexport interface ExecutionRuntimeConfig {\n emit?: (event: string, payload: unknown) => void;\n onCheckpoint?: (args: { nodeId: string; state: GraphState }) => void;\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 runtime: 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: (args: { checkpointer: BaseCheckpointSaver }) => CompiledGraphBase;\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)\n ? (params.model as NodeConfig[\"model\"])\n : undefined;\n const tool = isRecord(params?.tool)\n ? (params.tool as NodeConfig[\"tool\"])\n : undefined;\n const behaviorFromParams = isRecord(params?.behavior)\n ? (params.behavior as NodeConfig[\"behavior\"])\n : undefined;\n const behavior: NonNullable<NodeConfig[\"behavior\"]> = {\n ...(behaviorFromParams ?? {}),\n ...(nodeBehavior ?? {}),\n };\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: InterruptInput): InterruptResult => {\n const { kind, question } = interruptConfig;\n const isMulti =\n kind === \"multi-choice\" ||\n (interruptConfig.kind !== \"text\" &&\n interruptConfig.multiple === true);\n const sharedInterruptFields = {\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 const payload: InterruptInput =\n interruptConfig.kind === \"text\"\n ? {\n kind: \"text\",\n ...(question ? { question } : {}),\n ...sharedInterruptFields,\n }\n : {\n kind: interruptConfig.kind,\n multiple: isMulti,\n question: interruptConfig.question,\n options: interruptConfig.options,\n ...sharedInterruptFields,\n };\n let resumed: unknown;\n try {\n resumed = interrupt(payload) as unknown;\n } catch (error) {\n runtimeConfig.emit(\"interrupt\", {\n node: nodeId,\n workflow: workflowName,\n input: payload,\n });\n throw error;\n }\n if (isMulti) {\n if (Array.isArray(resumed)) {\n return (resumed as unknown[])\n .map((v) =>\n typeof v === \"string\"\n ? v\n : v &&\n typeof v === \"object\" &&\n \"id\" in v &&\n typeof (v as InterruptResultWithId).id === \"string\"\n ? (v as InterruptResultWithId).id\n : \"\",\n )\n .filter(Boolean);\n }\n if (typeof resumed === \"string\") return [resumed];\n return [];\n }\n if (typeof resumed === \"string\") return resumed;\n if (\n resumed &&\n typeof resumed === \"object\" &&\n \"id\" in resumed &&\n typeof (resumed as InterruptResultWithId).id === \"string\"\n ) {\n return String((resumed as InterruptResultWithId).id);\n }\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 hookRuntimeUpdates: Record<string, unknown> | null = null;\n let retryHookRuntime: Record<string, unknown> | null = null;\n\n while (attempt < maxAttempts) {\n try {\n attempt++;\n const attemptState =\n retryHookRuntime && typeof retryHookRuntime === \"object\"\n ? ({\n ...state,\n runtime: deepMergeWithArrayOverwrite(\n (state.runtime ?? {}) as Record<string, unknown>,\n retryHookRuntime,\n ),\n } as GraphState)\n : state;\n const hookContext = {\n node: ctx,\n state: attemptState,\n ...(runtimeConfig.getProvider\n ? { getProvider: runtimeConfig.getProvider }\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 hookRuntimeUpdates = hookRun.runtimeUpdates;\n break;\n } catch (err) {\n const patch = (err as HookPatchError)?.__kortyxHookStatePatch as\n | Record<string, unknown>\n | null\n | undefined;\n if (patch && typeof patch === \"object\") {\n // Preserve hook runtime state 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.runtime = deepMergeWithArrayOverwrite(\n (state.runtime ?? {}) as Record<string, unknown>,\n patch,\n );\n retryHookRuntime = deepMergeWithArrayOverwrite(\n (retryHookRuntime ?? {}) 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 (hookRuntimeUpdates) {\n res.infra = {\n ...(res.infra ?? {}),\n runtime: deepMergeWithArrayOverwrite(\n ((res.infra?.runtime ?? {}) as Record<string, unknown>) || {},\n hookRuntimeUpdates,\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?.runtime && typeof res.infra.runtime === \"object\") {\n updates.runtime = deepMergeWithArrayOverwrite(\n (state.runtime ?? {}) as Record<string, unknown>,\n res.infra.runtime 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;\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 =\n typeof config.session === \"object\" &&\n config.session &&\n \"id\" in config.session &&\n typeof config.session.id === \"string\"\n ? config.session.id\n : \"__default__\";\n const checkpointer = config.checkpointer ?? getCheckpointer(sessionId);\n const graph = edgeApi.compile({ checkpointer });\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 (await graph.invoke(resumed)) as GraphState;\n };\n\n runtimeGraph.timeTravelTo = async (\n state: GraphState,\n checkpointId: string,\n ) => {\n const checkpoints = (\n state.runtime 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, RuntimeEnvelope } from \"@kortyx/core\";\n\n/**\n * Prepares the initial graph state from chat context, runtime state, 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 runtime: RuntimeEnvelope;\n config: Config;\n defaultWorkflowId?: string;\n}\n\nexport async function buildInitialGraphState<Config>({\n input,\n runtime,\n config,\n defaultWorkflowId,\n}: InitialStateArgs<Config>): Promise<GraphState> {\n const currentWorkflow =\n (runtime.requestedWorkflow as any) || (defaultWorkflowId as any);\n if (!currentWorkflow) {\n throw new Error(\n \"No workflow selected. Provide defaultWorkflowId (or set runtime.requestedWorkflow) before starting the graph.\",\n );\n }\n\n return {\n input,\n lastNode: \"__start__\",\n runtime,\n config: config as unknown,\n conversationHistory: [],\n currentWorkflow,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,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,QAAQ,qBAA8B;AACzC,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.7.0",
3
+ "version": "0.8.1",
4
4
  "private": false,
5
5
  "description": "Runtime/orchestration wiring for Kortyx.",
6
6
  "keywords": [
@@ -36,10 +36,9 @@
36
36
  "@langchain/langgraph": "^1.0.1",
37
37
  "@langchain/langgraph-checkpoint": "^1.0.0",
38
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",
39
+ "@kortyx/stream": "0.5.2",
40
+ "@kortyx/core": "0.5.0",
41
+ "@kortyx/hooks": "0.8.0",
43
42
  "@kortyx/providers": "0.3.2",
44
43
  "@kortyx/utils": "0.2.5"
45
44
  },