@ykurilov/agent-chat-sandbox 0.107.0 → 0.107.2

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-sandbox
2
2
 
3
+ ## 0.107.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 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` в ядре), журнал и хеши миграций прежние: существующие базы ничего не применяют заново.
8
+ - Updated dependencies [4430082]
9
+ - @ykurilov/agent-chat-core@0.107.2
10
+ - @ykurilov/agent-chat-server@0.107.2
11
+ - @ykurilov/agent-chat-react@0.107.2
12
+
13
+ ## 0.107.1
14
+
15
+ ### Patch Changes
16
+
17
+ - @ykurilov/agent-chat-core@0.107.1
18
+ - @ykurilov/agent-chat-react@0.107.1
19
+ - @ykurilov/agent-chat-server@0.107.1
20
+
3
21
  ## 0.107.0
4
22
 
5
23
  ### Patch Changes
package/dist/postgres.js CHANGED
@@ -3,14 +3,12 @@ import {
3
3
  } from "./chunk-4O5NPJOS.js";
4
4
 
5
5
  // src/postgres.ts
6
- import { fileURLToPath } from "url";
7
6
  import pg from "pg";
8
7
 
9
8
  // src/journal/postgres-journal.ts
10
9
  import { and, asc, eq, inArray, lt, notExists, or } from "drizzle-orm";
11
10
  import { drizzle } from "drizzle-orm/node-postgres";
12
- import { migrate } from "drizzle-orm/node-postgres/migrator";
13
- import { migratePostgresSchema } from "@ykurilov/agent-chat-core";
11
+ import { migratePostgresSchema, applyEmbeddedMigrations } from "@ykurilov/agent-chat-core";
14
12
 
15
13
  // src/journal/postgres-schema.ts
16
14
  import { boolean, customType, doublePrecision, index, integer, jsonb, pgSchema, text, timestamp } from "drizzle-orm/pg-core";
