@ykurilov/agent-chat-storage-postgres 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-postgres
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/README.md CHANGED
@@ -26,7 +26,8 @@ await storage.close(); // при остановке сервера
26
26
  - Расход помечается «примерно» (колонка `estimated`), идущий ответ — «жив» (`alive_at`); обе миграции применяются сами.
27
27
  - Несколько копий сервера на одной базе можно: идущий ответ отмечает «жив» (`alive_at`), и копия прерывает только
28
28
  брошенные ответы. Время отметки берётся из часов базы, часы машин с копиями могут расходиться. Запросы одного чата
29
- держите на одной копии: поток ответа и «Стоп» живут в её памяти.
29
+ держите на одной копии: поток ответа живёт в её памяти. «Стоп» с id запроса хода (его шлёт экран SDK) доходит и с
30
+ другой копии: он записывается в таблицу `stop_requests` (живёт час, не больше 100 записей на человека).
30
31
 
31
32
  Тесты. Общий набор проверок хранилища идёт на встроенном PostgreSQL (pglite), ничего ставить не нужно. Чтобы прогнать
32
33
  тот же набор на настоящей базе, задайте `AGENT_CHAT_TEST_POSTGRES_URL`.
package/dist/index.js CHANGED
@@ -25,7 +25,7 @@ import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, ne, sql as sq
25
25
 
26
26
  // src/schema.ts
27
27
  import { sql } from "drizzle-orm";
