@deepagents/context 7.8.2 → 7.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11120,16 +11120,79 @@ function lockSchemaDDL(ddl, schema) {
11120
11120
  ${ddl}`;
11121
11121
  }
11122
11122
 
11123
+ // packages/context/src/lib/store/postgres-store-database.ts
11124
+ import { z as z14 } from "zod";
11125
+
11123
11126
  // packages/context/src/lib/store/postgres-transaction.ts
11124
11127
  function surfacedThroughQueries() {
11125
11128
  }
11126
- async function postgresTransaction(pool, fn) {
11127
- const client = await pool.connect();
11129
+ var openTransaction;
11130
+ var finishTransaction;
11131
+ var openSavepoint;
11132
+ var closeSavepoint;
11133
+ var PostgresTransaction = class _PostgresTransaction {
11134
+ static {
11135
+ openTransaction = (client) => new _PostgresTransaction(client, void 0);
11136
+ finishTransaction = (tx) => {
11137
+ tx.#finished = true;
11138
+ };
11139
+ openSavepoint = (parent) => {
11140
+ parent.#assertUsable();
11141
+ const child = new _PostgresTransaction(parent.#client, parent);
11142
+ parent.#child = child;
11143
+ return child;
11144
+ };
11145
+ closeSavepoint = (parent, child) => {
11146
+ child.#finished = true;
11147
+ parent.#child = void 0;
11148
+ };
11149
+ }
11150
+ #client;
11151
+ #parent;
11152
+ #child;
11153
+ #finished = false;
11154
+ constructor(client, parent) {
11155
+ this.#client = client;
11156
+ this.#parent = parent;
11157
+ }
11158
+ async query(text3, values) {
11159
+ this.#assertUsable();
11160
+ return this.#client.query(text3, values);
11161
+ }
11162
+ #assertUsable() {
11163
+ if (this.#isFinished()) {
11164
+ throw new Error(
11165
+ "PostgresTransaction: the transaction is already finished"
11166
+ );
11167
+ }
11168
+ if (this.#child) {
11169
+ throw new Error(
11170
+ "PostgresTransaction: a savepoint opened on this transaction is still running; run its work in sequence"
11171
+ );
11172
+ }
11173
+ }
11174
+ #isFinished() {
11175
+ const parent = this.#parent;
11176
+ return this.#finished || parent !== void 0 && parent.#isFinished();
11177
+ }
11178
+ };
11179
+ var savepoints = 0;
11180
+ async function postgresTransaction(db, fn) {
11181
+ if (db instanceof PostgresTransaction) {
11182
+ return inSavepoint(db, fn);
11183
+ }
11184
+ const client = await db.connect();
11128
11185
  client.on("error", surfacedThroughQueries);
11186
+ const tx = openTransaction(client);
11129
11187
  let broken = false;
11130
11188
  try {
11131
11189
  await client.query("BEGIN");
11132
- const result = await fn(client);
11190
+ let result;
11191
+ try {
11192
+ result = await fn(tx);
11193
+ } finally {
11194
+ finishTransaction(tx);
11195
+ }
11133
11196
  await client.query("COMMIT");
11134
11197
  return result;
11135
11198
  } catch (error) {
@@ -11144,9 +11207,60 @@ async function postgresTransaction(pool, fn) {
11144
11207
  client.release(broken);
11145
11208
  }
11146
11209
  }
11210
+ async function inSavepoint(parent, fn) {
11211
+ const savepoint = `deepagents_savepoint_${++savepoints}`;
11212
+ const child = openSavepoint(parent);
11213
+ let result;
11214
+ try {
11215
+ await child.query(`SAVEPOINT ${savepoint}`);
11216
+ result = await fn(child);
11217
+ } catch (error) {
11218
+ closeSavepoint(parent, child);
11219
+ await parent.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
11220
+ throw error;
11221
+ }
11222
+ closeSavepoint(parent, child);
11223
+ await parent.query(`RELEASE SAVEPOINT ${savepoint}`);
11224
+ return result;
11225
+ }
11226
+
11227
+ // packages/context/src/lib/store/postgres-store-database.ts
11228
+ var PostgresStoreDatabase = class _PostgresStoreDatabase {
11229
+ schema;
11230
+ #db;
11231
+ constructor(db, schema = "public") {
11232
+ if (!/^[a-zA-Z_]\w*$/.test(schema)) {
11233
+ throw new Error(`Invalid schema name: "${schema}"`);
11234
+ }
11235
+ this.schema = schema;
11236
+ this.#db = db;
11237
+ }
11238
+ /** The same schema, read and written inside `tx`. */
11239
+ bind(tx) {
11240
+ return new _PostgresStoreDatabase(tx, this.schema);
11241
+ }
11242
+ /** `name` qualified by the schema, quoted for SQL. */
11243
+ table(name) {
11244
+ return `"${this.schema}"."${name}"`;
11245
+ }
11246
+ query(text3, values) {
11247
+ const db = this.#db;
11248
+ return db.query(text3, values);
11249
+ }
11250
+ async rows(row, text3, values) {
11251
+ return z14.array(row).parse((await this.query(text3, values)).rows);
11252
+ }
11253
+ /**
11254
+ * Runs `fn` in a transaction: its own on the pool, or a savepoint of the
11255
+ * transaction this database is bound to.
11256
+ */
11257
+ transaction(fn) {
11258
+ return postgresTransaction(this.#db, fn);
11259
+ }
11260
+ };
11147
11261
 
11148
11262
  // packages/context/src/lib/store/postgres.store.ts
11149
- import { z as z14 } from "zod";
11263
+ import { z as z15 } from "zod";
11150
11264
 
11151
11265
  // packages/context/src/lib/store/ddl.postgres.ts
11152
11266
  function storeDDL(schema) {
@@ -11237,10 +11351,10 @@ CREATE TRIGGER "${schema}_messages_fts_vector_update"
11237
11351
  }
11238
11352
 
11239
11353
  // packages/context/src/lib/store/postgres.store.ts
11240
- var chatColumns2 = z14.object({
11241
- id: z14.string(),
11242
- userid: z14.string(),
11243
- title: z14.string().nullable(),
11354
+ var chatColumns2 = z15.object({
11355
+ id: z15.string(),
11356
+ userid: z15.string(),
11357
+ title: z15.string().nullable(),
11244
11358
  metadata: jsonObject.nullable(),
11245
11359
  createdat: bigintColumn,
11246
11360
  updatedat: bigintColumn
@@ -11251,27 +11365,27 @@ var chatInfo2 = chatColumns2.extend({ messagecount: bigintColumn, branchcount: b
11251
11365
  messageCount: row.messagecount,
11252
11366
  branchCount: row.branchcount
11253
11367
  }));
11254
- var messageColumns2 = z14.object({
11255
- id: z14.string(),
11256
- chatid: z14.string(),
11257
- parentid: z14.string().nullable(),
11258
- name: z14.string(),
11259
- type: z14.string().nullable(),
11260
- data: z14.unknown(),
11368
+ var messageColumns2 = z15.object({
11369
+ id: z15.string(),
11370
+ chatid: z15.string(),
11371
+ parentid: z15.string().nullable(),
11372
+ name: z15.string(),
11373
+ type: z15.string().nullable(),
11374
+ data: z15.unknown(),
11261
11375
  createdat: bigintColumn
11262
11376
  });
11263
11377
  var storedMessage2 = messageColumns2.transform(toMessage2);
11264
- var searchResult2 = messageColumns2.extend({ rank: z14.number(), snippet: z14.string() }).transform((row) => ({
11378
+ var searchResult2 = messageColumns2.extend({ rank: z15.number(), snippet: z15.string() }).transform((row) => ({
11265
11379
  message: toMessage2(row),
11266
11380
  rank: row.rank,
11267
11381
  snippet: row.snippet
11268
11382
  }));
11269
- var storedBranch2 = z14.object({
11270
- id: z14.string(),
11271
- chatid: z14.string(),
11272
- name: z14.string(),
11273
- headmessageid: z14.string().nullable(),
11274
- isactive: z14.boolean(),
11383
+ var storedBranch2 = z15.object({
11384
+ id: z15.string(),
11385
+ chatid: z15.string(),
11386
+ name: z15.string(),
11387
+ headmessageid: z15.string().nullable(),
11388
+ isactive: z15.boolean(),
11275
11389
  createdat: bigintColumn
11276
11390
  }).transform((row) => ({
11277
11391
  id: row.id,
@@ -11281,18 +11395,18 @@ var storedBranch2 = z14.object({
11281
11395
  isActive: row.isactive,
11282
11396
  createdAt: row.createdat
11283
11397
  }));
11284
- var branchRow = z14.object({
11285
- id: z14.string(),
11286
- name: z14.string(),
11287
- headmessageid: z14.string().nullable(),
11288
- isactive: z14.boolean(),
11398
+ var branchRow = z15.object({
11399
+ id: z15.string(),
11400
+ name: z15.string(),
11401
+ headmessageid: z15.string().nullable(),
11402
+ isactive: z15.boolean(),
11289
11403
  createdat: bigintColumn
11290
11404
  });
11291
- var storedCheckpoint2 = z14.object({
11292
- id: z14.string(),
11293
- chatid: z14.string(),
11294
- name: z14.string(),
11295
- messageid: z14.string(),
11405
+ var storedCheckpoint2 = z15.object({
11406
+ id: z15.string(),
11407
+ chatid: z15.string(),
11408
+ name: z15.string(),
11409
+ messageid: z15.string(),
11296
11410
  createdat: bigintColumn
11297
11411
  }).transform((row) => ({
11298
11412
  id: row.id,
@@ -11301,10 +11415,10 @@ var storedCheckpoint2 = z14.object({
11301
11415
  messageId: row.messageid,
11302
11416
  createdAt: row.createdat
11303
11417
  }));
11304
- var checkpointInfo2 = z14.object({
11305
- id: z14.string(),
11306
- name: z14.string(),
11307
- messageid: z14.string(),
11418
+ var checkpointInfo2 = z15.object({
11419
+ id: z15.string(),
11420
+ name: z15.string(),
11421
+ messageid: z15.string(),
11308
11422
  createdat: bigintColumn
11309
11423
  }).transform((row) => ({
11310
11424
  id: row.id,
@@ -11312,26 +11426,26 @@ var checkpointInfo2 = z14.object({
11312
11426
  messageId: row.messageid,
11313
11427
  createdAt: row.createdat
11314
11428
  }));
11315
- var idRow2 = z14.object({ id: z14.string() });
11316
- var existsRow = z14.object({ exists: z14.boolean() });
11317
- var countRow = z14.object({ count: bigintColumn });
11318
- var graphMessageRow2 = z14.object({
11319
- id: z14.string(),
11320
- parentid: z14.string().nullable(),
11321
- name: z14.string(),
11322
- data: z14.unknown(),
11429
+ var idRow2 = z15.object({ id: z15.string() });
11430
+ var existsRow = z15.object({ exists: z15.boolean() });
11431
+ var countRow = z15.object({ count: bigintColumn });
11432
+ var graphMessageRow2 = z15.object({
11433
+ id: z15.string(),
11434
+ parentid: z15.string().nullable(),
11435
+ name: z15.string(),
11436
+ data: z15.unknown(),
11323
11437
  createdat: bigintColumn
11324
11438
  });
11325
- var graphBranch2 = z14.object({
11326
- name: z14.string(),
11327
- headmessageid: z14.string().nullable(),
11328
- isactive: z14.boolean()
11439
+ var graphBranch2 = z15.object({
11440
+ name: z15.string(),
11441
+ headmessageid: z15.string().nullable(),
11442
+ isactive: z15.boolean()
11329
11443
  }).transform((row) => ({
11330
11444
  name: row.name,
11331
11445
  headMessageId: row.headmessageid,
11332
11446
  isActive: row.isactive
11333
11447
  }));
11334
- var graphCheckpoint2 = z14.object({ name: z14.string(), messageid: z14.string() }).transform((row) => ({
11448
+ var graphCheckpoint2 = z15.object({ name: z15.string(), messageid: z15.string() }).transform((row) => ({
11335
11449
  name: row.name,
11336
11450
  messageId: row.messageid
11337
11451
  }));
@@ -11357,49 +11471,30 @@ function toMessage2(row) {
11357
11471
  };
11358
11472
  }
11359
11473
  var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11360
- #pool;
11361
- #schema;
11362
- constructor(options) {
11474
+ #database;
11475
+ constructor(database) {
11363
11476
  super();
11364
- const schema = options.schema ?? "public";
11365
- if (!/^[a-zA-Z_]\w*$/.test(schema)) {
11366
- throw new Error(`Invalid schema name: "${schema}"`);
11367
- }
11368
- this.#schema = schema;
11369
- this.#pool = options.pool;
11370
- }
11371
- #t(name) {
11372
- return `"${this.#schema}"."${name}"`;
11477
+ this.#database = database;
11373
11478
  }
11374
11479
  /** Opens the store: creates its schema objects before it returns. */
11375
11480
  static async create(options) {
11376
- const store = new _PostgresContextStore(options);
11377
- await store.#initialize();
11378
- return store;
11379
- }
11380
- async #initialize() {
11381
- await this.#pool.query(lockSchemaDDL(storeDDL(this.#schema), this.#schema));
11382
- }
11383
- /**
11384
- * Execute a query using the pool (no transaction).
11385
- */
11386
- async #query(sql, params) {
11387
- const result = await this.#pool.query(sql, params);
11388
- return result.rows;
11481
+ const database = new PostgresStoreDatabase(options.pool, options.schema);
11482
+ await database.query(
11483
+ lockSchemaDDL(storeDDL(database.schema), database.schema)
11484
+ );
11485
+ return new _PostgresContextStore(database);
11389
11486
  }
11390
- /**
11391
- * Execute a query using the pool and parse every returned row.
11392
- */
11393
- async #rows(row, sql, params) {
11394
- return z14.array(row).parse(await this.#query(sql, params));
11487
+ /** A view of this store whose reads and writes run inside `tx`. */
11488
+ bind(tx) {
11489
+ return new _PostgresContextStore(this.#database.bind(tx));
11395
11490
  }
11396
11491
  // ==========================================================================
11397
11492
  // Chat Operations
11398
11493
  // ==========================================================================
11399
11494
  async createChat(chat2) {
11400
- return postgresTransaction(this.#pool, async (client) => {
11401
- const result = await client.query(
11402
- `INSERT INTO ${this.#t("chats")} (id, userId, title, metadata)
11495
+ return this.#database.transaction(async (tx) => {
11496
+ const result = await tx.query(
11497
+ `INSERT INTO ${this.#database.table("chats")} (id, userId, title, metadata)
11403
11498
  VALUES ($1, $2, $3, $4)
11404
11499
  RETURNING *`,
11405
11500
  [
@@ -11410,8 +11505,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11410
11505
  ]
11411
11506
  );
11412
11507
  const created = storedChat2.parse(result.rows[0]);
11413
- await client.query(
11414
- `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11508
+ await tx.query(
11509
+ `INSERT INTO ${this.#database.table("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11415
11510
  VALUES ($1, $2, 'main', NULL, TRUE, $3)`,
11416
11511
  [crypto.randomUUID(), chat2.id, Date.now()]
11417
11512
  );
@@ -11419,9 +11514,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11419
11514
  });
11420
11515
  }
11421
11516
  async upsertChat(chat2) {
11422
- return postgresTransaction(this.#pool, async (client) => {
11423
- const result = await client.query(
11424
- `INSERT INTO ${this.#t("chats")} (id, userId, title, metadata)
11517
+ return this.#database.transaction(async (tx) => {
11518
+ const result = await tx.query(
11519
+ `INSERT INTO ${this.#database.table("chats")} (id, userId, title, metadata)
11425
11520
  VALUES ($1, $2, $3, $4)
11426
11521
  ON CONFLICT(id) DO UPDATE SET id = EXCLUDED.id
11427
11522
  RETURNING *`,
@@ -11433,8 +11528,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11433
11528
  ]
11434
11529
  );
11435
11530
  const upserted = storedChat2.parse(result.rows[0]);
11436
- await client.query(
11437
- `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11531
+ await tx.query(
11532
+ `INSERT INTO ${this.#database.table("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11438
11533
  VALUES ($1, $2, 'main', NULL, TRUE, $3)
11439
11534
  ON CONFLICT(chatId, name) DO NOTHING`,
11440
11535
  [crypto.randomUUID(), chat2.id, Date.now()]
@@ -11443,17 +11538,17 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11443
11538
  });
11444
11539
  }
11445
11540
  async getChat(chatId) {
11446
- const [chat2] = await this.#rows(
11541
+ const [chat2] = await this.#database.rows(
11447
11542
  storedChat2,
11448
- `SELECT * FROM ${this.#t("chats")} WHERE id = $1`,
11543
+ `SELECT * FROM ${this.#database.table("chats")} WHERE id = $1`,
11449
11544
  [chatId]
11450
11545
  );
11451
11546
  return chat2;
11452
11547
  }
11453
11548
  async updateChat(chatId, update) {
11454
- return postgresTransaction(this.#pool, async (client) => {
11455
- const result = await client.query(
11456
- `SELECT * FROM ${this.#t("chats")} WHERE id = $1 FOR UPDATE`,
11549
+ return this.#database.transaction(async (tx) => {
11550
+ const result = await tx.query(
11551
+ `SELECT * FROM ${this.#database.table("chats")} WHERE id = $1 FOR UPDATE`,
11457
11552
  [chatId]
11458
11553
  );
11459
11554
  const current = storedChat2.optional().parse(result.rows[0]);
@@ -11476,8 +11571,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11476
11571
  params.push(JSON.stringify(updates.metadata));
11477
11572
  }
11478
11573
  params.push(chatId);
11479
- const updated = await client.query(
11480
- `UPDATE ${this.#t("chats")} SET ${setClauses.join(", ")} WHERE id = $${paramIndex} RETURNING *`,
11574
+ const updated = await tx.query(
11575
+ `UPDATE ${this.#database.table("chats")} SET ${setClauses.join(", ")} WHERE id = $${paramIndex} RETURNING *`,
11481
11576
  params
11482
11577
  );
11483
11578
  return storedChat2.parse(updated.rows[0]);
@@ -11508,7 +11603,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11508
11603
  params.push(options.offset);
11509
11604
  }
11510
11605
  }
11511
- return this.#rows(
11606
+ return this.#database.rows(
11512
11607
  chatInfo2,
11513
11608
  `SELECT
11514
11609
  c.id,
@@ -11519,9 +11614,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11519
11614
  c.updatedAt,
11520
11615
  COUNT(DISTINCT m.id) as messageCount,
11521
11616
  COUNT(DISTINCT b.id) as branchCount
11522
- FROM ${this.#t("chats")} c
11523
- LEFT JOIN ${this.#t("messages")} m ON m.chatId = c.id
11524
- LEFT JOIN ${this.#t("branches")} b ON b.chatId = c.id
11617
+ FROM ${this.#database.table("chats")} c
11618
+ LEFT JOIN ${this.#database.table("messages")} m ON m.chatId = c.id
11619
+ LEFT JOIN ${this.#database.table("branches")} b ON b.chatId = c.id
11525
11620
  ${whereClause}
11526
11621
  GROUP BY c.id
11527
11622
  ORDER BY c.updatedAt DESC${limitClause}`,
@@ -11529,14 +11624,14 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11529
11624
  );
11530
11625
  }
11531
11626
  async deleteChat(chatId, options) {
11532
- return postgresTransaction(this.#pool, async (client) => {
11533
- let sql = `DELETE FROM ${this.#t("chats")} WHERE id = $1`;
11627
+ return this.#database.transaction(async (tx) => {
11628
+ let sql = `DELETE FROM ${this.#database.table("chats")} WHERE id = $1`;
11534
11629
  const params = [chatId];
11535
11630
  if (options?.userId !== void 0) {
11536
11631
  sql += " AND userId = $2";
11537
11632
  params.push(options.userId);
11538
11633
  }
11539
- const result = await client.query(sql, params);
11634
+ const result = await tx.query(sql, params);
11540
11635
  return (result.rowCount ?? 0) > 0;
11541
11636
  });
11542
11637
  }
@@ -11547,9 +11642,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11547
11642
  if (message2.parentId === message2.id) {
11548
11643
  throw new Error(`Message ${message2.id} cannot be its own parent`);
11549
11644
  }
11550
- await postgresTransaction(this.#pool, async (client) => {
11551
- await client.query(
11552
- `INSERT INTO ${this.#t("messages")} (id, chatId, parentId, name, type, data, createdAt)
11645
+ await this.#database.transaction(async (tx) => {
11646
+ await tx.query(
11647
+ `INSERT INTO ${this.#database.table("messages")} (id, chatId, parentId, name, type, data, createdAt)
11553
11648
  VALUES ($1, $2, $3, $4, $5, $6, $7)
11554
11649
  ON CONFLICT(id) DO UPDATE SET
11555
11650
  name = EXCLUDED.name,
@@ -11566,8 +11661,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11566
11661
  ]
11567
11662
  );
11568
11663
  const content = typeof message2.data === "string" ? message2.data : JSON.stringify(message2.data);
11569
- await client.query(
11570
- `INSERT INTO ${this.#t("messages_fts")} (messageId, chatId, name, content)
11664
+ await tx.query(
11665
+ `INSERT INTO ${this.#database.table("messages_fts")} (messageId, chatId, name, content)
11571
11666
  VALUES ($1, $2, $3, $4)
11572
11667
  ON CONFLICT(messageId) DO UPDATE SET
11573
11668
  chatId = EXCLUDED.chatId,
@@ -11581,9 +11676,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11581
11676
  if (parentId === messageId) {
11582
11677
  throw new Error(`Message ${messageId} cannot be its own parent`);
11583
11678
  }
11584
- const rows = await this.#rows(
11679
+ const rows = await this.#database.rows(
11585
11680
  idRow2,
11586
- `UPDATE ${this.#t("messages")} SET parentId = $1 WHERE id = $2 RETURNING id`,
11681
+ `UPDATE ${this.#database.table("messages")} SET parentId = $1 WHERE id = $2 RETURNING id`,
11587
11682
  [parentId, messageId]
11588
11683
  );
11589
11684
  if (rows.length === 0) {
@@ -11591,20 +11686,20 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11591
11686
  }
11592
11687
  }
11593
11688
  async getMessage(messageId) {
11594
- const [message2] = await this.#rows(
11689
+ const [message2] = await this.#database.rows(
11595
11690
  storedMessage2,
11596
- `SELECT * FROM ${this.#t("messages")} WHERE id = $1`,
11691
+ `SELECT * FROM ${this.#database.table("messages")} WHERE id = $1`,
11597
11692
  [messageId]
11598
11693
  );
11599
11694
  return message2;
11600
11695
  }
11601
11696
  async getMessageChain(headId) {
11602
- return this.#rows(
11697
+ return this.#database.rows(
11603
11698
  storedMessage2,
11604
11699
  `WITH RECURSIVE chain AS (
11605
- SELECT *, 0 as depth FROM ${this.#t("messages")} WHERE id = $1
11700
+ SELECT *, 0 as depth FROM ${this.#database.table("messages")} WHERE id = $1
11606
11701
  UNION ALL
11607
- SELECT m.*, c.depth + 1 FROM ${this.#t("messages")} m
11702
+ SELECT m.*, c.depth + 1 FROM ${this.#database.table("messages")} m
11608
11703
  INNER JOIN chain c ON m.id = c.parentId
11609
11704
  WHERE c.depth < 10000
11610
11705
  )
@@ -11614,9 +11709,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11614
11709
  );
11615
11710
  }
11616
11711
  async hasChildren(messageId) {
11617
- const [row] = await this.#rows(
11712
+ const [row] = await this.#database.rows(
11618
11713
  existsRow,
11619
- `SELECT EXISTS(SELECT 1 FROM ${this.#t("messages")} WHERE parentId = $1) as exists`,
11714
+ `SELECT EXISTS(SELECT 1 FROM ${this.#database.table("messages")} WHERE parentId = $1) as exists`,
11620
11715
  [messageId]
11621
11716
  );
11622
11717
  return row.exists;
@@ -11636,8 +11731,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11636
11731
  // Branch Operations
11637
11732
  // ==========================================================================
11638
11733
  async createBranch(branch) {
11639
- await this.#query(
11640
- `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11734
+ await this.#database.query(
11735
+ `INSERT INTO ${this.#database.table("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11641
11736
  VALUES ($1, $2, $3, $4, $5, $6)`,
11642
11737
  [
11643
11738
  branch.id,
@@ -11650,37 +11745,37 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11650
11745
  );
11651
11746
  }
11652
11747
  async getBranch(chatId, name) {
11653
- const [branch] = await this.#rows(
11748
+ const [branch] = await this.#database.rows(
11654
11749
  storedBranch2,
11655
- `SELECT * FROM ${this.#t("branches")} WHERE chatId = $1 AND name = $2`,
11750
+ `SELECT * FROM ${this.#database.table("branches")} WHERE chatId = $1 AND name = $2`,
11656
11751
  [chatId, name]
11657
11752
  );
11658
11753
  return branch;
11659
11754
  }
11660
11755
  async getActiveBranch(chatId) {
11661
- const [branch] = await this.#rows(
11756
+ const [branch] = await this.#database.rows(
11662
11757
  storedBranch2,
11663
- `SELECT * FROM ${this.#t("branches")} WHERE chatId = $1 AND isActive = TRUE`,
11758
+ `SELECT * FROM ${this.#database.table("branches")} WHERE chatId = $1 AND isActive = TRUE`,
11664
11759
  [chatId]
11665
11760
  );
11666
11761
  return branch;
11667
11762
  }
11668
11763
  async setActiveBranch(chatId, branchId) {
11669
- await postgresTransaction(this.#pool, async (client) => {
11670
- await client.query(
11671
- `UPDATE ${this.#t("branches")} SET isActive = FALSE WHERE chatId = $1`,
11764
+ await this.#database.transaction(async (tx) => {
11765
+ await tx.query(
11766
+ `UPDATE ${this.#database.table("branches")} SET isActive = FALSE WHERE chatId = $1`,
11672
11767
  [chatId]
11673
11768
  );
11674
- await client.query(
11675
- `UPDATE ${this.#t("branches")} SET isActive = TRUE WHERE id = $1`,
11769
+ await tx.query(
11770
+ `UPDATE ${this.#database.table("branches")} SET isActive = TRUE WHERE id = $1`,
11676
11771
  [branchId]
11677
11772
  );
11678
11773
  });
11679
11774
  }
11680
11775
  async updateBranchHead(branchId, messageId, expectedHeadMessageId) {
11681
- const rows = await this.#rows(
11776
+ const rows = await this.#database.rows(
11682
11777
  idRow2,
11683
- `UPDATE ${this.#t("branches")} SET headMessageId = $1
11778
+ `UPDATE ${this.#database.table("branches")} SET headMessageId = $1
11684
11779
  WHERE id = $2 AND headMessageId IS NOT DISTINCT FROM $3
11685
11780
  RETURNING id`,
11686
11781
  [messageId, branchId, expectedHeadMessageId]
@@ -11688,7 +11783,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11688
11783
  return rows.length > 0;
11689
11784
  }
11690
11785
  async listBranches(chatId) {
11691
- const branches = await this.#rows(
11786
+ const branches = await this.#database.rows(
11692
11787
  branchRow,
11693
11788
  `SELECT
11694
11789
  id,
@@ -11696,7 +11791,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11696
11791
  headMessageId,
11697
11792
  isActive,
11698
11793
  createdAt
11699
- FROM ${this.#t("branches")}
11794
+ FROM ${this.#database.table("branches")}
11700
11795
  WHERE chatId = $1
11701
11796
  ORDER BY createdAt ASC`,
11702
11797
  [chatId]
@@ -11715,12 +11810,12 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11715
11810
  return result;
11716
11811
  }
11717
11812
  async #countChain(headMessageId) {
11718
- const [row] = await this.#rows(
11813
+ const [row] = await this.#database.rows(
11719
11814
  countRow,
11720
11815
  `WITH RECURSIVE chain AS (
11721
- SELECT id, parentId FROM ${this.#t("messages")} WHERE id = $1
11816
+ SELECT id, parentId FROM ${this.#database.table("messages")} WHERE id = $1
11722
11817
  UNION ALL
11723
- SELECT m.id, m.parentId FROM ${this.#t("messages")} m
11818
+ SELECT m.id, m.parentId FROM ${this.#database.table("messages")} m
11724
11819
  INNER JOIN chain c ON m.id = c.parentId
11725
11820
  )
11726
11821
  SELECT COUNT(*) as count FROM chain`,
@@ -11732,8 +11827,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11732
11827
  // Checkpoint Operations
11733
11828
  // ==========================================================================
11734
11829
  async createCheckpoint(checkpoint) {
11735
- await this.#query(
11736
- `INSERT INTO ${this.#t("checkpoints")} (id, chatId, name, messageId, createdAt)
11830
+ await this.#database.query(
11831
+ `INSERT INTO ${this.#database.table("checkpoints")} (id, chatId, name, messageId, createdAt)
11737
11832
  VALUES ($1, $2, $3, $4, $5)
11738
11833
  ON CONFLICT(chatId, name) DO UPDATE SET
11739
11834
  messageId = EXCLUDED.messageId,
@@ -11748,26 +11843,26 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11748
11843
  );
11749
11844
  }
11750
11845
  async getCheckpoint(chatId, name) {
11751
- const [checkpoint] = await this.#rows(
11846
+ const [checkpoint] = await this.#database.rows(
11752
11847
  storedCheckpoint2,
11753
- `SELECT * FROM ${this.#t("checkpoints")} WHERE chatId = $1 AND name = $2`,
11848
+ `SELECT * FROM ${this.#database.table("checkpoints")} WHERE chatId = $1 AND name = $2`,
11754
11849
  [chatId, name]
11755
11850
  );
11756
11851
  return checkpoint;
11757
11852
  }
11758
11853
  async listCheckpoints(chatId) {
11759
- return this.#rows(
11854
+ return this.#database.rows(
11760
11855
  checkpointInfo2,
11761
11856
  `SELECT id, name, messageId, createdAt
11762
- FROM ${this.#t("checkpoints")}
11857
+ FROM ${this.#database.table("checkpoints")}
11763
11858
  WHERE chatId = $1
11764
11859
  ORDER BY createdAt DESC`,
11765
11860
  [chatId]
11766
11861
  );
11767
11862
  }
11768
11863
  async deleteCheckpoint(chatId, name) {
11769
- await this.#query(
11770
- `DELETE FROM ${this.#t("checkpoints")} WHERE chatId = $1 AND name = $2`,
11864
+ await this.#database.query(
11865
+ `DELETE FROM ${this.#database.table("checkpoints")} WHERE chatId = $1 AND name = $2`,
11771
11866
  [chatId, name]
11772
11867
  );
11773
11868
  }
@@ -11789,8 +11884,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11789
11884
  ts_rank(fts.content_vector, plainto_tsquery('english', $2)) as rank,
11790
11885
  ts_headline('english', fts.content, plainto_tsquery('english', $2),
11791
11886
  'StartSel=<mark>, StopSel=</mark>, MaxWords=32, MinWords=5, MaxFragments=1') as snippet
11792
- FROM ${this.#t("messages_fts")} fts
11793
- JOIN ${this.#t("messages")} m ON m.id = fts.messageId
11887
+ FROM ${this.#database.table("messages_fts")} fts
11888
+ JOIN ${this.#database.table("messages")} m ON m.id = fts.messageId
11794
11889
  WHERE fts.content_vector @@ plainto_tsquery('english', $2)
11795
11890
  AND fts.chatId = $1
11796
11891
  `;
@@ -11803,16 +11898,16 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11803
11898
  }
11804
11899
  sql += ` ORDER BY rank DESC LIMIT $${paramIndex}`;
11805
11900
  params.push(limit);
11806
- return this.#rows(searchResult2, sql, params);
11901
+ return this.#database.rows(searchResult2, sql, params);
11807
11902
  }
11808
11903
  // ==========================================================================
11809
11904
  // Visualization Operations
11810
11905
  // ==========================================================================
11811
11906
  async getGraph(chatId) {
11812
- const messageRows = await this.#rows(
11907
+ const messageRows = await this.#database.rows(
11813
11908
  graphMessageRow2,
11814
11909
  `SELECT id, parentId, name, data, createdAt
11815
- FROM ${this.#t("messages")}
11910
+ FROM ${this.#database.table("messages")}
11816
11911
  WHERE chatId = $1
11817
11912
  ORDER BY createdAt ASC`,
11818
11913
  [chatId]
@@ -11828,18 +11923,18 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11828
11923
  createdAt: row.createdat
11829
11924
  };
11830
11925
  });
11831
- const branches = await this.#rows(
11926
+ const branches = await this.#database.rows(
11832
11927
  graphBranch2,
11833
11928
  `SELECT name, headMessageId, isActive
11834
- FROM ${this.#t("branches")}
11929
+ FROM ${this.#database.table("branches")}
11835
11930
  WHERE chatId = $1
11836
11931
  ORDER BY createdAt ASC`,
11837
11932
  [chatId]
11838
11933
  );
11839
- const checkpoints = await this.#rows(
11934
+ const checkpoints = await this.#database.rows(
11840
11935
  graphCheckpoint2,
11841
11936
  `SELECT name, messageId
11842
- FROM ${this.#t("checkpoints")}
11937
+ FROM ${this.#database.table("checkpoints")}
11843
11938
  WHERE chatId = $1
11844
11939
  ORDER BY createdAt ASC`,
11845
11940
  [chatId]
@@ -11855,7 +11950,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11855
11950
 
11856
11951
  // packages/context/src/lib/store/sqlserver.store.ts
11857
11952
  import { createRequire } from "node:module";
11858
- import { z as z15 } from "zod";
11953
+ import { z as z16 } from "zod";
11859
11954
 
11860
11955
  // packages/context/src/lib/store/ddl.sqlserver.ts
11861
11956
  function storeDDL2(schema) {
@@ -12015,82 +12110,82 @@ async function withSqlServerSchemaLock(mssql, pool, schema, run) {
12015
12110
  }
12016
12111
 
12017
12112
  // packages/context/src/lib/store/sqlserver.store.ts
12018
- var chatColumns3 = z15.object({
12019
- id: z15.string(),
12020
- userId: z15.string(),
12021
- title: z15.string().nullable(),
12022
- metadata: z15.string().nullable(),
12113
+ var chatColumns3 = z16.object({
12114
+ id: z16.string(),
12115
+ userId: z16.string(),
12116
+ title: z16.string().nullable(),
12117
+ metadata: z16.string().nullable(),
12023
12118
  createdAt: bigintColumn,
12024
12119
  updatedAt: bigintColumn
12025
12120
  });
12026
12121
  var storedChat3 = chatColumns3.transform(toStoredChat3);
12027
- var chatInfo3 = chatColumns3.extend({ messageCount: z15.number(), branchCount: z15.number() }).transform((row) => ({
12122
+ var chatInfo3 = chatColumns3.extend({ messageCount: z16.number(), branchCount: z16.number() }).transform((row) => ({
12028
12123
  ...toStoredChat3(row),
12029
12124
  messageCount: row.messageCount,
12030
12125
  branchCount: row.branchCount
12031
12126
  }));
12032
- var messageColumns3 = z15.object({
12033
- id: z15.string(),
12034
- chatId: z15.string(),
12035
- parentId: z15.string().nullable(),
12036
- name: z15.string(),
12037
- type: z15.string().nullable(),
12038
- data: z15.string(),
12127
+ var messageColumns3 = z16.object({
12128
+ id: z16.string(),
12129
+ chatId: z16.string(),
12130
+ parentId: z16.string().nullable(),
12131
+ name: z16.string(),
12132
+ type: z16.string().nullable(),
12133
+ data: z16.string(),
12039
12134
  createdAt: bigintColumn
12040
12135
  });
12041
12136
  var storedMessage3 = messageColumns3.transform(toMessage3);
12042
- var searchResult3 = messageColumns3.extend({ rank: z15.number(), snippet: z15.string() }).transform((row) => ({
12137
+ var searchResult3 = messageColumns3.extend({ rank: z16.number(), snippet: z16.string() }).transform((row) => ({
12043
12138
  message: toMessage3(row),
12044
12139
  rank: row.rank,
12045
12140
  snippet: row.snippet
12046
12141
  }));
12047
- var storedBranch3 = z15.object({
12048
- id: z15.string(),
12049
- chatId: z15.string(),
12050
- name: z15.string(),
12051
- headMessageId: z15.string().nullable(),
12052
- isActive: z15.boolean(),
12142
+ var storedBranch3 = z16.object({
12143
+ id: z16.string(),
12144
+ chatId: z16.string(),
12145
+ name: z16.string(),
12146
+ headMessageId: z16.string().nullable(),
12147
+ isActive: z16.boolean(),
12053
12148
  createdAt: bigintColumn
12054
12149
  });
12055
- var branchRow2 = z15.object({
12056
- id: z15.string(),
12057
- name: z15.string(),
12058
- headMessageId: z15.string().nullable(),
12059
- isActive: z15.boolean(),
12150
+ var branchRow2 = z16.object({
12151
+ id: z16.string(),
12152
+ name: z16.string(),
12153
+ headMessageId: z16.string().nullable(),
12154
+ isActive: z16.boolean(),
12060
12155
  createdAt: bigintColumn
12061
12156
  });
12062
- var storedCheckpoint3 = z15.object({
12063
- id: z15.string(),
12064
- chatId: z15.string(),
12065
- name: z15.string(),
12066
- messageId: z15.string(),
12157
+ var storedCheckpoint3 = z16.object({
12158
+ id: z16.string(),
12159
+ chatId: z16.string(),
12160
+ name: z16.string(),
12161
+ messageId: z16.string(),
12067
12162
  createdAt: bigintColumn
12068
12163
  });
12069
- var checkpointInfo3 = z15.object({
12070
- id: z15.string(),
12071
- name: z15.string(),
12072
- messageId: z15.string(),
12164
+ var checkpointInfo3 = z16.object({
12165
+ id: z16.string(),
12166
+ name: z16.string(),
12167
+ messageId: z16.string(),
12073
12168
  createdAt: bigintColumn
12074
12169
  });
12075
- var idRow3 = z15.object({ id: z15.string() });
12076
- var hasChildrenRow2 = z15.object({ hasChildren: z15.number() });
12077
- var countRow2 = z15.object({ count: z15.number() });
12078
- var ftsInstalledRow = z15.object({ ftsInstalled: z15.number().nullable() });
12079
- var graphMessageRow3 = z15.object({
12080
- id: z15.string(),
12081
- parentId: z15.string().nullable(),
12082
- name: z15.string(),
12083
- data: z15.string(),
12170
+ var idRow3 = z16.object({ id: z16.string() });
12171
+ var hasChildrenRow2 = z16.object({ hasChildren: z16.number() });
12172
+ var countRow2 = z16.object({ count: z16.number() });
12173
+ var ftsInstalledRow = z16.object({ ftsInstalled: z16.number().nullable() });
12174
+ var graphMessageRow3 = z16.object({
12175
+ id: z16.string(),
12176
+ parentId: z16.string().nullable(),
12177
+ name: z16.string(),
12178
+ data: z16.string(),
12084
12179
  createdAt: bigintColumn
12085
12180
  });
12086
- var graphBranch3 = z15.object({
12087
- name: z15.string(),
12088
- headMessageId: z15.string().nullable(),
12089
- isActive: z15.boolean()
12181
+ var graphBranch3 = z16.object({
12182
+ name: z16.string(),
12183
+ headMessageId: z16.string().nullable(),
12184
+ isActive: z16.boolean()
12090
12185
  });
12091
- var graphCheckpoint3 = z15.object({
12092
- name: z15.string(),
12093
- messageId: z15.string()
12186
+ var graphCheckpoint3 = z16.object({
12187
+ name: z16.string(),
12188
+ messageId: z16.string()
12094
12189
  });
12095
12190
  function toStoredChat3(row) {
12096
12191
  return {
@@ -12218,7 +12313,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12218
12313
  * Execute a query using the pool and parse every returned row.
12219
12314
  */
12220
12315
  async #rows(row, sql, params) {
12221
- return z15.array(row).parse(await this.#query(sql, params));
12316
+ return z16.array(row).parse(await this.#query(sql, params));
12222
12317
  }
12223
12318
  /**
12224
12319
  * Close the pool connection.
@@ -13076,7 +13171,7 @@ function staticPartText(part, options) {
13076
13171
  // packages/context/src/lib/stream/postgres-notify-change-source.ts
13077
13172
  import { EventEmitter, on } from "node:events";
13078
13173
  import pMemoize3 from "p-memoize";
13079
- import { z as z16 } from "zod";
13174
+ import { z as z17 } from "zod";
13080
13175
 
13081
13176
  // packages/context/src/lib/stream/ddl.stream.postgres-notify.ts
13082
13177
  var DEFAULT_POSTGRES_STREAM_CHANGES_CHANNEL = "deepagents_stream_changes";
@@ -13308,10 +13403,10 @@ var PostgresNotifyChangeSource = class _PostgresNotifyChangeSource {
13308
13403
  await listener.release(this.#channel);
13309
13404
  }
13310
13405
  };
13311
- var notificationPayload = z16.object({
13312
- schema: z16.string(),
13313
- streamId: z16.string(),
13314
- kind: z16.string()
13406
+ var notificationPayload = z17.object({
13407
+ schema: z17.string(),
13408
+ streamId: z17.string(),
13409
+ kind: z17.string()
13315
13410
  });
13316
13411
  function parsePayload(payload) {
13317
13412
  try {
@@ -13331,7 +13426,7 @@ function assertIdentifier(value, label) {
13331
13426
  }
13332
13427
 
13333
13428
  // packages/context/src/lib/stream/postgres.stream-store.ts
13334
- import { z as z18 } from "zod";
13429
+ import { z as z19 } from "zod";
13335
13430
 
13336
13431
  // packages/context/src/lib/stream/ddl.stream.postgres.ts
13337
13432
  function postgresStreamDDL(schema) {
@@ -13369,8 +13464,8 @@ CREATE INDEX IF NOT EXISTS "idx_${schema}_streams_status_created_at_id"
13369
13464
  // packages/context/src/lib/stream/rows.ts
13370
13465
  import { validateTypes } from "@ai-sdk/provider-utils";
13371
13466
  import { uiMessageChunkSchema } from "ai";
13372
- import { z as z17 } from "zod";
13373
- var streamStatus = z17.enum([
13467
+ import { z as z18 } from "zod";
13468
+ var streamStatus = z18.enum([
13374
13469
  "queued",
13375
13470
  "running",
13376
13471
  "completed",
@@ -13382,14 +13477,14 @@ function toStreamPart(value) {
13382
13477
  }
13383
13478
 
13384
13479
  // packages/context/src/lib/stream/postgres.stream-store.ts
13385
- var storedStream = z18.object({
13386
- id: z18.string(),
13480
+ var storedStream = z19.object({
13481
+ id: z19.string(),
13387
13482
  status: streamStatus,
13388
13483
  created_at: bigintColumn,
13389
13484
  started_at: bigintColumn.nullable(),
13390
13485
  finished_at: bigintColumn.nullable(),
13391
13486
  cancel_requested_at: bigintColumn.nullable(),
13392
- error: z18.string().nullable()
13487
+ error: z19.string().nullable()
13393
13488
  }).transform((row) => ({
13394
13489
  id: row.id,
13395
13490
  status: row.status,
@@ -13399,57 +13494,44 @@ var storedStream = z18.object({
13399
13494
  cancelRequestedAt: row.cancel_requested_at,
13400
13495
  error: row.error
13401
13496
  }));
13402
- var statusRow = z18.object({ status: streamStatus });
13403
- var idRow4 = z18.object({ id: z18.string() });
13404
- var chunkRow = z18.object({
13405
- stream_id: z18.string(),
13406
- seq: z18.number(),
13407
- data: z18.unknown(),
13497
+ var statusRow = z19.object({ status: streamStatus });
13498
+ var idRow4 = z19.object({ id: z19.string() });
13499
+ var chunkRow = z19.object({
13500
+ stream_id: z19.string(),
13501
+ seq: z19.number(),
13502
+ data: z19.unknown(),
13408
13503
  created_at: bigintColumn
13409
13504
  });
13410
13505
  var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13411
- #pool;
13412
- #schema;
13413
- constructor(options) {
13506
+ #database;
13507
+ constructor(database) {
13414
13508
  super();
13415
- const schema = options.schema ?? "public";
13416
- assertIdentifier2(schema, "schema");
13417
- this.#schema = schema;
13418
- this.#pool = options.pool;
13419
- }
13420
- #t(name) {
13421
- return `"${this.#schema}"."${name}"`;
13509
+ this.#database = database;
13422
13510
  }
13423
13511
  /** Opens the store: creates its tables before it returns. */
13424
13512
  static async create(options) {
13425
- const store = new _PostgresStreamStore(options);
13426
- await store.#initialize();
13427
- return store;
13428
- }
13429
- async #initialize() {
13430
- await this.#pool.query(
13431
- lockSchemaDDL(postgresStreamDDL(this.#schema), this.#schema)
13513
+ const database = new PostgresStoreDatabase(options.pool, options.schema);
13514
+ await database.query(
13515
+ lockSchemaDDL(postgresStreamDDL(database.schema), database.schema)
13432
13516
  );
13517
+ return new _PostgresStreamStore(database);
13433
13518
  }
13434
- async #query(sql, params) {
13435
- const result = await this.#pool.query(sql, params);
13436
- return result.rows;
13437
- }
13438
- async #rows(row, sql, params) {
13439
- return z18.array(row).parse(await this.#query(sql, params));
13519
+ /** A view of this store whose reads and writes run inside `tx`. */
13520
+ bind(tx) {
13521
+ return new _PostgresStreamStore(this.#database.bind(tx));
13440
13522
  }
13441
13523
  async createStream(stream) {
13442
- await this.#query(
13443
- `INSERT INTO ${this.#t("streams")}
13524
+ await this.#database.query(
13525
+ `INSERT INTO ${this.#database.table("streams")}
13444
13526
  (id, status, created_at, started_at, finished_at, cancel_requested_at, error)
13445
13527
  VALUES ($1, $2, $3, $4, $5, $6, $7)`,
13446
13528
  streamParams(stream)
13447
13529
  );
13448
13530
  }
13449
13531
  async upsertStream(stream) {
13450
- const [created] = await this.#rows(
13532
+ const [created] = await this.#database.rows(
13451
13533
  storedStream,
13452
- `INSERT INTO ${this.#t("streams")}
13534
+ `INSERT INTO ${this.#database.table("streams")}
13453
13535
  (id, status, created_at, started_at, finished_at, cancel_requested_at, error)
13454
13536
  VALUES ($1, $2, $3, $4, $5, $6, $7)
13455
13537
  ON CONFLICT(id) DO NOTHING
@@ -13468,36 +13550,36 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13468
13550
  return { stream: existing, created: false };
13469
13551
  }
13470
13552
  async getStream(streamId) {
13471
- const [found] = await this.#rows(
13553
+ const [found] = await this.#database.rows(
13472
13554
  storedStream,
13473
- `SELECT * FROM ${this.#t("streams")} WHERE id = $1`,
13555
+ `SELECT * FROM ${this.#database.table("streams")} WHERE id = $1`,
13474
13556
  [streamId]
13475
13557
  );
13476
13558
  return found;
13477
13559
  }
13478
13560
  async getStreamStatus(streamId) {
13479
- const rows = await this.#rows(
13561
+ const rows = await this.#database.rows(
13480
13562
  statusRow,
13481
- `SELECT status FROM ${this.#t("streams")} WHERE id = $1`,
13563
+ `SELECT status FROM ${this.#database.table("streams")} WHERE id = $1`,
13482
13564
  [streamId]
13483
13565
  );
13484
13566
  return rows[0]?.status;
13485
13567
  }
13486
13568
  async listStreamIds(options) {
13487
13569
  const params = [];
13488
- let sql = `SELECT id FROM ${this.#t("streams")}`;
13570
+ let sql = `SELECT id FROM ${this.#database.table("streams")}`;
13489
13571
  if (options?.status) {
13490
13572
  params.push(options.status);
13491
13573
  sql += ` WHERE status = $${params.length}`;
13492
13574
  }
13493
13575
  sql += " ORDER BY created_at ASC, id ASC";
13494
- const rows = await this.#rows(idRow4, sql, params);
13576
+ const rows = await this.#database.rows(idRow4, sql, params);
13495
13577
  return rows.map((row) => row.id);
13496
13578
  }
13497
13579
  async updateStream(streamId, update) {
13498
- return postgresTransaction(this.#pool, async (client) => {
13499
- const selected = await client.query(
13500
- `SELECT * FROM ${this.#t("streams")} WHERE id = $1 FOR UPDATE`,
13580
+ return this.#database.transaction(async (tx) => {
13581
+ const selected = await tx.query(
13582
+ `SELECT * FROM ${this.#database.table("streams")} WHERE id = $1 FOR UPDATE`,
13501
13583
  [streamId]
13502
13584
  );
13503
13585
  const stream = storedStream.optional().parse(selected.rows[0]);
@@ -13523,8 +13605,8 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13523
13605
  if (updates.error !== void 0) set("error", updates.error);
13524
13606
  if (setClauses.length === 0) return { stream, updated: false };
13525
13607
  params.push(streamId);
13526
- const updated = await client.query(
13527
- `UPDATE ${this.#t("streams")}
13608
+ const updated = await tx.query(
13609
+ `UPDATE ${this.#database.table("streams")}
13528
13610
  SET ${setClauses.join(", ")}
13529
13611
  WHERE id = $${params.length}
13530
13612
  RETURNING *`,
@@ -13537,40 +13619,40 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13537
13619
  const now = Date.now();
13538
13620
  switch (status) {
13539
13621
  case "running":
13540
- await this.#query(
13541
- `UPDATE ${this.#t("streams")}
13622
+ await this.#database.query(
13623
+ `UPDATE ${this.#database.table("streams")}
13542
13624
  SET status = $1, started_at = $2
13543
13625
  WHERE id = $3 AND status = 'queued'`,
13544
13626
  [status, now, streamId]
13545
13627
  );
13546
13628
  break;
13547
13629
  case "completed":
13548
- await this.#query(
13549
- `UPDATE ${this.#t("streams")}
13630
+ await this.#database.query(
13631
+ `UPDATE ${this.#database.table("streams")}
13550
13632
  SET status = $1, finished_at = $2
13551
13633
  WHERE id = $3 AND status IN ('queued', 'running')`,
13552
13634
  [status, now, streamId]
13553
13635
  );
13554
13636
  break;
13555
13637
  case "failed":
13556
- await this.#query(
13557
- `UPDATE ${this.#t("streams")}
13638
+ await this.#database.query(
13639
+ `UPDATE ${this.#database.table("streams")}
13558
13640
  SET status = $1, finished_at = $2, error = $3
13559
13641
  WHERE id = $4 AND status IN ('queued', 'running')`,
13560
13642
  [status, now, options?.error ?? null, streamId]
13561
13643
  );
13562
13644
  break;
13563
13645
  case "cancelled":
13564
- await this.#query(
13565
- `UPDATE ${this.#t("streams")}
13646
+ await this.#database.query(
13647
+ `UPDATE ${this.#database.table("streams")}
13566
13648
  SET status = $1, cancel_requested_at = $2, finished_at = $3
13567
13649
  WHERE id = $4 AND status IN ('queued', 'running')`,
13568
13650
  [status, now, now, streamId]
13569
13651
  );
13570
13652
  break;
13571
13653
  default:
13572
- await this.#query(
13573
- `UPDATE ${this.#t("streams")}
13654
+ await this.#database.query(
13655
+ `UPDATE ${this.#database.table("streams")}
13574
13656
  SET status = $1
13575
13657
  WHERE id = $2 AND status = 'queued'`,
13576
13658
  [status, streamId]
@@ -13586,28 +13668,28 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13586
13668
  created_at: chunk.createdAt
13587
13669
  }));
13588
13670
  const params = [JSON.stringify(rows)];
13589
- const insertSql = `INSERT INTO ${this.#t("stream_chunks")} (stream_id, seq, data, created_at)
13671
+ const insertSql = `INSERT INTO ${this.#database.table("stream_chunks")} (stream_id, seq, data, created_at)
13590
13672
  SELECT stream_id, seq, data, created_at
13591
13673
  FROM jsonb_to_recordset($1::jsonb)
13592
13674
  AS rows(stream_id TEXT, seq INTEGER, data JSONB, created_at BIGINT)`;
13593
13675
  const failures = collectStreamFailures(chunks);
13594
13676
  if (failures.length === 0) {
13595
- await this.#query(insertSql, params);
13677
+ await this.#database.query(insertSql, params);
13596
13678
  return;
13597
13679
  }
13598
- await postgresTransaction(this.#pool, async (client) => {
13599
- await client.query(insertSql, params);
13680
+ await this.#database.transaction(async (tx) => {
13681
+ await tx.query(insertSql, params);
13600
13682
  const failedAt = Date.now();
13601
13683
  for (const failure of failures) {
13602
- const result = await client.query(
13603
- `UPDATE ${this.#t("streams")}
13684
+ const result = await tx.query(
13685
+ `UPDATE ${this.#database.table("streams")}
13604
13686
  SET status = $1, finished_at = $2, error = $3
13605
13687
  WHERE id = $4 AND status IN ('queued', 'running')`,
13606
13688
  ["failed", failedAt, failure.error, failure.streamId]
13607
13689
  );
13608
13690
  if (result.rowCount !== 1) {
13609
- const existing = await client.query(
13610
- `SELECT id FROM ${this.#t("streams")} WHERE id = $1`,
13691
+ const existing = await tx.query(
13692
+ `SELECT id FROM ${this.#database.table("streams")} WHERE id = $1`,
13611
13693
  [failure.streamId]
13612
13694
  );
13613
13695
  if (existing.rowCount !== 1) {
@@ -13619,7 +13701,7 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13619
13701
  }
13620
13702
  async getChunks(streamId, fromSeq, limit) {
13621
13703
  const params = [streamId];
13622
- let sql = `SELECT * FROM ${this.#t("stream_chunks")} WHERE stream_id = $1`;
13704
+ let sql = `SELECT * FROM ${this.#database.table("stream_chunks")} WHERE stream_id = $1`;
13623
13705
  if (fromSeq !== void 0) {
13624
13706
  params.push(fromSeq);
13625
13707
  sql += ` AND seq >= $${params.length}`;
@@ -13629,7 +13711,7 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13629
13711
  params.push(limit);
13630
13712
  sql += ` LIMIT $${params.length}`;
13631
13713
  }
13632
- const rows = await this.#rows(chunkRow, sql, params);
13714
+ const rows = await this.#database.rows(chunkRow, sql, params);
13633
13715
  return Promise.all(
13634
13716
  rows.map(async (row) => ({
13635
13717
  streamId: row.stream_id,
@@ -13640,14 +13722,15 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13640
13722
  );
13641
13723
  }
13642
13724
  async deleteStream(streamId) {
13643
- await this.#query(`DELETE FROM ${this.#t("streams")} WHERE id = $1`, [
13644
- streamId
13645
- ]);
13725
+ await this.#database.query(
13726
+ `DELETE FROM ${this.#database.table("streams")} WHERE id = $1`,
13727
+ [streamId]
13728
+ );
13646
13729
  }
13647
13730
  async reopenStream(streamId) {
13648
- return postgresTransaction(this.#pool, async (client) => {
13649
- const result = await client.query(
13650
- `SELECT * FROM ${this.#t("streams")} WHERE id = $1 FOR UPDATE`,
13731
+ return this.#database.transaction(async (tx) => {
13732
+ const result = await tx.query(
13733
+ `SELECT * FROM ${this.#database.table("streams")} WHERE id = $1 FOR UPDATE`,
13651
13734
  [streamId]
13652
13735
  );
13653
13736
  const row = statusRow.optional().parse(result.rows[0]);
@@ -13659,9 +13742,10 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13659
13742
  `Cannot reopen stream "${streamId}" with status "${row.status}". Only terminal streams can be reopened.`
13660
13743
  );
13661
13744
  }
13662
- await client.query(`DELETE FROM ${this.#t("streams")} WHERE id = $1`, [
13663
- streamId
13664
- ]);
13745
+ await tx.query(
13746
+ `DELETE FROM ${this.#database.table("streams")} WHERE id = $1`,
13747
+ [streamId]
13748
+ );
13665
13749
  const now = Date.now();
13666
13750
  const stream = {
13667
13751
  id: streamId,
@@ -13672,8 +13756,8 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13672
13756
  cancelRequestedAt: null,
13673
13757
  error: null
13674
13758
  };
13675
- await client.query(
13676
- `INSERT INTO ${this.#t("streams")}
13759
+ await tx.query(
13760
+ `INSERT INTO ${this.#database.table("streams")}
13677
13761
  (id, status, created_at, started_at, finished_at, cancel_requested_at, error)
13678
13762
  VALUES ($1, $2, $3, $4, $5, $6, $7)`,
13679
13763
  streamParams(stream)
@@ -13696,17 +13780,12 @@ function streamParams(stream) {
13696
13780
  function isTerminal2(status) {
13697
13781
  return status !== "queued" && status !== "running";
13698
13782
  }
13699
- function assertIdentifier2(value, label) {
13700
- if (!/^[a-zA-Z_]\w*$/.test(value)) {
13701
- throw new Error(`Invalid ${label} name: "${value}"`);
13702
- }
13703
- }
13704
13783
 
13705
13784
  // packages/context/src/lib/stream/sqlite.stream-store.ts
13706
13785
  import { Declaration as Declaration2 } from "@zukhruf/sqlite-drift";
13707
13786
  import { open as open2 } from "@zukhruf/sqlite-open";
13708
13787
  import { transaction as transaction2 } from "@zukhruf/sqlite-transaction";
13709
- import { z as z19 } from "zod";
13788
+ import { z as z20 } from "zod";
13710
13789
 
13711
13790
  // packages/context/src/lib/stream/ddl.stream.sqlite.ts
13712
13791
  var SETUP2 = `
@@ -13741,22 +13820,22 @@ var statements2 = [
13741
13820
 
13742
13821
  // packages/context/src/lib/stream/sqlite.stream-store.ts
13743
13822
  var tables2 = new Declaration2(statements2, { rows: "keep" });
13744
- var streamRow = z19.object({
13745
- id: z19.string(),
13823
+ var streamRow = z20.object({
13824
+ id: z20.string(),
13746
13825
  status: streamStatus,
13747
- createdAt: z19.number(),
13748
- startedAt: z19.number().nullable(),
13749
- finishedAt: z19.number().nullable(),
13750
- cancelRequestedAt: z19.number().nullable(),
13751
- error: z19.string().nullable()
13826
+ createdAt: z20.number(),
13827
+ startedAt: z20.number().nullable(),
13828
+ finishedAt: z20.number().nullable(),
13829
+ cancelRequestedAt: z20.number().nullable(),
13830
+ error: z20.string().nullable()
13752
13831
  });
13753
- var statusRow2 = z19.object({ status: streamStatus });
13754
- var idRow5 = z19.object({ id: z19.string() });
13755
- var chunkRow2 = z19.object({
13756
- streamId: z19.string(),
13757
- seq: z19.number(),
13758
- data: z19.string(),
13759
- createdAt: z19.number()
13832
+ var statusRow2 = z20.object({ status: streamStatus });
13833
+ var idRow5 = z20.object({ id: z20.string() });
13834
+ var chunkRow2 = z20.object({
13835
+ streamId: z20.string(),
13836
+ seq: z20.number(),
13837
+ data: z20.string(),
13838
+ createdAt: z20.number()
13760
13839
  });
13761
13840
  var SqliteStreamStore = class extends StreamStore {
13762
13841
  #db;
@@ -13802,7 +13881,7 @@ var SqliteStreamStore = class extends StreamStore {
13802
13881
  return row?.status;
13803
13882
  }
13804
13883
  async listStreamIds(options) {
13805
- const rows = z19.array(idRow5).parse(
13884
+ const rows = z20.array(idRow5).parse(
13806
13885
  options?.status ? this.#sql.all`SELECT id FROM streams WHERE status = ${options.status} ORDER BY createdAt ASC, id ASC` : this.#sql.all`SELECT id FROM streams ORDER BY createdAt ASC, id ASC`
13807
13886
  );
13808
13887
  return rows.map((row) => row.id);
@@ -13895,7 +13974,7 @@ var SqliteStreamStore = class extends StreamStore {
13895
13974
  );
13896
13975
  }
13897
13976
  async getChunks(streamId, fromSeq, limit) {
13898
- const rows = z19.array(chunkRow2).parse(this.#chunkRows(streamId, fromSeq, limit));
13977
+ const rows = z20.array(chunkRow2).parse(this.#chunkRows(streamId, fromSeq, limit));
13899
13978
  return Promise.all(
13900
13979
  rows.map(async (row) => ({
13901
13980
  streamId: row.streamId,
@@ -14410,7 +14489,9 @@ export {
14410
14489
  PollingChangeSource,
14411
14490
  PostgresContextStore,
14412
14491
  PostgresNotifyChangeSource,
14492
+ PostgresStoreDatabase,
14413
14493
  PostgresStreamStore,
14494
+ PostgresTransaction,
14414
14495
  RuntimeStrategy,
14415
14496
  SearchQuerySyntaxError,
14416
14497
  SqlServerContextStore,