@prismshadow/penguin-server 0.2.15 → 0.2.17

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 (124) hide show
  1. package/README.md +1 -1
  2. package/dist/api/types.d.ts +318 -86
  3. package/dist/api/types.js +9 -3
  4. package/dist/auth-token.d.ts +1 -1
  5. package/dist/auth-token.js +2 -2
  6. package/dist/{chunk-HMTT2PX4.js → chunk-2LZDP26O.js} +8 -5
  7. package/dist/chunk-2LZDP26O.js.map +1 -0
  8. package/dist/{chunk-LPPVGHYD.js → chunk-BL4U7GYY.js} +2 -2
  9. package/dist/chunk-BL4U7GYY.js.map +1 -0
  10. package/dist/{chunk-5Z4UCHDB.js → chunk-D3JNA6ZI.js} +69 -6
  11. package/dist/chunk-D3JNA6ZI.js.map +1 -0
  12. package/dist/{chunk-TOOTEEM4.js → chunk-G7GY7PJU.js} +1 -1
  13. package/dist/chunk-G7GY7PJU.js.map +1 -0
  14. package/dist/chunk-GGIINEEK.js +3401 -0
  15. package/dist/chunk-GGIINEEK.js.map +1 -0
  16. package/dist/chunk-HDBZRVA5.js +29 -0
  17. package/dist/chunk-HDBZRVA5.js.map +1 -0
  18. package/dist/{chunk-NVWAYYRX.js → chunk-HPOHMZCH.js} +686 -531
  19. package/dist/chunk-HPOHMZCH.js.map +1 -0
  20. package/dist/{chunk-QFV3ERQO.js → chunk-OQZDL3TR.js} +2 -2
  21. package/dist/hmr/manifest.js +1 -1
  22. package/dist/index.js +9351 -5551
  23. package/dist/index.js.map +1 -1
  24. package/dist/machine-status.js +2 -2
  25. package/dist/model-catalog.d.ts +610 -0
  26. package/dist/model-catalog.js +108 -0
  27. package/dist/model-catalog.js.map +1 -0
  28. package/dist/plugin/index.d.ts +141 -78
  29. package/dist/reset-admin-password.js +3 -4
  30. package/dist/reset-admin-password.js.map +1 -1
  31. package/dist/version-report.js +2 -2
  32. package/package.json +15 -14
  33. package/web-dist/assets/{abnfDiagram-VCTEODGH-CKWh4hoA.js → abnfDiagram-VCTEODGH-DMzkb4l4.js} +1 -1
  34. package/web-dist/assets/{addon-clipboard-DxLqat7q.js → addon-clipboard-BtD2BVSi.js} +1 -1
  35. package/web-dist/assets/{addon-fit-B8oPGPkW.js → addon-fit-Dr6HWsi_.js} +1 -1
  36. package/web-dist/assets/{addon-web-links-C0W5TcK0.js → addon-web-links-VEE3YLzQ.js} +1 -1
  37. package/web-dist/assets/{arc-Dp9EkaAH.js → arc-CvMPOU_B.js} +1 -1
  38. package/web-dist/assets/{architectureDiagram-5GKGNRK7-BQ3LUcle.js → architectureDiagram-5GKGNRK7-Bk65mIBz.js} +1 -1
  39. package/web-dist/assets/{blockDiagram-I7D4REHJ-CZzyU0Jj.js → blockDiagram-I7D4REHJ-D54-XSNs.js} +1 -1
  40. package/web-dist/assets/{c4Diagram-7LVT6UL2-Qps3jeAu.js → c4Diagram-7LVT6UL2-Dm954LSt.js} +1 -1
  41. package/web-dist/assets/channel-CVHI75kz.js +1 -0
  42. package/web-dist/assets/{chunk-2Q5K7J3B-CQMntzuX.js → chunk-2Q5K7J3B-D_LJ_7Cn.js} +1 -1
  43. package/web-dist/assets/{chunk-5VM5RSS4-2H2ZJAte.js → chunk-5VM5RSS4-B8RI4tl3.js} +1 -1
  44. package/web-dist/assets/{chunk-F27PBJKO-B30xCNBv.js → chunk-F27PBJKO-aVSYH9JV.js} +1 -1
  45. package/web-dist/assets/{chunk-IMKFNOWR-Cyfx4zDs.js → chunk-IMKFNOWR-DnkdWeq2.js} +1 -1
  46. package/web-dist/assets/{chunk-JWPE2WC7-DADUytTh.js → chunk-JWPE2WC7-C2pJzKuW.js} +1 -1
  47. package/web-dist/assets/{chunk-POPQ4Y6H-9bjsAxLS.js → chunk-POPQ4Y6H-Bx7Iikzx.js} +1 -1
  48. package/web-dist/assets/{chunk-SVP7TREG-B9xO1VpN.js → chunk-SVP7TREG-qJC2SMqr.js} +1 -1
  49. package/web-dist/assets/{chunk-TICWLB2K-B6oDkrep.js → chunk-TICWLB2K-Crl_BgKI.js} +1 -1
  50. package/web-dist/assets/{chunk-XXDRQBXY-BbU8DR4B.js → chunk-XXDRQBXY-BFFemuGm.js} +1 -1
  51. package/web-dist/assets/classDiagram-ZZMXUADV-CBdzAPFu.js +1 -0
  52. package/web-dist/assets/classDiagram-v2-VYDZK3BY-CBdzAPFu.js +1 -0
  53. package/web-dist/assets/{cose-bilkent-JH36ORCC-pkbuyec-.js → cose-bilkent-JH36ORCC-Bmh2Kx7h.js} +1 -1
  54. package/web-dist/assets/{cynefin-OW5HDTMX-DU9YQQnc.js → cynefin-OW5HDTMX-BveNWnUV.js} +1 -1
  55. package/web-dist/assets/{cynefinDiagram-5FMLGOSQ-3a3XuhQq.js → cynefinDiagram-5FMLGOSQ-85itazbJ.js} +1 -1
  56. package/web-dist/assets/{dagre-GXQ25YYZ-BfZ9C5CZ.js → dagre-GXQ25YYZ-DIZT-KY_.js} +1 -1
  57. package/web-dist/assets/{diagram-S7CK7UJ4-BoGhVBMn.js → diagram-S7CK7UJ4-Dum-g63f.js} +1 -1
  58. package/web-dist/assets/{diagram-UQ7AKVKN-zE67quty.js → diagram-UQ7AKVKN-DallMKJl.js} +1 -1
  59. package/web-dist/assets/{diagram-VSXAHHWV-NihoXeXm.js → diagram-VSXAHHWV-DWELqxfN.js} +1 -1
  60. package/web-dist/assets/{diagram-VX7I27RA-1627np0S.js → diagram-VX7I27RA-BNs0gB9E.js} +1 -1
  61. package/web-dist/assets/{diagram-Z3DM3KII-Ddg_bUan.js → diagram-Z3DM3KII-C9mF9xAd.js} +1 -1
  62. package/web-dist/assets/{ebnfDiagram-PWID7BFC-CmPUOM4j.js → ebnfDiagram-PWID7BFC-D_Diy9HH.js} +1 -1
  63. package/web-dist/assets/{erDiagram-RLTQ6QDP-DiTnEK72.js → erDiagram-RLTQ6QDP-4QTS5VIh.js} +1 -1
  64. package/web-dist/assets/{flowDiagram-HODETNUW-mGQ38tRM.js → flowDiagram-HODETNUW-CliTRrtV.js} +1 -1
  65. package/web-dist/assets/{ganttDiagram-EL5Y4UJY-DU7MlzpW.js → ganttDiagram-EL5Y4UJY-DCRd-Ss4.js} +1 -1
  66. package/web-dist/assets/{gitGraphDiagram-WWUBYQGX-CRE_3vjl.js → gitGraphDiagram-WWUBYQGX-CTz13GjS.js} +1 -1
  67. package/web-dist/assets/highlighter-BScH1Ud3.js +2 -0
  68. package/web-dist/assets/{highlighter-core-B5CvXcEK.js → highlighter-core-DKz8Z6-I.js} +1 -1
  69. package/web-dist/assets/{highlighter.worker-D6D9fPma.js → highlighter.worker-CKF6ok1g.js} +1 -1
  70. package/web-dist/assets/index-BUvJ5Ctt.js +1299 -0
  71. package/web-dist/assets/index-DRj7nvPY.css +1 -0
  72. package/web-dist/assets/{infoDiagram-27XIBGKW-Cdo6Ar-a.js → infoDiagram-27XIBGKW-DNfTEPAV.js} +1 -1
  73. package/web-dist/assets/{ishikawaDiagram-5VMMS53U-C27pgect.js → ishikawaDiagram-5VMMS53U-B7aCjjG1.js} +1 -1
  74. package/web-dist/assets/{journeyDiagram-3NMN7TZE-CVxtKpLG.js → journeyDiagram-3NMN7TZE-COmDALVr.js} +1 -1
  75. package/web-dist/assets/{kanban-definition-UXKFOSKX-DWA31Da7.js → kanban-definition-UXKFOSKX-BzUfPINh.js} +1 -1
  76. package/web-dist/assets/{layout-DWKCU9PO.js → layout-BwzuPU4M.js} +1 -1
  77. package/web-dist/assets/{linear-BwCthj_k.js → linear-WPZTYjz3.js} +1 -1
  78. package/web-dist/assets/mermaid.core-zKzlwpkw.js +310 -0
  79. package/web-dist/assets/{mindmap-definition-YA3MSWOX-BLEDhbn1.js → mindmap-definition-YA3MSWOX-DCRg7eAx.js} +1 -1
  80. package/web-dist/assets/{pegDiagram-XKGWAZYB-CLEM1SDU.js → pegDiagram-XKGWAZYB-DyphzDLU.js} +1 -1
  81. package/web-dist/assets/{pieDiagram-E7YTZNPT-B__g6eF0.js → pieDiagram-E7YTZNPT-BI5DueGA.js} +1 -1
  82. package/web-dist/assets/powershell-DXrKVo3G.js +1 -0
  83. package/web-dist/assets/powershell-Dpen1YoG.js +1 -0
  84. package/web-dist/assets/{quadrantDiagram-AXDQQJYC-C7VQ2LMY.js → quadrantDiagram-AXDQQJYC-GZxSMY2Z.js} +1 -1
  85. package/web-dist/assets/{railroadDiagram-O6MQD6OU-eWNnzjwS.js → railroadDiagram-O6MQD6OU-DEFCigBf.js} +1 -1
  86. package/web-dist/assets/{requirementDiagram-BXWQKSXE-Bi5qeD4b.js → requirementDiagram-BXWQKSXE-Br0thc4j.js} +1 -1
  87. package/web-dist/assets/{sankeyDiagram-P5KCCOFB-DG1VOpXX.js → sankeyDiagram-P5KCCOFB-DYf0pY67.js} +1 -1
  88. package/web-dist/assets/{sequenceDiagram-WJ2MYXX4-Fhkw73Th.js → sequenceDiagram-WJ2MYXX4-1EFMboX4.js} +1 -1
  89. package/web-dist/assets/{sizeCapture-INFHLROL-D9E_17SF.js → sizeCapture-INFHLROL-BuOFv-5q.js} +1 -1
  90. package/web-dist/assets/{stateDiagram-D77RDMKH-Cs5Y0xhW.js → stateDiagram-D77RDMKH-Bg3H1tjX.js} +1 -1
  91. package/web-dist/assets/stateDiagram-v2-MP3YSRHH-DfaDaPAd.js +1 -0
  92. package/web-dist/assets/{swimlanes-42K2YHIH-t-EocvKZ.js → swimlanes-42K2YHIH-BuOa6Osb.js} +1 -1
  93. package/web-dist/assets/swimlanesDiagram-VR7AAH4N-BopAC7b8.js +8 -0
  94. package/web-dist/assets/{timeline-definition-24CTP7MA-CozGCxuA.js → timeline-definition-24CTP7MA-BDekfdDT.js} +1 -1
  95. package/web-dist/assets/{vennDiagram-4TSXK5OY-ewU8ycSa.js → vennDiagram-4TSXK5OY-DnC09UI4.js} +1 -1
  96. package/web-dist/assets/{wardleyDiagram-VM6X3IG4-DuAhDu-0.js → wardleyDiagram-VM6X3IG4-BXKvxuZQ.js} +1 -1
  97. package/web-dist/assets/{xterm-v5e56GC9.js → xterm-oY4DYg5s.js} +1 -1
  98. package/web-dist/assets/{xychartDiagram-S5SC5T6Z-BxGuZO23.js → xychartDiagram-S5SC5T6Z-DdDC1VLb.js} +1 -1
  99. package/web-dist/index.html +12 -6
  100. package/web-dist/{workflow-ui.css → workbench-ui.css} +72 -67
  101. package/dist/benchmark-package.d.ts +0 -39
  102. package/dist/benchmark-package.js +0 -97
  103. package/dist/benchmark-package.js.map +0 -1
  104. package/dist/chunk-54E64LWB.js +0 -63
  105. package/dist/chunk-54E64LWB.js.map +0 -1
  106. package/dist/chunk-5Z4UCHDB.js.map +0 -1
  107. package/dist/chunk-HMTT2PX4.js.map +0 -1
  108. package/dist/chunk-JKJXQTHH.js +0 -19
  109. package/dist/chunk-JKJXQTHH.js.map +0 -1
  110. package/dist/chunk-LPPVGHYD.js.map +0 -1
  111. package/dist/chunk-NVWAYYRX.js.map +0 -1
  112. package/dist/chunk-Q4ON2L6E.js +0 -52
  113. package/dist/chunk-Q4ON2L6E.js.map +0 -1
  114. package/dist/chunk-TOOTEEM4.js.map +0 -1
  115. package/web-dist/assets/channel--PblgLlC.js +0 -1
  116. package/web-dist/assets/classDiagram-ZZMXUADV-mn8tbuqa.js +0 -1
  117. package/web-dist/assets/classDiagram-v2-VYDZK3BY-mn8tbuqa.js +0 -1
  118. package/web-dist/assets/highlighter-CzfXQ6yd.js +0 -2
  119. package/web-dist/assets/index-BdG4qRyI.js +0 -1275
  120. package/web-dist/assets/index-W-xYFoIm.css +0 -1
  121. package/web-dist/assets/mermaid.core-BcTrmPOv.js +0 -310
  122. package/web-dist/assets/stateDiagram-v2-MP3YSRHH-CEM51fAf.js +0 -1
  123. package/web-dist/assets/swimlanesDiagram-VR7AAH4N-BrR66vrK.js +0 -8
  124. /package/dist/{chunk-QFV3ERQO.js.map → chunk-OQZDL3TR.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/@prismshadow+penguin-hmr@file+packages+hmr_supports-color@10.2.2_ws@8.21.0/node_modules/@prismshadow/penguin-hmr/src/manifest.ts"],"sourcesContent":["/**\n * The harness.json shape (`<root>/hmr/harness.json`) and pure readers over it.\n *\n * Split out of host.ts so a reader never needs a running HmrHost: `penguin` is a\n * separate, short-lived process per invocation (see packages/cli/src/index.ts) — it\n * has no host instance to ask, only the data root's own harness.json on disk.\n * `resolveCliBundlePath` is that reader: a plain disk read, no HTTP, no boot, no\n * in-memory state.\n *\n * ONE atomic version, THREE independent artifacts: `platform`, `cli`, and `web` are\n * always written together by HmrHost's single merged upgrade path (see host.ts's\n * persistVersion), but each is content-addressed and stored on its own — a push to\n * POST /api/hmr/upgrade carries `platform` and `cli` as two separate single-file ESM\n * sources, so `cli.bundle` points at its OWN file, a different sha from\n * `platform.bundle`. They are read back together too (see host.ts's restore): a\n * partial record (e.g. `platform` present but `web` or `cli` missing) is never\n * trusted — the whole version is treated as absent instead of partially applied.\n */\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { HarnessInfo } from \"@prismshadow/penguin-core\";\n\n/**\n * The committed on-disk record: a runtime restart resumes exactly this CODE (platform,\n * cli, web). It carries no STATE — a restart always boots the resumed platform bundle\n * against its own fresh initial context (bundle.context, see host.ts's PlatformBundle),\n * never a document parked from a previous run (see host.ts's module doc for why: a\n * parked doc's live-resource handles die with the process anyway, so resuming one could\n * only ever produce handles that fail to reclaim). Paths are relative to hmrDir\n * (`<root>/hmr`).\n */\n/**\n * Written into an assets directory once every file in it is on disk. Its absence marks a\n * directory whose materialization was interrupted; no asset path can collide with it\n * (assets arrive as `node_modules/...` paths).\n */\nexport const MATERIALIZED = \".materialized\";\n\nexport interface Manifest {\n platform?: { bundle: string };\n /**\n * The CLI's own bundle pointer — its own independent file (a different sha from\n * `platform.bundle`; the two are separately compiled artifacts), kept as its own\n * field so a reader that only wants \"which bundle does the CLI load right now\"\n * never has to reach into `platform` at all.\n */\n cli?: { bundle: string };\n /** One gzip(JSON.stringify({ files })) artifact, restored straight into memory. */\n web?: { manifest: string };\n /**\n * Files the pushed platform needs as REAL files on disk, unpacked under this directory\n * (relative to hmrDir). The web artifact stays in memory because it is only ever served\n * as bytes; an asset is something the platform hands to the OS — a native `.node` the\n * loader must resolve by path, a helper binary it execs — so it has to exist on the\n * filesystem, with its exec bit intact.\n */\n assets?: { dir: string };\n /**\n * Provenance of the push that produced this version, exactly as the pushing client sent\n * it (scripts/deploy.mjs fills it from its own checkout). Recorded, never executed or\n * resolved. Absent for a version pushed without it, and for every version committed\n * before the field existed — which is why every reader treats it as optional.\n */\n source?: { repo: string; revision: string };\n /** When this version was committed to the store (ISO 8601). Absent on older records. */\n pushedAt?: string;\n /**\n * The sha256 of each part this version was pushed as (platform, cli, every web file):\n * the blobs the store keeps alive so the next push need not carry an unchanged one.\n * Absent on older records.\n */\n blobs?: string[];\n}\n\n/** A string field of an untrusted manifest, or null unless it is a non-empty string. */\nfunction str(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n/**\n * What the store has committed, for version reporting: provenance, commit time, and the\n * three artifact pointers. Null when nothing has ever been pushed to this root.\n *\n * Read defensively rather than cast: harness.json is written only by persistVersion, but a\n * truncated or hand-edited file must degrade a `penguin version` to missing fields, never\n * crash it. A record missing every artifact pointer counts as nothing pushed, and so does an\n * unreadable one — the only reader here that deliberately collapses the two, because its\n * caller is a report with nowhere to put a fault. The host says so at boot instead, and\n * `penguin-hmr` says so through readPushedCli.\n */\nexport async function readHarnessInfo(root: string): Promise<HarnessInfo | null> {\n const manifest = await readManifest(root);\n if (manifest === null) return null;\n\n const bundles = {\n platform: str(manifest.platform?.bundle),\n cli: str(manifest.cli?.bundle),\n web: str(manifest.web?.manifest),\n };\n if (bundles.platform === null && bundles.cli === null && bundles.web === null) return null;\n\n const repo = str(manifest.source?.repo);\n const revision = str(manifest.source?.revision);\n return {\n // Both halves or neither: half a provenance names nothing.\n source: repo !== null && revision !== null ? { repo, revision } : null,\n pushedAt: str(manifest.pushedAt),\n bundles,\n };\n}\n\n/**\n * `<root>/hmr/harness.json`, as one of three answers. No file means nothing was ever pushed\n * here; a file that cannot be read or parsed is a fault on a root that DID commit a version,\n * and the two must not arrive as the same value — a reader that acts on \"nothing pushed\"\n * would quietly ignore a version this root still holds.\n */\ntype ManifestRead =\n { kind: \"none\" } | { kind: \"manifest\"; manifest: Manifest } | { kind: \"broken\"; reason: string };\n\nasync function readManifestFile(root: string): Promise<ManifestRead> {\n const file = path.join(root, \"hmr\", \"harness.json\");\n let raw: string;\n try {\n raw = await fsp.readFile(file, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return { kind: \"none\" };\n return { kind: \"broken\", reason: `${file} could not be read: ${msg(err)}` };\n }\n try {\n return { kind: \"manifest\", manifest: JSON.parse(raw) as Manifest };\n } catch (err) {\n return { kind: \"broken\", reason: `${file} is not readable JSON: ${msg(err)}` };\n }\n}\n\nfunction msg(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt. The published\n * `./hmr/manifest` subpath is a contract with installed CLIs, so this keeps its shape;\n * a caller that has to tell the two apart reads it through readPushedCli.\n */\nexport async function readManifest(root: string): Promise<Manifest | null> {\n const read = await readManifestFile(root);\n return read.kind === \"manifest\" ? read.manifest : null;\n}\n\n/**\n * What this root has for the `penguin-hmr` loader. Three answers, never two: a root that\n * pushed no CLI and a root whose record names one it cannot produce are different\n * situations, and collapsing them tells the caller \"nothing pushed\" when the truth is\n * \"the store lost it\".\n */\nexport type PushedCli =\n /** Nothing has pushed a CLI here: a fresh root, or a record with no `cli` entry. */\n | { kind: \"none\" }\n /** The committed CLI bundle, absolute. */\n | { kind: \"bundle\"; file: string }\n /** The record names a CLI this root cannot produce. Says which, so it can be repaired. */\n | { kind: \"broken\"; reason: string };\n\n/**\n * Reads the committed CLI bundle. Never throws: a malformed record is an answer\n * (`broken`), not an exception, because the caller is a CLI entry point that has to print\n * something useful either way.\n *\n * `cli.bundle` is trusted content, written only by persistVersion, but a reader must never\n * let a malformed or malicious value walk it out of the store via `..` segments — an escape\n * is `broken`, like a file the store no longer holds (pruned, see host.ts's pruneStore).\n */\nexport async function readPushedCli(root: string): Promise<PushedCli> {\n const read = await readManifestFile(root);\n if (read.kind === \"none\") return { kind: \"none\" };\n if (read.kind === \"broken\") return { kind: \"broken\", reason: read.reason };\n // No `cli` entry at all is a version that pushed no CLI; an entry that names nothing\n // usable is a record this root cannot act on.\n if (read.manifest.cli === undefined) return { kind: \"none\" };\n const bundle: unknown = read.manifest.cli.bundle;\n if (typeof bundle !== \"string\" || bundle.length === 0) {\n return { kind: \"broken\", reason: \"harness.json has a `cli` entry with no bundle path\" };\n }\n const hmrDir = path.join(root, \"hmr\");\n const abs = path.resolve(hmrDir, bundle);\n if (abs !== hmrDir && !abs.startsWith(hmrDir + path.sep)) {\n return {\n kind: \"broken\",\n reason: `harness.json points \\`cli.bundle\\` outside ${hmrDir}: ${bundle}`,\n };\n }\n if (!fs.existsSync(abs)) {\n return { kind: \"broken\", reason: `the committed CLI bundle is missing from the store: ${abs}` };\n }\n return { kind: \"bundle\", file: abs };\n}\n\n/**\n * The committed CLI bundle's path, or null for anything else. The published `./hmr/manifest`\n * subpath is a contract with installed CLIs, so this keeps its shape; readPushedCli is what\n * says WHY there is no path.\n */\nexport async function resolveCliBundlePath(root: string): Promise<string | null> {\n const cli = await readPushedCli(root);\n return cli.kind === \"bundle\" ? cli.file : null;\n}\n"],"mappings":";AAkBA,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AAiBV,IAAM,eAAe;AAuC5B,SAAS,IAAI,OAA+B;AAC1C,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAaA,eAAsB,gBAAgB,MAA2C;AAC/E,QAAM,WAAW,MAAM,aAAa,IAAI;AACxC,MAAI,aAAa,KAAM,QAAO;AAE9B,QAAM,UAAU;IACd,UAAU,IAA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EAAE,MAAM,UAAU,QAAQ,KAAK,OAAO;AAGzE,MAAI,KAAK,SAAS,QAAQ,OAAW,QAAO,EAAE,MAAM,OAAO;AAC3D,QAAM,SAAkB,KAAK,SAAS,IAAI;AAC1C,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,GAAG;AACrD,WAAO,EAAE,MAAM,UAAU,QAAQ,qDAAqD;EACxF;AACA,QAAM,SAAS,KAAK,KAAK,MAAM,KAAK;AACpC,QAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;AACvC,MAAI,QAAQ,UAAU,CAAC,IAAI,WAAW,SAAS,KAAK,GAAG,GAAG;AACxD,WAAO;MACL,MAAM;MACN,QAAQ,8CAA8C,MAAM,KAAK,MAAM;IACzE;EACF;AACA,MAAI,CAAC,GAAG,WAAW,GAAG,GAAG;AACvB,WAAO,EAAE,MAAM,UAAU,QAAQ,uDAAuD,GAAG,GAAG;EAChG;AACA,SAAO,EAAE,MAAM,UAAU,MAAM,IAAI;AACrC;AAOA,eAAsB,qBAAqB,MAAsC;AAC/E,QAAM,MAAM,MAAM,cAAc,IAAI;AACpC,SAAO,IAAI,SAAS,WAAW,IAAI,OAAO;AAC5C;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/db/database.ts","../src/db/migrations.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.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 restart-only migration may be applied: it\n // owns the 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 * Ordered, versioned schema migrations.\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\", so re-running it\n * converges a database toward the current declaration without ever knowing, or recording,\n * which state it came from. That is why a build could not tell a 0.2.4 database from a\n * 0.2.7 one, and why the only safe change was an additive one.\n *\n * A migration says what CHANGED, runs once, and leaves the database stamped with how far\n * it has come (`PRAGMA user_version`). Two rules make that stamp trustworthy:\n *\n * FROZEN DDL. A migration spells out its own SQL and never imports SCHEMA_SQL. Referring\n * to the live declaration would make an old migration silently mean something new every\n * time the schema moves, which is the property that makes migrations auditable at all.\n *\n * ONE WAY, IN ORDER. Versions are contiguous from 1 and never renumbered or rewritten\n * once released — a database that already stamped version N will never run N again, so\n * editing N only changes what NEW databases get, and silently forks the two.\n *\n * `swapSafe` is this codebase's extra axis, and it exists because of hot updates. A\n * pushed platform boots against a live database and is ROLLED BACK to its predecessor if\n * it fails; the predecessor then runs on whatever the migration already did. Additive\n * work survives that (the older build does not know the new table, so it never touches\n * it) — narrowing work does not. Anything that drops, retypes, constrains, or reshapes\n * is `swapSafe: false` and must be refused on the swap path rather than half-applied\n * (see `migrate`'s `swapPath` option).\n *\n * DOWN, AND WHO DOES NOT CALL IT. Every migration declares an undo — or declares `null`\n * to say it has none, which is a decision the author has to make rather than omit. What\n * `down` is NOT is the hot-update rollback mechanism. When a pushed platform fails to boot\n * the runtime reverts to its PREDECESSOR and the schema stays where the migration left it:\n * undoing DDL inside a process whose boot just failed would run destructive statements\n * against a half-known state, and `swapSafe` exists precisely so that not undoing is safe —\n * the predecessor does not know the new table or column, so it never touches it. `down` is\n * an operator's tool, called deliberately (`rollbackTo`), never by the swap.\n *\n * It is also LOSSY by nature: undoing \"add a table\" drops that table with its rows in it.\n * Each `down` below names what its rows were.\n *\n * ADOPTION. Databases created before this file existed are all stamped 0 while sitting in\n * genuinely different shapes, so a migration must tolerate finding its work already done.\n * That is not only a version-1 concern: `schema.ts` still DECLARES the current shape in\n * full and `openDatabase` still runs its ensureColumn list, so a database can arrive at a\n * migration with that migration's work already applied by the declarative track. Until\n * SCHEMA_SQL is frozen to a baseline and every later change is a migration, every\n * migration here stays idempotent — `IF NOT EXISTS`, or the same `ensureColumn` guard the\n * declarative track uses. Once that double track is gone, a bare `CREATE TABLE` that\n * fails loudly becomes the point.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { ensureColumn } from \"./database.js\";\n\nexport interface Migration {\n /** Contiguous from 1. Never renumbered, never edited once released. */\n version: number;\n /** Kebab-case, names the change — read in logs and in the stamp's history. */\n name: string;\n /**\n * May this run while a pushed platform boots? True only for strictly additive work,\n * which a rollback to the previous platform survives. See the module doc.\n */\n swapSafe: boolean;\n /** Applied inside a transaction; throw to abort and leave the version unchanged. */\n up: (db: DatabaseSync) => void;\n /**\n * Undoes `up`, or null when this migration cannot be undone — required, not optional, so\n * \"there is no undo\" is something the author states rather than forgets.\n *\n * Never called by the swap path (see the module doc): a failed boot reverts the platform,\n * not the schema. Reached only through `rollbackTo`, and destructive by nature — dropping\n * a table takes its rows with it.\n */\n down: ((db: DatabaseSync) => void) | null;\n}\n\nexport const MIGRATIONS: readonly Migration[] = [\n {\n version: 1,\n name: \"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 only because version 1 adopts unstamped databases, which may already\n // be at 0.2.7 (see the module doc's ADOPTION note).\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 {\n version: 2,\n name: \"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 the module doc's ADOPTION note).\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 {\n version: 3,\n name: \"drop-goal-state\",\n // Narrowing: drops a table. A pushed platform rolled back to 0.2.9 mid-process would\n // prepare its goal statements against a table that is gone (its declarative track only\n // runs at the runtime's own open, never at a platform boot), so this is the first\n // restart-only migration: refused on the swap path, applied by the runtime's open.\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 {\n version: 4,\n name: \"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 // 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 (ADOPTION).\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 {\n version: 5,\n name: \"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 (ADOPTION), 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 {\n version: 6,\n name: \"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_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 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 },\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 {\n version: 7,\n name: \"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 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 migration 6 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 {\n version: 8,\n name: \"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 {\n version: 9,\n name: \"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 // (ADOPTION).\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 {\n version: 10,\n name: \"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 schema 10 or newer. The release that\n // raises the minimum database baseline past 9 owns removing this migration block and its\n // version-9 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 // (ADOPTION).\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 {\n version: 11,\n name: \"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 {\n version: 12,\n name: \"machines-columns\",\n // A machines table can predate migration 4 — 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 4 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, 4 already declares, and a column it found in place\n // was never this migration's to take away.\n down() {},\n },\n {\n version: 13,\n name: \"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 (ADOPTION).\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 {\n version: 14,\n name: \"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 {\n version: 15,\n name: \"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 {\n version: 16,\n name: \"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];\n\n/** The highest version this build knows how to reach. */\nexport const LATEST_VERSION: number = MIGRATIONS.reduce((n, m) => Math.max(n, m.version), 0);\n\n/** How far this database has been migrated. Unstamped (pre-migrations) databases read 0. */\nexport function schemaVersion(db: DatabaseSync): number {\n const row = db.prepare(\"PRAGMA user_version\").get() as { user_version: number } | undefined;\n return row?.user_version ?? 0;\n}\n\nexport class IrreversibleMigrationError extends Error {\n constructor(readonly migration: Migration) {\n super(\n `migration ${migration.version} (${migration.name}) 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 RestartRequiredError extends Error {\n constructor(readonly migration: Migration) {\n super(\n `migration ${migration.version} (${migration.name}) is restart-only and cannot be applied ` +\n `while a pushed platform boots: it is not safe to leave behind if this boot is rolled back. ` +\n `Restart the runtime on a build that carries it, then push again.`,\n );\n this.name = \"RestartRequiredError\";\n }\n}\n\n/**\n * Applies every migration this database has not reached yet, in order.\n *\n * Each migration and its version stamp commit together, so an interrupted run leaves the\n * database at the last version that fully applied — never half-migrated. Already-current\n * databases do no work and touch nothing.\n *\n * `swapPath` marks the caller as a booting pushed platform: the first pending migration\n * that is not `swapSafe` throws RestartRequiredError BEFORE anything is applied, so the\n * push is refused whole rather than partially landed.\n */\nexport function migrate(\n db: DatabaseSync,\n { swapPath = false }: { swapPath?: boolean } = {},\n): { from: number; to: number; applied: readonly string[] } {\n const from = schemaVersion(db);\n const pending = [...MIGRATIONS]\n .sort((a, b) => a.version - b.version)\n .filter((m) => m.version > from);\n if (swapPath) {\n const blocked = pending.find((m) => !m.swapSafe);\n if (blocked) throw new RestartRequiredError(blocked);\n }\n const applied: string[] = [];\n for (const m of pending) {\n db.exec(\"BEGIN\");\n try {\n m.up(db);\n // PRAGMA takes no bound parameter; the value is this file's own integer literal.\n db.exec(`PRAGMA user_version = ${m.version}`);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`migration ${m.version} (${m.name}) failed: ${String(err)}`, { cause: err });\n }\n applied.push(m.name);\n }\n return { from, to: schemaVersion(db), applied };\n}\n\n/**\n * Reverts the database DOWN to `targetVersion`, newest migration first.\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 (module doc).\n *\n * Refused whole, before anything runs, if any migration in range declares no `down`: a\n * partial rollback would leave the database at a version whose meaning nobody wrote down.\n * Each `down` commits with its version stamp, so an interrupted run stops at a real version.\n */\nexport function rollbackTo(\n db: DatabaseSync,\n targetVersion: number,\n): { from: number; to: number; reverted: readonly string[] } {\n const from = schemaVersion(db);\n if (targetVersion < 0) throw new Error(`target version ${targetVersion} is negative`);\n if (targetVersion > from) {\n throw new Error(`database is at version ${from}, which is already below ${targetVersion}`);\n }\n const toRevert = [...MIGRATIONS]\n .filter((m) => m.version > targetVersion && m.version <= from)\n .sort((a, b) => b.version - a.version);\n const blocked = toRevert.find((m) => m.down === null);\n if (blocked) throw new IrreversibleMigrationError(blocked);\n\n const reverted: string[] = [];\n for (const m of toRevert) {\n db.exec(\"BEGIN\");\n try {\n m.down!(db);\n // Versions are contiguous, so the predecessor of `m` is exactly m.version - 1.\n db.exec(`PRAGMA user_version = ${m.version - 1}`);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw new Error(`rollback of migration ${m.version} (${m.name}) failed: ${String(err)}`, {\n cause: err,\n });\n }\n reverted.push(m.name);\n }\n return { from, to: schemaVersion(db), reverted };\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'; 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', -- the approval mode an API Session is CREATED with (allow-all|deny-all|read-only|always-ask); copied onto sessions.approval_mode, never read per decision\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);\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;;;ACoEV,IAAM,aAAmC;AAAA,EAC9C;AAAA,IACE,SAAS;AAAA,IACT,MAAM;AAAA;AAAA;AAAA;AAAA,IAIN,UAAU;AAAA,IACV,GAAG,IAAI;AAIL,SAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,OAkBP;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,IAAI;AACP,SAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,OAKP;AAAA,IACH;AAAA,EACF;AAAA,EACA;AAAA,IACE,SAAS;AAAA,IACT,MAAM;AAAA;AAAA;AAAA,IAGN,UAAU;AAAA,IACV,GAAG,IAAI;AAGL,mBAAa,IAAI,sBAAsB,oBAAoB,4BAA4B;AACvF,mBAAa,IAAI,sBAAsB,mBAAmB,4BAA4B;AAAA,IACxF;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,IAAI;AACP,SAAG,KAAK,4DAA4D;AACpE,SAAG,KAAK,6DAA6D;AAAA,IACvE;AAAA,EACF;AAAA,EACA;AAAA,IACE,SAAS;AAAA,IACT,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKN,UAAU;AAAA,IACV,GAAG,IAAI;AAKL,SAAG,KAAK;AAAA;AAAA;AAAA,OAGP;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,IAAI;AACP,SAAG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Y,kBAAkB,MAAM;AACrD,eAAa,IAAI,YAAY,WAAW,MAAM;AAG9C,eAAa,IAAI,iBAAiB,OAAO,MAAM;AAC/C,eAAa,IAAI,eAAe,cAAc,MAAM;AACpD,eAAa,IAAI,sBAAsB,oBAAoB,4BAA4B;AACvF,eAAa,IAAI,sBAAsB,oBAAoB,4BAA4B;AAKvF,eAAa,IAAI,sBAAsB,mBAAmB,4BAA4B;AACtF,eAAa,IAAI,sBAAsB,2BAA2B,MAAM;AAIxE,KAAG,KAAK,wCAAwC;AAUhD,KAAG,KAAK,4CAA4C;AACpD,sBAAoB,EAAE;AAGtB,UAAQ,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":[]}