28
- import { bigint, boolean, doublePrecision, index, integer, json, jsonb, pgSchema, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
28
+ import { bigint, boolean, doublePrecision, index, integer, json, jsonb, pgSchema, primaryKey, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
29
29
  var agentChatSchema = pgSchema("agent_chat");
30
30
  var chats = agentChatSchema.table(
31
31
  "chats",
@@ -163,6 +163,20 @@ var chatTurnLeases = agentChatSchema.table("chat_turn_leases", {
163
163
  holder: text("holder").notNull(),
164
164
  until: timestamp("until", { withTimezone: true, mode: "string" }).notNull()
165
165
  });
166
+ var stopRequests = agentChatSchema.table(
167
+ "stop_requests",
168
+ {
169
+ chatId: text("chat_id").notNull(),
170
+ turnRequestId: text("turn_request_id").notNull(),
171
+ ownerId: text("owner_id").notNull(),
172
+ expiresAt: timestamp("expires_at", { withTimezone: true, mode: "date" }).notNull()
173
+ },
174
+ (table) => [
175
+ primaryKey({ columns: [table.chatId, table.turnRequestId] }),
176
+ index("stop_requests_expires_idx").on(table.expiresAt),
177
+ index("stop_requests_owner_idx").on(table.ownerId, table.expiresAt)
178
+ ]
179
+ );
166
180
  var pendingBursts = agentChatSchema.table("pending_bursts", {
167
181
  chatId: text("chat_id").primaryKey(),
168
182
  ownerId: text("owner_id").notNull(),
@@ -367,6 +381,7 @@ function createDrizzleChatStorage(db) {
367
381
  await tx.delete(chats).where(eq(chats.id, chatId));
368
382
  await tx.delete(chatTurnLeases).where(eq(chatTurnLeases.chatId, chatId));
369
383
  await tx.delete(pendingBursts).where(eq(pendingBursts.chatId, chatId));
384
+ await tx.delete(stopRequests).where(eq(stopRequests.chatId, chatId));
370
385
  });
371
386
  },
372
387
  async claimChatTurn(chatId, holder, leaseMs) {
@@ -384,6 +399,20 @@ function createDrizzleChatStorage(db) {
384
399
  async clearChatTurnLeases() {
385
400
  await db.delete(chatTurnLeases);
386
401
  },
402
+ async saveStopRequest(request, { keepPerOwner }) {
403
+ await db.delete(stopRequests).where(lte(stopRequests.expiresAt, new Date(request.stoppedAt)));
404
+ await db.transaction(async (tx) => {
405
+ await tx.insert(stopRequests).values({ chatId: request.chatId, turnRequestId: request.turnRequestId, ownerId: request.ownerId, expiresAt: new Date(request.expiresAt) }).onConflictDoNothing();
406
+ const own = await tx.select({ chatId: stopRequests.chatId, turnRequestId: stopRequests.turnRequestId }).from(stopRequests).where(eq(stopRequests.ownerId, request.ownerId)).orderBy(desc(stopRequests.expiresAt));
407
+ for (const extra of own.slice(keepPerOwner)) {
408
+ await tx.delete(stopRequests).where(and(eq(stopRequests.chatId, extra.chatId), eq(stopRequests.turnRequestId, extra.turnRequestId)));
409
+ }
410
+ });
411
+ },
412
+ async hasStopRequest(chatId, turnRequestId) {
413
+ const rows = await db.select({ chatId: stopRequests.chatId }).from(stopRequests).where(and(eq(stopRequests.chatId, chatId), eq(stopRequests.turnRequestId, turnRequestId))).limit(1);
414
+ return rows.length > 0;
415
+ },
387
416
  async savePendingBurst(burst) {
388
417
  const row = {
389
418
  chatId: burst.chatId,
@@ -811,17 +840,160 @@ function toOptimizationRun(row) {
811
840
  }
812
841
 
813
842
  // src/migrate.ts
814
- import { fileURLToPath } from "url";
815
843
  import { drizzle } from "drizzle-orm/node-postgres";
816
- import { migrate } from "drizzle-orm/node-postgres/migrator";
817
- import { migratePostgresSchema } from "@ykurilov/agent-chat-core";
818
- var migrationsFolder = fileURLToPath(new URL("../drizzle", import.meta.url));
844
+ import { migratePostgresSchema, applyEmbeddedMigrations } from "@ykurilov/agent-chat-core";
845
+
846
+ // src/drizzle-migrations.generated.ts
847
+ var migrations = [
848
+ // 0000_init
849
+ { folderMillis: 1790715871912, hash: "5bda099f3dd949b1d48959adaae5ba3180b5245db34026bb4b8b674d3f774400", bps: true, sql: [
850
+ 'CREATE SCHEMA IF NOT EXISTS "agent_chat";\n',
851
+ '\nCREATE TABLE "agent_chat"."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',
852
+ '\nCREATE TABLE "agent_chat"."messages" (\n "seq" bigint GENERATED ALWAYS AS IDENTITY (sequence name "agent_chat"."messages_seq_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),\n "id" text PRIMARY KEY NOT NULL,\n "chat_id" text NOT NULL,\n "parent_id" text,\n "role" text NOT NULL,\n "parts" json NOT NULL,\n "format_version" integer NOT NULL,\n "status" text NOT NULL,\n "model_id" text,\n "provider_id" text,\n "usage" json,\n "reasoning_durations_ms" json NOT NULL,\n "error" json,\n "created_at" text NOT NULL\n);\n',
853
+ '\nALTER TABLE "agent_chat"."messages" ADD CONSTRAINT "messages_chat_id_chats_id_fk" FOREIGN KEY ("chat_id") REFERENCES "agent_chat"."chats"("id") ON DELETE cascade ON UPDATE no action;',
854
+ '\nCREATE INDEX "chats_owner_updated_idx" ON "agent_chat"."chats" USING btree ("owner_id","updated_at");',
855
+ '\nCREATE INDEX "messages_chat_created_idx" ON "agent_chat"."messages" USING btree ("chat_id","created_at","seq");',
856
+ `
857
+ CREATE INDEX "messages_streaming_idx" ON "agent_chat"."messages" USING btree ("status") WHERE "agent_chat"."messages"."status" = 'streaming';`
858
+ ] },
859
+ // 0001_chat_reasoning
860
+ { folderMillis: 1790718471271, hash: "ea0c40817fb8618fb95f9ad20744688d3eed2dbef79830041ca967944f312376", bps: true, sql: [
861
+ 'ALTER TABLE "agent_chat"."chats" ADD COLUMN "reasoning" text;'
862
+ ] },
863
+ // 0002_compactions
864
+ { folderMillis: 1790721546337, hash: "ef8ad0fbd22be1d1015ee8dad8e2f6138d01b28a7403aecbe12d18ee895d52ba", bps: true, sql: [
865
+ 'CREATE TABLE "agent_chat"."compactions" (\n "seq" bigint GENERATED ALWAYS AS IDENTITY (sequence name "agent_chat"."compactions_seq_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),\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" json,\n "created_at" text NOT NULL\n);\n',
866
+ '\nALTER TABLE "agent_chat"."compactions" ADD CONSTRAINT "compactions_chat_id_chats_id_fk" FOREIGN KEY ("chat_id") REFERENCES "agent_chat"."chats"("id") ON DELETE cascade ON UPDATE no action;',
867
+ '\nCREATE INDEX "compactions_chat_seq_idx" ON "agent_chat"."compactions" USING btree ("chat_id","seq");'
868
+ ] },
869
+ // 0003_branch_selections
870
+ { folderMillis: 1790735648692, hash: "10c33b0e6010b035042a8660f35ed29a0593fae4c54ecc2740d75cc3af55153d", bps: true, sql: [
871
+ 'CREATE TABLE "agent_chat"."branch_selections" (\n "seq" bigint GENERATED ALWAYS AS IDENTITY (sequence name "agent_chat"."branch_selections_seq_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1),\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);\n',
872
+ '\nALTER TABLE "agent_chat"."branch_selections" ADD CONSTRAINT "branch_selections_chat_id_chats_id_fk" FOREIGN KEY ("chat_id") REFERENCES "agent_chat"."chats"("id") ON DELETE cascade ON UPDATE no action;',
873
+ '\nCREATE INDEX "branch_selections_chat_seq_idx" ON "agent_chat"."branch_selections" USING btree ("chat_id","seq");'
874
+ ] },
875
+ // 0004_chat_title
876
+ { folderMillis: 1790738333623, hash: "7a54293f92dad4eb6ee2db7b81587ea01ca66a60d647127f04842c87dbcef1fd", bps: true, sql: [
877
+ 'ALTER TABLE "agent_chat"."chats" ADD COLUMN "title" text;',
878
+ `
879
+ -- \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
880
+ -- (\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).
881
+ UPDATE "agent_chat"."chats" AS c SET "title" = (
882
+ SELECT CASE
883
+ WHEN char_length(t) = 0 THEN NULL
884
+ WHEN char_length(t) > 60 THEN rtrim(left(t, 60)) || '\u2026'
885
+ ELSE t
886
+ END
887
+ FROM (
888
+ SELECT btrim(regexp_replace(x, '\\s+', ' ', 'g')) AS t
889
+ FROM (
890
+ SELECT (
891
+ SELECT p->>'text' FROM json_array_elements(m.parts) AS p
892
+ WHERE p->>'type' = 'text' LIMIT 1
893
+ ) AS x
894
+ FROM "agent_chat"."messages" AS m
895
+ WHERE m.chat_id = c.id AND m.role = 'user'
896
+ ORDER BY m.created_at, m.seq LIMIT 1
897
+ ) AS first_text
898
+ ) AS cleaned
899
+ );
900
+ `
901
+ ] },
902
+ // 0005_usage_records
903
+ { folderMillis: 1790740141054, hash: "42471afa5087b46a870158f268e68a53d9411042772aa19de466479ac56707ce", bps: true, sql: [
904
+ 'CREATE TABLE "agent_chat"."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" bigint NOT NULL,\n "cached_input_tokens" bigint NOT NULL,\n "cache_write_tokens" bigint NOT NULL,\n "output_tokens" bigint NOT NULL,\n "reasoning_tokens" bigint NOT NULL,\n "cost_usd" double precision NOT NULL,\n "created_at" text NOT NULL\n);\n',
905
+ '\nCREATE INDEX "usage_records_owner_created_idx" ON "agent_chat"."usage_records" USING btree ("owner_id","created_at");',
906
+ '\nCREATE INDEX "usage_records_chat_created_idx" ON "agent_chat"."usage_records" USING btree ("chat_id","created_at");'
907
+ ] },
908
+ // 0006_user_model_choices
909
+ { folderMillis: 1790752789473, hash: "ce1b90d09141be18d69b1dffc646e8e99142babe88009795e2c98659c3c49705", bps: true, sql: [
910
+ 'CREATE TABLE "agent_chat"."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'
911
+ ] },
912
+ // 0007_voice_dialog
913
+ { folderMillis: 1790755965363, hash: "1c17ca71d7377ff7304e0d7befd89aa889e01b81d1dee56b97024afbcff3aa67", bps: true, sql: [
914
+ 'CREATE TABLE "agent_chat"."voice_choices" (\n "owner_id" text PRIMARY KEY NOT NULL,\n "voice_id" text NOT NULL,\n "updated_at" text NOT NULL\n);\n',
915
+ '\nALTER TABLE "agent_chat"."messages" ADD COLUMN "voice_cut" json;'
916
+ ] },
917
+ // 0008_memory_notes
918
+ { folderMillis: 1790759982638, hash: "652d3eea6b62dad2c2edc7ffb306909f8ca69dd911210ee7425d2f08800ea448", bps: true, sql: [
919
+ 'CREATE TABLE "agent_chat"."memory_notes" (\n "id" text PRIMARY KEY NOT NULL,\n "owner_id" text NOT NULL,\n "categories" jsonb NOT NULL,\n "content" text NOT NULL,\n "version" integer DEFAULT 1 NOT NULL,\n "created_at" timestamp with time zone NOT NULL,\n "updated_at" timestamp with time zone NOT NULL\n);\n',
920
+ '\nCREATE INDEX "memory_notes_owner_updated_idx" ON "agent_chat"."memory_notes" USING btree ("owner_id","updated_at");'
921
+ ] },
922
+ // 0009_memory_optimization
923
+ { folderMillis: 1790761236531, hash: "3b8e31b07b1e28bbf864560629b2d2bd309d237620379a6f959a95fef23de39e", bps: true, sql: [
924
+ `CREATE TABLE "agent_chat"."memory_optimization_runs" (
925
+ "id" text PRIMARY KEY NOT NULL,
926
+ "owner_id" text NOT NULL,
927
+ "started_at" timestamp with time zone NOT NULL,
928
+ "finished_at" timestamp with time zone,
929
+ "status" text NOT NULL,
930
+ "groups" jsonb DEFAULT '[]'::jsonb NOT NULL,
931
+ "error" text,
932
+ "usage_record_id" text
933
+ );
934
+ `,
935
+ '\nALTER TABLE "agent_chat"."memory_notes" ADD COLUMN "merged_into" text;',
936
+ '\nCREATE INDEX "memory_optimization_runs_owner_started_idx" ON "agent_chat"."memory_optimization_runs" USING btree ("owner_id","started_at");',
937
+ `
938
+ CREATE UNIQUE INDEX "memory_optimization_runs_one_running_idx" ON "agent_chat"."memory_optimization_runs" USING btree ("owner_id") WHERE "agent_chat"."memory_optimization_runs"."status" = 'running';`,
939
+ '\nCREATE INDEX "memory_notes_merged_into_idx" ON "agent_chat"."memory_notes" USING btree ("merged_into");'
940
+ ] },
941
+ // 0010_usage_estimated
942
+ { folderMillis: 1790938846233, hash: "8aecf90b7f91c5fdd145f34a40b37a7f48eb241406c3ce57a029cefd303fd45b", bps: true, sql: [
943
+ 'ALTER TABLE "agent_chat"."usage_records" ADD COLUMN "estimated" boolean DEFAULT false NOT NULL;'
944
+ ] },
945
+ // 0011_message_alive_at
946
+ { folderMillis: 1790944385687, hash: "4e5a3fe4945d5208f4c2df006d8e153fdc8b9268ebc9a08ed4b6b4ecf7a82c66", bps: true, sql: [
947
+ 'ALTER TABLE "agent_chat"."messages" ADD COLUMN "alive_at" text;'
948
+ ] },
949
+ // 0012_spending_limit_states
950
+ { folderMillis: 1791185874971, hash: "fdd524d59380eb0fea94d3a2a8c28ae1ac98fcd08446d797b653a16b1434c05a", bps: true, sql: [
951
+ 'CREATE TABLE "agent_chat"."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'
952
+ ] },
953
+ // 0013_chat_origin
954
+ { folderMillis: 1791197610368, hash: "af64ddc45fd3715d9fd2031860d7fd4a5ec7fa7d15e51c130956d0be3e06e398", bps: true, sql: [
955
+ 'ALTER TABLE "agent_chat"."chats" ADD COLUMN "origin" text;'
956
+ ] },
957
+ // 0014_chat_subject_after_turn
958
+ { folderMillis: 1791265708083, hash: "3c58fce1fd0c6440492a6da8ccbf1d58044dcdd38a40cb6e01220281db1d7fe1", bps: true, sql: [
959
+ 'ALTER TABLE "agent_chat"."chats" ADD COLUMN "subject_key" text;',
960
+ '\nALTER TABLE "agent_chat"."chats" ADD COLUMN "subject_data" json;',
961
+ '\nALTER TABLE "agent_chat"."messages" ADD COLUMN "after_turn" text;',
962
+ '\nCREATE UNIQUE INDEX "chats_owner_subject_idx" ON "agent_chat"."chats" USING btree ("owner_id","subject_key");',
963
+ `
964
+ CREATE INDEX "messages_after_turn_pending_idx" ON "agent_chat"."messages" USING btree ("after_turn") WHERE "agent_chat"."messages"."after_turn" = 'pending';`
965
+ ] },
966
+ // 0015_chat_closed
967
+ { folderMillis: 1791285255799, hash: "0f8402da4644ae030f8935bedcc35ea41f53d24a0083717506357562fcdae219", bps: true, sql: [
968
+ 'ALTER TABLE "agent_chat"."chats" ADD COLUMN "closed" json;'
969
+ ] },
970
+ // 0016_chat_turn_leases
971
+ { folderMillis: 1791968017742, hash: "840ddf4a0c8bff43b2241a339d7aa67abf7cb3a59cd396fd6f1f380c79632d0f", bps: true, sql: [
972
+ 'CREATE TABLE "agent_chat"."chat_turn_leases" (\n "chat_id" text PRIMARY KEY NOT NULL,\n "holder" text NOT NULL,\n "until" timestamp with time zone NOT NULL\n);\n'
973
+ ] },
974
+ // 0017_pending_bursts
975
+ { folderMillis: 1792017521169, hash: "a533a271a5a9c8154a8320b608727d34fe0e0a3969ff880501cf59792d944914", bps: true, sql: [
976
+ 'CREATE TABLE "agent_chat"."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" timestamp with time zone NOT NULL,\n "holder" text NOT NULL,\n "held_until" timestamp with time zone NOT NULL,\n "page" jsonb\n);\n'
977
+ ] },
978
+ // 0018_usage_created_index
979
+ { folderMillis: 1793442948920, hash: "309053a858e4d5da6ab55fb22282b4dfdc45ba9c3a35a2a665cc00231477fccd", bps: true, sql: [
980
+ 'CREATE INDEX "usage_records_created_idx" ON "agent_chat"."usage_records" USING btree ("created_at");'
981
+ ] },
982
+ // 0019_stop_requests
983
+ { folderMillis: 1794403275223, hash: "b2b13cca84b216efcc536e2b2f51c354abebdaf28a758edbcc7918b9f9b942a4", bps: true, sql: [
984
+ 'CREATE TABLE "agent_chat"."stop_requests" (\n "chat_id" text NOT NULL,\n "turn_request_id" text NOT NULL,\n "owner_id" text NOT NULL,\n "expires_at" timestamp with time zone NOT NULL,\n CONSTRAINT "stop_requests_chat_id_turn_request_id_pk" PRIMARY KEY("chat_id","turn_request_id")\n);\n',
985
+ '\nCREATE INDEX "stop_requests_expires_idx" ON "agent_chat"."stop_requests" USING btree ("expires_at");',
986
+ '\nCREATE INDEX "stop_requests_owner_idx" ON "agent_chat"."stop_requests" USING btree ("owner_id","expires_at");'
987
+ ] }
988
+ ];
989
+
990
+ // src/migrate.ts
819
991
  var MIGRATION_LOCK_KEY = 7311900442;
820
992
  async function migrateToLatest(pool) {
821
993
  await migratePostgresSchema({
822
994
  connect: () => pool.connect(),
823
995
  lockKey: MIGRATION_LOCK_KEY,
824
- migrate: (client) => migrate(drizzle(client), { migrationsFolder, migrationsSchema: "agent_chat" })
996
+ migrate: async (client) => await applyEmbeddedMigrations(drizzle(client), migrations, { migrationsSchema: "agent_chat" })
825
997
  });
826
998
  }
827
999