@ykurilov/agent-chat-storage-sqlite 0.107.1 → 0.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @ykurilov/agent-chat-storage-sqlite
2
2
 
3
+ ## 0.108.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b951be1: «Стоп», нажатый сразу после отправки, останавливает именно этот ход — как бы ни легли запросы. Раньше «Стоп», дошедший до сервера раньше начала хода (маршрут, вход, чтение базы) или попавший на другую копию сервера, получал «нечего останавливать», и ответ дописывался до конца.
8
+
9
+ - Каждый запрос, начинающий ход (отправка, правка, переделка, повтор, решение по подтверждению, ответ на виджет, поправка, начавшая ход), несёт новый `turnRequestId` (`TurnRequestContext.turnRequestId`). Экран SDK шлёт его сам и называет в теле `POST /stop` (`{ turnRequestId }`).
10
+ - Сервер: ход этого запроса идёт на копии — останавливается сразу; ещё не начался или идёт на другой копии — «Стоп» запоминается (`202`), ход останавливается сразу после старта или на сверке с базой раз в 2 с (`STOP_REQUESTS_CHECK_EVERY_MS`). Ход другого запроса такой «Стоп» не трогает: запоздавший «Стоп» не остановит следующий вопрос. `service.stop(userId, chatId, { turnRequestId })`.
11
+ - Ответ на поправки — новый ход с id последней поправки: «Стоп» прежнего ответа его не трогает (на любой копии), «Стоп» с id поправки останавливает.
12
+ - `POST /stop` с `turnRequestId` всегда отвечает `202` (остановлено или запомнено), даже если хода с этим id так и не будет. Без id — как раньше: `202` или `204`.
13
+ - Хранилища: необязательные `saveStopRequest(request, { keepPerOwner })` / `hasStopRequest`. Запись несёт `ownerId`, живёт час; у человека не больше `keepPerOwner` (служба передаёт 100) живых записей — сверх уходят его самые ранние, чужие не трогаются. Тот же предел — в памяти копии. SQLite и PostgreSQL — таблица `stop_requests`, миграция применяется сама. Свои хранилища без этих методов работают как раньше: ранний «Стоп» держится в памяти копии.
14
+ - «Стоп» без `turnRequestId` (свои клиенты, ход, к которому экран только подключился) работает как раньше.
15
+
16
+ ### Patch Changes
17
+
18
+ - Updated dependencies [b951be1]
19
+ - @ykurilov/agent-chat-core@0.108.0
20
+
21
+ ## 0.107.2
22
+
23
+ ### Patch Changes
24
+
25
+ - 4430082: Хранилища SQLite и PostgreSQL собираются бандлером Next.js (Turbopack и webpack, `next dev`, `next build`, `output: "standalone"`) без `serverExternalPackages` и без настройки трассировки. Раньше сборка падала с «Module not found: Can't resolve '../drizzle'» (путь к папке миграций бандлер принимал за импорт), а standalone-сервер — с «Can't find meta/_journal.json» (папку миграций Next не копировал). Теперь миграции вшиты в код пакетов (`applyEmbeddedMigrations` и тип `EmbeddedMigration` в ядре), журнал и хеши миграций прежние: существующие базы ничего не применяют заново.
26
+ - Updated dependencies [4430082]
27
+ - @ykurilov/agent-chat-core@0.107.2
28
+
3
29
  ## 0.107.1
4
30
 
