@prismshadow/penguin-server 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/api/types.d.ts +242 -28
- package/dist/{chunk-3QINBW3W.js → chunk-KQQ3HSTK.js} +11 -8
- package/dist/chunk-KQQ3HSTK.js.map +1 -0
- package/dist/hmr/manifest.d.ts +10 -0
- package/dist/hmr/manifest.js.map +1 -1
- package/dist/index.js +2604 -349
- package/dist/index.js.map +1 -1
- package/dist/reset-admin-password.js +1 -1
- package/package.json +7 -3
- package/web-dist/assets/addon-fit-ClUHZ6NU.js +1 -0
- package/web-dist/assets/addon-web-links-BKMSMMvN.js +1 -0
- package/web-dist/assets/{highlighter-Nvj8c0Yw.js → highlighter-Cp5vYdaX.js} +1 -1
- package/web-dist/assets/index-BJNmFD1m.js +187 -0
- package/web-dist/assets/index-BneOZQwC.css +1 -0
- package/web-dist/assets/xterm-j28bzvOQ.js +9 -0
- package/web-dist/index.html +2 -2
- package/dist/chunk-3QINBW3W.js.map +0 -1
- package/web-dist/assets/index--uKtXcEB.js +0 -183
- package/web-dist/assets/index-BqF51KT4.css +0 -1
package/README.md
CHANGED
|
@@ -9,6 +9,7 @@ The PenguinHarness Web backend — the Web implementation of the SDK's Human bou
|
|
|
9
9
|
- **Runtime**: a session manager keeps active Sessions (get-or-resume-or-heal, per-Session mutex, run/compact driving); approvals surface over SSE as `approval_request` and decisions re-read the stored approval mode each time; interrupts converge pending approvals to deny before aborting; a scheduler fires `agent_state/schedule/*.toml` tasks while the service runs.
|
|
10
10
|
- **SSE**: per-channel monotonic event ids with a bounded replay buffer (1000 events / 2MB); reconnects replay from `Last-Event-ID` or receive `resync_required`; heartbeat comment every 20s.
|
|
11
11
|
- **Usage**: `token_usage` events are persisted row by row; costs are computed at query time from current per-model pricing.
|
|
12
|
+
- **Terminals**: `src/terminal/` runs pty sessions server-side (node-pty) and feeds every byte into a headless xterm, so the daemon — not the browser — owns the screen. Control is JSON over HTTP (`/api/terminals`: list / create / capture / keys / kill; create accepts `cwd`, `name`, `cols`/`rows` and a `shell` override); the byte stream is a binary WebSocket at `/api/terminals/:id/stream` (`[opcode, slot, payload]`, output coalesced into ~5ms windows with an immediate leading flush). On attach the server renders the current grid back into an ANSI restore stream, so a reload or a second device rebuilds the exact screen — scrollback, colours, cursor and DEC input modes — while the shell keeps running the whole time. The web app surfaces this twice: an in-app dock (Ctrl+` , Codex-style) and the standalone `/terminal` page (`?id=` attaches an existing terminal — the dock's detach handoff — `?cwd=`/`?name=` parameterize a new one). Sessions run in-process (no forked terminal worker); this module is the only thing touching node-pty, which is where that split would go if load ever demands it.
|
|
12
13
|
|
|
13
14
|
The full route tables and the SSE protocol are documented in the [Server API reference](https://penguin.ooo/docs/server-api). DTO types are exported for type-only import via `@prismshadow/penguin-server/api`.
|
|
14
15
|
|
|
@@ -41,6 +42,7 @@ pnpm --filter @prismshadow/penguin-server start # node dist/index.js
|
|
|
41
42
|
- **Built-in admin `admin` starts with a random initial password** of the form `penguin-1234`, printed once to the server console at seed time (`PENGUIN_SEED_ADMIN_PASSWORD` pins it for tests/e2e): change it immediately (a banner keeps reminding until you do).
|
|
42
43
|
- Passwords use `node:crypto` scrypt (`scrypt$N$r$p$salt$hash`, timingSafeEqual); login sessions renew on a 7-day sliding window; the DB stores only the token's sha256.
|
|
43
44
|
- Model credentials live in the Project's hidden 0600 config file; the API always masks them.
|
|
45
|
+
- **Terminals are a shell as the OS account running the server**, i.e. the most privileged thing the API hands out — they are not Project-scoped. A terminal is only visible to the account that created it (someone else's id answers 404, not 403), and the stream WebSocket checks `Origin` on top of the session cookie because a WebSocket handshake is not subject to CORS. Do not expose a deployment with terminals enabled to accounts you would not give SSH.
|
|
44
46
|
- Behind a reverse proxy, disable response buffering for SSE paths (the server already sends `X-Accel-Buffering: no`) and forward `x-forwarded-proto` to enable Secure cookies.
|
|
45
47
|
|
|
46
48
|
Part of [PenguinHarness](https://github.com/Prism-Shadow/penguin-harness) · Apache-2.0
|
package/dist/api/types.d.ts
CHANGED
|
@@ -198,6 +198,18 @@ interface ServerSettingsUpdateRequest {
|
|
|
198
198
|
*/
|
|
199
199
|
attachmentTotalMb?: number;
|
|
200
200
|
}
|
|
201
|
+
/**
|
|
202
|
+
* One draft-screen shortcut: a prompt the user wrote, filed under a name they chose. Clicking it
|
|
203
|
+
* fills the composer exactly like a built-in example does, and sends nothing. Deliberately holds
|
|
204
|
+
* no Skill list — a saved prompt is not authored against a known Skill catalog the way a shipped
|
|
205
|
+
* example is, and the Agent it will run under is picked after the click.
|
|
206
|
+
*/
|
|
207
|
+
interface DraftShortcut {
|
|
208
|
+
/** Stable client-generated id: what an edit or a delete addresses the row by. Unique per user. */
|
|
209
|
+
id: string;
|
|
210
|
+
title: string;
|
|
211
|
+
prompt: string;
|
|
212
|
+
}
|
|
201
213
|
/** User UI preferences (SQLite ui_prefs, free-form JSON; known keys declared here). */
|
|
202
214
|
interface UiPrefs {
|
|
203
215
|
theme?: "light" | "dark";
|
|
@@ -212,6 +224,13 @@ interface UiPrefs {
|
|
|
212
224
|
showCliSessions?: boolean;
|
|
213
225
|
/** The initial-password notice banner (app layout) was permanently dismissed by the user. */
|
|
214
226
|
initialPasswordBannerDismissed?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* The draft screen's user-defined shortcuts, in display order. Replaced whole on every write
|
|
229
|
+
* (the merge is shallow, so the array is one field like any other) and bounded on write by
|
|
230
|
+
* services/draft-shortcuts.ts — count, title length and prompt length — because this is the one
|
|
231
|
+
* known key holding user-authored text rather than a flag or an id.
|
|
232
|
+
*/
|
|
233
|
+
draftShortcuts?: DraftShortcut[];
|
|
215
234
|
[key: string]: unknown;
|
|
216
235
|
}
|
|
217
236
|
interface PrefsResponse {
|
|
@@ -319,6 +338,14 @@ interface ModelInfo {
|
|
|
319
338
|
pricing?: ModelPricingDto;
|
|
320
339
|
/** Environment variable name to fall back to when api_key is empty (e.g. ANTHROPIC_API_KEY); unset if no known fallback. */
|
|
321
340
|
envKey?: string;
|
|
341
|
+
/**
|
|
342
|
+
* Masked preview (same rule as `credential.apiKeyMasked`) of the value the server process
|
|
343
|
+
* currently holds for `envKey` — the plaintext is never serialized. Reported only for
|
|
344
|
+
* first-party official entries (vendor group, catalog shape unmodified); gateway, custom
|
|
345
|
+
* and user-defined groups never carry it. Absent = the variable is unset or empty, or the
|
|
346
|
+
* entry is not first-party.
|
|
347
|
+
*/
|
|
348
|
+
envKeyMasked?: string;
|
|
322
349
|
credential?: CredentialInfo;
|
|
323
350
|
isDefault: boolean;
|
|
324
351
|
}
|
|
@@ -501,6 +528,29 @@ interface ModelProtocolDetectResponse {
|
|
|
501
528
|
detected?: string;
|
|
502
529
|
probes: ModelProtocolProbeDto[];
|
|
503
530
|
}
|
|
531
|
+
/**
|
|
532
|
+
* Endpoint model listing (POST /api/projects/:p/models/list, owner): given a base URL and
|
|
533
|
+
* the protocol `/detect` reported, returns every model id the endpoint serves (AgentHub's
|
|
534
|
+
* `listModels()` on the routed client). Used by the add-group dialog to import a provider's
|
|
535
|
+
* whole listing in one go; the ids come back in the endpoint's own order.
|
|
536
|
+
*/
|
|
537
|
+
interface EndpointModelListRequest {
|
|
538
|
+
/** Endpoint base URL (as typed in the add-group dialog). */
|
|
539
|
+
baseUrl: string;
|
|
540
|
+
/** AgentHub client type to speak (normally a detected generic protocol; whole-endpoint listings need one). */
|
|
541
|
+
clientType: string;
|
|
542
|
+
/** Newly entered API key (plaintext); omitted = the SDK's environment fallback for the protocol. */
|
|
543
|
+
apiKey?: string;
|
|
544
|
+
}
|
|
545
|
+
/** Listing outcome: model ids on success, a truncated provider/SDK reason otherwise. */
|
|
546
|
+
interface EndpointModelListResponse {
|
|
547
|
+
ok: boolean;
|
|
548
|
+
/** The model ids the endpoint serves, in the order the endpoint returned them (ok only). */
|
|
549
|
+
models?: string[];
|
|
550
|
+
/** The routed client has no models endpoint (AgentHub UnsupportedOperationError) — callers offer the manual path. */
|
|
551
|
+
unsupported?: boolean;
|
|
552
|
+
message?: string;
|
|
553
|
+
}
|
|
504
554
|
/**
|
|
505
555
|
* PUT /api/projects/:p/models/default (owner): narrow default-model switch — flips the same
|
|
506
556
|
* top-level `default_model` the models page's whole-table PUT writes, without resending the
|
|
@@ -537,6 +587,36 @@ interface ChatDefaultsDto {
|
|
|
537
587
|
*/
|
|
538
588
|
thinkingLevel?: Exclude<ThinkingLevelName, "none">;
|
|
539
589
|
}
|
|
590
|
+
/**
|
|
591
|
+
* One deny rule of the sandbox command policy — plain project-editable data. The factory
|
|
592
|
+
* rules are seeded into new projects and carry no special status thereafter: every rule
|
|
593
|
+
* can be edited, disabled, or deleted.
|
|
594
|
+
*/
|
|
595
|
+
interface CommandPolicyRuleDto {
|
|
596
|
+
name: string;
|
|
597
|
+
/** JavaScript regex source, matched against the whitespace-normalized command. */
|
|
598
|
+
pattern: string;
|
|
599
|
+
/** What the rule catches (free text). */
|
|
600
|
+
description?: string;
|
|
601
|
+
/** Per-rule switch, effective value (defaults on). */
|
|
602
|
+
enabled: boolean;
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Per-Project sandbox command policy: deny rules for shell commands, evaluated ahead of
|
|
606
|
+
* the approval mode (a hit is denied even under allow-all). Serves as the GET response and
|
|
607
|
+
* the PUT response. The PUT request body carries `enabled?` plus the full `rules` list
|
|
608
|
+
* (required — a PUT always materializes the list into the config, model-presets style);
|
|
609
|
+
* per-rule `enabled` may be omitted there and defaults to on. Owner-only to write; any
|
|
610
|
+
* member may read.
|
|
611
|
+
*/
|
|
612
|
+
interface CommandPolicyDto {
|
|
613
|
+
/** Effective master switch; an absent stored value reads as true (the policy defaults on). */
|
|
614
|
+
enabled: boolean;
|
|
615
|
+
/** The effective rule list — the factory set when the project predates seeding and has none stored. */
|
|
616
|
+
rules: CommandPolicyRuleDto[];
|
|
617
|
+
/** The factory set, served for the settings UI's "restore defaults". */
|
|
618
|
+
defaultRules: CommandPolicyRuleDto[];
|
|
619
|
+
}
|
|
540
620
|
/** Read-only vault entry display: key name + masked value; plaintext is never sent. */
|
|
541
621
|
interface VaultEntryInfo {
|
|
542
622
|
key: string;
|
|
@@ -744,6 +824,8 @@ interface MemoryScopeInfo {
|
|
|
744
824
|
workspacePath?: string;
|
|
745
825
|
/** Number of Markdown topic files in the directory (the `MEMORY.md` index not counted). */
|
|
746
826
|
fileCount: number;
|
|
827
|
+
/** Whether the directory holds a `MEMORY.md` index, so an import confirmation can say whether one would be replaced. */
|
|
828
|
+
hasIndex: boolean;
|
|
747
829
|
/** Most recent topic-file mtime in the directory (ISO 8601); unset when the directory holds no topic file. */
|
|
748
830
|
updatedAt?: string;
|
|
749
831
|
}
|
|
@@ -783,6 +865,64 @@ interface MemoryFileResponse {
|
|
|
783
865
|
file: MemoryFileInfo;
|
|
784
866
|
content: string;
|
|
785
867
|
}
|
|
868
|
+
/** One topic file inside a transfer document: the name it had in its scope, and its whole text. */
|
|
869
|
+
interface MemoryTransferFile {
|
|
870
|
+
/** File name inside the scope directory, e.g. `prefers-pnpm.md` — a name, never a path. */
|
|
871
|
+
name: string;
|
|
872
|
+
/** The file's full Markdown text, frontmatter included. */
|
|
873
|
+
content: string;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* GET …/memory/scopes/:key/export, and the body a POST …/import carries back: everything one
|
|
877
|
+
* scope holds, as one JSON document — the topic files and the scope's own `MEMORY.md`.
|
|
878
|
+
*/
|
|
879
|
+
interface MemoryScopeExport {
|
|
880
|
+
/** Format marker, so a foreign JSON file is refused with a clear reason rather than half-imported. */
|
|
881
|
+
format: "penguin-memory-scope";
|
|
882
|
+
/** Document version. A reader accepts exactly this; a later format bumps it and states its own compatibility. */
|
|
883
|
+
version: 1;
|
|
884
|
+
/** The scope this was exported from. Informational: an import writes into the scope its URL names. */
|
|
885
|
+
scopeKey: string;
|
|
886
|
+
kind: MemoryScopeInfo["kind"];
|
|
887
|
+
/** The Workspace the source scope stood for, when it had a `.workspace` marker. */
|
|
888
|
+
workspacePath?: string;
|
|
889
|
+
/** When the document was produced (ISO 8601). */
|
|
890
|
+
exportedAt: string;
|
|
891
|
+
/** The scope's `MEMORY.md`, or null when the scope has none. Only the index reaches the model's context. */
|
|
892
|
+
index: string | null;
|
|
893
|
+
files: MemoryTransferFile[];
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* What an import does with a name the target scope already holds:
|
|
897
|
+
* - `skip` — keep what is on disk, write only names the scope does not have (destroys nothing);
|
|
898
|
+
* - `overwrite` — replace a same-named file's content;
|
|
899
|
+
* - `replace` — additionally delete every topic file the document does not carry.
|
|
900
|
+
* The two destructive modes require `confirm`.
|
|
901
|
+
*/
|
|
902
|
+
type MemoryImportMode = "skip" | "overwrite" | "replace";
|
|
903
|
+
/** POST …/memory/scopes/:key/import */
|
|
904
|
+
interface MemoryImportRequest {
|
|
905
|
+
/** Defaults to `skip`. */
|
|
906
|
+
mode?: MemoryImportMode;
|
|
907
|
+
/** Required by `overwrite` and `replace`; without it they are refused with 409 `memory_import_confirm_required`. */
|
|
908
|
+
confirm?: boolean;
|
|
909
|
+
payload: MemoryScopeExport;
|
|
910
|
+
}
|
|
911
|
+
/** What one import did, name by name, so the UI can report it rather than claim success. */
|
|
912
|
+
interface MemoryImportResponse {
|
|
913
|
+
scopeKey: string;
|
|
914
|
+
mode: MemoryImportMode;
|
|
915
|
+
/** Names written that the scope did not have. */
|
|
916
|
+
added: string[];
|
|
917
|
+
/** Names whose existing content was replaced. */
|
|
918
|
+
overwritten: string[];
|
|
919
|
+
/** Names left untouched because the scope already had them (`skip` only). */
|
|
920
|
+
skipped: string[];
|
|
921
|
+
/** Names deleted because `replace` dropped everything the document did not carry. */
|
|
922
|
+
removed: string[];
|
|
923
|
+
/** Whether the scope's `MEMORY.md` was written or extended. */
|
|
924
|
+
indexWritten: boolean;
|
|
925
|
+
}
|
|
786
926
|
interface SessionInfo {
|
|
787
927
|
sessionId: string;
|
|
788
928
|
projectId: string;
|
|
@@ -1190,6 +1330,8 @@ interface SessionProcessInfo {
|
|
|
1190
1330
|
cwd: string;
|
|
1191
1331
|
startedAt: string;
|
|
1192
1332
|
running: boolean;
|
|
1333
|
+
/** The service the process serves, when detected: the last local URL its output printed, else an origin probed from its listening ports. */
|
|
1334
|
+
serviceUrl?: string;
|
|
1193
1335
|
}
|
|
1194
1336
|
interface SessionProcessesResponse {
|
|
1195
1337
|
processes: SessionProcessInfo[];
|
|
@@ -1647,35 +1789,47 @@ interface UsageGroupRow {
|
|
|
1647
1789
|
cost: number | null;
|
|
1648
1790
|
hasUncosted: boolean;
|
|
1649
1791
|
}
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1792
|
+
/** Time-series precision for the usage series (`granularity` query parameter). `minute` requires the `fromTs`/`toTs` window bounds. */
|
|
1793
|
+
type UsageGranularity = "minute" | "hour" | "day" | "week" | "month";
|
|
1794
|
+
/**
|
|
1795
|
+
* One bucket of the usage time series (for the cost center's time-series charts).
|
|
1796
|
+
* Buckets are zero-filled across the whole requested range, so consecutive points
|
|
1797
|
+
* are always adjacent in time. Bucket keys by granularity: minute
|
|
1798
|
+
* `yyyy-mm-ddThh:mm` and hour `yyyy-mm-ddThh:00` (server-local clock), day
|
|
1799
|
+
* `yyyy-mm-dd`, week the ISO week's Monday `yyyy-mm-dd`, month `yyyy-mm`.
|
|
1800
|
+
*/
|
|
1801
|
+
interface UsageSeriesPoint {
|
|
1802
|
+
bucket: string;
|
|
1655
1803
|
cacheRead: number;
|
|
1656
1804
|
cacheWrite: number;
|
|
1657
1805
|
output: number;
|
|
1806
|
+
total: number;
|
|
1807
|
+
/** Cost converted at query time (USD); null when no priced Model contributed. */
|
|
1808
|
+
cost: number | null;
|
|
1809
|
+
requests: number;
|
|
1810
|
+
/** Successful requests in the bucket. */
|
|
1811
|
+
completed: number;
|
|
1812
|
+
/** Success-rate denominator: all requests minus aborted (a user interruption is not a model failure). */
|
|
1813
|
+
denominator: number;
|
|
1658
1814
|
}
|
|
1659
|
-
/**
|
|
1660
|
-
|
|
1815
|
+
/**
|
|
1816
|
+
* One entity's per-bucket request and success counts, aligned index-for-index
|
|
1817
|
+
* with `series` (the requests-and-success-rate chart draws one such entity —
|
|
1818
|
+
* or stacks them all). `denominator` excludes aborted, same as elsewhere.
|
|
1819
|
+
*/
|
|
1820
|
+
interface UsageEntitySeriesCounts {
|
|
1821
|
+
requests: number[];
|
|
1822
|
+
completed: number[];
|
|
1823
|
+
denominator: number[];
|
|
1824
|
+
}
|
|
1825
|
+
/** Per-Agent counts per bucket. */
|
|
1826
|
+
interface UsageAgentSeries extends UsageEntitySeriesCounts {
|
|
1661
1827
|
agentId: string;
|
|
1662
|
-
requests: number;
|
|
1663
|
-
total: number;
|
|
1664
1828
|
}
|
|
1665
|
-
/**
|
|
1666
|
-
interface
|
|
1829
|
+
/** Per-Model counts per bucket (entity identity is the (provider, modelId) pair). */
|
|
1830
|
+
interface UsageModelSeries extends UsageEntitySeriesCounts {
|
|
1667
1831
|
provider: string;
|
|
1668
1832
|
modelId: string;
|
|
1669
|
-
/** Number of successful requests. */
|
|
1670
|
-
completed: number;
|
|
1671
|
-
/** Success rate denominator = all requests − aborted (user-initiated interruption isn't a model failure and shouldn't lower the success rate). */
|
|
1672
|
-
total: number;
|
|
1673
|
-
/** Count of user interruptions (excluded from success rate, shown separately). */
|
|
1674
|
-
aborted: number;
|
|
1675
|
-
/** Failure breakdown (shown on hover; unknown statuses count toward total but not these three). */
|
|
1676
|
-
failed: number;
|
|
1677
|
-
timeout: number;
|
|
1678
|
-
malformed: number;
|
|
1679
1833
|
}
|
|
1680
1834
|
/** Occurrence count of an error for a given source · code (the "most common" metric in the stats center's error panel). */
|
|
1681
1835
|
interface UsageErrorCount {
|
|
@@ -1728,12 +1882,27 @@ interface UsageResponse {
|
|
|
1728
1882
|
};
|
|
1729
1883
|
groupBy: UsageGroupBy;
|
|
1730
1884
|
groups: UsageGroupRow[];
|
|
1731
|
-
/**
|
|
1732
|
-
|
|
1733
|
-
/**
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1885
|
+
/** Effective precision of `series` (the validated `granularity` query parameter; defaults to day). */
|
|
1886
|
+
granularity: UsageGranularity;
|
|
1887
|
+
/**
|
|
1888
|
+
* Usage time series over the requested from/to range (defaulting to the last 30
|
|
1889
|
+
* days), zero-filled at `granularity`; affected by agent/model filters. Carries
|
|
1890
|
+
* everything the time-series charts draw: Token buckets, cost, request count,
|
|
1891
|
+
* and per-bucket success counts.
|
|
1892
|
+
*/
|
|
1893
|
+
series: UsageSeriesPoint[];
|
|
1894
|
+
/**
|
|
1895
|
+
* Per-Agent counts per bucket, aligned index-for-index with `series`, sorted
|
|
1896
|
+
* by total requests descending. Unaffected by the agent filter — the by-Agent
|
|
1897
|
+
* chart draws the whole breakdown — but affected by date/model filters.
|
|
1898
|
+
*/
|
|
1899
|
+
byAgentSeries: UsageAgentSeries[];
|
|
1900
|
+
/**
|
|
1901
|
+
* Per-Model counts per bucket, aligned index-for-index with `series`, sorted
|
|
1902
|
+
* by total requests descending. Unaffected by the model filter — the by-Model
|
|
1903
|
+
* chart draws the whole breakdown — but affected by date/agent filters.
|
|
1904
|
+
*/
|
|
1905
|
+
byModelSeries: UsageModelSeries[];
|
|
1737
1906
|
/** Server-side error capture stats (affected by date/agent filters; unaffected by model filter). */
|
|
1738
1907
|
errors: UsageErrors;
|
|
1739
1908
|
/** List of Agent ids that have appeared in this Project (for the filter dropdown; unaffected by current filters). */
|
|
@@ -1952,6 +2121,51 @@ interface UpdateCheckResponse {
|
|
|
1952
2121
|
/** Why the lookup failed: unreachable network / GitHub rate limit / unusable response. */
|
|
1953
2122
|
error?: "network" | "rate_limited" | "bad_response";
|
|
1954
2123
|
}
|
|
2124
|
+
/**
|
|
2125
|
+
* The desktop shell's updater snapshot, pushed to the embedded server over the
|
|
2126
|
+
* utilityProcess message channel and served at GET /api/desktop/update. `state` is the
|
|
2127
|
+
* discriminator; the optional fields belong to the states named on them.
|
|
2128
|
+
*
|
|
2129
|
+
* A `downloaded` build stays the reported state until it is installed: a later periodic
|
|
2130
|
+
* check (or its failure) must not hide the actionable "restart to install" step.
|
|
2131
|
+
*/
|
|
2132
|
+
interface DesktopUpdateStatus {
|
|
2133
|
+
/** Installed shell version (Electron app.getVersion()). */
|
|
2134
|
+
appVersion: string;
|
|
2135
|
+
/**
|
|
2136
|
+
* Bumped by the shell on every updater event it folds, whether or not the visible
|
|
2137
|
+
* state changed. A row-initiated check settles when the seq has moved past its
|
|
2138
|
+
* at-click value and the state is no longer `checking` — snapshot equality can't
|
|
2139
|
+
* carry that signal (a check that ends where it started is byte-identical).
|
|
2140
|
+
*/
|
|
2141
|
+
seq?: number;
|
|
2142
|
+
state: "idle" | "checking" | "up-to-date" | "downloading" | "downloaded" | "error" | "unsupported";
|
|
2143
|
+
/** Newer release being fetched / ready to install (`downloading`, `downloaded`). */
|
|
2144
|
+
version?: string;
|
|
2145
|
+
/** Download progress 0–100 (`downloading`). */
|
|
2146
|
+
percent?: number;
|
|
2147
|
+
/** Updater failure text (`error`). */
|
|
2148
|
+
message?: string;
|
|
2149
|
+
/** Why this install form cannot update itself (`unsupported`): dev run, or a Linux install that is not an AppImage (e.g. .deb — the system package manager owns it). */
|
|
2150
|
+
reason?: "dev" | "linux-not-appimage";
|
|
2151
|
+
}
|
|
2152
|
+
/**
|
|
2153
|
+
* GET /api/desktop/update (desktop-shell sessions only): the latest shell snapshot.
|
|
2154
|
+
* `status` is null until the shell's first push lands (a beat after server start).
|
|
2155
|
+
*/
|
|
2156
|
+
interface DesktopUpdateStatusResponse {
|
|
2157
|
+
status: DesktopUpdateStatus | null;
|
|
2158
|
+
}
|
|
2159
|
+
/** Shell → server push over the utilityProcess message channel. */
|
|
2160
|
+
interface DesktopUpdaterStatusMessage {
|
|
2161
|
+
type: "desktop-updater-status";
|
|
2162
|
+
status: DesktopUpdateStatus;
|
|
2163
|
+
}
|
|
2164
|
+
/** Server → shell command over the utilityProcess message channel (relayed from POST /api/desktop/update/check|install). */
|
|
2165
|
+
interface DesktopUpdaterCommandMessage {
|
|
2166
|
+
type: "desktop-updater-command";
|
|
2167
|
+
action: "check" | "install";
|
|
2168
|
+
}
|
|
1955
2169
|
/**
|
|
1956
2170
|
* POST /api/version/update (admin only): runs the CLI self-update (`penguin update --yes`)
|
|
1957
2171
|
* on the server host. `unsupported` covers both a server not launched via the CLI and the
|
|
@@ -1967,4 +2181,4 @@ interface UpdateRunResponse {
|
|
|
1967
2181
|
needsRestart: boolean;
|
|
1968
2182
|
}
|
|
1969
2183
|
|
|
1970
|
-
export type { AdminPasswordResetRequest, AdminUserCreateRequest, AdminUserCreateResponse, AdminUsersResponse, AgentCompactionConfigDto, AgentConfigDto, AgentConfigResponse, AgentConfigUpdateRequest, AgentCreateRequest, AgentCreateResponse, AgentImportRequest, AgentImportResponse, AgentKernelUpdateResponse, AgentMemoryConfigDto, AgentModelConfigDto, AgentSchedulesConfigDto, AgentSkillsConfigDto, AgentSkillsResponse, AgentSummary, AgentTraceDateGroup, AgentTraceFileRef, AgentTraceSessionEntry, AgentTraceSessionFile, AgentTraceSessionGroup, AgentTracesResponse, AgentVaultConfigDto, AgentsResponse, ApprovalDecisionRequest, ApprovalMode, AuthLoginRequest, AuthResponse, BenchmarkCaseScore, BenchmarkCaseSummary, BenchmarkCasesResponse, BenchmarkEvaluation, BenchmarkRunScore, BenchmarkSummary, BenchmarksResponse, CaseMaterial, ChatDefaultsDto, CredentialInfo, DefaultModelResponse, DefaultModelUpdateRequest, DirEntryInfo, DirListResponse, ErrorBody, FilesStatRequest, FilesStatResponse, GoalResponse, GoalServerEvent, GoalStateView, HistoryMessage, McpServerTestResponse, MeResponse, MemberAddRequest, MemberAddResponse, MemberInfo, MembersResponse, MemoryFileInfo, MemoryFileResponse, MemoryFilesResponse, MemoryOverviewResponse, MemoryScopeInfo, MessagesLiveTail, MessagesPageInfo, MessagesResponse, ModelInfo, ModelPricingDto, ModelProtocolDetectRequest, ModelProtocolDetectResponse, ModelProtocolProbeDto, ModelRefDto, ModelTestRequest, ModelTestResponse, ModelUpdateEntry, ModelVisionDetectRequest, ModelVisionDetectResponse, ModelVisionOutcome, ModelsResponse, ModelsUpdateRequest, PasswordChangeRequest, PendingFollowUpInfo, PendingSteeringInfo, PrefsResponse, ProjectCreateRequest, ProjectCreateResponse, ProjectRole, ProjectSummary, ProjectUpdateRequest, ProjectUpdateResponse, ProjectsResponse, ProtocolProbeOutcome, RecalledMessageResponse, RequestSpan, RetryNowResponse, ScheduleItem, ScheduleServerEvent, ScheduleStatus, ScheduleUpsertRequest, SchedulesResponse, ServerEvent, ServerSettings, ServerSettingsResponse, ServerSettingsUpdateRequest, SessionCategory, SessionCategoryCounts, SessionCreateRequest, SessionCreateResponse, SessionForkRequest, SessionForkResponse, SessionInfo, SessionPatchRequest, SessionProcessInfo, SessionProcessesResponse, SessionResponse, SessionSource, SessionStatus, SessionTracesResponse, SessionsResponse, SkillArchiveInstallRequest, SkillGroupItem, SkillInstallRequest, SkillLibraryResponse, SkillMetadataItem, SteerRequest, TaskCreateRequest, TaskCreateResponse, TaskInputPart, ToolCallSpan, TraceAnalysisResponse, TraceEventsResponse, TraceFileInfo, TraceImportRequest, TraceImportResponse, TraceModelSegment, TraceOtherSpan, TracePosition, TraceTaskStats, TraceToolSpan, UiPrefs, UpdateCheckResponse, UpdateRunResponse, UploadLimits,
|
|
2184
|
+
export type { AdminPasswordResetRequest, AdminUserCreateRequest, AdminUserCreateResponse, AdminUsersResponse, AgentCompactionConfigDto, AgentConfigDto, AgentConfigResponse, AgentConfigUpdateRequest, AgentCreateRequest, AgentCreateResponse, AgentImportRequest, AgentImportResponse, AgentKernelUpdateResponse, AgentMemoryConfigDto, AgentModelConfigDto, AgentSchedulesConfigDto, AgentSkillsConfigDto, AgentSkillsResponse, AgentSummary, AgentTraceDateGroup, AgentTraceFileRef, AgentTraceSessionEntry, AgentTraceSessionFile, AgentTraceSessionGroup, AgentTracesResponse, AgentVaultConfigDto, AgentsResponse, ApprovalDecisionRequest, ApprovalMode, AuthLoginRequest, AuthResponse, BenchmarkCaseScore, BenchmarkCaseSummary, BenchmarkCasesResponse, BenchmarkEvaluation, BenchmarkRunScore, BenchmarkSummary, BenchmarksResponse, CaseMaterial, ChatDefaultsDto, CommandPolicyDto, CommandPolicyRuleDto, CredentialInfo, DefaultModelResponse, DefaultModelUpdateRequest, DesktopUpdateStatus, DesktopUpdateStatusResponse, DesktopUpdaterCommandMessage, DesktopUpdaterStatusMessage, DirEntryInfo, DirListResponse, DraftShortcut, EndpointModelListRequest, EndpointModelListResponse, ErrorBody, FilesStatRequest, FilesStatResponse, GoalResponse, GoalServerEvent, GoalStateView, HistoryMessage, McpServerTestResponse, MeResponse, MemberAddRequest, MemberAddResponse, MemberInfo, MembersResponse, MemoryFileInfo, MemoryFileResponse, MemoryFilesResponse, MemoryImportMode, MemoryImportRequest, MemoryImportResponse, MemoryOverviewResponse, MemoryScopeExport, MemoryScopeInfo, MemoryTransferFile, MessagesLiveTail, MessagesPageInfo, MessagesResponse, ModelInfo, ModelPricingDto, ModelProtocolDetectRequest, ModelProtocolDetectResponse, ModelProtocolProbeDto, ModelRefDto, ModelTestRequest, ModelTestResponse, ModelUpdateEntry, ModelVisionDetectRequest, ModelVisionDetectResponse, ModelVisionOutcome, ModelsResponse, ModelsUpdateRequest, PasswordChangeRequest, PendingFollowUpInfo, PendingSteeringInfo, PrefsResponse, ProjectCreateRequest, ProjectCreateResponse, ProjectRole, ProjectSummary, ProjectUpdateRequest, ProjectUpdateResponse, ProjectsResponse, ProtocolProbeOutcome, RecalledMessageResponse, RequestSpan, RetryNowResponse, ScheduleItem, ScheduleServerEvent, ScheduleStatus, ScheduleUpsertRequest, SchedulesResponse, ServerEvent, ServerSettings, ServerSettingsResponse, ServerSettingsUpdateRequest, SessionCategory, SessionCategoryCounts, SessionCreateRequest, SessionCreateResponse, SessionForkRequest, SessionForkResponse, SessionInfo, SessionPatchRequest, SessionProcessInfo, SessionProcessesResponse, SessionResponse, SessionSource, SessionStatus, SessionTracesResponse, SessionsResponse, SkillArchiveInstallRequest, SkillGroupItem, SkillInstallRequest, SkillLibraryResponse, SkillMetadataItem, SteerRequest, TaskCreateRequest, TaskCreateResponse, TaskInputPart, ToolCallSpan, TraceAnalysisResponse, TraceEventsResponse, TraceFileInfo, TraceImportRequest, TraceImportResponse, TraceModelSegment, TraceOtherSpan, TracePosition, TraceTaskStats, TraceToolSpan, UiPrefs, UpdateCheckResponse, UpdateRunResponse, UploadLimits, UsageAgentSeries, UsageBucket, UsageEntitySeriesCounts, UsageErrorCount, UsageErrorItem, UsageErrors, UsageErrorsPage, UsageGranularity, UsageGroupBy, UsageGroupRow, UsageModelSeries, UsageResponse, UsageSeriesPoint, UsageTrendPointInTrace, UserInfo, VaultEntryInfo, VaultEntryUpdate, VaultResponse, VaultUpdateRequest, VersionResponse, WorkspaceFileEntry, WorkspaceFilesResponse };
|
|
@@ -282,7 +282,7 @@ var UsersRepo = class {
|
|
|
282
282
|
|
|
283
283
|
// src/auth/password.ts
|
|
284
284
|
import { randomBytes, scrypt, timingSafeEqual } from "crypto";
|
|
285
|
-
var
|
|
285
|
+
var SCRYPT_COST = 16384;
|
|
286
286
|
var SCRYPT_R = 8;
|
|
287
287
|
var SCRYPT_P = 1;
|
|
288
288
|
var SALT_BYTES = 16;
|
|
@@ -295,12 +295,12 @@ function scryptAsync(password, salt, keyLen, n, r, p) {
|
|
|
295
295
|
});
|
|
296
296
|
});
|
|
297
297
|
}
|
|
298
|
-
async function hashPassword(password) {
|
|
298
|
+
async function hashPassword(password, cost = SCRYPT_COST) {
|
|
299
299
|
const salt = randomBytes(SALT_BYTES);
|
|
300
|
-
const key = await scryptAsync(password, salt, KEY_BYTES,
|
|
300
|
+
const key = await scryptAsync(password, salt, KEY_BYTES, cost, SCRYPT_R, SCRYPT_P);
|
|
301
301
|
return [
|
|
302
302
|
"scrypt",
|
|
303
|
-
String(
|
|
303
|
+
String(cost),
|
|
304
304
|
String(SCRYPT_R),
|
|
305
305
|
String(SCRYPT_P),
|
|
306
306
|
salt.toString("base64"),
|
|
@@ -393,9 +393,11 @@ var AuthService = class {
|
|
|
393
393
|
constructor(deps) {
|
|
394
394
|
this.deps = deps;
|
|
395
395
|
this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
396
|
+
this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
|
|
396
397
|
}
|
|
397
398
|
deps;
|
|
398
399
|
now;
|
|
400
|
+
hashCost;
|
|
399
401
|
/**
|
|
400
402
|
* Startup seeding (idempotent): creates the built-in admin and adopts
|
|
401
403
|
* default_project when the users table is empty; if the initial Project fails,
|
|
@@ -414,7 +416,7 @@ var AuthService = class {
|
|
|
414
416
|
}
|
|
415
417
|
const user = {
|
|
416
418
|
userId: ADMIN_USER_ID,
|
|
417
|
-
passwordHash: await hashPassword(password),
|
|
419
|
+
passwordHash: await hashPassword(password, this.hashCost),
|
|
418
420
|
isAdmin: true,
|
|
419
421
|
passwordIsInitial: true,
|
|
420
422
|
createdAt: this.now().toISOString()
|
|
@@ -492,7 +494,7 @@ var AuthService = class {
|
|
|
492
494
|
if (newPassword.length < MIN_PASSWORD_LENGTH) {
|
|
493
495
|
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
|
|
494
496
|
}
|
|
495
|
-
this.deps.users.updatePassword(userId, await hashPassword(newPassword), false);
|
|
497
|
+
this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
|
|
496
498
|
this.deps.onPasswordChanged?.(userId);
|
|
497
499
|
}
|
|
498
500
|
/**
|
|
@@ -505,7 +507,7 @@ var AuthService = class {
|
|
|
505
507
|
if (newPassword.length < MIN_PASSWORD_LENGTH) {
|
|
506
508
|
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
|
|
507
509
|
}
|
|
508
|
-
this.deps.users.updatePassword(userId, await hashPassword(newPassword), false);
|
|
510
|
+
this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
|
|
509
511
|
this.deps.onPasswordChanged?.(userId);
|
|
510
512
|
}
|
|
511
513
|
logout(token) {
|
|
@@ -555,6 +557,7 @@ export {
|
|
|
555
557
|
isMissingCredential,
|
|
556
558
|
modelCredentialMissing,
|
|
557
559
|
handleError,
|
|
560
|
+
SCRYPT_COST,
|
|
558
561
|
hashPassword,
|
|
559
562
|
MIN_PASSWORD_LENGTH,
|
|
560
563
|
ADMIN_USER_ID,
|
|
@@ -562,4 +565,4 @@ export {
|
|
|
562
565
|
toUserInfo,
|
|
563
566
|
AuthService
|
|
564
567
|
};
|
|
565
|
-
//# sourceMappingURL=chunk-
|
|
568
|
+
//# sourceMappingURL=chunk-KQQ3HSTK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/db/database.ts","../src/db/schema.ts","../src/db/repos/auth-sessions.ts","../src/db/repos/users.ts","../src/auth/password.ts","../src/auth/service.ts","../src/http/errors.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 { 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/** 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 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, \"auth_sessions\", \"via\", \"TEXT\");\n ensureColumn(db, \"trace_files\", \"page_stats\", \"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 upgradeLastActiveAt(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 */\nfunction ensureColumn(db: DatabaseSync, table: string, column: string, ddl: string): 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 * 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 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 created_at TEXT NOT NULL\n);\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, -- 7-day sliding renewal (topped up when <6 days remain)\n via TEXT -- 'password' | 'desktop'; NULL = legacy row (password)\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);\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 model (paired with model_id as a model reference)\n model_id TEXT NOT NULL, -- upstream model id (sent to AgentHub 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, -- archive time; NULL=not archived (shown by default; archived ones move under \"Archived\")\n client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); 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 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 schedule/subagent SOURCE 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)\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\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 goal_state ( -- goal-mode runtime state (GOAL.yaml on disk is the model-facing protocol; this row is what the UI reads)\n id INTEGER PRIMARY KEY AUTOINCREMENT, -- one row per goal run; a Session may run goals repeatedly, latest row wins for display\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, -- active | complete | blocked | budget_limited | aborted (aborted is server-side only; on-disk status stays active)\n budget INTEGER NOT NULL, -- token budget; -1 = unlimited\n used INTEGER NOT NULL DEFAULT 0, -- uncached input + output, refreshed per round (mirrors the runner's accounting)\n rounds INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);\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 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 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 origin: 'subagent' | 'schedule' | NULL = user-created (or head not yet readable)\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 (CLI adoption reads it from here; 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);\n`;\n","/**\n * auth_sessions table repo (server-side sessions backing the HttpOnly cookie).\n *\n * Stores only the sha256(token) hex hash; the raw token appears only in the cookie.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\n\nexport interface AuthSessionRow {\n tokenHash: string;\n userId: string;\n createdAt: string;\n expiresAt: string;\n /** How the session was established (\"password\" | \"desktop\"); null on rows formed before the column existed (treated as \"password\"). */\n via: string | null;\n}\n\nexport class AuthSessionsRepo {\n constructor(private readonly db: DatabaseSync) {}\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 string | 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 * 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 type { DatabaseSync } from \"node:sqlite\";\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 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 createdAt: r.created_at as string,\n };\n}\n\nexport class UsersRepo {\n constructor(private readonly db: DatabaseSync) {}\n\n insert(row: UserRow): void {\n this.db\n .prepare(\n \"INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, created_at) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(\n row.userId,\n row.passwordHash,\n row.isAdmin ? 1 : 0,\n row.passwordIsInitial ? 1 : 0,\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 /** 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 * Password hashing (slow-hash storage).\n *\n * Uses node:crypto's scrypt (built-in, no extra dependency, meets the same\n * slow-hash requirement as bcrypt/argon2). Storage format:\n * `scrypt$N$r$p$<salt b64>$<hash b64>` — parameters are stored alongside the hash,\n * so old hashes remain verifiable after future parameter tuning; comparison uses\n * timingSafeEqual to guard against timing side-channels.\n */\nimport { randomBytes, scrypt, timingSafeEqual } from \"node:crypto\";\n\n/**\n * Work factor for new hashes. `hashPassword` takes it as a defaulted argument so the server's\n * own test suite can hash at a token cost: almost every case there seeds an admin, provisions\n * users and logs them in, and one derivation at this strength costs on the order of 100ms.\n * Nothing on the production path passes the argument, and no configuration reaches it —\n * `buildAppDeps`, which carries the test override, is not part of this package's exports.\n */\nexport const SCRYPT_COST = 16384;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SALT_BYTES = 16;\nconst KEY_BYTES = 64;\n\nfunction scryptAsync(\n password: string,\n salt: Buffer,\n keyLen: number,\n n: number,\n r: number,\n p: number,\n): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n scrypt(password, salt, keyLen, { N: n, r, p, maxmem: 128 * 1024 * 1024 }, (err, key) => {\n if (err) reject(err);\n else resolve(key);\n });\n });\n}\n\n/**\n * Generates a password hash in `scrypt$N$r$p$salt$hash` format. `cost` is scrypt's N and\n * is recorded in the hash, so `verifyPassword` re-derives at whatever cost produced the\n * stored string.\n */\nexport async function hashPassword(password: string, cost: number = SCRYPT_COST): Promise<string> {\n const salt = randomBytes(SALT_BYTES);\n const key = await scryptAsync(password, salt, KEY_BYTES, cost, SCRYPT_R, SCRYPT_P);\n return [\n \"scrypt\",\n String(cost),\n String(SCRYPT_R),\n String(SCRYPT_P),\n salt.toString(\"base64\"),\n key.toString(\"base64\"),\n ].join(\"$\");\n}\n\n/** Verifies a password; returns false if the stored string has an invalid format (never throws, so the login path can uniformly treat it as a credential error). */\nexport async function verifyPassword(password: string, stored: string): Promise<boolean> {\n const parts = stored.split(\"$\");\n if (parts.length !== 6 || parts[0] !== \"scrypt\") return false;\n const n = Number(parts[1]);\n const r = Number(parts[2]);\n const p = Number(parts[3]);\n if (!Number.isInteger(n) || !Number.isInteger(r) || !Number.isInteger(p)) return false;\n let salt: Buffer;\n let expected: Buffer;\n try {\n salt = Buffer.from(parts[4]!, \"base64\");\n expected = Buffer.from(parts[5]!, \"base64\");\n } catch {\n return false;\n }\n if (salt.length === 0 || expected.length === 0) return false;\n let actual: Buffer;\n try {\n actual = await scryptAsync(password, salt, expected.length, n, r, p);\n } catch {\n return false;\n }\n return actual.length === expected.length && timingSafeEqual(actual, expected);\n}\n","/**\n * Auth service: built-in admin seeding /\n * login / logout / password change / session validation.\n *\n * - No open registration: on startup, if there are no users at all, the built-in\n * admin `admin` is seeded with a random `penguin-<4 digits>` initial password\n * (printed once by the startup entrypoint; PENGUIN_SEED_ADMIN_PASSWORD injects\n * a fixed one for tests/e2e), and it adopts `default_project`; all other users\n * are created by an admin via the user backend (admin-service).\n * - An initial password (whether seeded or set by an admin) is flagged with\n * password_is_initial, which the frontend uses to prompt for a password change soon.\n * - Sessions: a 32-byte random token, with only its sha256 hash stored in the DB;\n * valid for 7 days, with sliding renewal once less than 6 days remain.\n */\nimport { createHash, randomBytes, randomInt } from \"node:crypto\";\nimport type { UserInfo } from \"../api/types.js\";\nimport { HttpError } from \"../http/errors.js\";\nimport type { AuthSessionsRepo } from \"../db/repos/auth-sessions.js\";\nimport type { UserRow, UsersRepo } from \"../db/repos/users.js\";\nimport { SCRYPT_COST, hashPassword, verifyPassword } from \"./password.js\";\n\nexport const MIN_PASSWORD_LENGTH = 8;\n\n/** Built-in admin user_id. */\nexport const ADMIN_USER_ID = \"admin\";\n\n/**\n * Login throttling (per userId): the seeded initial password is `penguin-<4 digits>` —\n * 10,000 combinations — so unthrottled guessing would enumerate it in minutes. After\n * LOGIN_FREE_ATTEMPTS consecutive failures, the next attempt is admitted only after an\n * exponentially growing delay from the last failure (1s, 2s, … capped at 60s; attempts\n * inside the window are 429 `too_many_attempts` and do not extend it). Beyond ~40\n * failures that is one guess per minute, so the 10k space stops being enumerable, while\n * a legitimate user who mistyped a few times never waits more than the cap. A successful\n * login clears the counter. Counters are process memory (a restart clears them —\n * restarting is slower than waiting out the cap) and are kept for nonexistent userIds\n * too, so throttling is not an account-existence oracle. Known limit: a concurrent burst\n * can slip in before its first failure is recorded; the steady-state backoff still\n * dominates the search space.\n */\nconst LOGIN_FREE_ATTEMPTS = 5;\nconst LOGIN_BACKOFF_START_MS = 1000;\nconst LOGIN_BACKOFF_CAP_MS = 60_000;\n/** Failure entries idle longer than this are swept (bounds the map; far above the cap). */\nconst LOGIN_FAILURE_IDLE_MS = 15 * 60_000;\n\n/**\n * Random initial password for the seeded admin: `penguin-<4 digits>` — brand-related and\n * easy to type, shown once in the server startup output (the README, docs and login-page\n * hint all describe this form).\n */\nexport function generateInitialAdminPassword(): string {\n return \"penguin-\" + String(randomInt(0, 10000)).padStart(4, \"0\");\n}\n\nfunction sha256Hex(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\n/**\n * How a session was established: \"password\" via the login form, \"desktop\" via the\n * desktop shell's one-shot token. Persisted per session so desktop-specific allowances\n * (password change without the old password) apply only to sessions the shell itself\n * opened. Legacy rows (NULL) read as \"password\".\n */\nexport type SessionVia = \"password\" | \"desktop\";\n\nexport function toUserInfo(row: UserRow): UserInfo {\n return {\n userId: row.userId,\n isAdmin: row.isAdmin,\n passwordIsInitial: row.passwordIsInitial,\n createdAt: row.createdAt,\n };\n}\n\nexport interface AuthServiceDeps {\n users: UsersRepo;\n authSessions: AuthSessionsRepo;\n /** Provisions the initial Project at signup (injected by project-service, to avoid a circular dependency). */\n provisionInitialProject: (user: UserRow, isAdmin: boolean) => Promise<void>;\n /** Fixed initial password for the seeded admin (config.seedAdminPassword); null generates a random one at seed time. */\n seedAdminPassword: string | null;\n /**\n * Fired after any successful password update (self change / desktop set). The server\n * wires it to drop the stored initial-password plaintext once it goes stale (see\n * initial-password.ts); standalone/test constructions may omit it.\n */\n onPasswordChanged?: (userId: string) => void;\n sessionTtlMs: number;\n sessionRenewMs: number;\n /**\n * Test double: scrypt work factor for hashes this service writes. Omitted in\n * production, where {@link SCRYPT_COST} applies.\n */\n passwordHashCost?: number;\n now?: () => Date;\n}\n\nexport class AuthService {\n private readonly now: () => Date;\n private readonly hashCost: number;\n\n constructor(private readonly deps: AuthServiceDeps) {\n this.now = deps.now ?? (() => new Date());\n this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;\n }\n\n /**\n * Startup seeding (idempotent): creates the built-in admin and adopts\n * default_project when the users table is empty; if the initial Project fails,\n * the user row is rolled back and the server retries on next startup.\n * Returns the initial password when it actually seeded — the caller prints it,\n * the only place a generated password is ever shown — and null when users\n * already exist.\n */\n async seedAdmin(): Promise<string | null> {\n if (this.deps.users.count() > 0) return null;\n const password = this.deps.seedAdminPassword ?? generateInitialAdminPassword();\n // The override (PENGUIN_SEED_ADMIN_PASSWORD) must meet the same policy as every\n // other initial/reset password; rejecting it here, before any insert, keeps a\n // configuration typo from creating a trivially weak privileged account. Generated\n // passwords are always 12 characters and never trip this.\n if (password.length < MIN_PASSWORD_LENGTH) {\n throw new Error(\n `PENGUIN_SEED_ADMIN_PASSWORD must be at least ${MIN_PASSWORD_LENGTH} characters.`,\n );\n }\n const user: UserRow = {\n userId: ADMIN_USER_ID,\n passwordHash: await hashPassword(password, this.hashCost),\n isAdmin: true,\n passwordIsInitial: true,\n createdAt: this.now().toISOString(),\n };\n this.deps.users.insert(user);\n try {\n await this.deps.provisionInitialProject(user, true);\n } catch (err) {\n this.deps.users.delete(user.userId);\n throw err;\n }\n return password;\n }\n\n /** Whether the built-in admin still runs on its initial password (drives the startup reminder notice). */\n adminPasswordIsInitial(): boolean {\n return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;\n }\n\n /** Consecutive login failures per userId (see the throttling comment on the constants). */\n private readonly loginFailures = new Map<string, { failures: number; lastFailureAt: number }>();\n\n /** The wait imposed after `failures` consecutive failures (0 while within the free attempts). */\n private loginDelayMs(failures: number): number {\n const excess = failures - LOGIN_FREE_ATTEMPTS;\n if (excess <= 0) return 0;\n return Math.min(LOGIN_BACKOFF_START_MS * 2 ** (excess - 1), LOGIN_BACKOFF_CAP_MS);\n }\n\n async login(userId: string, password: string): Promise<{ user: UserInfo; token: string }> {\n const nowMs = this.now().getTime();\n for (const [key, entry] of this.loginFailures) {\n if (nowMs - entry.lastFailureAt > LOGIN_FAILURE_IDLE_MS) this.loginFailures.delete(key);\n }\n const failed = this.loginFailures.get(userId);\n if (failed) {\n const readyAt = failed.lastFailureAt + this.loginDelayMs(failed.failures);\n if (nowMs < readyAt) {\n throw new HttpError(\n 429,\n \"too_many_attempts\",\n `Too many failed sign-in attempts. Try again in ${Math.ceil((readyAt - nowMs) / 1000)}s.`,\n );\n }\n }\n const row = this.deps.users.findById(userId);\n const ok = row !== null && (await verifyPassword(password, row.passwordHash));\n if (!row || !ok) {\n this.loginFailures.set(userId, {\n failures: (failed?.failures ?? 0) + 1,\n lastFailureAt: this.now().getTime(),\n });\n throw new HttpError(401, \"invalid_credentials\", \"Incorrect username or password.\");\n }\n this.loginFailures.delete(userId);\n this.deps.authSessions.deleteExpired(this.now().toISOString());\n return { user: toUserInfo(row), token: this.issueSession(row.userId, \"password\") };\n }\n\n /**\n * Desktop-mode sign-in: issues an admin session WITHOUT a password check — the caller\n * (the desktop-login route) has already redeemed the shell's one-shot token, which is\n * the credential here. Throws if the admin has not been seeded yet (desktop-login runs\n * after startup seeding, so this only trips on a broken deployment).\n */\n loginDesktop(): { user: UserInfo; token: string } {\n const row = this.deps.users.findById(ADMIN_USER_ID);\n if (!row) {\n throw new HttpError(500, \"internal\", \"Built-in admin has not been seeded.\");\n }\n this.deps.authSessions.deleteExpired(this.now().toISOString());\n return { user: toUserInfo(row), token: this.issueSession(row.userId, \"desktop\") };\n }\n\n /** Self password change (user settings): validates the old password, and on success clears the initial-password flag; the current session remains valid. */\n async changePassword(userId: string, oldPassword: string, newPassword: string): Promise<void> {\n const row = this.deps.users.findById(userId);\n if (!row || !(await verifyPassword(oldPassword, row.passwordHash))) {\n throw new HttpError(400, \"password_mismatch\", \"Current password is incorrect.\");\n }\n if (newPassword.length < MIN_PASSWORD_LENGTH) {\n throw new HttpError(400, \"invalid_password\", \"Password must be at least 8 characters.\");\n }\n this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);\n this.deps.onPasswordChanged?.(userId);\n }\n\n /**\n * Desktop-session password set: no old-password check. Only reachable for sessions\n * established via desktop-login (the me route gates on sessionVia) — the seed password\n * of a desktop-created root is random and never shown, so its holder has nothing to\n * type into an old-password field; the shell's token already proved machine ownership.\n */\n async setPasswordDesktop(userId: string, newPassword: string): Promise<void> {\n if (newPassword.length < MIN_PASSWORD_LENGTH) {\n throw new HttpError(400, \"invalid_password\", \"Password must be at least 8 characters.\");\n }\n this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);\n this.deps.onPasswordChanged?.(userId);\n }\n\n logout(token: string): void {\n this.deps.authSessions.delete(sha256Hex(token));\n }\n\n /** Validates the cookie token: returns null if expired/unknown; sliding renewal once less than 6 days remain. */\n authenticateWithMeta(token: string): { user: UserRow; via: SessionVia } | null {\n const tokenHash = sha256Hex(token);\n const session = this.deps.authSessions.findByTokenHash(tokenHash);\n if (!session) return null;\n const now = this.now();\n const expiresAt = Date.parse(session.expiresAt);\n if (!(expiresAt > now.getTime())) {\n this.deps.authSessions.delete(tokenHash);\n return null;\n }\n if (expiresAt - now.getTime() < this.deps.sessionRenewMs) {\n this.deps.authSessions.touch(\n tokenHash,\n new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),\n );\n }\n const user = this.deps.users.findById(session.userId);\n if (!user) return null;\n return { user, via: session.via === \"desktop\" ? \"desktop\" : \"password\" };\n }\n\n private issueSession(userId: string, via: SessionVia): string {\n const token = randomBytes(32).toString(\"base64url\");\n const now = this.now();\n this.deps.authSessions.insert({\n tokenHash: sha256Hex(token),\n userId,\n createdAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),\n via,\n });\n return token;\n }\n}\n","/**\n * Unified HTTP error: `{error: {code, message}}` 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 */\nimport type { Context } from \"hono\";\nimport type { ErrorBody } from \"../api/types.js\";\n\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"HttpError\";\n }\n}\n\nexport function errorBody(code: string, message: string): ErrorBody {\n return { error: { code, message } };\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 return c.json(errorBody(err.code, err.message), 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":";AAOA,SAAS,iBAAiB;AAC1B,OAAO,UAA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,YAAY,EAAE,YAAY;AAAA,MACxE;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AACF;","names":["randomBytes","randomBytes"]}
|
package/dist/hmr/manifest.d.ts
CHANGED
|
@@ -24,6 +24,16 @@ interface Manifest {
|
|
|
24
24
|
web?: {
|
|
25
25
|
manifest: string;
|
|
26
26
|
};
|
|
27
|
+
/**
|
|
28
|
+
* Files the pushed platform needs as REAL files on disk, unpacked under this directory
|
|
29
|
+
* (relative to hmrDir). The web artifact stays in memory because it is only ever served
|
|
30
|
+
* as bytes; an asset is something the platform hands to the OS — a native `.node` the
|
|
31
|
+
* loader must resolve by path, a helper binary it execs — so it has to exist on the
|
|
32
|
+
* filesystem, with its exec bit intact.
|
|
33
|
+
*/
|
|
34
|
+
assets?: {
|
|
35
|
+
dir: string;
|
|
36
|
+
};
|
|
27
37
|
}
|
|
28
38
|
/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */
|
|
29
39
|
declare function readManifest(root: string): Promise<Manifest | null>;
|
package/dist/hmr/manifest.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hmr/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\";\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 */\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\n/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */\nexport async function readManifest(root: string): Promise<Manifest | null> {\n try {\n const raw = await fsp.readFile(path.join(root, \"hmr\", \"harness.json\"), \"utf8\");\n return JSON.parse(raw) as Manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves the current CLI bundle's absolute path from a data root, or null when\n * nothing has been pushed yet: a fresh root, a missing/corrupt manifest, no `cli`\n * entry, a `cli.bundle` that isn't a non-empty string (e.g. `{\"cli\":{}}` — a\n * hand-edited or truncated harness.json), a path that resolves outside `<root>/hmr/`\n * (defense in depth: `manifest.cli.bundle` is trusted content today, written only by\n * this same process's persistVersion, but a reader must never let a malformed or\n * malicious manifest value walk it out of the store directory via `..` segments), or\n * a referenced file that no longer exists (e.g. pruned from the store — see host.ts's\n * pruneStore). A null return means \"use the packaged default\" to every caller;\n * nothing here ever throws for an ordinary unconfigured or malformed root.\n */\nexport async function resolveCliBundlePath(root: string): Promise<string | null> {\n const manifest = await readManifest(root);\n const bundle = manifest?.cli?.bundle;\n if (typeof bundle !== \"string\" || bundle.length === 0) return null;\n const hmrDir = path.join(root, \"hmr\");\n const abs = path.resolve(hmrDir, bundle);\n const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);\n if (!withinHmrDir) return null;\n return fs.existsSync(abs) ? abs : null;\n}\n"],"mappings":";AAkBA,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;
|
|
1
|
+
{"version":3,"sources":["../../src/hmr/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\";\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 */\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\n/** Reads and parses `<root>/hmr/harness.json`; null when missing or corrupt (nothing committed yet). */\nexport async function readManifest(root: string): Promise<Manifest | null> {\n try {\n const raw = await fsp.readFile(path.join(root, \"hmr\", \"harness.json\"), \"utf8\");\n return JSON.parse(raw) as Manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves the current CLI bundle's absolute path from a data root, or null when\n * nothing has been pushed yet: a fresh root, a missing/corrupt manifest, no `cli`\n * entry, a `cli.bundle` that isn't a non-empty string (e.g. `{\"cli\":{}}` — a\n * hand-edited or truncated harness.json), a path that resolves outside `<root>/hmr/`\n * (defense in depth: `manifest.cli.bundle` is trusted content today, written only by\n * this same process's persistVersion, but a reader must never let a malformed or\n * malicious manifest value walk it out of the store directory via `..` segments), or\n * a referenced file that no longer exists (e.g. pruned from the store — see host.ts's\n * pruneStore). A null return means \"use the packaged default\" to every caller;\n * nothing here ever throws for an ordinary unconfigured or malformed root.\n */\nexport async function resolveCliBundlePath(root: string): Promise<string | null> {\n const manifest = await readManifest(root);\n const bundle = manifest?.cli?.bundle;\n if (typeof bundle !== \"string\" || bundle.length === 0) return null;\n const hmrDir = path.join(root, \"hmr\");\n const abs = path.resolve(hmrDir, bundle);\n const withinHmrDir = abs === hmrDir || abs.startsWith(hmrDir + path.sep);\n if (!withinHmrDir) return null;\n return fs.existsSync(abs) ? abs : null;\n}\n"],"mappings":";AAkBA,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AAiCjB,eAAsB,aAAa,MAAwC;AACzE,MAAI;AACF,UAAM,MAAM,MAAM,IAAI,SAAS,KAAK,KAAK,MAAM,OAAO,cAAc,GAAG,MAAM;AAC7E,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcA,eAAsB,qBAAqB,MAAsC;AAC/E,QAAM,WAAW,MAAM,aAAa,IAAI;AACxC,QAAM,SAAS,UAAU,KAAK;AAC9B,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,EAAG,QAAO;AAC9D,QAAM,SAAS,KAAK,KAAK,MAAM,KAAK;AACpC,QAAM,MAAM,KAAK,QAAQ,QAAQ,MAAM;AACvC,QAAM,eAAe,QAAQ,UAAU,IAAI,WAAW,SAAS,KAAK,GAAG;AACvE,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,GAAG,WAAW,GAAG,IAAI,MAAM;AACpC;","names":[]}
|