@langgraph-js/pure-graph 1.4.5 → 1.4.6

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.
@@ -1,6 +1,6 @@
1
1
  import { Hono } from 'hono';
2
2
  import { zValidator } from '@hono/zod-validator';
3
- import { c as createEndpoint, s as serialiseAsDict } from '../../createEndpoint-BcVhF-uq.js';
3
+ import { c as createEndpoint, s as serialiseAsDict } from '../../createEndpoint-B0FQz0jr.js';
4
4
  import { A as AssistantsSearchSchema, a as AssistantGraphQuerySchema, T as ThreadIdParamSchema, R as RunStreamPayloadSchema, b as RunListQuerySchema, c as RunIdParamSchema, d as RunCancelQuerySchema, e as ThreadStateUpdate, f as ThreadCreatePayloadSchema, g as ThreadSearchPayloadSchema } from '../../zod-BaCzVUl8.js';
5
5
  import { streamSSE } from 'hono/streaming';
6
6
  import z from 'zod';
@@ -1,5 +1,5 @@
1
1
  import { NextResponse } from 'next/server';
2
- import { c as createEndpoint, s as serialiseAsDict } from '../../createEndpoint-BcVhF-uq.js';
2
+ import { c as createEndpoint, s as serialiseAsDict } from '../../createEndpoint-B0FQz0jr.js';
3
3
  import { a as AssistantGraphQuerySchema, b as RunListQuerySchema, A as AssistantsSearchSchema, f as ThreadCreatePayloadSchema, g as ThreadSearchPayloadSchema, e as ThreadStateUpdate, R as RunStreamPayloadSchema, d as RunCancelQuerySchema } from '../../zod-BaCzVUl8.js';
4
4
 
5
5
  const client = createEndpoint();
@@ -942,6 +942,304 @@ class SQLiteThreadsManager {
942
942
  }
943
943
  }
944
944
 
