@ykurilov/agent-chat-storage-sqlite 0.107.2 → 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,23 @@
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
+
3
21
  ## 0.107.2
4
22
 
5
23
  ### Patch Changes
package/dist/index.js CHANGED
@@ -24,7 +24,7 @@ import { drizzle } from "drizzle-orm/better-sqlite3";
24
24
 
25
25
  // src/schema.ts
26
26
  import { sql } from "drizzle-orm";
27
- 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";
28
28
  var chats = sqliteTable(
29
29
  "chats",
30
30
  {
@@ -166,6 +166,20 @@ var chatTurnLeases = sqliteTable("chat_turn_leases", {
166
166
  holder: text("holder").notNull(),
167
167
  until: integer("until").notNull()
168
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
+ );
169
183
  var pendingBursts = sqliteTable("pending_bursts", {
170
184
  chatId: text("chat_id").primaryKey(),
171
185
  ownerId: text("owner_id").notNull(),
@@ -313,6 +327,12 @@ var migrations = [
313
327
  // 0018_pending_bursts
314
328
  { folderMillis: 1792017491455, hash: "88c4008efaa9701f32deb336f35b66693638acb510530f399f1a4fcb922358ca", bps: true, sql: [
315
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`);"
316
336
  ] }
317
337
  ];
318
338
 
@@ -543,6 +563,7 @@ function createSqliteChatStorage(options) {
543
563
  tx.delete(chats).where(eq(chats.id, chatId)).run();
544
564
  tx.delete(chatTurnLeases).where(eq(chatTurnLeases.chatId, chatId)).run();
545
565
  tx.delete(pendingBursts).where(eq(pendingBursts.chatId, chatId)).run();
566
+ tx.delete(stopRequests).where(eq(stopRequests.chatId, chatId)).run();
546
567
  }, { behavior: "immediate" });
547
568
  },
548
569
  async claimChatTurn(chatId, holder, leaseMs) {
@@ -560,6 +581,20 @@ function createSqliteChatStorage(options) {
560
581
  async clearChatTurnLeases() {
561
582
  db.delete(chatTurnLeases).run();
562
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
+ },
563
598
  async savePendingBurst(burst) {
564
599
  const row = {
565
600
  chatId: burst.chatId,