@prismshadow/penguin-server 0.2.16 → 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.
Files changed (113) hide show
  1. package/README.md +1 -1
  2. package/dist/api/types.d.ts +402 -52
  3. package/dist/api/types.js +17 -3
  4. package/dist/auth-token.js +1 -1
  5. package/dist/{chunk-HMTT2PX4.js → chunk-2LZDP26O.js} +8 -5
  6. package/dist/chunk-2LZDP26O.js.map +1 -0
  7. package/dist/chunk-5YLLSHY3.js +1195 -0
  8. package/dist/chunk-5YLLSHY3.js.map +1 -0
  9. package/dist/{chunk-D3JNA6ZI.js → chunk-B3PSKR3D.js} +2 -2
  10. package/dist/chunk-B3PSKR3D.js.map +1 -0
  11. package/dist/{chunk-LPPVGHYD.js → chunk-BL4U7GYY.js} +2 -2
  12. package/dist/chunk-BL4U7GYY.js.map +1 -0
  13. package/dist/chunk-BRMNPLU6.js +37 -0
  14. package/dist/chunk-BRMNPLU6.js.map +1 -0
  15. package/dist/chunk-GGIINEEK.js +3401 -0
  16. package/dist/chunk-GGIINEEK.js.map +1 -0
  17. package/dist/{chunk-QFV3ERQO.js → chunk-OQZDL3TR.js} +2 -2
  18. package/dist/hmr/manifest.js +1 -1
  19. package/dist/index.js +13440 -8991
  20. package/dist/index.js.map +1 -1
  21. package/dist/machine-status.js +2 -2
  22. package/dist/model-catalog.d.ts +610 -0
  23. package/dist/model-catalog.js +108 -0
  24. package/dist/model-catalog.js.map +1 -0
  25. package/dist/plugin/index.d.ts +170 -74
  26. package/dist/reset-admin-password.js +2 -2
  27. package/dist/version-report.js +2 -2
  28. package/package.json +14 -9
  29. package/web-dist/assets/{abnfDiagram-VCTEODGH-0AKFiyig.js → abnfDiagram-VCTEODGH-C_Ej4MyZ.js} +1 -1
  30. package/web-dist/assets/{addon-clipboard-BovFnNVg.js → addon-clipboard-eONBCa8x.js} +1 -1
  31. package/web-dist/assets/{addon-fit-B1npgxQk.js → addon-fit-Dk6bkT8u.js} +1 -1
  32. package/web-dist/assets/{addon-web-links-D88QHj7A.js → addon-web-links-e0JpGvGv.js} +1 -1
  33. package/web-dist/assets/{arc-Beox1Cgf.js → arc-ytwqobEL.js} +1 -1
  34. package/web-dist/assets/{architectureDiagram-5GKGNRK7-CC1sLMY1.js → architectureDiagram-5GKGNRK7-oxT9SNOE.js} +1 -1
  35. package/web-dist/assets/{blockDiagram-I7D4REHJ-B8BY1PkZ.js → blockDiagram-I7D4REHJ-D8OXfpb9.js} +1 -1
  36. package/web-dist/assets/{c4Diagram-7LVT6UL2-yjY0BkxQ.js → c4Diagram-7LVT6UL2-BNYNzSWK.js} +1 -1
  37. package/web-dist/assets/channel-7Be_pU-b.js +1 -0
  38. package/web-dist/assets/{chunk-2Q5K7J3B-DdgIvETg.js → chunk-2Q5K7J3B-C2yNhFmh.js} +1 -1
  39. package/web-dist/assets/{chunk-5VM5RSS4-BE38k1Rs.js → chunk-5VM5RSS4-CAeuhwbB.js} +1 -1
  40. package/web-dist/assets/{chunk-F27PBJKO-D4YXmaqQ.js → chunk-F27PBJKO-DSuRiLxP.js} +1 -1
  41. package/web-dist/assets/{chunk-IMKFNOWR-CyJFdThc.js → chunk-IMKFNOWR-MStar4cf.js} +1 -1
  42. package/web-dist/assets/{chunk-JWPE2WC7-BAM_oEUU.js → chunk-JWPE2WC7-CIgQwRv4.js} +1 -1
  43. package/web-dist/assets/{chunk-POPQ4Y6H-BP3D0FVi.js → chunk-POPQ4Y6H-CA8evx9g.js} +1 -1
  44. package/web-dist/assets/{chunk-SVP7TREG-Clk8PdKZ.js → chunk-SVP7TREG-bR7-FT1W.js} +1 -1
  45. package/web-dist/assets/{chunk-TICWLB2K-EvWPnEGg.js → chunk-TICWLB2K-C0ZdCnvI.js} +1 -1
  46. package/web-dist/assets/{chunk-XXDRQBXY-6p5D0UB1.js → chunk-XXDRQBXY-CzozFLFI.js} +1 -1
  47. package/web-dist/assets/classDiagram-ZZMXUADV-BjVhvDIH.js +1 -0
  48. package/web-dist/assets/classDiagram-v2-VYDZK3BY-BjVhvDIH.js +1 -0
  49. package/web-dist/assets/{cose-bilkent-JH36ORCC-bpkI-tLJ.js → cose-bilkent-JH36ORCC-nkjrY6eI.js} +1 -1
  50. package/web-dist/assets/{cynefin-OW5HDTMX-srLaqJ4e.js → cynefin-OW5HDTMX-D2A0h062.js} +1 -1
  51. package/web-dist/assets/{cynefinDiagram-5FMLGOSQ-BPfpHSPc.js → cynefinDiagram-5FMLGOSQ-DFZQ7d_T.js} +1 -1
  52. package/web-dist/assets/{dagre-GXQ25YYZ-C4fF5-j7.js → dagre-GXQ25YYZ-DPYLLARd.js} +1 -1
  53. package/web-dist/assets/{diagram-S7CK7UJ4-BzBLb_9-.js → diagram-S7CK7UJ4-B204Nrur.js} +1 -1
  54. package/web-dist/assets/{diagram-UQ7AKVKN-BJuJ1o_T.js → diagram-UQ7AKVKN-DWORCZlS.js} +1 -1
  55. package/web-dist/assets/{diagram-VSXAHHWV-DFelN9i9.js → diagram-VSXAHHWV-Su6Bzm4Z.js} +1 -1
  56. package/web-dist/assets/{diagram-VX7I27RA-BgrEoPyp.js → diagram-VX7I27RA-B4p8ssYj.js} +1 -1
  57. package/web-dist/assets/{diagram-Z3DM3KII-C71KiMiX.js → diagram-Z3DM3KII-BgMz7jjW.js} +1 -1
  58. package/web-dist/assets/{ebnfDiagram-PWID7BFC-EYteyp1b.js → ebnfDiagram-PWID7BFC-DBCS3Cwc.js} +1 -1
  59. package/web-dist/assets/{erDiagram-RLTQ6QDP-B6n6-sz6.js → erDiagram-RLTQ6QDP-DEm39S5C.js} +1 -1
  60. package/web-dist/assets/{flowDiagram-HODETNUW-BtoMTdyT.js → flowDiagram-HODETNUW-CEUQGUza.js} +1 -1
  61. package/web-dist/assets/{ganttDiagram-EL5Y4UJY-CbOAa3vS.js → ganttDiagram-EL5Y4UJY-myYTgwFp.js} +1 -1
  62. package/web-dist/assets/{gitGraphDiagram-WWUBYQGX-B7-8sszH.js → gitGraphDiagram-WWUBYQGX-BAQ0Kl1C.js} +1 -1
  63. package/web-dist/assets/highlighter-DRTMVWxI.js +2 -0
  64. package/web-dist/assets/{highlighter-core-CMXoD8ze.js → highlighter-core-DgISzHrX.js} +1 -1
  65. package/web-dist/assets/{highlighter.worker-D6D9fPma.js → highlighter.worker-CKF6ok1g.js} +1 -1
  66. package/web-dist/assets/index-PA-IFoA6.js +1300 -0
  67. package/web-dist/assets/index-oCEyg9BT.css +1 -0
  68. package/web-dist/assets/{infoDiagram-27XIBGKW-BBjf6pkP.js → infoDiagram-27XIBGKW-B2WDMvX9.js} +1 -1
  69. package/web-dist/assets/{ishikawaDiagram-5VMMS53U-BBSvCv45.js → ishikawaDiagram-5VMMS53U-8qHTttjq.js} +1 -1
  70. package/web-dist/assets/{journeyDiagram-3NMN7TZE-CuHHl5zk.js → journeyDiagram-3NMN7TZE-DKE_xRCO.js} +1 -1
  71. package/web-dist/assets/{kanban-definition-UXKFOSKX-DJyP4Myw.js → kanban-definition-UXKFOSKX-EnJbHEmV.js} +1 -1
  72. package/web-dist/assets/{layout-Bqqhdwtt.js → layout-BlhCFmEZ.js} +1 -1
  73. package/web-dist/assets/{linear-BZfUSIf8.js → linear-Dw2VzU-D.js} +1 -1
  74. package/web-dist/assets/mermaid.core-CaXNMz57.js +310 -0
  75. package/web-dist/assets/{mindmap-definition-YA3MSWOX-BtyMD4wz.js → mindmap-definition-YA3MSWOX-DnTTfqbu.js} +1 -1
  76. package/web-dist/assets/{pegDiagram-XKGWAZYB-BUF_GJ0B.js → pegDiagram-XKGWAZYB-C3SArVd6.js} +1 -1
  77. package/web-dist/assets/{pieDiagram-E7YTZNPT-nweubbsU.js → pieDiagram-E7YTZNPT-CTOmO6ke.js} +1 -1
  78. package/web-dist/assets/powershell-DXrKVo3G.js +1 -0
  79. package/web-dist/assets/powershell-Dpen1YoG.js +1 -0
  80. package/web-dist/assets/{quadrantDiagram-AXDQQJYC-B_r4Wkxy.js → quadrantDiagram-AXDQQJYC-CbUsMwzO.js} +1 -1
  81. package/web-dist/assets/{railroadDiagram-O6MQD6OU-Dn7nm0MX.js → railroadDiagram-O6MQD6OU-Co2hsvaZ.js} +1 -1
  82. package/web-dist/assets/{requirementDiagram-BXWQKSXE-DaagYJ49.js → requirementDiagram-BXWQKSXE-BqFG0eYQ.js} +1 -1
  83. package/web-dist/assets/{sankeyDiagram-P5KCCOFB-CqEX6H-B.js → sankeyDiagram-P5KCCOFB-YgQHJlB7.js} +1 -1
  84. package/web-dist/assets/{sequenceDiagram-WJ2MYXX4-BzLfQO55.js → sequenceDiagram-WJ2MYXX4-CdDrP6O2.js} +1 -1
  85. package/web-dist/assets/{sizeCapture-INFHLROL-BcUuVH2L.js → sizeCapture-INFHLROL-CKwbEVhU.js} +1 -1
  86. package/web-dist/assets/{stateDiagram-D77RDMKH-BO3LWLvT.js → stateDiagram-D77RDMKH-kTJR3t2p.js} +1 -1
  87. package/web-dist/assets/stateDiagram-v2-MP3YSRHH-DzaSnZwj.js +1 -0
  88. package/web-dist/assets/{swimlanes-42K2YHIH-etP_hkIB.js → swimlanes-42K2YHIH-DCAO3rCQ.js} +1 -1
  89. package/web-dist/assets/swimlanesDiagram-VR7AAH4N-DNfCLejq.js +8 -0
  90. package/web-dist/assets/{timeline-definition-24CTP7MA-CTLt2XCT.js → timeline-definition-24CTP7MA-DEjnyzKw.js} +1 -1
  91. package/web-dist/assets/{vennDiagram-4TSXK5OY-DPO6ZSvH.js → vennDiagram-4TSXK5OY-DSihUvCq.js} +1 -1
  92. package/web-dist/assets/{wardleyDiagram-VM6X3IG4-DFofGg8b.js → wardleyDiagram-VM6X3IG4-CnAoMeCH.js} +1 -1
  93. package/web-dist/assets/{xterm-RdyTuaAH.js → xterm-3JwPT74G.js} +1 -1
  94. package/web-dist/assets/{xychartDiagram-S5SC5T6Z-Bgtb34Gu.js → xychartDiagram-S5SC5T6Z-43dHqZTr.js} +1 -1
  95. package/web-dist/index.html +6 -5
  96. package/web-dist/workbench-ui.css +164 -34
  97. package/dist/chunk-3SFJKLQU.js +0 -1016
  98. package/dist/chunk-3SFJKLQU.js.map +0 -1
  99. package/dist/chunk-D3JNA6ZI.js.map +0 -1
  100. package/dist/chunk-HMTT2PX4.js.map +0 -1
  101. package/dist/chunk-LPPVGHYD.js.map +0 -1
  102. package/dist/chunk-W7JNIJ25.js +0 -19
  103. package/dist/chunk-W7JNIJ25.js.map +0 -1
  104. package/web-dist/assets/channel-mfsAVJLE.js +0 -1
  105. package/web-dist/assets/classDiagram-ZZMXUADV-BPVO1m8i.js +0 -1
  106. package/web-dist/assets/classDiagram-v2-VYDZK3BY-BPVO1m8i.js +0 -1
  107. package/web-dist/assets/highlighter-Bj5l2XH_.js +0 -2
  108. package/web-dist/assets/index-BOCqRT4e.css +0 -1
  109. package/web-dist/assets/index-BrMpjp2s.js +0 -1286
  110. package/web-dist/assets/mermaid.core-BlUspEsI.js +0 -310
  111. package/web-dist/assets/stateDiagram-v2-MP3YSRHH-B-EuucjM.js +0 -1
  112. package/web-dist/assets/swimlanesDiagram-VR7AAH4N-0JbFdDbQ.js +0 -8
  113. /package/dist/{chunk-QFV3ERQO.js.map → chunk-OQZDL3TR.js.map} +0 -0