5
31
  ### Patch Changes
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  // src/sqlite-storage.ts
2
- import { fileURLToPath } from "url";
3
2
  import {
4
3
  aliveAtByLocalClock,
5
4
  assertChatDataFilter,
@@ -22,11 +21,10 @@ import {
22
21
  import Database from "better-sqlite3";
23
22
  import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, ne, sql as sql2 } from "drizzle-orm";
24
23
  import { drizzle } from "drizzle-orm/better-sqlite3";
25
- import { readMigrationFiles } from "drizzle-orm/migrator";
26
24
 
27
25
  // src/schema.ts
28
26
  import { sql } from "drizzle-orm";
29
- import { index, integer, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
27
+ import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
30
28
  var chats = sqliteTable(
31
29
  "chats",
32
30
  {
@@ -168,6 +166,20 @@ var chatTurnLeases = sqliteTable("chat_turn_leases", {
168
166
  holder: text("holder").notNull(),
169
167
  until: integer("until").notNull()
170
168
  });
169
+ var stopRequests = sqliteTable(
170
+ "stop_requests",
171
+ {
172
+ chatId: text("chat_id").notNull(),
173
+ turnRequestId: text("turn_request_id").notNull(),
174
+ ownerId: text("owner_id").notNull(),
175
+ expiresAt: integer("expires_at").notNull()
176
+ },
177
+ (table) => [
178
+ primaryKey({ columns: [table.chatId, table.turnRequestId] }),
179
+ index("stop_requests_expires_idx").on(table.expiresAt),
180
+ index("stop_requests_owner_idx").on(table.ownerId, table.expiresAt)
181
+ ]
182
+ );
171
183
  var pendingBursts = sqliteTable("pending_bursts", {
172
184
  chatId: text("chat_id").primaryKey(),
173
185
  ownerId: text("owner_id").notNull(),
@@ -213,8 +225,118 @@ var memoryOptimizationRuns = sqliteTable(
213
225
  ]
214
226
  );
215
227
 
228
+ // src/drizzle-migrations.generated.ts
229
+ var migrations = [
230
+ // 0000_init
231
+ { folderMillis: 1790637217361, hash: "fa6180a59138a232a1cb9d94efa6031bb233ecd91bcadf71a4d2e73e96e4e86a", bps: true, sql: [
232
+ "CREATE TABLE `chats` (\n `id` text PRIMARY KEY NOT NULL,\n `owner_id` text NOT NULL,\n `model_id` text NOT NULL,\n `provider_id` text NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n",
233
+ "\nCREATE INDEX `chats_owner_updated_idx` ON `chats` (`owner_id`,`updated_at`);",
234
+ "\nCREATE TABLE `messages` (\n `id` text PRIMARY KEY NOT NULL,\n `chat_id` text NOT NULL,\n `parent_id` text,\n `role` text NOT NULL,\n `parts` text NOT NULL,\n `format_version` integer NOT NULL,\n `status` text NOT NULL,\n `model_id` text,\n `provider_id` text,\n `usage` text,\n `reasoning_durations_ms` text NOT NULL,\n `error` text,\n `created_at` text NOT NULL,\n FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade\n);\n",
235
+ "\nCREATE INDEX `messages_chat_created_idx` ON `messages` (`chat_id`,`created_at`);",
236
+ '\nCREATE INDEX `messages_streaming_idx` ON `messages` (`status`) WHERE "messages"."status" = \'streaming\';'
237
+ ] },
238
+ // 0001_message_seq
239
+ { folderMillis: 1790717189202, hash: "423ea238f8cd3309c77df1f090d873efbe26132224083db668a280e34ee7543a", bps: true, sql: [
240
+ "ALTER TABLE `messages` ADD `seq` integer DEFAULT 0 NOT NULL;",
241
+ "\nUPDATE `messages` SET `seq` = `rowid`;",
242
+ "\nDROP INDEX `messages_chat_created_idx`;",
243
+ "\nCREATE UNIQUE INDEX `messages_seq_idx` ON `messages` (`seq`);",
244
+ "\nCREATE INDEX `messages_chat_created_idx` ON `messages` (`chat_id`,`created_at`,`seq`);\n"
245
+ ] },
246
+ // 0002_chat_reasoning
247
+ { folderMillis: 1790718146337, hash: "28847ceb90b91ec97fce1d232bb1b140eab5ea0b193524cb550d1b7799bfc77e", bps: true, sql: [
248
+ "ALTER TABLE `chats` ADD `reasoning` text;"
249
+ ] },
250
+ // 0003_compactions
251
+ { folderMillis: 1790721542955, hash: "cbcd2847791f9efe7ee6304405090c708c3d695fac1fd2a30b57da0b466f1a9a", bps: true, sql: [
252
+ "CREATE TABLE `compactions` (\n `id` text PRIMARY KEY NOT NULL,\n `chat_id` text NOT NULL,\n `from_message_id` text NOT NULL,\n `through_message_id` text NOT NULL,\n `summary` text NOT NULL,\n `summary_tokens` integer NOT NULL,\n `model_id` text NOT NULL,\n `provider_id` text NOT NULL,\n `usage` text,\n `created_at` text NOT NULL,\n `seq` integer DEFAULT 0 NOT NULL,\n FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade\n);\n",
253
+ "\nCREATE INDEX `compactions_chat_seq_idx` ON `compactions` (`chat_id`,`seq`);",
254
+ "\nCREATE UNIQUE INDEX `compactions_seq_idx` ON `compactions` (`seq`);"
255
+ ] },
256
+ // 0004_branch_selections
257
+ { folderMillis: 1790735648121, hash: "823b1f9e9f622882df6964e056206488ef1dc8d57e863822fe2e85ed5a4da97f", bps: true, sql: [
258
+ "CREATE TABLE `branch_selections` (\n `id` text PRIMARY KEY NOT NULL,\n `chat_id` text NOT NULL,\n `message_id` text NOT NULL,\n `selected_at` text NOT NULL,\n `seq` integer DEFAULT 0 NOT NULL,\n FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade\n);\n",
259
+ "\nCREATE INDEX `branch_selections_chat_seq_idx` ON `branch_selections` (`chat_id`,`seq`);",
260
+ "\nCREATE UNIQUE INDEX `branch_selections_seq_idx` ON `branch_selections` (`seq`);"
261
+ ] },
262
+ // 0005_chat_title
263
+ { folderMillis: 1790738333184, hash: "d51260d54c7710b880b88ec94ca8280c1d2151ea002c4ab5fb0f6787a091456b", bps: true, sql: [
264
+ "ALTER TABLE `chats` ADD `title` text;",
265
+ "\n-- \u041D\u0430\u0437\u0432\u0430\u043D\u0438\u044F \u0443 \u043F\u0440\u0435\u0436\u043D\u0438\u0445 \u0447\u0430\u0442\u043E\u0432: \u0438\u0437 \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u0442\u0435\u043A\u0441\u0442\u0430 \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0441\u043E\u0431\u0435\u0441\u0435\u0434\u043D\u0438\u043A\u0430, \u043A\u0430\u043A \u044D\u0442\u043E \u0434\u0435\u043B\u0430\u0435\u0442 \u044F\u0434\u0440\u043E\n-- (\u043F\u0440\u043E\u0431\u0435\u043B\u044B \u0441\u0445\u043B\u043E\u043F\u043D\u0443\u0442\u044B, \u043D\u0435 \u0434\u043B\u0438\u043D\u043D\u0435\u0435 60 \u0437\u043D\u0430\u043A\u043E\u0432 \u0438 \xAB\u2026\xBB). \u041E\u0447\u0435\u043D\u044C \u0434\u043B\u0438\u043D\u043D\u044B\u0435 \u0440\u044F\u0434\u044B \u043F\u0440\u043E\u0431\u0435\u043B\u043E\u0432 (\u0431\u043E\u043B\u044C\u0448\u0435 64) \u0441\u0445\u043B\u043E\u043F\u044B\u0432\u0430\u044E\u0442\u0441\u044F \u043D\u0435 \u0434\u043E \u043A\u043E\u043D\u0446\u0430.\nUPDATE `chats` SET `title` = (\n SELECT CASE\n WHEN length(t) = 0 THEN NULL\n WHEN length(t) > 60 THEN rtrim(substr(t, 1, 60)) || '\u2026'\n ELSE t\n END\n FROM (\n SELECT trim(replace(replace(replace(replace(replace(replace(replace(replace(replace(x, char(13), ' '), char(10), ' '), char(9), ' '), ' ', ' '), ' ', ' '), ' ', ' '), ' ', ' '), ' ', ' '), ' ', ' ')) AS t\n FROM (\n SELECT (\n SELECT json_extract(p.value, '$.text') FROM json_each(m.parts) AS p\n WHERE json_extract(p.value, '$.type') = 'text' LIMIT 1\n ) AS x\n FROM `messages` AS m\n WHERE m.chat_id = `chats`.id AND m.role = 'user'\n ORDER BY m.created_at, m.seq LIMIT 1\n )\n )\n);\n"
266
+ ] },
267
+ // 0006_usage_records
268
+ { folderMillis: 1790740140515, hash: "a97547795d7eaffc5cf323f94382fdeace070362686b277f718f41263f4eaf86", bps: true, sql: [
269
+ "CREATE TABLE `usage_records` (\n `id` text PRIMARY KEY NOT NULL,\n `owner_id` text NOT NULL,\n `chat_id` text NOT NULL,\n `message_id` text,\n `source` text NOT NULL,\n `model_id` text NOT NULL,\n `provider_id` text NOT NULL,\n `input_tokens` integer NOT NULL,\n `cached_input_tokens` integer NOT NULL,\n `cache_write_tokens` integer NOT NULL,\n `output_tokens` integer NOT NULL,\n `reasoning_tokens` integer NOT NULL,\n `cost_usd` real NOT NULL,\n `created_at` text NOT NULL\n);\n",
270
+ "\nCREATE INDEX `usage_records_owner_created_idx` ON `usage_records` (`owner_id`,`created_at`);",
271
+ "\nCREATE INDEX `usage_records_chat_created_idx` ON `usage_records` (`chat_id`,`created_at`);"
272
+ ] },
273
+ // 0007_user_model_choices
274
+ { folderMillis: 1790752788778, hash: "e065052e74b77c78c2e772af08202085163bf334a6cef0a0eef5a3c8f7be0776", bps: true, sql: [
275
+ "CREATE TABLE `user_model_choices` (\n `owner_id` text PRIMARY KEY NOT NULL,\n `model_id` text NOT NULL,\n `provider_id` text NOT NULL,\n `reasoning` text,\n `updated_at` text NOT NULL\n);\n"
276
+ ] },
277
+ // 0008_voice_dialog
278
+ { folderMillis: 1790755964781, hash: "0bad85e76400d4ae4fd25d452fbcf7045c620ec159b077c073be518c5fda6c27", bps: true, sql: [
279
+ "CREATE TABLE `voice_choices` (\n `owner_id` text PRIMARY KEY NOT NULL,\n `voice_id` text NOT NULL,\n `updated_at` text NOT NULL\n);\n",
280
+ "\nALTER TABLE `messages` ADD `voice_cut` text;"
281
+ ] },
282
+ // 0009_memory_notes
283
+ { folderMillis: 1790759903309, hash: "24eacd844307e151fcca6162d0a6cb7511811e340f11e6d27a3a348e774adc66", bps: true, sql: [
284
+ "CREATE TABLE `memory_notes` (\n `id` text PRIMARY KEY NOT NULL,\n `owner_id` text NOT NULL,\n `categories` text NOT NULL,\n `content` text NOT NULL,\n `version` integer DEFAULT 1 NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n",
285
+ "\nCREATE INDEX `memory_notes_owner_updated_idx` ON `memory_notes` (`owner_id`,`updated_at`);"
286
+ ] },
287
+ // 0010_memory_optimization
288
+ { folderMillis: 1790761149164, hash: "59af37bb0e69b0c69a9087d8e37028af09789d8a9764043250d8a06759bbaf39", bps: true, sql: [
289
+ "CREATE TABLE `memory_optimization_runs` (\n `id` text PRIMARY KEY NOT NULL,\n `owner_id` text NOT NULL,\n `started_at` integer NOT NULL,\n `finished_at` integer,\n `status` text NOT NULL,\n `groups` text DEFAULT '[]' NOT NULL,\n `error` text,\n `usage_record_id` text\n);\n",
290
+ "\nCREATE INDEX `memory_optimization_runs_owner_started_idx` ON `memory_optimization_runs` (`owner_id`,`started_at`);",
291
+ '\nCREATE UNIQUE INDEX `memory_optimization_runs_one_running_idx` ON `memory_optimization_runs` (`owner_id`) WHERE "memory_optimization_runs"."status" = \'running\';',
292
+ "\nALTER TABLE `memory_notes` ADD `merged_into` text;",
293
+ "\nCREATE INDEX `memory_notes_merged_into_idx` ON `memory_notes` (`merged_into`);"
294
+ ] },
295
+ // 0011_usage_estimated
296
+ { folderMillis: 1790938845657, hash: "9f80b73e93bc185baa36a03fd0fbc997998bd99c64f403e5c7913f9fa8d18722", bps: true, sql: [
297
+ "ALTER TABLE `usage_records` ADD `estimated` integer DEFAULT false NOT NULL;"
298
+ ] },
299
+ // 0012_message_alive_at
300
+ { folderMillis: 1790944385262, hash: "9f6428da30a32aec3b8569efd56f4ea71b212f01cb4d04ea9ed5d4220d0b9a31", bps: true, sql: [
301
+ "ALTER TABLE `messages` ADD `alive_at` text;"
302
+ ] },
303
+ // 0013_spending_limit_states
304
+ { folderMillis: 1791185874367, hash: "b9bb386d3aa74283aac71512527f1ffa75bd74a0661df7cc0151996fe51b5bcf", bps: true, sql: [
305
+ "CREATE TABLE `spending_limit_states` (\n `key` text PRIMARY KEY NOT NULL,\n `value` text NOT NULL,\n `version` integer NOT NULL,\n `updated_at` text NOT NULL\n);\n"
306
+ ] },
307
+ // 0014_chat_origin
308
+ { folderMillis: 1791197610961, hash: "b5e906059b8c10c2d88a7a0cd1eb2608ebe3106f6f0fa5081d64f7c59af59e63", bps: true, sql: [
309
+ "ALTER TABLE `chats` ADD `origin` text;"
310
+ ] },
311
+ // 0015_chat_subject_after_turn
312
+ { folderMillis: 1791265707340, hash: "44b870dcbcaf4ef7bec3416b36d4ab2cb58b62afb821744b49b301507bdce538", bps: true, sql: [
313
+ "ALTER TABLE `chats` ADD `subject_key` text;",
314
+ "\nALTER TABLE `chats` ADD `subject_data` text;",
315
+ "\nCREATE UNIQUE INDEX `chats_owner_subject_idx` ON `chats` (`owner_id`,`subject_key`);",
316
+ "\nALTER TABLE `messages` ADD `after_turn` text;",
317
+ '\nCREATE INDEX `messages_after_turn_pending_idx` ON `messages` (`after_turn`) WHERE "messages"."after_turn" = \'pending\';'
318
+ ] },
319
+ // 0016_chat_closed
320
+ { folderMillis: 1791285236475, hash: "2b574bb852b12d867146b1a68a05c46c39840b8158b1e6382833fcf8df903a7e", bps: true, sql: [
321
+ "ALTER TABLE `chats` ADD `closed` text;"
322
+ ] },
323
+ // 0017_chat_turn_leases
324
+ { folderMillis: 1791967992215, hash: "caf472f803cc3d42322de0a601392afcefad8b9c04909051d3f7a1c1f5591373", bps: true, sql: [
325
+ "CREATE TABLE `chat_turn_leases` (\n `chat_id` text PRIMARY KEY NOT NULL,\n `holder` text NOT NULL,\n `until` integer NOT NULL\n);\n"
326
+ ] },
327
+ // 0018_pending_bursts
328
+ { folderMillis: 1792017491455, hash: "88c4008efaa9701f32deb336f35b66693638acb510530f399f1a4fcb922358ca", bps: true, sql: [
329
+ "CREATE TABLE `pending_bursts` (\n `chat_id` text PRIMARY KEY NOT NULL,\n `owner_id` text NOT NULL,\n `message_id` text NOT NULL,\n `due_at` integer NOT NULL,\n `holder` text NOT NULL,\n `held_until` integer NOT NULL,\n `page` text\n);\n"
330
+ ] },
331
+ // 0019_stop_requests
332
+ { folderMillis: 1794403274307, hash: "7692f3fc2a232a0f2f9de347a600bc2cd35765faa737a57e7bf4bbead914d3b3", bps: true, sql: [
333
+ "CREATE TABLE `stop_requests` (\n `chat_id` text NOT NULL,\n `turn_request_id` text NOT NULL,\n `owner_id` text NOT NULL,\n `expires_at` integer NOT NULL,\n PRIMARY KEY(`chat_id`, `turn_request_id`)\n);\n",
334
+ "\nCREATE INDEX `stop_requests_expires_idx` ON `stop_requests` (`expires_at`);",
335
+ "\nCREATE INDEX `stop_requests_owner_idx` ON `stop_requests` (`owner_id`,`expires_at`);"
336
+ ] }
337
+ ];
338
+
216
339
  // src/sqlite-storage.ts
217
- var migrationsFolder = fileURLToPath(new URL("../drizzle", import.meta.url));
218
340
  var MIGRATIONS_TABLE = "__agent_chat_migrations";
219
341
  var SHARED_MIGRATIONS_TABLE = "__drizzle_migrations";
220
342
  var ForeignChatTablesError = class extends Error {
@@ -233,7 +355,7 @@ function assertNoForeignChatTables(sqlite, filePath) {
233
355
  const names = tableNames(sqlite);
234
356
  const found = ["chats", "messages"].filter((name) => names.has(name));
235
357
  if (found.length === 0) return;
236
- const firstMigrationHash = readMigrationFiles({ migrationsFolder })[0]?.hash;
358
+ const firstMigrationHash = migrations[0]?.hash;
237
359
  const ours = [MIGRATIONS_TABLE, SHARED_MIGRATIONS_TABLE].some((table) => {
238
360
  try {
239
361
  return names.has(table) && sqlite.prepare(`select 1 from "${table}" where hash = ?`).get(firstMigrationHash) !== void 0;
@@ -256,8 +378,7 @@ function moveSharedMigrationJournal(sqlite) {
256
378
  } catch {
257
379
  return;
258
380
  }
259
- const sdk = readMigrationFiles({ migrationsFolder });
260
- const ours = rows.filter((row) => sdk.some((migration) => migration.hash === row.hash || migration.folderMillis === Number(row.created_at)));
381
+ const ours = rows.filter((row) => migrations.some((migration) => migration.hash === row.hash || migration.folderMillis === Number(row.created_at)));
261
382
  if (ours.length === 0) return;
262
383
  sqlite.exec(`create table "${MIGRATIONS_TABLE}" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)`);
263
384
  const insert = sqlite.prepare(`insert into "${MIGRATIONS_TABLE}" (hash, created_at) values (?, ?)`);
@@ -265,7 +386,6 @@ function moveSharedMigrationJournal(sqlite) {
265
386
  }).immediate();
266
387
  }
267
388
  function applyMigrations(sqlite) {
268
- const migrations = readMigrationFiles({ migrationsFolder });
269
389
  sqlite.transaction(() => {
270
390
  sqlite.exec(`create table if not exists "${MIGRATIONS_TABLE}" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)`);
271
391
  const rows = sqlite.prepare(`select hash, created_at from "${MIGRATIONS_TABLE}"`).all();
@@ -443,6 +563,7 @@ function createSqliteChatStorage(options) {
443
563
  tx.delete(chats).where(eq(chats.id, chatId)).run();
444
564
  tx.delete(chatTurnLeases).where(eq(chatTurnLeases.chatId, chatId)).run();
445
565
  tx.delete(pendingBursts).where(eq(pendingBursts.chatId, chatId)).run();
566
+ tx.delete(stopRequests).where(eq(stopRequests.chatId, chatId)).run();
446
567
  }, { behavior: "immediate" });
447
568
  },
448
569
  async claimChatTurn(chatId, holder, leaseMs) {
@@ -460,6 +581,20 @@ function createSqliteChatStorage(options) {
460
581
  async clearChatTurnLeases() {
461
582
  db.delete(chatTurnLeases).run();
462
583
  },
584
+ async saveStopRequest(request, { keepPerOwner }) {
585
+ db.transaction((tx) => {
586
+ tx.delete(stopRequests).where(lte(stopRequests.expiresAt, Date.parse(request.stoppedAt))).run();
587
+ tx.insert(stopRequests).values({ chatId: request.chatId, turnRequestId: request.turnRequestId, ownerId: request.ownerId, expiresAt: Date.parse(request.expiresAt) }).onConflictDoNothing().run();
588
+ const own = tx.select({ chatId: stopRequests.chatId, turnRequestId: stopRequests.turnRequestId }).from(stopRequests).where(eq(stopRequests.ownerId, request.ownerId)).orderBy(desc(stopRequests.expiresAt)).all();
589
+ for (const extra of own.slice(keepPerOwner)) {
590
+ tx.delete(stopRequests).where(and(eq(stopRequests.chatId, extra.chatId), eq(stopRequests.turnRequestId, extra.turnRequestId))).run();
591
+ }
592
+ }, { behavior: "immediate" });
593
+ },
594
+ async hasStopRequest(chatId, turnRequestId) {
595
+ const row = db.select({ chatId: stopRequests.chatId }).from(stopRequests).where(and(eq(stopRequests.chatId, chatId), eq(stopRequests.turnRequestId, turnRequestId))).get();
596
+ return row !== void 0;
597
+ },
463
598
  async savePendingBurst(burst) {
464
599
  const row = {
465
600
  chatId: burst.chatId,