@deepagents/context 0.16.0 → 0.17.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/dist/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // packages/context/src/lib/agent.ts
2
- import { groq } from "@ai-sdk/groq";
3
2
  import {
4
- NoSuchToolError,
5
3
  Output,
6
4
  convertToModelMessages,
7
5
  createUIMessageStream,
@@ -13,7 +11,7 @@ import {
13
11
  } from "ai";
14
12
  import chalk from "chalk";
15
13
  import "zod";
16
- import "@deepagents/agent";
14
+ import { createRepairToolCall } from "@deepagents/agent";
17
15
 
18
16
  // packages/context/src/lib/fragments.ts
19
17
  import { generateId } from "ai";
@@ -169,7 +167,7 @@ var Agent = class _Agent {
169
167
  stopWhen: stepCountIs(25),
170
168
  tools: this.#options.tools,
171
169
  experimental_context: contextVariables,
172
- experimental_repairToolCall: repairToolCall,
170
+ experimental_repairToolCall: createRepairToolCall(this.#options.model),
173
171
  toolChoice: this.#options.toolChoice,
174
172
  onStepFinish: (step) => {
175
173
  const toolCall = step.toolCalls.at(-1);
@@ -225,7 +223,7 @@ var Agent = class _Agent {
225
223
  model: this.#options.model,
226
224
  system: systemPrompt,
227
225
  messages: await convertToModelMessages(messages),
228
- experimental_repairToolCall: repairToolCall,
226
+ experimental_repairToolCall: createRepairToolCall(this.#options.model),
229
227
  stopWhen: stepCountIs(50),
230
228
  experimental_transform: config?.transform ?? smoothStream(),
231
229
  tools: this.#options.tools,
@@ -365,7 +363,7 @@ function structuredOutput(options) {
365
363
  system: systemPrompt,
366
364
  messages: await convertToModelMessages(messages),
367
365
  stopWhen: stepCountIs(25),
368
- experimental_repairToolCall: repairToolCall,
366
+ experimental_repairToolCall: createRepairToolCall(options.model),
369
367
  experimental_context: contextVariables,
370
368
  output: Output.object({ schema: options.schema }),
371
369
  tools: options.tools
@@ -387,7 +385,7 @@ function structuredOutput(options) {
387
385
  providerOptions: options.providerOptions,
388
386
  model: options.model,
389
387
  system: systemPrompt,
390
- experimental_repairToolCall: repairToolCall,
388
+ experimental_repairToolCall: createRepairToolCall(options.model),
391
389
  messages: await convertToModelMessages(messages),
392
390
  stopWhen: stepCountIs(50),
393
391
  experimental_transform: config?.transform ?? smoothStream(),
@@ -398,34 +396,6 @@ function structuredOutput(options) {
398
396
  }
399
397
  };
400
398
  }
401
- var repairToolCall = async ({
402
- toolCall,
403
- tools,
404
- inputSchema,
405
- error
406
- }) => {
407
- console.log(
408
- `Debug: ${chalk.yellow("RepairingToolCall")}: ${chalk.bgYellow(toolCall.toolName)}`,
409
- error.name,
410
- JSON.stringify(toolCall)
411
- );
412
- if (NoSuchToolError.isInstance(error)) {
413
- return null;
414
- }
415
- const tool = tools[toolCall.toolName];
416
- const { output } = await generateText({
417
- model: groq("openai/gpt-oss-20b"),
418
- output: Output.object({ schema: tool.inputSchema }),
419
- prompt: [
420
- `The model tried to call the tool "${toolCall.toolName}" with the following inputs:`,
421
- JSON.stringify(toolCall.input),
422
- `The tool accepts the following schema:`,
423
- JSON.stringify(inputSchema(toolCall)),
424
- "Please fix the inputs."
425
- ].join("\n")
426
- });
427
- return { ...toolCall, input: JSON.stringify(output) };
428
- };
429
399
  function writeText(writer, text) {
430
400
  const feedbackPartId = generateId2();
431
401
  writer.write({
@@ -1593,6 +1563,13 @@ var ContextEngine = class {
1593
1563
  get branch() {
1594
1564
  return this.#branchName;
1595
1565
  }
1566
+ /**
1567
+ * Get the current branch head message ID.
1568
+ * Returns undefined if no messages have been saved yet.
1569
+ */
1570
+ get headMessageId() {
1571
+ return this.#branch?.headMessageId ?? void 0;
1572
+ }
1596
1573
  /**
1597
1574
  * Get metadata for the current chat.
1598
1575
  * Returns null if the chat hasn't been initialized yet.
@@ -1699,7 +1676,7 @@ var ContextEngine = class {
1699
1676
  async save(options) {
1700
1677
  await this.#ensureInitialized();
1701
1678
  if (this.#pendingMessages.length === 0) {
1702
- return;
1679
+ return { headMessageId: this.#branch?.headMessageId ?? void 0 };
1703
1680
  }
1704
1681
  const shouldBranch = options?.branch ?? true;
1705
1682
  for (let i = 0; i < this.#pendingMessages.length; i++) {
@@ -1751,6 +1728,7 @@ var ContextEngine = class {
1751
1728
  await this.#store.updateBranchHead(this.#branch.id, parentId);
1752
1729
  this.#branch.headMessageId = parentId;
1753
1730
  this.#pendingMessages = [];
1731
+ return { headMessageId: this.#branch.headMessageId ?? void 0 };
1754
1732
  }
1755
1733
  /**
1756
1734
  * Resolve a lazy fragment by finding the appropriate ID.
@@ -3916,18 +3894,113 @@ var InMemoryContextStore = class extends SqliteContextStore {
3916
3894
  // packages/context/src/lib/store/postgres.store.ts
3917
3895
  import { createRequire } from "node:module";
3918
3896
 
3919
- // packages/context/src/lib/store/ddl.postgres.sql
3920
- var ddl_postgres_default = "-- Context Store DDL for PostgreSQL\n-- This schema implements a DAG-based message history with branching and checkpoints.\n\n-- Chats table\n-- createdAt/updatedAt: DEFAULT for insert, inline SET for updates\nCREATE TABLE IF NOT EXISTS chats (\n id TEXT PRIMARY KEY,\n userId TEXT NOT NULL,\n title TEXT,\n metadata JSONB,\n createdAt BIGINT NOT NULL DEFAULT (EXTRACT(EPOCH FROM NOW()) * 1000)::BIGINT,\n updatedAt BIGINT NOT NULL DEFAULT (EXTRACT(EPOCH FROM NOW()) * 1000)::BIGINT\n);\n\nCREATE INDEX IF NOT EXISTS idx_chats_updatedAt ON chats(updatedAt);\nCREATE INDEX IF NOT EXISTS idx_chats_userId ON chats(userId);\nCREATE INDEX IF NOT EXISTS idx_chats_metadata ON chats USING GIN (metadata);\n\n-- Messages table (nodes in the DAG)\nCREATE TABLE IF NOT EXISTS messages (\n id TEXT PRIMARY KEY,\n chatId TEXT NOT NULL,\n parentId TEXT,\n name TEXT NOT NULL,\n type TEXT,\n data JSONB NOT NULL,\n createdAt BIGINT NOT NULL,\n FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,\n FOREIGN KEY (parentId) REFERENCES messages(id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_messages_chatId ON messages(chatId);\nCREATE INDEX IF NOT EXISTS idx_messages_parentId ON messages(parentId);\n\n-- Branches table (pointers to head messages)\nCREATE TABLE IF NOT EXISTS branches (\n id TEXT PRIMARY KEY,\n chatId TEXT NOT NULL,\n name TEXT NOT NULL,\n headMessageId TEXT,\n isActive BOOLEAN NOT NULL DEFAULT FALSE,\n createdAt BIGINT NOT NULL,\n FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,\n FOREIGN KEY (headMessageId) REFERENCES messages(id),\n UNIQUE(chatId, name)\n);\n\nCREATE INDEX IF NOT EXISTS idx_branches_chatId ON branches(chatId);\n\n-- Checkpoints table (pointers to message nodes)\nCREATE TABLE IF NOT EXISTS checkpoints (\n id TEXT PRIMARY KEY,\n chatId TEXT NOT NULL,\n name TEXT NOT NULL,\n messageId TEXT NOT NULL,\n createdAt BIGINT NOT NULL,\n FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,\n FOREIGN KEY (messageId) REFERENCES messages(id),\n UNIQUE(chatId, name)\n);\n\nCREATE INDEX IF NOT EXISTS idx_checkpoints_chatId ON checkpoints(chatId);\n\n-- Full-text search using tsvector + GIN index\nCREATE TABLE IF NOT EXISTS messages_fts (\n messageId TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,\n chatId TEXT NOT NULL,\n name TEXT NOT NULL,\n content TEXT NOT NULL,\n content_vector TSVECTOR\n);\n\nCREATE INDEX IF NOT EXISTS idx_messages_fts_vector ON messages_fts USING GIN(content_vector);\nCREATE INDEX IF NOT EXISTS idx_messages_fts_chatId ON messages_fts(chatId);\n\n-- Trigger to automatically update tsvector on insert/update\nCREATE OR REPLACE FUNCTION messages_fts_update_vector() RETURNS TRIGGER AS $$\nBEGIN\n NEW.content_vector := to_tsvector('english', NEW.content);\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS messages_fts_vector_update ON messages_fts;\nCREATE TRIGGER messages_fts_vector_update\n BEFORE INSERT OR UPDATE ON messages_fts\n FOR EACH ROW\n EXECUTE FUNCTION messages_fts_update_vector();\n";
3897
+ // packages/context/src/lib/store/ddl.postgres.ts
3898
+ function storeDDL(schema) {
3899
+ return `
3900
+ CREATE SCHEMA IF NOT EXISTS "${schema}";
3901
+
3902
+ CREATE TABLE IF NOT EXISTS "${schema}"."chats" (
3903
+ id TEXT PRIMARY KEY,
3904
+ userId TEXT NOT NULL,
3905
+ title TEXT,
3906
+ metadata JSONB,
3907
+ createdAt BIGINT NOT NULL DEFAULT (EXTRACT(EPOCH FROM NOW()) * 1000)::BIGINT,
3908
+ updatedAt BIGINT NOT NULL DEFAULT (EXTRACT(EPOCH FROM NOW()) * 1000)::BIGINT
3909
+ );
3910
+
3911
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_chats_updatedAt" ON "${schema}"."chats"(updatedAt);
3912
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_chats_userId" ON "${schema}"."chats"(userId);
3913
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_chats_metadata" ON "${schema}"."chats" USING GIN (metadata);
3914
+
3915
+ CREATE TABLE IF NOT EXISTS "${schema}"."messages" (
3916
+ id TEXT PRIMARY KEY,
3917
+ chatId TEXT NOT NULL,
3918
+ parentId TEXT,
3919
+ name TEXT NOT NULL,
3920
+ type TEXT,
3921
+ data JSONB NOT NULL,
3922
+ createdAt BIGINT NOT NULL,
3923
+ FOREIGN KEY (chatId) REFERENCES "${schema}"."chats"(id) ON DELETE CASCADE,
3924
+ FOREIGN KEY (parentId) REFERENCES "${schema}"."messages"(id)
3925
+ );
3926
+
3927
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_messages_chatId" ON "${schema}"."messages"(chatId);
3928
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_messages_parentId" ON "${schema}"."messages"(parentId);
3929
+
3930
+ CREATE TABLE IF NOT EXISTS "${schema}"."branches" (
3931
+ id TEXT PRIMARY KEY,
3932
+ chatId TEXT NOT NULL,
3933
+ name TEXT NOT NULL,
3934
+ headMessageId TEXT,
3935
+ isActive BOOLEAN NOT NULL DEFAULT FALSE,
3936
+ createdAt BIGINT NOT NULL,
3937
+ FOREIGN KEY (chatId) REFERENCES "${schema}"."chats"(id) ON DELETE CASCADE,
3938
+ FOREIGN KEY (headMessageId) REFERENCES "${schema}"."messages"(id),
3939
+ UNIQUE(chatId, name)
3940
+ );
3941
+
3942
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_branches_chatId" ON "${schema}"."branches"(chatId);
3943
+
3944
+ CREATE TABLE IF NOT EXISTS "${schema}"."checkpoints" (
3945
+ id TEXT PRIMARY KEY,
3946
+ chatId TEXT NOT NULL,
3947
+ name TEXT NOT NULL,
3948
+ messageId TEXT NOT NULL,
3949
+ createdAt BIGINT NOT NULL,
3950
+ FOREIGN KEY (chatId) REFERENCES "${schema}"."chats"(id) ON DELETE CASCADE,
3951
+ FOREIGN KEY (messageId) REFERENCES "${schema}"."messages"(id),
3952
+ UNIQUE(chatId, name)
3953
+ );
3954
+
3955
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_checkpoints_chatId" ON "${schema}"."checkpoints"(chatId);
3956
+
3957
+ CREATE TABLE IF NOT EXISTS "${schema}"."messages_fts" (
3958
+ messageId TEXT PRIMARY KEY REFERENCES "${schema}"."messages"(id) ON DELETE CASCADE,
3959
+ chatId TEXT NOT NULL,
3960
+ name TEXT NOT NULL,
3961
+ content TEXT NOT NULL,
3962
+ content_vector TSVECTOR
3963
+ );
3964
+
3965
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_messages_fts_vector" ON "${schema}"."messages_fts" USING GIN(content_vector);
3966
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_messages_fts_chatId" ON "${schema}"."messages_fts"(chatId);
3967
+
3968
+ CREATE OR REPLACE FUNCTION "${schema}"."messages_fts_update_vector"() RETURNS TRIGGER AS $$
3969
+ BEGIN
3970
+ NEW.content_vector := to_tsvector('english', NEW.content);
3971
+ RETURN NEW;
3972
+ END;
3973
+ $$ LANGUAGE plpgsql;
3974
+
3975
+ DROP TRIGGER IF EXISTS "${schema}_messages_fts_vector_update" ON "${schema}"."messages_fts";
3976
+ CREATE TRIGGER "${schema}_messages_fts_vector_update"
3977
+ BEFORE INSERT OR UPDATE ON "${schema}"."messages_fts"
3978
+ FOR EACH ROW
3979
+ EXECUTE FUNCTION "${schema}"."messages_fts_update_vector"();
3980
+ `;
3981
+ }
3921
3982
 
3922
3983
  // packages/context/src/lib/store/postgres.store.ts
3923
3984
  var PostgresContextStore = class _PostgresContextStore extends ContextStore {
3924
3985
  #pool;
3925
- #initialized;
3986
+ #schema;
3987
+ #ownsPool;
3988
+ #isInitialized = false;
3926
3989
  constructor(options) {
3927
3990
  super();
3991
+ const schema = options.schema ?? "public";
3992
+ if (!/^[a-zA-Z_]\w*$/.test(schema)) {
3993
+ throw new Error(`Invalid schema name: "${schema}"`);
3994
+ }
3995
+ this.#schema = schema;
3928
3996
  const pg = _PostgresContextStore.#requirePg();
3929
- this.#pool = typeof options.pool === "string" ? new pg.Pool({ connectionString: options.pool }) : new pg.Pool(options.pool);
3930
- this.#initialized = this.#initialize();
3997
+ if (options.pool instanceof pg.Pool) {
3998
+ this.#pool = options.pool;
3999
+ this.#ownsPool = false;
4000
+ } else {
4001
+ this.#pool = typeof options.pool === "string" ? new pg.Pool({ connectionString: options.pool }) : new pg.Pool(options.pool);
4002
+ this.#ownsPool = true;
4003
+ }
3931
4004
  }
3932
4005
  static #requirePg() {
3933
4006
  try {
@@ -3939,21 +4012,27 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
3939
4012
  );
3940
4013
  }
3941
4014
  }
3942
- async #initialize() {
3943
- await this.#pool.query(ddl_postgres_default);
4015
+ #t(name) {
4016
+ return `"${this.#schema}"."${name}"`;
3944
4017
  }
3945
- /**
3946
- * Ensure initialization is complete before any operation.
3947
- */
3948
- async #ensureInitialized() {
3949
- await this.#initialized;
4018
+ async initialize() {
4019
+ const ddl = storeDDL(this.#schema);
4020
+ await this.#pool.query(ddl);
4021
+ this.#isInitialized = true;
4022
+ }
4023
+ #ensureInitialized() {
4024
+ if (!this.#isInitialized) {
4025
+ throw new Error(
4026
+ "PostgresContextStore not initialized. Call await store.initialize() after construction."
4027
+ );
4028
+ }
3950
4029
  }
3951
4030
  /**
3952
4031
  * Execute a function within a transaction.
3953
4032
  * Automatically commits on success or rolls back on error.
3954
4033
  */
3955
4034
  async #useTransaction(fn) {
3956
- await this.#ensureInitialized();
4035
+ this.#ensureInitialized();
3957
4036
  const client = await this.#pool.connect();
3958
4037
  try {
3959
4038
  await client.query("BEGIN");
@@ -3971,7 +4050,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
3971
4050
  * Execute a query using the pool (no transaction).
3972
4051
  */
3973
4052
  async #query(sql, params) {
3974
- await this.#ensureInitialized();
4053
+ this.#ensureInitialized();
3975
4054
  const result = await this.#pool.query(sql, params);
3976
4055
  return result.rows;
3977
4056
  }
@@ -3980,7 +4059,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
3980
4059
  * Call this when done with the store.
3981
4060
  */
3982
4061
  async close() {
3983
- await this.#pool.end();
4062
+ if (this.#ownsPool) {
4063
+ await this.#pool.end();
4064
+ }
3984
4065
  }
3985
4066
  // ==========================================================================
3986
4067
  // Chat Operations
@@ -3988,7 +4069,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
3988
4069
  async createChat(chat) {
3989
4070
  return this.#useTransaction(async (client) => {
3990
4071
  const result = await client.query(
3991
- `INSERT INTO chats (id, userId, title, metadata)
4072
+ `INSERT INTO ${this.#t("chats")} (id, userId, title, metadata)
3992
4073
  VALUES ($1, $2, $3, $4)
3993
4074
  RETURNING *`,
3994
4075
  [
@@ -4000,7 +4081,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4000
4081
  );
4001
4082
  const row = result.rows[0];
4002
4083
  await client.query(
4003
- `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
4084
+ `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
4004
4085
  VALUES ($1, $2, 'main', NULL, TRUE, $3)`,
4005
4086
  [crypto.randomUUID(), chat.id, Date.now()]
4006
4087
  );
@@ -4017,7 +4098,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4017
4098
  async upsertChat(chat) {
4018
4099
  return this.#useTransaction(async (client) => {
4019
4100
  const result = await client.query(
4020
- `INSERT INTO chats (id, userId, title, metadata)
4101
+ `INSERT INTO ${this.#t("chats")} (id, userId, title, metadata)
4021
4102
  VALUES ($1, $2, $3, $4)
4022
4103
  ON CONFLICT(id) DO UPDATE SET id = EXCLUDED.id
4023
4104
  RETURNING *`,
@@ -4030,7 +4111,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4030
4111
  );
4031
4112
  const row = result.rows[0];
4032
4113
  await client.query(
4033
- `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
4114
+ `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
4034
4115
  VALUES ($1, $2, 'main', NULL, TRUE, $3)
4035
4116
  ON CONFLICT(chatId, name) DO NOTHING`,
4036
4117
  [crypto.randomUUID(), chat.id, Date.now()]
@@ -4046,7 +4127,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4046
4127
  });
4047
4128
  }
4048
4129
  async getChat(chatId) {
4049
- const rows = await this.#query("SELECT * FROM chats WHERE id = $1", [chatId]);
4130
+ const rows = await this.#query(`SELECT * FROM ${this.#t("chats")} WHERE id = $1`, [chatId]);
4050
4131
  if (rows.length === 0) {
4051
4132
  return void 0;
4052
4133
  }
@@ -4076,7 +4157,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4076
4157
  }
4077
4158
  params.push(chatId);
4078
4159
  const rows = await this.#query(
4079
- `UPDATE chats SET ${setClauses.join(", ")} WHERE id = $${paramIndex} RETURNING *`,
4160
+ `UPDATE ${this.#t("chats")} SET ${setClauses.join(", ")} WHERE id = $${paramIndex} RETURNING *`,
4080
4161
  params
4081
4162
  );
4082
4163
  const row = rows[0];
@@ -4124,9 +4205,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4124
4205
  c.updatedAt,
4125
4206
  COUNT(DISTINCT m.id) as messageCount,
4126
4207
  COUNT(DISTINCT b.id) as branchCount
4127
- FROM chats c
4128
- LEFT JOIN messages m ON m.chatId = c.id
4129
- LEFT JOIN branches b ON b.chatId = c.id
4208
+ FROM ${this.#t("chats")} c
4209
+ LEFT JOIN ${this.#t("messages")} m ON m.chatId = c.id
4210
+ LEFT JOIN ${this.#t("branches")} b ON b.chatId = c.id
4130
4211
  ${whereClause}
4131
4212
  GROUP BY c.id
4132
4213
  ORDER BY c.updatedAt DESC${limitClause}`,
@@ -4145,7 +4226,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4145
4226
  }
4146
4227
  async deleteChat(chatId, options) {
4147
4228
  return this.#useTransaction(async (client) => {
4148
- let sql = "DELETE FROM chats WHERE id = $1";
4229
+ let sql = `DELETE FROM ${this.#t("chats")} WHERE id = $1`;
4149
4230
  const params = [chatId];
4150
4231
  if (options?.userId !== void 0) {
4151
4232
  sql += " AND userId = $2";
@@ -4164,7 +4245,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4164
4245
  }
4165
4246
  await this.#useTransaction(async (client) => {
4166
4247
  await client.query(
4167
- `INSERT INTO messages (id, chatId, parentId, name, type, data, createdAt)
4248
+ `INSERT INTO ${this.#t("messages")} (id, chatId, parentId, name, type, data, createdAt)
4168
4249
  VALUES ($1, $2, $3, $4, $5, $6, $7)
4169
4250
  ON CONFLICT(id) DO UPDATE SET
4170
4251
  name = EXCLUDED.name,
@@ -4182,7 +4263,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4182
4263
  );
4183
4264
  const content = typeof message2.data === "string" ? message2.data : JSON.stringify(message2.data);
4184
4265
  await client.query(
4185
- `INSERT INTO messages_fts (messageId, chatId, name, content)
4266
+ `INSERT INTO ${this.#t("messages_fts")} (messageId, chatId, name, content)
4186
4267
  VALUES ($1, $2, $3, $4)
4187
4268
  ON CONFLICT(messageId) DO UPDATE SET
4188
4269
  chatId = EXCLUDED.chatId,
@@ -4193,7 +4274,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4193
4274
  });
4194
4275
  }
4195
4276
  async getMessage(messageId) {
4196
- const rows = await this.#query("SELECT * FROM messages WHERE id = $1", [messageId]);
4277
+ const rows = await this.#query(`SELECT * FROM ${this.#t("messages")} WHERE id = $1`, [messageId]);
4197
4278
  if (rows.length === 0) {
4198
4279
  return void 0;
4199
4280
  }
@@ -4211,9 +4292,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4211
4292
  async getMessageChain(headId) {
4212
4293
  const rows = await this.#query(
4213
4294
  `WITH RECURSIVE chain AS (
4214
- SELECT *, 0 as depth FROM messages WHERE id = $1
4295
+ SELECT *, 0 as depth FROM ${this.#t("messages")} WHERE id = $1
4215
4296
  UNION ALL
4216
- SELECT m.*, c.depth + 1 FROM messages m
4297
+ SELECT m.*, c.depth + 1 FROM ${this.#t("messages")} m
4217
4298
  INNER JOIN chain c ON m.id = c.parentId
4218
4299
  WHERE c.depth < 10000
4219
4300
  )
@@ -4233,7 +4314,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4233
4314
  }
4234
4315
  async hasChildren(messageId) {
4235
4316
  const rows = await this.#query(
4236
- "SELECT EXISTS(SELECT 1 FROM messages WHERE parentId = $1) as exists",
4317
+ `SELECT EXISTS(SELECT 1 FROM ${this.#t("messages")} WHERE parentId = $1) as exists`,
4237
4318
  [messageId]
4238
4319
  );
4239
4320
  return rows[0].exists;
@@ -4254,7 +4335,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4254
4335
  // ==========================================================================
4255
4336
  async createBranch(branch) {
4256
4337
  await this.#query(
4257
- `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
4338
+ `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
4258
4339
  VALUES ($1, $2, $3, $4, $5, $6)`,
4259
4340
  [
4260
4341
  branch.id,
@@ -4267,7 +4348,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4267
4348
  );
4268
4349
  }
4269
4350
  async getBranch(chatId, name) {
4270
- const rows = await this.#query("SELECT * FROM branches WHERE chatId = $1 AND name = $2", [
4351
+ const rows = await this.#query(`SELECT * FROM ${this.#t("branches")} WHERE chatId = $1 AND name = $2`, [
4271
4352
  chatId,
4272
4353
  name
4273
4354
  ]);
@@ -4285,9 +4366,10 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4285
4366
  };
4286
4367
  }
4287
4368
  async getActiveBranch(chatId) {
4288
- const rows = await this.#query("SELECT * FROM branches WHERE chatId = $1 AND isActive = TRUE", [
4289
- chatId
4290
- ]);
4369
+ const rows = await this.#query(
4370
+ `SELECT * FROM ${this.#t("branches")} WHERE chatId = $1 AND isActive = TRUE`,
4371
+ [chatId]
4372
+ );
4291
4373
  if (rows.length === 0) {
4292
4374
  return void 0;
4293
4375
  }
@@ -4304,19 +4386,20 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4304
4386
  async setActiveBranch(chatId, branchId) {
4305
4387
  await this.#useTransaction(async (client) => {
4306
4388
  await client.query(
4307
- "UPDATE branches SET isActive = FALSE WHERE chatId = $1",
4389
+ `UPDATE ${this.#t("branches")} SET isActive = FALSE WHERE chatId = $1`,
4308
4390
  [chatId]
4309
4391
  );
4310
- await client.query("UPDATE branches SET isActive = TRUE WHERE id = $1", [
4311
- branchId
4312
- ]);
4392
+ await client.query(
4393
+ `UPDATE ${this.#t("branches")} SET isActive = TRUE WHERE id = $1`,
4394
+ [branchId]
4395
+ );
4313
4396
  });
4314
4397
  }
4315
4398
  async updateBranchHead(branchId, messageId) {
4316
- await this.#query("UPDATE branches SET headMessageId = $1 WHERE id = $2", [
4317
- messageId,
4318
- branchId
4319
- ]);
4399
+ await this.#query(
4400
+ `UPDATE ${this.#t("branches")} SET headMessageId = $1 WHERE id = $2`,
4401
+ [messageId, branchId]
4402
+ );
4320
4403
  }
4321
4404
  async listBranches(chatId) {
4322
4405
  const branches = await this.#query(
@@ -4326,7 +4409,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4326
4409
  headMessageId,
4327
4410
  isActive,
4328
4411
  createdAt
4329
- FROM branches
4412
+ FROM ${this.#t("branches")}
4330
4413
  WHERE chatId = $1
4331
4414
  ORDER BY createdAt ASC`,
4332
4415
  [chatId]
@@ -4337,9 +4420,9 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4337
4420
  if (branch.headmessageid) {
4338
4421
  const countRows = await this.#query(
4339
4422
  `WITH RECURSIVE chain AS (
4340
- SELECT id, parentId FROM messages WHERE id = $1
4423
+ SELECT id, parentId FROM ${this.#t("messages")} WHERE id = $1
4341
4424
  UNION ALL
4342
- SELECT m.id, m.parentId FROM messages m
4425
+ SELECT m.id, m.parentId FROM ${this.#t("messages")} m
4343
4426
  INNER JOIN chain c ON m.id = c.parentId
4344
4427
  )
4345
4428
  SELECT COUNT(*) as count FROM chain`,
@@ -4363,7 +4446,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4363
4446
  // ==========================================================================
4364
4447
  async createCheckpoint(checkpoint) {
4365
4448
  await this.#query(
4366
- `INSERT INTO checkpoints (id, chatId, name, messageId, createdAt)
4449
+ `INSERT INTO ${this.#t("checkpoints")} (id, chatId, name, messageId, createdAt)
4367
4450
  VALUES ($1, $2, $3, $4, $5)
4368
4451
  ON CONFLICT(chatId, name) DO UPDATE SET
4369
4452
  messageId = EXCLUDED.messageId,
@@ -4378,10 +4461,10 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4378
4461
  );
4379
4462
  }
4380
4463
  async getCheckpoint(chatId, name) {
4381
- const rows = await this.#query("SELECT * FROM checkpoints WHERE chatId = $1 AND name = $2", [
4382
- chatId,
4383
- name
4384
- ]);
4464
+ const rows = await this.#query(
4465
+ `SELECT * FROM ${this.#t("checkpoints")} WHERE chatId = $1 AND name = $2`,
4466
+ [chatId, name]
4467
+ );
4385
4468
  if (rows.length === 0) {
4386
4469
  return void 0;
4387
4470
  }
@@ -4397,7 +4480,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4397
4480
  async listCheckpoints(chatId) {
4398
4481
  const rows = await this.#query(
4399
4482
  `SELECT id, name, messageId, createdAt
4400
- FROM checkpoints
4483
+ FROM ${this.#t("checkpoints")}
4401
4484
  WHERE chatId = $1
4402
4485
  ORDER BY createdAt DESC`,
4403
4486
  [chatId]
@@ -4411,7 +4494,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4411
4494
  }
4412
4495
  async deleteCheckpoint(chatId, name) {
4413
4496
  await this.#query(
4414
- "DELETE FROM checkpoints WHERE chatId = $1 AND name = $2",
4497
+ `DELETE FROM ${this.#t("checkpoints")} WHERE chatId = $1 AND name = $2`,
4415
4498
  [chatId, name]
4416
4499
  );
4417
4500
  }
@@ -4433,8 +4516,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4433
4516
  ts_rank(fts.content_vector, plainto_tsquery('english', $2)) as rank,
4434
4517
  ts_headline('english', fts.content, plainto_tsquery('english', $2),
4435
4518
  'StartSel=<mark>, StopSel=</mark>, MaxWords=32, MinWords=5, MaxFragments=1') as snippet
4436
- FROM messages_fts fts
4437
- JOIN messages m ON m.id = fts.messageId
4519
+ FROM ${this.#t("messages_fts")} fts
4520
+ JOIN ${this.#t("messages")} m ON m.id = fts.messageId
4438
4521
  WHERE fts.content_vector @@ plainto_tsquery('english', $2)
4439
4522
  AND fts.chatId = $1
4440
4523
  `;
@@ -4468,7 +4551,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4468
4551
  async getGraph(chatId) {
4469
4552
  const messageRows = await this.#query(
4470
4553
  `SELECT id, parentId, name, data, createdAt
4471
- FROM messages
4554
+ FROM ${this.#t("messages")}
4472
4555
  WHERE chatId = $1
4473
4556
  ORDER BY createdAt ASC`,
4474
4557
  [chatId]
@@ -4486,7 +4569,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4486
4569
  });
4487
4570
  const branchRows = await this.#query(
4488
4571
  `SELECT name, headMessageId, isActive
4489
- FROM branches
4572
+ FROM ${this.#t("branches")}
4490
4573
  WHERE chatId = $1
4491
4574
  ORDER BY createdAt ASC`,
4492
4575
  [chatId]
@@ -4498,7 +4581,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4498
4581
  }));
4499
4582
  const checkpointRows = await this.#query(
4500
4583
  `SELECT name, messageId
4501
- FROM checkpoints
4584
+ FROM ${this.#t("checkpoints")}
4502
4585
  WHERE chatId = $1
4503
4586
  ORDER BY createdAt ASC`,
4504
4587
  [chatId]
@@ -4520,12 +4603,11 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
4520
4603
  import { createRequire as createRequire2 } from "node:module";
4521
4604
 
4522
4605
  // packages/context/src/lib/store/ddl.sqlserver.ts
4523
- function storeDDL(schema) {
4524
- const s = schema;
4606
+ function storeDDL2(schema) {
4525
4607
  return `
4526
- IF OBJECT_ID('[${s}].[chats]', 'U') IS NULL
4608
+ IF OBJECT_ID('[${schema}].[chats]', 'U') IS NULL
4527
4609
  BEGIN
4528
- CREATE TABLE [${s}].[chats] (
4610
+ CREATE TABLE [${schema}].[chats] (
4529
4611
  id NVARCHAR(255) PRIMARY KEY,
4530
4612
  userId NVARCHAR(255) NOT NULL,
4531
4613
  title NVARCHAR(MAX),
@@ -4535,15 +4617,15 @@ BEGIN
4535
4617
  );
4536
4618
  END;
4537
4619
 
4538
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_chats_updatedAt' AND object_id = OBJECT_ID('[${s}].[chats]'))
4539
- CREATE INDEX [idx_${s}_chats_updatedAt] ON [${s}].[chats](updatedAt);
4620
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_chats_updatedAt' AND object_id = OBJECT_ID('[${schema}].[chats]'))
4621
+ CREATE INDEX [idx_${schema}_chats_updatedAt] ON [${schema}].[chats](updatedAt);
4540
4622
 
4541
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_chats_userId' AND object_id = OBJECT_ID('[${s}].[chats]'))
4542
- CREATE INDEX [idx_${s}_chats_userId] ON [${s}].[chats](userId);
4623
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_chats_userId' AND object_id = OBJECT_ID('[${schema}].[chats]'))
4624
+ CREATE INDEX [idx_${schema}_chats_userId] ON [${schema}].[chats](userId);
4543
4625
 
4544
- IF OBJECT_ID('[${s}].[messages]', 'U') IS NULL
4626
+ IF OBJECT_ID('[${schema}].[messages]', 'U') IS NULL
4545
4627
  BEGIN
4546
- CREATE TABLE [${s}].[messages] (
4628
+ CREATE TABLE [${schema}].[messages] (
4547
4629
  id NVARCHAR(255) PRIMARY KEY,
4548
4630
  chatId NVARCHAR(255) NOT NULL,
4549
4631
  parentId NVARCHAR(255),
@@ -4551,85 +4633,85 @@ BEGIN
4551
4633
  type NVARCHAR(255),
4552
4634
  data NVARCHAR(MAX) NOT NULL,
4553
4635
  createdAt BIGINT NOT NULL,
4554
- FOREIGN KEY (chatId) REFERENCES [${s}].[chats](id) ON DELETE CASCADE,
4555
- FOREIGN KEY (parentId) REFERENCES [${s}].[messages](id)
4636
+ FOREIGN KEY (chatId) REFERENCES [${schema}].[chats](id) ON DELETE CASCADE,
4637
+ FOREIGN KEY (parentId) REFERENCES [${schema}].[messages](id)
4556
4638
  );
4557
4639
  END;
4558
4640
 
4559
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_messages_chatId' AND object_id = OBJECT_ID('[${s}].[messages]'))
4560
- CREATE INDEX [idx_${s}_messages_chatId] ON [${s}].[messages](chatId);
4641
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_messages_chatId' AND object_id = OBJECT_ID('[${schema}].[messages]'))
4642
+ CREATE INDEX [idx_${schema}_messages_chatId] ON [${schema}].[messages](chatId);
4561
4643
 
4562
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_messages_parentId' AND object_id = OBJECT_ID('[${s}].[messages]'))
4563
- CREATE INDEX [idx_${s}_messages_parentId] ON [${s}].[messages](parentId);
4644
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_messages_parentId' AND object_id = OBJECT_ID('[${schema}].[messages]'))
4645
+ CREATE INDEX [idx_${schema}_messages_parentId] ON [${schema}].[messages](parentId);
4564
4646
 
4565
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_messages_chatId_parentId' AND object_id = OBJECT_ID('[${s}].[messages]'))
4566
- CREATE INDEX [idx_${s}_messages_chatId_parentId] ON [${s}].[messages](chatId, parentId);
4647
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_messages_chatId_parentId' AND object_id = OBJECT_ID('[${schema}].[messages]'))
4648
+ CREATE INDEX [idx_${schema}_messages_chatId_parentId] ON [${schema}].[messages](chatId, parentId);
4567
4649
 
4568
- IF OBJECT_ID('[${s}].[branches]', 'U') IS NULL
4650
+ IF OBJECT_ID('[${schema}].[branches]', 'U') IS NULL
4569
4651
  BEGIN
4570
- CREATE TABLE [${s}].[branches] (
4652
+ CREATE TABLE [${schema}].[branches] (
4571
4653
  id NVARCHAR(255) PRIMARY KEY,
4572
4654
  chatId NVARCHAR(255) NOT NULL,
4573
4655
  name NVARCHAR(255) NOT NULL,
4574
4656
  headMessageId NVARCHAR(255),
4575
4657
  isActive BIT NOT NULL DEFAULT 0,
4576
4658
  createdAt BIGINT NOT NULL,
4577
- FOREIGN KEY (chatId) REFERENCES [${s}].[chats](id) ON DELETE CASCADE,
4578
- FOREIGN KEY (headMessageId) REFERENCES [${s}].[messages](id),
4579
- CONSTRAINT [UQ_${s}_branches_chatId_name] UNIQUE(chatId, name)
4659
+ FOREIGN KEY (chatId) REFERENCES [${schema}].[chats](id) ON DELETE CASCADE,
4660
+ FOREIGN KEY (headMessageId) REFERENCES [${schema}].[messages](id),
4661
+ CONSTRAINT [UQ_${schema}_branches_chatId_name] UNIQUE(chatId, name)
4580
4662
  );
4581
4663
  END;
4582
4664
 
4583
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_branches_chatId' AND object_id = OBJECT_ID('[${s}].[branches]'))
4584
- CREATE INDEX [idx_${s}_branches_chatId] ON [${s}].[branches](chatId);
4665
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_branches_chatId' AND object_id = OBJECT_ID('[${schema}].[branches]'))
4666
+ CREATE INDEX [idx_${schema}_branches_chatId] ON [${schema}].[branches](chatId);
4585
4667
 
4586
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_branches_chatId_isActive' AND object_id = OBJECT_ID('[${s}].[branches]'))
4587
- CREATE INDEX [idx_${s}_branches_chatId_isActive] ON [${s}].[branches](chatId, isActive);
4668
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_branches_chatId_isActive' AND object_id = OBJECT_ID('[${schema}].[branches]'))
4669
+ CREATE INDEX [idx_${schema}_branches_chatId_isActive] ON [${schema}].[branches](chatId, isActive);
4588
4670
 
4589
- IF OBJECT_ID('[${s}].[checkpoints]', 'U') IS NULL
4671
+ IF OBJECT_ID('[${schema}].[checkpoints]', 'U') IS NULL
4590
4672
  BEGIN
4591
- CREATE TABLE [${s}].[checkpoints] (
4673
+ CREATE TABLE [${schema}].[checkpoints] (
4592
4674
  id NVARCHAR(255) PRIMARY KEY,
4593
4675
  chatId NVARCHAR(255) NOT NULL,
4594
4676
  name NVARCHAR(255) NOT NULL,
4595
4677
  messageId NVARCHAR(255) NOT NULL,
4596
4678
  createdAt BIGINT NOT NULL,
4597
- FOREIGN KEY (chatId) REFERENCES [${s}].[chats](id) ON DELETE CASCADE,
4598
- FOREIGN KEY (messageId) REFERENCES [${s}].[messages](id),
4599
- CONSTRAINT [UQ_${s}_checkpoints_chatId_name] UNIQUE(chatId, name)
4679
+ FOREIGN KEY (chatId) REFERENCES [${schema}].[chats](id) ON DELETE CASCADE,
4680
+ FOREIGN KEY (messageId) REFERENCES [${schema}].[messages](id),
4681
+ CONSTRAINT [UQ_${schema}_checkpoints_chatId_name] UNIQUE(chatId, name)
4600
4682
  );
4601
4683
  END;
4602
4684
 
4603
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_checkpoints_chatId' AND object_id = OBJECT_ID('[${s}].[checkpoints]'))
4604
- CREATE INDEX [idx_${s}_checkpoints_chatId] ON [${s}].[checkpoints](chatId);
4685
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_checkpoints_chatId' AND object_id = OBJECT_ID('[${schema}].[checkpoints]'))
4686
+ CREATE INDEX [idx_${schema}_checkpoints_chatId] ON [${schema}].[checkpoints](chatId);
4605
4687
 
4606
- IF OBJECT_ID('[${s}].[messages_fts]', 'U') IS NULL
4688
+ IF OBJECT_ID('[${schema}].[messages_fts]', 'U') IS NULL
4607
4689
  BEGIN
4608
- CREATE TABLE [${s}].[messages_fts] (
4690
+ CREATE TABLE [${schema}].[messages_fts] (
4609
4691
  messageId NVARCHAR(255) NOT NULL,
4610
4692
  chatId NVARCHAR(255) NOT NULL,
4611
4693
  name NVARCHAR(255) NOT NULL,
4612
4694
  content NVARCHAR(MAX) NOT NULL,
4613
- CONSTRAINT [PK_${s}_messages_fts] PRIMARY KEY (messageId),
4614
- FOREIGN KEY (messageId) REFERENCES [${s}].[messages](id) ON DELETE CASCADE
4695
+ CONSTRAINT [PK_${schema}_messages_fts] PRIMARY KEY (messageId),
4696
+ FOREIGN KEY (messageId) REFERENCES [${schema}].[messages](id) ON DELETE CASCADE
4615
4697
  );
4616
4698
  END;
4617
4699
 
4618
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${s}_messages_fts_chatId' AND object_id = OBJECT_ID('[${s}].[messages_fts]'))
4619
- CREATE INDEX [idx_${s}_messages_fts_chatId] ON [${s}].[messages_fts](chatId);
4700
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'idx_${schema}_messages_fts_chatId' AND object_id = OBJECT_ID('[${schema}].[messages_fts]'))
4701
+ CREATE INDEX [idx_${schema}_messages_fts_chatId] ON [${schema}].[messages_fts](chatId);
4620
4702
 
4621
4703
  GO
4622
4704
 
4623
4705
  IF SERVERPROPERTY('IsFullTextInstalled') = 1
4624
4706
  BEGIN
4625
- IF NOT EXISTS (SELECT * FROM sys.fulltext_catalogs WHERE name = '${s}_context_store_catalog')
4626
- CREATE FULLTEXT CATALOG [${s}_context_store_catalog];
4707
+ IF NOT EXISTS (SELECT * FROM sys.fulltext_catalogs WHERE name = '${schema}_context_store_catalog')
4708
+ CREATE FULLTEXT CATALOG [${schema}_context_store_catalog];
4627
4709
 
4628
- IF NOT EXISTS (SELECT * FROM sys.fulltext_indexes WHERE object_id = OBJECT_ID('[${s}].[messages_fts]'))
4710
+ IF NOT EXISTS (SELECT * FROM sys.fulltext_indexes WHERE object_id = OBJECT_ID('[${schema}].[messages_fts]'))
4629
4711
  BEGIN
4630
- CREATE FULLTEXT INDEX ON [${s}].[messages_fts](content)
4631
- KEY INDEX [PK_${s}_messages_fts]
4632
- ON [${s}_context_store_catalog]
4712
+ CREATE FULLTEXT INDEX ON [${schema}].[messages_fts](content)
4713
+ KEY INDEX [PK_${schema}_messages_fts]
4714
+ ON [${schema}_context_store_catalog]
4633
4715
  WITH STOPLIST = SYSTEM;
4634
4716
  END;
4635
4717
  END;
@@ -4684,7 +4766,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
4684
4766
  EXEC sp_executesql @sql;
4685
4767
  END
4686
4768
  `);
4687
- const ddl = storeDDL(this.#schema);
4769
+ const ddl = storeDDL2(this.#schema);
4688
4770
  const batches = ddl.split(/\bGO\b/i).filter((b) => b.trim());
4689
4771
  for (const batch of batches) {
4690
4772
  if (batch.trim()) {
@@ -5469,6 +5551,43 @@ var SqliteStreamStore = class extends StreamStore {
5469
5551
  stream.error
5470
5552
  );
5471
5553
  }
5554
+ async upsertStream(stream) {
5555
+ const row = this.#stmt(
5556
+ `INSERT INTO streams (id, status, createdAt, startedAt, finishedAt, cancelRequestedAt, error)
5557
+ VALUES (?, ?, ?, ?, ?, ?, ?)
5558
+ ON CONFLICT(id) DO NOTHING
5559
+ RETURNING *`
5560
+ ).get(
5561
+ stream.id,
5562
+ stream.status,
5563
+ stream.createdAt,
5564
+ stream.startedAt,
5565
+ stream.finishedAt,
5566
+ stream.cancelRequestedAt,
5567
+ stream.error
5568
+ );
5569
+ if (row) {
5570
+ return {
5571
+ stream: {
5572
+ id: row.id,
5573
+ status: row.status,
5574
+ createdAt: row.createdAt,
5575
+ startedAt: row.startedAt,
5576
+ finishedAt: row.finishedAt,
5577
+ cancelRequestedAt: row.cancelRequestedAt,
5578
+ error: row.error
5579
+ },
5580
+ created: true
5581
+ };
5582
+ }
5583
+ const existing = await this.getStream(stream.id);
5584
+ if (!existing) {
5585
+ throw new Error(
5586
+ `Stream "${stream.id}" disappeared between upsert and fetch`
5587
+ );
5588
+ }
5589
+ return { stream: existing, created: false };
5590
+ }
5472
5591
  async getStream(streamId) {
5473
5592
  const row = this.#stmt("SELECT * FROM streams WHERE id = ?").get(
5474
5593
  streamId
@@ -5575,7 +5694,7 @@ var StreamManager = class {
5575
5694
  return this.#store;
5576
5695
  }
5577
5696
  async register(streamId) {
5578
- await this.#store.createStream({
5697
+ return this.#store.upsertStream({
5579
5698
  id: streamId,
5580
5699
  status: "queued",
5581
5700
  createdAt: Date.now(),