@prismshadow/penguin-server 0.2.17 → 0.2.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/types.d.ts +181 -17
- package/dist/api/types.js +9 -1
- package/dist/auth-token.js +1 -1
- package/dist/{chunk-HPOHMZCH.js → chunk-5YLLSHY3.js} +61 -2
- package/dist/chunk-5YLLSHY3.js.map +1 -0
- package/dist/{chunk-D3JNA6ZI.js → chunk-B3PSKR3D.js} +2 -2
- package/dist/chunk-B3PSKR3D.js.map +1 -0
- package/dist/{chunk-HDBZRVA5.js → chunk-BRMNPLU6.js} +9 -1
- package/dist/chunk-BRMNPLU6.js.map +1 -0
- package/dist/index.js +8331 -6769
- package/dist/index.js.map +1 -1
- package/dist/machine-status.js +1 -1
- package/dist/plugin/index.d.ts +57 -16
- package/dist/reset-admin-password.js +2 -2
- package/package.json +4 -4
- package/web-dist/assets/{abnfDiagram-VCTEODGH-DMzkb4l4.js → abnfDiagram-VCTEODGH-C_Ej4MyZ.js} +1 -1
- package/web-dist/assets/{addon-clipboard-BtD2BVSi.js → addon-clipboard-eONBCa8x.js} +1 -1
- package/web-dist/assets/{addon-fit-Dr6HWsi_.js → addon-fit-Dk6bkT8u.js} +1 -1
- package/web-dist/assets/{addon-web-links-VEE3YLzQ.js → addon-web-links-e0JpGvGv.js} +1 -1
- package/web-dist/assets/{arc-CvMPOU_B.js → arc-ytwqobEL.js} +1 -1
- package/web-dist/assets/{architectureDiagram-5GKGNRK7-Bk65mIBz.js → architectureDiagram-5GKGNRK7-oxT9SNOE.js} +1 -1
- package/web-dist/assets/{blockDiagram-I7D4REHJ-D54-XSNs.js → blockDiagram-I7D4REHJ-D8OXfpb9.js} +1 -1
- package/web-dist/assets/{c4Diagram-7LVT6UL2-Dm954LSt.js → c4Diagram-7LVT6UL2-BNYNzSWK.js} +1 -1
- package/web-dist/assets/channel-7Be_pU-b.js +1 -0
- package/web-dist/assets/{chunk-2Q5K7J3B-D_LJ_7Cn.js → chunk-2Q5K7J3B-C2yNhFmh.js} +1 -1
- package/web-dist/assets/{chunk-5VM5RSS4-B8RI4tl3.js → chunk-5VM5RSS4-CAeuhwbB.js} +1 -1
- package/web-dist/assets/{chunk-F27PBJKO-aVSYH9JV.js → chunk-F27PBJKO-DSuRiLxP.js} +1 -1
- package/web-dist/assets/{chunk-IMKFNOWR-DnkdWeq2.js → chunk-IMKFNOWR-MStar4cf.js} +1 -1
- package/web-dist/assets/{chunk-JWPE2WC7-C2pJzKuW.js → chunk-JWPE2WC7-CIgQwRv4.js} +1 -1
- package/web-dist/assets/{chunk-POPQ4Y6H-Bx7Iikzx.js → chunk-POPQ4Y6H-CA8evx9g.js} +1 -1
- package/web-dist/assets/{chunk-SVP7TREG-qJC2SMqr.js → chunk-SVP7TREG-bR7-FT1W.js} +1 -1
- package/web-dist/assets/{chunk-TICWLB2K-Crl_BgKI.js → chunk-TICWLB2K-C0ZdCnvI.js} +1 -1
- package/web-dist/assets/{chunk-XXDRQBXY-BFFemuGm.js → chunk-XXDRQBXY-CzozFLFI.js} +1 -1
- package/web-dist/assets/classDiagram-ZZMXUADV-BjVhvDIH.js +1 -0
- package/web-dist/assets/classDiagram-v2-VYDZK3BY-BjVhvDIH.js +1 -0
- package/web-dist/assets/{cose-bilkent-JH36ORCC-Bmh2Kx7h.js → cose-bilkent-JH36ORCC-nkjrY6eI.js} +1 -1
- package/web-dist/assets/{cynefin-OW5HDTMX-BveNWnUV.js → cynefin-OW5HDTMX-D2A0h062.js} +1 -1
- package/web-dist/assets/{cynefinDiagram-5FMLGOSQ-85itazbJ.js → cynefinDiagram-5FMLGOSQ-DFZQ7d_T.js} +1 -1
- package/web-dist/assets/{dagre-GXQ25YYZ-DIZT-KY_.js → dagre-GXQ25YYZ-DPYLLARd.js} +1 -1
- package/web-dist/assets/{diagram-S7CK7UJ4-Dum-g63f.js → diagram-S7CK7UJ4-B204Nrur.js} +1 -1
- package/web-dist/assets/{diagram-UQ7AKVKN-DallMKJl.js → diagram-UQ7AKVKN-DWORCZlS.js} +1 -1
- package/web-dist/assets/{diagram-VSXAHHWV-DWELqxfN.js → diagram-VSXAHHWV-Su6Bzm4Z.js} +1 -1
- package/web-dist/assets/{diagram-VX7I27RA-BNs0gB9E.js → diagram-VX7I27RA-B4p8ssYj.js} +1 -1
- package/web-dist/assets/{diagram-Z3DM3KII-C9mF9xAd.js → diagram-Z3DM3KII-BgMz7jjW.js} +1 -1
- package/web-dist/assets/{ebnfDiagram-PWID7BFC-D_Diy9HH.js → ebnfDiagram-PWID7BFC-DBCS3Cwc.js} +1 -1
- package/web-dist/assets/{erDiagram-RLTQ6QDP-4QTS5VIh.js → erDiagram-RLTQ6QDP-DEm39S5C.js} +1 -1
- package/web-dist/assets/{flowDiagram-HODETNUW-CliTRrtV.js → flowDiagram-HODETNUW-CEUQGUza.js} +1 -1
- package/web-dist/assets/{ganttDiagram-EL5Y4UJY-DCRd-Ss4.js → ganttDiagram-EL5Y4UJY-myYTgwFp.js} +1 -1
- package/web-dist/assets/{gitGraphDiagram-WWUBYQGX-CTz13GjS.js → gitGraphDiagram-WWUBYQGX-BAQ0Kl1C.js} +1 -1
- package/web-dist/assets/{highlighter-BScH1Ud3.js → highlighter-DRTMVWxI.js} +2 -2
- package/web-dist/assets/{highlighter-core-DKz8Z6-I.js → highlighter-core-DgISzHrX.js} +1 -1
- package/web-dist/assets/index-PA-IFoA6.js +1300 -0
- package/web-dist/assets/index-oCEyg9BT.css +1 -0
- package/web-dist/assets/{infoDiagram-27XIBGKW-DNfTEPAV.js → infoDiagram-27XIBGKW-B2WDMvX9.js} +1 -1
- package/web-dist/assets/{ishikawaDiagram-5VMMS53U-B7aCjjG1.js → ishikawaDiagram-5VMMS53U-8qHTttjq.js} +1 -1
- package/web-dist/assets/{journeyDiagram-3NMN7TZE-COmDALVr.js → journeyDiagram-3NMN7TZE-DKE_xRCO.js} +1 -1
- package/web-dist/assets/{kanban-definition-UXKFOSKX-BzUfPINh.js → kanban-definition-UXKFOSKX-EnJbHEmV.js} +1 -1
- package/web-dist/assets/{layout-BwzuPU4M.js → layout-BlhCFmEZ.js} +1 -1
- package/web-dist/assets/{linear-WPZTYjz3.js → linear-Dw2VzU-D.js} +1 -1
- package/web-dist/assets/{mermaid.core-zKzlwpkw.js → mermaid.core-CaXNMz57.js} +6 -6
- package/web-dist/assets/{mindmap-definition-YA3MSWOX-DCRg7eAx.js → mindmap-definition-YA3MSWOX-DnTTfqbu.js} +1 -1
- package/web-dist/assets/{pegDiagram-XKGWAZYB-DyphzDLU.js → pegDiagram-XKGWAZYB-C3SArVd6.js} +1 -1
- package/web-dist/assets/{pieDiagram-E7YTZNPT-BI5DueGA.js → pieDiagram-E7YTZNPT-CTOmO6ke.js} +1 -1
- package/web-dist/assets/{quadrantDiagram-AXDQQJYC-GZxSMY2Z.js → quadrantDiagram-AXDQQJYC-CbUsMwzO.js} +1 -1
- package/web-dist/assets/{railroadDiagram-O6MQD6OU-DEFCigBf.js → railroadDiagram-O6MQD6OU-Co2hsvaZ.js} +1 -1
- package/web-dist/assets/{requirementDiagram-BXWQKSXE-Br0thc4j.js → requirementDiagram-BXWQKSXE-BqFG0eYQ.js} +1 -1
- package/web-dist/assets/{sankeyDiagram-P5KCCOFB-DYf0pY67.js → sankeyDiagram-P5KCCOFB-YgQHJlB7.js} +1 -1
- package/web-dist/assets/{sequenceDiagram-WJ2MYXX4-1EFMboX4.js → sequenceDiagram-WJ2MYXX4-CdDrP6O2.js} +1 -1
- package/web-dist/assets/{sizeCapture-INFHLROL-BuOFv-5q.js → sizeCapture-INFHLROL-CKwbEVhU.js} +1 -1
- package/web-dist/assets/{stateDiagram-D77RDMKH-Bg3H1tjX.js → stateDiagram-D77RDMKH-kTJR3t2p.js} +1 -1
- package/web-dist/assets/stateDiagram-v2-MP3YSRHH-DzaSnZwj.js +1 -0
- package/web-dist/assets/{swimlanes-42K2YHIH-BuOa6Osb.js → swimlanes-42K2YHIH-DCAO3rCQ.js} +1 -1
- package/web-dist/assets/swimlanesDiagram-VR7AAH4N-DNfCLejq.js +8 -0
- package/web-dist/assets/{timeline-definition-24CTP7MA-BDekfdDT.js → timeline-definition-24CTP7MA-DEjnyzKw.js} +1 -1
- package/web-dist/assets/{vennDiagram-4TSXK5OY-DnC09UI4.js → vennDiagram-4TSXK5OY-DSihUvCq.js} +1 -1
- package/web-dist/assets/{wardleyDiagram-VM6X3IG4-BXKvxuZQ.js → wardleyDiagram-VM6X3IG4-CnAoMeCH.js} +1 -1
- package/web-dist/assets/{xterm-oY4DYg5s.js → xterm-3JwPT74G.js} +1 -1
- package/web-dist/assets/{xychartDiagram-S5SC5T6Z-DdDC1VLb.js → xychartDiagram-S5SC5T6Z-43dHqZTr.js} +1 -1
- package/web-dist/index.html +2 -2
- package/web-dist/workbench-ui.css +164 -34
- package/dist/chunk-D3JNA6ZI.js.map +0 -1
- package/dist/chunk-HDBZRVA5.js.map +0 -1
- package/dist/chunk-HPOHMZCH.js.map +0 -1
- package/web-dist/assets/channel-CVHI75kz.js +0 -1
- package/web-dist/assets/classDiagram-ZZMXUADV-CBdzAPFu.js +0 -1
- package/web-dist/assets/classDiagram-v2-VYDZK3BY-CBdzAPFu.js +0 -1
- package/web-dist/assets/index-BUvJ5Ctt.js +0 -1299
- package/web-dist/assets/index-DRj7nvPY.css +0 -1
- package/web-dist/assets/stateDiagram-v2-MP3YSRHH-DfaDaPAd.js +0 -1
- package/web-dist/assets/swimlanesDiagram-VR7AAH4N-BopAC7b8.js +0 -8
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/db/database.ts","../src/db/migrations/runner.ts","../src/db/migrations/steps/2026-08-31-messaging-bindings.ts","../src/db/migrations/steps/2026-08-31-messaging-delivery-flags.ts","../src/db/migrations/steps/2026-09-02-drop-goal-state.ts","../src/db/migrations/steps/2026-09-04-machines.ts","../src/db/migrations/steps/2026-09-14-user-profile.ts","../src/db/migrations/steps/2026-09-16-company-mode-channels.ts","../src/db/migrations/steps/2026-09-16-company-mode-desk-notices.ts","../src/db/migrations/steps/2026-09-16-company-mode-org-caches.ts","../src/db/migrations/steps/2026-09-17-model-promotions.ts","../src/db/migrations/steps/2026-09-21-model-provider-auth-tokens.ts","../src/db/migrations/steps/2026-09-22-sessions-sandbox.ts","../src/db/migrations/steps/2026-09-23-machines-columns.ts","../src/db/migrations/steps/2026-09-23-model-tables-adoption.ts","../src/db/migrations/steps/2026-10-04-browser-extensions.ts","../src/db/migrations/steps/2026-10-10-agent-api.ts","../src/db/migrations/steps/2026-10-12-messaging-conversations.ts","../src/db/migrations/steps/2026-10-12-sessions-kept-at.ts","../src/db/migrations/steps/2026-10-14-agent-api-concurrency.ts","../src/db/migrations/steps/2026-10-14-agent-api-session-settings.ts","../src/db/migrations/steps/2026-10-16-machines-adopted-at.ts","../src/db/migrations/index.ts","../src/db/schema.ts"],"sourcesContent":["/**\n * SQLite connection & initialization (node:sqlite DatabaseSync).\n *\n * Single process, single writer: a synchronous API is sufficient and avoids a connection\n * pool; WAL mode and foreign key constraints are enabled. Table-creation SQL runs on open\n * (idempotent), with no migration branches (product not yet released).\n */\nimport { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { migrate } from \"./migrations/index.js\";\nimport { SCHEMA_SQL } from \"./schema.js\";\n\n// Fetch the runtime module via process.getBuiltinModule (node >=22.3): avoids static\n// resolution of `node:sqlite` by bundlers/vite (some tools' builtin lists don't yet\n// recognize this experimental module).\nconst sqlite = process.getBuiltinModule(\"node:sqlite\");\n\n/**\n * Opens an EXISTING database for a narrow write, without running any schema work.\n *\n * `openDatabase` migrates — CREATE TABLE, several ensureColumn calls, a DROP INDEX and a backfill.\n * That is right for the process that owns the database and wrong for a short-lived CLI writing\n * one row (`penguin auth token`): after `penguin update` the CLI on disk can be NEWER than the\n * running server, and migrating under a live server's prepared statements is not something a\n * token mint should do. The caller has already established that the file exists.\n */\nexport function openExistingDatabase(dbPath: string): DatabaseSync {\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA foreign_keys = ON;\");\n // Wait for the live server's write lock instead of failing SQLITE_BUSY at once.\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n return db;\n}\n\n/**\n * Opens an EXISTING database for reading only — SQLite refuses every write on the connection,\n * so a reader cannot change the file even by mistake. For a question asked of a database some\n * other process owns (`penguin server status`, run over ssh by a controller): the answer must\n * not reshape that server's schema, and must not be able to. The caller has established that\n * the file exists; a read-only open of a missing file is an error, not a creation.\n */\nexport function openDatabaseReadOnly(dbPath: string): DatabaseSync {\n const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n return db;\n}\n\n/** Open (creating if necessary) the database: ensure the parent directory exists, set PRAGMAs, run table creation. */\nexport function openDatabase(dbPath: string): DatabaseSync {\n if (dbPath !== \":memory:\") {\n mkdirSync(path.dirname(dbPath), { recursive: true });\n }\n const db = new sqlite.DatabaseSync(dbPath);\n db.exec(\"PRAGMA journal_mode = WAL;\");\n // A second connection (the CLI minting a token while the server runs) waits for the write\n // lock rather than failing SQLITE_BUSY at once.\n db.exec(\"PRAGMA busy_timeout = 5000;\");\n db.exec(\"PRAGMA foreign_keys = ON;\");\n db.exec(SCHEMA_SQL);\n // Columns added to the schema after a web.db was formed: CREATE TABLE IF NOT EXISTS never\n // touches an existing table, so they are ALTERed in here. Keep the list in sync with\n // schema.ts; drop entries only in a release allowed to break existing web.db files.\n ensureColumn(db, \"sessions\", \"client\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"has_trace\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"fork_count\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"sessions\", \"thinking_level\", \"TEXT\");\n ensureColumn(db, \"sessions\", \"sandbox\", \"TEXT\");\n // A v0.2.0 web.db has auth_sessions without `via`; CREATE TABLE IF NOT EXISTS never adds a\n // column, so every INSERT would fail \"no column named via\" until this runs.\n ensureColumn(db, \"auth_sessions\", \"via\", \"TEXT\");\n ensureColumn(db, \"trace_files\", \"page_stats\", \"TEXT\");\n ensureColumn(db, \"messaging_bindings\", \"line_per_message\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"messaging_bindings\", \"final_reply_only\", \"INTEGER NOT NULL DEFAULT 0\");\n // DEFAULT 1, unlike every other added flag here: this one's default is the CORRECTED\n // behaviour, not the previous one. Sending the model's Markdown as characters was the\n // defect, so an existing binding starts rendering it — a visible change to every relayed\n // message, recorded in the release's backward-compatibility entry.\n ensureColumn(db, \"messaging_bindings\", \"render_markdown\", \"INTEGER NOT NULL DEFAULT 1\");\n ensureColumn(db, \"messaging_bindings\", \"last_inbound_message_id\", \"TEXT\");\n // Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on\n // this database: the old index is a strict prefix of it, so every query it served is\n // served identically. Dropping is safe — an index is derived, never data.\n db.exec(\"DROP INDEX IF EXISTS idx_usage_session\");\n // The uniqueness index of the old binding model, where a bot account belonged to one\n // Session forever and a second Session could not even SAVE its credentials. Enabling a\n // connection is the binding now, so exclusivity is checked per enable (the state route's\n // 409 account_enabled_elsewhere) and the same account may sit saved on many Sessions —\n // which this index would reject. SCHEMA_SQL has just created idx_messaging_by_account\n // over the same columns, so the by-account lookup stays indexed. Dropping is safe: an\n // index is derived, never data. It is however ONE-WAY — an older build recreates the\n // unique index on open, which fails outright once duplicate (channel, account_id) rows\n // exist, so a downgrade after two Sessions saved the same bot needs those rows removed.\n db.exec(\"DROP INDEX IF EXISTS idx_messaging_account\");\n upgradeLastActiveAt(db);\n // The runtime's own open is the ONLY place a contract migration is applied: it owns the\n // process, so there is no boot to roll back out from under it.\n migrate(db);\n return db;\n}\n\n/**\n * One-time `sessions.last_active_at` upgrade, ALTER + backfill in a single transaction.\n *\n * The backfill runs **only in the open that actually adds the column** (SQLite's ALTER\n * TABLE ADD COLUMN is transactional, so a crash mid-upgrade rolls back to \"no column\" and\n * the next open redoes both halves — never a half-migrated table, and never a full\n * `sessions` scan on the millions of opens that follow). Legacy rows take the session's\n * most recent request timestamp — usage_records, covered by idx_usage_session_ts, the\n * closest persisted proxy for \"last Trace activity\" — else their own created_at.\n */\nfunction upgradeLastActiveAt(db: DatabaseSync): void {\n db.exec(\"BEGIN\");\n try {\n if (ensureColumn(db, \"sessions\", \"last_active_at\", \"TEXT\")) {\n db.exec(\n `UPDATE sessions SET last_active_at = COALESCE(\n (SELECT MAX(ts) FROM usage_records WHERE usage_records.session_id = sessions.session_id),\n created_at\n )`,\n );\n }\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n}\n\n/**\n * Idempotent per-column upgrade for databases formed before the column existed.\n * Returns whether this call actually ALTERed the table (false = the column was already\n * there), so a caller can gate one-time backfill work on it.\n */\nexport function ensureColumn(\n db: DatabaseSync,\n table: string,\n column: string,\n ddl: string,\n): boolean {\n const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n if (cols.some((c) => c.name === column)) return false;\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);\n return true;\n}\n","/**\n * Applies and reverts named migrations against the `schema_migrations` ledger.\n *\n * The ledger records which migrations ran, by NAME, one row each, in the order they ran (a\n * rowid table hands every insert max(rowid) + 1, so rowid order is application order). The\n * migration list is passed in, so this file knows nothing about any particular migration.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type { Migration } from \"./migration.js\";\n\n/**\n * The ledger's DDL. An on-disk contract shared by every build that has the ledger: an older\n * one reads the names a newer one wrote. Never changed, only ever created.\n */\nconst LEDGER_DDL = `\n CREATE TABLE IF NOT EXISTS schema_migrations (\n name TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL\n );\n`;\n\nexport class IrreversibleMigrationError extends Error {\n constructor(readonly migration: string) {\n super(\n `migration ${migration} declares no down and cannot be rolled back. ` +\n `Restore the database from a backup taken before it was applied.`,\n );\n this.name = \"IrreversibleMigrationError\";\n }\n}\n\nexport class UnknownMigrationError extends Error {\n constructor(readonly migration: string) {\n super(\n `migration ${migration} was applied by a build that knows it, and this build does not: ` +\n `it cannot roll it back. Roll back with that build.`,\n );\n this.name = \"UnknownMigrationError\";\n }\n}\n\nfunction hasLedger(db: DatabaseSync): boolean {\n return (\n db\n .prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'\")\n .get() !== undefined\n );\n}\n\n/** The names this database's ledger records, in the order they were applied. Empty without a ledger. */\nexport function appliedMigrations(db: DatabaseSync): string[] {\n if (!hasLedger(db)) return [];\n const rows = db.prepare(\"SELECT name FROM schema_migrations ORDER BY rowid\").all() as {\n name: string;\n }[];\n return rows.map((r) => r.name);\n}\n\nexport interface MigrateResult {\n /**\n * True when this run found no ledger and created it: a database from before the ledger\n * (stamped with a `user_version` whose meaning depended on the line that wrote it), or a\n * new one. Every migration then ran, as the re-runnable no-op it is where its work was done.\n */\n adopted: boolean;\n /** Names applied by this run, in order. */\n applied: readonly string[];\n /**\n * Contract migrations this swap-path run left pending, in order: the runtime's next open on\n * a build that declares them applies them. Always empty off the swap path.\n */\n deferred: readonly string[];\n}\n\n/**\n * Applies every migration in `migrations` whose name the ledger does not record, in\n * declaration order. Names in the ledger that `migrations` does not declare — written by a\n * newer build or another line — are left alone.\n *\n * Each migration and its ledger row commit together, so an interrupted run leaves the database\n * with exactly the migrations that fully applied. An already-current database does no work\n * and writes nothing. `PRAGMA user_version` is neither read nor written.\n *\n * `swapPath` marks the caller as a booting pushed platform. Expand migrations apply as\n * anywhere else; contract migrations (`swapSafe: false`) are skipped and stay pending — never\n * applied, never a reason to refuse the boot — and are returned in `deferred`. A hot push\n * therefore never fails on a migration it is not allowed to run, and never runs a contract.\n * (One expand removes something all the same: see steps/2026-09-16-company-mode-channels.ts.)\n */\nexport function migrate(\n db: DatabaseSync,\n migrations: readonly Migration[],\n { swapPath = false }: { swapPath?: boolean } = {},\n): MigrateResult {\n const adopted = !hasLedger(db);\n const done = new Set(appliedMigrations(db));\n const pending = migrations.filter((m) => !done.has(m.name));\n if (adopted) db.exec(LEDGER_DDL);\n const record = db.prepare(\"INSERT INTO schema_migrations (name, applied_at) VALUES (?, ?)\");\n const applied: string[] = [];\n const deferred: string[] = [];\n for (const m of pending) {\n if (swapPath && !m.swapSafe) {\n deferred.push(m.name);\n continue;\n }\n db.exec(\"BEGIN\");\n try {\n m.up(db);\n record.run(m.name, new Date().toISOString());\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`migration ${m.name} failed: ${String(err)}`, { cause: err });\n }\n applied.push(m.name);\n }\n return { adopted, applied, deferred };\n}\n\n/**\n * Reverts every migration applied AFTER `target`, newest-applied first; `null` reverts them\n * all. Order is the ledger's, not the declaration's: a migration another line's build applied\n * late is undone early.\n *\n * An operator's tool, and a destructive one — see each migration's `down` for what its rows\n * were. Deliberately not reachable from the swap path: a failed platform boot reverts the\n * PLATFORM, never the schema.\n *\n * Refused whole, before anything runs, when any migration in range declares no `down` or is\n * not one this build declares. Each `down` commits with the removal of its ledger row, so an\n * interrupted run stops between two whole steps.\n */\nexport function rollbackTo(\n db: DatabaseSync,\n migrations: readonly Migration[],\n target: string | null,\n): { reverted: readonly string[] } {\n const applied = appliedMigrations(db);\n const from = target === null ? 0 : applied.indexOf(target) + 1;\n if (target !== null && from === 0) {\n throw new Error(`migration ${target} is not applied to this database`);\n }\n const byName = new Map(migrations.map((m) => [m.name, m]));\n const toRevert = applied.slice(from).reverse();\n for (const name of toRevert) {\n const m = byName.get(name);\n if (m === undefined) throw new UnknownMigrationError(name);\n if (m.down === null) throw new IrreversibleMigrationError(name);\n }\n const forget = db.prepare(\"DELETE FROM schema_migrations WHERE name = ?\");\n const reverted: string[] = [];\n for (const name of toRevert) {\n db.exec(\"BEGIN\");\n try {\n byName.get(name)!.down!(db);\n forget.run(name);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`rollback of migration ${name} failed: ${String(err)}`, { cause: err });\n }\n reverted.push(name);\n }\n return { reverted };\n}\n","import type { Migration } from \"../migration.js\";\n\nexport const messagingBindings: Migration = {\n name: \"2026-08-31-messaging-bindings\",\n // Purely additive: one new table plus three indexes, no column of any existing table\n // touched. A platform that rolls back to a predecessor without messaging simply never\n // queries them.\n swapSafe: true,\n up(db) {\n // 0.2.4 → 0.2.7. Frozen copy of the DDL as of 0.2.7; do not re-derive from schema.ts.\n // IF NOT EXISTS because a database from before migrations may already be at 0.2.7, and\n // because every migration is re-runnable (see index.ts).\n db.exec(`\n CREATE TABLE IF NOT EXISTS messaging_bindings (\n session_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n config_json TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0,\n line_per_message INTEGER NOT NULL DEFAULT 0,\n last_chat_id TEXT,\n last_chat_is_direct INTEGER NOT NULL DEFAULT 1,\n last_inbound_message_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session_id, channel)\n );\n CREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id);\n CREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);\n CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);\n `);\n },\n // LOSES every messaging binding: the channel credentials, the enabled flag and the\n // last-chat memory all live in the table this drops. The auth_sessions indexes are\n // derived and cost nothing to lose.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_auth_sessions_user;\n DROP INDEX IF EXISTS idx_auth_sessions_expires;\n DROP INDEX IF EXISTS idx_messaging_by_account;\n DROP TABLE IF EXISTS messaging_bindings;\n `);\n },\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const messagingDeliveryFlags: Migration = {\n name: \"2026-08-31-messaging-delivery-flags\",\n // Two columns with defaults on an existing table: a rollback to a predecessor that\n // does not know them leaves them at their defaults and reads nothing.\n swapSafe: true,\n up(db) {\n // 0.2.7 → 0.2.8. ensureColumn rather than a bare ALTER because the declarative\n // track may already have added these (see RE-RUNNABLE in index.ts).\n ensureColumn(db, \"messaging_bindings\", \"final_reply_only\", \"INTEGER NOT NULL DEFAULT 0\");\n ensureColumn(db, \"messaging_bindings\", \"render_markdown\", \"INTEGER NOT NULL DEFAULT 1\");\n },\n // LOSES both delivery preferences on every binding; the bindings themselves survive.\n // Dropped in reverse order for symmetry with `up`. Neither column is indexed, which is\n // what lets SQLite drop them at all.\n down(db) {\n db.exec(\"ALTER TABLE messaging_bindings DROP COLUMN render_markdown\");\n db.exec(\"ALTER TABLE messaging_bindings DROP COLUMN final_reply_only\");\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const dropGoalState: Migration = {\n name: \"2026-09-02-drop-goal-state\",\n // CONTRACT: drops a table no build since 0.2.10 reads. A pushed platform rolled back to\n // 0.2.9 mid-process would prepare its goal statements against a table that is gone, so it\n // is left pending on the swap path and applied by the runtime's own open; until then the\n // table just sits there unused.\n swapSafe: false,\n up(db) {\n // 0.2.9 → 0.2.10. goal_state held goal mode's run state, one row per goal run, read\n // back only for the chat page's goal banner; the goal plugin's GOAL.json in the\n // Session scratchpad is that record now (see runtime/goal-events.ts). IF EXISTS only\n // because a database this build created never had the table.\n db.exec(`\n DROP INDEX IF EXISTS idx_goal_session;\n DROP TABLE IF EXISTS goal_state;\n `);\n },\n // Recreates the table exactly as 0.2.9 declared it — EMPTY. LOSES every goal run ever\n // recorded (objective, status, budget, used, rounds per run): the rows only ever fed the\n // banner of a finished goal, and a build with this migration reads the goal file instead.\n down(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS goal_state (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n objective TEXT NOT NULL,\n status TEXT NOT NULL,\n budget INTEGER NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n rounds INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);\n `);\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const machines: Migration = {\n name: \"2026-09-04-machines\",\n // Three new tables, nothing existing touched: a platform rolled back to one without\n // machines never queries them. Swap-safe on its own; a database still behind\n // 2026-09-02-drop-goal-state is refused whole by that one first, which is the rule.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the machines feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created them (RE-RUNNABLE in index.ts).\n db.exec(`\n CREATE TABLE IF NOT EXISTS machine (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n machine_id TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS machines (\n address TEXT PRIMARY KEY,\n machine_id TEXT,\n version TEXT,\n installed_at TEXT,\n session_pid INTEGER,\n remote_port INTEGER,\n platform TEXT\n );\n CREATE TABLE IF NOT EXISTS machine_project (\n project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,\n addresses TEXT NOT NULL\n );\n `);\n },\n // LOSES this server's own machine id (every stored reference to it on other machines\n // then points at nothing), what was installed where, the sessions held, and which\n // machines each Project used.\n down(db) {\n db.exec(`\n DROP TABLE IF EXISTS machine_project;\n DROP TABLE IF EXISTS machines;\n DROP TABLE IF EXISTS machine;\n `);\n },\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const userProfile: Migration = {\n name: \"2026-09-14-user-profile\",\n // Two nullable columns on `users`, no default and nothing existing rewritten: a platform\n // rolled back to a predecessor that does not know them never selects or writes them, and\n // every existing account simply reads NULL — no profile yet.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the user-profile feature; do not re-derive from schema.ts.\n // SQLite has no ADD COLUMN IF NOT EXISTS, and the declarative track may already have\n // added both (RE-RUNNABLE in index.ts), so each one goes through the same table_info guard the\n // declarative track uses.\n ensureColumn(db, \"users\", \"display_name\", \"TEXT\");\n ensureColumn(db, \"users\", \"avatar\", \"TEXT\");\n },\n // LOSES every stored nickname and avatar: both live entirely in the two columns this\n // drops, and nothing else on disk holds a copy. Dropped in reverse order for symmetry\n // with `up`; neither column is indexed, which is what lets SQLite drop them at all.\n down(db) {\n const cols = db.prepare(\"PRAGMA table_info(users)\").all() as { name: string }[];\n const has = (name: string): boolean => cols.some((c) => c.name === name);\n if (has(\"avatar\")) db.exec(\"ALTER TABLE users DROP COLUMN avatar\");\n if (has(\"display_name\")) db.exec(\"ALTER TABLE users DROP COLUMN display_name\");\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const companyModeChannels: Migration = {\n name: \"2026-09-16-company-mode-channels\",\n // The organization's single group chat became channels: a message lives in\n // `channels/<channel_id>/<date>.jsonl`, so the tail-scan cursor and each user's read\n // cursor are per channel. `org_chat_state` / `org_chat_reads` are dropped for\n // `org_channel_state` / `org_channel_reads`: the tables are renamed and the channel\n // belongs in the primary key, neither of which SQLite does in place. Nothing is carried\n // over: company mode is unreleased, and every row was either rebuildable from the files\n // (the scan cursor) or one pass of \"everything looks unread\" (the read cursor). A\n // predecessor build reads neither table's shape, only its own writes, so this is\n // swap-safe.\n //\n // By the expand / contract rule (migration.ts) the two DROPs are a contract, and this is the\n // one expand that removes anything on the swap path. It stays an expand because it is frozen\n // and cannot be deferred: the same step creates the channel tables a pushed platform needs.\n // A new change of this kind is split into an expand and a later contract instead.\n swapSafe: true,\n up(db) {\n db.exec(`\n DROP TABLE IF EXISTS org_chat_state;\n DROP TABLE IF EXISTS org_chat_reads;\n CREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, channel_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, channel_id, user_id)\n );\n `);\n },\n // Recreates the two tables under their old names, exactly as 2026-09-16-company-mode-org-caches declared them —\n // EMPTY. LOSES every scan cursor (re-derived by the next pass, which republishes the\n // messages it re-reads) and every read cursor (users see the recent days as unread once).\n down(db) {\n db.exec(`\n DROP TABLE IF EXISTS org_channel_state;\n DROP TABLE IF EXISTS org_channel_reads;\n CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, user_id)\n );\n `);\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const companyModeDeskNotices: Migration = {\n name: \"2026-09-16-company-mode-desk-notices\",\n // Additive: one new table and its index. A ticket change no longer starts a work run at\n // the owner's desk; it is queued here and delivered inside the body of that employee's\n // next calendar sweep. A predecessor build never reads the table, so a rollback survives\n // it — with whatever rows are in it left undelivered.\n swapSafe: true,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n change TEXT NOT NULL,\n at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);\n `);\n },\n // LOSES every queued notice: the ticket changes an employee has not been told about yet.\n // The change itself is in the ticket file and its history either way; what\n // goes is the \"Since your last sweep\" line that would have named it.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_org_desk_notices_agent;\n DROP TABLE IF EXISTS org_desk_notices;\n `);\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const companyModeOrgCaches: Migration = {\n name: \"2026-09-16-company-mode-org-caches\",\n // Additive: seven new tables for company mode (organizations of Agents), no change to any\n // existing table. Every row is either rebuildable from the organization's files (desks.toml,\n // the tickets' Sessions headers, the calendar files, usage records) or a user's own read\n // cursor; a predecessor build never touches them.\n swapSafe: true,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is chat-chain accounting and reads 0 after a rebuild\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n current INTEGER NOT NULL DEFAULT 1,\n trigger_hop INTEGER NOT NULL DEFAULT 0\n );\n CREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);\n CREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n trigger_hop INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, ticket_id, session_id)\n );\n CREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);\n CREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL,\n start_at_ms INTEGER NOT NULL,\n def_hash TEXT NOT NULL,\n last_slot_ms INTEGER,\n last_fired_at TEXT,\n fired_once INTEGER NOT NULL DEFAULT 0,\n missed INTEGER NOT NULL DEFAULT 0,\n invalid_reason TEXT,\n last_outcome TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, name)\n );\n CREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n status TEXT NOT NULL,\n owner TEXT NOT NULL DEFAULT '',\n blocked TEXT NOT NULL DEFAULT '',\n blocked_by TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (project_id, org_id, ticket_id)\n );\n CREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n period TEXT NOT NULL,\n warned_at TEXT,\n paused_at TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, period)\n );\n `);\n // The two chat tables 2026-09-16-company-mode-channels replaced. Re-running this migration after that\n // one (adoption runs every migration again) must not bring them back, so they are created\n // only while the channel tables that superseded them are absent.\n const superseded =\n db\n .prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'org_channel_state'\")\n .get() !== undefined;\n if (!superseded) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, date)\n );\n CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, user_id)\n );\n `);\n }\n },\n // Drops the seven tables. LOSES: chat read cursors (each user's \"read up to here\" marks) and\n // the run marks that stop a calendar slot, a ticket change or a budget alert from firing\n // twice — a build with this migration re-registers everything from the files, without\n // backfilling missed slots, and users see every chat message as unread once.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_org_ticket_sessions_session;\n DROP INDEX IF EXISTS idx_org_sessions_org;\n DROP TABLE IF EXISTS org_budget_state;\n DROP TABLE IF EXISTS org_chat_reads;\n DROP TABLE IF EXISTS org_chat_state;\n DROP TABLE IF EXISTS org_ticket_state;\n DROP TABLE IF EXISTS org_calendar_state;\n DROP TABLE IF EXISTS org_ticket_sessions;\n DROP TABLE IF EXISTS org_sessions;\n `);\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const modelPromotions: Migration = {\n name: \"2026-09-17-model-promotions\",\n // Additive: one new table, nothing existing touched. A predecessor build never reads it\n // and prices every row at the number in its Project file, so a rollback survives it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the model-promotions feature; do not re-derive from\n // schema.ts. IF NOT EXISTS because the declarative track may already have created it\n // (RE-RUNNABLE in index.ts).\n db.exec(`\n CREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, \"sync presets\" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n discount REAL NOT NULL CHECK (discount > 0 AND discount < 1),\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider, model_id)\n );\n `);\n },\n // LOSES every stored promotion: no file holds a copy of the fractions, so usage is priced\n // at the Project files' list prices until the next \"sync presets\" or Penguin Go sync\n // writes them back.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS model_promotions\");\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const modelProviderAuthTokens: Migration = {\n name: \"2026-09-21-model-provider-auth-tokens\",\n // Additive: one new table, nothing existing touched. A predecessor build never reads it;\n // the access token already written into .project_config.toml keeps working until it\n // expires, so rollback only loses silent refresh state.\n // KEEP until every supported upgrade starts from a database that already has this table.\n // The release that raises the minimum database baseline past it owns removing this\n // migration and its fixture; the table itself remains while provider token refresh uses it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the provider-auth-token feature; do not re-derive from\n // schema.ts. IF NOT EXISTS because the declarative track may already have created it\n // (RE-RUNNABLE in index.ts).\n db.exec(`\n CREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n refresh_token TEXT NOT NULL,\n access_token_expires_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider)\n );\n `);\n },\n // LOSES every stored refresh token and access-token expiry. Existing access tokens in\n // Project files remain until they expire; users re-authorize to restore silent refresh.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS model_provider_auth_tokens\");\n },\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const sessionsSandbox: Migration = {\n name: \"2026-09-22-sessions-sandbox\",\n // The Session's own sandbox policy (JSON), snapshotted from the server's settings when\n // the Session is created, so a later settings change leaves running Sessions alone.\n // NULL = a row from before this column: it takes the settings in force at its next\n // command and keeps them from then on. Swap-safe: a pushed platform boots against the\n // runtime's already-open database, so the column has to arrive by a migration.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"sessions\", \"sandbox\", \"TEXT\");\n },\n // Not a DROP: schema.ts declares the column, and dropping it would put every Session\n // back under whatever the settings say.\n down() {},\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const machinesColumns: Migration = {\n name: \"2026-09-23-machines-columns\",\n // A machines table can predate `machines` — a data root that ran the machines line\n // before it was released kept forwards, not sessions — and that migration's IF NOT\n // EXISTS adopted it whatever its columns were, so the first connect failed on the row's\n // insert. Adds what is missing, nullable; a platform rolled back to `machines` declared these\n // columns itself, so there is nothing for it to mind.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"machines\", \"session_pid\", \"INTEGER\");\n ensureColumn(db, \"machines\", \"platform\", \"TEXT\");\n },\n // Nothing to undo: what this added, `machines` already declares, and a column it found in place\n // was never this migration's to take away.\n down() {},\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const modelTablesAdoption: Migration = {\n name: \"2026-09-23-model-tables-adoption\",\n // A data root that ran the chain before it was restacked onto main (2026-09-23) is\n // stamped 16 under THAT line's numbering, where 9 and 10 were 2026-09-22-sessions-sandbox and\n // 2026-09-23-machines-columns. This line numbers main's 2026-09-17-model-promotions and\n // 2026-09-21-model-provider-auth-tokens 9 and 10 and everything after them two higher, so such a\n // root reads both as already applied, reaches 18 without `model_promotions` or\n // `model_provider_auth_tokens`, and answers 500 wherever cost or provider auth reads\n // them (the models page, an organization's overview). Seen on the release instance at\n // the first push of the restacked line.\n //\n // Re-runs 9's and 10's own `up` — the frozen DDL, both `IF NOT EXISTS`, so a root that\n // took them in their proper place finds its work done. The ledger ended the numbering\n // hazard: adopting a numbered root runs 2026-09-17-model-promotions and 2026-09-21-model-provider-auth-tokens\n // themselves. Remove together with the ledger's adoption of numbered roots (index.ts).\n swapSafe: true,\n up(db) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS model_promotions (\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n discount REAL NOT NULL CHECK (discount > 0 AND discount < 1),\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider, model_id)\n );\n CREATE TABLE IF NOT EXISTS model_provider_auth_tokens (\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n refresh_token TEXT NOT NULL,\n access_token_expires_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider)\n );\n `);\n },\n // Nothing to undo: the tables are 2026-09-17-model-promotions' and 2026-09-21-model-provider-auth-tokens', and\n // their own downs drop them.\n down() {},\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const browserExtensions: Migration = {\n name: \"2026-10-04-browser-extensions\",\n // Additive: one new table and its index. The Chrome backend's pairings — one row per\n // PenguinHarness Browser extension a user paired, its token stored hashed. A predecessor\n // build never reads the table, so a rollback survives it; the paired extensions then simply\n // fail to connect until a build that knows them is back.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the system-Chrome feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created it (RE-RUNNABLE in\n // index.ts).\n db.exec(`\n CREATE TABLE IF NOT EXISTS browser_extensions ( -- one row per Chrome paired to a user (builtin-browser/extension-pairing.ts): the PenguinHarness Browser extension's long-lived credential, stored only hashed; NOT rebuildable — a lost row means pairing that Chrome again\n extension_id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE,\n name TEXT NOT NULL,\n version TEXT NOT NULL,\n created_at TEXT NOT NULL,\n last_seen_at TEXT,\n revoked_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);\n `);\n },\n // LOSES every pairing: each user's Chrome has to be paired again (a new code from the\n // Browser panel) before agents can drive it.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_browser_extensions_user;\n DROP TABLE IF EXISTS browser_extensions;\n `);\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const agentApi: Migration = {\n name: \"2026-10-10-agent-api\",\n // Additive: two new tables and an index. The Agent API's per-Agent settings (the switch,\n // keyless access, the approval mode API Sessions are created with) and its keys, stored\n // hashed. A predecessor build never reads them and serves no /api/amsp route, so a\n // rollback survives it: callers get 404 until a build that knows the tables is back.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the Agent API feature; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created them (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0,\n open INTEGER NOT NULL DEFAULT 0,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all',\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n );\n CREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key\n key_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n token_hash TEXT NOT NULL UNIQUE,\n prefix TEXT NOT NULL,\n name TEXT NOT NULL,\n created_by TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL,\n last_used_at TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);\n `);\n },\n // LOSES every Agent's API settings and every key: each exposed Agent reads as disabled\n // again (404 to its callers), and every caller needs a newly created key once it is back\n // on — no file holds a copy of either.\n down(db) {\n db.exec(`\n DROP INDEX IF EXISTS idx_agent_api_keys_agent;\n DROP TABLE IF EXISTS agent_api_keys;\n DROP TABLE IF EXISTS agent_api;\n `);\n },\n};\n","import type { Migration } from \"../migration.js\";\n\nexport const messagingConversations: Migration = {\n name: \"2026-10-12-messaging-conversations\",\n // Additive: one new table. The WeChat connector's per-(bot, user) delivery state — the\n // context token every send must echo, how many sends it has funded, and replies held for\n // the user's next message. A predecessor build never reads it and keeps its tokens in\n // memory as it always did, so a rollback survives it.\n swapSafe: true,\n up(db) {\n // Frozen copy of the DDL as of the WeChat delivery fix; do not re-derive from schema.ts.\n // IF NOT EXISTS because the declarative track may already have created it (ADOPTION).\n db.exec(`\n CREATE TABLE IF NOT EXISTS messaging_conversations ( -- per-(bot, chat) delivery state a connector must keep across reconnects and restarts (WeChat: the context token, its send count, held replies); deleted once no messaging_bindings row references (channel, account_id) — see MessagingBindingsRepo\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n state_json TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (channel, account_id, chat_id)\n );\n `);\n },\n // LOSES every stored context token and every held reply: replies sent before each user's\n // next message are refused again, and what was held never arrives.\n down(db) {\n db.exec(\"DROP TABLE IF EXISTS messaging_conversations\");\n },\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const sessionsKeptAt: Migration = {\n name: \"2026-10-12-sessions-kept-at\",\n // The \"keep in sidebar\" mark: written when the user unarchives a Session, cleared when they\n // archive it. The listing rule files a background Session (api / schedule / cli) away unless\n // it carries the mark, so existing rows are listed by the rule as they stand and nothing is\n // rewritten. Swap-safe: a pushed platform boots against the runtime's already-open database,\n // so the column has to arrive by a migration.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"sessions\", \"kept_at\", \"TEXT\");\n },\n // Not a DROP: schema.ts declares the column, and dropping it would file every kept\n // background Session away again.\n down() {},\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const agentApiConcurrency: Migration = {\n name: \"2026-10-14-agent-api-concurrency\",\n // How many of an Agent API Agent's runs may be live at once.\n // Retain while a supported data root can predate this column; the maintainer raising\n // that baseline removes this upgrade once every supported data root has it.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"agent_api\", \"max_concurrent_runs\", \"INTEGER NOT NULL DEFAULT 4\");\n },\n // Keep the configured limit on rollback; older builds ignore this column.\n down() {},\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const agentApiSessionSettings: Migration = {\n name: \"2026-10-14-agent-api-session-settings\",\n // The per-Agent API defaults a new Session starts with: which provider, model, thinking\n // level and workspace it opens in. Nullable additions preserve existing keys, exposure,\n // approvals and new-Session defaults.\n // Retain while a supported data root can predate these columns; the maintainer raising\n // that baseline removes this upgrade after all supported data roots have them.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"agent_api\", \"provider\", \"TEXT\");\n ensureColumn(db, \"agent_api\", \"model_id\", \"TEXT\");\n ensureColumn(db, \"agent_api\", \"thinking_level\", \"TEXT\");\n ensureColumn(db, \"agent_api\", \"workspace\", \"TEXT\");\n },\n // Keep the saved defaults on rollback; older builds ignore the additional columns.\n down() {},\n};\n","import { ensureColumn } from \"../../database.js\";\nimport type { Migration } from \"../migration.js\";\n\nexport const machinesAdoptedAt: Migration = {\n name: \"2026-10-16-machines-adopted-at\",\n // When this server adopted a machine (first recorded it): the Sessions that machine held\n // before then read as CLI tasks through this server (session-sources.ts sourceSeenBy). A\n // machine recorded before this column has none and never gets one, so the rule does not apply\n // to it (user decision, 2026-10-15) — nothing on either side is rewritten. Swap-safe: a pushed platform boots against the runtime's\n // already-open database, so the column has to arrive by a migration.\n swapSafe: true,\n up(db) {\n ensureColumn(db, \"machines\", \"adopted_at\", \"TEXT\");\n },\n // Keep the adoption times on rollback; older builds ignore the column.\n down() {},\n};\n","/**\n * Named schema migrations, recorded in a ledger.\n *\n * `schema.ts` declares the shape a FRESH database is created with. It cannot express a\n * CHANGE — `CREATE TABLE IF NOT EXISTS` only ever says \"should exist\". A migration says what\n * CHANGED; the `schema_migrations` ledger records, by name, which ones a database has run\n * (runner.ts). Every unrecorded migration is applied on open, in the order declared below.\n *\n * NAMES, NOT NUMBERS. A migration's name is its identity. Migrations used to be numbered and\n * stamped in `PRAGMA user_version`, and parallel PR lines kept giving one number two meanings:\n * a root stamped by one line skipped another line's migrations of the same numbers. Names do\n * not collide that way — two lines that each add a migration add two names, and a root that\n * ran one of them runs the other when it meets it. A build ignores names it does not declare,\n * so an older build keeps running on a database a newer one migrated.\n *\n * FROZEN. A migration spells out its own SQL and never imports SCHEMA_SQL, and once pushed its\n * name and DDL never change: some root may already have recorded it, and a recorded migration\n * never runs again there. A correction is a NEW migration.\n *\n * RE-RUNNABLE. Every `up` must leave a database that already has its effect exactly as it\n * was: `IF NOT EXISTS`, `ensureColumn`, `PRAGMA table_info` guards, and a shape check before\n * any table is rebuilt or data moved. The ledger records names, not shapes, so this is what\n * lets a root be adopted (below), and what lets the declarative track — SCHEMA_SQL and\n * openDatabase's ensureColumn list, which still run first at every runtime open — get there\n * before a migration does.\n *\n * SWAP-SAFE. A pushed platform boots against a live database and is ROLLED BACK to its\n * predecessor if it fails; the predecessor then runs on whatever the migration already did.\n * Additive work survives that, narrowing work does not. Anything that drops, retypes,\n * constrains, or reshapes in a way the predecessor cannot read or write is a CONTRACT\n * (`swapSafe: false`): the swap path leaves it pending and boots without it, and the runtime's\n * own open applies it (migration.ts). A hot push never refuses on a migration.\n *\n * DOWN, AND WHO DOES NOT CALL IT. Every migration declares an undo — or `null` to say it has\n * none. `down` is NOT the hot-update rollback mechanism: a failed platform boot reverts the\n * platform and leaves the schema where the migration put it, which `swapSafe` makes safe.\n * `down` is an operator's tool (`rollbackTo`), and LOSSY by nature: undoing \"add a table\" drops\n * the table with its rows. Each `down` names what its rows were.\n *\n * ADOPTION OF NUMBERED ROOTS. A database with no ledger — one stamped in `user_version` by a\n * build from before the ledger, whatever line it came from, or a new one — runs EVERY\n * migration once, re-runnably, and records them all. `user_version` is not read: the same\n * number meant different migrations on different lines. Nor is it written any more; it stays\n * at whatever the last numbered build left. Remove this adoption once no supported root can\n * still be without the ledger — the release that sets that baseline owns it.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type { Migration } from \"./migration.js\";\nimport * as runner from \"./runner.js\";\nimport { messagingBindings } from \"./steps/2026-08-31-messaging-bindings.js\";\nimport { messagingDeliveryFlags } from \"./steps/2026-08-31-messaging-delivery-flags.js\";\nimport { dropGoalState } from \"./steps/2026-09-02-drop-goal-state.js\";\nimport { machines } from \"./steps/2026-09-04-machines.js\";\nimport { userProfile } from \"./steps/2026-09-14-user-profile.js\";\nimport { companyModeChannels } from \"./steps/2026-09-16-company-mode-channels.js\";\nimport { companyModeDeskNotices } from \"./steps/2026-09-16-company-mode-desk-notices.js\";\nimport { companyModeOrgCaches } from \"./steps/2026-09-16-company-mode-org-caches.js\";\nimport { modelPromotions } from \"./steps/2026-09-17-model-promotions.js\";\nimport { modelProviderAuthTokens } from \"./steps/2026-09-21-model-provider-auth-tokens.js\";\nimport { sessionsSandbox } from \"./steps/2026-09-22-sessions-sandbox.js\";\nimport { machinesColumns } from \"./steps/2026-09-23-machines-columns.js\";\nimport { modelTablesAdoption } from \"./steps/2026-09-23-model-tables-adoption.js\";\nimport { browserExtensions } from \"./steps/2026-10-04-browser-extensions.js\";\nimport { agentApi } from \"./steps/2026-10-10-agent-api.js\";\nimport { messagingConversations } from \"./steps/2026-10-12-messaging-conversations.js\";\nimport { sessionsKeptAt } from \"./steps/2026-10-12-sessions-kept-at.js\";\nimport { agentApiConcurrency } from \"./steps/2026-10-14-agent-api-concurrency.js\";\nimport { agentApiSessionSettings } from \"./steps/2026-10-14-agent-api-session-settings.js\";\nimport { machinesAdoptedAt } from \"./steps/2026-10-16-machines-adopted-at.js\";\n\nexport type { Migration } from \"./migration.js\";\nexport { IrreversibleMigrationError, UnknownMigrationError, appliedMigrations } from \"./runner.js\";\nexport type { MigrateResult } from \"./runner.js\";\n\n/**\n * Every migration this build declares, in the order a database that lacks them applies them.\n * A new migration is appended, its name carrying the `yyyy-mm-dd-` date it was introduced\n * (migration.ts); an existing one is never moved, renamed or removed while some root may\n * still lack it.\n */\nexport const MIGRATIONS: readonly Migration[] = [\n messagingBindings,\n messagingDeliveryFlags,\n dropGoalState,\n machines,\n userProfile,\n companyModeOrgCaches,\n companyModeChannels,\n companyModeDeskNotices,\n modelPromotions,\n modelProviderAuthTokens,\n sessionsSandbox,\n machinesColumns,\n browserExtensions,\n agentApi,\n messagingConversations,\n sessionsKeptAt,\n agentApiSessionSettings,\n agentApiConcurrency,\n machinesAdoptedAt,\n modelTablesAdoption,\n];\n\n/**\n * Applies every declared migration the ledger does not record. `swapPath` marks the caller as\n * a booting pushed platform, where contract migrations stay pending (runner.ts).\n */\nexport function migrate(\n db: DatabaseSync,\n options: { swapPath?: boolean } = {},\n): runner.MigrateResult {\n return runner.migrate(db, MIGRATIONS, options);\n}\n\n/** Reverts every migration applied after `target` (`null`: all), newest-applied first. */\nexport function rollbackTo(\n db: DatabaseSync,\n target: string | null,\n): { reverted: readonly string[] } {\n return runner.rollbackTo(db, MIGRATIONS, target);\n}\n","/**\n * SQLite table-creation SQL.\n *\n * SQLite stores only indexes and aggregates: users / login sessions / Project authorization /\n * Agent & Session indexes / usage summaries / error records / UI preferences. Agent State,\n * Trace, and Workspace still follow the local directory-based storage rules.\n * Product not yet released: no migration branches — everything is CREATE IF NOT EXISTS, formed\n * once. The one exception: columns added to an existing table after release of a web.db are\n * ALTERed in by the idempotent per-column guard in database.ts (ensureColumn), since CREATE\n * TABLE IF NOT EXISTS never touches an existing table. A *reshaped* index follows the same\n * rule under a new name, with the superseded one dropped on open (idx_usage_session →\n * idx_usage_session_ts): CREATE INDEX IF NOT EXISTS never rebuilds an existing index either.\n */\n\nexport const MODEL_PROMOTIONS_SQL = `\nCREATE TABLE IF NOT EXISTS model_promotions ( -- NOT a cache rebuildable from files: the only record of a Project row's running promotion (.project_config.toml keeps the list price), written by preset seeding at Project creation, \"sync presets\" and Penguin Go authorization / sync, and read by cost; lost rows price usage at list until the next sync writes them back\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n model_id TEXT NOT NULL,\n discount REAL NOT NULL CHECK (discount > 0 AND discount < 1), -- fraction off the row's list price: billed = list × (1 − discount)\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider, model_id)\n);`;\n\nexport const MODEL_PROVIDER_AUTH_TOKENS_SQL = `\nCREATE TABLE IF NOT EXISTS model_provider_auth_tokens ( -- Server-side OAuth refresh metadata for provider groups. The current request token remains in .project_config.toml as api_key; this table holds only the refresh material that must never be returned to the frontend or written into Project files.\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n provider TEXT NOT NULL,\n refresh_token TEXT NOT NULL,\n access_token_expires_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, provider)\n);`;\n\nexport const SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS users (\n user_id TEXT PRIMARY KEY, -- semantic id doubles as login name: ^[a-z][a-z0-9_-]{1,31}$\n password_hash TEXT NOT NULL, -- scrypt$N$r$p$salt$hash(base64)\n is_admin INTEGER NOT NULL DEFAULT 0, -- 1 for the built-in admin (seeded at startup)\n password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it\n display_name TEXT, -- nickname shown in place of user_id (1-32 characters); NULL = never set, surfaces show the id\n avatar TEXT, -- avatar as a data URL (image/png|jpeg|webp, <= 131072 characters); NULL = never set, surfaces draw the letter placeholder\n created_at TEXT NOT NULL\n);\n-- Server-side sessions backing the HttpOnly cookie: the cookie carries a 32-byte random\n-- token, the row stores only its sha256. A session outlives a restart (it is on disk), which\n-- is why the model is a row and not a signed statement.\nCREATE TABLE IF NOT EXISTS auth_sessions (\n token_hash TEXT PRIMARY KEY, -- sha256(token) hex; the cookie stores only the raw token\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL, -- 30-day sliding renewal, topped up in place when <29 days remain\n via TEXT -- 'password'|'desktop'|'setup'|'cli'|'remote'; NULL = legacy (password)\n);\n-- deleteExpired runs on every login and mint, deleteByUser on every admin reset; without\n-- these both scan the whole table.\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);\nCREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);\n\nCREATE TABLE IF NOT EXISTS projects (\n project_id TEXT PRIMARY KEY, -- directory name doubles as id; display name lives in project_config.toml\n owner_user_id TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL\n);\nCREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners are not stored here\n project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, user_id)\n);\n${MODEL_PROMOTIONS_SQL}\n${MODEL_PROVIDER_AUTH_TOKENS_SQL}\nCREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yaml\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS sessions (\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n provider TEXT NOT NULL, -- provider group of the session's CURRENT model (paired with model_id as a model reference; moves with each in-session switch)\n model_id TEXT NOT NULL, -- upstream model id of the current model (sent to MMSP as-is; never concatenate <provider>/<id>)\n workspace TEXT NOT NULL,\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask\n thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config\n title TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows \"New chat\")\n archived_at TEXT, -- the user archived it (ISO time); NULL = not archived by hand (the listing rule may still file it away)\n kept_at TEXT, -- \"keep in sidebar\": set when the user unarchives, cleared when they archive; NULL = the listing rule decides (a background source is archived, a user Session is active). Never written by a run.\n client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace) | 'org' (company mode) | 'api' (an Agent API run); NULL = legacy row, treated as web\n has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)\n fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted\n sandbox TEXT, -- the Session's sandbox policy snapshot (JSON SandboxSettings); NULL = legacy row, snapshotted at its next command\n last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill\n created_at TEXT NOT NULL\n); -- the Session's SOURCE (user/api/schedule/subagent/cli/company) is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); \"client\" is a different, DB-only axis (who created the row), read for the source only where the Trace records none ('org' → company)\nCREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);\nCREATE TABLE IF NOT EXISTS usage_records (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (aggregation key; same convention as Trace date directories)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL, -- top-level Session (child-session usage counts toward its main Session)\n origin_session_id TEXT, -- immediate source child Session (last of the origin chain); NULL=main session\n provider TEXT NOT NULL, -- provider group: paired with model_id as the attribution key; always GROUP BY provider, model_id\n model_id TEXT NOT NULL, -- upstream model id (paired with provider; same model_id across providers aggregates separately)\n cache_read INTEGER NOT NULL,\n cache_write INTEGER NOT NULL,\n output INTEGER NOT NULL,\n total INTEGER NOT NULL, -- from token_usage.request (one row per Request)\n status TEXT NOT NULL DEFAULT 'completed' -- request outcome: completed=success (with tokens); others=failure (0 tokens, for success rate)\n); -- cost is not stored: computed at query time from current pricing\nCREATE INDEX IF NOT EXISTS idx_usage_project_date ON usage_records(project_id, date);\nCREATE INDEX IF NOT EXISTS idx_usage_session_ts ON usage_records(session_id, ts); -- (session_id) alone was idx_usage_session (dropped on open): ts makes the last_active_at backfill's MAX(ts) a covering index scan instead of a random row lookup per usage record\nCREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the Costs page's \"Errors\" tab)\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts TEXT NOT NULL,\n date TEXT NOT NULL, -- local date yyyy-mm-dd (same convention as usage_records)\n project_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project context\n agent_id TEXT,\n session_id TEXT,\n source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule | messaging | organization | id_suggest | plugin\n kind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)\n code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...\n status INTEGER, -- HTTP status code; NULL for non-HTTP sources\n message TEXT NOT NULL -- truncated to 500 chars (no stack stored: stacks go to logs only)\n);\nCREATE INDEX IF NOT EXISTS idx_error_project_date ON error_records(project_id, date);\nCREATE TABLE IF NOT EXISTS schedule_state ( -- schedule runtime state (files are declarative intent; the system never writes back)\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL, -- file name (without .toml) doubles as the identifier\n creator_user_id TEXT, -- creator (recorded on API create; hand-edited file reconciliation falls back to the Project owner)\n start_at_ms INTEGER NOT NULL, -- defines identity: a start_at change counts as a new task instance, resetting fire state\n def_hash TEXT NOT NULL, -- file content fingerprint: any change clears the invalid flag (the file takes effect again after edits)\n last_slot_ms INTEGER, -- latest due slot already consumed (advances on fire or skip; no re-fire across restarts)\n last_fired_at TEXT, -- last actual fire time (for display)\n fired_once INTEGER NOT NULL DEFAULT 0, -- one-shot task has fired\n missed INTEGER NOT NULL DEFAULT 0, -- one-shot task was missed (flagged by startup/registration reconciliation; not backfilled)\n invalid_reason TEXT, -- invalidation reason (e.g. the bound Session was deleted); NULL=healthy\n PRIMARY KEY (project_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel bot bindings (runtime/messaging/ holds the long connections)\n session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled), and enabling is what binds the account to this Session\n channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram' | 'qq' | 'wechat')\n account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id; qq: the bot's App ID; wechat: the scanned bot id); NOT unique — any number of Sessions may keep the same account saved side by side, each with its own config and last-chat memory; only ENABLING is exclusive (route-enforced, 409 account_enabled_elsewhere: one account has one event stream, two live connections on it would race)\n config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret; wechat: botId/botToken/baseUrl/userId); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as \"\" (the row and its account identity stay)\n enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle does\n line_per_message INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = every non-blank line of a relayed assistant reply is sent as its own message (a reply written as spoken lines arrives as spoken lines), 0 = one message per reply. Channel-agnostic, so it lives here rather than in config_json, which each connector owns\n final_reply_only INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = a run's intermediate assistant messages are held and only its LAST completed one is sent, at the run's end, 0 = every completed assistant message mirrors the moment it completes. Channel-agnostic like the column above and independent of it: with both set, that one final text is the one split per line\n render_markdown INTEGER NOT NULL DEFAULT 1, -- delivery preference: 1 = a relayed reply's Markdown is rendered in the channel's own markup (Telegram HTML, a Feishu card, QQ markdown, the subset WeChat itself reads), 0 = the reply's characters are sent as written. DEFAULT 1 because the model writes Markdown and showing it raw was the defect; the per-channel subsets and the plain-text fallback live in the connectors\n last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it); CONNECTOR-OPAQUE, not necessarily a bare chat id — telegram appends the forum topic (see telegram-connector.ts chatRefOf), so only that channel's connector may interpret it\n last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)\n last_inbound_message_id TEXT, -- channel id of the most recently PROCESSED inbound message (NULL until one arrives); the durable half of the bridge's redelivery guard, so a channel replaying an event this server already turned into a Task after a restart does not run it twice\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (session_id, channel)\n);\nCREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id); -- serves the enable guard's by-account lookup; deliberately NOT unique, unlike its predecessor idx_messaging_account (dropped on open) which made an account exclusive to one Session forever\nCREATE TABLE IF NOT EXISTS messaging_conversations ( -- per-(bot, chat) delivery state a connector must keep across reconnects and restarts (WeChat: the context token, its send count, held replies); deleted once no messaging_bindings row references (channel, account_id) — see MessagingBindingsRepo\n channel TEXT NOT NULL, -- messaging channel discriminator (only 'wechat' writes rows today)\n account_id TEXT NOT NULL, -- the bot, as messaging_bindings.account_id names it\n chat_id TEXT NOT NULL, -- the connector's own chat id (wechat: the user's ilink_user_id)\n state_json TEXT NOT NULL, -- connector-owned JSON (wechat: {contextToken, tokenAt, spent, held, heldSince}); the token is a conversation handle at rest, same trade-off as config_json's credentials\n updated_at TEXT NOT NULL,\n PRIMARY KEY (channel, account_id, chat_id)\n);\nCREATE TABLE IF NOT EXISTS ui_prefs (\n user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,\n prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON\n);\nCREATE TABLE IF NOT EXISTS browser_extensions ( -- one row per Chrome paired to a user (builtin-browser/extension-pairing.ts): the PenguinHarness Browser extension's long-lived credential, stored only hashed; NOT rebuildable — a lost row means pairing that Chrome again\n extension_id TEXT PRIMARY KEY, -- random id shown in the Web App's list\n user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL UNIQUE, -- sha256(token) hex; the extension alone holds the token\n name TEXT NOT NULL, -- how the extension names this Chrome (\"Chrome 130 on macOS\")\n version TEXT NOT NULL, -- the extension's version, as of its last hello\n created_at TEXT NOT NULL,\n last_seen_at TEXT, -- last connect or disconnect; NULL = never connected\n revoked_at TEXT -- set by Revoke; a revoked token's socket is closed 4003\n);\nCREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);\nCREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 0, -- the API tab's switch; off = every /api/amsp request for it is 404 agent_not_found\n open INTEGER NOT NULL DEFAULT 0, -- keyless access: a request without Authorization is accepted; off = 401 unauthorized\n approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- copied onto each new API Session\n provider TEXT, -- NULL pair follows the Project default model\n model_id TEXT,\n thinking_level TEXT, -- NULL follows Agent/Project configuration\n workspace TEXT, -- NULL creates a temporary Workspace\n max_concurrent_runs INTEGER NOT NULL DEFAULT 4,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, agent_id)\n);\nCREATE TABLE IF NOT EXISTS agent_api_keys ( -- one row per key the API tab or the CLI minted; the caller alone holds the key\n key_id TEXT PRIMARY KEY, -- 16 base64url chars, shown in the list\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n token_hash TEXT NOT NULL UNIQUE, -- sha256(key) hex\n prefix TEXT NOT NULL, -- the key's first 16 characters (\"penguin_\" + 8), shown in the list\n name TEXT NOT NULL, -- 1-64 characters\n created_by TEXT NOT NULL REFERENCES users(user_id),\n created_at TEXT NOT NULL,\n last_used_at TEXT -- stamped once per run request that authenticated with it; NULL = never\n);\nCREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);\nCREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global settings (GET/PUT /api/admin/settings)\n key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'\n value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default\n);\nCREATE TABLE IF NOT EXISTS machine ( -- this server's OWN identity, minted here and never assigned from outside (what 'penguin server status' reports)\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1), -- exactly one row, enforced by the schema rather than by convention\n machine_id TEXT NOT NULL -- 16 base64url characters; what every stored reference to this machine points at\n);\nCREATE TABLE IF NOT EXISTS machines ( -- one row per machine this server installed on or reached (machines/service.ts)\n address TEXT PRIMARY KEY, -- 'ssh:<alias>'\n machine_id TEXT, -- that machine's own id, once heard\n version TEXT, -- what this server last installed there; NULL = never\n installed_at TEXT,\n session_pid INTEGER, -- the ssh session this server holds to it; what a successor App closes after a hot swap\n remote_port INTEGER, -- its server's port over there, as of the last connect\n platform TEXT, -- linux | darwin | win32, as the install found it: the shell dialect the status probe speaks to it in\n adopted_at TEXT -- when this server first recorded this machine (reset when the address answers with another machine's id): Sessions it held before then read as CLI tasks through this server. NULL = recorded before the column existed; never filled in later, and the rule does not apply\n);\nCREATE TABLE IF NOT EXISTS machine_project ( -- which machines a Project uses; no row = none yet. Follows the Project out, like project_members\n project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,\n addresses TEXT NOT NULL -- JSON array of 'ssh:<alias>'\n);\nCREATE TABLE IF NOT EXISTS trace_files ( -- DERIVED CACHE of the on-disk Trace tree (services/trace-index.ts): the directories stay the single source of truth, every row is rebuildable from disk, and a row is never authority for absence — consumers reconcile + retry on a miss, so a stale index costs one extra scan, never a false 404\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n file_index INTEGER NOT NULL, -- shard index NNN of <session_id>_NNN.jsonl (name/path are reconstructed from the row, never stored: the data root may move)\n date TEXT NOT NULL, -- date directory name (local yyyy-mm-dd)\n size_bytes INTEGER NOT NULL, -- last observed size (listings stat-refresh the returned page and write back; an actively-appended shard may lag in between)\n page_stats TEXT, -- cached message-window scan state at this shard's END (services/message-window.ts ShardPrefixRecord JSON); immutable shards only, NULL = not yet computed, nulled whenever size_bytes changes\n PRIMARY KEY (project_id, agent_id, session_id, file_index)\n);\nCREATE INDEX IF NOT EXISTS idx_trace_files_agent_date ON trace_files(project_id, agent_id, date);\nCREATE INDEX IF NOT EXISTS idx_trace_files_session ON trace_files(session_id);\nCREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at registration from the earliest shard's head (same derived-cache rules as trace_files; listing needs zero head-reads)\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n source TEXT, -- session_meta source as the head carried it: 'user' | 'api' | 'schedule' | 'subagent' | 'cli' | 'company'; NULL = the head records none (written before the source was required: read as 'company' for an 'org' row, else 'user' — readRecordedSource); 'benchmark' from older rows reads as 'cli' (normalizeSessionSource; meaningless while meta_read = 0)\n workspace TEXT NOT NULL DEFAULT '',\n title TEXT, -- first-prompt fallback title (sessions.title always wins when present)\n provider TEXT, -- model reference from session_meta: the model the Session was created on (CLI adoption reads it from here, and the runtime's own answer corrects the row at load; NULL = meta unreadable / legacy without provider)\n model_id TEXT,\n first_ts TEXT, -- first record's timestamp (adoption's createdAt fallback when the id embeds no time)\n meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session\n);\nCREATE INDEX IF NOT EXISTS idx_trace_sessions_agent ON trace_sessions(project_id, agent_id);\nCREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is mention-chain accounting and reads 0 after a rebuild\n session_id TEXT PRIMARY KEY,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n current INTEGER NOT NULL DEFAULT 1,\n trigger_hop INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);\nCREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n trigger_hop INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, ticket_id, session_id)\n);\nCREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);\nCREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL,\n start_at_ms INTEGER NOT NULL,\n def_hash TEXT NOT NULL,\n last_slot_ms INTEGER,\n last_fired_at TEXT,\n fired_once INTEGER NOT NULL DEFAULT 0,\n missed INTEGER NOT NULL DEFAULT 0,\n invalid_reason TEXT,\n last_outcome TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, name)\n);\nCREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n status TEXT NOT NULL,\n owner TEXT NOT NULL DEFAULT '',\n blocked TEXT NOT NULL DEFAULT '',\n blocked_by TEXT NOT NULL DEFAULT '',\n PRIMARY KEY (project_id, org_id, ticket_id)\n);\nCREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n date TEXT NOT NULL,\n offset_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (project_id, org_id, channel_id, date)\n);\nCREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n last_read_id TEXT NOT NULL,\n PRIMARY KEY (project_id, org_id, channel_id, user_id)\n);\nCREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n period TEXT NOT NULL,\n warned_at TEXT,\n paused_at TEXT,\n PRIMARY KEY (project_id, org_id, agent_id, period)\n);\nCREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n project_id TEXT NOT NULL,\n org_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n ticket_id TEXT NOT NULL,\n change TEXT NOT NULL,\n at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);\n`;\n"],"mappings":";AAOA,SAAS,iBAAiB;AAC1B,OAAO,UAAU;;;ACMjB,IAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AA2BnB,SAAS,UAAU,IAA2B;AAC5C,SACE,GACG,QAAQ,iFAAiF,EACzF,IAAI,MAAM;AAEjB;AAGO,SAAS,kBAAkB,IAA4B;AAC5D,MAAI,CAAC,UAAU,EAA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4C;AACpD,sBAAoB,EAAE;AAGtB,EAAAC,SAAQ,EAAE;AACV,SAAO;AACT;AAYA,SAAS,oBAAoB,IAAwB;AACnD,KAAG,KAAK,OAAO;AACf,MAAI;AACF,QAAI,aAAa,IAAI,YAAY,kBAAkB,MAAM,GAAG;AAC1D,SAAG;AAAA,QACD;AAAA;AAAA;AAAA;AAAA,MAIF;AAAA,IACF;AACA,OAAG,KAAK,QAAQ;AAAA,EAClB,SAAS,KAAK;AACZ,OAAG,KAAK,UAAU;AAClB,UAAM;AAAA,EACR;AACF;AAOO,SAAS,aACd,IACA,OACA,QACA,KACS;AACT,QAAM,OAAO,GAAG,QAAQ,qBAAqB,KAAK,GAAG,EAAE,IAAI;AAC3D,MAAI,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,EAAG,QAAO;AAChD,KAAG,KAAK,eAAe,KAAK,eAAe,MAAM,IAAI,GAAG,EAAE;AAC1D,SAAO;AACT;","names":["migrate","migrate"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{U as a,C as n}from"./mermaid.core-zKzlwpkw.js";const t=(r,o)=>a.lang.round(n.parse(r)[o]);export{t as c};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as a,c as s,a as e,C as t}from"./chunk-TICWLB2K-Crl_BgKI.js";import{_ as i}from"./mermaid.core-zKzlwpkw.js";import"./chunk-5VM5RSS4-B8RI4tl3.js";import"./chunk-XXDRQBXY-BFFemuGm.js";import"./chunk-POPQ4Y6H-Bx7Iikzx.js";import"./chunk-F27PBJKO-aVSYH9JV.js";import"./index-BUvJ5Ctt.js";var n={parser:e,get db(){return new t},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{n as diagram};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as a,c as s,a as e,C as t}from"./chunk-TICWLB2K-Crl_BgKI.js";import{_ as i}from"./mermaid.core-zKzlwpkw.js";import"./chunk-5VM5RSS4-B8RI4tl3.js";import"./chunk-XXDRQBXY-BFFemuGm.js";import"./chunk-POPQ4Y6H-Bx7Iikzx.js";import"./chunk-F27PBJKO-aVSYH9JV.js";import"./index-BUvJ5Ctt.js";var n={parser:e,get db(){return new t},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{n as diagram};
|