945
+ class PostgresThreadsManager {
946
+ pool;
947
+ isSetup = false;
948
+ constructor(checkpointer) {
949
+ this.pool = checkpointer.pool;
950
+ }
951
+ async setup() {
952
+ if (this.isSetup) {
953
+ return;
954
+ }
955
+ await this.pool.query(`
956
+ CREATE TABLE IF NOT EXISTS threads (
957
+ thread_id TEXT PRIMARY KEY,
958
+ created_at TIMESTAMP NOT NULL,
959
+ updated_at TIMESTAMP NOT NULL,
960
+ metadata JSONB NOT NULL DEFAULT '{}',
961
+ status TEXT NOT NULL DEFAULT 'idle',
962
+ "values" JSONB,
963
+ interrupts JSONB NOT NULL DEFAULT '{}'
964
+ )
965
+ `);
966
+ await this.pool.query(`
967
+ CREATE TABLE IF NOT EXISTS runs (
968
+ run_id TEXT PRIMARY KEY,
969
+ thread_id TEXT NOT NULL,
970
+ assistant_id TEXT NOT NULL,
971
+ created_at TIMESTAMP NOT NULL,
972
+ updated_at TIMESTAMP NOT NULL,
973
+ status TEXT NOT NULL DEFAULT 'pending',
974
+ metadata JSONB NOT NULL DEFAULT '{}',
975
+ multitask_strategy TEXT NOT NULL DEFAULT 'reject',
976
+ FOREIGN KEY (thread_id) REFERENCES threads(thread_id) ON DELETE CASCADE
977
+ )
978
+ `);
979
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_threads_status ON threads(status)`);
980
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_threads_created_at ON threads(created_at)`);
981
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_threads_updated_at ON threads(updated_at)`);
982
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_runs_thread_id ON runs(thread_id)`);
983
+ await this.pool.query(`CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status)`);
984
+ this.isSetup = true;
985
+ }
986
+ async create(payload) {
987
+ const threadId = payload?.threadId || crypto.randomUUID();
988
+ if (payload?.ifExists === "raise") {
989
+ const result = await this.pool.query("SELECT thread_id FROM threads WHERE thread_id = $1", [threadId]);
990
+ if (result.rows.length > 0) {
991
+ throw new Error(`Thread with ID ${threadId} already exists.`);
992
+ }
993
+ }
994
+ const now = /* @__PURE__ */ new Date();
995
+ const metadata = payload?.metadata || {};
996
+ const interrupts = {};
997
+ const thread = {
998
+ thread_id: threadId,
999
+ created_at: now.toISOString(),
1000
+ updated_at: now.toISOString(),
1001
+ metadata,
1002
+ status: "idle",
1003
+ values: null,
1004
+ interrupts
1005
+ };
1006
+ await this.pool.query(
1007
+ `
1008
+ INSERT INTO threads (thread_id, created_at, updated_at, metadata, status, "values", interrupts)
1009
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
1010
+ `,
1011
+ [threadId, now, now, JSON.stringify(metadata), "idle", null, JSON.stringify(interrupts)]
1012
+ );
1013
+ return thread;
1014
+ }
1015
+ async search(query) {
1016
+ let sql = "SELECT * FROM threads";
1017
+ const whereConditions = [];
1018
+ const params = [];
1019
+ let paramIndex = 1;
1020
+ if (query?.status) {
1021
+ whereConditions.push(`status = $${paramIndex++}`);
1022
+ params.push(query.status);
1023
+ }
1024
+ if (query?.metadata) {
1025
+ for (const [key, value] of Object.entries(query.metadata)) {
1026
+ whereConditions.push(`metadata->$${paramIndex} = $${paramIndex + 1}`);
1027
+ params.push(key, JSON.stringify(value));
1028
+ paramIndex += 2;
1029
+ }
1030
+ }
1031
+ if (whereConditions.length > 0) {
1032
+ sql += " WHERE " + whereConditions.join(" AND ");
1033
+ }
1034
+ if (query?.sortBy) {
1035
+ sql += ` ORDER BY ${query.sortBy}`;
1036
+ if (query.sortOrder === "desc") {
1037
+ sql += " DESC";
1038
+ } else {
1039
+ sql += " ASC";
1040
+ }
1041
+ }
1042
+ if (query?.limit) {
1043
+ sql += ` LIMIT $${paramIndex++}`;
1044
+ params.push(query.limit);
1045
+ if (query?.offset) {
1046
+ sql += ` OFFSET $${paramIndex++}`;
1047
+ params.push(query.offset);
1048
+ }
1049
+ }
1050
+ const result = await this.pool.query(sql, params);
1051
+ return result.rows.map((row) => ({
1052
+ thread_id: row.thread_id,
1053
+ created_at: new Date(row.created_at).toISOString(),
1054
+ updated_at: new Date(row.updated_at).toISOString(),
1055
+ metadata: row.metadata,
1056
+ status: row.status,
1057
+ values: row.values || null,
1058
+ interrupts: row.interrupts
1059
+ }));
1060
+ }
1061
+ async get(threadId) {
1062
+ const result = await this.pool.query("SELECT * FROM threads WHERE thread_id = $1", [threadId]);
1063
+ if (result.rows.length === 0) {
1064
+ throw new Error(`Thread with ID ${threadId} not found.`);
1065
+ }
1066
+ const row = result.rows[0];
1067
+ return {
1068
+ thread_id: row.thread_id,
1069
+ created_at: new Date(row.created_at).toISOString(),
1070
+ updated_at: new Date(row.updated_at).toISOString(),
1071
+ metadata: row.metadata,
1072
+ status: row.status,
1073
+ values: row.values || null,
1074
+ interrupts: row.interrupts
1075
+ };
1076
+ }
1077
+ async set(threadId, thread) {
1078
+ const existingThread = await this.pool.query("SELECT thread_id FROM threads WHERE thread_id = $1", [threadId]);
1079
+ if (existingThread.rows.length === 0) {
1080
+ throw new Error(`Thread with ID ${threadId} not found.`);
1081
+ }
1082
+ const updateFields = [];
1083
+ const values = [];
1084
+ let paramIndex = 1;
1085
+ if (thread.metadata !== void 0) {
1086
+ updateFields.push(`metadata = $${paramIndex++}`);
1087
+ values.push(JSON.stringify(thread.metadata));
1088
+ }
1089
+ if (thread.status !== void 0) {
1090
+ updateFields.push(`status = $${paramIndex++}`);
1091
+ values.push(thread.status);
1092
+ }
1093
+ if (thread.values !== void 0) {
1094
+ updateFields.push(`"values" = $${paramIndex++}`);
1095
+ values.push(thread.values ? JSON.stringify(thread.values) : null);
1096
+ }
1097
+ if (thread.interrupts !== void 0) {
1098
+ updateFields.push(`interrupts = $${paramIndex++}`);
1099
+ values.push(JSON.stringify(thread.interrupts));
1100
+ }
1101
+ updateFields.push(`updated_at = $${paramIndex++}`);
1102
+ values.push(/* @__PURE__ */ new Date());
1103
+ if (updateFields.length > 0) {
1104
+ values.push(threadId);
1105
+ await this.pool.query(
1106
+ `
1107
+ UPDATE threads
1108
+ SET ${updateFields.join(", ")}
1109
+ WHERE thread_id = $${paramIndex}
1110
+ `,
1111
+ values
1112
+ );
1113
+ }
1114
+ }
1115
+ async updateState(threadId, thread) {
1116
+ const result = await this.pool.query("SELECT * FROM threads WHERE thread_id = $1", [threadId]);
1117
+ if (result.rows.length === 0) {
1118
+ throw new Error(`Thread with ID ${threadId} not found.`);
1119
+ }
1120
+ const row = result.rows[0];
1121
+ const targetThread = {
1122
+ thread_id: row.thread_id,
1123
+ created_at: new Date(row.created_at).toISOString(),
1124
+ updated_at: new Date(row.updated_at).toISOString(),
1125
+ metadata: row.metadata,
1126
+ status: row.status,
1127
+ values: row.values || null,
1128
+ interrupts: row.interrupts
1129
+ };
1130
+ if (targetThread.status === "busy") {
1131
+ throw new Error(`Thread with ID ${threadId} is busy, can't update state.`);
1132
+ }
1133
+ if (!targetThread.metadata?.graph_id) {
1134
+ throw new Error(`Thread with ID ${threadId} has no graph_id.`);
1135
+ }
1136
+ const graphId = targetThread.metadata?.graph_id;
1137
+ const config = {
1138
+ configurable: {
1139
+ thread_id: threadId,
1140
+ graph_id: graphId
1141
+ }
1142
+ };
1143
+ const graph = await getGraph(graphId, config);
1144
+ const nextConfig = await graph.updateState(config, thread.values);
1145
+ const graphState = await graph.getState(config);
1146
+ await this.set(threadId, { values: JSON.parse(serialiseAsDict(graphState.values)) });
1147
+ return nextConfig;
1148
+ }
1149
+ async delete(threadId) {
1150
+ const result = await this.pool.query("DELETE FROM threads WHERE thread_id = $1", [threadId]);
1151
+ if (result.rowCount === 0) {
1152
+ throw new Error(`Thread with ID ${threadId} not found.`);
1153
+ }
1154
+ }
1155
+ async createRun(threadId, assistantId, payload) {
1156
+ const runId = crypto.randomUUID();
1157
+ const now = /* @__PURE__ */ new Date();
1158
+ const metadata = payload?.metadata ?? {};
1159
+ const run = {
1160
+ run_id: runId,
1161
+ thread_id: threadId,
1162
+ assistant_id: assistantId,
1163
+ created_at: now.toISOString(),
1164
+ updated_at: now.toISOString(),
1165
+ status: "pending",
1166
+ metadata,
1167
+ multitask_strategy: "reject"
1168
+ };
1169
+ await this.pool.query(
1170
+ `
1171
+ INSERT INTO runs (run_id, thread_id, assistant_id, created_at, updated_at, status, metadata, multitask_strategy)
1172
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
1173
+ `,
1174
+ [runId, threadId, assistantId, now, now, "pending", JSON.stringify(metadata), "reject"]
1175
+ );
1176
+ return run;
1177
+ }
1178
+ async listRuns(threadId, options) {
1179
+ let sql = "SELECT * FROM runs WHERE thread_id = $1";
1180
+ const params = [threadId];
1181
+ let paramIndex = 2;
1182
+ if (options?.status) {
1183
+ sql += ` AND status = $${paramIndex++}`;
1184
+ params.push(options.status);
1185
+ }
1186
+ sql += " ORDER BY created_at DESC";
1187
+ if (options?.limit) {
1188
+ sql += ` LIMIT $${paramIndex++}`;
1189
+ params.push(options.limit);
1190
+ if (options?.offset) {
1191
+ sql += ` OFFSET $${paramIndex++}`;
1192
+ params.push(options.offset);
1193
+ }
1194
+ }
1195
+ const result = await this.pool.query(sql, params);
1196
+ return result.rows.map((row) => ({
1197
+ run_id: row.run_id,
1198
+ thread_id: row.thread_id,
1199
+ assistant_id: row.assistant_id,
1200
+ created_at: new Date(row.created_at).toISOString(),
1201
+ updated_at: new Date(row.updated_at).toISOString(),
1202
+ status: row.status,
1203
+ metadata: row.metadata,
1204
+ multitask_strategy: row.multitask_strategy
1205
+ }));
1206
+ }
1207
+ async updateRun(runId, run) {
1208
+ const existingRun = await this.pool.query("SELECT run_id FROM runs WHERE run_id = $1", [runId]);
1209
+ if (existingRun.rows.length === 0) {
1210
+ throw new Error(`Run with ID ${runId} not found.`);
1211
+ }
1212
+ const updateFields = [];
1213
+ const values = [];
1214
+ let paramIndex = 1;
1215
+ if (run.status !== void 0) {
1216
+ updateFields.push(`status = $${paramIndex++}`);
1217
+ values.push(run.status);
1218
+ }
1219
+ if (run.metadata !== void 0) {
1220
+ updateFields.push(`metadata = $${paramIndex++}`);
1221
+ values.push(JSON.stringify(run.metadata));
1222
+ }
1223
+ if (run.multitask_strategy !== void 0) {
1224
+ updateFields.push(`multitask_strategy = $${paramIndex++}`);
1225
+ values.push(run.multitask_strategy);
1226
+ }
1227
+ updateFields.push(`updated_at = $${paramIndex++}`);
1228
+ values.push(/* @__PURE__ */ new Date());
1229
+ if (updateFields.length > 0) {
1230
+ values.push(runId);
1231
+ await this.pool.query(
1232
+ `
1233
+ UPDATE runs
1234
+ SET ${updateFields.join(", ")}
1235
+ WHERE run_id = $${paramIndex}
1236
+ `,
1237
+ values
1238
+ );
1239
+ }
1240
+ }
1241
+ }
1242
+
945
1243
  const createCheckPointer = async () => {
946
1244
  if (process.env.REDIS_URL && process.env.CHECKPOINT_TYPE === "redis" || process.env.CHECKPOINT_TYPE === "shallow/redis") {
947
1245
  if (process.env.CHECKPOINT_TYPE === "redis") {
@@ -976,7 +1274,7 @@ const createMessageQueue = async () => {
976
1274
  let q;
977
1275
  if (process.env.REDIS_URL) {
978
1276
  console.debug("LG | Using redis as stream queue");
979
- const { RedisStreamQueue } = await import('./queue-pSZu1PVS.js');
1277
+ const { RedisStreamQueue } = await import('./queue-Cao_-0hm.js');
980
1278
  q = RedisStreamQueue;
981
1279
  } else {
982
1280
  q = MemoryStreamQueue;
@@ -985,7 +1283,6 @@ const createMessageQueue = async () => {
985
1283
  };
986
1284
  const createThreadManager = async (config) => {
987
1285
  if (process.env.DATABASE_URL && config.checkpointer) {
988
- const { PostgresThreadsManager } = await import('./threads-amMaxKul.js');
989
1286
  const threadsManager = new PostgresThreadsManager(config.checkpointer);
990
1287
  if (process.env.DATABASE_INIT === "true") {
991
1288
  await threadsManager.setup();
@@ -1249,5 +1546,5 @@ const createEndpoint = () => {
1249
1546
  };
1250
1547
  };
1251
1548
 
1252
- export { AssistantEndpoint as A, BaseStreamQueue as B, CancelEventMessage as C, LangGraphGlobal as L, createEndpoint as c, getGraph as g, registerGraph as r, serialiseAsDict as s };
1253
- //# sourceMappingURL=createEndpoint-BcVhF-uq.js.map
1549
+ export { AssistantEndpoint as A, BaseStreamQueue as B, CancelEventMessage as C, LangGraphGlobal as L, createEndpoint as c, registerGraph as r, serialiseAsDict as s };
1550
+ //# sourceMappingURL=createEndpoint-B0FQz0jr.js.map