@@ -102,11 +100,11 @@ var sandboxAnswerEdits = agentChatSchema.table(
102
100
  // src/journal/postgres-journal.ts
103
101
  var MIGRATION_LOCK_KEY = 7311900443;
104
102
  var MIGRATIONS_TABLE = "__sandbox_migrations";
105
- async function migrateJournalToLatest(pool, migrationsFolder2) {
103
+ async function migrateJournalToLatest(pool, migrations2) {
106
104
  await migratePostgresSchema({
107
105
  connect: () => pool.connect(),
108
106
  lockKey: MIGRATION_LOCK_KEY,
109
- migrate: (client) => migrate(drizzle(client), { migrationsFolder: migrationsFolder2, migrationsSchema: "agent_chat", migrationsTable: MIGRATIONS_TABLE })
107
+ migrate: async (client) => await applyEmbeddedMigrations(drizzle(client), migrations2, { migrationsSchema: "agent_chat", migrationsTable: MIGRATIONS_TABLE })
110
108
  });
111
109
  }
112
110
  function createPostgresJournalStore(pool) {
@@ -205,15 +203,36 @@ function toBlobRow(row) {
205
203
  return { hash: row.hash, data: new Uint8Array(row.data), bytes: row.bytes, truncated: row.truncated };
206
204
  }
207
205
 
206
+ // src/drizzle-migrations-postgres.generated.ts
207
+ var migrations = [
208
+ // 0000_journal_init
209
+ { folderMillis: 1791041535977, hash: "944772a6c593f0ac2f3e5a656f527454d14cf9734e77e84dff54c8c2614c9162", bps: true, sql: [
210
+ 'CREATE SCHEMA IF NOT EXISTS "agent_chat";\n',
211
+ '\nCREATE TABLE "agent_chat"."sandbox_answer_edits" (\n "message_id" text PRIMARY KEY NOT NULL,\n "source_message_id" text NOT NULL,\n "chat_id" text NOT NULL,\n "text_edited" boolean NOT NULL,\n "edited_tool_call_ids" jsonb NOT NULL,\n "edited_by" text NOT NULL,\n "edited_at" timestamp (3) with time zone NOT NULL\n);\n',
212
+ '\nCREATE TABLE "agent_chat"."sandbox_blob_refs" (\n "call_id" text NOT NULL,\n "hash" text NOT NULL,\n "chat_id" text NOT NULL,\n "owner_id" text NOT NULL\n);\n',
213
+ '\nCREATE TABLE "agent_chat"."sandbox_blobs" (\n "hash" text PRIMARY KEY NOT NULL,\n "data" "bytea" NOT NULL,\n "bytes" integer NOT NULL,\n "truncated" boolean NOT NULL\n);\n',
214
+ '\nCREATE TABLE "agent_chat"."sandbox_model_calls" (\n "id" text PRIMARY KEY NOT NULL,\n "chat_id" text NOT NULL,\n "owner_id" text NOT NULL,\n "message_id" text,\n "purpose" text NOT NULL,\n "attempt" integer NOT NULL,\n "model_id" text NOT NULL,\n "provider_id" text NOT NULL,\n "usage" jsonb,\n "cost_usd" double precision,\n "started_at" timestamp (3) with time zone NOT NULL,\n "first_chunk_ms" integer,\n "duration_ms" integer NOT NULL,\n "status" text NOT NULL,\n "error" text,\n "instructions_hash" text NOT NULL,\n "message_hashes" jsonb NOT NULL,\n "tools_hash" text NOT NULL,\n "settings_hash" text NOT NULL,\n "response_hash" text NOT NULL,\n "tool_call_ids" jsonb NOT NULL\n);\n',
215
+ '\nCREATE TABLE "agent_chat"."sandbox_settings" (\n "chat_id" text PRIMARY KEY NOT NULL,\n "instructions" text,\n "updated_by" text NOT NULL,\n "updated_at" timestamp (3) with time zone NOT NULL\n);\n',
216
+ '\nCREATE TABLE "agent_chat"."sandbox_tool_calls" (\n "id" text PRIMARY KEY NOT NULL,\n "chat_id" text NOT NULL,\n "owner_id" text NOT NULL,\n "message_id" text NOT NULL,\n "tool_call_id" text NOT NULL,\n "tool_name" text NOT NULL,\n "input_hash" text NOT NULL,\n "output_hash" text,\n "error" text,\n "started_at" timestamp (3) with time zone NOT NULL,\n "duration_ms" integer NOT NULL\n);\n',
217
+ '\nCREATE INDEX "sandbox_answer_edits_chat_idx" ON "agent_chat"."sandbox_answer_edits" USING btree ("chat_id","edited_at");',
218
+ '\nCREATE INDEX "sandbox_blob_refs_call_idx" ON "agent_chat"."sandbox_blob_refs" USING btree ("call_id");',
219
+ '\nCREATE INDEX "sandbox_blob_refs_hash_idx" ON "agent_chat"."sandbox_blob_refs" USING btree ("hash","owner_id");',
220
+ '\nCREATE INDEX "sandbox_blob_refs_chat_idx" ON "agent_chat"."sandbox_blob_refs" USING btree ("chat_id");',
221
+ '\nCREATE INDEX "sandbox_model_calls_chat_idx" ON "agent_chat"."sandbox_model_calls" USING btree ("chat_id","started_at");',
222
+ '\nCREATE INDEX "sandbox_model_calls_started_idx" ON "agent_chat"."sandbox_model_calls" USING btree ("started_at");',
223
+ '\nCREATE INDEX "sandbox_tool_calls_chat_idx" ON "agent_chat"."sandbox_tool_calls" USING btree ("chat_id","started_at");',
224
+ '\nCREATE INDEX "sandbox_tool_calls_started_idx" ON "agent_chat"."sandbox_tool_calls" USING btree ("started_at");'
225
+ ] }
226
+ ];
227
+
208
228
  // src/postgres.ts
209
229
  var DEFAULT_POOL_SIZE = 5;
210
- var migrationsFolder = fileURLToPath(new URL("../drizzle/postgres", import.meta.url));
211
230
  async function createPostgresSandboxJournal(options) {
212
231
  const logError = options.logError ?? ((message) => console.error(message));
213
232
  const pool = new pg.Pool({ connectionString: options.connectionString, max: options.poolSize ?? DEFAULT_POOL_SIZE });
214
233
  pool.on("error", (error) => logError(`\u0436\u0443\u0440\u043D\u0430\u043B \u043F\u0435\u0441\u043E\u0447\u043D\u0438\u0446\u044B: \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0441 PostgreSQL \u043E\u0431\u043E\u0440\u0432\u0430\u043B\u043E\u0441\u044C: ${error.message}`));
215
234
  try {
216
- await migrateJournalToLatest(pool, migrationsFolder);
235
+ await migrateJournalToLatest(pool, migrations);
217
236
  } catch (error) {
218
237
  await pool.end().catch(() => {
219
238
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/postgres.ts","../src/journal/postgres-journal.ts","../src/journal/postgres-schema.ts"],"sourcesContent":["import { fileURLToPath } from \"node:url\";\nimport pg from \"pg\";\nimport type { JournalOptions } from \"./journal/journal\";\nimport { createSandboxJournal } from \"./journal/journal\";\nimport { createPostgresJournalStore, migrateJournalToLatest } from \"./journal/postgres-journal\";\nimport type { SandboxJournal } from \"./types\";\n\nexport type { LogError, SandboxJournal } from \"./types\";\n\nexport type PostgresSandboxJournalOptions = JournalOptions & {\n /** Например `postgres://user:password@host:5432/database`; та же база, что у `createPostgresChatStorage`. */\n connectionString: string;\n /** Сколько соединений держать открытыми. По умолчанию 5. */\n poolSize?: number;\n};\n\nconst DEFAULT_POOL_SIZE = 5;\nconst migrationsFolder = fileURLToPath(new URL(\"../drizzle/postgres\", import.meta.url));\n\n/**\n * Журнал песочницы в PostgreSQL. Таблицы лежат в схеме `agent_chat`; схема приводится\n * к последней миграции при создании, под блокировкой базы.\n */\nexport async function createPostgresSandboxJournal(options: PostgresSandboxJournalOptions): Promise<SandboxJournal> {\n const logError = options.logError ?? ((message: string) => console.error(message));\n const pool = new pg.Pool({ connectionString: options.connectionString, max: options.poolSize ?? DEFAULT_POOL_SIZE });\n // Без обработчика оборвавшееся соединение простаивающего пула роняет процесс.\n pool.on(\"error\", (error) => logError(`журнал песочницы: соединение с PostgreSQL оборвалось: ${error.message}`));\n try {\n await migrateJournalToLatest(pool, migrationsFolder);\n } catch (error) {\n await pool.end().catch(() => {});\n throw failure(error, options.connectionString);\n }\n return createSandboxJournal(createPostgresJournalStore(pool), { ...options, logError });\n}\n\n/** Ошибка без строки подключения: пароль в текст не попадает. */\nfunction failure(cause: unknown, connectionString: string): Error {\n const reason = cause instanceof Error ? cause.message : String(cause);\n return new Error(`Не удалось подготовить журнал песочницы в PostgreSQL: ${reason.split(connectionString).join(\"<строка подключения>\")}`);\n}\n","import { and, asc, eq, inArray, lt, notExists, or } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { migrate } from \"drizzle-orm/node-postgres/migrator\";\nimport { migratePostgresSchema } from \"@ykurilov/agent-chat-core\";\nimport type { Pool } from \"pg\";\nimport type { BlobRow, JournalStore, ModelCallRow, ToolCallRow } from \"./journal-store\";\nimport { sandboxAnswerEdits, sandboxBlobRefs, sandboxBlobs, sandboxModelCalls, sandboxSettings, sandboxToolCalls } from \"./postgres-schema\";\n\n/** Постоянное число для блокировки базы миграциями журнала; не совпадает с ключом хранилища чатов. */\nconst MIGRATION_LOCK_KEY = 7_311_900_443;\n\n/** Своя таблица учёта: хранилище чатов живёт в той же схеме и ведёт свою (`__drizzle_migrations`). */\nconst MIGRATIONS_TABLE = \"__sandbox_migrations\";\n\n/**\n * Приводит таблицы журнала к последней миграции. Схема `agent_chat` создаётся под общей блокировкой всех пакетов, миграции — под своей:\n * копии пакета ждут друг друга, а разные пакеты стартуют разом на пустой базе без гонки за схему.\n */\nexport async function migrateJournalToLatest(pool: Pool, migrationsFolder: string): Promise<void> {\n await migratePostgresSchema({\n connect: () => pool.connect(),\n lockKey: MIGRATION_LOCK_KEY,\n migrate: (client) => migrate(drizzle(client), { migrationsFolder, migrationsSchema: \"agent_chat\", migrationsTable: MIGRATIONS_TABLE }),\n });\n}\n\n/** Хранилище журнала в PostgreSQL (схема `agent_chat`). Закрытие закрывает и пул. */\nexport function createPostgresJournalStore(pool: Pool): JournalStore {\n const db = drizzle(pool);\n type Executor = Pick<typeof db, \"delete\" | \"select\" | \"insert\">;\n\n /** Куски, на которые не осталось ссылок. */\n async function dropUnreferencedBlobs(tx: Executor): Promise<void> {\n await tx.delete(sandboxBlobs).where(notExists(tx.select({ one: sandboxBlobRefs.hash }).from(sandboxBlobRefs).where(eq(sandboxBlobRefs.hash, sandboxBlobs.hash))));\n }\n\n /**\n * Куски обращения пишутся одним запросом: в длинном чате их сотни (вся история), и запрос на каждый кусок\n * превращал одну запись журнала в сотни походов к базе. Порядок по хэшу одинаков у всех записей —\n * параллельные записи с общими кусками не ждут друг друга крест-накрест.\n */\n async function saveBlobs(tx: Executor, callId: string, row: { chatId: string; ownerId: string }, hashes: string[], blobs: BlobRow[]): Promise<void> {\n const unique = [...new Map(blobs.map((blob) => [blob.hash, blob])).values()].sort((left, right) => (left.hash < right.hash ? -1 : left.hash > right.hash ? 1 : 0));\n if (unique.length > 0) {\n await tx\n .insert(sandboxBlobs)\n .values(unique.map((blob) => ({ hash: blob.hash, data: Buffer.from(blob.data), bytes: blob.bytes, truncated: blob.truncated })))\n .onConflictDoNothing();\n }\n const refs = [...new Set(hashes)].map((hash) => ({ callId, hash, chatId: row.chatId, ownerId: row.ownerId }));\n if (refs.length > 0) await tx.insert(sandboxBlobRefs).values(refs);\n }\n\n return {\n async saveModelCall(row, blobs) {\n await db.transaction(async (tx) => {\n const inserted = await tx.insert(sandboxModelCalls).values({ ...row, error: withoutNul(row.error) }).onConflictDoNothing().returning({ id: sandboxModelCalls.id });\n if (inserted.length === 0) return;\n await saveBlobs(tx, row.id, row, [row.instructionsHash, ...row.messageHashes, row.toolsHash, row.settingsHash, row.responseHash], blobs);\n });\n },\n async saveToolCall(row, blobs) {\n await db.transaction(async (tx) => {\n const inserted = await tx.insert(sandboxToolCalls).values({ ...row, error: withoutNul(row.error) }).onConflictDoNothing().returning({ id: sandboxToolCalls.id });\n if (inserted.length === 0) return;\n await saveBlobs(tx, row.id, row, row.outputHash ? [row.inputHash, row.outputHash] : [row.inputHash], blobs);\n });\n },\n async listModelCalls(chatId) {\n return db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId)).orderBy(asc(sandboxModelCalls.startedAt));\n },\n async listToolCalls(chatId) {\n return db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId)).orderBy(asc(sandboxToolCalls.startedAt));\n },\n async findModelCall(id) {\n return (await db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.id, id)).limit(1))[0] ?? null;\n },\n async findToolCall(id) {\n return (await db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.id, id)).limit(1))[0] ?? null;\n },\n async loadBlobs(hashes) {\n if (hashes.length === 0) return [];\n return (await db.select().from(sandboxBlobs).where(inArray(sandboxBlobs.hash, hashes))).map(toBlobRow);\n },\n async loadBlobForOwner(hash, ownerId) {\n const owned = await db.select({ hash: sandboxBlobRefs.hash }).from(sandboxBlobRefs).where(and(eq(sandboxBlobRefs.hash, hash), eq(sandboxBlobRefs.ownerId, ownerId))).limit(1);\n if (owned.length === 0) return null;\n const row = (await db.select().from(sandboxBlobs).where(eq(sandboxBlobs.hash, hash)).limit(1))[0];\n return row ? toBlobRow(row) : null;\n },\n async getSettings(chatId) {\n return (await db.select().from(sandboxSettings).where(eq(sandboxSettings.chatId, chatId)).limit(1))[0] ?? null;\n },\n async setSettings(settings) {\n const clean = { ...settings, instructions: withoutNul(settings.instructions) };\n await db.insert(sandboxSettings).values(clean).onConflictDoUpdate({ target: sandboxSettings.chatId, set: clean });\n },\n async saveAnswerEdit(record) {\n await db.insert(sandboxAnswerEdits).values(record).onConflictDoUpdate({ target: sandboxAnswerEdits.messageId, set: record });\n },\n async listAnswerEdits(chatId) {\n return db.select().from(sandboxAnswerEdits).where(eq(sandboxAnswerEdits.chatId, chatId)).orderBy(asc(sandboxAnswerEdits.editedAt));\n },\n async deleteChat(chatId) {\n await db.transaction(async (tx) => {\n await tx.delete(sandboxBlobRefs).where(eq(sandboxBlobRefs.chatId, chatId));\n await tx.delete(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId));\n await tx.delete(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId));\n await tx.delete(sandboxSettings).where(eq(sandboxSettings.chatId, chatId));\n await tx.delete(sandboxAnswerEdits).where(eq(sandboxAnswerEdits.chatId, chatId));\n await dropUnreferencedBlobs(tx);\n });\n },\n async deleteOlderThan(before) {\n return db.transaction(async (tx) => {\n const oldModels = tx.select({ id: sandboxModelCalls.id }).from(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, before));\n const oldTools = tx.select({ id: sandboxToolCalls.id }).from(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, before));\n await tx.delete(sandboxBlobRefs).where(or(inArray(sandboxBlobRefs.callId, oldModels), inArray(sandboxBlobRefs.callId, oldTools)));\n const models = await tx.delete(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, before)).returning({ id: sandboxModelCalls.id });\n const tools = await tx.delete(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, before)).returning({ id: sandboxToolCalls.id });\n await dropUnreferencedBlobs(tx);\n return models.length + tools.length;\n });\n },\n async close() {\n await pool.end();\n },\n };\n}\n\n/** PostgreSQL не хранит символ NUL в тексте: сообщение об ошибке или инструкция с ним отклонили бы запись. */\nfunction withoutNul(text: string | null): string | null {\n return text === null ? null : text.replaceAll(\"\\u0000\", \"\");\n}\n\nfunction toBlobRow(row: typeof sandboxBlobs.$inferSelect): BlobRow {\n return { hash: row.hash, data: new Uint8Array(row.data), bytes: row.bytes, truncated: row.truncated };\n}\n","import type { ModelCallEvent } from \"@ykurilov/agent-chat-core\";\nimport { boolean, customType, doublePrecision, index, integer, jsonb, pgSchema, text, timestamp } from \"drizzle-orm/pg-core\";\n\n/** Та же схема базы, что у хранилища чатов: у приложения одна база и одна схема `agent_chat`. */\nconst agentChatSchema = pgSchema(\"agent_chat\");\n\nconst bytea = customType<{ data: Buffer; driverData: Buffer }>({\n dataType: () => \"bytea\",\n});\n\nconst startedAt = (name: string) => timestamp(name, { mode: \"date\", precision: 3, withTimezone: true });\n\nexport const sandboxBlobs = agentChatSchema.table(\"sandbox_blobs\", {\n hash: text(\"hash\").primaryKey(),\n data: bytea(\"data\").notNull(),\n bytes: integer(\"bytes\").notNull(),\n truncated: boolean(\"truncated\").notNull(),\n});\n\nexport const sandboxModelCalls = agentChatSchema.table(\n \"sandbox_model_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\"),\n purpose: text(\"purpose\").$type<ModelCallEvent[\"purpose\"]>().notNull(),\n attempt: integer(\"attempt\").notNull(),\n modelId: text(\"model_id\").notNull(),\n providerId: text(\"provider_id\").notNull(),\n usage: jsonb(\"usage\").$type<ModelCallEvent[\"usage\"]>(),\n costUsd: doublePrecision(\"cost_usd\"),\n startedAt: startedAt(\"started_at\").notNull(),\n firstChunkMs: integer(\"first_chunk_ms\"),\n durationMs: integer(\"duration_ms\").notNull(),\n status: text(\"status\").$type<ModelCallEvent[\"status\"]>().notNull(),\n error: text(\"error\"),\n instructionsHash: text(\"instructions_hash\").notNull(),\n messageHashes: jsonb(\"message_hashes\").$type<string[]>().notNull(),\n toolsHash: text(\"tools_hash\").notNull(),\n settingsHash: text(\"settings_hash\").notNull(),\n responseHash: text(\"response_hash\").notNull(),\n toolCallIds: jsonb(\"tool_call_ids\").$type<string[]>().notNull(),\n },\n (table) => [index(\"sandbox_model_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_model_calls_started_idx\").on(table.startedAt)],\n);\n\nexport const sandboxToolCalls = agentChatSchema.table(\n \"sandbox_tool_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\").notNull(),\n toolCallId: text(\"tool_call_id\").notNull(),\n toolName: text(\"tool_name\").notNull(),\n inputHash: text(\"input_hash\").notNull(),\n outputHash: text(\"output_hash\"),\n error: text(\"error\"),\n startedAt: startedAt(\"started_at\").notNull(),\n durationMs: integer(\"duration_ms\").notNull(),\n },\n (table) => [index(\"sandbox_tool_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_tool_calls_started_idx\").on(table.startedAt)],\n);\n\n/** Кто на какой кусок ссылается: по этим строкам решается, чей кусок и какие куски уже никому не нужны. */\nexport const sandboxBlobRefs = agentChatSchema.table(\n \"sandbox_blob_refs\",\n {\n callId: text(\"call_id\").notNull(),\n hash: text(\"hash\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n },\n (table) => [index(\"sandbox_blob_refs_call_idx\").on(table.callId), index(\"sandbox_blob_refs_hash_idx\").on(table.hash, table.ownerId), index(\"sandbox_blob_refs_chat_idx\").on(table.chatId)],\n);\n\nexport const sandboxSettings = agentChatSchema.table(\"sandbox_settings\", {\n chatId: text(\"chat_id\").primaryKey(),\n instructions: text(\"instructions\"),\n updatedBy: text(\"updated_by\").notNull(),\n updatedAt: startedAt(\"updated_at\").notNull(),\n});\n\nexport const sandboxAnswerEdits = agentChatSchema.table(\n \"sandbox_answer_edits\",\n {\n messageId: text(\"message_id\").primaryKey(),\n sourceMessageId: text(\"source_message_id\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n textEdited: boolean(\"text_edited\").notNull(),\n editedToolCallIds: jsonb(\"edited_tool_call_ids\").$type<string[]>().notNull(),\n editedBy: text(\"edited_by\").notNull(),\n editedAt: startedAt(\"edited_at\").notNull(),\n },\n (table) => [index(\"sandbox_answer_edits_chat_idx\").on(table.chatId, table.editedAt)],\n);\n"],"mappings":";;;;;AAAA,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;;;ACDf,SAAS,KAAK,KAAK,IAAI,SAAS,IAAI,WAAW,UAAU;AACzD,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,6BAA6B;;;ACFtC,SAAS,SAAS,YAAY,iBAAiB,OAAO,SAAS,OAAO,UAAU,MAAM,iBAAiB;AAGvG,IAAM,kBAAkB,SAAS,YAAY;AAE7C,IAAM,QAAQ,WAAiD;AAAA,EAC7D,UAAU,MAAM;AAClB,CAAC;AAED,IAAM,YAAY,CAAC,SAAiB,UAAU,MAAM,EAAE,MAAM,QAAQ,WAAW,GAAG,cAAc,KAAK,CAAC;AAE/F,IAAM,eAAe,gBAAgB,MAAM,iBAAiB;AAAA,EACjE,MAAM,KAAK,MAAM,EAAE,WAAW;AAAA,EAC9B,MAAM,MAAM,MAAM,EAAE,QAAQ;AAAA,EAC5B,OAAO,QAAQ,OAAO,EAAE,QAAQ;AAAA,EAChC,WAAW,QAAQ,WAAW,EAAE,QAAQ;AAC1C,CAAC;AAEM,IAAM,oBAAoB,gBAAgB;AAAA,EAC/C;AAAA,EACA;AA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AAE,MAAM,IAAI,MAAM,MAAM,IAAI,WAAW,IAAI,IAAI,GAAG,OAAO,IAAI,OAAO,WAAW,IAAI,UAAU;AACtG;;;ADzHA,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB,cAAc,IAAI,IAAI,uBAAuB,YAAY,GAAG,CAAC;AAMtF,eAAsB,6BAA6B,SAAiE;AAClH,QAAM,WAAW,QAAQ,aAAa,CAAC,YAAoB,QAAQ,MAAM,OAAO;AAChF,QAAM,OAAO,IAAI,GAAG,KAAK,EAAE,kBAAkB,QAAQ,kBAAkB,KAAK,QAAQ,YAAY,kBAAkB,CAAC;AAEnH,OAAK,GAAG,SAAS,CAAC,UAAU,SAAS,6OAAyD,MAAM,OAAO,EAAE,CAAC;AAC9G,MAAI;AACF,UAAM,uBAAuB,MAAM,gBAAgB;AAAA,EACrD,SAAS,OAAO;AACd,UAAM,KAAK,IAAI,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAC/B,UAAM,QAAQ,OAAO,QAAQ,gBAAgB;AAAA,EAC/C;AACA,SAAO,qBAAqB,2BAA2B,IAAI,GAAG,EAAE,GAAG,SAAS,SAAS,CAAC;AACxF;AAGA,SAAS,QAAQ,OAAgB,kBAAiC;AAChE,QAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACpE,SAAO,IAAI,MAAM,6OAAyD,OAAO,MAAM,gBAAgB,EAAE,KAAK,2GAAsB,CAAC,EAAE;AACzI;","names":["migrationsFolder","text"]}
1
+ {"version":3,"sources":["../src/postgres.ts","../src/journal/postgres-journal.ts","../src/journal/postgres-schema.ts","../src/drizzle-migrations-postgres.generated.ts"],"sourcesContent":["import pg from \"pg\";\nimport type { JournalOptions } from \"./journal/journal\";\nimport { createSandboxJournal } from \"./journal/journal\";\nimport { createPostgresJournalStore, migrateJournalToLatest } from \"./journal/postgres-journal\";\nimport type { SandboxJournal } from \"./types\";\nimport { migrations } from \"./drizzle-migrations-postgres.generated\";\n\nexport type { LogError, SandboxJournal } from \"./types\";\n\nexport type PostgresSandboxJournalOptions = JournalOptions & {\n /** Например `postgres://user:password@host:5432/database`; та же база, что у `createPostgresChatStorage`. */\n connectionString: string;\n /** Сколько соединений держать открытыми. По умолчанию 5. */\n poolSize?: number;\n};\n\nconst DEFAULT_POOL_SIZE = 5;\n\n/**\n * Журнал песочницы в PostgreSQL. Таблицы лежат в схеме `agent_chat`; схема приводится\n * к последней миграции при создании, под блокировкой базы.\n */\nexport async function createPostgresSandboxJournal(options: PostgresSandboxJournalOptions): Promise<SandboxJournal> {\n const logError = options.logError ?? ((message: string) => console.error(message));\n const pool = new pg.Pool({ connectionString: options.connectionString, max: options.poolSize ?? DEFAULT_POOL_SIZE });\n // Без обработчика оборвавшееся соединение простаивающего пула роняет процесс.\n pool.on(\"error\", (error) => logError(`журнал песочницы: соединение с PostgreSQL оборвалось: ${error.message}`));\n try {\n await migrateJournalToLatest(pool, migrations);\n } catch (error) {\n await pool.end().catch(() => {});\n throw failure(error, options.connectionString);\n }\n return createSandboxJournal(createPostgresJournalStore(pool), { ...options, logError });\n}\n\n/** Ошибка без строки подключения: пароль в текст не попадает. */\nfunction failure(cause: unknown, connectionString: string): Error {\n const reason = cause instanceof Error ? cause.message : String(cause);\n return new Error(`Не удалось подготовить журнал песочницы в PostgreSQL: ${reason.split(connectionString).join(\"<строка подключения>\")}`);\n}\n","import { and, asc, eq, inArray, lt, notExists, or } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { migratePostgresSchema, applyEmbeddedMigrations, type EmbeddedMigration } from \"@ykurilov/agent-chat-core\";\nimport type { Pool } from \"pg\";\nimport type { BlobRow, JournalStore, ModelCallRow, ToolCallRow } from \"./journal-store\";\nimport { sandboxAnswerEdits, sandboxBlobRefs, sandboxBlobs, sandboxModelCalls, sandboxSettings, sandboxToolCalls } from \"./postgres-schema\";\n\n/** Постоянное число для блокировки базы миграциями журнала; не совпадает с ключом хранилища чатов. */\nconst MIGRATION_LOCK_KEY = 7_311_900_443;\n\n/** Своя таблица учёта: хранилище чатов живёт в той же схеме и ведёт свою (`__drizzle_migrations`). */\nconst MIGRATIONS_TABLE = \"__sandbox_migrations\";\n\n/**\n * Приводит таблицы журнала к последней миграции. Схема `agent_chat` создаётся под общей блокировкой всех пакетов, миграции — под своей:\n * копии пакета ждут друг друга, а разные пакеты стартуют разом на пустой базе без гонки за схему.\n */\nexport async function migrateJournalToLatest(pool: Pool, migrations: readonly EmbeddedMigration[]): Promise<void> {\n await migratePostgresSchema({\n connect: () => pool.connect(),\n lockKey: MIGRATION_LOCK_KEY,\n migrate: async (client) => await applyEmbeddedMigrations(drizzle(client), migrations, { migrationsSchema: \"agent_chat\", migrationsTable: MIGRATIONS_TABLE }),\n });\n}\n\n/** Хранилище журнала в PostgreSQL (схема `agent_chat`). Закрытие закрывает и пул. */\nexport function createPostgresJournalStore(pool: Pool): JournalStore {\n const db = drizzle(pool);\n type Executor = Pick<typeof db, \"delete\" | \"select\" | \"insert\">;\n\n /** Куски, на которые не осталось ссылок. */\n async function dropUnreferencedBlobs(tx: Executor): Promise<void> {\n await tx.delete(sandboxBlobs).where(notExists(tx.select({ one: sandboxBlobRefs.hash }).from(sandboxBlobRefs).where(eq(sandboxBlobRefs.hash, sandboxBlobs.hash))));\n }\n\n /**\n * Куски обращения пишутся одним запросом: в длинном чате их сотни (вся история), и запрос на каждый кусок\n * превращал одну запись журнала в сотни походов к базе. Порядок по хэшу одинаков у всех записей —\n * параллельные записи с общими кусками не ждут друг друга крест-накрест.\n */\n async function saveBlobs(tx: Executor, callId: string, row: { chatId: string; ownerId: string }, hashes: string[], blobs: BlobRow[]): Promise<void> {\n const unique = [...new Map(blobs.map((blob) => [blob.hash, blob])).values()].sort((left, right) => (left.hash < right.hash ? -1 : left.hash > right.hash ? 1 : 0));\n if (unique.length > 0) {\n await tx\n .insert(sandboxBlobs)\n .values(unique.map((blob) => ({ hash: blob.hash, data: Buffer.from(blob.data), bytes: blob.bytes, truncated: blob.truncated })))\n .onConflictDoNothing();\n }\n const refs = [...new Set(hashes)].map((hash) => ({ callId, hash, chatId: row.chatId, ownerId: row.ownerId }));\n if (refs.length > 0) await tx.insert(sandboxBlobRefs).values(refs);\n }\n\n return {\n async saveModelCall(row, blobs) {\n await db.transaction(async (tx) => {\n const inserted = await tx.insert(sandboxModelCalls).values({ ...row, error: withoutNul(row.error) }).onConflictDoNothing().returning({ id: sandboxModelCalls.id });\n if (inserted.length === 0) return;\n await saveBlobs(tx, row.id, row, [row.instructionsHash, ...row.messageHashes, row.toolsHash, row.settingsHash, row.responseHash], blobs);\n });\n },\n async saveToolCall(row, blobs) {\n await db.transaction(async (tx) => {\n const inserted = await tx.insert(sandboxToolCalls).values({ ...row, error: withoutNul(row.error) }).onConflictDoNothing().returning({ id: sandboxToolCalls.id });\n if (inserted.length === 0) return;\n await saveBlobs(tx, row.id, row, row.outputHash ? [row.inputHash, row.outputHash] : [row.inputHash], blobs);\n });\n },\n async listModelCalls(chatId) {\n return db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId)).orderBy(asc(sandboxModelCalls.startedAt));\n },\n async listToolCalls(chatId) {\n return db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId)).orderBy(asc(sandboxToolCalls.startedAt));\n },\n async findModelCall(id) {\n return (await db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.id, id)).limit(1))[0] ?? null;\n },\n async findToolCall(id) {\n return (await db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.id, id)).limit(1))[0] ?? null;\n },\n async loadBlobs(hashes) {\n if (hashes.length === 0) return [];\n return (await db.select().from(sandboxBlobs).where(inArray(sandboxBlobs.hash, hashes))).map(toBlobRow);\n },\n async loadBlobForOwner(hash, ownerId) {\n const owned = await db.select({ hash: sandboxBlobRefs.hash }).from(sandboxBlobRefs).where(and(eq(sandboxBlobRefs.hash, hash), eq(sandboxBlobRefs.ownerId, ownerId))).limit(1);\n if (owned.length === 0) return null;\n const row = (await db.select().from(sandboxBlobs).where(eq(sandboxBlobs.hash, hash)).limit(1))[0];\n return row ? toBlobRow(row) : null;\n },\n async getSettings(chatId) {\n return (await db.select().from(sandboxSettings).where(eq(sandboxSettings.chatId, chatId)).limit(1))[0] ?? null;\n },\n async setSettings(settings) {\n const clean = { ...settings, instructions: withoutNul(settings.instructions) };\n await db.insert(sandboxSettings).values(clean).onConflictDoUpdate({ target: sandboxSettings.chatId, set: clean });\n },\n async saveAnswerEdit(record) {\n await db.insert(sandboxAnswerEdits).values(record).onConflictDoUpdate({ target: sandboxAnswerEdits.messageId, set: record });\n },\n async listAnswerEdits(chatId) {\n return db.select().from(sandboxAnswerEdits).where(eq(sandboxAnswerEdits.chatId, chatId)).orderBy(asc(sandboxAnswerEdits.editedAt));\n },\n async deleteChat(chatId) {\n await db.transaction(async (tx) => {\n await tx.delete(sandboxBlobRefs).where(eq(sandboxBlobRefs.chatId, chatId));\n await tx.delete(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId));\n await tx.delete(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId));\n await tx.delete(sandboxSettings).where(eq(sandboxSettings.chatId, chatId));\n await tx.delete(sandboxAnswerEdits).where(eq(sandboxAnswerEdits.chatId, chatId));\n await dropUnreferencedBlobs(tx);\n });\n },\n async deleteOlderThan(before) {\n return db.transaction(async (tx) => {\n const oldModels = tx.select({ id: sandboxModelCalls.id }).from(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, before));\n const oldTools = tx.select({ id: sandboxToolCalls.id }).from(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, before));\n await tx.delete(sandboxBlobRefs).where(or(inArray(sandboxBlobRefs.callId, oldModels), inArray(sandboxBlobRefs.callId, oldTools)));\n const models = await tx.delete(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, before)).returning({ id: sandboxModelCalls.id });\n const tools = await tx.delete(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, before)).returning({ id: sandboxToolCalls.id });\n await dropUnreferencedBlobs(tx);\n return models.length + tools.length;\n });\n },\n async close() {\n await pool.end();\n },\n };\n}\n\n/** PostgreSQL не хранит символ NUL в тексте: сообщение об ошибке или инструкция с ним отклонили бы запись. */\nfunction withoutNul(text: string | null): string | null {\n return text === null ? null : text.replaceAll(\"\\u0000\", \"\");\n}\n\nfunction toBlobRow(row: typeof sandboxBlobs.$inferSelect): BlobRow {\n return { hash: row.hash, data: new Uint8Array(row.data), bytes: row.bytes, truncated: row.truncated };\n}\n","import type { ModelCallEvent } from \"@ykurilov/agent-chat-core\";\nimport { boolean, customType, doublePrecision, index, integer, jsonb, pgSchema, text, timestamp } from \"drizzle-orm/pg-core\";\n\n/** Та же схема базы, что у хранилища чатов: у приложения одна база и одна схема `agent_chat`. */\nconst agentChatSchema = pgSchema(\"agent_chat\");\n\nconst bytea = customType<{ data: Buffer; driverData: Buffer }>({\n dataType: () => \"bytea\",\n});\n\nconst startedAt = (name: string) => timestamp(name, { mode: \"date\", precision: 3, withTimezone: true });\n\nexport const sandboxBlobs = agentChatSchema.table(\"sandbox_blobs\", {\n hash: text(\"hash\").primaryKey(),\n data: bytea(\"data\").notNull(),\n bytes: integer(\"bytes\").notNull(),\n truncated: boolean(\"truncated\").notNull(),\n});\n\nexport const sandboxModelCalls = agentChatSchema.table(\n \"sandbox_model_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\"),\n purpose: text(\"purpose\").$type<ModelCallEvent[\"purpose\"]>().notNull(),\n attempt: integer(\"attempt\").notNull(),\n modelId: text(\"model_id\").notNull(),\n providerId: text(\"provider_id\").notNull(),\n usage: jsonb(\"usage\").$type<ModelCallEvent[\"usage\"]>(),\n costUsd: doublePrecision(\"cost_usd\"),\n startedAt: startedAt(\"started_at\").notNull(),\n firstChunkMs: integer(\"first_chunk_ms\"),\n durationMs: integer(\"duration_ms\").notNull(),\n status: text(\"status\").$type<ModelCallEvent[\"status\"]>().notNull(),\n error: text(\"error\"),\n instructionsHash: text(\"instructions_hash\").notNull(),\n messageHashes: jsonb(\"message_hashes\").$type<string[]>().notNull(),\n toolsHash: text(\"tools_hash\").notNull(),\n settingsHash: text(\"settings_hash\").notNull(),\n responseHash: text(\"response_hash\").notNull(),\n toolCallIds: jsonb(\"tool_call_ids\").$type<string[]>().notNull(),\n },\n (table) => [index(\"sandbox_model_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_model_calls_started_idx\").on(table.startedAt)],\n);\n\nexport const sandboxToolCalls = agentChatSchema.table(\n \"sandbox_tool_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\").notNull(),\n toolCallId: text(\"tool_call_id\").notNull(),\n toolName: text(\"tool_name\").notNull(),\n inputHash: text(\"input_hash\").notNull(),\n outputHash: text(\"output_hash\"),\n error: text(\"error\"),\n startedAt: startedAt(\"started_at\").notNull(),\n durationMs: integer(\"duration_ms\").notNull(),\n },\n (table) => [index(\"sandbox_tool_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_tool_calls_started_idx\").on(table.startedAt)],\n);\n\n/** Кто на какой кусок ссылается: по этим строкам решается, чей кусок и какие куски уже никому не нужны. */\nexport const sandboxBlobRefs = agentChatSchema.table(\n \"sandbox_blob_refs\",\n {\n callId: text(\"call_id\").notNull(),\n hash: text(\"hash\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n },\n (table) => [index(\"sandbox_blob_refs_call_idx\").on(table.callId), index(\"sandbox_blob_refs_hash_idx\").on(table.hash, table.ownerId), index(\"sandbox_blob_refs_chat_idx\").on(table.chatId)],\n);\n\nexport const sandboxSettings = agentChatSchema.table(\"sandbox_settings\", {\n chatId: text(\"chat_id\").primaryKey(),\n instructions: text(\"instructions\"),\n updatedBy: text(\"updated_by\").notNull(),\n updatedAt: startedAt(\"updated_at\").notNull(),\n});\n\nexport const sandboxAnswerEdits = agentChatSchema.table(\n \"sandbox_answer_edits\",\n {\n messageId: text(\"message_id\").primaryKey(),\n sourceMessageId: text(\"source_message_id\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n textEdited: boolean(\"text_edited\").notNull(),\n editedToolCallIds: jsonb(\"edited_tool_call_ids\").$type<string[]>().notNull(),\n editedBy: text(\"edited_by\").notNull(),\n editedAt: startedAt(\"edited_at\").notNull(),\n },\n (table) => [index(\"sandbox_answer_edits_chat_idx\").on(table.chatId, table.editedAt)],\n);\n","// Создано scripts/embed-migrations.mjs из packages/sandbox/drizzle/postgres; не править руками: `pnpm db:generate` пакета пересоздаёт файл.\nimport type { EmbeddedMigration } from \"@ykurilov/agent-chat-core\";\n\nexport const migrations: readonly EmbeddedMigration[] = [\n // 0000_journal_init\n { folderMillis: 1791041535977, hash: \"944772a6c593f0ac2f3e5a656f527454d14cf9734e77e84dff54c8c2614c9162\", bps: true, sql: [\n \"CREATE SCHEMA IF NOT EXISTS \\\"agent_chat\\\";\\n\",\n \"\\nCREATE TABLE \\\"agent_chat\\\".\\\"sandbox_answer_edits\\\" (\\n\\t\\\"message_id\\\" text PRIMARY KEY NOT NULL,\\n\\t\\\"source_message_id\\\" text NOT NULL,\\n\\t\\\"chat_id\\\" text NOT NULL,\\n\\t\\\"text_edited\\\" boolean NOT NULL,\\n\\t\\\"edited_tool_call_ids\\\" jsonb NOT NULL,\\n\\t\\\"edited_by\\\" text NOT NULL,\\n\\t\\\"edited_at\\\" timestamp (3) with time zone NOT NULL\\n);\\n\",\n \"\\nCREATE TABLE \\\"agent_chat\\\".\\\"sandbox_blob_refs\\\" (\\n\\t\\\"call_id\\\" text NOT NULL,\\n\\t\\\"hash\\\" text NOT NULL,\\n\\t\\\"chat_id\\\" text NOT NULL,\\n\\t\\\"owner_id\\\" text NOT NULL\\n);\\n\",\n \"\\nCREATE TABLE \\\"agent_chat\\\".\\\"sandbox_blobs\\\" (\\n\\t\\\"hash\\\" text PRIMARY KEY NOT NULL,\\n\\t\\\"data\\\" \\\"bytea\\\" NOT NULL,\\n\\t\\\"bytes\\\" integer NOT NULL,\\n\\t\\\"truncated\\\" boolean NOT NULL\\n);\\n\",\n \"\\nCREATE TABLE \\\"agent_chat\\\".\\\"sandbox_model_calls\\\" (\\n\\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\\t\\\"chat_id\\\" text NOT NULL,\\n\\t\\\"owner_id\\\" text NOT NULL,\\n\\t\\\"message_id\\\" text,\\n\\t\\\"purpose\\\" text NOT NULL,\\n\\t\\\"attempt\\\" integer NOT NULL,\\n\\t\\\"model_id\\\" text NOT NULL,\\n\\t\\\"provider_id\\\" text NOT NULL,\\n\\t\\\"usage\\\" jsonb,\\n\\t\\\"cost_usd\\\" double precision,\\n\\t\\\"started_at\\\" timestamp (3) with time zone NOT NULL,\\n\\t\\\"first_chunk_ms\\\" integer,\\n\\t\\\"duration_ms\\\" integer NOT NULL,\\n\\t\\\"status\\\" text NOT NULL,\\n\\t\\\"error\\\" text,\\n\\t\\\"instructions_hash\\\" text NOT NULL,\\n\\t\\\"message_hashes\\\" jsonb NOT NULL,\\n\\t\\\"tools_hash\\\" text NOT NULL,\\n\\t\\\"settings_hash\\\" text NOT NULL,\\n\\t\\\"response_hash\\\" text NOT NULL,\\n\\t\\\"tool_call_ids\\\" jsonb NOT NULL\\n);\\n\",\n \"\\nCREATE TABLE \\\"agent_chat\\\".\\\"sandbox_settings\\\" (\\n\\t\\\"chat_id\\\" text PRIMARY KEY NOT NULL,\\n\\t\\\"instructions\\\" text,\\n\\t\\\"updated_by\\\" text NOT NULL,\\n\\t\\\"updated_at\\\" timestamp (3) with time zone NOT NULL\\n);\\n\",\n \"\\nCREATE TABLE \\\"agent_chat\\\".\\\"sandbox_tool_calls\\\" (\\n\\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\\t\\\"chat_id\\\" text NOT NULL,\\n\\t\\\"owner_id\\\" text NOT NULL,\\n\\t\\\"message_id\\\" text NOT NULL,\\n\\t\\\"tool_call_id\\\" text NOT NULL,\\n\\t\\\"tool_name\\\" text NOT NULL,\\n\\t\\\"input_hash\\\" text NOT NULL,\\n\\t\\\"output_hash\\\" text,\\n\\t\\\"error\\\" text,\\n\\t\\\"started_at\\\" timestamp (3) with time zone NOT NULL,\\n\\t\\\"duration_ms\\\" integer NOT NULL\\n);\\n\",\n \"\\nCREATE INDEX \\\"sandbox_answer_edits_chat_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_answer_edits\\\" USING btree (\\\"chat_id\\\",\\\"edited_at\\\");\",\n \"\\nCREATE INDEX \\\"sandbox_blob_refs_call_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_blob_refs\\\" USING btree (\\\"call_id\\\");\",\n \"\\nCREATE INDEX \\\"sandbox_blob_refs_hash_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_blob_refs\\\" USING btree (\\\"hash\\\",\\\"owner_id\\\");\",\n \"\\nCREATE INDEX \\\"sandbox_blob_refs_chat_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_blob_refs\\\" USING btree (\\\"chat_id\\\");\",\n \"\\nCREATE INDEX \\\"sandbox_model_calls_chat_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_model_calls\\\" USING btree (\\\"chat_id\\\",\\\"started_at\\\");\",\n \"\\nCREATE INDEX \\\"sandbox_model_calls_started_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_model_calls\\\" USING btree (\\\"started_at\\\");\",\n \"\\nCREATE INDEX \\\"sandbox_tool_calls_chat_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_tool_calls\\\" USING btree (\\\"chat_id\\\",\\\"started_at\\\");\",\n \"\\nCREATE INDEX \\\"sandbox_tool_calls_started_idx\\\" ON \\\"agent_chat\\\".\\\"sandbox_tool_calls\\\" USING btree (\\\"started_at\\\");\",\n ] },\n];\n"],"mappings":";;;;;AAAA,OAAO,QAAQ;;;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BAAkB,CAAC;AAEnH,OAAK,GAAG,SAAS,CAAC,UAAU,SAAS,6OAAyD,MAAM,OAAO,EAAE,CAAC;AAC9G,MAAI;AACF,UAAM,uBAAuB,MAAM,UAAU;AAAA,EAC/C,SAAS,OAAO;AACd,UAAM,KAAK,IAAI,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAC/B,UAAM,QAAQ,OAAO,QAAQ,gBAAgB;AAAA,EAC/C;AACA,SAAO,qBAAqB,2BAA2B,IAAI,GAAG,EAAE,GAAG,SAAS,SAAS,CAAC;AACxF;AAGA,SAAS,QAAQ,OAAgB,kBAAiC;AAChE,QAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACpE,SAAO,IAAI,MAAM,6OAAyD,OAAO,MAAM,gBAAgB,EAAE,KAAK,2GAAsB,CAAC,EAAE;AACzI;","names":["migrations","text"]}
package/dist/sqlite.js CHANGED
@@ -3,13 +3,12 @@ import {
3
3
  } from "./chunk-4O5NPJOS.js";
4
4
 
5
5
  // src/sqlite.ts
6
- import { fileURLToPath } from "url";
7
6
  import Database from "better-sqlite3";
8
7
 
9
8
  // src/journal/sqlite-journal.ts
9
+ import { applyEmbeddedMigrations } from "@ykurilov/agent-chat-core";
10
10
  import { and, asc, eq, inArray, lt, notInArray, or } from "drizzle-orm";
11
11
  import { drizzle } from "drizzle-orm/better-sqlite3";
12
- import { migrate } from "drizzle-orm/better-sqlite3/migrator";
13
12
 
14
13
  // src/journal/sqlite-schema.ts
15
14
  import { blob, index, integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
@@ -95,9 +94,9 @@ var sandboxAnswerEdits = sqliteTable(
95
94
 
96
95
  // src/journal/sqlite-journal.ts
97
96
  var MIGRATIONS_TABLE = "__sandbox_migrations";
98
- function createSqliteJournalStore(sqlite, migrationsFolder2) {
97
+ function createSqliteJournalStore(sqlite, migrations2) {
99
98
  const db = drizzle(sqlite);
100
- migrate(db, { migrationsFolder: migrationsFolder2, migrationsTable: MIGRATIONS_TABLE });
99
+ applyEmbeddedMigrations(db, migrations2, { migrationsTable: MIGRATIONS_TABLE });
101
100
  function dropUnreferencedBlobs(tx) {
102
101
  tx.delete(sandboxBlobs).where(notInArray(sandboxBlobs.hash, tx.select({ hash: sandboxBlobRefs.hash }).from(sandboxBlobRefs))).run();
103
102
  }
@@ -202,14 +201,34 @@ function toBlobRow(row) {
202
201
  return { hash: row.hash, data: new Uint8Array(row.data), bytes: row.bytes, truncated: row.truncated };
203
202
  }
204
203
 
204
+ // src/drizzle-migrations-sqlite.generated.ts
205
+ var migrations = [
206
+ // 0000_journal_init
207
+ { folderMillis: 1791041535561, hash: "f32a0634b1a1856ba157e10ccb34f8b0b5799487d069e5536ed391d2daeae10c", bps: true, sql: [
208
+ "CREATE TABLE `sandbox_answer_edits` (\n `message_id` text PRIMARY KEY NOT NULL,\n `source_message_id` text NOT NULL,\n `chat_id` text NOT NULL,\n `text_edited` integer NOT NULL,\n `edited_tool_call_ids` text NOT NULL,\n `edited_by` text NOT NULL,\n `edited_at` integer NOT NULL\n);\n",
209
+ "\nCREATE INDEX `sandbox_answer_edits_chat_idx` ON `sandbox_answer_edits` (`chat_id`,`edited_at`);",
210
+ "\nCREATE TABLE `sandbox_blob_refs` (\n `call_id` text NOT NULL,\n `hash` text NOT NULL,\n `chat_id` text NOT NULL,\n `owner_id` text NOT NULL\n);\n",
211
+ "\nCREATE INDEX `sandbox_blob_refs_call_idx` ON `sandbox_blob_refs` (`call_id`);",
212
+ "\nCREATE INDEX `sandbox_blob_refs_hash_idx` ON `sandbox_blob_refs` (`hash`,`owner_id`);",
213
+ "\nCREATE INDEX `sandbox_blob_refs_chat_idx` ON `sandbox_blob_refs` (`chat_id`);",
214
+ "\nCREATE TABLE `sandbox_blobs` (\n `hash` text PRIMARY KEY NOT NULL,\n `data` blob NOT NULL,\n `bytes` integer NOT NULL,\n `truncated` integer NOT NULL\n);\n",
215
+ "\nCREATE TABLE `sandbox_model_calls` (\n `id` text PRIMARY KEY NOT NULL,\n `chat_id` text NOT NULL,\n `owner_id` text NOT NULL,\n `message_id` text,\n `purpose` text NOT NULL,\n `attempt` integer NOT NULL,\n `model_id` text NOT NULL,\n `provider_id` text NOT NULL,\n `usage` text,\n `cost_usd` real,\n `started_at` integer NOT NULL,\n `first_chunk_ms` integer,\n `duration_ms` integer NOT NULL,\n `status` text NOT NULL,\n `error` text,\n `instructions_hash` text NOT NULL,\n `message_hashes` text NOT NULL,\n `tools_hash` text NOT NULL,\n `settings_hash` text NOT NULL,\n `response_hash` text NOT NULL,\n `tool_call_ids` text NOT NULL\n);\n",
216
+ "\nCREATE INDEX `sandbox_model_calls_chat_idx` ON `sandbox_model_calls` (`chat_id`,`started_at`);",
217
+ "\nCREATE INDEX `sandbox_model_calls_started_idx` ON `sandbox_model_calls` (`started_at`);",
218
+ "\nCREATE TABLE `sandbox_settings` (\n `chat_id` text PRIMARY KEY NOT NULL,\n `instructions` text,\n `updated_by` text NOT NULL,\n `updated_at` integer NOT NULL\n);\n",
219
+ "\nCREATE TABLE `sandbox_tool_calls` (\n `id` text PRIMARY KEY NOT NULL,\n `chat_id` text NOT NULL,\n `owner_id` text NOT NULL,\n `message_id` text NOT NULL,\n `tool_call_id` text NOT NULL,\n `tool_name` text NOT NULL,\n `input_hash` text NOT NULL,\n `output_hash` text,\n `error` text,\n `started_at` integer NOT NULL,\n `duration_ms` integer NOT NULL\n);\n",
220
+ "\nCREATE INDEX `sandbox_tool_calls_chat_idx` ON `sandbox_tool_calls` (`chat_id`,`started_at`);",
221
+ "\nCREATE INDEX `sandbox_tool_calls_started_idx` ON `sandbox_tool_calls` (`started_at`);"
222
+ ] }
223
+ ];
224
+
205
225
  // src/sqlite.ts
206
- var migrationsFolder = fileURLToPath(new URL("../drizzle/sqlite", import.meta.url));
207
226
  async function createSqliteSandboxJournal(options) {
208
227
  const sqlite = new Database(options.filePath);
209
228
  try {
210
229
  sqlite.pragma("journal_mode = WAL");
211
230
  sqlite.pragma("busy_timeout = 5000");
212
- return createSandboxJournal(createSqliteJournalStore(sqlite, migrationsFolder), options);
231
+ return createSandboxJournal(createSqliteJournalStore(sqlite, migrations), options);
213
232
  } catch (error) {
214
233
  sqlite.close();
215
234
  throw error;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sqlite.ts","../src/journal/sqlite-journal.ts","../src/journal/sqlite-schema.ts"],"sourcesContent":["import { fileURLToPath } from \"node:url\";\nimport Database from \"better-sqlite3\";\nimport type { JournalOptions } from \"./journal/journal\";\nimport { createSandboxJournal } from \"./journal/journal\";\nimport { createSqliteJournalStore } from \"./journal/sqlite-journal\";\nimport type { SandboxJournal } from \"./types\";\n\nexport type { LogError, SandboxJournal } from \"./types\";\n\nexport type SqliteSandboxJournalOptions = JournalOptions & {\n /** Файл SQLite; может быть тем же, что у `createSqliteChatStorage`. */\n filePath: string;\n};\n\nconst migrationsFolder = fileURLToPath(new URL(\"../drizzle/sqlite\", import.meta.url));\n\n/** Журнал песочницы в файле SQLite. Схема приводится к последней миграции при открытии. */\nexport async function createSqliteSandboxJournal(options: SqliteSandboxJournalOptions): Promise<SandboxJournal> {\n const sqlite = new Database(options.filePath);\n try {\n sqlite.pragma(\"journal_mode = WAL\");\n // Хранилище чатов и журнал открывают один файл: при блокировке второй ждёт, а не падает.\n sqlite.pragma(\"busy_timeout = 5000\");\n return createSandboxJournal(createSqliteJournalStore(sqlite, migrationsFolder), options);\n } catch (error) {\n sqlite.close();\n throw error;\n }\n}\n","import type Database from \"better-sqlite3\";\nimport { and, asc, eq, inArray, lt, notInArray, or, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { migrate } from \"drizzle-orm/better-sqlite3/migrator\";\nimport type { BlobRow, JournalStore, ModelCallRow, ToolCallRow } from \"./journal-store\";\nimport { sandboxAnswerEdits, sandboxBlobRefs, sandboxBlobs, sandboxModelCalls, sandboxSettings, sandboxToolCalls } from \"./sqlite-schema\";\n\n/** Своя таблица учёта: хранилище чатов живёт в той же базе и ведёт свою (`__agent_chat_migrations`). */\nconst MIGRATIONS_TABLE = \"__sandbox_migrations\";\n\n/** Хранилище журнала в SQLite. Схема приводится к последней миграции при создании. */\nexport function createSqliteJournalStore(sqlite: Database.Database, migrationsFolder: string): JournalStore {\n const db = drizzle(sqlite);\n migrate(db, { migrationsFolder, migrationsTable: MIGRATIONS_TABLE });\n\n /** Куски, на которые не осталось ссылок. */\n function dropUnreferencedBlobs(tx: Pick<typeof db, \"delete\" | \"select\">): void {\n tx.delete(sandboxBlobs).where(notInArray(sandboxBlobs.hash, tx.select({ hash: sandboxBlobRefs.hash }).from(sandboxBlobRefs))).run();\n }\n\n function saveBlobs(tx: Pick<typeof db, \"insert\">, callId: string, row: { chatId: string; ownerId: string }, hashes: string[], blobs: BlobRow[]): void {\n for (const blob of blobs) tx.insert(sandboxBlobs).values({ hash: blob.hash, data: Buffer.from(blob.data), bytes: blob.bytes, truncated: blob.truncated }).onConflictDoNothing().run();\n for (const hash of new Set(hashes)) tx.insert(sandboxBlobRefs).values({ callId, hash, chatId: row.chatId, ownerId: row.ownerId }).run();\n }\n\n return {\n async saveModelCall(row, blobs) {\n db.transaction((tx) => {\n const inserted = tx.insert(sandboxModelCalls).values(modelValues(row)).onConflictDoNothing().run();\n if (inserted.changes === 0) return;\n saveBlobs(tx, row.id, row, [row.instructionsHash, ...row.messageHashes, row.toolsHash, row.settingsHash, row.responseHash], blobs);\n });\n },\n async saveToolCall(row, blobs) {\n db.transaction((tx) => {\n const inserted = tx.insert(sandboxToolCalls).values(toolValues(row)).onConflictDoNothing().run();\n if (inserted.changes === 0) return;\n saveBlobs(tx, row.id, row, row.outputHash ? [row.inputHash, row.outputHash] : [row.inputHash], blobs);\n });\n },\n async listModelCalls(chatId) {\n return db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId)).orderBy(asc(sandboxModelCalls.startedAt)).all().map(toModelRow);\n },\n async listToolCalls(chatId) {\n return db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId)).orderBy(asc(sandboxToolCalls.startedAt)).all().map(toToolRow);\n },\n async findModelCall(id) {\n const row = db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.id, id)).get();\n return row ? toModelRow(row) : null;\n },\n async findToolCall(id) {\n const row = db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.id, id)).get();\n return row ? toToolRow(row) : null;\n },\n async loadBlobs(hashes) {\n if (hashes.length === 0) return [];\n return db.select().from(sandboxBlobs).where(inArray(sandboxBlobs.hash, hashes)).all().map(toBlobRow);\n },\n async loadBlobForOwner(hash, ownerId) {\n const owned = db.select({ hash: sandboxBlobRefs.hash }).from(sandboxBlobRefs).where(and(eq(sandboxBlobRefs.hash, hash), eq(sandboxBlobRefs.ownerId, ownerId))).limit(1).get();\n if (!owned) return null;\n const row = db.select().from(sandboxBlobs).where(eq(sandboxBlobs.hash, hash)).get();\n return row ? toBlobRow(row) : null;\n },\n async getSettings(chatId) {\n const row = db.select().from(sandboxSettings).where(eq(sandboxSettings.chatId, chatId)).get();\n return row ? { chatId: row.chatId, instructions: row.instructions, updatedBy: row.updatedBy, updatedAt: new Date(row.updatedAt) } : null;\n },\n async setSettings(settings) {\n const values = { chatId: settings.chatId, instructions: settings.instructions, updatedBy: settings.updatedBy, updatedAt: settings.updatedAt.getTime() };\n db.insert(sandboxSettings).values(values).onConflictDoUpdate({ target: sandboxSettings.chatId, set: values }).run();\n },\n async saveAnswerEdit(record) {\n const values = { ...record, editedAt: record.editedAt.getTime() };\n db.insert(sandboxAnswerEdits).values(values).onConflictDoUpdate({ target: sandboxAnswerEdits.messageId, set: values }).run();\n },\n async listAnswerEdits(chatId) {\n return db\n .select()\n .from(sandboxAnswerEdits)\n .where(eq(sandboxAnswerEdits.chatId, chatId))\n .orderBy(asc(sandboxAnswerEdits.editedAt))\n .all()\n .map((row) => ({ ...row, editedAt: new Date(row.editedAt) }));\n },\n async deleteChat(chatId) {\n db.transaction((tx) => {\n tx.delete(sandboxBlobRefs).where(eq(sandboxBlobRefs.chatId, chatId)).run();\n tx.delete(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId)).run();\n tx.delete(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId)).run();\n tx.delete(sandboxSettings).where(eq(sandboxSettings.chatId, chatId)).run();\n tx.delete(sandboxAnswerEdits).where(eq(sandboxAnswerEdits.chatId, chatId)).run();\n dropUnreferencedBlobs(tx);\n });\n },\n async deleteOlderThan(before) {\n const cutoff = before.getTime();\n return db.transaction((tx) => {\n const oldModels = tx.select({ id: sandboxModelCalls.id }).from(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, cutoff));\n const oldTools = tx.select({ id: sandboxToolCalls.id }).from(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, cutoff));\n tx.delete(sandboxBlobRefs).where(or(inArray(sandboxBlobRefs.callId, oldModels), inArray(sandboxBlobRefs.callId, oldTools))).run();\n const models = tx.delete(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, cutoff)).run().changes;\n const tools = tx.delete(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, cutoff)).run().changes;\n dropUnreferencedBlobs(tx);\n return models + tools;\n });\n },\n async close() {\n sqlite.close();\n },\n };\n}\n\nfunction modelValues(row: ModelCallRow): typeof sandboxModelCalls.$inferInsert {\n return { ...row, startedAt: row.startedAt.getTime() };\n}\n\nfunction toolValues(row: ToolCallRow): typeof sandboxToolCalls.$inferInsert {\n return { ...row, startedAt: row.startedAt.getTime() };\n}\n\nfunction toModelRow(row: typeof sandboxModelCalls.$inferSelect): ModelCallRow {\n return { ...row, startedAt: new Date(row.startedAt) };\n}\n\nfunction toToolRow(row: typeof sandboxToolCalls.$inferSelect): ToolCallRow {\n return { ...row, startedAt: new Date(row.startedAt) };\n}\n\nfunction toBlobRow(row: typeof sandboxBlobs.$inferSelect): BlobRow {\n return { hash: row.hash, data: new Uint8Array(row.data), bytes: row.bytes, truncated: row.truncated };\n}\n","import type { ModelCallEvent } from \"@ykurilov/agent-chat-core\";\nimport { blob, index, integer, real, sqliteTable, text } from \"drizzle-orm/sqlite-core\";\n\n/** Куски журнала: один раз на хеш, сжатый JSON. */\nexport const sandboxBlobs = sqliteTable(\"sandbox_blobs\", {\n hash: text(\"hash\").primaryKey(),\n data: blob(\"data\", { mode: \"buffer\" }).notNull(),\n bytes: integer(\"bytes\").notNull(),\n truncated: integer(\"truncated\", { mode: \"boolean\" }).notNull(),\n});\n\nexport const sandboxModelCalls = sqliteTable(\n \"sandbox_model_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\"),\n purpose: text(\"purpose\").$type<ModelCallEvent[\"purpose\"]>().notNull(),\n attempt: integer(\"attempt\").notNull(),\n modelId: text(\"model_id\").notNull(),\n providerId: text(\"provider_id\").notNull(),\n usage: text(\"usage\", { mode: \"json\" }).$type<ModelCallEvent[\"usage\"]>(),\n costUsd: real(\"cost_usd\"),\n startedAt: integer(\"started_at\").notNull(),\n firstChunkMs: integer(\"first_chunk_ms\"),\n durationMs: integer(\"duration_ms\").notNull(),\n status: text(\"status\").$type<ModelCallEvent[\"status\"]>().notNull(),\n error: text(\"error\"),\n instructionsHash: text(\"instructions_hash\").notNull(),\n messageHashes: text(\"message_hashes\", { mode: \"json\" }).$type<string[]>().notNull(),\n toolsHash: text(\"tools_hash\").notNull(),\n settingsHash: text(\"settings_hash\").notNull(),\n responseHash: text(\"response_hash\").notNull(),\n toolCallIds: text(\"tool_call_ids\", { mode: \"json\" }).$type<string[]>().notNull(),\n },\n (table) => [index(\"sandbox_model_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_model_calls_started_idx\").on(table.startedAt)],\n);\n\nexport const sandboxToolCalls = sqliteTable(\n \"sandbox_tool_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\").notNull(),\n toolCallId: text(\"tool_call_id\").notNull(),\n toolName: text(\"tool_name\").notNull(),\n inputHash: text(\"input_hash\").notNull(),\n outputHash: text(\"output_hash\"),\n error: text(\"error\"),\n startedAt: integer(\"started_at\").notNull(),\n durationMs: integer(\"duration_ms\").notNull(),\n },\n (table) => [index(\"sandbox_tool_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_tool_calls_started_idx\").on(table.startedAt)],\n);\n\n/** Кто на какой кусок ссылается: по этим строкам решается, чей кусок и какие куски уже никому не нужны. */\nexport const sandboxBlobRefs = sqliteTable(\n \"sandbox_blob_refs\",\n {\n callId: text(\"call_id\").notNull(),\n hash: text(\"hash\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n },\n (table) => [index(\"sandbox_blob_refs_call_idx\").on(table.callId), index(\"sandbox_blob_refs_hash_idx\").on(table.hash, table.ownerId), index(\"sandbox_blob_refs_chat_idx\").on(table.chatId)],\n);\n\nexport const sandboxSettings = sqliteTable(\"sandbox_settings\", {\n chatId: text(\"chat_id\").primaryKey(),\n instructions: text(\"instructions\"),\n updatedBy: text(\"updated_by\").notNull(),\n updatedAt: integer(\"updated_at\").notNull(),\n});\n\nexport const sandboxAnswerEdits = sqliteTable(\n \"sandbox_answer_edits\",\n {\n messageId: text(\"message_id\").primaryKey(),\n sourceMessageId: text(\"source_message_id\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n textEdited: integer(\"text_edited\", { mode: \"boolean\" }).notNull(),\n editedToolCallIds: text(\"edited_tool_call_ids\", { mode: \"json\" }).$type<string[]>().notNull(),\n editedBy: text(\"edited_by\").notNull(),\n editedAt: integer(\"edited_at\").notNull(),\n },\n (table) => [index(\"sandbox_answer_edits_chat_idx\").on(table.chatId, table.editedAt)],\n);\n"],"mappings":";;;;;AAAA,SAAS,qBAAqB;AAC9B,OAAO,cAAc;;;ACArB,SAAS,KAAK,KAAK,IAAI,SAAS,IAAI,YAAY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AEA,SAAS,YAAY,KAA0D;AAC7E,SAAO,EAAE,GAAG,KAAK,WAAW,IAAI,UAAU,QAAQ,EAAE;AACtD;AAEA,SAAS,WAAW,KAAwD;AAC1E,SAAO,EAAE,GAAG,KAAK,WAAW,IAAI,UAAU,QAAQ,EAAE;AACtD;AAEA,SAAS,WAAW,KAA0D;AAC5E,SAAO,EAAE,GAAG,KAAK,WAAW,IAAI,KAAK,IAAI,SAAS,EAAE;AACtD;AAEA,SAAS,UAAU,KAAwD;AACzE,SAAO,EAAE,GAAG,KAAK,WAAW,IAAI,KAAK,IAAI,SAAS,EAAE;AACtD;AAEA,SAAS,UAAU,KAAgD;AACjE,SAAO,EAAE,MAAM,IAAI,MAAM,MAAM,IAAI,WAAW,IAAI,IAAI,GAAG,OAAO,IAAI,OAAO,WAAW,IAAI,UAAU;AACtG;;;ADrHA,IAAM,mBAAmB,cAAc,IAAI,IAAI,qBAAqB,YAAY,GAAG,CAAC;AAGpF,eAAsB,2BAA2B,SAA+D;AAC9G,QAAM,SAAS,IAAI,SAAS,QAAQ,QAAQ;AAC5C,MAAI;AACF,WAAO,OAAO,oBAAoB;AAElC,WAAO,OAAO,qBAAqB;AACnC,WAAO,qBAAqB,yBAAyB,QAAQ,gBAAgB,GAAG,OAAO;AAAA,EACzF,SAAS,OAAO;AACd,WAAO,MAAM;AACb,UAAM;AAAA,EACR;AACF;","names":["migrationsFolder","blob"]}
1
+ {"version":3,"sources":["../src/sqlite.ts","../src/journal/sqlite-journal.ts","../src/journal/sqlite-schema.ts","../src/drizzle-migrations-sqlite.generated.ts"],"sourcesContent":["import Database from \"better-sqlite3\";\nimport type { JournalOptions } from \"./journal/journal\";\nimport { createSandboxJournal } from \"./journal/journal\";\nimport { createSqliteJournalStore } from \"./journal/sqlite-journal\";\nimport type { SandboxJournal } from \"./types\";\nimport { migrations } from \"./drizzle-migrations-sqlite.generated\";\n\nexport type { LogError, SandboxJournal } from \"./types\";\n\nexport type SqliteSandboxJournalOptions = JournalOptions & {\n /** Файл SQLite; может быть тем же, что у `createSqliteChatStorage`. */\n filePath: string;\n};\n\n\n/** Журнал песочницы в файле SQLite. Схема приводится к последней миграции при открытии. */\nexport async function createSqliteSandboxJournal(options: SqliteSandboxJournalOptions): Promise<SandboxJournal> {\n const sqlite = new Database(options.filePath);\n try {\n sqlite.pragma(\"journal_mode = WAL\");\n // Хранилище чатов и журнал открывают один файл: при блокировке второй ждёт, а не падает.\n sqlite.pragma(\"busy_timeout = 5000\");\n return createSandboxJournal(createSqliteJournalStore(sqlite, migrations), options);\n } catch (error) {\n sqlite.close();\n throw error;\n }\n}\n","import { applyEmbeddedMigrations, type EmbeddedMigration } from \"@ykurilov/agent-chat-core\";\nimport type Database from \"better-sqlite3\";\nimport { and, asc, eq, inArray, lt, notInArray, or, sql } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport type { BlobRow, JournalStore, ModelCallRow, ToolCallRow } from \"./journal-store\";\nimport { sandboxAnswerEdits, sandboxBlobRefs, sandboxBlobs, sandboxModelCalls, sandboxSettings, sandboxToolCalls } from \"./sqlite-schema\";\n\n/** Своя таблица учёта: хранилище чатов живёт в той же базе и ведёт свою (`__agent_chat_migrations`). */\nconst MIGRATIONS_TABLE = \"__sandbox_migrations\";\n\n/** Хранилище журнала в SQLite. Схема приводится к последней миграции при создании. */\nexport function createSqliteJournalStore(sqlite: Database.Database, migrations: readonly EmbeddedMigration[]): JournalStore {\n const db = drizzle(sqlite);\n applyEmbeddedMigrations(db, migrations, { migrationsTable: MIGRATIONS_TABLE });\n\n /** Куски, на которые не осталось ссылок. */\n function dropUnreferencedBlobs(tx: Pick<typeof db, \"delete\" | \"select\">): void {\n tx.delete(sandboxBlobs).where(notInArray(sandboxBlobs.hash, tx.select({ hash: sandboxBlobRefs.hash }).from(sandboxBlobRefs))).run();\n }\n\n function saveBlobs(tx: Pick<typeof db, \"insert\">, callId: string, row: { chatId: string; ownerId: string }, hashes: string[], blobs: BlobRow[]): void {\n for (const blob of blobs) tx.insert(sandboxBlobs).values({ hash: blob.hash, data: Buffer.from(blob.data), bytes: blob.bytes, truncated: blob.truncated }).onConflictDoNothing().run();\n for (const hash of new Set(hashes)) tx.insert(sandboxBlobRefs).values({ callId, hash, chatId: row.chatId, ownerId: row.ownerId }).run();\n }\n\n return {\n async saveModelCall(row, blobs) {\n db.transaction((tx) => {\n const inserted = tx.insert(sandboxModelCalls).values(modelValues(row)).onConflictDoNothing().run();\n if (inserted.changes === 0) return;\n saveBlobs(tx, row.id, row, [row.instructionsHash, ...row.messageHashes, row.toolsHash, row.settingsHash, row.responseHash], blobs);\n });\n },\n async saveToolCall(row, blobs) {\n db.transaction((tx) => {\n const inserted = tx.insert(sandboxToolCalls).values(toolValues(row)).onConflictDoNothing().run();\n if (inserted.changes === 0) return;\n saveBlobs(tx, row.id, row, row.outputHash ? [row.inputHash, row.outputHash] : [row.inputHash], blobs);\n });\n },\n async listModelCalls(chatId) {\n return db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId)).orderBy(asc(sandboxModelCalls.startedAt)).all().map(toModelRow);\n },\n async listToolCalls(chatId) {\n return db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId)).orderBy(asc(sandboxToolCalls.startedAt)).all().map(toToolRow);\n },\n async findModelCall(id) {\n const row = db.select().from(sandboxModelCalls).where(eq(sandboxModelCalls.id, id)).get();\n return row ? toModelRow(row) : null;\n },\n async findToolCall(id) {\n const row = db.select().from(sandboxToolCalls).where(eq(sandboxToolCalls.id, id)).get();\n return row ? toToolRow(row) : null;\n },\n async loadBlobs(hashes) {\n if (hashes.length === 0) return [];\n return db.select().from(sandboxBlobs).where(inArray(sandboxBlobs.hash, hashes)).all().map(toBlobRow);\n },\n async loadBlobForOwner(hash, ownerId) {\n const owned = db.select({ hash: sandboxBlobRefs.hash }).from(sandboxBlobRefs).where(and(eq(sandboxBlobRefs.hash, hash), eq(sandboxBlobRefs.ownerId, ownerId))).limit(1).get();\n if (!owned) return null;\n const row = db.select().from(sandboxBlobs).where(eq(sandboxBlobs.hash, hash)).get();\n return row ? toBlobRow(row) : null;\n },\n async getSettings(chatId) {\n const row = db.select().from(sandboxSettings).where(eq(sandboxSettings.chatId, chatId)).get();\n return row ? { chatId: row.chatId, instructions: row.instructions, updatedBy: row.updatedBy, updatedAt: new Date(row.updatedAt) } : null;\n },\n async setSettings(settings) {\n const values = { chatId: settings.chatId, instructions: settings.instructions, updatedBy: settings.updatedBy, updatedAt: settings.updatedAt.getTime() };\n db.insert(sandboxSettings).values(values).onConflictDoUpdate({ target: sandboxSettings.chatId, set: values }).run();\n },\n async saveAnswerEdit(record) {\n const values = { ...record, editedAt: record.editedAt.getTime() };\n db.insert(sandboxAnswerEdits).values(values).onConflictDoUpdate({ target: sandboxAnswerEdits.messageId, set: values }).run();\n },\n async listAnswerEdits(chatId) {\n return db\n .select()\n .from(sandboxAnswerEdits)\n .where(eq(sandboxAnswerEdits.chatId, chatId))\n .orderBy(asc(sandboxAnswerEdits.editedAt))\n .all()\n .map((row) => ({ ...row, editedAt: new Date(row.editedAt) }));\n },\n async deleteChat(chatId) {\n db.transaction((tx) => {\n tx.delete(sandboxBlobRefs).where(eq(sandboxBlobRefs.chatId, chatId)).run();\n tx.delete(sandboxModelCalls).where(eq(sandboxModelCalls.chatId, chatId)).run();\n tx.delete(sandboxToolCalls).where(eq(sandboxToolCalls.chatId, chatId)).run();\n tx.delete(sandboxSettings).where(eq(sandboxSettings.chatId, chatId)).run();\n tx.delete(sandboxAnswerEdits).where(eq(sandboxAnswerEdits.chatId, chatId)).run();\n dropUnreferencedBlobs(tx);\n });\n },\n async deleteOlderThan(before) {\n const cutoff = before.getTime();\n return db.transaction((tx) => {\n const oldModels = tx.select({ id: sandboxModelCalls.id }).from(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, cutoff));\n const oldTools = tx.select({ id: sandboxToolCalls.id }).from(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, cutoff));\n tx.delete(sandboxBlobRefs).where(or(inArray(sandboxBlobRefs.callId, oldModels), inArray(sandboxBlobRefs.callId, oldTools))).run();\n const models = tx.delete(sandboxModelCalls).where(lt(sandboxModelCalls.startedAt, cutoff)).run().changes;\n const tools = tx.delete(sandboxToolCalls).where(lt(sandboxToolCalls.startedAt, cutoff)).run().changes;\n dropUnreferencedBlobs(tx);\n return models + tools;\n });\n },\n async close() {\n sqlite.close();\n },\n };\n}\n\nfunction modelValues(row: ModelCallRow): typeof sandboxModelCalls.$inferInsert {\n return { ...row, startedAt: row.startedAt.getTime() };\n}\n\nfunction toolValues(row: ToolCallRow): typeof sandboxToolCalls.$inferInsert {\n return { ...row, startedAt: row.startedAt.getTime() };\n}\n\nfunction toModelRow(row: typeof sandboxModelCalls.$inferSelect): ModelCallRow {\n return { ...row, startedAt: new Date(row.startedAt) };\n}\n\nfunction toToolRow(row: typeof sandboxToolCalls.$inferSelect): ToolCallRow {\n return { ...row, startedAt: new Date(row.startedAt) };\n}\n\nfunction toBlobRow(row: typeof sandboxBlobs.$inferSelect): BlobRow {\n return { hash: row.hash, data: new Uint8Array(row.data), bytes: row.bytes, truncated: row.truncated };\n}\n","import type { ModelCallEvent } from \"@ykurilov/agent-chat-core\";\nimport { blob, index, integer, real, sqliteTable, text } from \"drizzle-orm/sqlite-core\";\n\n/** Куски журнала: один раз на хеш, сжатый JSON. */\nexport const sandboxBlobs = sqliteTable(\"sandbox_blobs\", {\n hash: text(\"hash\").primaryKey(),\n data: blob(\"data\", { mode: \"buffer\" }).notNull(),\n bytes: integer(\"bytes\").notNull(),\n truncated: integer(\"truncated\", { mode: \"boolean\" }).notNull(),\n});\n\nexport const sandboxModelCalls = sqliteTable(\n \"sandbox_model_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\"),\n purpose: text(\"purpose\").$type<ModelCallEvent[\"purpose\"]>().notNull(),\n attempt: integer(\"attempt\").notNull(),\n modelId: text(\"model_id\").notNull(),\n providerId: text(\"provider_id\").notNull(),\n usage: text(\"usage\", { mode: \"json\" }).$type<ModelCallEvent[\"usage\"]>(),\n costUsd: real(\"cost_usd\"),\n startedAt: integer(\"started_at\").notNull(),\n firstChunkMs: integer(\"first_chunk_ms\"),\n durationMs: integer(\"duration_ms\").notNull(),\n status: text(\"status\").$type<ModelCallEvent[\"status\"]>().notNull(),\n error: text(\"error\"),\n instructionsHash: text(\"instructions_hash\").notNull(),\n messageHashes: text(\"message_hashes\", { mode: \"json\" }).$type<string[]>().notNull(),\n toolsHash: text(\"tools_hash\").notNull(),\n settingsHash: text(\"settings_hash\").notNull(),\n responseHash: text(\"response_hash\").notNull(),\n toolCallIds: text(\"tool_call_ids\", { mode: \"json\" }).$type<string[]>().notNull(),\n },\n (table) => [index(\"sandbox_model_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_model_calls_started_idx\").on(table.startedAt)],\n);\n\nexport const sandboxToolCalls = sqliteTable(\n \"sandbox_tool_calls\",\n {\n id: text(\"id\").primaryKey(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n messageId: text(\"message_id\").notNull(),\n toolCallId: text(\"tool_call_id\").notNull(),\n toolName: text(\"tool_name\").notNull(),\n inputHash: text(\"input_hash\").notNull(),\n outputHash: text(\"output_hash\"),\n error: text(\"error\"),\n startedAt: integer(\"started_at\").notNull(),\n durationMs: integer(\"duration_ms\").notNull(),\n },\n (table) => [index(\"sandbox_tool_calls_chat_idx\").on(table.chatId, table.startedAt), index(\"sandbox_tool_calls_started_idx\").on(table.startedAt)],\n);\n\n/** Кто на какой кусок ссылается: по этим строкам решается, чей кусок и какие куски уже никому не нужны. */\nexport const sandboxBlobRefs = sqliteTable(\n \"sandbox_blob_refs\",\n {\n callId: text(\"call_id\").notNull(),\n hash: text(\"hash\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n ownerId: text(\"owner_id\").notNull(),\n },\n (table) => [index(\"sandbox_blob_refs_call_idx\").on(table.callId), index(\"sandbox_blob_refs_hash_idx\").on(table.hash, table.ownerId), index(\"sandbox_blob_refs_chat_idx\").on(table.chatId)],\n);\n\nexport const sandboxSettings = sqliteTable(\"sandbox_settings\", {\n chatId: text(\"chat_id\").primaryKey(),\n instructions: text(\"instructions\"),\n updatedBy: text(\"updated_by\").notNull(),\n updatedAt: integer(\"updated_at\").notNull(),\n});\n\nexport const sandboxAnswerEdits = sqliteTable(\n \"sandbox_answer_edits\",\n {\n messageId: text(\"message_id\").primaryKey(),\n sourceMessageId: text(\"source_message_id\").notNull(),\n chatId: text(\"chat_id\").notNull(),\n textEdited: integer(\"text_edited\", { mode: \"boolean\" }).notNull(),\n editedToolCallIds: text(\"edited_tool_call_ids\", { mode: \"json\" }).$type<string[]>().notNull(),\n editedBy: text(\"edited_by\").notNull(),\n editedAt: integer(\"edited_at\").notNull(),\n },\n (table) => [index(\"sandbox_answer_edits_chat_idx\").on(table.chatId, table.editedAt)],\n);\n","// Создано scripts/embed-migrations.mjs из packages/sandbox/drizzle/sqlite; не править руками: `pnpm db:generate` пакета пересоздаёт файл.\nimport type { EmbeddedMigration } from \"@ykurilov/agent-chat-core\";\n\nexport const migrations: readonly EmbeddedMigration[] = [\n // 0000_journal_init\n { folderMillis: 1791041535561, hash: \"f32a0634b1a1856ba157e10ccb34f8b0b5799487d069e5536ed391d2daeae10c\", bps: true, sql: [\n \"CREATE TABLE `sandbox_answer_edits` (\\n\\t`message_id` text PRIMARY KEY NOT NULL,\\n\\t`source_message_id` text NOT NULL,\\n\\t`chat_id` text NOT NULL,\\n\\t`text_edited` integer NOT NULL,\\n\\t`edited_tool_call_ids` text NOT NULL,\\n\\t`edited_by` text NOT NULL,\\n\\t`edited_at` integer NOT NULL\\n);\\n\",\n \"\\nCREATE INDEX `sandbox_answer_edits_chat_idx` ON `sandbox_answer_edits` (`chat_id`,`edited_at`);\",\n \"\\nCREATE TABLE `sandbox_blob_refs` (\\n\\t`call_id` text NOT NULL,\\n\\t`hash` text NOT NULL,\\n\\t`chat_id` text NOT NULL,\\n\\t`owner_id` text NOT NULL\\n);\\n\",\n \"\\nCREATE INDEX `sandbox_blob_refs_call_idx` ON `sandbox_blob_refs` (`call_id`);\",\n \"\\nCREATE INDEX `sandbox_blob_refs_hash_idx` ON `sandbox_blob_refs` (`hash`,`owner_id`);\",\n \"\\nCREATE INDEX `sandbox_blob_refs_chat_idx` ON `sandbox_blob_refs` (`chat_id`);\",\n \"\\nCREATE TABLE `sandbox_blobs` (\\n\\t`hash` text PRIMARY KEY NOT NULL,\\n\\t`data` blob NOT NULL,\\n\\t`bytes` integer NOT NULL,\\n\\t`truncated` integer NOT NULL\\n);\\n\",\n \"\\nCREATE TABLE `sandbox_model_calls` (\\n\\t`id` text PRIMARY KEY NOT NULL,\\n\\t`chat_id` text NOT NULL,\\n\\t`owner_id` text NOT NULL,\\n\\t`message_id` text,\\n\\t`purpose` text NOT NULL,\\n\\t`attempt` integer NOT NULL,\\n\\t`model_id` text NOT NULL,\\n\\t`provider_id` text NOT NULL,\\n\\t`usage` text,\\n\\t`cost_usd` real,\\n\\t`started_at` integer NOT NULL,\\n\\t`first_chunk_ms` integer,\\n\\t`duration_ms` integer NOT NULL,\\n\\t`status` text NOT NULL,\\n\\t`error` text,\\n\\t`instructions_hash` text NOT NULL,\\n\\t`message_hashes` text NOT NULL,\\n\\t`tools_hash` text NOT NULL,\\n\\t`settings_hash` text NOT NULL,\\n\\t`response_hash` text NOT NULL,\\n\\t`tool_call_ids` text NOT NULL\\n);\\n\",\n \"\\nCREATE INDEX `sandbox_model_calls_chat_idx` ON `sandbox_model_calls` (`chat_id`,`started_at`);\",\n \"\\nCREATE INDEX `sandbox_model_calls_started_idx` ON `sandbox_model_calls` (`started_at`);\",\n \"\\nCREATE TABLE `sandbox_settings` (\\n\\t`chat_id` text PRIMARY KEY NOT NULL,\\n\\t`instructions` text,\\n\\t`updated_by` text NOT NULL,\\n\\t`updated_at` integer NOT NULL\\n);\\n\",\n \"\\nCREATE TABLE `sandbox_tool_calls` (\\n\\t`id` text PRIMARY KEY NOT NULL,\\n\\t`chat_id` text NOT NULL,\\n\\t`owner_id` text NOT NULL,\\n\\t`message_id` text NOT NULL,\\n\\t`tool_call_id` text NOT NULL,\\n\\t`tool_name` text NOT NULL,\\n\\t`input_hash` text NOT NULL,\\n\\t`output_hash` text,\\n\\t`error` text,\\n\\t`started_at` integer NOT NULL,\\n\\t`duration_ms` integer NOT NULL\\n);\\n\",\n \"\\nCREATE INDEX `sandbox_tool_calls_chat_idx` ON `sandbox_tool_calls` (`chat_id`,`started_at`);\",\n \"\\nCREATE INDEX `sandbox_tool_calls_started_idx` ON `sandbox_tool_calls` (`started_at`);\",\n ] },\n];\n"],"mappings":";;;;;AAAA,OAAO,cAAc;;;ACArB,SAAS,+BAAuD;AAEhE,SAAS,KAAK,KAAK,IAAI,SAAS,IAAI,YAAY,UAAe;AAC/D,SAAS,eAAe;;;ACFxB,SAAS,MAAM,OAAO,SAAS,MAAM,aAAa,YAAY;AAGvD,IAAM,eAAe,YAAY,iBAAiB;AAAA,EACvD,MAAM,KAAK,MAAM,EAAE,WAAW;AAAA,EAC9B,MAAM,KAAK,QAAQ,EAAE,MAAM,SAAS,CAAC,EAAE,QAAQ;AAAA,EAC/C,OAAO,QAAQ,OAAO,EAAE,QAAQ;AAAA,EAChC,WAAW,QAAQ,aAAa,EAAE,MAAM,UAAU,CAAC,EAAE,QAAQ;AAC/D,CAAC;AAEM,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,IACE,IAAI,KAAK,IAAI,EAAE,WAAW;AAAA,IAC1B,QAAQ,KAAK,SAAS,EAAE,QAAQ;AAAA,IAChC,SAAS,KAAK,UAAU,EAAE,QAAQ;AAAA,IAClC,WAAW,KAAK,YAAY;AAAA,IAC5B,SAAS,KAAK,SAAS,EAAE,MAAiC,EAAE,QAAQ;AAAA,IACpE,SAAS,QAAQ,SAAS,EAAE,QA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AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE;AACJ;;;AHLA,eAAsB,2BAA2B,SAA+D;AAC9G,QAAM,SAAS,IAAI,SAAS,QAAQ,QAAQ;AAC5C,MAAI;AACF,WAAO,OAAO,oBAAoB;AAElC,WAAO,OAAO,qBAAqB;AACnC,WAAO,qBAAqB,yBAAyB,QAAQ,UAAU,GAAG,OAAO;AAAA,EACnF,SAAS,OAAO;AACd,WAAO,MAAM;AACb,UAAM;AAAA,EACR;AACF;","names":["migrations","blob"]}
@@ -0,0 +1,2 @@
1
+ import type { EmbeddedMigration } from "@ykurilov/agent-chat-core";
2
+ export declare const migrations: readonly EmbeddedMigration[];
@@ -0,0 +1,2 @@
1
+ import type { EmbeddedMigration } from "@ykurilov/agent-chat-core";
2
+ export declare const migrations: readonly EmbeddedMigration[];
@@ -1,9 +1,10 @@
1
+ import { type EmbeddedMigration } from "@ykurilov/agent-chat-core";
1
2
  import type { Pool } from "pg";
2
3
  import type { JournalStore } from "./journal-store.js";
3
4
  /**
4
5
  * Приводит таблицы журнала к последней миграции. Схема `agent_chat` создаётся под общей блокировкой всех пакетов, миграции — под своей:
5
6
  * копии пакета ждут друг друга, а разные пакеты стартуют разом на пустой базе без гонки за схему.
6
7
  */
7
- export declare function migrateJournalToLatest(pool: Pool, migrationsFolder: string): Promise<void>;
8
+ export declare function migrateJournalToLatest(pool: Pool, migrations: readonly EmbeddedMigration[]): Promise<void>;
8
9
  /** Хранилище журнала в PostgreSQL (схема `agent_chat`). Закрытие закрывает и пул. */
9
10
  export declare function createPostgresJournalStore(pool: Pool): JournalStore;
@@ -1,4 +1,5 @@
1
+ import { type EmbeddedMigration } from "@ykurilov/agent-chat-core";
1
2
  import type Database from "better-sqlite3";
2
3
  import type { JournalStore } from "./journal-store.js";
3
4
  /** Хранилище журнала в SQLite. Схема приводится к последней миграции при создании. */
4
- export declare function createSqliteJournalStore(sqlite: Database.Database, migrationsFolder: string): JournalStore;
5
+ export declare function createSqliteJournalStore(sqlite: Database.Database, migrations: readonly EmbeddedMigration[]): JournalStore;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ykurilov/agent-chat-sandbox",
3
- "version": "0.107.0",
3
+ "version": "0.107.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -46,14 +46,14 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "drizzle-orm": "^0.45.3",
49
- "@ykurilov/agent-chat-core": "0.107.0",
50
- "@ykurilov/agent-chat-server": "0.107.0"
49
+ "@ykurilov/agent-chat-core": "0.107.2",
50
+ "@ykurilov/agent-chat-server": "0.107.2"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "better-sqlite3": "^13.0.3",
54
54
  "pg": "^8.23.0",
55
55
  "react": "~19.0.1 || ~19.1.2 || ^19.2.1",
56
- "@ykurilov/agent-chat-react": "^0.107.0"
56
+ "@ykurilov/agent-chat-react": "^0.107.2"
57
57
  },
58
58
  "peerDependenciesMeta": {
59
59
  "better-sqlite3": {
@@ -85,14 +85,14 @@
85
85
  "pg": "^8.23.0",
86
86
  "react": "^19.3.0",
87
87
  "react-dom": "^19.3.0",
88
- "@ykurilov/agent-chat-images": "0.107.0",
89
- "@ykurilov/agent-chat-memory": "0.107.0",
90
- "@ykurilov/agent-chat-attachments": "0.107.0",
91
- "@ykurilov/agent-chat-react": "0.107.0"
88
+ "@ykurilov/agent-chat-memory": "0.107.2",
89
+ "@ykurilov/agent-chat-attachments": "0.107.2",
90
+ "@ykurilov/agent-chat-images": "0.107.2",
91
+ "@ykurilov/agent-chat-react": "0.107.2"
92
92
  },
93
93
  "scripts": {
94
94
  "build": "node ../../scripts/build-package.mjs",
95
95
  "typecheck": "tsc -p tsconfig.json",
96
- "db:generate": "drizzle-kit generate --config drizzle.config.sqlite.ts && drizzle-kit generate --config drizzle.config.postgres.ts"
96
+ "db:generate": "drizzle-kit generate --config drizzle.config.sqlite.ts && drizzle-kit generate --config drizzle.config.postgres.ts && node ../../scripts/embed-migrations.mjs"
97
97
  }
98
98
  }