@@ -0,0 +1,1195 @@
1
+ // src/db/database.ts
2
+ import { mkdirSync } from "fs";
3
+ import path from "path";
4
+
5
+ // src/db/migrations/runner.ts
6
+ var LEDGER_DDL = `
7
+ CREATE TABLE IF NOT EXISTS schema_migrations (
8
+ name TEXT PRIMARY KEY,
9
+ applied_at TEXT NOT NULL
10
+ );
11
+ `;
12
+ function hasLedger(db) {
13
+ return db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'").get() !== void 0;
14
+ }
15
+ function appliedMigrations(db) {
16
+ if (!hasLedger(db)) return [];
17
+ const rows = db.prepare("SELECT name FROM schema_migrations ORDER BY rowid").all();
18
+ return rows.map((r) => r.name);
19
+ }
20
+ function migrate(db, migrations, { swapPath = false } = {}) {
21
+ const adopted = !hasLedger(db);
22
+ const done = new Set(appliedMigrations(db));
23
+ const pending = migrations.filter((m) => !done.has(m.name));
24
+ if (adopted) db.exec(LEDGER_DDL);
25
+ const record = db.prepare("INSERT INTO schema_migrations (name, applied_at) VALUES (?, ?)");
26
+ const applied = [];
27
+ const deferred = [];
28
+ for (const m of pending) {
29
+ if (swapPath && !m.swapSafe) {
30
+ deferred.push(m.name);
31
+ continue;
32
+ }
33
+ db.exec("BEGIN");
34
+ try {
35
+ m.up(db);
36
+ record.run(m.name, (/* @__PURE__ */ new Date()).toISOString());
37
+ db.exec("COMMIT");
38
+ } catch (err) {
39
+ db.exec("ROLLBACK");
40
+ throw new Error(`migration ${m.name} failed: ${String(err)}`, { cause: err });
41
+ }
42
+ applied.push(m.name);
43
+ }
44
+ return { adopted, applied, deferred };
45
+ }
46
+
47
+ // src/db/migrations/steps/2026-08-31-messaging-bindings.ts
48
+ var messagingBindings = {
49
+ name: "2026-08-31-messaging-bindings",
50
+ // Purely additive: one new table plus three indexes, no column of any existing table
51
+ // touched. A platform that rolls back to a predecessor without messaging simply never
52
+ // queries them.
53
+ swapSafe: true,
54
+ up(db) {
55
+ db.exec(`
56
+ CREATE TABLE IF NOT EXISTS messaging_bindings (
57
+ session_id TEXT NOT NULL,
58
+ channel TEXT NOT NULL,
59
+ account_id TEXT NOT NULL,
60
+ config_json TEXT NOT NULL,
61
+ enabled INTEGER NOT NULL DEFAULT 0,
62
+ line_per_message INTEGER NOT NULL DEFAULT 0,
63
+ last_chat_id TEXT,
64
+ last_chat_is_direct INTEGER NOT NULL DEFAULT 1,
65
+ last_inbound_message_id TEXT,
66
+ created_at TEXT NOT NULL,
67
+ updated_at TEXT NOT NULL,
68
+ PRIMARY KEY (session_id, channel)
69
+ );
70
+ CREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id);
71
+ CREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);
72
+ CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);
73
+ `);
74
+ },
75
+ // LOSES every messaging binding: the channel credentials, the enabled flag and the
76
+ // last-chat memory all live in the table this drops. The auth_sessions indexes are
77
+ // derived and cost nothing to lose.
78
+ down(db) {
79
+ db.exec(`
80
+ DROP INDEX IF EXISTS idx_auth_sessions_user;
81
+ DROP INDEX IF EXISTS idx_auth_sessions_expires;
82
+ DROP INDEX IF EXISTS idx_messaging_by_account;
83
+ DROP TABLE IF EXISTS messaging_bindings;
84
+ `);
85
+ }
86
+ };
87
+
88
+ // src/db/migrations/steps/2026-08-31-messaging-delivery-flags.ts
89
+ var messagingDeliveryFlags = {
90
+ name: "2026-08-31-messaging-delivery-flags",
91
+ // Two columns with defaults on an existing table: a rollback to a predecessor that
92
+ // does not know them leaves them at their defaults and reads nothing.
93
+ swapSafe: true,
94
+ up(db) {
95
+ ensureColumn(db, "messaging_bindings", "final_reply_only", "INTEGER NOT NULL DEFAULT 0");
96
+ ensureColumn(db, "messaging_bindings", "render_markdown", "INTEGER NOT NULL DEFAULT 1");
97
+ },
98
+ // LOSES both delivery preferences on every binding; the bindings themselves survive.
99
+ // Dropped in reverse order for symmetry with `up`. Neither column is indexed, which is
100
+ // what lets SQLite drop them at all.
101
+ down(db) {
102
+ db.exec("ALTER TABLE messaging_bindings DROP COLUMN render_markdown");
103
+ db.exec("ALTER TABLE messaging_bindings DROP COLUMN final_reply_only");
104
+ }
105
+ };
106
+
107
+ // src/db/migrations/steps/2026-09-02-drop-goal-state.ts
108
+ var dropGoalState = {
109
+ name: "2026-09-02-drop-goal-state",
110
+ // CONTRACT: drops a table no build since 0.2.10 reads. A pushed platform rolled back to
111
+ // 0.2.9 mid-process would prepare its goal statements against a table that is gone, so it
112
+ // is left pending on the swap path and applied by the runtime's own open; until then the
113
+ // table just sits there unused.
114
+ swapSafe: false,
115
+ up(db) {
116
+ db.exec(`
117
+ DROP INDEX IF EXISTS idx_goal_session;
118
+ DROP TABLE IF EXISTS goal_state;
119
+ `);
120
+ },
121
+ // Recreates the table exactly as 0.2.9 declared it — EMPTY. LOSES every goal run ever
122
+ // recorded (objective, status, budget, used, rounds per run): the rows only ever fed the
123
+ // banner of a finished goal, and a build with this migration reads the goal file instead.
124
+ down(db) {
125
+ db.exec(`
126
+ CREATE TABLE IF NOT EXISTS goal_state (
127
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
128
+ session_id TEXT NOT NULL,
129
+ project_id TEXT NOT NULL,
130
+ agent_id TEXT NOT NULL,
131
+ objective TEXT NOT NULL,
132
+ status TEXT NOT NULL,
133
+ budget INTEGER NOT NULL,
134
+ used INTEGER NOT NULL DEFAULT 0,
135
+ rounds INTEGER NOT NULL DEFAULT 0,
136
+ created_at TEXT NOT NULL,
137
+ updated_at TEXT NOT NULL
138
+ );
139
+ CREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);
140
+ `);
141
+ }
142
+ };
143
+
144
+ // src/db/migrations/steps/2026-09-04-machines.ts
145
+ var machines = {
146
+ name: "2026-09-04-machines",
147
+ // Three new tables, nothing existing touched: a platform rolled back to one without
148
+ // machines never queries them. Swap-safe on its own; a database still behind
149
+ // 2026-09-02-drop-goal-state is refused whole by that one first, which is the rule.
150
+ swapSafe: true,
151
+ up(db) {
152
+ db.exec(`
153
+ CREATE TABLE IF NOT EXISTS machine (
154
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
155
+ machine_id TEXT NOT NULL
156
+ );
157
+ CREATE TABLE IF NOT EXISTS machines (
158
+ address TEXT PRIMARY KEY,
159
+ machine_id TEXT,
160
+ version TEXT,
161
+ installed_at TEXT,
162
+ session_pid INTEGER,
163
+ remote_port INTEGER,
164
+ platform TEXT
165
+ );
166
+ CREATE TABLE IF NOT EXISTS machine_project (
167
+ project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,
168
+ addresses TEXT NOT NULL
169
+ );
170
+ `);
171
+ },
172
+ // LOSES this server's own machine id (every stored reference to it on other machines
173
+ // then points at nothing), what was installed where, the sessions held, and which
174
+ // machines each Project used.
175
+ down(db) {
176
+ db.exec(`
177
+ DROP TABLE IF EXISTS machine_project;
178
+ DROP TABLE IF EXISTS machines;
179
+ DROP TABLE IF EXISTS machine;
180
+ `);
181
+ }
182
+ };
183
+
184
+ // src/db/migrations/steps/2026-09-14-user-profile.ts
185
+ var userProfile = {
186
+ name: "2026-09-14-user-profile",
187
+ // Two nullable columns on `users`, no default and nothing existing rewritten: a platform
188
+ // rolled back to a predecessor that does not know them never selects or writes them, and
189
+ // every existing account simply reads NULL — no profile yet.
190
+ swapSafe: true,
191
+ up(db) {
192
+ ensureColumn(db, "users", "display_name", "TEXT");
193
+ ensureColumn(db, "users", "avatar", "TEXT");
194
+ },
195
+ // LOSES every stored nickname and avatar: both live entirely in the two columns this
196
+ // drops, and nothing else on disk holds a copy. Dropped in reverse order for symmetry
197
+ // with `up`; neither column is indexed, which is what lets SQLite drop them at all.
198
+ down(db) {
199
+ const cols = db.prepare("PRAGMA table_info(users)").all();
200
+ const has = (name) => cols.some((c) => c.name === name);
201
+ if (has("avatar")) db.exec("ALTER TABLE users DROP COLUMN avatar");
202
+ if (has("display_name")) db.exec("ALTER TABLE users DROP COLUMN display_name");
203
+ }
204
+ };
205
+
206
+ // src/db/migrations/steps/2026-09-16-company-mode-channels.ts
207
+ var companyModeChannels = {
208
+ name: "2026-09-16-company-mode-channels",
209
+ // The organization's single group chat became channels: a message lives in
210
+ // `channels/<channel_id>/<date>.jsonl`, so the tail-scan cursor and each user's read
211
+ // cursor are per channel. `org_chat_state` / `org_chat_reads` are dropped for
212
+ // `org_channel_state` / `org_channel_reads`: the tables are renamed and the channel
213
+ // belongs in the primary key, neither of which SQLite does in place. Nothing is carried
214
+ // over: company mode is unreleased, and every row was either rebuildable from the files
215
+ // (the scan cursor) or one pass of "everything looks unread" (the read cursor). A
216
+ // predecessor build reads neither table's shape, only its own writes, so this is
217
+ // swap-safe.
218
+ //
219
+ // By the expand / contract rule (migration.ts) the two DROPs are a contract, and this is the
220
+ // one expand that removes anything on the swap path. It stays an expand because it is frozen
221
+ // and cannot be deferred: the same step creates the channel tables a pushed platform needs.
222
+ // A new change of this kind is split into an expand and a later contract instead.
223
+ swapSafe: true,
224
+ up(db) {
225
+ db.exec(`
226
+ DROP TABLE IF EXISTS org_chat_state;
227
+ DROP TABLE IF EXISTS org_chat_reads;
228
+ CREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file
229
+ project_id TEXT NOT NULL,
230
+ org_id TEXT NOT NULL,
231
+ channel_id TEXT NOT NULL,
232
+ date TEXT NOT NULL,
233
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
234
+ PRIMARY KEY (project_id, org_id, channel_id, date)
235
+ );
236
+ CREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel
237
+ project_id TEXT NOT NULL,
238
+ org_id TEXT NOT NULL,
239
+ channel_id TEXT NOT NULL,
240
+ user_id TEXT NOT NULL,
241
+ last_read_id TEXT NOT NULL,
242
+ PRIMARY KEY (project_id, org_id, channel_id, user_id)
243
+ );
244
+ `);
245
+ },
246
+ // Recreates the two tables under their old names, exactly as 2026-09-16-company-mode-org-caches declared them —
247
+ // EMPTY. LOSES every scan cursor (re-derived by the next pass, which republishes the
248
+ // messages it re-reads) and every read cursor (users see the recent days as unread once).
249
+ down(db) {
250
+ db.exec(`
251
+ DROP TABLE IF EXISTS org_channel_state;
252
+ DROP TABLE IF EXISTS org_channel_reads;
253
+ CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file
254
+ project_id TEXT NOT NULL,
255
+ org_id TEXT NOT NULL,
256
+ date TEXT NOT NULL,
257
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
258
+ PRIMARY KEY (project_id, org_id, date)
259
+ );
260
+ CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat
261
+ project_id TEXT NOT NULL,
262
+ org_id TEXT NOT NULL,
263
+ user_id TEXT NOT NULL,
264
+ last_read_id TEXT NOT NULL,
265
+ PRIMARY KEY (project_id, org_id, user_id)
266
+ );
267
+ `);
268
+ }
269
+ };
270
+
271
+ // src/db/migrations/steps/2026-09-16-company-mode-desk-notices.ts
272
+ var companyModeDeskNotices = {
273
+ name: "2026-09-16-company-mode-desk-notices",
274
+ // Additive: one new table and its index. A ticket change no longer starts a work run at
275
+ // the owner's desk; it is queued here and delivered inside the body of that employee's
276
+ // next calendar sweep. A predecessor build never reads the table, so a rollback survives
277
+ // it — with whatever rows are in it left undelivered.
278
+ swapSafe: true,
279
+ up(db) {
280
+ db.exec(`
281
+ 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
282
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
283
+ project_id TEXT NOT NULL,
284
+ org_id TEXT NOT NULL,
285
+ agent_id TEXT NOT NULL,
286
+ ticket_id TEXT NOT NULL,
287
+ change TEXT NOT NULL,
288
+ at TEXT NOT NULL
289
+ );
290
+ CREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);
291
+ `);
292
+ },
293
+ // LOSES every queued notice: the ticket changes an employee has not been told about yet.
294
+ // The change itself is in the ticket file and its history either way; what
295
+ // goes is the "Since your last sweep" line that would have named it.
296
+ down(db) {
297
+ db.exec(`
298
+ DROP INDEX IF EXISTS idx_org_desk_notices_agent;
299
+ DROP TABLE IF EXISTS org_desk_notices;
300
+ `);
301
+ }
302
+ };
303
+
304
+ // src/db/migrations/steps/2026-09-16-company-mode-org-caches.ts
305
+ var companyModeOrgCaches = {
306
+ name: "2026-09-16-company-mode-org-caches",
307
+ // Additive: seven new tables for company mode (organizations of Agents), no change to any
308
+ // existing table. Every row is either rebuildable from the organization's files (desks.toml,
309
+ // the tickets' Sessions headers, the calendar files, usage records) or a user's own read
310
+ // cursor; a predecessor build never touches them.
311
+ swapSafe: true,
312
+ up(db) {
313
+ db.exec(`
314
+ 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
315
+ session_id TEXT PRIMARY KEY,
316
+ project_id TEXT NOT NULL,
317
+ org_id TEXT NOT NULL,
318
+ agent_id TEXT NOT NULL,
319
+ current INTEGER NOT NULL DEFAULT 1,
320
+ trigger_hop INTEGER NOT NULL DEFAULT 0
321
+ );
322
+ CREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);
323
+ CREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header
324
+ project_id TEXT NOT NULL,
325
+ org_id TEXT NOT NULL,
326
+ ticket_id TEXT NOT NULL,
327
+ session_id TEXT NOT NULL,
328
+ agent_id TEXT NOT NULL,
329
+ trigger_hop INTEGER NOT NULL DEFAULT 0,
330
+ PRIMARY KEY (project_id, org_id, ticket_id, session_id)
331
+ );
332
+ CREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);
333
+ CREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state
334
+ project_id TEXT NOT NULL,
335
+ org_id TEXT NOT NULL,
336
+ agent_id TEXT NOT NULL,
337
+ name TEXT NOT NULL,
338
+ start_at_ms INTEGER NOT NULL,
339
+ def_hash TEXT NOT NULL,
340
+ last_slot_ms INTEGER,
341
+ last_fired_at TEXT,
342
+ fired_once INTEGER NOT NULL DEFAULT 0,
343
+ missed INTEGER NOT NULL DEFAULT 0,
344
+ invalid_reason TEXT,
345
+ last_outcome TEXT,
346
+ PRIMARY KEY (project_id, org_id, agent_id, name)
347
+ );
348
+ 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
349
+ project_id TEXT NOT NULL,
350
+ org_id TEXT NOT NULL,
351
+ ticket_id TEXT NOT NULL,
352
+ status TEXT NOT NULL,
353
+ owner TEXT NOT NULL DEFAULT '',
354
+ blocked TEXT NOT NULL DEFAULT '',
355
+ blocked_by TEXT NOT NULL DEFAULT '',
356
+ PRIMARY KEY (project_id, org_id, ticket_id)
357
+ );
358
+ 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
359
+ project_id TEXT NOT NULL,
360
+ org_id TEXT NOT NULL,
361
+ agent_id TEXT NOT NULL,
362
+ period TEXT NOT NULL,
363
+ warned_at TEXT,
364
+ paused_at TEXT,
365
+ PRIMARY KEY (project_id, org_id, agent_id, period)
366
+ );
367
+ `);
368
+ const superseded = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'org_channel_state'").get() !== void 0;
369
+ if (!superseded) {
370
+ db.exec(`
371
+ CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file
372
+ project_id TEXT NOT NULL,
373
+ org_id TEXT NOT NULL,
374
+ date TEXT NOT NULL,
375
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
376
+ PRIMARY KEY (project_id, org_id, date)
377
+ );
378
+ CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat
379
+ project_id TEXT NOT NULL,
380
+ org_id TEXT NOT NULL,
381
+ user_id TEXT NOT NULL,
382
+ last_read_id TEXT NOT NULL,
383
+ PRIMARY KEY (project_id, org_id, user_id)
384
+ );
385
+ `);
386
+ }
387
+ },
388
+ // Drops the seven tables. LOSES: chat read cursors (each user's "read up to here" marks) and
389
+ // the run marks that stop a calendar slot, a ticket change or a budget alert from firing
390
+ // twice — a build with this migration re-registers everything from the files, without
391
+ // backfilling missed slots, and users see every chat message as unread once.
392
+ down(db) {
393
+ db.exec(`
394
+ DROP INDEX IF EXISTS idx_org_ticket_sessions_session;
395
+ DROP INDEX IF EXISTS idx_org_sessions_org;
396
+ DROP TABLE IF EXISTS org_budget_state;
397
+ DROP TABLE IF EXISTS org_chat_reads;
398
+ DROP TABLE IF EXISTS org_chat_state;
399
+ DROP TABLE IF EXISTS org_ticket_state;
400
+ DROP TABLE IF EXISTS org_calendar_state;
401
+ DROP TABLE IF EXISTS org_ticket_sessions;
402
+ DROP TABLE IF EXISTS org_sessions;
403
+ `);
404
+ }
405
+ };
406
+
407
+ // src/db/migrations/steps/2026-09-17-model-promotions.ts
408
+ var modelPromotions = {
409
+ name: "2026-09-17-model-promotions",
410
+ // Additive: one new table, nothing existing touched. A predecessor build never reads it
411
+ // and prices every row at the number in its Project file, so a rollback survives it.
412
+ swapSafe: true,
413
+ up(db) {
414
+ db.exec(`
415
+ 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
416
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
417
+ provider TEXT NOT NULL,
418
+ model_id TEXT NOT NULL,
419
+ discount REAL NOT NULL CHECK (discount > 0 AND discount < 1),
420
+ updated_at TEXT NOT NULL,
421
+ PRIMARY KEY (project_id, provider, model_id)
422
+ );
423
+ `);
424
+ },
425
+ // LOSES every stored promotion: no file holds a copy of the fractions, so usage is priced
426
+ // at the Project files' list prices until the next "sync presets" or Penguin Go sync
427
+ // writes them back.
428
+ down(db) {
429
+ db.exec("DROP TABLE IF EXISTS model_promotions");
430
+ }
431
+ };
432
+
433
+ // src/db/migrations/steps/2026-09-21-model-provider-auth-tokens.ts
434
+ var modelProviderAuthTokens = {
435
+ name: "2026-09-21-model-provider-auth-tokens",
436
+ // Additive: one new table, nothing existing touched. A predecessor build never reads it;
437
+ // the access token already written into .project_config.toml keeps working until it
438
+ // expires, so rollback only loses silent refresh state.
439
+ // KEEP until every supported upgrade starts from a database that already has this table.
440
+ // The release that raises the minimum database baseline past it owns removing this
441
+ // migration and its fixture; the table itself remains while provider token refresh uses it.
442
+ swapSafe: true,
443
+ up(db) {
444
+ db.exec(`
445
+ 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.
446
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
447
+ provider TEXT NOT NULL,
448
+ refresh_token TEXT NOT NULL,
449
+ access_token_expires_at TEXT,
450
+ updated_at TEXT NOT NULL,
451
+ PRIMARY KEY (project_id, provider)
452
+ );
453
+ `);
454
+ },
455
+ // LOSES every stored refresh token and access-token expiry. Existing access tokens in
456
+ // Project files remain until they expire; users re-authorize to restore silent refresh.
457
+ down(db) {
458
+ db.exec("DROP TABLE IF EXISTS model_provider_auth_tokens");
459
+ }
460
+ };
461
+
462
+ // src/db/migrations/steps/2026-09-22-sessions-sandbox.ts
463
+ var sessionsSandbox = {
464
+ name: "2026-09-22-sessions-sandbox",
465
+ // The Session's own sandbox policy (JSON), snapshotted from the server's settings when
466
+ // the Session is created, so a later settings change leaves running Sessions alone.
467
+ // NULL = a row from before this column: it takes the settings in force at its next
468
+ // command and keeps them from then on. Swap-safe: a pushed platform boots against the
469
+ // runtime's already-open database, so the column has to arrive by a migration.
470
+ swapSafe: true,
471
+ up(db) {
472
+ ensureColumn(db, "sessions", "sandbox", "TEXT");
473
+ },
474
+ // Not a DROP: schema.ts declares the column, and dropping it would put every Session
475
+ // back under whatever the settings say.
476
+ down() {
477
+ }
478
+ };
479
+
480
+ // src/db/migrations/steps/2026-09-23-machines-columns.ts
481
+ var machinesColumns = {
482
+ name: "2026-09-23-machines-columns",
483
+ // A machines table can predate `machines` — a data root that ran the machines line
484
+ // before it was released kept forwards, not sessions — and that migration's IF NOT
485
+ // EXISTS adopted it whatever its columns were, so the first connect failed on the row's
486
+ // insert. Adds what is missing, nullable; a platform rolled back to `machines` declared these
487
+ // columns itself, so there is nothing for it to mind.
488
+ swapSafe: true,
489
+ up(db) {
490
+ ensureColumn(db, "machines", "session_pid", "INTEGER");
491
+ ensureColumn(db, "machines", "platform", "TEXT");
492
+ },
493
+ // Nothing to undo: what this added, `machines` already declares, and a column it found in place
494
+ // was never this migration's to take away.
495
+ down() {
496
+ }
497
+ };
498
+
499
+ // src/db/migrations/steps/2026-09-23-model-tables-adoption.ts
500
+ var modelTablesAdoption = {
501
+ name: "2026-09-23-model-tables-adoption",
502
+ // A data root that ran the chain before it was restacked onto main (2026-09-23) is
503
+ // stamped 16 under THAT line's numbering, where 9 and 10 were 2026-09-22-sessions-sandbox and
504
+ // 2026-09-23-machines-columns. This line numbers main's 2026-09-17-model-promotions and
505
+ // 2026-09-21-model-provider-auth-tokens 9 and 10 and everything after them two higher, so such a
506
+ // root reads both as already applied, reaches 18 without `model_promotions` or
507
+ // `model_provider_auth_tokens`, and answers 500 wherever cost or provider auth reads
508
+ // them (the models page, an organization's overview). Seen on the release instance at
509
+ // the first push of the restacked line.
510
+ //
511
+ // Re-runs 9's and 10's own `up` — the frozen DDL, both `IF NOT EXISTS`, so a root that
512
+ // took them in their proper place finds its work done. The ledger ended the numbering
513
+ // hazard: adopting a numbered root runs 2026-09-17-model-promotions and 2026-09-21-model-provider-auth-tokens
514
+ // themselves. Remove together with the ledger's adoption of numbered roots (index.ts).
515
+ swapSafe: true,
516
+ up(db) {
517
+ db.exec(`
518
+ CREATE TABLE IF NOT EXISTS model_promotions (
519
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
520
+ provider TEXT NOT NULL,
521
+ model_id TEXT NOT NULL,
522
+ discount REAL NOT NULL CHECK (discount > 0 AND discount < 1),
523
+ updated_at TEXT NOT NULL,
524
+ PRIMARY KEY (project_id, provider, model_id)
525
+ );
526
+ CREATE TABLE IF NOT EXISTS model_provider_auth_tokens (
527
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
528
+ provider TEXT NOT NULL,
529
+ refresh_token TEXT NOT NULL,
530
+ access_token_expires_at TEXT,
531
+ updated_at TEXT NOT NULL,
532
+ PRIMARY KEY (project_id, provider)
533
+ );
534
+ `);
535
+ },
536
+ // Nothing to undo: the tables are 2026-09-17-model-promotions' and 2026-09-21-model-provider-auth-tokens', and
537
+ // their own downs drop them.
538
+ down() {
539
+ }
540
+ };
541
+
542
+ // src/db/migrations/steps/2026-10-04-browser-extensions.ts
543
+ var browserExtensions = {
544
+ name: "2026-10-04-browser-extensions",
545
+ // Additive: one new table and its index. The Chrome backend's pairings — one row per
546
+ // PenguinHarness Browser extension a user paired, its token stored hashed. A predecessor
547
+ // build never reads the table, so a rollback survives it; the paired extensions then simply
548
+ // fail to connect until a build that knows them is back.
549
+ swapSafe: true,
550
+ up(db) {
551
+ db.exec(`
552
+ 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 \u2014 a lost row means pairing that Chrome again
553
+ extension_id TEXT PRIMARY KEY,
554
+ user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
555
+ token_hash TEXT NOT NULL UNIQUE,
556
+ name TEXT NOT NULL,
557
+ version TEXT NOT NULL,
558
+ created_at TEXT NOT NULL,
559
+ last_seen_at TEXT,
560
+ revoked_at TEXT
561
+ );
562
+ CREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);
563
+ `);
564
+ },
565
+ // LOSES every pairing: each user's Chrome has to be paired again (a new code from the
566
+ // Browser panel) before agents can drive it.
567
+ down(db) {
568
+ db.exec(`
569
+ DROP INDEX IF EXISTS idx_browser_extensions_user;
570
+ DROP TABLE IF EXISTS browser_extensions;
571
+ `);
572
+ }
573
+ };
574
+
575
+ // src/db/migrations/steps/2026-10-10-agent-api.ts
576
+ var agentApi = {
577
+ name: "2026-10-10-agent-api",
578
+ // Additive: two new tables and an index. The Agent API's per-Agent settings (the switch,
579
+ // keyless access, the approval mode API Sessions are created with) and its keys, stored
580
+ // hashed. A predecessor build never reads them and serves no /api/amsp route, so a
581
+ // rollback survives it: callers get 404 until a build that knows the tables is back.
582
+ swapSafe: true,
583
+ up(db) {
584
+ db.exec(`
585
+ CREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files
586
+ project_id TEXT NOT NULL,
587
+ agent_id TEXT NOT NULL,
588
+ enabled INTEGER NOT NULL DEFAULT 0,
589
+ open INTEGER NOT NULL DEFAULT 0,
590
+ approval_mode TEXT NOT NULL DEFAULT 'allow-all',
591
+ updated_at TEXT NOT NULL,
592
+ PRIMARY KEY (project_id, agent_id)
593
+ );
594
+ 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
595
+ key_id TEXT PRIMARY KEY,
596
+ project_id TEXT NOT NULL,
597
+ agent_id TEXT NOT NULL,
598
+ token_hash TEXT NOT NULL UNIQUE,
599
+ prefix TEXT NOT NULL,
600
+ name TEXT NOT NULL,
601
+ created_by TEXT NOT NULL REFERENCES users(user_id),
602
+ created_at TEXT NOT NULL,
603
+ last_used_at TEXT
604
+ );
605
+ CREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);
606
+ `);
607
+ },
608
+ // LOSES every Agent's API settings and every key: each exposed Agent reads as disabled
609
+ // again (404 to its callers), and every caller needs a newly created key once it is back
610
+ // on — no file holds a copy of either.
611
+ down(db) {
612
+ db.exec(`
613
+ DROP INDEX IF EXISTS idx_agent_api_keys_agent;
614
+ DROP TABLE IF EXISTS agent_api_keys;
615
+ DROP TABLE IF EXISTS agent_api;
616
+ `);
617
+ }
618
+ };
619
+
620
+ // src/db/migrations/steps/2026-10-12-messaging-conversations.ts
621
+ var messagingConversations = {
622
+ name: "2026-10-12-messaging-conversations",
623
+ // Additive: one new table. The WeChat connector's per-(bot, user) delivery state — the
624
+ // context token every send must echo, how many sends it has funded, and replies held for
625
+ // the user's next message. A predecessor build never reads it and keeps its tokens in
626
+ // memory as it always did, so a rollback survives it.
627
+ swapSafe: true,
628
+ up(db) {
629
+ db.exec(`
630
+ 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) \u2014 see MessagingBindingsRepo
631
+ channel TEXT NOT NULL,
632
+ account_id TEXT NOT NULL,
633
+ chat_id TEXT NOT NULL,
634
+ state_json TEXT NOT NULL,
635
+ updated_at TEXT NOT NULL,
636
+ PRIMARY KEY (channel, account_id, chat_id)
637
+ );
638
+ `);
639
+ },
640
+ // LOSES every stored context token and every held reply: replies sent before each user's
641
+ // next message are refused again, and what was held never arrives.
642
+ down(db) {
643
+ db.exec("DROP TABLE IF EXISTS messaging_conversations");
644
+ }
645
+ };
646
+
647
+ // src/db/migrations/steps/2026-10-12-sessions-kept-at.ts
648
+ var sessionsKeptAt = {
649
+ name: "2026-10-12-sessions-kept-at",
650
+ // The "keep in sidebar" mark: written when the user unarchives a Session, cleared when they
651
+ // archive it. The listing rule files a background Session (api / schedule / cli) away unless
652
+ // it carries the mark, so existing rows are listed by the rule as they stand and nothing is
653
+ // rewritten. Swap-safe: a pushed platform boots against the runtime's already-open database,
654
+ // so the column has to arrive by a migration.
655
+ swapSafe: true,
656
+ up(db) {
657
+ ensureColumn(db, "sessions", "kept_at", "TEXT");
658
+ },
659
+ // Not a DROP: schema.ts declares the column, and dropping it would file every kept
660
+ // background Session away again.
661
+ down() {
662
+ }
663
+ };
664
+
665
+ // src/db/migrations/steps/2026-10-14-agent-api-concurrency.ts
666
+ var agentApiConcurrency = {
667
+ name: "2026-10-14-agent-api-concurrency",
668
+ // How many of an Agent API Agent's runs may be live at once.
669
+ // Retain while a supported data root can predate this column; the maintainer raising
670
+ // that baseline removes this upgrade once every supported data root has it.
671
+ swapSafe: true,
672
+ up(db) {
673
+ ensureColumn(db, "agent_api", "max_concurrent_runs", "INTEGER NOT NULL DEFAULT 4");
674
+ },
675
+ // Keep the configured limit on rollback; older builds ignore this column.
676
+ down() {
677
+ }
678
+ };
679
+
680
+ // src/db/migrations/steps/2026-10-14-agent-api-session-settings.ts
681
+ var agentApiSessionSettings = {
682
+ name: "2026-10-14-agent-api-session-settings",
683
+ // The per-Agent API defaults a new Session starts with: which provider, model, thinking
684
+ // level and workspace it opens in. Nullable additions preserve existing keys, exposure,
685
+ // approvals and new-Session defaults.
686
+ // Retain while a supported data root can predate these columns; the maintainer raising
687
+ // that baseline removes this upgrade after all supported data roots have them.
688
+ swapSafe: true,
689
+ up(db) {
690
+ ensureColumn(db, "agent_api", "provider", "TEXT");
691
+ ensureColumn(db, "agent_api", "model_id", "TEXT");
692
+ ensureColumn(db, "agent_api", "thinking_level", "TEXT");
693
+ ensureColumn(db, "agent_api", "workspace", "TEXT");
694
+ },
695
+ // Keep the saved defaults on rollback; older builds ignore the additional columns.
696
+ down() {
697
+ }
698
+ };
699
+
700
+ // src/db/migrations/steps/2026-10-16-machines-adopted-at.ts
701
+ var machinesAdoptedAt = {
702
+ name: "2026-10-16-machines-adopted-at",
703
+ // When this server adopted a machine (first recorded it): the Sessions that machine held
704
+ // before then read as CLI tasks through this server (session-sources.ts sourceSeenBy). A
705
+ // machine recorded before this column has none and never gets one, so the rule does not apply
706
+ // to it (user decision, 2026-10-15) — nothing on either side is rewritten. Swap-safe: a pushed platform boots against the runtime's
707
+ // already-open database, so the column has to arrive by a migration.
708
+ swapSafe: true,
709
+ up(db) {
710
+ ensureColumn(db, "machines", "adopted_at", "TEXT");
711
+ },
712
+ // Keep the adoption times on rollback; older builds ignore the column.
713
+ down() {
714
+ }
715
+ };
716
+
717
+ // src/db/migrations/steps/2026-10-26-user-drafts.ts
718
+ var userDrafts = {
719
+ name: "2026-10-26-user-drafts",
720
+ // Additive: two new tables and two indexes. A user's unsent drafts and the custom background
721
+ // image, which used to live only in the browser that made them. A predecessor build never
722
+ // reads either table, so a rollback survives it; its Web App then keeps drafts and the image
723
+ // in that browser alone, as it always did.
724
+ swapSafe: true,
725
+ up(db) {
726
+ db.exec(`
727
+ CREATE TABLE IF NOT EXISTS user_drafts ( -- a user's unsent drafts (composer text, parked conversations, form answers), so they follow the account to another browser; bounded per user, dropped with the Session or Project they belong to
728
+ user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
729
+ draft_key TEXT NOT NULL,
730
+ session_id TEXT,
731
+ project_id TEXT,
732
+ value_json TEXT NOT NULL,
733
+ updated_at TEXT NOT NULL,
734
+ PRIMARY KEY (user_id, draft_key)
735
+ );
736
+ CREATE INDEX IF NOT EXISTS idx_user_drafts_session ON user_drafts(session_id);
737
+ CREATE INDEX IF NOT EXISTS idx_user_drafts_project ON user_drafts(project_id);
738
+ CREATE TABLE IF NOT EXISTS user_background_images ( -- the custom background image of a user's appearance settings, apart from ui_prefs so the megabyte it may hold is read only by the one route that serves it
739
+ user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,
740
+ image TEXT NOT NULL,
741
+ image_id TEXT NOT NULL,
742
+ updated_at TEXT NOT NULL
743
+ );
744
+ `);
745
+ },
746
+ // LOSES every draft and background image the accounts hold on the server. A browser that still
747
+ // caches them keeps showing its own copy; another browser starts without them.
748
+ down(db) {
749
+ db.exec(`
750
+ DROP INDEX IF EXISTS idx_user_drafts_project;
751
+ DROP INDEX IF EXISTS idx_user_drafts_session;
752
+ DROP TABLE IF EXISTS user_drafts;
753
+ DROP TABLE IF EXISTS user_background_images;
754
+ `);
755
+ }
756
+ };
757
+
758
+ // src/db/migrations/index.ts
759
+ var MIGRATIONS = [
760
+ messagingBindings,
761
+ messagingDeliveryFlags,
762
+ dropGoalState,
763
+ machines,
764
+ userProfile,
765
+ companyModeOrgCaches,
766
+ companyModeChannels,
767
+ companyModeDeskNotices,
768
+ modelPromotions,
769
+ modelProviderAuthTokens,
770
+ sessionsSandbox,
771
+ machinesColumns,
772
+ browserExtensions,
773
+ agentApi,
774
+ messagingConversations,
775
+ sessionsKeptAt,
776
+ agentApiSessionSettings,
777
+ agentApiConcurrency,
778
+ machinesAdoptedAt,
779
+ modelTablesAdoption,
780
+ userDrafts
781
+ ];
782
+ function migrate2(db, options = {}) {
783
+ return migrate(db, MIGRATIONS, options);
784
+ }
785
+
786
+ // src/db/schema.ts
787
+ var MODEL_PROMOTIONS_SQL = `
788
+ 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
789
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
790
+ provider TEXT NOT NULL,
791
+ model_id TEXT NOT NULL,
792
+ discount REAL NOT NULL CHECK (discount > 0 AND discount < 1), -- fraction off the row's list price: billed = list \xD7 (1 \u2212 discount)
793
+ updated_at TEXT NOT NULL,
794
+ PRIMARY KEY (project_id, provider, model_id)
795
+ );`;
796
+ var MODEL_PROVIDER_AUTH_TOKENS_SQL = `
797
+ 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.
798
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
799
+ provider TEXT NOT NULL,
800
+ refresh_token TEXT NOT NULL,
801
+ access_token_expires_at TEXT,
802
+ updated_at TEXT NOT NULL,
803
+ PRIMARY KEY (project_id, provider)
804
+ );`;
805
+ var SCHEMA_SQL = `
806
+ CREATE TABLE IF NOT EXISTS users (
807
+ user_id TEXT PRIMARY KEY, -- semantic id doubles as login name: ^[a-z][a-z0-9_-]{1,31}$
808
+ password_hash TEXT NOT NULL, -- scrypt$N$r$p$salt$hash(base64)
809
+ is_admin INTEGER NOT NULL DEFAULT 0, -- 1 for the built-in admin (seeded at startup)
810
+ password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it
811
+ display_name TEXT, -- nickname shown in place of user_id (1-32 characters); NULL = never set, surfaces show the id
812
+ avatar TEXT, -- avatar as a data URL (image/png|jpeg|webp, <= 131072 characters); NULL = never set, surfaces draw the letter placeholder
813
+ created_at TEXT NOT NULL
814
+ );
815
+ -- Server-side sessions backing the HttpOnly cookie: the cookie carries a 32-byte random
816
+ -- token, the row stores only its sha256. A session outlives a restart (it is on disk), which
817
+ -- is why the model is a row and not a signed statement.
818
+ CREATE TABLE IF NOT EXISTS auth_sessions (
819
+ token_hash TEXT PRIMARY KEY, -- sha256(token) hex; the cookie stores only the raw token
820
+ user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
821
+ created_at TEXT NOT NULL,
822
+ expires_at TEXT NOT NULL, -- 30-day sliding renewal, topped up in place when <29 days remain
823
+ via TEXT -- 'password'|'desktop'|'setup'|'cli'|'remote'; NULL = legacy (password)
824
+ );
825
+ -- deleteExpired runs on every login and mint, deleteByUser on every admin reset; without
826
+ -- these both scan the whole table.
827
+ CREATE INDEX IF NOT EXISTS idx_auth_sessions_expires ON auth_sessions(expires_at);
828
+ CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(user_id);
829
+
830
+ CREATE TABLE IF NOT EXISTS projects (
831
+ project_id TEXT PRIMARY KEY, -- directory name doubles as id; display name lives in project_config.toml
832
+ owner_user_id TEXT NOT NULL REFERENCES users(user_id),
833
+ created_at TEXT NOT NULL
834
+ );
835
+ CREATE TABLE IF NOT EXISTS project_members ( -- member grants only; owners are not stored here
836
+ project_id TEXT NOT NULL REFERENCES projects(project_id) ON DELETE CASCADE,
837
+ user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
838
+ created_at TEXT NOT NULL,
839
+ PRIMARY KEY (project_id, user_id)
840
+ );
841
+ ${MODEL_PROMOTIONS_SQL}
842
+ ${MODEL_PROVIDER_AUTH_TOKENS_SQL}
843
+ CREATE TABLE IF NOT EXISTS agents ( -- index only; name/description live in system_config.yaml
844
+ project_id TEXT NOT NULL,
845
+ agent_id TEXT NOT NULL,
846
+ created_at TEXT NOT NULL,
847
+ PRIMARY KEY (project_id, agent_id)
848
+ );
849
+ CREATE TABLE IF NOT EXISTS sessions (
850
+ session_id TEXT PRIMARY KEY,
851
+ project_id TEXT NOT NULL,
852
+ agent_id TEXT NOT NULL,
853
+ 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)
854
+ model_id TEXT NOT NULL, -- upstream model id of the current model (sent to MMSP as-is; never concatenate <provider>/<id>)
855
+ workspace TEXT NOT NULL,
856
+ approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- allow-all|deny-all|read-only|always-ask
857
+ thinking_level TEXT, -- level pinned for THIS session (none|low|medium|high|xhigh|max); NULL=not pinned, runs follow the Agent config
858
+ title TEXT, -- auto-generated by the model after the first exchange; NULL=not yet (frontend shows "New chat")
859
+ archived_at TEXT, -- the user archived it (ISO time); NULL = not archived by hand (the listing rule may still file it away)
860
+ 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.
861
+ 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
862
+ has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)
863
+ fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deleted
864
+ sandbox TEXT, -- the Session's sandbox policy snapshot (JSON SandboxSettings); NULL = legacy row, snapshotted at its next command
865
+ 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
866
+ created_at TEXT NOT NULL
867
+ ); -- 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' \u2192 company)
868
+ CREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);
869
+ CREATE TABLE IF NOT EXISTS usage_records (
870
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
871
+ ts TEXT NOT NULL,
872
+ date TEXT NOT NULL, -- local date yyyy-mm-dd (aggregation key; same convention as Trace date directories)
873
+ project_id TEXT NOT NULL,
874
+ agent_id TEXT NOT NULL,
875
+ session_id TEXT NOT NULL, -- top-level Session (child-session usage counts toward its main Session)
876
+ origin_session_id TEXT, -- immediate source child Session (last of the origin chain); NULL=main session
877
+ provider TEXT NOT NULL, -- provider group: paired with model_id as the attribution key; always GROUP BY provider, model_id
878
+ model_id TEXT NOT NULL, -- upstream model id (paired with provider; same model_id across providers aggregates separately)
879
+ cache_read INTEGER NOT NULL,
880
+ cache_write INTEGER NOT NULL,
881
+ output INTEGER NOT NULL,
882
+ total INTEGER NOT NULL, -- from token_usage.request (one row per Request)
883
+ status TEXT NOT NULL DEFAULT 'completed' -- request outcome: completed=success (with tokens); others=failure (0 tokens, for success rate)
884
+ ); -- cost is not stored: computed at query time from current pricing
885
+ CREATE INDEX IF NOT EXISTS idx_usage_project_date ON usage_records(project_id, date);
886
+ CREATE 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
887
+ CREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the Costs page's "Errors" tab)
888
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
889
+ ts TEXT NOT NULL,
890
+ date TEXT NOT NULL, -- local date yyyy-mm-dd (same convention as usage_records)
891
+ project_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project context
892
+ agent_id TEXT,
893
+ session_id TEXT,
894
+ source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule | messaging | organization | id_suggest | plugin
895
+ kind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)
896
+ code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...
897
+ status INTEGER, -- HTTP status code; NULL for non-HTTP sources
898
+ message TEXT NOT NULL -- truncated to 500 chars (no stack stored: stacks go to logs only)
899
+ );
900
+ CREATE INDEX IF NOT EXISTS idx_error_project_date ON error_records(project_id, date);
901
+ CREATE TABLE IF NOT EXISTS schedule_state ( -- schedule runtime state (files are declarative intent; the system never writes back)
902
+ project_id TEXT NOT NULL,
903
+ agent_id TEXT NOT NULL,
904
+ name TEXT NOT NULL, -- file name (without .toml) doubles as the identifier
905
+ creator_user_id TEXT, -- creator (recorded on API create; hand-edited file reconciliation falls back to the Project owner)
906
+ start_at_ms INTEGER NOT NULL, -- defines identity: a start_at change counts as a new task instance, resetting fire state
907
+ def_hash TEXT NOT NULL, -- file content fingerprint: any change clears the invalid flag (the file takes effect again after edits)
908
+ last_slot_ms INTEGER, -- latest due slot already consumed (advances on fire or skip; no re-fire across restarts)
909
+ last_fired_at TEXT, -- last actual fire time (for display)
910
+ fired_once INTEGER NOT NULL DEFAULT 0, -- one-shot task has fired
911
+ missed INTEGER NOT NULL DEFAULT 0, -- one-shot task was missed (flagged by startup/registration reconciliation; not backfilled)
912
+ invalid_reason TEXT, -- invalidation reason (e.g. the bound Session was deleted); NULL=healthy
913
+ PRIMARY KEY (project_id, agent_id, name)
914
+ );
915
+ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session \u2194 messaging-channel bot bindings (runtime/messaging/ holds the long connections)
916
+ 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
917
+ channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram' | 'qq' | 'wechat')
918
+ 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 \u2014 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)
919
+ 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)
920
+ enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled \u2014 saving credentials never opens a connection, the explicit state toggle does
921
+ 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
922
+ 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
923
+ 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
924
+ 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 \u2014 telegram appends the forum topic (see telegram-connector.ts chatRefOf), so only that channel's connector may interpret it
925
+ last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)
926
+ 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
927
+ created_at TEXT NOT NULL,
928
+ updated_at TEXT NOT NULL,
929
+ PRIMARY KEY (session_id, channel)
930
+ );
931
+ CREATE 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
932
+ 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) \u2014 see MessagingBindingsRepo
933
+ channel TEXT NOT NULL, -- messaging channel discriminator (only 'wechat' writes rows today)
934
+ account_id TEXT NOT NULL, -- the bot, as messaging_bindings.account_id names it
935
+ chat_id TEXT NOT NULL, -- the connector's own chat id (wechat: the user's ilink_user_id)
936
+ 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
937
+ updated_at TEXT NOT NULL,
938
+ PRIMARY KEY (channel, account_id, chat_id)
939
+ );
940
+ CREATE TABLE IF NOT EXISTS ui_prefs (
941
+ user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,
942
+ prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON
943
+ );
944
+ CREATE TABLE IF NOT EXISTS user_drafts ( -- a user's unsent drafts (composer text, parked conversations, form answers), so they follow the account to another browser; bounded per user, dropped with the Session or Project they belong to
945
+ user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
946
+ draft_key TEXT NOT NULL, -- <kind>:<id> (api/types.ts DRAFT_KINDS)
947
+ session_id TEXT, -- the Session the key names (session / a2ui kinds); NULL otherwise
948
+ project_id TEXT, -- the Project the key names (chat / parked / org / channel kinds); NULL otherwise
949
+ value_json TEXT NOT NULL, -- the draft as the Web App wrote it
950
+ updated_at TEXT NOT NULL, -- last write (ISO); the oldest go first when the user's bound is exceeded
951
+ PRIMARY KEY (user_id, draft_key)
952
+ );
953
+ CREATE INDEX IF NOT EXISTS idx_user_drafts_session ON user_drafts(session_id);
954
+ CREATE INDEX IF NOT EXISTS idx_user_drafts_project ON user_drafts(project_id);
955
+ CREATE TABLE IF NOT EXISTS user_background_images ( -- the custom background image of a user's appearance settings, apart from ui_prefs so the megabyte it may hold is read only by the one route that serves it
956
+ user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,
957
+ image TEXT NOT NULL, -- data URL (image/png|jpeg|webp, <= BACKGROUND_IMAGE_MAX_CHARS characters)
958
+ image_id TEXT NOT NULL, -- content hash; mirrored into ui_prefs.backgroundImageId so a browser fetches the image only when it changed
959
+ updated_at TEXT NOT NULL
960
+ );
961
+ 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 \u2014 a lost row means pairing that Chrome again
962
+ extension_id TEXT PRIMARY KEY, -- random id shown in the Web App's list
963
+ user_id TEXT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE,
964
+ token_hash TEXT NOT NULL UNIQUE, -- sha256(token) hex; the extension alone holds the token
965
+ name TEXT NOT NULL, -- how the extension names this Chrome ("Chrome 130 on macOS")
966
+ version TEXT NOT NULL, -- the extension's version, as of its last hello
967
+ created_at TEXT NOT NULL,
968
+ last_seen_at TEXT, -- last connect or disconnect; NULL = never connected
969
+ revoked_at TEXT -- set by Revoke; a revoked token's socket is closed 4003
970
+ );
971
+ CREATE INDEX IF NOT EXISTS idx_browser_extensions_user ON browser_extensions(user_id);
972
+ CREATE TABLE IF NOT EXISTS agent_api ( -- per-Agent public API settings (amsp/routes.ts); NOT rebuildable from files
973
+ project_id TEXT NOT NULL,
974
+ agent_id TEXT NOT NULL,
975
+ enabled INTEGER NOT NULL DEFAULT 0, -- the API tab's switch; off = every /api/amsp request for it is 404 agent_not_found
976
+ open INTEGER NOT NULL DEFAULT 0, -- keyless access: a request without Authorization is accepted; off = 401 unauthorized
977
+ approval_mode TEXT NOT NULL DEFAULT 'allow-all', -- copied onto each new API Session
978
+ provider TEXT, -- NULL pair follows the Project default model
979
+ model_id TEXT,
980
+ thinking_level TEXT, -- NULL follows Agent/Project configuration
981
+ workspace TEXT, -- NULL creates a temporary Workspace
982
+ max_concurrent_runs INTEGER NOT NULL DEFAULT 4,
983
+ updated_at TEXT NOT NULL,
984
+ PRIMARY KEY (project_id, agent_id)
985
+ );
986
+ 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
987
+ key_id TEXT PRIMARY KEY, -- 16 base64url chars, shown in the list
988
+ project_id TEXT NOT NULL,
989
+ agent_id TEXT NOT NULL,
990
+ token_hash TEXT NOT NULL UNIQUE, -- sha256(key) hex
991
+ prefix TEXT NOT NULL, -- the key's first 16 characters ("penguin_" + 8), shown in the list
992
+ name TEXT NOT NULL, -- 1-64 characters
993
+ created_by TEXT NOT NULL REFERENCES users(user_id),
994
+ created_at TEXT NOT NULL,
995
+ last_used_at TEXT -- stamped once per run request that authenticated with it; NULL = never
996
+ );
997
+ CREATE INDEX IF NOT EXISTS idx_agent_api_keys_agent ON agent_api_keys(project_id, agent_id);
998
+ CREATE TABLE IF NOT EXISTS server_settings ( -- admin-level server-global settings (GET/PUT /api/admin/settings)
999
+ key TEXT PRIMARY KEY, -- setting name, e.g. 'proxy_for_app'
1000
+ value TEXT NOT NULL -- JSON-encoded value; an absent row means the setting's built-in default
1001
+ );
1002
+ CREATE TABLE IF NOT EXISTS machine ( -- this server's OWN identity, minted here and never assigned from outside (what 'penguin server status' reports)
1003
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1), -- exactly one row, enforced by the schema rather than by convention
1004
+ machine_id TEXT NOT NULL -- 16 base64url characters; what every stored reference to this machine points at
1005
+ );
1006
+ CREATE TABLE IF NOT EXISTS machines ( -- one row per machine this server installed on or reached (machines/service.ts)
1007
+ address TEXT PRIMARY KEY, -- 'ssh:<alias>'
1008
+ machine_id TEXT, -- that machine's own id, once heard
1009
+ version TEXT, -- what this server last installed there; NULL = never
1010
+ installed_at TEXT,
1011
+ session_pid INTEGER, -- the ssh session this server holds to it; what a successor App closes after a hot swap
1012
+ remote_port INTEGER, -- its server's port over there, as of the last connect
1013
+ platform TEXT, -- linux | darwin | win32, as the install found it: the shell dialect the status probe speaks to it in
1014
+ 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
1015
+ );
1016
+ CREATE TABLE IF NOT EXISTS machine_project ( -- which machines a Project uses; no row = none yet. Follows the Project out, like project_members
1017
+ project_id TEXT PRIMARY KEY REFERENCES projects(project_id) ON DELETE CASCADE,
1018
+ addresses TEXT NOT NULL -- JSON array of 'ssh:<alias>'
1019
+ );
1020
+ CREATE 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 \u2014 consumers reconcile + retry on a miss, so a stale index costs one extra scan, never a false 404
1021
+ project_id TEXT NOT NULL,
1022
+ agent_id TEXT NOT NULL,
1023
+ session_id TEXT NOT NULL,
1024
+ 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)
1025
+ date TEXT NOT NULL, -- date directory name (local yyyy-mm-dd)
1026
+ 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)
1027
+ 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
1028
+ PRIMARY KEY (project_id, agent_id, session_id, file_index)
1029
+ );
1030
+ CREATE INDEX IF NOT EXISTS idx_trace_files_agent_date ON trace_files(project_id, agent_id, date);
1031
+ CREATE INDEX IF NOT EXISTS idx_trace_files_session ON trace_files(session_id);
1032
+ CREATE 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)
1033
+ session_id TEXT PRIMARY KEY,
1034
+ project_id TEXT NOT NULL,
1035
+ agent_id TEXT NOT NULL,
1036
+ 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' \u2014 readRecordedSource); 'benchmark' from older rows reads as 'cli' (normalizeSessionSource; meaningless while meta_read = 0)
1037
+ workspace TEXT NOT NULL DEFAULT '',
1038
+ title TEXT, -- first-prompt fallback title (sessions.title always wins when present)
1039
+ 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)
1040
+ model_id TEXT,
1041
+ first_ts TEXT, -- first record's timestamp (adoption's createdAt fallback when the id embeds no time)
1042
+ meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session
1043
+ );
1044
+ CREATE INDEX IF NOT EXISTS idx_trace_sessions_agent ON trace_sessions(project_id, agent_id);
1045
+ 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 mention-chain accounting and reads 0 after a rebuild
1046
+ session_id TEXT PRIMARY KEY,
1047
+ project_id TEXT NOT NULL,
1048
+ org_id TEXT NOT NULL,
1049
+ agent_id TEXT NOT NULL,
1050
+ current INTEGER NOT NULL DEFAULT 1,
1051
+ trigger_hop INTEGER NOT NULL DEFAULT 0
1052
+ );
1053
+ CREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);
1054
+ CREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header
1055
+ project_id TEXT NOT NULL,
1056
+ org_id TEXT NOT NULL,
1057
+ ticket_id TEXT NOT NULL,
1058
+ session_id TEXT NOT NULL,
1059
+ agent_id TEXT NOT NULL,
1060
+ trigger_hop INTEGER NOT NULL DEFAULT 0,
1061
+ PRIMARY KEY (project_id, org_id, ticket_id, session_id)
1062
+ );
1063
+ CREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);
1064
+ CREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state
1065
+ project_id TEXT NOT NULL,
1066
+ org_id TEXT NOT NULL,
1067
+ agent_id TEXT NOT NULL,
1068
+ name TEXT NOT NULL,
1069
+ start_at_ms INTEGER NOT NULL,
1070
+ def_hash TEXT NOT NULL,
1071
+ last_slot_ms INTEGER,
1072
+ last_fired_at TEXT,
1073
+ fired_once INTEGER NOT NULL DEFAULT 0,
1074
+ missed INTEGER NOT NULL DEFAULT 0,
1075
+ invalid_reason TEXT,
1076
+ last_outcome TEXT,
1077
+ PRIMARY KEY (project_id, org_id, agent_id, name)
1078
+ );
1079
+ 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
1080
+ project_id TEXT NOT NULL,
1081
+ org_id TEXT NOT NULL,
1082
+ ticket_id TEXT NOT NULL,
1083
+ status TEXT NOT NULL,
1084
+ owner TEXT NOT NULL DEFAULT '',
1085
+ blocked TEXT NOT NULL DEFAULT '',
1086
+ blocked_by TEXT NOT NULL DEFAULT '',
1087
+ PRIMARY KEY (project_id, org_id, ticket_id)
1088
+ );
1089
+ CREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file
1090
+ project_id TEXT NOT NULL,
1091
+ org_id TEXT NOT NULL,
1092
+ channel_id TEXT NOT NULL,
1093
+ date TEXT NOT NULL,
1094
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
1095
+ PRIMARY KEY (project_id, org_id, channel_id, date)
1096
+ );
1097
+ CREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel
1098
+ project_id TEXT NOT NULL,
1099
+ org_id TEXT NOT NULL,
1100
+ channel_id TEXT NOT NULL,
1101
+ user_id TEXT NOT NULL,
1102
+ last_read_id TEXT NOT NULL,
1103
+ PRIMARY KEY (project_id, org_id, channel_id, user_id)
1104
+ );
1105
+ 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
1106
+ project_id TEXT NOT NULL,
1107
+ org_id TEXT NOT NULL,
1108
+ agent_id TEXT NOT NULL,
1109
+ period TEXT NOT NULL,
1110
+ warned_at TEXT,
1111
+ paused_at TEXT,
1112
+ PRIMARY KEY (project_id, org_id, agent_id, period)
1113
+ );
1114
+ 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
1115
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
1116
+ project_id TEXT NOT NULL,
1117
+ org_id TEXT NOT NULL,
1118
+ agent_id TEXT NOT NULL,
1119
+ ticket_id TEXT NOT NULL,
1120
+ change TEXT NOT NULL,
1121
+ at TEXT NOT NULL
1122
+ );
1123
+ CREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);
1124
+ `;
1125
+
1126
+ // src/db/database.ts
1127
+ var sqlite = process.getBuiltinModule("node:sqlite");
1128
+ function openExistingDatabase(dbPath) {
1129
+ const db = new sqlite.DatabaseSync(dbPath);
1130
+ db.exec("PRAGMA foreign_keys = ON;");
1131
+ db.exec("PRAGMA busy_timeout = 5000;");
1132
+ return db;
1133
+ }
1134
+ function openDatabaseReadOnly(dbPath) {
1135
+ const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
1136
+ db.exec("PRAGMA busy_timeout = 5000;");
1137
+ return db;
1138
+ }
1139
+ function openDatabase(dbPath) {
1140
+ if (dbPath !== ":memory:") {
1141
+ mkdirSync(path.dirname(dbPath), { recursive: true });
1142
+ }
1143
+ const db = new sqlite.DatabaseSync(dbPath);
1144
+ db.exec("PRAGMA journal_mode = WAL;");
1145
+ db.exec("PRAGMA busy_timeout = 5000;");
1146
+ db.exec("PRAGMA foreign_keys = ON;");
1147
+ db.exec(SCHEMA_SQL);
1148
+ ensureColumn(db, "sessions", "client", "TEXT");
1149
+ ensureColumn(db, "sessions", "has_trace", "INTEGER NOT NULL DEFAULT 0");
1150
+ ensureColumn(db, "sessions", "fork_count", "INTEGER NOT NULL DEFAULT 0");
1151
+ ensureColumn(db, "sessions", "thinking_level", "TEXT");
1152
+ ensureColumn(db, "sessions", "sandbox", "TEXT");
1153
+ ensureColumn(db, "auth_sessions", "via", "TEXT");
1154
+ ensureColumn(db, "trace_files", "page_stats", "TEXT");
1155
+ ensureColumn(db, "messaging_bindings", "line_per_message", "INTEGER NOT NULL DEFAULT 0");
1156
+ ensureColumn(db, "messaging_bindings", "final_reply_only", "INTEGER NOT NULL DEFAULT 0");
1157
+ ensureColumn(db, "messaging_bindings", "render_markdown", "INTEGER NOT NULL DEFAULT 1");
1158
+ ensureColumn(db, "messaging_bindings", "last_inbound_message_id", "TEXT");
1159
+ db.exec("DROP INDEX IF EXISTS idx_usage_session");
1160
+ db.exec("DROP INDEX IF EXISTS idx_messaging_account");
1161
+ upgradeLastActiveAt(db);
1162
+ migrate2(db);
1163
+ return db;
1164
+ }
1165
+ function upgradeLastActiveAt(db) {
1166
+ db.exec("BEGIN");
1167
+ try {
1168
+ if (ensureColumn(db, "sessions", "last_active_at", "TEXT")) {
1169
+ db.exec(
1170
+ `UPDATE sessions SET last_active_at = COALESCE(
1171
+ (SELECT MAX(ts) FROM usage_records WHERE usage_records.session_id = sessions.session_id),
1172
+ created_at
1173
+ )`
1174
+ );
1175
+ }
1176
+ db.exec("COMMIT");
1177
+ } catch (err) {
1178
+ db.exec("ROLLBACK");
1179
+ throw err;
1180
+ }
1181
+ }
1182
+ function ensureColumn(db, table, column, ddl) {
1183
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all();
1184
+ if (cols.some((c) => c.name === column)) return false;
1185
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);
1186
+ return true;
1187
+ }
1188
+
1189
+ export {
1190
+ migrate2 as migrate,
1191
+ openExistingDatabase,
1192
+ openDatabaseReadOnly,
1193
+ openDatabase
1194
+ };
1195
+ //# sourceMappingURL=chunk-5YLLSHY3.js.map