@@ -1,52 +0,0 @@
1
- // src/http/errors.ts
2
- var HttpError = class extends Error {
3
- constructor(status, code, message, retryAfterSeconds, details) {
4
- super(message);
5
- this.status = status;
6
- this.code = code;
7
- this.retryAfterSeconds = retryAfterSeconds;
8
- this.details = details;
9
- this.name = "HttpError";
10
- }
11
- status;
12
- code;
13
- retryAfterSeconds;
14
- details;
15
- };
16
- function badRequest(message) {
17
- return new HttpError(400, "bad_request", message);
18
- }
19
- function errorBody(code, message, details) {
20
- return { error: { code, message, ...details !== void 0 ? { details } : {} } };
21
- }
22
- function isMissingCredential(err) {
23
- const message = err instanceof Error ? err.message : String(err);
24
- return /missing credentials|api[_ ]?key/i.test(message);
25
- }
26
- function modelCredentialMissing(modelId) {
27
- return new HttpError(
28
- 400,
29
- "model_credential_missing",
30
- `Model ${modelId} has no API key yet. Configure it on the Models page first.`
31
- );
32
- }
33
- function handleError(err, c) {
34
- if (err instanceof HttpError) {
35
- if (err.retryAfterSeconds !== void 0) {
36
- c.header("Retry-After", String(err.retryAfterSeconds));
37
- }
38
- return c.json(errorBody(err.code, err.message, err.details), err.status);
39
- }
40
- console.error(`[server] Unhandled exception: ${err.stack ?? err.message}`);
41
- return c.json(errorBody("internal", "Internal server error."), 500);
42
- }
43
-
44
- export {
45
- HttpError,
46
- badRequest,
47
- errorBody,
48
- isMissingCredential,
49
- modelCredentialMissing,
50
- handleError
51
- };
52
- //# sourceMappingURL=chunk-Q4ON2L6E.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/http/errors.ts"],"sourcesContent":["/**\n * Unified HTTP error: `{error: {code, message, details?}}` response body,\n * with message in English.\n *\n * Routes and services express business errors via throw HttpError; app-level onError\n * uniformly converges these into a JSON response, with unknown errors converged to 500\n * (never leaking internal details to the client).\n *\n * `details` carries the facts a client acts on beside the code — the id a 409 is about, say — so\n * that no client has to parse them out of the message, which is prose and may change.\n */\nimport type { Context } from \"hono\";\nimport type { ErrorBody, ErrorDetails } from \"../api/types.js\";\n\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n readonly retryAfterSeconds?: number,\n readonly details?: ErrorDetails,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\n/** A 400 for a request the route cannot take as it is; validate.ts re-exports it beside its checks. */\nexport function badRequest(message: string): HttpError {\n return new HttpError(400, \"bad_request\", message);\n}\n\nexport function errorBody(code: string, message: string, details?: ErrorDetails): ErrorBody {\n return { error: { code, message, ...(details !== undefined ? { details } : {}) } };\n}\n\n/**\n * Model missing a credential: the provider SDK throws this at **client-construction\n * time** (hit by both creating a Session and resuming a Session); the original message\n * is full of environment variable names, meaningless to a user — uniformly replaced\n * with a single actionable sentence. The frontend produces localized text by code\n * (message is only a fallback); see web's lib/api-error.ts.\n */\nexport function isMissingCredential(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err);\n return /missing credentials|api[_ ]?key/i.test(message);\n}\n\nexport function modelCredentialMissing(modelId: string): HttpError {\n return new HttpError(\n 400,\n \"model_credential_missing\",\n `Model ${modelId} has no API key yet. Configure it on the Models page first.`,\n );\n}\n\n/** app.onError handler: maps HttpError through as-is; everything else is logged and converged to 500. */\nexport function handleError(err: Error, c: Context): Response {\n if (err instanceof HttpError) {\n if (err.retryAfterSeconds !== undefined) {\n c.header(\"Retry-After\", String(err.retryAfterSeconds));\n }\n return c.json(errorBody(err.code, err.message, err.details), err.status as 400);\n }\n // Unknown error: print the stack for diagnosis, but never expose details externally.\n console.error(`[server] Unhandled exception: ${err.stack ?? err.message}`);\n return c.json(errorBody(\"internal\", \"Internal server error.\"), 500);\n}\n"],"mappings":";AAcO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACW,QACA,MACT,SACS,mBACA,SACT;AACA,UAAM,OAAO;AANJ;AACA;AAEA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EARW;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAKb;AAGO,SAAS,WAAW,SAA4B;AACrD,SAAO,IAAI,UAAU,KAAK,eAAe,OAAO;AAClD;AAEO,SAAS,UAAU,MAAc,SAAiB,SAAmC;AAC1F,SAAO,EAAE,OAAO,EAAE,MAAM,SAAS,GAAI,YAAY,SAAY,EAAE,QAAQ,IAAI,CAAC,EAAG,EAAE;AACnF;AASO,SAAS,oBAAoB,KAAuB;AACzD,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,SAAO,mCAAmC,KAAK,OAAO;AACxD;AAEO,SAAS,uBAAuB,SAA4B;AACjE,SAAO,IAAI;AAAA,IACT;AAAA,IACA;AAAA,IACA,SAAS,OAAO;AAAA,EAClB;AACF;AAGO,SAAS,YAAY,KAAY,GAAsB;AAC5D,MAAI,eAAe,WAAW;AAC5B,QAAI,IAAI,sBAAsB,QAAW;AACvC,QAAE,OAAO,eAAe,OAAO,IAAI,iBAAiB,CAAC;AAAA,IACvD;AACA,WAAO,EAAE,KAAK,UAAU,IAAI,MAAM,IAAI,SAAS,IAAI,OAAO,GAAG,IAAI,MAAa;AAAA,EAChF;AAEA,UAAQ,MAAM,iCAAiC,IAAI,SAAS,IAAI,OAAO,EAAE;AACzE,SAAO,EAAE,KAAK,UAAU,YAAY,wBAAwB,GAAG,GAAG;AACpE;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/db/repos/users.ts","../src/db/repos/auth-sessions.ts"],"sourcesContent":["/**\n * users table repo: pure SQL wrapper, no business rules.\n * user_id is the login name (a semantic id, specified at creation, immutable).\n */\nimport { Component, Use } from \"@prismshadow/penguin-core/kernel\";\nimport type { Db } from \"../../hmr/capabilities.js\";\nimport type { Users } from \"../../mechanisms/identity.js\";\n\nexport interface UserRow {\n userId: string;\n passwordHash: string;\n isAdmin: boolean;\n /** Still using the initial password (seeded / set by an admin); cleared to 0 once the user changes it. */\n passwordIsInitial: boolean;\n /** Nickname shown in place of the id; null = never set. */\n displayName: string | null;\n /** Avatar as a data URL; null = never set. */\n avatar: string | null;\n createdAt: string;\n}\n\nfunction mapRow(r: Record<string, unknown>): UserRow {\n return {\n userId: r.user_id as string,\n passwordHash: r.password_hash as string,\n isAdmin: (r.is_admin as number) === 1,\n passwordIsInitial: (r.password_is_initial as number) === 1,\n displayName: (r.display_name as string | null) ?? null,\n avatar: (r.avatar as string | null) ?? null,\n createdAt: r.created_at as string,\n };\n}\n\n@Component()\nexport class UsersRepo implements Users {\n @Use() private readonly db!: Db;\n\n insert(row: UserRow): void {\n this.db\n .prepare(\n \"INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, display_name, avatar, created_at)\" +\n \" VALUES (?, ?, ?, ?, ?, ?, ?)\",\n )\n .run(\n row.userId,\n row.passwordHash,\n row.isAdmin ? 1 : 0,\n row.passwordIsInitial ? 1 : 0,\n row.displayName,\n row.avatar,\n row.createdAt,\n );\n }\n\n findById(userId: string): UserRow | null {\n const r = this.db.prepare(\"SELECT * FROM users WHERE user_id = ?\").get(userId);\n return r ? mapRow(r) : null;\n }\n\n /** All users (for the admin user backend), ordered by creation time ascending. */\n list(): UserRow[] {\n const rows = this.db.prepare(\"SELECT * FROM users ORDER BY created_at ASC, user_id ASC\").all();\n return rows.map(mapRow);\n }\n\n count(): number {\n const r = this.db.prepare(\"SELECT COUNT(*) AS n FROM users\").get();\n return (r?.n as number) ?? 0;\n }\n\n /** Update the password hash; isInitial marks whether the password was set by someone else (seed / admin). */\n updatePassword(userId: string, passwordHash: string, isInitial: boolean): void {\n this.db\n .prepare(\"UPDATE users SET password_hash = ?, password_is_initial = ? WHERE user_id = ?\")\n .run(passwordHash, isInitial ? 1 : 0, userId);\n }\n\n /**\n * Writes the profile fields the patch names, leaving the rest as they are: an absent key\n * keeps the stored value, `null` clears it, a string replaces it. A patch naming neither\n * field writes nothing rather than issuing an UPDATE with an empty SET list.\n */\n updateProfile(\n userId: string,\n patch: { displayName?: string | null; avatar?: string | null },\n ): void {\n const sets: string[] = [];\n const values: (string | null)[] = [];\n if (patch.displayName !== undefined) {\n sets.push(\"display_name = ?\");\n values.push(patch.displayName);\n }\n if (patch.avatar !== undefined) {\n sets.push(\"avatar = ?\");\n values.push(patch.avatar);\n }\n if (sets.length === 0) return;\n this.db.prepare(`UPDATE users SET ${sets.join(\", \")} WHERE user_id = ?`).run(...values, userId);\n }\n\n /** Used by admin user deletion and account-creation compensation paths (owned Projects must be cleaned up first). */\n delete(userId: string): void {\n this.db.prepare(\"DELETE FROM users WHERE user_id = ?\").run(userId);\n }\n}\n","/**\n * auth_sessions table repo (server-side sessions backing the HttpOnly cookie). Stores only\n * sha256(token); the raw token appears only in the cookie. `issue()` is the ONE minting point,\n * so a CLI-minted row cannot drift from one the server issues itself.\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { Component, Use } from \"@prismshadow/penguin-core/kernel\";\nimport type { Db } from \"../../hmr/capabilities.js\";\nimport type { AuthSessions } from \"../../mechanisms/identity.js\";\n\n/** How a session was established, as stored. NULL on rows formed before the column existed. */\nexport type SessionViaValue = \"password\" | \"desktop\" | \"setup\" | \"cli\";\n\nexport interface AuthSessionRow {\n tokenHash: string;\n userId: string;\n createdAt: string;\n expiresAt: string;\n via: SessionViaValue | null;\n}\n\n/** sha256 hex of a raw session token — the only form the database ever holds. */\nexport function sessionTokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n@Component()\nexport class AuthSessionsRepo implements AuthSessions {\n @Use() private readonly db!: Db;\n\n /**\n * Mints a session and returns the raw token for a cookie or the terminal. `maxTtlMs` caps a\n * caller-supplied lifetime (`--ttl-seconds`): one longer than an ordinary session would make\n * a leaked token file outlive every other credential, sliding forever. Expired rows are\n * swept here too, so a cron that only mints does not accumulate them.\n */\n issue(opts: {\n userId: string;\n via: SessionViaValue;\n now: Date;\n ttlMs: number;\n maxTtlMs?: number;\n }): { token: string; expiresAt: string } {\n const ttlMs = Math.max(1_000, Math.min(opts.ttlMs, opts.maxTtlMs ?? opts.ttlMs));\n const token = randomBytes(32).toString(\"base64url\");\n const createdAt = opts.now.toISOString();\n const expiresAt = new Date(opts.now.getTime() + ttlMs).toISOString();\n this.deleteExpired(createdAt);\n this.insert({\n tokenHash: sessionTokenHash(token),\n userId: opts.userId,\n createdAt,\n expiresAt,\n via: opts.via,\n });\n return { token, expiresAt };\n }\n\n insert(row: AuthSessionRow): void {\n this.db\n .prepare(\n \"INSERT INTO auth_sessions (token_hash, user_id, created_at, expires_at, via) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(row.tokenHash, row.userId, row.createdAt, row.expiresAt, row.via);\n }\n\n findByTokenHash(tokenHash: string): AuthSessionRow | null {\n const r = this.db.prepare(\"SELECT * FROM auth_sessions WHERE token_hash = ?\").get(tokenHash);\n if (!r) return null;\n return {\n tokenHash: r.token_hash as string,\n userId: r.user_id as string,\n createdAt: r.created_at as string,\n expiresAt: r.expires_at as string,\n via: (r.via as SessionViaValue | null) ?? null,\n };\n }\n\n /** Sliding renewal: update the expiration time. */\n touch(tokenHash: string, expiresAt: string): void {\n this.db\n .prepare(\"UPDATE auth_sessions SET expires_at = ? WHERE token_hash = ?\")\n .run(expiresAt, tokenHash);\n }\n\n delete(tokenHash: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE token_hash = ?\").run(tokenHash);\n }\n\n /** Opportunistically clean up expired sessions (called during login/validation). */\n deleteExpired(nowIso: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE expires_at < ?\").run(nowIso);\n }\n\n /** Clear all sessions for a user (forces re-login after an admin resets the password). */\n deleteByUser(userId: string): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE user_id = ?\").run(userId);\n }\n\n /**\n * Clear a user's sessions of one kind. Used to end EVERY first-login session when a password\n * is set: an earlier boot's link may still be live in someone's scrollback, and a `setup`\n * session may change the password without knowing the old one.\n */\n deleteByUserAndVia(userId: string, via: SessionViaValue): void {\n this.db.prepare(\"DELETE FROM auth_sessions WHERE user_id = ? AND via = ?\").run(userId, via);\n }\n}\n"],"mappings":";;;;;;;;AAIA,SAAS,WAAW,WAAW;AAiB/B,SAAS,OAAO,GAAqC;AACnD,SAAO;AAAA,IACL,QAAQ,EAAE;AAAA,IACV,cAAc,EAAE;AAAA,IAChB,SAAU,EAAE,aAAwB;AAAA,IACpC,mBAAoB,EAAE,wBAAmC;AAAA,IACzD,aAAc,EAAE,gBAAkC;AAAA,IAClD,QAAS,EAAE,UAA4B;AAAA,IACvC,WAAW,EAAE;AAAA,EACf;AACF;AA/BA;AAiCA,yBAA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AAAA,EAEA,gBAAgB,WAA0C;AACxD,UAAM,IAAI,KAAK,GAAG,QAAQ,kDAAkD,EAAE,IAAI,SAAS;AAC3F,QAAI,CAAC,EAAG,QAAO;AACf,WAAO;AAAA,MACL,WAAW,EAAE;AAAA,MACb,QAAQ,EAAE;AAAA,MACV,WAAW,EAAE;AAAA,MACb,WAAW,EAAE;AAAA,MACb,KAAM,EAAE,OAAkC;AAAA,IAC5C;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAAmB,WAAyB;AAChD,SAAK,GACF,QAAQ,8DAA8D,EACtE,IAAI,WAAW,SAAS;AAAA,EAC7B;AAAA,EAEA,OAAO,WAAyB;AAC9B,SAAK,GAAG,QAAQ,gDAAgD,EAAE,IAAI,SAAS;AAAA,EACjF;AAAA;AAAA,EAGA,cAAc,QAAsB;AAClC,SAAK,GAAG,QAAQ,gDAAgD,EAAE,IAAI,MAAM;AAAA,EAC9E;AAAA;AAAA,EAGA,aAAa,QAAsB;AACjC,SAAK,GAAG,QAAQ,6CAA6C,EAAE,IAAI,MAAM;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,mBAAmB,QAAgB,KAA4B;AAC7D,SAAK,GAAG,QAAQ,yDAAyD,EAAE,IAAI,QAAQ,GAAG;AAAA,EAC5F;AACF;AAhFOA,SAAA;AACE,kBAAAA,QAAA,GAAiB,MAAxBD,UADW;AAAA,mBAAN,kBAAAC,QAAA,uBADP,8BACa;AAAN,kBAAAA,QAAA,GAAM;","names":["Component","Use","_db_dec","_init","Component","Use"]}
@@ -1 +0,0 @@
1
- import{U as a,C as n}from"./mermaid.core-BcTrmPOv.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-B6oDkrep.js";import{_ as i}from"./mermaid.core-BcTrmPOv.js";import"./chunk-5VM5RSS4-2H2ZJAte.js";import"./chunk-XXDRQBXY-BbU8DR4B.js";import"./chunk-POPQ4Y6H-9bjsAxLS.js";import"./chunk-F27PBJKO-B30xCNBv.js";import"./index-BdG4qRyI.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-B6oDkrep.js";import{_ as i}from"./mermaid.core-BcTrmPOv.js";import"./chunk-5VM5RSS4-2H2ZJAte.js";import"./chunk-XXDRQBXY-BbU8DR4B.js";import"./chunk-POPQ4Y6H-9bjsAxLS.js";import"./chunk-F27PBJKO-B30xCNBv.js";import"./index-BdG4qRyI.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,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/highlighter-core-B5CvXcEK.js","assets/index-BdG4qRyI.js","assets/index-W-xYFoIm.css"])))=>i.map(i=>d[i]);
2
- import{r as g,i as h,_ as f}from"./index-BdG4qRyI.js";let o,w=0;const n=new Map;function v(r){for(const[e,t]of n)t(r(e));n.clear()}function p(){if(o!==void 0)return o;try{const r=new Worker(new URL("/assets/highlighter.worker-D6D9fPma.js",import.meta.url),{type:"module"});r.onmessage=e=>{const t=n.get(e.data.id);t&&(n.delete(e.data.id),t(e.data))},r.onerror=()=>{o=null,v(e=>({id:e,error:"worker failed"}))},o=r}catch{o=null}return o}async function k(r,e,t={}){const i=g(e),a=i!==void 0&&h(i)?{id:i,grammarUrl:`/api/languages/${encodeURIComponent(i)}/grammar`}:void 0,l=p();if(l===null){const{highlight:s}=await f(async()=>{const{highlight:m}=await import("./highlighter-core-B5CvXcEK.js");return{highlight:m}},__vite__mapDeps([0,1,2]));return s(r,e,t,a)}const d=w+=1,u={id:d,code:r,language:e,options:t,...a!==void 0?{runtime:a}:{}},c=await new Promise(s=>{n.set(d,s),l.postMessage(u)});if(c.error===void 0)return c.html}export{k as highlightToHtml};