@prismshadow/penguin-server 0.2.10 → 0.2.13
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 +1 -1
- package/dist/api/types.d.ts +1014 -12
- package/dist/api/types.js +7 -0
- package/dist/auth-token.js +6 -4
- package/dist/auth-token.js.map +1 -1
- package/dist/{chunk-Q65VPAQS.js → chunk-3I2XOPJB.js} +102 -55
- package/dist/chunk-3I2XOPJB.js.map +1 -0
- package/dist/{chunk-ADZJYDNC.js → chunk-A3QANMU5.js} +293 -3
- package/dist/chunk-A3QANMU5.js.map +1 -0
- package/dist/chunk-B5IP37ZQ.js +56 -0
- package/dist/chunk-L2H3K4DT.js +7 -0
- package/dist/chunk-L2H3K4DT.js.map +1 -0
- package/dist/chunk-LPPVGHYD.js +83 -0
- package/dist/chunk-LPPVGHYD.js.map +1 -0
- package/dist/{chunk-TTGGJDNA.js → chunk-S3BI6R7I.js} +2 -2
- package/dist/{chunk-HOS3W3UP.js → chunk-TOOTEEM4.js} +50 -8
- package/dist/chunk-TOOTEEM4.js.map +1 -0
- package/dist/hmr/manifest.d.ts +1 -77
- package/dist/hmr/manifest.js +6 -1
- package/dist/index.js +50757 -20174
- package/dist/index.js.map +1 -1
- package/dist/initial-password.js +1 -0
- package/dist/lock.js +1 -0
- package/dist/machine-status.js +2 -1
- package/dist/machine-status.js.map +1 -1
- package/dist/plugin/index.d.ts +2595 -0
- package/dist/plugin/index.js.map +1 -0
- package/dist/reset-admin-password.js +7 -5
- package/dist/reset-admin-password.js.map +1 -1
- package/dist/secret-file.js +2 -0
- package/dist/secret-file.js.map +1 -1
- package/dist/version-report.js +3 -2
- package/package.json +11 -9
- package/web-dist/assets/{addon-clipboard-1cARCaK9.js → addon-clipboard-DrZY90Ks.js} +1 -1
- package/web-dist/assets/{addon-fit-BWdzl8Er.js → addon-fit-CtEAdAax.js} +1 -1
- package/web-dist/assets/{addon-web-links-DjXuvn4Z.js → addon-web-links-DJL13cYY.js} +1 -1
- package/web-dist/assets/c-BG-tZi7o.js +1 -0
- package/web-dist/assets/cpp-CaeG3uDQ.js +1 -0
- package/web-dist/assets/css-Br67jR8j.js +1 -0
- package/web-dist/assets/diff-jW5kmiru.js +1 -0
- package/web-dist/assets/github-dark-BQV5ugrc.js +1 -0
- package/web-dist/assets/github-light-Rcb2q3L5.js +1 -0
- package/web-dist/assets/go-B7VTfpnm.js +1 -0
- package/web-dist/assets/highlighter-CUb4XKtQ.js +2 -0
- package/web-dist/assets/{highlighter-Cu43iYr8.js → highlighter-core-CrBdruEx.js} +2 -2
- package/web-dist/assets/highlighter.worker-CL6f9Fzw.js +152 -0
- package/web-dist/assets/html-BW_6VhB7.js +1 -0
- package/web-dist/assets/index-CmfumtXy.js +570 -0
- package/web-dist/assets/index-Ywc2uM5u.css +1 -0
- package/web-dist/assets/ini-Dix3pTmg.js +1 -0
- package/web-dist/assets/java-BTDmaRNO.js +1 -0
- package/web-dist/assets/javascript-WyGyM1wV.js +1 -0
- package/web-dist/assets/json-B8JryHcM.js +1 -0
- package/web-dist/assets/jsx-8cLv2Six.js +1 -0
- package/web-dist/assets/log-CcaF_xNv.js +1 -0
- package/web-dist/assets/markdown-DX-TNHnc.js +1 -0
- package/web-dist/assets/php-CNeTOyEV.js +1 -0
- package/web-dist/assets/python-B6Ihcp-E.js +1 -0
- package/web-dist/assets/ruby-CYiNE6ps.js +1 -0
- package/web-dist/assets/rust-CxuBE0J8.js +1 -0
- package/web-dist/assets/shellscript-DgJyDXW6.js +1 -0
- package/web-dist/assets/sql-Dq2MiB0T.js +1 -0
- package/web-dist/assets/toml-Ms459DBw.js +1 -0
- package/web-dist/assets/tsx-D6116Ycy.js +1 -0
- package/web-dist/assets/typescript-BqvgUolh.js +1 -0
- package/web-dist/assets/xml-BkAJuBCc.js +1 -0
- package/web-dist/assets/{xterm-DKcY6q-I.js → xterm-B2oS8Mg8.js} +1 -1
- package/web-dist/assets/yaml-Bopit2L3.js +1 -0
- package/web-dist/index.html +2 -2
- package/dist/chunk-4SXGU7RO.js +0 -50
- package/dist/chunk-4SXGU7RO.js.map +0 -1
- package/dist/chunk-ADZJYDNC.js.map +0 -1
- package/dist/chunk-HOS3W3UP.js.map +0 -1
- package/dist/chunk-Q65VPAQS.js.map +0 -1
- package/dist/extension/index.d.ts +0 -212
- package/web-dist/assets/index-Bm9n7ZV-.js +0 -457
- package/web-dist/assets/index-DR4PrRzS.css +0 -1
- /package/dist/{extension/index.js.map → chunk-B5IP37ZQ.js.map} +0 -0
- /package/dist/{chunk-TTGGJDNA.js.map → chunk-S3BI6R7I.js.map} +0 -0
- /package/dist/{extension → plugin}/index.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/api/types.ts"],"sourcesContent":["/**\n * Web API DTO contract — request/response types shared between server routes and the\n * frontend SPA (single source of truth).\n *\n * These field definitions are authoritative for the Web API contract. Conventions:\n * - DTO fields use camelCase; OmniMessage keeps the core protocol as-is (snake_case shell),\n * no conversion;\n * - This file holds only types, no implementation; exposed to the frontend via package\n * exports `\"./api\"` for type-only import;\n * - Types are taken only from core's pure subpaths (omnimessage / interfaces), so the\n * frontend can safely reference them.\n *\n * Docs: packages/docs/content/server-api.{zh,en}.md (site path /docs/server-api) is the\n * public route/SSE reference for this contract — keep it in sync when changing DTOs.\n */\nimport type {\n CompactionMode,\n OmniMessage,\n ToolCallPayload,\n} from \"@prismshadow/penguin-core/omnimessage\";\nimport type {\n MCPServerConfig,\n ThinkingLevelName,\n ToolDefinitionConfig,\n} from \"@prismshadow/penguin-core/interfaces\";\n// Build/harness identity is not an interface contract — it ships from the barrel (core's version-info.ts).\nimport type { HarnessInfo, VersionReport } from \"@prismshadow/penguin-core\";\n\n// ---------------------------------------------------------------------------\n// General\n// ---------------------------------------------------------------------------\n\n/** Unified error response body; `code` is a machine-readable error code, `message` is a Chinese user-facing message. */\nexport interface ErrorBody {\n error: { code: string; message: string };\n}\n\n/** Session approval mode (reuses the CLI enum). */\nexport type ApprovalMode = \"allow-all\" | \"deny-all\" | \"read-only\" | \"always-ask\";\n\n/** Session run status: idle / Task in progress / compacting. */\nexport type SessionStatus = \"idle\" | \"running\" | \"compacting\";\n\n/** Session source marker (default = user-created): triggered by Schedule / registered as a subagent session / created by a Benchmark evaluation or optimization. */\nexport type SessionSource = \"schedule\" | \"subagent\" | \"benchmark\";\n\n// ---------------------------------------------------------------------------\n// Authentication and users\n// ---------------------------------------------------------------------------\n\nexport interface UserInfo {\n /** Semantic id, i.e. login name: `^[a-z][a-z0-9_-]{1,31}$`, immutable after creation. */\n userId: string;\n /** Built-in admin (seeded at startup). */\n isAdmin: boolean;\n /** Still using the initial password (seeded/set by admin): frontend prompts the user to change it soon. */\n passwordIsInitial: boolean;\n /**\n * Nickname the account chose (1-32 characters), shown wherever the id would otherwise be.\n * Omitted when unset — every account that predates the Profile page starts without one, and\n * a surface with no value falls back to `userId`.\n */\n displayName?: string;\n /**\n * Avatar as a `data:image/...;base64,` URL, at most 131072 characters. Omitted when unset,\n * and a surface with no value draws the letter placeholder instead.\n */\n avatar?: string;\n createdAt: string;\n}\n\n/**\n * PUT /api/me/profile — a patch, not a replacement: an absent field keeps what is stored,\n * `null` clears it, a string sets it. A body naming neither field is a 400, since it can only\n * be a mistake.\n */\nexport interface UpdateProfileRequest {\n displayName?: string | null;\n avatar?: string | null;\n}\n\nexport interface UpdateProfileResponse {\n user: UserInfo;\n}\n\nexport interface AuthLoginRequest {\n userId: string;\n password: string;\n}\n\nexport interface AuthResponse {\n user: UserInfo;\n}\n\n/**\n * GET /api/install — the identity of the data root this server is serving (install-id.ts),\n * read by the web app before it mounts so state persisted against a DIFFERENT root can be\n * swept. Public, like the login route it sits next to.\n */\nexport interface InstallResponse {\n /**\n * Opaque per-data-root id, or null when the server could not establish one (an\n * unreadable or unwritable root). Null means \"unknown\", and a client must change\n * nothing on it — never treat it as a new install.\n */\n installId: string | null;\n}\n\nexport interface MeResponse {\n user: UserInfo;\n /**\n * Whether Workspace HTML previews open on a separate origin (the loopback\n * counterpart of the App host, or PENGUIN_PREVIEW_ORIGIN when set). False means this\n * deployment has no usable preview origin —\n * the App is reached on something other than a loopback name and\n * PENGUIN_PREVIEW_ORIGIN is unset — so previews fall back to the same-origin sandbox,\n * where `localStorage`, cookies and third-party embeds do not work. Computed per\n * request, since it depends on the host the caller is using.\n */\n previewIsolated: boolean;\n /**\n * Whether this server runs in desktop mode (spawned by the desktop shell with\n * PENGUIN_DESKTOP_TOKEN). The web app then hides the logout entry, the\n * initial-password banner and the self-update entry.\n */\n desktopMode: boolean;\n /**\n * How THIS session was established — distinct from desktopMode, which describes the\n * server: a browser signed into a desktop-mode server holds a \"password\" session.\n * \"desktop\" is the shell's own window (one-shot token); \"setup\" was claimed through the\n * first-login link on a server whose admin password has never been set. Both may set a\n * password without the old one (it is random and was never shown); only \"desktop\" opens\n * desktop-only routes. \"token\" marks a request authenticated by the local API token's\n * Bearer header (the CLI and agent-driven calls) — no stored session at all.\n */\n sessionVia: \"password\" | \"desktop\" | \"setup\" | \"token\";\n /**\n * The upload limits currently in force, so the composer can refuse an oversize pick before\n * reading it and can name the real number in the message. They are admin-settable and ride\n * `/api/me` rather than `/api/admin/settings` because every user's composer needs them, not\n * just an admin's.\n */\n uploadLimits: UploadLimits;\n /**\n * Whether company mode is enabled server-wide (the admin switch in server settings, default\n * on). Off hides the mode switch in every client and 404s every organization route; the\n * user's own preference (`UiPrefs.companyMode`) only hides the switch for that user.\n */\n companyMode: boolean;\n}\n\n/**\n * Upload limits as the web app sees them: whole MB, the same unit the admin form uses, so the\n * number in the error message is the number the admin typed.\n */\nexport interface UploadLimits {\n /** Per-file cap for composer file attachments. */\n attachmentMaxMb: number;\n /** Per-message total of decoded attachment bytes. */\n attachmentTotalMb: number;\n /** Per-message file count. Fixed server-side, not admin-settable. */\n attachmentMaxCount: number;\n /**\n * Per-image cap for images that ride the conversation inline. Fixed server-side and\n * deliberately far below the attachment cap — an inline image enters the conversation and the\n * Trace, where its size is paid again on every history page and every resume.\n */\n imageMaxMb: number;\n /**\n * The range the two admin-settable limits may be set to. Carried here so the admin form states\n * the real bounds without compiling its own copy of them — the server is the only place that\n * decides how large an upload it can survive.\n */\n attachmentLimitMinMb: number;\n attachmentLimitMaxMb: number;\n}\n\nexport interface PasswordChangeRequest {\n /** Omitted only by a \"desktop\" or \"setup\" session (see {@link MeResponse.sessionVia}); required otherwise. */\n oldPassword?: string;\n /** At least 8 characters. */\n newPassword: string;\n}\n\n// ---------------------------------------------------------------------------\n// Admin user backend (admin only)\n// ---------------------------------------------------------------------------\n\nexport interface AdminUsersResponse {\n users: UserInfo[];\n}\n\nexport interface AdminUserCreateRequest {\n /** Username, i.e. user_id: `^[a-z][a-z0-9_-]{1,31}$`. */\n userId: string;\n /** Initial password (at least 8 characters), flagged as an initial password. */\n password: string;\n}\n\nexport interface AdminUserCreateResponse {\n user: UserInfo;\n}\n\nexport interface AdminPasswordResetRequest {\n /** New initial password (at least 8 characters); resets invalidate all of the user's sessions. */\n password: string;\n}\n\n/**\n * Admin-level server-global settings (SQLite server_settings):\n * two independent proxy switches sharing one optional explicit address. In every\n * on-state the effective NO_PROXY always includes localhost/127.0.0.1/::1 (loopback is\n * never proxied), and changes apply to newly initiated connections/spawns immediately —\n * no restart.\n */\nexport interface ServerSettings {\n /**\n * \"Application uses the proxy\" (default on): the server's own outbound traffic (LLM\n * requests, the update check, image fetches). On with `proxyUrl` set = that address\n * for both http and https; on without an address = the proxy environment variables\n * HTTP_PROXY / HTTPS_PROXY (both spellings); off = always direct.\n */\n proxyForApp: boolean;\n /**\n * \"Agent environment uses the proxy\" (default on): agent command subprocess\n * environments. On with `proxyUrl` set = HTTP_PROXY / HTTPS_PROXY (plus lowercase\n * twins) injected as that address with the merged NO_PROXY, overriding inherited\n * values; on without an address = the host environment passes through unchanged;\n * off = the proxy variables are stripped (NO_PROXY kept).\n */\n proxyForAgent: boolean;\n /**\n * The shared explicit proxy address (a canonical URL — http(s):// or socks5:// /\n * socks://), or null = follow the proxy environment variables. When set it takes\n * precedence over HTTP_PROXY / HTTPS_PROXY wherever the owning switch is on.\n */\n proxyUrl: string | null;\n /**\n * Per-file cap for composer file attachments, in whole MB (default 100). Applies to the very\n * next upload — the validators read it per request, nothing is snapshotted at boot.\n */\n attachmentMaxMb: number;\n /**\n * Per-message total of decoded attachment bytes, in whole MB (default 120). Never below\n * `attachmentMaxMb`, so a message may always carry one full-size attachment. The global request\n * body cap is derived from this value (base64 inflates it by 4/3, plus headroom for one inline\n * image and the JSON framing), which is why raising it needs no separate setting.\n */\n attachmentTotalMb: number;\n /**\n * Company mode master switch (default on). Off stops the organization scheduler (no\n * calendar event or chat mention fires, nothing is backfilled when it is turned on again),\n * every `/api/projects/:projectId/organizations` route answers 404, and `GET /api/me`\n * reports it so clients hide the mode switch. Organizations on disk are untouched.\n */\n companyMode: boolean;\n}\n\nexport interface ServerSettingsResponse {\n settings: ServerSettings;\n}\n\n/** PUT body: every field optional, omitted fields keep their current value (mirrors prefs). */\nexport interface ServerSettingsUpdateRequest {\n proxyForApp?: boolean;\n proxyForAgent?: boolean;\n /** Company mode master switch; see `ServerSettings.companyMode`. */\n companyMode?: boolean;\n /**\n * New proxy address. Accepted forms: any proxy URL undici's dispatcher takes —\n * `http://`, `https://`, `socks5://` / `socks://`, credentials allowed — or bare\n * `host[:port]` (normalized to `http://…`; only normalized values are stored, and the\n * response echoes the stored form). Empty/whitespace-only or null clears the address\n * (follow the environment variables); anything else is 400 `invalid_proxy_url`.\n */\n proxyUrl?: string | null;\n /**\n * New per-file attachment cap in whole MB. Must be an integer between 1 and 200; anything else\n * — a fraction, a string, 102400 for \"100GB\" — is 400 `invalid_attachment_limit` and writes\n * nothing.\n */\n attachmentMaxMb?: number;\n /**\n * New per-message total attachment cap in whole MB. Same 1..200 integer range, and additionally\n * must not be below the *effective* per-file cap (the value in the same PUT, or the stored one\n * when this PUT does not change it) — a total below the per-file cap would make a legal single\n * attachment unsendable. Violations are 400 `invalid_attachment_limit`.\n */\n attachmentTotalMb?: number;\n}\n\n/**\n * The endpoints the proxy reachability probe covers. A fixed list: the route takes a provider\n * id from this set and never a URL, so nothing a caller sends decides what the server fetches.\n *\n * GLM is two entries rather than one because it is two hosts: Z.AI serves the global endpoint\n * and BigModel the mainland one, they are reached over different routes, and a proxy can carry\n * one and not the other.\n */\nexport type ProxyProbeProvider =\n \"openai\" | \"anthropic\" | \"gemini\" | \"deepseek\" | \"zai\" | \"bigmodel\";\n\n/**\n * One probe's verdict. `reachable` means an HTTP answer arrived, whatever its status — a\n * rejected credential still proves the whole path works. The rest are transport failures,\n * named so a proxy that swallows connections can be told apart from one whose address does\n * not resolve: `timeout` (no answer within the probe's window), `dns` (the name never\n * became an address), `refused` (the connection was refused at the TCP level), `tls` (the\n * handshake or the certificate failed) and `network` (anything else).\n */\nexport type ProxyProbeOutcome = \"reachable\" | \"timeout\" | \"dns\" | \"refused\" | \"tls\" | \"network\";\n\n/**\n * One probe target. Served before any probe runs so the page can list what it is about to\n * request — the URLs are the concrete answer to \"what does no API key mean here\".\n */\nexport interface ProxyProbeTargetDto {\n provider: ProxyProbeProvider;\n /** The exact URL a probe requests, unauthenticated. */\n url: string;\n}\n\n/** What the probe endpoint would request, without requesting it. */\nexport interface ProxyProbeTargetsResponse {\n targets: ProxyProbeTargetDto[];\n}\n\n/** One provider's probe result. */\nexport interface ProxyProbeDto extends ProxyProbeTargetDto {\n outcome: ProxyProbeOutcome;\n /** Wall time in milliseconds until the answer's headers arrived, or until the attempt failed. */\n ms: number;\n /** The HTTP status, present only when `outcome` is `reachable`. */\n status?: number;\n}\n\n/**\n * One probe's answer. The route measures a single target per call: the page asks for all of\n * them at once and fills each row the moment its own answer lands, so one black-holed host\n * cannot hold every other result behind its timeout.\n */\nexport interface ProxyProbeResponse {\n probe: ProxyProbeDto;\n}\n\n/**\n * One draft-screen shortcut: a prompt the user wrote, filed under a name they chose. Clicking it\n * fills the composer exactly like a built-in example does, and sends nothing. Deliberately holds\n * no Skill list — a saved prompt is not authored against a known Skill catalog the way a shipped\n * example is, and the Agent it will run under is picked after the click.\n */\nexport interface DraftShortcut {\n /** Stable client-generated id: what an edit or a delete addresses the row by. Unique per user. */\n id: string;\n title: string;\n prompt: string;\n}\n\n/** User UI preferences (SQLite ui_prefs, free-form JSON; known keys declared here). */\nexport interface UiPrefs {\n theme?: \"light\" | \"dark\";\n lastProjectId?: string;\n /** Whether the \"no API key configured\" guide has already been shown: once ever (on first visit to the chat page). */\n credentialGuideSeen?: boolean;\n /** The initial-password notice banner (app layout) was permanently dismissed by the user. */\n initialPasswordBannerDismissed?: boolean;\n /**\n * \"I have dealt with this\" markers for the dismissible to-do badges, per Project id and then\n * per trail (`skills` / `models` / `errors`). Each value is the SIGNATURE of what was waved\n * away rather than a hidden flag, so anything new raises the dot again (web's\n * `lib/todo-badges.ts`). Replaced whole on every write, like `draftShortcuts`: the merge is\n * shallow, so this whole map is one field.\n */\n todoDismissed?: Record<string, Record<string, string>>;\n /**\n * The draft screen's user-defined shortcuts, in display order. Replaced whole on every write\n * (the merge is shallow, so the array is one field like any other) and bounded on write by\n * services/draft-shortcuts.ts — count, title length and prompt length — because this is the one\n * known key holding user-authored text rather than a flag or an id.\n */\n draftShortcuts?: DraftShortcut[];\n /** Personal company-mode switch (default on): off only hides this user's mode switch; organizations keep running. */\n companyMode?: boolean;\n /** The work mode the user last chose in the shell: development (default) or company. */\n workMode?: \"dev\" | \"company\";\n /** The organization last opened in company mode, as `<projectId>/<orgId>`. */\n lastOrgKey?: string;\n [key: string]: unknown;\n}\n\nexport interface PrefsResponse {\n prefs: UiPrefs;\n}\n\n// ---------------------------------------------------------------------------\n// Project and member authorization\n// ---------------------------------------------------------------------------\n\nexport type ProjectRole = \"owner\" | \"member\";\n\nexport interface ProjectSummary {\n projectId: string;\n /** Display name (the `name` in project_config.toml); frontend falls back to projectId when unset. */\n name?: string;\n /** Current user's role in this Project. */\n role: ProjectRole;\n ownerUserId: string;\n createdAt: string;\n}\n\nexport interface ProjectsResponse {\n projects: ProjectSummary[];\n}\n\nexport interface ProjectCreateRequest {\n /**\n * Semantic id, specified by the creator: `^[a-z][a-z0-9_-]{1,63}$`, immutable after creation.\n * Non-admins must prefix it with `<username>-` (the web input locks the prefix segment);\n * admins are unrestricted.\n */\n projectId: string;\n /** Display name; defaults to projectId. */\n name?: string;\n}\n\nexport interface ProjectCreateResponse {\n project: ProjectSummary;\n}\n\nexport interface ProjectUpdateRequest {\n /** New display name. The projectId itself is immutable — only this label can change. */\n name: string;\n}\n\nexport interface ProjectUpdateResponse {\n project: ProjectSummary;\n}\n\nexport interface MemberInfo {\n userId: string;\n role: ProjectRole;\n createdAt: string;\n}\n\nexport interface MembersResponse {\n members: MemberInfo[];\n}\n\nexport interface MemberAddRequest {\n /** Username of the user being granted access (owner invites by username). */\n userId: string;\n}\n\nexport interface MemberAddResponse {\n member: MemberInfo;\n}\n\n// ---------------------------------------------------------------------------\n// Model and credential config (single .project_config.toml file; credentials are inlined on model entries)\n// ---------------------------------------------------------------------------\n\n/**\n * Model reference DTO: `(provider, modelId)` pair.\n * `modelId` is the upstream request id, sent to AgentHub as-is — `<provider>/<id>` string\n * concatenation is forbidden throughout the pipeline.\n */\nexport interface ModelRefDto {\n provider: string;\n modelId: string;\n}\n\n/** Three pricing buckets, in USD per million tokens (unit is fixed at usd_per_mtok; not carried in the DTO). */\nexport interface ModelPricingDto {\n cacheRead: number;\n cacheWrite: number;\n output: number;\n}\n\n/** Read-only credential display: masked key and creation time; plaintext is never sent. */\nexport interface CredentialInfo {\n apiKeyMasked?: string;\n baseUrl?: string;\n createdAt?: string;\n}\n\nexport interface ModelInfo {\n /** Provider group id (anthropic / openai / …, see core's MODEL_PROVIDERS; custom models use `custom`). */\n provider: string;\n /** Upstream model id (the request id actually sent to AgentHub); paired with `provider` forms the entry's unique key. */\n modelId: string;\n /**\n * Display name: explicit TOML field (user-edited) takes priority, then the built-in catalog;\n * falls back to unset (frontend shows modelId). The empty string is reported as such and\n * means the user cleared the name on a model the catalog does name — render it as modelId,\n * and send it back unchanged, since absent would ask for the catalog's name instead.\n */\n displayName?: string;\n contextWindow?: number;\n /** AgentHub client protocol (`openai-chat`, `openai-responses`, etc.); defaults to AgentHub inferring it from modelId. */\n clientType?: string;\n /**\n * Whether image input (vision/multimodal) is supported: the TOML `vision` annotation takes\n * priority, falling back to the built-in catalog annotation; if neither exists, defaults to\n * unset (= treated as supported).\n */\n vision?: boolean;\n /**\n * Per-model max output tokens (TOML `max_tokens` annotation; user-only, never preset by the\n * built-in catalog): when set it wins over the Agent's `system_config.model.max_tokens`;\n * unset = inherit the Agent value. Lets a small-context model cap its output below the\n * seeded per-Agent default (32000), which cannot fit into e.g. a 32k context window.\n */\n maxTokens?: number;\n /**\n * Per-model fast mode (TOML `fast_mode` annotation; user-only, never preset by the\n * built-in catalog): when true, session requests opt into the provider's faster serving\n * tier at premium pricing (AgentHub UniConfig `fast_mode`). Only `true` is reported;\n * unset = off. Models without a fast tier reject requests carrying it.\n */\n fastMode?: boolean;\n pricing?: ModelPricingDto;\n /** Environment variable name to fall back to when api_key is empty (e.g. ANTHROPIC_API_KEY); unset if no known fallback. */\n envKey?: string;\n /**\n * Masked preview (same rule as `credential.apiKeyMasked`) of the value the server process\n * currently holds for `envKey` — the plaintext is never serialized. Reported only for\n * first-party official entries (vendor group, catalog shape unmodified); gateway, custom\n * and user-defined groups never carry it. Absent = the variable is unset or empty, or the\n * entry is not first-party.\n */\n envKeyMasked?: string;\n credential?: CredentialInfo;\n isDefault: boolean;\n}\n\nexport interface ModelsResponse {\n /** Paired reference to the default Model. */\n defaultModel?: ModelRefDto;\n /** Vision model used as a proxy reader for read_file (describes images when the session model has vision=false). */\n visionModel?: ModelRefDto;\n /**\n * When the Project's model/credential config last changed (ISO; the config file's mtime,\n * so it survives restarts). The web's auth-dead gate compares it against the last auth\n * abort: an abort OLDER than the last credential update no longer disables the composer\n * (the key was fixed since). Absent when the Project has no config file yet.\n */\n updatedAt?: string;\n models: ModelInfo[];\n}\n\n/** PUT full-table replace semantics: models not present are deleted; omitting apiKey = keep existing value. Key = (provider, modelId). */\nexport interface ModelUpdateEntry {\n /** Provider group (an independent entry field, always submitted with the request). */\n provider: string;\n /** Upstream model id (sent to AgentHub as-is). */\n modelId: string;\n /**\n * Display name; the server does not persist it when it matches the built-in catalog (keeps\n * the config file clean). Absent and empty are different requests: absent inherits whatever\n * the catalog calls the model, the empty string records that the user cleared the name.\n */\n displayName?: string;\n /**\n * The pair reference this entry was renamed from (provided when either the group or the\n * upstream id changes): the server uses this to migrate the original entry's credential\n * and unknown fields to the new key — otherwise a full-table replace would delete the\n * original entry along with its credential.\n */\n renamedFrom?: ModelRefDto;\n contextWindow?: number;\n /** Empty string/omitted = unspecified (AgentHub infers it from modelId). */\n clientType?: string;\n /** Whether image input (vision/multimodal) is supported; omitted = supported (not persisted). */\n vision?: boolean;\n /** Per-model max output tokens, a positive integer (wins over the Agent config); omitted = inherit the Agent value (the annotation is cleared). */\n maxTokens?: number;\n /** Per-model fast mode: only `true` is persisted; omitted or `false` clears the annotation (absent = off). */\n fastMode?: boolean;\n pricing?: ModelPricingDto;\n /** Providing it overwrites and updates createdAt; omitting it keeps the existing value. */\n apiKey?: string;\n /** When true, clears the stored api_key. */\n clearApiKey?: boolean;\n /** null clears it; omitted keeps the existing value. */\n baseUrl?: string | null;\n}\n\nexport interface ModelsUpdateRequest {\n /** Must be included in models (matched by paired reference). */\n defaultModel?: ModelRefDto;\n /** Vision model used as a proxy reader for read_file: must be included in models and not annotated vision=false; omitted keeps the existing value. */\n visionModel?: ModelRefDto;\n models: ModelUpdateEntry[];\n}\n\n/**\n * Connectivity test (POST /api/projects/:p/models/test): the model reference is submitted as\n * a pair in the request body; the rest are optional overrides (for trying out an unsaved\n * config). When the model isn't in the config yet (adding a custom model — test-before-save),\n * all parameters come from this request body.\n */\nexport interface ModelTestRequest {\n /** Provider group of the model under test (paired with modelId). */\n provider: string;\n /** Upstream id of the model under test (sent to AgentHub as-is). */\n modelId: string;\n /** Newly entered API key (plaintext); used for the test if provided. */\n apiKey?: string;\n /** \"Clear saved API key\" is checked: the test does **not** fall back to the stored key (tests against the current draft). */\n clearApiKey?: boolean;\n /** Speed-test mode: raises the probe's output cap (16 -> 64 tokens) so TTFT/TPS are measurable; costs a little more quota. */\n speed?: boolean;\n /**\n * base URL (not secret; the frontend always sends the form's current value): a string\n * means use it, `null` means explicitly clear it (no fallback to the stored value),\n * `undefined` means fall back to the stored value only when not provided.\n */\n baseUrl?: string | null;\n /** AgentHub client protocol; required for unsaved custom models (otherwise the id can't be auto-routed). */\n clientType?: string;\n /**\n * Test with fast mode (the frontend always sends the form's current value, so an unsaved\n * toggle — either direction — is what gets tested); omitted falls back to the stored\n * annotation. Lets \"Test connection\" surface a fast-mode rejection before saving.\n */\n fastMode?: boolean;\n}\n\n/**\n * Vision capability probe: sends one 1x1 image and a one-word prompt on this model's\n * credential, to decide whether the models dialog's \"supports vision\" switch should be\n * turned on. The body mirrors the connectivity test (same paired reference and same\n * not-yet-saved overrides), so an unsaved model can be probed before it exists on disk.\n *\n * Unlike protocol detection this is a real, billed completion — an image request cannot be\n * shaped to cost nothing — so it only ever runs when the user presses the control.\n */\nexport interface ModelVisionDetectRequest {\n provider: string;\n modelId: string;\n /** Newly entered API key (plaintext); the stored one backs the probe when omitted. */\n apiKey?: string;\n /** \"Clear saved API key\" is checked: do not fall back to the stored key. */\n clearApiKey?: boolean;\n /** Form's current base URL; null means \"explicitly none\" (as in the connectivity test). */\n baseUrl?: string | null;\n /** Protocol to speak, when the form has one; otherwise the stored/auto-routed client. */\n clientType?: string;\n}\n\n/**\n * Vision probe verdict. `supported` = the model took the image and answered; `unsupported`\n * = it answered specifically that it will not take an image (a definitive negative, not an\n * error); `failed` = the probe never got a usable answer (auth, network, an unrelated\n * error), so nothing about the capability was learned and the setting is left alone.\n */\nexport type ModelVisionOutcome = \"supported\" | \"unsupported\" | \"failed\";\n\n/** Vision probe result; `message` carries the truncated provider error for the failed case. */\nexport interface ModelVisionDetectResponse {\n outcome: ModelVisionOutcome;\n message?: string;\n}\n\n/**\n * Connectivity test result: carries round-trip latency when ok, and a reason on failure\n * (truncated raw provider error). When streamed content was observed, also carries the\n * time-to-first-token and, when usage was reported (completed streams), the output rate.\n */\nexport interface ModelTestResponse {\n ok: boolean;\n latencyMs?: number;\n /** Time from request start to the first streamed content (thinking or text), ms. */\n ttftMs?: number;\n /**\n * Output tokens per second over the streaming window (first content -> stream end), 1dp.\n * Omitted unless the sample is large enough to mean anything: a reply of a few tokens is\n * dominated by the final chunk's round trip, so the rate it yields tracks network jitter\n * rather than the model. Callers render TTFT alone in that case.\n */\n tps?: number;\n message?: string;\n}\n\n/**\n * Protocol auto-detection (POST /api/projects/:p/models/detect, owner): probes which of\n * AgentHub's generic protocol clients a custom base URL serves — `openai-responses` first,\n * then `ant-messages`, then `openai-chat` — and reports the first hit. Used by the custom\n * model dialog to fill `clientType` from the endpoint itself; costs no tokens (each probe\n * is a minimal invalid request whose error reveals the protocol shape).\n */\nexport interface ModelProtocolDetectRequest {\n /** Base URL to probe (as typed in the form); each probe appends its protocol path. */\n baseUrl: string;\n /** Newly entered API key (plaintext); used for probe auth if provided. Detection also works keyless: a protocol-shaped 401/403 still proves the route. */\n apiKey?: string;\n /** \"Clear saved API key\" is checked: do not fall back to the stored key (probe the current draft). */\n clearApiKey?: boolean;\n /** Optional paired reference: when it names a stored entry and no apiKey is given, that entry's saved key backs the probes (mirrors the connectivity test). */\n provider?: string;\n modelId?: string;\n}\n\n/**\n * One probe's outcome: `served` = the route answered in an API shape (including auth\n * failures — 401/403 with a protocol-shaped body proves the route exists);\n * `route_missing` = 404/405; `server_error` = 5xx (proves nothing about the path);\n * `junk` = HTML / non-JSON / JSON matching no API shape; `timeout` / `network_error` =\n * the request itself failed.\n */\nexport type ProtocolProbeOutcome =\n \"served\" | \"route_missing\" | \"server_error\" | \"junk\" | \"timeout\" | \"network_error\";\n\n/** One probe, for debugging display: the probed URL derives from baseUrl only (never contains the key). */\nexport interface ModelProtocolProbeDto {\n /** AgentHub client type this probe stands for (`openai-responses` / `ant-messages` / `openai-chat`). */\n clientType: string;\n /** Full URL probed (base URL + the protocol's path). */\n url: string;\n outcome: ProtocolProbeOutcome;\n /** HTTP status, when a response arrived at all. */\n status?: number;\n}\n\n/**\n * Detection result: probes run sequentially over the candidate base URLs derived from the\n * one that was typed and stop at the first served protocol, so `probes` lists only the\n * ones actually run, in order.\n */\nexport interface ModelProtocolDetectResponse {\n /** The first protocol an endpoint serves (an AgentHub client type); absent when none of the three matched. */\n detected?: string;\n /**\n * The base URL the detected protocol answered at — the typed URL normalized (endpoint\n * path stripped, repeated `/v1` collapsed) and possibly with a trailing `/v1` added or\n * removed, so `https://host/v1/chat/completions` comes back as `https://host/v1`.\n * Present only alongside `detected`; callers write it back into their base URL field,\n * since that is where the protocol is served.\n */\n baseUrl?: string;\n probes: ModelProtocolProbeDto[];\n}\n\n/**\n * Endpoint model listing (POST /api/projects/:p/models/list, owner): given a base URL and\n * the protocol `/detect` reported, returns every model id the endpoint serves (AgentHub's\n * `listModels()` on the routed client). Used by the add-group dialog to import a provider's\n * whole listing in one go; the ids come back in the endpoint's own order.\n */\nexport interface EndpointModelListRequest {\n /** Endpoint base URL (as typed in the add-group dialog). */\n baseUrl: string;\n /** AgentHub client type to speak (normally a detected generic protocol; whole-endpoint listings need one). */\n clientType: string;\n /** Newly entered API key (plaintext); omitted = the SDK's environment fallback for the protocol. */\n apiKey?: string;\n}\n\n/** Listing outcome: model ids on success, a truncated provider/SDK reason otherwise. */\nexport interface EndpointModelListResponse {\n ok: boolean;\n /** The model ids the endpoint serves, in the order the endpoint returned them (ok only). */\n models?: string[];\n /** The routed client has no models endpoint (AgentHub UnsupportedOperationError) — callers offer the manual path. */\n unsupported?: boolean;\n message?: string;\n}\n\n/**\n * PUT /api/projects/:p/models/default (owner): narrow default-model switch — flips the same\n * top-level `default_model` the models page's whole-table PUT writes, without resending the\n * table (and thus without touching credentials). The pair must name a configured model\n * entry, exactly like the whole-table route's defaultModel validation.\n */\nexport interface DefaultModelUpdateRequest {\n provider: string;\n modelId: string;\n}\n\n/** Response mirrors what GET models reports as `defaultModel`. */\nexport interface DefaultModelResponse {\n defaultModel: ModelRefDto;\n}\n\n// ---------------------------------------------------------------------------\n// Provider key-minting flows (/api/projects/:p/model-oauth, owner)\n// ---------------------------------------------------------------------------\n\n/**\n * How the authorization code travels back. `callback` sends the browser to a harness URL\n * the provider redirects to; `manual` asks the provider for a one-time code the user copies\n * back by hand, for the case where that redirect cannot reach the harness.\n */\nexport type ModelOAuthMode = \"callback\" | \"manual\";\n\n/**\n * POST /api/projects/:p/model-oauth/start (owner): opens a flow for one provider group.\n * The group must declare an authorization flow in the built-in catalog — the endpoints it\n * uses come from there, never from this request.\n */\nexport interface ModelOAuthStartRequest {\n /** Provider group id (must be a catalog group that publishes a key-minting flow). */\n provider: string;\n /** Defaults to `callback`. */\n mode?: ModelOAuthMode;\n}\n\n/** The opaque flow handle plus the page to send the user to. No secret of the flow's is included. */\nexport interface ModelOAuthStartResponse {\n flowId: string;\n authorizeUrl: string;\n}\n\n/** Why a flow failed, as a code the frontend phrases; never carries a code, a verifier or a key. */\nexport type ModelOAuthErrorCode =\n \"invalid_request\" | \"code_rejected\" | \"upstream_failed\" | \"unreachable\" | \"apply_failed\";\n\n/**\n * GET /api/projects/:p/model-oauth/:flowId (owner): where a flow stands. Unknown, expired,\n * and other users' flows are all 404 alike.\n */\nexport interface ModelOAuthStatusResponse {\n status: \"pending\" | \"done\" | \"error\";\n /** The provider group the flow mints a key for. */\n provider: string;\n /**\n * How many models the minted key was written to — set on the `done` answer, the way\n * {@link ModelOAuthCodeResponse} sets it on a redemption. The dialog reports this number, so\n * it has to be the server's own: the caller's model table can outlive a rejected save and\n * would otherwise name a count the server never wrote.\n */\n applied?: number;\n error?: ModelOAuthErrorCode;\n}\n\n/**\n * POST /api/projects/:p/model-oauth/:flowId/code (owner): redeems a code the user pasted,\n * the manual counterpart of the redirect callback. A flow is single-use either way.\n */\nexport interface ModelOAuthCodeRequest {\n code: string;\n}\n\n/** Redemption outcome; `applied` counts the models the minted key was written to. */\nexport interface ModelOAuthCodeResponse {\n ok: boolean;\n applied?: number;\n error?: ModelOAuthErrorCode;\n}\n\n// ---------------------------------------------------------------------------\n// New-chat defaults (the `[default_chat]` block of .project_config.toml)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-Project new-chat defaults: prefill for the chat draft page. Every key is optional —\n * an absent key means \"not set\" (the pre-existing behavior). Serves as the GET response,\n * the PUT request body (whole-block replace: an omitted key clears it) and the PUT\n * response (the stored block). The default MODEL is deliberately not here: it stays the\n * top-level `default_model` served/written via the models routes (single-sourced with the\n * models page).\n */\nexport interface ChatDefaultsDto {\n /** Preselected Agent; must reference an existing Agent of the Project (400 unknown_agent). */\n agentId?: string;\n /** Prefilled Workspace directory; absent/empty = a temporary workspace. */\n workspace?: string;\n /** Prefilled approval mode; absent = the built-in \"allow-all\". */\n approvalMode?: ApprovalMode;\n /**\n * Fallback thinking level for Agents whose config has no explicit `model.thinking_level`\n * (resolution chain: Agent explicit > this project default > built-in \"medium\"). Never\n * \"none\" — only the selectable tiers.\n */\n thinkingLevel?: Exclude<ThinkingLevelName, \"none\">;\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox command policy (Project-level: the [command_policy] block)\n// ---------------------------------------------------------------------------\n\n/**\n * One deny rule of the sandbox command policy — plain project-editable data. The factory\n * rules are seeded into new projects and carry no special status thereafter: every rule\n * can be edited, disabled, or deleted.\n */\nexport interface CommandPolicyRuleDto {\n name: string;\n /** JavaScript regex source, matched against the whitespace-normalized command. */\n pattern: string;\n /** What the rule catches (free text). */\n description?: string;\n /** Per-rule switch, effective value (defaults on). */\n enabled: boolean;\n}\n\n/**\n * Per-Project sandbox command policy: deny rules for shell commands, evaluated ahead of\n * the approval mode (a hit is denied even under allow-all). Serves as the GET response and\n * the PUT response. The PUT request body carries `enabled?` plus the full `rules` list\n * (required — a PUT always materializes the list into the config, model-presets style);\n * per-rule `enabled` may be omitted there and defaults to on. Owner-only to write; any\n * member may read.\n */\nexport interface CommandPolicyDto {\n /** Effective master switch; an absent stored value reads as true (the policy defaults on). */\n enabled: boolean;\n /** The effective rule list — the factory set when the project predates seeding and has none stored. */\n rules: CommandPolicyRuleDto[];\n /** The factory set, served for the settings UI's \"restore defaults\". */\n defaultRules: CommandPolicyRuleDto[];\n}\n\n// ---------------------------------------------------------------------------\n// Vault environment variables (Agent-level: agent_state/.vault.toml)\n// ---------------------------------------------------------------------------\n\n/** Read-only vault entry display: key name + masked value; plaintext is never sent. */\nexport interface VaultEntryInfo {\n key: string;\n valueMasked: string;\n}\n\nexport interface VaultResponse {\n entries: VaultEntryInfo[];\n}\n\n/** A single entry under PUT full-table replace semantics: omitting value = keep the existing value (required for new keys). */\nexport interface VaultEntryUpdate {\n /** Shell environment variable name rule: starts with a letter or underscore, followed by letters/digits/underscores only. */\n key: string;\n /** Non-empty string; omitted keeps the existing value. */\n value?: string;\n}\n\n/** PUT full-table replace semantics (same as models): keys not present in the body are deleted. */\nexport interface VaultUpdateRequest {\n entries: VaultEntryUpdate[];\n}\n\n// ---------------------------------------------------------------------------\n// Agent and its config (system_config.yaml + AGENTS.md)\n// ---------------------------------------------------------------------------\n\n/** One installed plugin (a skill or a hook package) the library carries a higher version of (see {@link AgentSummary.pluginUpdates}). */\nexport interface PluginUpdateRef {\n /** Plugin name — what `POST …/plugins` reinstalls to bring the Agent up to date. */\n name: string;\n /** The LIBRARY's version (`YYYY.MM.DD.N`), i.e. what installing again would bring, not what is on disk. */\n version: string;\n}\n\nexport interface AgentSummary {\n agentId: string;\n name?: string;\n description?: string;\n createdAt?: string;\n /** Last config modification time: the larger mtime of system_config.yaml / AGENTS.md (unset if stat fails). */\n updatedAt?: string;\n /** Number of this Agent's Sessions currently running / compacting. */\n activeSessionCount: number;\n /** Total Session count (DB index ∪ Trace directory discovery, including archived). */\n sessionCount: number;\n /** Daily active Session count for the last 30 days (index 0 = earliest, last = today; active = created that day or has a Trace record that day). */\n sessionActivity: number[];\n /** Tool count: number of tools.builtin + tools.mcpServers config entries (MCP counted per server). */\n toolCount: number;\n /** Agent State version number (the `version` in system_config.yaml; treated as 1 if missing). */\n version: number;\n /** Whether the config's kernel stamp is behind the current defaults generation (a missing stamp counts as outdated) — drives the list card's update hint. */\n kernelOutdated: boolean;\n /** Vault key count (number of keys in agent_state/.vault.toml). */\n vaultKeyCount: number;\n /** Schedule count (number of .toml files under agent_state/schedule/, including invalid ones). */\n scheduleCount: number;\n /** Installed Skill count (number of agent_state/skills/<name>/ directories with a SKILL.md). */\n skillCount: number;\n /** Installed hook-package count (number of agent_state/hooks/<name>/ directories with a hooks.json). */\n hookCount: number;\n /**\n * Installed plugins the built-in library has moved past — a skill or a hook package whose\n * on-disk version is behind the library plugin that ships it — each with the library version\n * on offer: the plugin-library update gate, riding along on the Agent list so a badge over\n * that page costs no request of its own. Empty when nothing is behind. Skills the library\n * does not carry (installed from a zip or a picked directory) are never listed: there is no\n * library version for them to be behind.\n */\n pluginUpdates: PluginUpdateRef[];\n /** Memory count (topic files summed over the scope directories under agent_state/memory/, independent of the memory switch). */\n memoryCount: number;\n}\n\nexport interface AgentsResponse {\n agents: AgentSummary[];\n}\n\nexport interface AgentCreateRequest {\n /** Semantic id, specified by the creator: `^[a-z][a-z0-9_-]{1,63}$`, unique within the Project, immutable after creation. */\n agentId: string;\n /** Display name; defaults to agentId. */\n name?: string;\n description?: string;\n /**\n * Library plugin names installed into the new Agent, seeding it at creation — each plugin's\n * skills and hook package. Every name must exist in the library (404 `unknown_plugin`\n * otherwise, before anything is created); omitted or empty leaves the Agent with nothing\n * installed, which is what a plain Agent gets by default.\n */\n plugins?: string[];\n /**\n * Skills imported from a directory on disk instead of the library. `skillsDirectory` is the\n * absolute path the user picked and `directorySkills` are the names to install from it, read\n * back from `.agents/skills` / `.claude/skills` at creation time. Both are required together,\n * and every name must still be there (404 `unknown_skill` otherwise, before anything is\n * created) — the client sends names, never Skill content.\n */\n skillsDirectory?: string;\n directorySkills?: string[];\n /**\n * Base64 of an exported Agent State snapshot package (`.tar.gz`): the new Agent is\n * initialized from the package instead of the default template. Mutually exclusive with\n * seeding (`plugins` / `skillsDirectory`) — the package carries its own skills and hooks.\n * Explicit `name` / `description` override the package's values; absent ones keep them.\n */\n dataBase64?: string;\n}\n\nexport interface AgentCreateResponse {\n agent: AgentSummary;\n}\n\nexport interface AgentModelConfigDto {\n maxTokens?: number;\n thinkingLevel?: ThinkingLevelName;\n timeoutMs?: number;\n}\n\nexport interface AgentCompactionConfigDto {\n maxContextLength?: number;\n maxSessionTurns?: number;\n mode?: \"summarize\" | \"discard\";\n prompt?: string;\n}\n\n/** Memory config. All fields report effective values (a config with no `memory` section reads as enabled with the built-in prompts, matching core); the prompts are edited on the Memory tab. */\nexport interface AgentMemoryConfigDto {\n enabled: boolean;\n /** The always-injected half of the `{{MEMORY}}` block (carries `{{USER_MEMORY_INDEX}}`; the User directory is literal text). */\n prompt: string;\n /** Appended only in a persistent Workspace (carries `{{WORKSPACE_MEMORY_INDEX}}` and the rendered `{{WORKSPACE_MEMORY_DIR}}` directory). */\n workspacePrompt: string;\n}\n\n/**\n * Vault prompt-injection config, edited on the Vault tab. `enabled` / `prompt` report\n * effective values (a config with no `vault` section reads as enabled with the built-in\n * prompt, matching core); the last two are read-only facts computed from the stored template.\n */\nexport interface AgentVaultConfigDto {\n /** Whether the Vault section enters the model context (values are injected into subprocesses regardless). */\n enabled: boolean;\n /** The `{{VAULT}}` block (carries `{{VAULT_KEYS}}`). */\n prompt: string;\n /** Whether the stored template carries `{{VAULT}}`; POST …/vault/template-placeholder inserts (or migrates to) it explicitly. */\n templateHasPlaceholder: boolean;\n /** Whether the stored template still carries the legacy hardcoded # Vault section verbatim (a pre-`{{VAULT}}` Agent) — the migration case of the insert endpoint. */\n legacySectionPresent: boolean;\n}\n\n/** Skills prompt-injection config, edited on the Skills tab; same field semantics as AgentVaultConfigDto, for `{{SKILLS}}` / `{{SKILL_METADATA}}` and the legacy # Skills section. */\nexport interface AgentSkillsConfigDto {\n /** Whether the Skills section enters the model context (installed skills remain explicitly invocable regardless). */\n enabled: boolean;\n /** The `{{SKILLS}}` block (carries `{{SKILL_METADATA}}`). */\n prompt: string;\n /** Whether the stored template carries `{{SKILLS}}`; POST …/skills/template-placeholder inserts (or migrates to) it explicitly. */\n templateHasPlaceholder: boolean;\n /** Whether the stored template still carries the legacy hardcoded # Skills section verbatim — the migration case of the insert endpoint. */\n legacySectionPresent: boolean;\n}\n\n/** Schedules prompt-injection config, edited on the Schedules tab. No legacy field: Schedules never had a hardcoded template section. */\nexport interface AgentSchedulesConfigDto {\n /** Whether the Scheduled Tasks section enters the model context (the server fires configured tasks regardless). */\n enabled: boolean;\n /** The `{{SCHEDULES}}` block (carries `{{SCHEDULE_LIST}}`). */\n prompt: string;\n /** Whether the stored template carries `{{SCHEDULES}}`; POST …/schedules/template-placeholder inserts it explicitly. */\n templateHasPlaceholder: boolean;\n}\n\n/**\n * Hook config, edited on the Hooks tab. One Agent-level switch and no prompt: hook packages\n * are scripts run at the loop's hook points, not text injected into the context. `enabled`\n * reports the effective value (a config with no `hooks` section reads as enabled, matching\n * core).\n */\nexport interface AgentHooksConfigDto {\n /** Whether a Session created from now on runs the installed hook packages (they stay installed either way). */\n enabled: boolean;\n}\n\n/** Structured view of system_config.yaml (for the edit form). */\nexport interface AgentConfigDto {\n name?: string;\n description?: string;\n /** Agent State version number (treated as 1 if missing; shown in the settings page overview). */\n version: number;\n /** The stored kernel stamp (`kernel_version`): which defaults generation the config is based on; null when the config predates the kernel-version mechanism. */\n kernelVersion: string | null;\n /** The current defaults generation (core's KERNEL_VERSION) — what a kernel update would stamp. */\n kernelLatest: string;\n /** Whether the stamp is behind kernelLatest (a missing stamp counts as outdated). */\n kernelOutdated: boolean;\n systemPrompt: string;\n maxTurns?: number;\n model?: AgentModelConfigDto;\n compaction?: AgentCompactionConfigDto;\n memory: AgentMemoryConfigDto;\n vault: AgentVaultConfigDto;\n skills: AgentSkillsConfigDto;\n schedules: AgentSchedulesConfigDto;\n hooks: AgentHooksConfigDto;\n toolsBuiltin: ToolDefinitionConfig[];\n mcpServers: MCPServerConfig[];\n}\n\nexport interface AgentConfigResponse {\n agentsMd: string;\n /** Raw system_config.yaml text (read-only display / diagnostics). */\n systemConfigYaml: string;\n config: AgentConfigDto;\n /** Agent State absolute path. */\n stateDir: string;\n activeSessionCount: number;\n}\n\n/**\n * POST …/config/kernel-update result: the smart merge's outcome (core's applyKernelUpdate).\n * The entries are Agent settings **tabs** (`prompt`, `runtime`, `tools`, `skills`, `memory`,\n * `vault`, `schedules`) in the settings page's tab order; the client maps them to tab labels.\n */\nexport interface AgentKernelUpdateResponse {\n /** Tabs advanced to the current defaults (previously absent, or an untouched old default). */\n advanced: string[];\n /** Tabs kept whole because they match no recorded default (customized, kept conservatively). */\n kept: string[];\n /** The kernel stamp written (the current defaults generation). */\n kernelVersion: string;\n}\n\n/** POST …/config/mcp-test result: reachability of one MCP Server entry. */\nexport interface McpServerTestResponse {\n ok: boolean;\n /** Discovered tool names (`mcp__<server>__<tool>`), present on success. */\n tools?: string[];\n /** Failure detail (connect error, timeout, server stderr tail), present on failure. */\n error?: string;\n /** Connect + discovery wall time (both outcomes) — the models test reports latency, this matches. */\n latencyMs?: number;\n}\n\n/** PUT any subset: only provided keys are updated (remaining YAML content and comments preserved); agentsMd overwrites the whole file. */\nexport interface AgentConfigUpdateRequest {\n agentsMd?: string;\n config?: {\n name?: string;\n description?: string;\n systemPrompt?: string;\n maxTurns?: number;\n model?: AgentModelConfigDto;\n compaction?: AgentCompactionConfigDto;\n memory?: Partial<AgentMemoryConfigDto>;\n /** Only the writable half of the DTO — the template facts (templateHasPlaceholder / legacySectionPresent) are computed, never written. */\n vault?: { enabled?: boolean; prompt?: string };\n skills?: { enabled?: boolean; prompt?: string };\n schedules?: { enabled?: boolean; prompt?: string };\n /** The Agent-level hook switch; it has no prompt half. */\n hooks?: { enabled?: boolean };\n toolsBuiltin?: ToolDefinitionConfig[];\n mcpServers?: MCPServerConfig[];\n };\n}\n\n// ---------------------------------------------------------------------------\n// Memory\n// ---------------------------------------------------------------------------\n\n/** One Memory scope directory: `agent_state/memory/user/` or `agent_state/memory/<workspaceKey>/`. */\nexport interface MemoryScopeInfo {\n /** Directory name under `memory/`: `user`, or a Workspace's `<safe-basename>-<hash>` key. */\n scopeKey: string;\n /** `user` — the scope every Session reads, temporary Workspaces included; `workspace` — one Workspace's scope. */\n kind: \"user\" | \"workspace\";\n /** Workspace path the key was derived from, read from the directory's `.workspace` marker; unset on the user scope (it stands for no path) and for a directory edited by hand. */\n workspacePath?: string;\n /** Number of Markdown topic files in the directory (the `MEMORY.md` index not counted). */\n fileCount: number;\n /** Whether the directory holds a `MEMORY.md` index, so an import confirmation can say whether one would be replaced. */\n hasIndex: boolean;\n /** Most recent topic-file mtime in the directory (ISO 8601); unset when the directory holds no topic file. */\n updatedAt?: string;\n}\n\n/** One Memory topic file, as listed (frontmatter only — the body is fetched per file). */\nexport interface MemoryFileInfo {\n /** File name inside the scope directory, e.g. `prefers-pnpm.md`. */\n name: string;\n /** Frontmatter `name`; falls back to the file name. */\n title: string;\n /** Frontmatter `description`; empty when the file declares none. */\n description: string;\n /** Frontmatter `updated_at`, verbatim. */\n updatedAt?: string;\n /** File size in bytes. */\n size: number;\n /** File mtime (ISO 8601). */\n modifiedAt: string;\n}\n\n/** GET …/memory — the tab's landing payload: the switch and every scope group, user scope first. */\nexport interface MemoryOverviewResponse {\n /** Whether Memory reaches the model context (the Agent-level switch). */\n enabled: boolean;\n /** Whether the prompt template carries the `{{MEMORY}}` placeholder. An Agent created before Memory has none and injects nothing; POST …/memory/template-placeholder inserts it explicitly. */\n templateHasMemory: boolean;\n /** Absolute path of `agent_state/memory/`. */\n memoryDir: string;\n scopes: MemoryScopeInfo[];\n}\n\n/** GET …/memory/scopes/:key/files */\nexport interface MemoryFilesResponse {\n scopeKey: string;\n files: MemoryFileInfo[];\n}\n\n/** GET …/memory/scopes/:key/files/:name */\nexport interface MemoryFileResponse {\n scopeKey: string;\n file: MemoryFileInfo;\n content: string;\n}\n\n/** One topic file inside a transfer document: the name it had in its scope, and its whole text. */\nexport interface MemoryTransferFile {\n /** File name inside the scope directory, e.g. `prefers-pnpm.md` — a name, never a path. */\n name: string;\n /** The file's full Markdown text, frontmatter included. */\n content: string;\n}\n\n/**\n * GET …/memory/scopes/:key/export, and the body a POST …/import carries back: everything one\n * scope holds, as one JSON document — the topic files and the scope's own `MEMORY.md`.\n */\nexport interface MemoryScopeExport {\n /** Format marker, so a foreign JSON file is refused with a clear reason rather than half-imported. */\n format: \"penguin-memory-scope\";\n /** Document version. A reader accepts exactly this; a later format bumps it and states its own compatibility. */\n version: 1;\n /** The scope this was exported from. Informational: an import writes into the scope its URL names. */\n scopeKey: string;\n kind: MemoryScopeInfo[\"kind\"];\n /** The Workspace the source scope stood for, when it had a `.workspace` marker. */\n workspacePath?: string;\n /** When the document was produced (ISO 8601). */\n exportedAt: string;\n /** The scope's `MEMORY.md`, or null when the scope has none. Only the index reaches the model's context. */\n index: string | null;\n files: MemoryTransferFile[];\n}\n\n/**\n * What an import does with a name the target scope already holds:\n * - `skip` — keep what is on disk, write only names the scope does not have (destroys nothing);\n * - `overwrite` — replace a same-named file's content;\n * - `replace` — additionally delete every topic file the document does not carry.\n * The two destructive modes require `confirm`.\n */\nexport type MemoryImportMode = \"skip\" | \"overwrite\" | \"replace\";\n\n/** POST …/memory/scopes/:key/import */\nexport interface MemoryImportRequest {\n /** Defaults to `skip`. */\n mode?: MemoryImportMode;\n /** Required by `overwrite` and `replace`; without it they are refused with 409 `memory_import_confirm_required`. */\n confirm?: boolean;\n payload: MemoryScopeExport;\n}\n\n/** What one import did, name by name, so the UI can report it rather than claim success. */\nexport interface MemoryImportResponse {\n scopeKey: string;\n mode: MemoryImportMode;\n /** Names written that the scope did not have. */\n added: string[];\n /** Names whose existing content was replaced. */\n overwritten: string[];\n /** Names left untouched because the scope already had them (`skip` only). */\n skipped: string[];\n /** Names deleted because `replace` dropped everything the document did not carry. */\n removed: string[];\n /** Whether the scope's `MEMORY.md` was written or extended. */\n indexWritten: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Session\n// ---------------------------------------------------------------------------\n\nexport interface SessionInfo {\n sessionId: string;\n projectId: string;\n agentId: string;\n /** Provider group of the session's model (paired with `modelId` to form a model reference). */\n provider: string;\n /** Upstream model_id of the session's model (the request id sent to AgentHub). */\n modelId: string;\n workspace: string;\n approvalMode: ApprovalMode;\n /**\n * Thinking level pinned for this Session (set via PATCH; the Web App's in-chat picker).\n * Unset = never pinned: each model context the Session opens reads the Agent config's\n * `model.thinking_level`, so config edits keep taking effect. Once pinned it survives\n * reloads and applies from the Session's very next LLM request — the thinking level is\n * the soft-limited runtime parameter, changeable mid-context at the cost of the\n * provider's cached context (the picker advises compacting first) — and every later\n * context opens at it; an Agent-config change no longer moves it.\n */\n thinkingLevel?: ThinkingLevelName;\n /** Short title auto-generated by the model after the first turn; unset until generated (frontend shows \"New Chat\"). */\n title?: string;\n /** Session source (for list badges/folders), derived from core session_meta — the single source of truth (not stored in the DB); unset for user-created sessions. */\n source?: SessionSource;\n createdAt: string;\n /**\n * Last activity the server drove for this Session (ISO 8601, same convention as\n * createdAt), monotonic — it never moves backwards. Set to createdAt at creation, then\n * stamped when a run starts and again when it ends; a run here is one Task, one\n * compaction, or one whole goal loop (every round of a goal belongs to a single run, so\n * an N-round goal stamps twice, not 2N times).\n *\n * Two kinds of row therefore stay at createdAt no matter how busy they look: Sessions\n * adopted from a CLI Trace (this server drives none of their runs) and subagent rows\n * (their work is driven through the parent Session's entry). Reading real activity for\n * those would mean consulting the Trace tree, which this field deliberately does not do.\n *\n * Rows that predate the field are backfilled once at startup from the Session's most\n * recent request timestamp, falling back to createdAt.\n */\n lastActiveAt: string;\n status: SessionStatus;\n /** Number of approvals awaiting human decision (a persisted count outside server events, for list badges). */\n pendingApprovalCount: number;\n /** Number of queued follow-up tasks (`queueIfBusy`) awaiting auto-start once the session is idle. */\n pendingFollowUpCount: number;\n /** Whether a Trace record exists (a Task has been started). */\n hasTrace: boolean;\n /** Whether archived (hidden from the default list, grouped under \"Archived\"). */\n archived: boolean;\n /**\n * Absolute path of the session's latest Trace file (the current context shard); absent\n * when no Trace exists yet. Populated on the **single-session GET only** — list rows omit\n * it (locating it costs a directory walk per Session). The web's `/model` switch puts it\n * into the new session's `[model_switch_from]` block so the model can read the source\n * history itself when it needs it.\n */\n tracePath?: string;\n /** Present when the Session has an ENABLED messaging binding: its channel (the sidebar row's per-channel indicator). */\n messagingChannel?: MessagingChannel;\n /**\n * Company mode: the organization that owns this Session — a desk session of one of its\n * employees, or a session contributing to one of its tickets — read from the organization\n * caches. Absent for every ordinary Session. Development mode's list and its time buckets\n * hide every row that carries it (only while company mode is available to that user: it is\n * stamped either way, and company mode is what lists these Sessions instead), and the\n * company sidebar's 工位 / 工单会话 groups are where they are listed.\n */\n orgId?: string;\n /**\n * Which client opened the Session, as stored on the index row: \"cli\" from the CLI (a\n * Session adopted from a legacy CLI-direct Trace included), \"org\" from the organization\n * runtime (a desk or a ticket session), \"web\" otherwise. Absent only on a row that\n * predates the column, which reads as \"web\". Unlike {@link SessionInfo.orgId} — projected\n * from the organization caches, so it disappears with the organization and is not read\n * while company mode is off — this is a durable stamp on the row: development mode's list\n * hides an \"org\" Session either way.\n */\n client?: \"web\" | \"cli\" | \"org\";\n /**\n * Background work the Session's loaded runtime still owns: command sessions running past\n * their yield window (`exec_command` promotions and `run_in_background` launches) and\n * background subagent sessions mid-round. Read from the runtime's in-memory registries —\n * no Trace is consulted — and present only while at least one count is non-zero, so a\n * Session that is not loaded (a resumed entry starts with empty registries) and one with\n * nothing running both omit it. Changes are pushed as `session_background` on the user\n * channel; list rows and the single-session GET carry the same field.\n */\n backgroundTasks?: SessionBackgroundTasks;\n}\n\n/** The background-task counts of one Session (see SessionInfo.backgroundTasks). */\nexport interface SessionBackgroundTasks {\n /** Background command sessions whose process is still running. */\n processes: number;\n /** Background subagent sessions (promoted to a `subagent_id`) currently mid-round. */\n subagents: number;\n}\n\n/**\n * Session list category, the sidebar's five-way split applied server-side: archived wins\n * regardless of origin (archiving is an explicit user action), then the origin's bucket,\n * and a Session with no (or an unknown) source is `active` — user-created rows.\n */\nexport type SessionCategory = \"active\" | SessionSource | \"archived\";\n\n/** Per-category totals across an Agent's whole Session list (returned when the list is requested with counts). */\nexport type SessionCategoryCounts = Record<SessionCategory, number>;\n\nexport interface SessionsResponse {\n sessions: SessionInfo[];\n /** Present when the request asked for counts (`counts=1`): totals per category over the full list, not just the returned page. */\n counts?: SessionCategoryCounts;\n /**\n * Present with `counts`: the same totals broken down by Workspace path (only paths\n * with at least one Session appear). The sidebar's workspace grouping decides each\n * group's folders and \"More\" from its own share, so a group never advertises\n * content that lives in other Workspaces.\n */\n workspaceCounts?: Record<string, SessionCategoryCounts>;\n /**\n * Present with `counts`: each Workspace path's newest Session (any category), as its\n * `createdAt`. With `workspaceCounts` this is what lets the sidebar list every Workspace\n * that holds Sessions and place the groups by recency before — or without — loading any\n * of their rows.\n */\n workspaceLatest?: Record<string, string>;\n}\n\n/** Server directory browsing (advanced new-Workspace picker): starts from the home directory by default, can navigate up to the root. */\nexport interface DirEntryInfo {\n name: string;\n /** Absolute path of this subdirectory (can be submitted directly as a Workspace). */\n path: string;\n}\nexport interface DirListResponse {\n /** Absolute path of the current directory (realpath). */\n path: string;\n /** Absolute path of the parent directory; null when already at the root. */\n parent: string | null;\n /** Subdirectory list (sorted by name, files excluded). */\n entries: DirEntryInfo[];\n}\n\n/** One Skill found in a picked directory: metadata plus which of the two layouts it came from. */\nexport interface DirectorySkillItem extends SkillMetadataItem {\n /** `.agents/skills` or `.claude/skills` — shown so the origin of an offered Skill is visible. */\n source: string;\n}\n\nexport interface DirectorySkillsResponse {\n /** Absolute path that was scanned (realpath). */\n path: string;\n /** Installable Skills found under the directory's Skill layouts; empty when it carries none. */\n skills: DirectorySkillItem[];\n}\n\nexport interface SessionCreateRequest {\n /** Upstream id of the session's model; always sent together with provider. Omit both for the Project's default Model. */\n modelId?: string;\n /**\n * Provider group for `modelId`. A model reference is always a complete\n * (provider, modelId) pair — the provider is never inferred, so sending one field\n * without the other returns 400 instead of being resolved.\n */\n provider?: string;\n /** Any existing directory on the server; defaults to auto-creating a temporary Workspace. */\n workspace?: string;\n /** Defaults to allow-all. */\n approvalMode?: ApprovalMode;\n /**\n * Creating-client hint stored on the Session row: \"cli\" when the CLI creates the\n * Session through the API, \"org\" when the organization runtime opened it (a desk or a\n * ticket session — company mode's own, kept out of development mode's lists whether or\n * not the organization still exists); defaults to \"web\". A REQUEST may send only \"web\" or\n * \"cli\": the runtime writes \"org\" by calling the service directly, so no caller can claim\n * an organization's provenance for its own Session. Lists serve every row regardless of\n * client; only development mode's session list filters on it.\n */\n client?: \"web\" | \"cli\" | \"org\";\n /**\n * Marks the Session as created by a Benchmark evaluation or optimization (the Evaluation\n * Center's Use flows, and the Test Sessions agent-evaluation launches through the CLI). Only\n * this value is accepted from a client: `subagent` and `schedule` are written by the server\n * itself. The Web App files such Sessions into the Evaluations folder of the session list.\n */\n source?: \"benchmark\";\n}\n\nexport interface SessionCreateResponse {\n session: SessionInfo;\n}\n\n/** Immutable location of one record in a Session's append-only Trace. */\nexport interface TracePosition {\n /** Trace shard index (`001` on disk becomes `1`). */\n fileIndex: number;\n /** Zero-based record ordinal within the parsed shard. */\n ordinal: number;\n}\n\n/** History-only transport metadata; `tracePosition` is never persisted into Trace JSONL. */\nexport type HistoryMessage = OmniMessage & { tracePosition?: TracePosition };\n\nexport interface SessionForkRequest {\n /** The final root assistant text record of the completed Task to keep. */\n position: TracePosition;\n}\n\nexport interface SessionForkResponse {\n session: SessionInfo;\n}\n\nexport interface SessionResponse {\n session: SessionInfo;\n}\n\nexport interface SessionPatchRequest {\n approvalMode?: ApprovalMode;\n /**\n * Pin this Session's thinking level (`none | low | medium | high | xhigh | max`, anything else\n * is a 400). It replaces the Agent-config fallback for this Session and applies from the\n * very next LLM request — soft-limited: a mid-context change is allowed, at the cost of\n * the provider's cached context, which is why the picker advises compacting first. There\n * is no unpin: the picker only offers concrete levels.\n */\n thinkingLevel?: ThinkingLevelName;\n /** Archive / unarchive (default list hides archived). */\n archived?: boolean;\n /** Manual rename; non-empty string, overrides the auto-generated title. */\n title?: string;\n}\n\n/**\n * Live in-progress tail of a running Session, carried by `MessagesResponse.live`.\n *\n * Contract (see runtime/live-tail.ts and the GET /messages route): the server captures\n * `cursor` and `fragments` atomically — in one synchronous tick, before starting the\n * trace read — while the Session is running/compacting.\n * - `cursor`: the Session channel's most recently assigned SSE event id\n * (`<epoch>-<seq>`); every event published up to and including this id is already\n * reflected in `fragments`.\n * - `fragments`: one synthetic `partial_* start` OmniMessage per open streaming\n * fragment, whose payload carries the full accumulated content so far (text/thinking\n * prefix, tool-call name + accumulated arguments, tool-output prefix + images), with\n * the original `origin` chain preserved.\n *\n * Client usage (the bundled Web App's connect-first flow): after applying `messages`,\n * when the cursor's epoch matches the epoch of the SSE events seen on the current\n * connection, drop every buffered **partial** event with seq <= cursor (its content is\n * already inside `fragments`), feed `fragments` through the normal reducer path, then\n * replay the rest of the buffer. Buffered **complete** messages are never dropped by the\n * cursor — the regular overlap dedup decides for them — so nothing is lost even when a\n * complete message's trace append is still in flight at read time.\n */\nexport interface MessagesLiveTail {\n cursor: string;\n fragments: OmniMessage[];\n}\n\n/**\n * Pagination envelope of a windowed `GET /messages` (`tailLimit` / `before` requests\n * only; the parameterless full read never carries it). A window is a run of whole\n * message-bearing units — one unit = one Task in the Web reducer's sense, opened by a\n * main-session user prompt — cut so that no pairing (tool_call/output), compaction span\n * or steering group ever splits across windows.\n */\nexport interface MessagesPageInfo {\n /**\n * Cursor of this window's first unit (`<shardIndex>:<ordinal>`): pass it back as\n * `before=` to fetch the previous window. Stable across requests and compaction —\n * rotation opens a NEW shard and closed shards are immutable. Absent = this window\n * reaches the very beginning of the transcript (no older history).\n */\n before?: string;\n /**\n * Outline turns (the Web conversation outline's entry rule) opened BEFORE this\n * window: the client offsets its global \"round N\" numbering by this, so a partial\n * window never mis-numbers. 0 when the window starts at the beginning.\n */\n earlierTurns: number;\n /**\n * Cumulative stats accrued before this window, seeded into the client's stats\n * tracker so header chips and per-turn cumulative rows equal a full load:\n * finished-Task elapsed, subagent token totals, and the last main-session\n * session/context token readings.\n */\n prior: {\n subagentTokens: number;\n elapsedMs: number;\n /**\n * Model-API time and tool wall time accrued before this window, the breakdown of\n * `elapsedMs` the chat header shows under it. Seeded together with their total: seeding\n * one alone would put a full elapsed time beside components covering only the window.\n * The two may overlap and do not partition `elapsedMs` (see `TraceTaskStats.toolMs`).\n */\n apiMs: number;\n toolMs: number;\n sessionTokens: number;\n contextTokens: number;\n };\n}\n\n/** Message history: the full messages and events from concatenating all of this Session's Trace files in order (excludes partial_*). */\nexport interface MessagesResponse {\n messages: HistoryMessage[];\n /**\n * Present only while the Session is running/compacting: the in-progress stream tail\n * (open streaming fragments + the channel cursor they cover), so a client joining\n * mid-stream can render the currently streaming message. Omitted when idle. On\n * windowed requests it rides TAIL pages only — a `before` page is immutable history\n * and never carries it.\n */\n live?: MessagesLiveTail;\n /**\n * Present exactly on windowed requests (`tailLimit` / `before`): `messages` is then\n * the requested window (subagent pointers inside it expanded as usual) rather than\n * the full transcript. See MessagesPageInfo.\n */\n page?: MessagesPageInfo;\n}\n\n// ---------------------------------------------------------------------------\n// Task run, approval, interruption, compaction\n// ---------------------------------------------------------------------------\n\n/**\n * A single Prompt's input parts: text, image (data: / http(s) URL), or an uploaded file.\n * Docs: /docs/server-api § \"Session-Level Endpoints\".\n */\nexport type TaskInputPart =\n | { type: \"text\"; text: string }\n /**\n * An image that rides the conversation inline, as a base64 `data:` URL or an http(s) URL.\n * A data URL is capped at 20MB (413 `image_too_large`) — a fixed limit that does NOT follow\n * the admin-settable attachment cap, because an inline image is written into the Trace and\n * read back on every history page and every resume.\n */\n | { type: \"image_url\"; imageUrl: string }\n /**\n * File attachment (the composer's \"+\" menu): `dataUrl` is a base64 `data:` URL of the\n * file's bytes, capped per file and per message by the admin-settable upload limits\n * (defaults 100MB / 120MB; 413 `file_too_large` / `payload_too_large` / `too_many_files`,\n * and the request as a whole still has to fit the body cap those limits derive). The\n * server writes it into the Session scratchpad under a sanitized name and appends an\n * `[attached file: <path>]` line to the message text — the bytes never enter the\n * conversation, the model opens the file by path. `fileName` is the original name (no path\n * separators, no `..`).\n */\n | { type: \"file\"; fileName: string; dataUrl: string };\n\nexport interface TaskCreateRequest {\n input: TaskInputPart[];\n /**\n * Queue instead of 409 when a Task/compaction is already in progress: the input is held\n * server-side and auto-starts as an ordinary next task once the session returns to idle\n * (in queue order, one at a time). The response then carries `queued: true`.\n */\n queueIfBusy?: boolean;\n /**\n * Present = goal mode: the input's text becomes the objective (leading `[use_skills]`\n * blocks and the like are stripped from the recorded objective; the round-1 message keeps\n * them) and the Session's installed `goal` hook package drives round after round until the\n * goal reaches a terminal state. `budget` is the token budget (uncached input + output);\n * omitted or -1 = unlimited. Requires the goal plugin installed on the Agent — 409\n * `goal_plugin_not_installed` otherwise.\n */\n goal?: { budget?: number };\n}\n\n/** Goal-mode run state, read from the Session's GOAL.json — the goal plugin's file (the chat page's banner restores from it; a live status on an idle Session reads as `aborted`). */\nexport interface GoalStateView {\n objective: string;\n status: \"active\" | \"complete\" | \"blocked\" | \"budget_limited\" | \"aborted\";\n /** Token budget; -1 = unlimited. */\n budget: number;\n used: number;\n rounds: number;\n}\n\nexport interface GoalResponse {\n /** The Session's most recent goal run; null if it never ran one. */\n goal: GoalStateView | null;\n}\n\nexport interface TaskCreateResponse {\n /** Current actual session_id: a Trace-less invalid Session self-heals and returns a new id; the frontend updates its route accordingly. */\n sessionId: string;\n /** True when `queueIfBusy` enqueued the input as a follow-up instead of starting it (absent/false: the task started). */\n queued?: boolean;\n}\n\n/**\n * Mid-run steering (POST /api/sessions/:id/steer): a user message for the **running** Task,\n * delivered by core between turns as a standalone `[user_steering]` user message. 202 on\n * queue; 409 `not_running` when no Task is in progress (the frontend falls back to a normal\n * task POST).\n */\nexport interface SteerRequest {\n /** Message text (trimmed server-side); may be empty when `images` or `files` carries the message. */\n text: string;\n /**\n * Images sent with the steering message (`data:` or http(s) URLs, same rule as\n * `TaskInputPart.image_url`): delivered as user image messages right behind the\n * `[user_steering]` text. A model without vision receives them as scratchpad path lines\n * instead, exactly as it would a Prompt's images. At least one of `text` / `images` /\n * `files` must be non-empty.\n */\n images?: string[];\n /**\n * File attachments riding the steering message — the same shape, caps and handling as a\n * task input's `{type:\"file\"}` parts: written into the Session scratchpad and delivered\n * as `[attached file: <path>]` lines on the `[user_steering]` text, so a file-only draft\n * steers exactly like an image-only one instead of falling back to the follow-up queue.\n */\n files?: { fileName: string; dataUrl: string }[];\n}\n\n/**\n * One steering message queued on the server but not yet delivered to the model (delivery\n * happens at the next input assembly between turns). Carried on `task_state` events and the\n * SSE subscribe snapshot so the composer's \"steering queued\" hint — including what was sent —\n * survives reloads; entries leave the list as their `[user_steering]` message appears on the\n * stream, and the whole list drops when the run exits (core discards undelivered steering).\n */\nexport interface PendingSteeringInfo {\n /** Server-assigned id, stable for the entry's queued lifetime: the handle DELETE /steer/:steerId recalls it by. */\n id: string;\n /** The message text as accepted (trimmed); may be empty when images/files carry the message. */\n text: string;\n /** Number of images that rode along. */\n images: number;\n /** Number of file attachments that rode along. */\n files: number;\n}\n\n/**\n * One follow-up task queued with `queueIfBusy` but not yet auto-started. Carried on\n * `task_state` events and the SSE subscribe snapshot (like `pendingSteering`) so the\n * composer can show each queued message's content with a recall affordance; entries leave\n * the list when they auto-start on idle — or when DELETE /follow-ups/:followUpId recalls one.\n */\nexport interface PendingFollowUpInfo {\n /** Server-assigned id, stable for the entry's queued lifetime: the handle DELETE /follow-ups/:followUpId recalls it by. */\n id: string;\n /** The queued input's text parts, joined; may be empty when images/files carry the message. */\n text: string;\n /** Number of images in the queued input. */\n images: number;\n /** Number of file attachments in the queued input. */\n files: number;\n}\n\n/**\n * One live subagent child of a session's runtime, carried on `task_state` events and the SSE\n * subscribe snapshot: the child Session id (the origin hop the stream already correlates by),\n * its background registry handle (null while it only lives inside a foreground collect\n * window), and whether a round is currently running. Only an ACTIVE parent runtime reports\n * children — after a server restart the in-process children are gone, and the empty list is\n * the truth.\n */\nexport interface SubagentRuntimeInfo {\n sessionId: string;\n subagentId: string | null;\n running: boolean;\n}\n\n/**\n * Response of POST /api/sessions/:sessionId/subagents/:childSessionId/message — a user input\n * on the child, whatever its state: `steered` = queued as a mid-run interjection, `started` =\n * began a follow-up run on the idle child, `resumed` = the released child session was revived\n * (resume-session semantics) and the message began its next round. The failure shapes are\n * HTTP statuses instead: 404 when the child's session record does not exist or cannot be\n * revived, 409 when the child cannot take the message right now.\n */\nexport interface SubagentMessageResponse {\n outcome: \"steered\" | \"started\" | \"resumed\";\n}\n\n/**\n * Response of the two recall endpoints — DELETE /api/sessions/:id/steer/:steerId and\n * DELETE /api/sessions/:id/follow-ups/:followUpId: the withdrawn message's original content,\n * for the composer to restore into the input box for editing and resending (#287). File\n * attachments are read back from the Session scratchpad (then deleted from it); one that\n * disappeared meanwhile is omitted rather than failing the recall. 409 when the entry is no\n * longer queued, with a code per endpoint because the reasons read differently to the user:\n * `not_pending` — the steering message already reached the model; `follow_up_started` — the\n * follow-up already auto-started as a task of its own (unknown ids land on the same code).\n */\nexport interface RecalledMessageResponse {\n text: string;\n /** The images as submitted (`data:` / http(s) URLs). */\n images: string[];\n /** The file attachments, re-encoded as base64 data URLs (the shape the composer submits them in). */\n files: { fileName: string; dataUrl: string }[];\n}\n\nexport interface ApprovalDecisionRequest {\n decision: \"allow\" | \"deny\";\n}\n\n/**\n * POST /api/sessions/:sessionId/retry-now — skip the in-progress reconnect backoff and\n * fire the next retry immediately (the \"retry now\" button on the reconnect countdown).\n * `skipped: false` is the benign \"no reconnect wait in progress\" case (idle session, or\n * the wait elapsed in a timing race), not an error.\n */\nexport interface RetryNowResponse {\n skipped: boolean;\n}\n\n/**\n * One background command process started by the Session (an exec_command promoted past\n * its yield window). Served from the ACTIVE runtime only: a session whose runtime entry\n * is gone truthfully reports an empty list.\n */\nexport interface SessionProcessInfo {\n processId: string;\n /** OS pid of the process-group leader; null when the spawn itself failed. */\n pid: number | null;\n cmd: string;\n cwd: string;\n startedAt: string;\n running: boolean;\n /** The service the process serves, when detected: the last local URL its output printed, else an origin probed from its listening ports. */\n serviceUrl?: string;\n}\n\nexport interface SessionProcessesResponse {\n processes: SessionProcessInfo[];\n}\n\n// ---------------------------------------------------------------------------\n// Messaging bindings (/api/sessions/:sessionId/messaging/*)\n// ---------------------------------------------------------------------------\n\n/** Messaging channels a Session can bind to. */\nexport type MessagingChannel = \"feishu\" | \"telegram\" | \"qq\" | \"wechat\";\n\n/** Event-connection runtime state of one binding (kept in memory, not persisted). */\nexport type MessagingRuntimeState = \"disconnected\" | \"connecting\" | \"connected\" | \"error\";\n\n/**\n * A failure that happened AFTER an inbound message was accepted — as opposed to a\n * connection failure, which `MessagingRuntimeStatus.lastError` reports.\n *\n * The two stages fail in completely different places and lead to different actions, and\n * from the chat they are indistinguishable (both produce silence), which is why the stage\n * is stated rather than folded into one message.\n */\nexport interface MessagingDeliveryError {\n /** ISO 8601 timestamp of the failure. */\n at: string;\n /** `inbound` — the message arrived and its Task never started; `send` — a reply never reached the chat. */\n stage: \"inbound\" | \"send\";\n /** The failure's own message, as the channel or the Session reported it. */\n detail: string;\n}\n\nexport interface MessagingRuntimeStatus {\n state: MessagingRuntimeState;\n /** Failure detail; present only in the `error` state. */\n lastError?: string;\n /** When the state last changed (ISO 8601); absent for a binding that never connected. */\n changedAt?: string;\n /**\n * When this binding last accepted an inbound message (ISO 8601).\n *\n * \"Connected, and nothing has arrived\" is the answer to the one question a chat cannot\n * answer for itself — whether the platform is delivering anything at all. A channel that\n * withholds messages (Telegram's group privacy, a bot that is not a member) produces\n * exactly that, with no error anywhere.\n *\n * In-process AND scoped to one connection: it starts empty on every (re)connect, and a\n * re-enable or a credential save opens a new one. So an absent field means \"nothing since\n * this connection opened\", never \"nothing ever\" — anything reporting it has to say which,\n * or it sends a reader off to fix a channel that is working.\n */\n lastInboundAt?: string;\n /**\n * The most recent post-acceptance failure; absent when none has happened since this\n * connection opened, and never cleared by a later success — an intermittent failure would\n * otherwise be erased by the next ordinary message. `at` is what says how stale it is.\n */\n lastDeliveryError?: MessagingDeliveryError;\n /**\n * The most recent CONNECTION failure, kept after the connection recovers — unlike\n * `lastError`, which belongs to the `error` state and is gone the moment the state leaves it.\n *\n * A connection that fails and recovers repeatedly (a second program polling the same bot\n * token takes turns with this one) reads as `connected` in any snapshot taken between\n * flaps, with nothing at all to show for the failures in between. This is what is left\n * behind — for the life of the connection, like the two above it.\n */\n lastConnectionError?: { at: string; detail: string };\n}\n\n/**\n * What a messaging binding carries whatever channel it is: the connection intent, the three\n * delivery preferences, whether a chat is known, and the row's identity and timestamps.\n *\n * Split out because this is the half that grows. Three delivery preferences arrived in one\n * release, and each would otherwise have been written into three interfaces — the credential\n * slice is the only thing a channel genuinely differs in, and it is what stays per-channel.\n *\n * `channel` is NOT here: a discriminated union discriminates on a literal the member itself\n * declares, so each interface keeps its own.\n *\n * A channel may RE-DECLARE a field below when it has more to say about it — QQ does, for all\n * three preferences, because the platform's passive-reply budget and its expiring window\n * change what setting one costs there. The re-declared type must be identical, which the\n * compiler enforces, so the redeclaration can only add documentation and never a contract.\n */\nexport interface MessagingBindingCommon {\n sessionId: string;\n /** Connection INTENT (the state toggle's value); new bindings start disabled, and at most one of a Session's channels is enabled. */\n enabled: boolean;\n /**\n * Send each non-blank line of a relayed assistant reply as its own message instead of one\n * message per reply. Off by default; off is the original one-message-per-reply behaviour.\n */\n linePerMessage: boolean;\n /**\n * Relay only the LAST completed assistant message of a run, delivered when the run ends,\n * instead of mirroring each completed message as it completes. Off by default; off is the\n * original every-message behaviour. Independent of `linePerMessage`, which then applies to\n * that one final message. The approval notice is not a reply and is unaffected.\n */\n finalReplyOnly: boolean;\n /**\n * Render a relayed reply's Markdown in this channel's own markup instead of sending its\n * characters as written. ON by default. Each channel shows what it can — Telegram has no\n * headings, lists or tables, QQ has no code or tables, Feishu has all of them, and WeChat\n * reads Markdown itself so the render is a subtraction rather than a translation — and a\n * rendering the channel refuses falls back to the plain source, so this can cost\n * formatting and never a message.\n */\n renderMarkdown: boolean;\n /**\n * Whether an inbound chat is known (the bot has been messaged at least once). Replies and\n * test messages target that chat; until it exists nothing can be sent.\n */\n lastChatKnown: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/** The stored Feishu config, secret masked (plaintext never leaves the server). */\nexport interface FeishuBindingInfo extends MessagingBindingCommon {\n channel: \"feishu\";\n appId: string;\n /**\n * Masked app secret (site-wide mask rule: `***`, or `first4…last4` for long values);\n * absent when no secret is stored (never entered, or cleared) — the binding cannot be\n * enabled until one is saved.\n */\n appSecretMasked?: string;\n baseDomain: string;\n}\n\n/** The stored Telegram config, token masked (plaintext never leaves the server). */\nexport interface TelegramBindingInfo extends MessagingBindingCommon {\n channel: \"telegram\";\n /** The numeric bot id (the token's half before the colon) — the channel-scoped account identity, never secret. */\n botId: string;\n /**\n * Masked bot token (site-wide mask rule: `***`, or `first4…last4` for long values);\n * absent when no token is stored (cleared) — the binding cannot be enabled until one\n * is saved.\n */\n botTokenMasked?: string;\n}\n\n/**\n * The stored QQ config, secret masked (plaintext never leaves the server).\n *\n * The three preference fields are re-declared unchanged: every one of them costs something\n * different here, and the platform's reply budget is what a reader setting one needs to know.\n */\nexport interface QQBindingInfo extends MessagingBindingCommon {\n channel: \"qq\";\n /** The bot's App ID — the channel-scoped account identity, never secret. */\n appId: string;\n /**\n * Masked App Secret (site-wide mask rule: `***`, or `first4…last4` for long values);\n * absent when no secret is stored (never entered, or cleared) — the binding cannot be\n * enabled until one is saved.\n */\n appSecretMasked?: string;\n /**\n * Send each non-blank line of a relayed assistant reply as its own message instead of one\n * message per reply. Off by default. On QQ the split is additionally capped at the\n * platform's passive-reply budget rather than the channel-neutral ceiling, so it yields\n * far fewer messages here than on the other channels.\n */\n linePerMessage: boolean;\n /**\n * Relay only the LAST completed assistant message of a run, delivered when the run ends.\n * Off by default.\n *\n * On QQ it cuts both ways, which is worth knowing before setting it here. It spends the\n * least of the platform's passive-reply budget a run can spend — one message, where an\n * every-message relay spends one per completed message. But a passive reply is accepted\n * only for a few minutes after the inbound message that funds it, and holding the reply\n * to the run's end spends that window on the run: a run that outlives it delivers nothing\n * at all, where the every-message relay would have sent whatever completed inside it.\n */\n finalReplyOnly: boolean;\n /**\n * Render a relayed reply's Markdown in this channel's own markup. ON by default. QQ's own\n * subset is the widest for prose and the narrowest for code: headings, lists, blockquotes\n * and rules render, while inline code, fenced code and tables have no syntax at all here —\n * a code block arrives as plain escaped lines. A rendering the platform refuses falls back\n * to the plain source, at the cost of one more slot from the passive-reply budget.\n */\n renderMarkdown: boolean;\n /**\n * Whether an inbound QQ chat is known (the bot has been messaged at least once). Weaker\n * than it looks on this channel: QQ accepts only replies to a recent message, so a known\n * chat is necessary but not sufficient for anything to be deliverable right now.\n */\n lastChatKnown: boolean;\n}\n\n/**\n * The stored WeChat config, token masked (plaintext never leaves the server).\n *\n * No preference field is re-declared. The three delivery preferences cost exactly what they\n * cost on Feishu and Telegram here — this channel has no reply budget and no expiring reply\n * window — and re-declaring a field to say nothing new about it would only invite the next\n * reader to look for the difference.\n */\nexport interface WeChatBindingInfo extends MessagingBindingCommon {\n channel: \"wechat\";\n /** The bot id a scan issued — the channel-scoped account identity, never secret. */\n botId: string;\n /**\n * Masked bot token (site-wide mask rule: `***`, or `first4…last4` for long values);\n * absent when none is stored (cleared, or a scan that never completed) — the binding\n * cannot be enabled until a scan saves one.\n */\n botTokenMasked?: string;\n}\n\n/** A Session's saved config for one messaging channel (`channel` is the discriminant). */\nexport type MessagingBindingInfo =\n FeishuBindingInfo | TelegramBindingInfo | QQBindingInfo | WeChatBindingInfo;\n\n/** One saved channel config with its event-connection runtime status. */\nexport interface MessagingChannelState {\n binding: MessagingBindingInfo;\n /** Only the enabled channel's connection is ever anything but disconnected. */\n status: MessagingRuntimeStatus;\n}\n\n/**\n * GET …/messaging response — the channel-agnostic read the channel-aware binding editor\n * loads: EVERY saved channel config (masked) with its runtime status. A Session may keep\n * both channels saved; at most one of them is enabled.\n */\nexport interface MessagingBindingsResponse {\n bindings: MessagingChannelState[];\n}\n\n/** GET / PUT …/messaging/feishu response: the Feishu config (null = not saved) plus its runtime status. */\nexport interface FeishuBindingResponse {\n binding: FeishuBindingInfo | null;\n status: MessagingRuntimeStatus;\n}\n\n/** GET / PUT …/messaging/telegram response (the Telegram narrowing of the same envelope). */\nexport interface TelegramBindingResponse {\n binding: TelegramBindingInfo | null;\n status: MessagingRuntimeStatus;\n}\n\n/** GET / PUT …/messaging/qq response (the QQ narrowing of the same envelope). */\nexport interface QQBindingResponse {\n binding: QQBindingInfo | null;\n status: MessagingRuntimeStatus;\n}\n\n/** GET / PUT …/messaging/wechat response (the WeChat narrowing of the same envelope). */\nexport interface WeChatBindingResponse {\n binding: WeChatBindingInfo | null;\n status: MessagingRuntimeStatus;\n}\n\n/**\n * PUT …/messaging/feishu — saves credentials/config ONLY, never flipping the connection\n * (exception: an enabled binding's connector restarts with the new credentials so stored\n * config and live connection never diverge). The connection toggle is POST …/state.\n */\n/**\n * The delivery preferences any channel's PUT may set. Each is optional and each behaves the\n * same way on every channel: an omitted field keeps the stored value, so a client that knows\n * about one preference can save it without having to send the others back. Their meanings are\n * on {@link MessagingBindingCommon}, and where a channel charges differently for one, on that\n * channel's own `*BindingInfo`.\n *\n * The defaults a binding created without them starts from: `linePerMessage` off,\n * `finalReplyOnly` off, `renderMarkdown` ON.\n */\nexport interface MessagingDeliveryPatch {\n linePerMessage?: boolean;\n finalReplyOnly?: boolean;\n renderMarkdown?: boolean;\n}\n\nexport interface FeishuBindingPutRequest extends MessagingDeliveryPatch {\n appId: string;\n /** Omitted or blank keeps the stored secret (the masked value never round-trips). */\n appSecret?: string;\n /** Defaults to https://open.feishu.cn when omitted or blank. */\n baseDomain?: string;\n /**\n * Drops the STORED secret (the models-page clear idiom; a typed `appSecret` wins over\n * it). Refused with 409 `messaging_disable_before_clear` while the binding is enabled.\n */\n clearAppSecret?: boolean;\n}\n\n/**\n * PUT …/messaging/telegram — saves the credential ONLY, same contract as the Feishu PUT\n * (an enabled binding's connector restarts with the new token; the connection toggle is\n * POST …/state). Saving never conflicts across Sessions: the same bot may sit saved on\n * several, and only enabling it is exclusive.\n */\nexport interface TelegramBindingPutRequest extends MessagingDeliveryPatch {\n /** Omitted or blank keeps the stored token (the masked value never round-trips). */\n botToken?: string;\n /**\n * Drops the STORED token (the models-page clear idiom; a typed `botToken` wins over\n * it — and the row keeps its bot identity). Refused with 409\n * `messaging_disable_before_clear` while the binding is enabled.\n */\n clearBotToken?: boolean;\n}\n\n/**\n * PUT …/messaging/qq — saves the credential pair ONLY, same contract as the Feishu PUT\n * (an enabled binding's connector restarts with the new credentials; the connection toggle\n * is POST …/state). The App ID is the account identity, so changing it rebinds the row to\n * a different bot and drops the remembered chat.\n */\nexport interface QQBindingPutRequest extends MessagingDeliveryPatch {\n appId: string;\n /** Omitted or blank keeps the stored secret (the masked value never round-trips). */\n appSecret?: string;\n /**\n * Drops the STORED secret (the models-page clear idiom; a typed `appSecret` wins over\n * it). Refused with 409 `messaging_disable_before_clear` while the binding is enabled.\n */\n clearAppSecret?: boolean;\n}\n\n/**\n * PUT …/messaging/wechat — the delivery preferences ONLY.\n *\n * The one PUT on this router that carries no credential, because there is none to carry: a\n * WeChat bot token exists only where a scan put it, and there is no console to copy one out\n * of. Saving therefore presupposes a binding — a PUT before any scan answers 400\n * `wechat_token_required` rather than creating an empty row — and the connection toggle\n * stays POST …/state, as on every channel.\n */\nexport interface WeChatBindingPutRequest extends MessagingDeliveryPatch {\n /**\n * Drops the STORED token (the models-page clear idiom). Refused with 409\n * `messaging_disable_before_clear` while the binding is enabled. The row and its bot\n * identity stay; only a fresh scan can make it connectable again.\n */\n clearBotToken?: boolean;\n}\n\n/**\n * POST …/messaging/<channel>/state — enable connects with the STORED credentials,\n * disable terminates. Enabling is what binds the bot account to this Session, and it is\n * mutually exclusive twice over: while another channel of the same Session is enabled it\n * answers 409 `another_channel_enabled`, and while another SESSION has the same account\n * enabled it answers 409 `account_enabled_elsewhere` (both say: turn that one off first).\n * A config whose secret is missing answers its channel's 400 `*_required`.\n */\nexport interface MessagingBindingStateRequest {\n enabled: boolean;\n}\n\n/** POST …/messaging/feishu/test — draft values; each omitted field falls back to the stored binding. */\nexport interface FeishuTestRequest {\n appId?: string;\n appSecret?: string;\n baseDomain?: string;\n}\n\n/** Credential-test outcome (an unreachable/rejected credential is `ok:false`, not an HTTP error). */\nexport interface FeishuTestResponse {\n ok: boolean;\n latencyMs?: number;\n error?: string;\n}\n\n/** POST …/messaging/telegram/test — a draft token, falling back to the stored binding when omitted. */\nexport interface TelegramTestRequest {\n botToken?: string;\n}\n\n/** Telegram credential-test outcome: success additionally names the bot the token signs in as. */\nexport interface TelegramTestResponse {\n ok: boolean;\n latencyMs?: number;\n /** The bot's `@username`, when the API reports one. */\n botUsername?: string;\n /**\n * True when @BotFather's **Group Privacy** is ON for this bot, which is the default. In\n * every group where the bot is not an administrator it then receives only a command\n * addressed to it or a reply to one of its own messages — an ordinary sentence is never\n * delivered, so a binding that answers fine in a direct chat stays silent there. The\n * setting is account-wide and Telegram overrides it for a group the bot administers, so\n * this reports the setting and never the outcome in any particular group. Absent when the\n * API did not report the setting; never inferred.\n */\n groupPrivacy?: boolean;\n error?: string;\n}\n\n/** POST …/messaging/qq/test — draft values; each omitted field falls back to the stored binding. */\nexport interface QQTestRequest {\n appId?: string;\n appSecret?: string;\n}\n\n/**\n * QQ credential-test outcome. There is no account label: the platform's only credential\n * call is the access-token exchange, which identifies nothing beyond the App ID that was\n * sent to it.\n */\nexport interface QQTestResponse {\n ok: boolean;\n latencyMs?: number;\n error?: string;\n}\n\n/**\n * POST …/messaging/qq/scan — starts a scan-to-connect flow: the server registers a bind\n * task under a fresh AES key it keeps to itself, and answers with what the browser may\n * know. The key is absent from this type on purpose — it decrypts the App Secret, so it\n * never leaves the server (the same rule that keeps a stored secret from round-tripping).\n */\nexport interface QQScanStartResponse {\n /** Opaque bind-task handle, passed back to the poll endpoint. */\n taskId: string;\n /** The URL to ENCODE into a QR code. It is opened by the QQ app, never fetched by the browser. */\n qrUrl: string;\n /** How often to poll, in milliseconds (the interval the protocol is designed around). */\n pollMs: number;\n}\n\n/**\n * POST …/messaging/qq/scan/poll — one step of the scan. `pending` means keep polling,\n * `expired` means start a new task and show a new QR, and `completed` means the server has\n * already decrypted the App Secret and SAVED the binding: `appId` names the bot that landed.\n * Saving is all it does — enabling the connection stays the separate, exclusive act it is on\n * every channel. A task id that is unknown, belongs to another Session, was already\n * resolved, or is being resolved by a poll still in flight answers 404\n * `qq_scan_task_unknown`: the task is claimed by one poll, so a client whose interval fires\n * before the previous request came back binds once rather than once per overlapping poll.\n */\nexport interface QQScanPollResponse {\n status: \"none\" | \"pending\" | \"completed\" | \"expired\";\n /** The bound bot's App ID; present only on `completed`. Never the secret. */\n appId?: string;\n /** The saved binding, present on `completed` so the editor refreshes without a second GET. */\n binding?: QQBindingInfo;\n}\n\n/**\n * WeChat credential-test outcome. There is no request body and no draft to probe: this\n * channel's credential exists only where a scan put it, so the test always probes the STORED\n * binding. It answers 400 `wechat_token_required` when there is none.\n *\n * No account label, for the same reason QQ has none: the probe (`getconfig`) reports the\n * bot's settings and names neither the bot nor the person.\n */\nexport interface WeChatTestResponse {\n ok: boolean;\n latencyMs?: number;\n error?: string;\n}\n\n/**\n * POST …/messaging/wechat/scan — starts a scan-to-connect flow, which on this channel is the\n * ONLY way to bind: the bot token has no console to be copied out of.\n *\n * The server registers a code and answers with what the browser may know. The platform's own\n * poll handle is absent from this type on purpose — it is what collects the bot token, so it\n * never leaves the server, and `taskId` is a handle this server mints in its place.\n */\nexport interface WeChatScanStartResponse {\n /** Opaque scan handle, passed back to the poll, verify and cancel endpoints. */\n taskId: string;\n /** The URL to ENCODE into a QR code. It is opened by WeChat, never fetched by the browser. */\n qrUrl: string;\n /** How often to poll, in milliseconds. */\n pollMs: number;\n}\n\n/**\n * Where a WeChat scan stands. Richer than QQ's four states because the flow is: WeChat\n * separates scanning from confirming, and may interpose a pairing code shown on the phone.\n *\n * - `pending` — the code is up and nothing has happened; keep polling.\n * - `scanned` — scanned; the phone is showing the confirmation prompt.\n * - `need_verify_code` — the phone is showing digits that must be sent to the verify\n * endpoint before the bind proceeds.\n * - `blocked` — too many wrong pairing codes; the code is spent and a new scan is needed.\n * - `expired` — the code lapsed before it was used; show a new one.\n * - `already_bound` — this bot is already bound to this server, so no new credentials were\n * issued and nothing was saved. Not a failure: the existing binding still works.\n * - `completed` — the server has already SAVED the binding; `botId` names the bot.\n */\nexport type WeChatScanStatus =\n | \"pending\"\n | \"scanned\"\n | \"need_verify_code\"\n | \"blocked\"\n | \"expired\"\n | \"already_bound\"\n | \"completed\";\n\n/**\n * POST …/messaging/wechat/scan/poll — one step of the scan.\n *\n * `completed` means the server has decrypted nothing and stored everything: the credentials\n * went from the platform into storage without passing through the browser. Saving is all it\n * does — enabling the connection stays the separate, exclusive act it is on every channel. A\n * task id that is unknown, belongs to another Session, or was already resolved answers 404\n * `wechat_scan_task_unknown`.\n *\n * Unlike QQ's poll, an overlapping request answers `pending` rather than 404: the upstream\n * call is a LONG poll, so one of them spans several of the client's intervals, and that\n * overlap is the normal rhythm rather than a replay.\n */\nexport interface WeChatScanPollResponse {\n status: WeChatScanStatus;\n /** The bound bot's id; present only on `completed`. Never the token. */\n botId?: string;\n /** The saved binding, present on `completed` so the editor refreshes without a second GET. */\n binding?: WeChatBindingInfo;\n}\n\n/**\n * POST …/messaging/wechat/scan/verify — the digits WeChat showed on the phone.\n *\n * They ride the NEXT poll rather than a request of their own, because the platform takes the\n * pairing code as a parameter of the status call: this endpoint records them and answers\n * 204. A wrong code is not reported here — the next poll asks for one again, which is how\n * the platform reports it.\n */\nexport interface WeChatScanVerifyRequest {\n taskId: string;\n verifyCode: string;\n}\n\n/**\n * POST …/messaging/<channel>/test-message — sent to the last known chat (409\n * `feishu_no_chat` / `telegram_no_chat` / `qq_no_chat` before one exists). On QQ this can\n * still fail with 502 afterwards: the platform accepts only replies to a message sent from\n * QQ minutes earlier, so a known chat does not mean a deliverable one.\n */\nexport interface MessagingTestMessageResponse {\n ok: true;\n}\n\n// ---------------------------------------------------------------------------\n// SSE server events (OmniMessage uses the default event, only server_event here)\n// ---------------------------------------------------------------------------\n\n/** Docs: /docs/server-api § \"Streaming (SSE)\". */\nexport type ServerEvent =\n /**\n * Approval request escalated to a human: every call under always-ask, plus rw/unknown-permission\n * calls under read-only (see runtime/approvals.ts); pending approvals are resent on reconnect.\n */\n | { type: \"approval_request\"; toolCall: OmniMessage<ToolCallPayload>; origin?: string[] }\n /** Session run status flip (for toggling the input area and list); `queued` = queued follow-up count (see TaskCreateRequest.queueIfBusy). */\n | {\n type: \"task_state\";\n state: SessionStatus;\n queued?: number;\n /** Steering messages queued but not yet delivered (absent = none): lets the composer's hint and its content survive reloads. */\n pendingSteering?: PendingSteeringInfo[];\n /**\n * Steering the run ended without delivering (absent = none) — an interrupt while a tool\n * was running is the ordinary way to produce one. Handed back rather than discarded: the\n * composer recalls each by the same handle and restores it into the draft, so the typed\n * message returns to the input box instead of being lost.\n */\n returnedSteering?: PendingSteeringInfo[];\n /** Queued follow-up tasks awaiting auto-start (absent = none): per-entry content + recall handle, alongside the `queued` count. */\n pendingFollowUps?: PendingFollowUpInfo[];\n /**\n * Live subagent children of this session's runtime (absent = none): the panel renders\n * child running marks from this structural liveness instead of parsing tool-output\n * text. Refreshed on every child run start/settle.\n */\n subagents?: SubagentRuntimeInfo[];\n }\n /** The model-generated title after the first turn has been persisted (for in-place list updates). */\n | { type: \"session_title\"; sessionId: string; title: string }\n /**\n * The user-channel counterpart of `task_state`: the same run-state flip, named by\n * `sessionId`, delivered on GET /api/events.\n *\n * `task_state` is session-scoped and deliberately carries no id, so it only ever reaches the\n * one conversation a tab has subscribed to — every OTHER row in that tab's Session list would\n * otherwise keep whatever status its last list fetch returned. This event exists so the list\n * can stay live without polling; the per-Session contract is unchanged.\n *\n * `lastActiveAt` and `hasTrace` are the row's own fields as they stand after the flip, both\n * written just before publishing (`markDriven` at run start sets has_trace and stamps\n * last_active_at; `touchLastActive` stamps again at run end). They are what let a list act on\n * the flip without refetching: the stamp separates \"this finished while I was looking\n * elsewhere\" from \"this finished before I last looked\", and `hasTrace` separates a Session\n * that has now run from one that never has — a first run would otherwise settle back into the\n * blank \"never ran\" row the client still believes in.\n *\n * Published only to the user channels of the Project's owner and members.\n */\n | {\n type: \"session_state\";\n sessionId: string;\n state: SessionStatus;\n lastActiveAt: string;\n hasTrace: boolean;\n }\n /**\n * A Session's background-task counts changed: a command promoted to the background, a\n * process that exited or was stopped, a background subagent starting or settling a round,\n * a released session. The counts are the row's `backgroundTasks` as they stand after the\n * change — zeros included, so a list can clear its mark without refetching. Published to\n * the user channels of the Project's owner and members, like `session_state`.\n */\n | { type: \"session_background\"; sessionId: string; processes: number; subagents: number }\n /** Last-Event-ID has been evicted from the buffer: the frontend should re-fetch the history endpoint before continuing to consume this connection. */\n | { type: \"resync_required\" }\n /**\n * The Project's model credentials changed (PUT /models): cached runtimes have been\n * invalidated server-side, so an auth-dead Session can continue — the frontend clears\n * its auth-dead composer state immediately. Published to every existing Session channel\n * of the Project; tabs without a live channel learn the same fact from the models\n * response's `updatedAt` on their next load.\n */\n | { type: \"credentials_updated\" }\n /** Placeholder handshake on the user channel (reserved for automated task notifications). */\n | { type: \"hello\" }\n /** The served web assets were hot-swapped by a platform upgrade: clients reload to pick them up. */\n | { type: \"web_updated\"; rev: string }\n /** New session registered (pushed over the parent session's channel for subagent sessions): frontend refreshes the list in place. */\n | {\n type: \"session_created\";\n projectId: string;\n agentId: string;\n sessionId: string;\n source: SessionSource;\n }\n | ScheduleServerEvent\n | GoalServerEvent\n | CompanyServerEvent;\n\n/** Goal-mode progress on the session channel (the chat page drives its goal banner from these). */\nexport type GoalServerEvent =\n /** A goal run began (published before the first round). */\n | { type: \"goal_started\"; sessionId: string; objective: string; budget: number }\n /** A round is starting; `used` is the runner's accounting up to this point. */\n | { type: \"goal_round\"; sessionId: string; round: number; used: number; budget: number }\n /** The goal reached a terminal state. */\n | {\n type: \"goal_finished\";\n sessionId: string;\n outcome: \"complete\" | \"blocked\" | \"budget_limited\" | \"aborted\";\n rounds: number;\n used: number;\n };\n\n/** Schedule notification (user-level event stream; firing and delivery are notified via /api/events). */\nexport type ScheduleServerEvent =\n /** Fired and sent (sessionId is the session that received the Prompt; a new session under new-Session mode). */\n | { type: \"schedule_fired\"; projectId: string; agentId: string; name: string; sessionId: string }\n /** Target Session is running; this firing is queued and will be sent once it's idle. */\n | {\n type: \"schedule_queued\";\n projectId: string;\n agentId: string;\n name: string;\n sessionId: string;\n };\n\n// ---------------------------------------------------------------------------\n// Trace browsing and performance analysis\n// ---------------------------------------------------------------------------\n\nexport interface TraceFileInfo {\n /** Trace file index (one file corresponds to one complete model context). */\n index: number;\n /** Date subdirectory it belongs to (yyyy-mm-dd). */\n date: string;\n sizeBytes: number;\n mtime: string;\n}\n\nexport interface SessionTracesResponse {\n files: TraceFileInfo[];\n}\n\n/** One tool's share of the context: its calls plus their results. Its *definition* is counted in `toolDefs`, not here. */\nexport interface ContextToolShare {\n name: string;\n tokens: number;\n}\n\n/**\n * One file's share of the context: its `read_file` / `edit_file` / `write_file` calls plus their\n * results, keyed by the file each call named.\n */\nexport interface ContextFileShare {\n /**\n * Workspace-relative when the file is inside the Session's Workspace; otherwise absolute, with\n * the home directory shortened to `~`. Spellings that resolve to the same file are one row.\n */\n path: string;\n tokens: number;\n /** How many calls of each file tool named the file in this context. */\n ops: { read: number; edit: number; write: number };\n}\n\n/**\n * What the Session's current model context is made of — the part derived from its messages.\n *\n * Every token figure is an **estimate** from a character heuristic, not a tokenizer: the\n * authoritative occupancy is the last `token_usage`'s `request.total`, which says how large the\n * context is but not what fills it. Consumers should present these as shares of that measured\n * occupancy rather than as counts of their own.\n *\n * The six parts partition the context and sum to `total`; `topTools` is a ranking inside\n * `toolRequests + toolResults` and can sum to less than those two (a result whose call was not\n * recorded in the same Trace shard has no tool to be attributed to). `topFiles` is the same\n * ranking narrowed to the three file tools and keyed by the file each call named.\n */\nexport interface SessionContextParts {\n systemPrompt: number;\n toolDefs: number;\n userMessages: number;\n assistantMessages: number;\n toolRequests: number;\n toolResults: number;\n /** Sum of the six parts. */\n total: number;\n /** Tools ranked by the context their traffic occupies, descending; at most five. */\n topTools: ContextToolShare[];\n /** Files ranked by the context their file-tool traffic occupies, descending; at most five. */\n topFiles: ContextFileShare[];\n /**\n * A completed compaction closed the context these figures describe, and the next one has not\n * been written yet: the composition is of what was compacted away, not of what the model now\n * carries. The same state in which the chat page's context ring shows `—`.\n */\n contextClosed: boolean;\n}\n\n/** `GET /api/sessions/:id/context`: the message-derived composition plus where compaction will fire. */\nexport interface SessionContextResponse extends SessionContextParts {\n /**\n * Occupancy (tokens) at which this Session's next Request triggers context compaction: the\n * Agent's configured `compaction.max_context_length`, capped by what the model's context window\n * leaves room for. Null when compaction is disabled, when the Agent's config could not be read,\n * or when the derived threshold is not below the window — nothing to mark inside the gauge.\n */\n compactionThreshold: number | null;\n}\n\nexport interface TraceEventsResponse {\n events: OmniMessage[];\n offset: number;\n limit: number;\n /** Total line count of the file (basis for pagination). */\n total: number;\n}\n\n/** Duration span of a single LLM Request (request_begin/request_end paired by proximity). */\nexport interface RequestSpan {\n beginTs: string;\n endTs?: string;\n durationMs?: number;\n status?: string;\n /** The Task it belongs to (same convention as modelSegments/toolSpans). */\n taskIndex: number;\n /** Compaction request (falls between compaction_begin and compaction_end): excluded from TPS, see TraceTaskStats. */\n compaction?: boolean;\n /**\n * Total human approval wait time within this Request. core does `await approve(tc)` inside\n * the streaming loop — if approval doesn't return, the next chunk isn't consumed and\n * `request_end` can't be emitted either, so the entire human wait falls inside the span\n * (see context-engine's runTurn). Tool **execution** is not included (`void executeOne`,\n * doesn't block the loop).\n */\n approvalWaitMs?: number;\n /** LLM generation duration = durationMs − approvalWaitMs (≥ 0): only this can be used as the TPS denominator, not durationMs. */\n activeMs?: number;\n}\n\n/**\n * Per-Task Token / duration figures (aggregated server-side over the **entire** Trace file,\n * aligned with the Chat page's task-stats).\n *\n * Provided separately instead of letting the frontend aggregate `requests` + events itself:\n * the frontend's events are paginated (only the first N), so self-aggregation would mismatch\n * a numerator covering only the first N against a denominator covering the whole file.\n */\nexport interface TraceTaskStats {\n taskIndex: number;\n /**\n * This turn is a **compaction turn** (compaction forms its own turn); the UI marks it with\n * a badge accordingly. It's treated the same as a user turn: it has Token /\n * cost / duration / TPS, and **counts normally toward global stats** — the global totals are\n * just the sum of the per-turn cards below, the two scopes match, so adding up the per-turn\n * numbers must equal the total.\n */\n compaction?: boolean;\n /**\n * Which kind of compaction turn it is, from the turn's `compaction_begin`. Additive beside\n * the flag rather than folded into it: `compaction` stays the sole gate on \"is this a\n * compaction turn\", so a client that only knows the boolean keeps working unchanged, and one\n * that reads this can name the turn for what it did — the two modes are different operations,\n * and only `summarize` actually compacts anything (`discard` drops the old context outright).\n * Absent on a turn analyzed before this field existed, or whose `compaction_begin` carried no\n * mode; treat an absent value as `summarize`, which is what the badge said before the split.\n */\n compactionMode?: CompactionMode;\n /**\n * This turn's message index range within the **entire file** (inclusive). A single\n * sequential scan on the server tells which turn each message belongs to; the frontend\n * attributes messages by this, **no longer guessing by timestamp** — the same millisecond\n * can pack \"previous turn's last reply + compaction start + compaction prompt + next turn's\n * request_begin\", which time boundaries can't separate, misattributing this turn's reply to\n * the next turn.\n */\n messageFrom: number;\n messageTo: number;\n /**\n * This turn's duration span: `startTs` = the moment of this turn's **first `request_begin`**\n * — duration only looks at LLM requests, not the timestamp of user text like the user\n * Prompt / compaction summary (`[context_summary]` is created during compaction but only\n * persisted on the next run; resuming the next day would inflate the first turn by a whole\n * day for no reason); `endTs` = the moment of the last non-session_meta message in the\n * range. For a degenerate turn with no Request at all (interrupted right after sending),\n * `startTs` is an empty string and duration counts as 0.\n */\n startTs: string;\n endTs: string;\n /**\n * Context usage at the end of this Task = the three-bucket Token snapshot of the last\n * **non-compaction** Request (same convention as the Chat page's `contextNow`). Note this\n * must not be the sum of this Task's Requests — each Request's input carries the full\n * history again, so summing double-counts the context, and a few rounds of tool calls\n * would blow past the context window. A pure-compaction Task (no non-compaction Request)\n * has no value here.\n */\n context?: { cacheRead: number; cacheWrite: number; output: number };\n /**\n * This turn's **cumulative** usage (the sum of the three buckets over every Request in this\n * Task), for Token stats and cost conversion. Two different figures from `context`: that one\n * is a snapshot (how much is occupied right now), this one is a ledger (how much this turn\n * spent in total). Includes compaction requests — compaction tokens are real money spent and\n * must be counted; consistent with the Chat page's tokensByBucket.\n */\n tokens: { cacheRead: number; cacheWrite: number; output: number };\n /**\n * This turn's cost in USD: each Request's three buckets at the Project's current rates for\n * the file's model, at the tier that Request's own timestamp fell in — the rule and the\n * price lookup the cost center applies to the usage row the same `token_usage` produced,\n * so this figure, the toolbar's and the cost center's agree on what a request cost. Present\n * on every turn of a priced file (a turn with no Request reads 0); absent when the model has\n * no pricing or the file's head names no provider, and then absent from the response's\n * total as well.\n */\n cost?: number;\n /**\n * Total LLM generation duration for this turn (the denominator for output TPS; human\n * approval wait already deducted). The numerator is simply `tokens.output`: since\n * compaction forms its own turn, each turn's output tokens are just its own Requests'\n * output — there's no second figure to reconcile.\n */\n llmMs: number;\n /**\n * Wall-clock time this turn spent executing tools: the **union** of its tool spans'\n * execution intervals (`approvalTs ?? callTs` to `outputTs`), so tools running in parallel\n * are counted once instead of summed. Two exclusions, both deliberate: the human approval\n * wait (`callTs` to `approvalTs`) is not tool work, and the argument-generation segment is\n * the model streaming arguments, already counted in `llmMs`. A span with no `outputTs` —\n * still running when the file ended, or interrupted — contributes nothing rather than being\n * extrapolated to now.\n *\n * This and `llmMs` may **overlap**: a tool started in the background keeps running while the\n * model decodes. They are two measured components of the turn's duration, not a partition of\n * it, and they need not add up to the turn's span (approval waits and harness overhead belong\n * to neither). Never derive one by subtracting the other from the duration.\n */\n toolMs: number;\n}\n\n/** Duration span of a single tool call (complete tool_call message → paired tool_call_output). */\nexport interface ToolCallSpan {\n toolCallId: string;\n name: string;\n startTs: string;\n endTs?: string;\n durationMs?: number;\n stopReason?: string;\n}\n\n/** Workspace file entry (Files tab). */\nexport interface WorkspaceFileEntry {\n name: string;\n kind: \"dir\" | \"file\";\n sizeBytes: number;\n mtime: string;\n}\n\nexport interface WorkspaceFilesResponse {\n /** Requested relative path (\"\" = Workspace root). */\n path: string;\n entries: WorkspaceFileEntry[];\n}\n\n/** Write one Workspace file whole (the Upload button, a drop, and the Files panel's editor). */\nexport interface FilesWriteRequest {\n /** The entire file, base64-encoded (≤14MB decoded). */\n dataBase64: string;\n /**\n * Write precondition: the version marker the caller read off this file's `ETag` on\n * `GET files/content`. The server compares it against the file's state immediately\n * before writing and answers 409 `file_changed` — having written nothing — when they\n * differ, which is what stops the editor's save from quietly dropping what the Agent\n * wrote during the turn. Omitted by a caller that read no version (an upload creates or\n * replaces unconditionally); that absence, not a sentinel value, is what says there was\n * no prior version to match.\n */\n ifVersion?: string;\n}\n\n/** Move or rename one Workspace file (the Files panel's context menu). */\nexport interface FilesMoveRequest {\n /** Source path, relative to the Workspace root. */\n from: string;\n /** Destination path, relative to the Workspace root. Its parent directory is created when missing. */\n to: string;\n /**\n * Move precondition, read exactly like {@link FilesWriteRequest.ifVersion}: the marker the\n * caller got from this file's `ETag` on `GET files/content`, which the file must still\n * carry. It differs on only one point — the marker guards the **source**. The destination\n * has none, because the caller never read it, which is why an occupied destination is\n * refused with 409 `target_exists` rather than overwritten.\n *\n * A directory `from` is a 400 whatever this field says: a directory carries no single\n * version marker, so the precondition that protects this operation cannot be expressed for\n * one, and silently moving a tree without that protection is worse than refusing to move it.\n */\n ifVersion?: string;\n}\n\n/**\n * One Workspace search match. `kind`, `sizeBytes` and `mtime` are named and typed exactly as\n * {@link WorkspaceFileEntry} names them: a hit is drawn by the same row renderer as a tree\n * entry, and it can only render identically if it carries the same fields.\n */\nexport interface WorkspaceSearchHit {\n /** Workspace-relative, \"/\"-separated, with no leading \"./\" (a tree entry's `name` is only its last segment). */\n path: string;\n kind: \"dir\" | \"file\";\n sizeBytes: number;\n mtime: string;\n}\n\nexport interface WorkspaceSearchResponse {\n /** Shallowest first, then directories before files, then by name — the order the breadth-first walk produced. */\n hits: WorkspaceSearchHit[];\n /**\n * A cap stopped the walk (200 hits, or 20000 directory entries visited), so this is a\n * partial list. Breadth-first is what makes that degrade well: the hits that survive\n * truncation are the shallowest ones, not the ones that happened to be enumerated first.\n */\n truncated: boolean;\n}\n\n/** Batch file existence check (message file cards only list files that actually exist). */\nexport interface FilesStatRequest {\n /** Paths relative to the Workspace root (≤100 items, each ≤512 characters). */\n paths: string[];\n}\n\nexport interface FilesStatResponse {\n /** Confirmed existing paths (regular files within bounds), preserving request order and deduplicated; out-of-bounds and resolution failures count as non-existent. */\n existing: string[];\n}\n\n/**\n * Model serial segments (autoregressive decoding): Trace records completion times, so each\n * segment's duration = its own time − the previous event's time (the request's first segment\n * is based on request_begin; user input is treated as sent instantaneously and takes no\n * segment).\n */\nexport interface TraceModelSegment {\n kind: \"thinking\" | \"text\" | \"tool_call\";\n startTs: string;\n endTs: string;\n /** Given when kind=tool_call. */\n toolCallId?: string;\n name?: string;\n /** The Task it belongs to (a single user turn can contain multiple Requests): the frontend groups by this, each Task on its own independent timeline. */\n taskIndex: number;\n}\n\n/**\n * Tool full lifecycle (parallel to model decoding): initiated (callTs) → approved\n * (approvalTs) → output (outputTs). Unclosed fields are unset (approval pending / executing /\n * file truncated).\n */\nexport interface TraceToolSpan {\n toolCallId: string;\n name: string;\n callTs: string;\n approvalTs?: string;\n decision?: string;\n outputTs?: string;\n stopReason?: string;\n /** The Task that initiated this tool (grouped with its tool_call segment): async output belongs to this Task even if it arrives after request_end. */\n taskIndex: number;\n}\n\n/**\n * Non-tool auxiliary phase on the timeline: rendered in its own lane under the \"other\"\n * legend category — deliberately not a tool span, since nothing was called. Currently the\n * first run's MCP connect + discovery (from the mcp_connect_begin/end event pair).\n */\nexport interface TraceOtherSpan {\n /** Unique bar key (e.g. `mcp-connect-<beginTs>`). */\n key: string;\n /** Lane label, e.g. \"mcp connect\". */\n name: string;\n startTs: string;\n endTs: string;\n /** Attached to the Task that follows the phase (same grouping convention as toolSpans). */\n taskIndex: number;\n /** True when the phase ended with failures (some servers unreachable) or was aborted. */\n failed?: boolean;\n}\n\nexport interface UsageTrendPointInTrace {\n ts: string;\n requestTotal: number;\n sessionTotal: number;\n}\n\nexport interface TraceAnalysisResponse {\n /**\n * Sum of all turns' durations (**including compaction turns**, same scope as `tasks` — the\n * global figure is just the sum of the per-turn figures below; gaps between turns where the\n * user is thinking or away are not counted). Computed server-side over the entire file: the\n * frontend's events are paginated, so self-aggregation would undercount.\n */\n elapsedMs: number;\n /**\n * The file's model-API time: the sum of the turns' `llmMs` (human approval wait deducted,\n * compaction requests included, so the scope matches `elapsedMs`).\n */\n apiMs: number;\n /**\n * The file's tool wall time: the sum of the turns' `toolMs` (parallel tools counted once\n * within a turn). Summed per turn rather than unioned across the file, so the global figure\n * stays the sum of the per-turn figures, exactly as `elapsedMs` is. May overlap `apiMs` —\n * see `TraceTaskStats.toolMs`.\n */\n toolMs: number;\n /**\n * The file's cost in USD: the sum of the turns' `cost` (compaction turns included, the\n * scope every total here shares). Absent exactly when the turns carry no `cost`.\n */\n cost?: number;\n requests: RequestSpan[];\n /** Token / duration aggregated per Task (used directly by the Trace page's context ring and per-turn TPS). */\n tasks: TraceTaskStats[];\n toolCalls: ToolCallSpan[];\n /** Execution timeline: model serial segments (LLM lane). */\n modelSegments: TraceModelSegment[];\n /** Execution timeline: each tool's approval/execution phases (independent lane, can overlap with model decoding). */\n toolSpans: TraceToolSpan[];\n /** Execution timeline: non-tool auxiliary phases (their own \"other\" lanes — currently the first run's MCP connect + discovery). */\n otherSpans: TraceOtherSpan[];\n /** Number of request_end events with status ∈ {timeout, malformed}. */\n reconnectCount: number;\n /** Number of compaction_begin events. */\n compactionCount: number;\n usageTrend: UsageTrendPointInTrace[];\n}\n\nexport interface AgentTraceFileRef {\n index: number;\n sizeBytes: number;\n}\n\nexport interface AgentTraceSessionGroup {\n sessionId: string;\n files: AgentTraceFileRef[];\n}\n\nexport interface AgentTraceDateGroup {\n date: string;\n sessions: AgentTraceSessionGroup[];\n}\n\n/** One Trace file in the session-centric listing (`date` carried per file: one Session's shards can span date directories). */\nexport interface AgentTraceSessionFile {\n index: number;\n date: string;\n sizeBytes: number;\n}\n\n/** One Session's Trace files merged across date directories (the paginated listing's unit). */\nexport interface AgentTraceSessionEntry {\n sessionId: string;\n /**\n * Display title, resolved only for the returned page: the sessions DB title when one\n * exists, else derived from the Session's first user prompt (bounded head-read of the\n * earliest shard); absent when neither yields one (the client falls back to its\n * default title — raw session ids are never rendered).\n */\n title?: string;\n /**\n * Sidebar category of this Session, from the same bounded classification the listing\n * filters and counts with: archived exactly from the DB row; origin from the shared\n * in-process registry / previously observed session_meta; a DB-untracked Session this\n * process has not yet head-read falls into `active` until a page surfaces it (its\n * head-read then registers the true origin for subsequent requests).\n */\n category: SessionCategory;\n /** Workspace path locked at creation (DB row or observed session_meta); \"\" when unknown — the client's merged temp-group fallback. */\n workspace: string;\n /** Sorted by index ascending (a higher index is newer). */\n files: AgentTraceSessionFile[];\n}\n\n/**\n * Agent-level Trace browsing structure. Without `limit` the response is the legacy full\n * drill-down (`dates`: Agent → date → Session → Trace file, reverse chronological) and the\n * paging fields are absent. With `offset`/`limit` the response is session-group-centric:\n * `sessions` carries the requested slice (newest first by sessionId desc — ids embed a\n * timestamp, so that is reverse chronological) with titles and classification,\n * `totalSessions` the session-group count (within `category` when one is given, so paging\n * and the count agree), `counts` / `workspaceCounts` the per-category totals over ALL of\n * the Agent's session groups (folder labels / workspace-mode group headers), and `dates`\n * stays empty (per-file stats are only taken for the returned page).\n */\nexport interface AgentTracesResponse {\n dates: AgentTraceDateGroup[];\n /** Present only when the request paginates: the requested slice of Session groups, newest first. */\n sessions?: AgentTraceSessionEntry[];\n /** Present only when the request paginates: session-group count of the paged (category-filtered) set. */\n totalSessions?: number;\n /** Present only when the request paginates: per-category totals over all of the Agent's session groups. */\n counts?: SessionCategoryCounts;\n /** Present only when the request paginates: `counts` broken down by Workspace path (\"\" = unknown). */\n workspaceCounts?: Record<string, SessionCategoryCounts>;\n}\n\nexport interface TraceImportRequest {\n /** Base64 of the Trace file content (JSON Lines; the first record must be `session_meta`). */\n dataBase64: string;\n}\n\nexport interface TraceImportResponse {\n /** Session id taken from the imported file's `session_meta`. */\n sessionId: string;\n /** Allocated file index: always 1 — an import creates a new Session (a duplicate session id is rejected with 409 `trace_session_exists`). */\n index: number;\n /** Date directory the file landed in (local yyyy-mm-dd from the first record's timestamp, matching the Trace Writer's convention). */\n date: string;\n}\n\n// ---------------------------------------------------------------------------\n// Usage and cost statistics\n// ---------------------------------------------------------------------------\n\nexport type UsageGroupBy = \"date\" | \"agent\" | \"model\" | \"session\";\n\nexport interface UsageBucket {\n total: number;\n requests: number;\n /** Cost converted using current pricing at query time (USD); a partial sum when uncosted Models are included, null if none has pricing. */\n cost: number | null;\n /** Whether any Model has no pricing (its usage isn't included in cost; counted once pricing is added later). */\n hasUncosted: boolean;\n}\n\nexport interface UsageGroupRow {\n /** Group key: date / agentId / modelId / sessionId. */\n key: string;\n /** Provider group when groupBy=model (rows are broken down by (provider, modelId); unset for other dimensions). */\n provider?: string;\n cacheRead: number;\n cacheWrite: number;\n output: number;\n total: number;\n requests: number;\n cost: number | null;\n hasUncosted: boolean;\n}\n\n/** Time-series precision for the usage series (`granularity` query parameter). `minute` requires the `fromTs`/`toTs` window bounds. */\nexport type UsageGranularity = \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\";\n\n/**\n * One bucket of the usage time series (for the cost center's time-series charts).\n * Buckets are zero-filled across the whole requested range, so consecutive points\n * are always adjacent in time. Bucket keys by granularity: minute\n * `yyyy-mm-ddThh:mm` and hour `yyyy-mm-ddThh:00` (server-local clock), day\n * `yyyy-mm-dd`, week the ISO week's Monday `yyyy-mm-dd`, month `yyyy-mm`.\n */\nexport interface UsageSeriesPoint {\n bucket: string;\n cacheRead: number;\n cacheWrite: number;\n output: number;\n total: number;\n /** Cost converted at query time (USD); null when no priced Model contributed. */\n cost: number | null;\n requests: number;\n /** Successful requests in the bucket. */\n completed: number;\n /** Success-rate denominator: all requests minus aborted (a user interruption is not a model failure). */\n denominator: number;\n}\n\n/**\n * One entity's per-bucket request and success counts, aligned index-for-index\n * with `series` (the requests-and-success-rate chart draws one such entity —\n * or stacks them all). `denominator` excludes aborted, same as elsewhere.\n */\nexport interface UsageEntitySeriesCounts {\n requests: number[];\n completed: number[];\n denominator: number[];\n}\n\n/** Per-Agent counts per bucket. */\nexport interface UsageAgentSeries extends UsageEntitySeriesCounts {\n agentId: string;\n}\n\n/** Per-Model counts per bucket (entity identity is the (provider, modelId) pair). */\nexport interface UsageModelSeries extends UsageEntitySeriesCounts {\n provider: string;\n modelId: string;\n}\n\n/**\n * Lifetime Token total for one Model, keyed by the (provider, modelId) pair. Deliberately\n * unfiltered — no date range, no Agent: it answers \"how much has this model been used\", a\n * question with no window attached, and the models page that shows it carries no filters of its\n * own to honour. Models never used are absent rather than zero.\n */\nexport interface UsageModelTotal {\n provider: string;\n modelId: string;\n /** The three buckets summed (cache read + cache write + output), matching the cost center's Token figure. */\n tokens: number;\n requests: number;\n}\n\n/** Response of `GET /usage/model-totals`. */\nexport interface UsageModelTotals {\n totals: UsageModelTotal[];\n}\n\n/**\n * The two categories an error record is filed under: `unexpected` is a 500 or an unforeseen\n * runtime exception, `expected` an HttpError / business 4xx. The panel separates them by\n * colour, and `GET /usage/errors` takes one of them as its `kind` filter.\n */\nexport type UsageErrorKind = \"unexpected\" | \"expected\";\n\n/** Occurrence count of an error for a given source · code (the \"most common\" metric in the stats center's error panel). */\nexport interface UsageErrorCount {\n source: string;\n code: string;\n kind: string;\n count: number;\n}\n\n/** A single error summary (one row in the stats center's error panel table). */\nexport interface UsageErrorItem {\n ts: string;\n source: string;\n code: string;\n kind: string;\n message: string;\n}\n\n/**\n * Server-side error capture stats: not affected by the model\n * filter (HTTP / process errors have no Model dimension), but affected by date and agent\n * filters. Errors with no Project attribution (login, process-level) are counted in every\n * Project's view. The stats center presents this as \"summary stats + detail table\" with no\n * chart, so it only has a total count, the most common error code, and the most recent N\n * items.\n */\nexport interface UsageErrors {\n /** Filtered row count — also what a clear of the same filter takes (see {@link UsageErrorsClearResponse}). */\n total: number;\n /** Count of unexpected ones (500 / runtime exceptions) among them — the part the frontend highlights. */\n unexpected: number;\n /** The most frequent source · code (null when there are no errors). */\n topCode: UsageErrorCount | null;\n /** Most recent N items (reverse chronological) — the first page; older ones come from `GET /usage/errors`. */\n recent: UsageErrorItem[];\n}\n\n/**\n * GET /api/projects/:projectId/usage/errors — one page of the error detail table, newest\n * first. The dashboard response above already carries the first page; this exists so\n * \"show me earlier ones\" does not have to refetch the whole aggregate. It takes the same\n * date/agent filter as the dashboard (`fromTs`/`toTs` narrow it to a trailing window, both\n * or neither), so a page never widens what the summary counted, plus an optional `kind`\n * ({@link UsageErrorKind}) narrowing to one of the two categories — which\n * is how the cost-center badge asks \"are there unexpected errors, and how new is the newest\"\n * with `limit=1` instead of pulling the whole dashboard aggregate.\n */\nexport interface UsageErrorsPage {\n items: UsageErrorItem[];\n /** Filtered row count, so the caller knows when it has reached the end. */\n total: number;\n}\n\n/**\n * DELETE /api/projects/:projectId/usage/errors — empties the error table for the filter the\n * panel is showing (its date range, the trailing window when one is on, and Agent), Project\n * owner only.\n *\n * Scoped to the filter rather than the Project's whole history, so a clear takes exactly the\n * rows on screen — for an admin, the unattributed rows an admin's panel shows included; a\n * member's panel never shows them and a member's clear never takes them.\n *\n * `from` and `to` are both required (400 otherwise), where the reads treat them as optional:\n * an absent bound is unbounded on that side, which is the whole history rather than a filter.\n */\nexport interface UsageErrorsClearResponse {\n /** How many rows were deleted, so the caller can say what went instead of guessing. */\n deleted: number;\n}\n\nexport interface UsageResponse {\n summary: {\n today: UsageBucket;\n last7d: UsageBucket;\n total: UsageBucket;\n };\n groupBy: UsageGroupBy;\n groups: UsageGroupRow[];\n /** Effective precision of `series` (the validated `granularity` query parameter; defaults to day). */\n granularity: UsageGranularity;\n /**\n * Usage time series over the requested from/to range (defaulting to the last 30\n * days), zero-filled at `granularity`; affected by agent/model filters. Carries\n * everything the time-series charts draw: Token buckets, cost, request count,\n * and per-bucket success counts.\n */\n series: UsageSeriesPoint[];\n /**\n * Per-Agent counts per bucket, aligned index-for-index with `series`, sorted\n * by total requests descending. Unaffected by the agent filter — the by-Agent\n * chart draws the whole breakdown — but affected by date/model filters.\n */\n byAgentSeries: UsageAgentSeries[];\n /**\n * Per-Model counts per bucket, aligned index-for-index with `series`, sorted\n * by total requests descending. Unaffected by the model filter — the by-Model\n * chart draws the whole breakdown — but affected by date/agent filters.\n */\n byModelSeries: UsageModelSeries[];\n /** Server-side error capture stats (affected by date/agent filters; unaffected by model filter). */\n errors: UsageErrors;\n /** List of Agent ids that have appeared in this Project (for the filter dropdown; unaffected by current filters). */\n agentIds: string[];\n /** List of Model paired references that have appeared in this Project (for the filter dropdown). */\n models: ModelRefDto[];\n}\n\n// ---------------------------------------------------------------------------\n// Schedule\n// ---------------------------------------------------------------------------\n\n/** Display-facing schedule status: the file's `enabled` only expresses intent; the rest is derived from runtime state. */\nexport type ScheduleStatus = \"active\" | \"disabled\" | \"expired\" | \"done\" | \"missed\" | \"invalid\";\n\nexport interface ScheduleItem {\n /** Filename (without .toml) is the identifier. */\n name: string;\n prompt: string;\n enabled: boolean;\n /** ISO 8601. */\n startAt: string;\n /** Raw fixed interval (e.g. `30m`); unset means a one-off task. */\n period?: string;\n endAt?: string;\n /** Bound target Session; defaults to creating a new Session each time. */\n sessionId?: string;\n workspace?: string;\n /** Model for new-Session mode (upstream id, always paired with provider); absent means the Project's default reference. */\n modelId?: string;\n /** Provider group for `modelId`; present exactly when `modelId` is — a model reference is always a pair. */\n provider?: string;\n status: ScheduleStatus;\n invalidReason?: string;\n /** Next scheduled fire time (ISO 8601); unset when done/missed/invalid/disabled. */\n nextFireAt?: string;\n /** Most recent actual fire time (ISO 8601). */\n lastFiredAt?: string;\n /** Queued, waiting for the target Session to become idle. */\n queued: boolean;\n creatorUserId?: string;\n}\n\nexport interface SchedulesResponse {\n schedules: ScheduleItem[];\n /** Files that failed to parse (skipped from scheduling and logged as errors). */\n invalidFiles: Array<{ name: string; error: string }>;\n}\n\nexport interface ScheduleUpsertRequest {\n prompt: string;\n enabled: boolean;\n startAt: string;\n period?: string;\n endAt?: string;\n sessionId?: string;\n workspace?: string;\n /** Model for new-Session mode (upstream id); always sent together with provider, omit both for the Project's default reference. */\n modelId?: string;\n /**\n * Provider group for `modelId`. Both fields are sent as a pair (400 otherwise); the\n * pair is checked against the Project config at save/reconciliation time.\n */\n provider?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Agent State version and snapshots\n// ---------------------------------------------------------------------------\n\nexport interface AgentImportRequest {\n /** Base64 of the snapshot package (tar.gz). */\n dataBase64: string;\n /** Explicit confirmation is required when the package version is equal to or lower than the current version, otherwise 409. */\n confirm?: boolean;\n}\n\nexport interface AgentImportResponse {\n /** Agent State version number after import (taken from the package's value). */\n version: number;\n}\n\n// ---------------------------------------------------------------------------\n// Benchmark scoring (display), manual creation and deletion\n// ---------------------------------------------------------------------------\n\n/** Raw result of a single run (a scoreboard per-case runs[] entry). */\nexport interface BenchmarkRunScore {\n score: number;\n /** Run cost, or null when unavailable. */\n cost: number | null;\n durationMs: number;\n /** Id of the Session under test in this run (links to Trace). */\n sessionId: string;\n}\n\nexport interface BenchmarkCaseScore {\n case: string;\n /** Model-written average of this Case's Run scores, on the fixed 0..100 scale. */\n score: number;\n /** Model-written average of known Run costs; null when every Run cost is unknown. */\n cost: number | null;\n /** Model-written average of Run durations, rounded to an integer. */\n durationMs: number;\n /** Raw results per Run. */\n runs: BenchmarkRunScore[];\n}\n\nexport interface BenchmarkEvaluation {\n /** Evaluation timestamp (ISO 8601). */\n time: string;\n /**\n * Agent under test in this round (the `agent_id` field), part of the record's label; `null`\n * when the record carries none, as a Benchmark evaluates whichever Agents it is pointed at.\n */\n agentId: string | null;\n /** Evaluation summary title (a one-line conclusion; shown separately from the body summary; required when generating, tolerated as unset when displaying). */\n summaryTitle?: string;\n /** Evaluation summary body: how the score was derived, what optimizations were made to the Agent this round (required when generating, tolerated as unset when displaying). */\n summary?: string;\n /** Model actually used for this evaluation round (upstream id, paired with provider; the chart series is split by model). */\n modelId: string;\n /** Provider group for `modelId`. */\n provider: string;\n /** Thinking level read from the unchanged Target Agent configuration. */\n thinkingLevel: string;\n /** Agent State version number under test. */\n version: number;\n /** Model-written average of Case scores, on the fixed 0..100 scale. */\n score: number;\n /** Model-written average of known Case costs; null when every Case cost is unknown. */\n cost: number | null;\n /** Model-written average of Case durations, rounded to an integer. */\n durationMs: number;\n cases: BenchmarkCaseScore[];\n}\n\n/**\n * Whether the Skill that builds a Benchmark is done with it, and how it ended; see\n * `BenchmarkSummary.status`.\n */\nexport type BenchmarkStatus = \"draft\" | \"published\" | \"failed\";\n\nexport interface BenchmarkSummary {\n /** Directory name is the identifier (semantic naming, e.g. swe-bench-v1). */\n id: string;\n /** Title from benchmark_config.toml; falls back to the directory name if unset. */\n title: string;\n description?: string;\n /** Number of runs per case (the `runs` field in benchmark_config.toml, ≥1; defaults to 1). */\n runs?: number;\n /**\n * `draft` while the Skill that builds the Benchmark is still writing its cases and\n * calibrating their difficulty — the Web App masks such a Benchmark; `published` once the\n * Benchmark is frozen and its Formal Baseline recorded; `failed` when calibration ended\n * without a Pilot result that could be frozen, which leaves the Benchmark unusable — the Web\n * App masks it too and says it has to be deleted and created again. benchmark_config.toml is\n * read literally: only `draft` is a draft and only `failed` is a failure, so a missing field,\n * or any other value, reads as published.\n */\n status: BenchmarkStatus;\n /** Case count (number of case subfolders). */\n caseCount: number;\n /** Time-ordered evaluation records (the evaluations[] in scoreboard.yaml). */\n evaluations: BenchmarkEvaluation[];\n /**\n * Agents this Benchmark has evaluated: the distinct non-null `agentId`s of `evaluations`, in\n * first-seen order. Empty while nothing has been evaluated — a Benchmark names no Agent of its\n * own.\n */\n agentIds: string[];\n}\n\nexport interface BenchmarksResponse {\n benchmarks: BenchmarkSummary[];\n}\n\nexport type CaseMaterial = \"statement\" | \"rubric\";\n\n/** Public Benchmark Case metadata. Rubric and Gold content are never included. */\nexport interface BenchmarkCaseSummary {\n id: string;\n /** First Markdown heading with an optional leading \"Case N:\" removed; falls back to id. */\n title: string;\n}\n\nexport interface BenchmarkCasesResponse {\n cases: BenchmarkCaseSummary[];\n}\n\n/**\n * POST /api/projects/:p/benchmarks (owner only): create a Benchmark by hand. The\n * server writes the on-disk layout the evaluation Skills read — `benchmark_config.toml`, a\n * `scoreboard.yaml` holding `evaluations: []`, and one `<case id>/` per case with\n * `statement/README.md` and `rubric/README.md`. 409 `benchmark_exists` when the directory is\n * already there; nothing is merged into an existing Benchmark.\n */\nexport interface BenchmarkCreateRequest {\n /** Directory name, which is the identifier: letters, digits, `_` and `-` only. */\n id: string;\n title: string;\n description?: string;\n /** Runs per case for the optimization loop (integer ≥ 1; default 1). */\n runs?: number;\n /** At least one case; ids must be unique within the request. */\n cases: BenchmarkCreateCase[];\n}\n\nexport interface BenchmarkCreateCase {\n /** Case directory name: `CASE-` followed by letters, digits, `_` and `-` (for example `CASE-001-excel-task`). */\n id: string;\n /** Written as the statement README's first heading, which the case list reads back as the case title. */\n title: string;\n /** Statement body (Markdown), written after that heading; the Target Agent sees only this side. */\n statement: string;\n /** Scoring rubric (Markdown, items totalling 100 points), written verbatim as `rubric/README.md`. */\n rubric: string;\n}\n\nexport interface BenchmarkCreateResponse {\n benchmark: BenchmarkSummary;\n}\n\n// ---------------------------------------------------------------------------\n// Plugin library, and an Agent's installed skills and hooks\n// ---------------------------------------------------------------------------\n\nexport interface SkillMetadataItem {\n /** Skill directory name (the identity key for install / uninstall / Prompt addressing). */\n name: string;\n description: string;\n /** Short description for frontend display (frontmatter short_description, optional; falls back to description if missing). */\n shortDescription?: string;\n shortDescriptionZh?: string;\n /**\n * Raw icon.svg text from the installed skill directory: the plugin's icon for a library\n * install (written beside SKILL.md at install time), a custom one for a user-authored skill.\n * Only installed lists carry it — the library listing's skills share their plugin's icon,\n * which the plugin item carries once. Absent, the frontend draws the book glyph.\n */\n icon?: string;\n /** Version (`YYYY.MM.DD.N`, frontmatter version; a copy installed before that spelling still carries `YYYY-MM-DD.N`); an empty string when the frontmatter carries none or a malformed one. */\n version: string;\n}\n\n/** One installed hook package (`agent_state/hooks/<name>/`): its manifest, without the scripts. */\nexport interface HookItem {\n /** Hook package name — the plugin that shipped it (the identity uninstall addresses it by). */\n name: string;\n description: string;\n descriptionZh?: string;\n /** Version (`YYYY.MM.DD.N`; a copy installed before that spelling still carries `YYYY-MM-DD.N`); an empty string when the manifest carries none. */\n version: string;\n /** The hook points the package answers at, e.g. `[\"stop\"]`. */\n events: string[];\n /** The plugin's raw icon.svg, written beside the manifest at install time; absent when the plugin ships none (the frontend draws the hook glyph). */\n icon?: string;\n}\n\n/** One library plugin as the listing describes it: the manifest fields plus what it ships (skill bodies and scripts are never sent). */\nexport interface PluginItem {\n name: string;\n description: string;\n descriptionZh?: string;\n shortDescription?: string;\n shortDescriptionZh?: string;\n /** `YYYY.MM.DD.N`. */\n version: string;\n /** The plugin's skills (metadata only). */\n skills: SkillMetadataItem[];\n /** The hook points the plugin's hook package answers at (`[]` without one). */\n hooks: string[];\n /** The plugin's raw icon.svg (beside plugin.json — every built-in plugin ships one), the icon of everything it ships; the frontend draws the puzzle-piece plugin glyph without it. */\n icon?: string;\n}\n\nexport interface PluginGroupItem {\n id: string;\n title: string;\n /** Chinese category title (optional; the UI displays it per language). */\n titleZh?: string;\n plugins: PluginItem[];\n}\n\n/** GET /api/plugins: the library by category (any logged-in user). */\nexport interface PluginLibraryResponse {\n groups: PluginGroupItem[];\n}\n\n/**\n * GET /api/plugins/:plugin/files: everything a library plugin ships, for the detail view's file\n * browser — each skill's installable SKILL.md and auxiliary files under `skills/<name>/`, the\n * hook package's scripts under `hooks/` — keyed by path relative to the plugin directory. The\n * manifest and the icon are not among them: the listing already carries both.\n */\nexport interface PluginFilesResponse {\n files: Record<string, string>;\n}\n\n/**\n * POST /api/projects/:p/agents/:a/plugins: install library plugins by name — each one's skills\n * and hook package; already-installed ones are overwritten with library content (i.e. updated).\n * Every name must be in the library (404 `unknown_plugin`, nothing written). 201 returns the\n * refreshed installed lists.\n */\nexport interface PluginInstallRequest {\n names: string[];\n}\n\nexport interface AgentPluginsInstallResponse {\n skills: SkillMetadataItem[];\n hooks: HookItem[];\n}\n\n/** GET /api/projects/:p/agents/:a/skills: Skills installed on this Agent. */\nexport interface AgentSkillsResponse {\n skills: SkillMetadataItem[];\n}\n\n/** GET /api/projects/:p/agents/:a/hooks: hook packages installed on this Agent; DELETE …/hooks/:name uninstalls one (204). */\nexport interface AgentHooksResponse {\n hooks: HookItem[];\n}\n\n/**\n * POST /api/projects/:p/agents/:a/hooks/archive: install one hook package from an uploaded zip.\n * Layout: hooks.json and its scripts at the zip root, or exactly one top-level directory\n * containing them (the directory name is then the package name). 201 returns the refreshed\n * installed list (AgentHooksResponse); an already-installed name without `overwrite` is 409\n * `hook_exists`. GET …/hooks/:name/archive is the matching export: the installed directory as\n * a zip attachment, which round-trips through this POST.\n */\nexport interface HookArchiveInstallRequest {\n /** Base64-encoded zip archive (decoded size capped at 14MB, like the skill archive). */\n dataBase64: string;\n /** Replace an installed package of the same name instead of answering 409. */\n overwrite?: boolean;\n}\n\n/**\n * POST /api/projects/:p/agents/:a/skills/archive: install one Skill from an uploaded zip.\n * Layout: SKILL.md at the zip root, or exactly one top-level directory containing SKILL.md\n * (the directory name is then the Skill name). 201 returns the refreshed installed list\n * (AgentSkillsResponse); an already-installed name without `overwrite` is 409 `skill_exists`.\n */\nexport interface SkillArchiveInstallRequest {\n /** Base64-encoded zip archive (decoded size capped at 14MB, same as the Agent snapshot import). */\n dataBase64: string;\n /** Replace an already-installed Skill of the same name (deletes its directory first). */\n overwrite?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Version and self-update\n// ---------------------------------------------------------------------------\n\n/**\n * GET /api/version: the running build's identity plus this root's pushed harness, verbatim\n * from `versionReport()` — the same record `penguin version --json` prints, so the two\n * cannot drift apart. Field meanings live on {@link VersionReport} and {@link HarnessInfo};\n * the ones the web reads are `version` and `buildDate` (the stamped release date behind the\n * sidebar's \"last updated\", needing no network, and null for a source build or a release\n * predating the stamping — v0.1.2 and earlier — where the UI shows the version alone).\n */\nexport type VersionResponse = VersionReport;\n\n/**\n * GET /api/version/update-check: newest published release vs the running version.\n * Always HTTP 200 (fail-soft): a lookup failure sets `error` and leaves `latestVersion`\n * null rather than failing the request; results are cached server-side.\n */\nexport interface UpdateCheckResponse {\n currentVersion: string;\n /** Same as VersionResponse.buildDate: the running version's release date, stamped at build time. */\n buildDate: string | null;\n /** Newest published release (normalized, no leading `v`); null when the lookup failed or checks are disabled. */\n latestVersion: string | null;\n updateAvailable: boolean;\n /** Release page of the newest release (for the \"release notes\" link). */\n releaseUrl: string | null;\n /** Publish timestamp of the newest release (ISO 8601). */\n publishedAt: string | null;\n /** When this result was produced (ISO 8601) — a cached result keeps its original timestamp. */\n checkedAt: string;\n /** Present (true) when update checks are turned off via PENGUIN_UPDATE_CHECK=off; no network call was made. */\n disabled?: true;\n /** Why the lookup failed: unreachable network / GitHub rate limit / unusable response. */\n error?: \"network\" | \"rate_limited\" | \"bad_response\";\n}\n\n// ---------------------------------------------------------------------------\n// Desktop client update (desktop mode only)\n// ---------------------------------------------------------------------------\n\n/**\n * The desktop shell's updater snapshot, pushed to the embedded server over the\n * utilityProcess message channel and served at GET /api/desktop/update. `state` is the\n * discriminator; the optional fields belong to the states named on them.\n *\n * The shell never downloads on its own: a check ends in `available`, and the download\n * starts only on the page's (or the native dialog's) say-so — the `download` command. A\n * `downloaded` build stays the reported state until it is installed: a later periodic\n * check (or its failure) must not hide the actionable \"restart to install\" step.\n */\nexport interface DesktopUpdateStatus {\n /** Installed shell version (Electron app.getVersion()). */\n appVersion: string;\n /**\n * Bumped by the shell on every updater event it folds, whether or not the visible\n * state changed. A row-initiated check settles when the seq has moved past its\n * at-click value and the state is no longer `checking` — snapshot equality can't\n * carry that signal (a check that ends where it started is byte-identical).\n */\n seq?: number;\n state:\n | \"idle\"\n | \"checking\"\n | \"up-to-date\"\n | \"available\"\n | \"downloading\"\n | \"downloaded\"\n | \"error\"\n | \"unsupported\";\n /** The newer release: offered (`available`), being fetched (`downloading`) or ready to install (`downloaded`). */\n version?: string;\n /** Download progress 0–100 (`downloading`). */\n percent?: number;\n /** Updater failure text (`error`). */\n message?: string;\n /** 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). */\n reason?: \"dev\" | \"linux-not-appimage\";\n}\n\n/**\n * GET /api/desktop/update (desktop-shell sessions only): the latest shell snapshot.\n * `status` is null until the shell's first push lands (a beat after server start).\n */\nexport interface DesktopUpdateStatusResponse {\n status: DesktopUpdateStatus | null;\n}\n\n/** Shell → server push over the utilityProcess message channel. */\nexport interface DesktopUpdaterStatusMessage {\n type: \"desktop-updater-status\";\n status: DesktopUpdateStatus;\n}\n\n/**\n * Server → shell command over the utilityProcess message channel (relayed from\n * POST /api/desktop/update/check|download|install): look for a release, fetch the one\n * offered, or restart into the one downloaded.\n */\nexport interface DesktopUpdaterCommandMessage {\n type: \"desktop-updater-command\";\n action: \"check\" | \"download\" | \"install\";\n}\n\n// Desktop tray icon (desktop mode only)\n//\n// The shell keeps an icon in the system tray for as long as the app runs, and Settings ›\n// Appearance is where it is turned off and on. The switch rides the same utilityProcess\n// message channel as the client updater above: the shell pushes what it currently shows,\n// the page reads it at GET /api/desktop/tray and writes through PUT, which is relayed\n// back. The window stays a plain browser — no renderer IPC bridge.\n//\n// The page reports its UI language over the same route, so the tray menu reads in the\n// language the window does. The shell cannot see that preference itself: it lives in the\n// browser's localStorage, on the other side of a boundary this design keeps one-way.\n\n/** The two languages the Web App has; the shell's tray menu follows whichever is in use. */\nexport type DesktopTrayLocale = \"zh\" | \"en\";\n\n/** What the shell is currently doing about its tray icon. */\nexport interface DesktopTrayStatus {\n /** Whether an icon is shown in the system tray while the app runs. */\n showTrayIcon: boolean;\n /**\n * The language the tray menu is drawn in. Until a page reports one the shell uses the\n * device language, so this can differ from the Web App's until the first report lands.\n */\n locale: DesktopTrayLocale;\n}\n\n/**\n * What one PUT asks the shell to change. Every field is optional and a request must carry at\n * least one: the switch and the language reach this route from different parts of the page.\n */\nexport interface DesktopTrayPatch {\n showTrayIcon?: boolean;\n locale?: DesktopTrayLocale;\n}\n\n/**\n * GET / PUT /api/desktop/tray (desktop-shell sessions only): the tray preference.\n * `status` is null until the shell's first push lands (a beat after server start); a\n * client that finds null reads it as on, which is the shell's own default.\n */\nexport interface DesktopTrayStatusResponse {\n status: DesktopTrayStatus | null;\n}\n\n/** Shell → server push over the utilityProcess message channel. */\nexport interface DesktopTrayStatusMessage {\n type: \"desktop-tray-status\";\n status: DesktopTrayStatus;\n}\n\n/**\n * Server → shell command over the utilityProcess message channel (relayed from PUT\n * /api/desktop/tray). A patch, not a snapshot: the switch and the language are written by\n * different parts of the page at different moments, and neither should have to restate the\n * other's value to change its own.\n */\nexport interface DesktopTrayCommandMessage {\n type: \"desktop-tray-command\";\n showTrayIcon?: boolean;\n locale?: DesktopTrayLocale;\n}\n\n/**\n * The outcome of one self-update run (`penguin update --yes` on the server host), carried\n * by {@link UpdateJobStatus.result}. `unsupported` covers both a server not launched via\n * the CLI and the CLI's own refusals (source checkout, unrecognized install layout, Windows).\n */\nexport interface UpdateRunResponse {\n status: \"updated\" | \"failed\" | \"unsupported\";\n /** Set when the server cannot run the CLI at all (started without `penguin server|web`). */\n reason?: \"not_launched_via_cli\";\n /** Tail of the update command's combined stdout+stderr (capped; empty when nothing ran). */\n output: string;\n /** True when the install changed (or was already current): restart the service to run the new version. */\n needsRestart: boolean;\n}\n\n/**\n * Where a running self-update is: resolving the release and fetching the installer,\n * downloading the bundle (the one phase with a percentage), or verifying and installing it.\n */\nexport type UpdateJobPhase = \"resolving\" | \"downloading\" | \"installing\";\n\n/**\n * GET / POST /api/version/update (admin only): the self-update job. POST starts a run when\n * none is in flight — a finished run may be started again, which is how a failed one is\n * retried — and answers with the status exactly as GET does; the page polls GET while\n * `state` is `running`. One job per process: two admins clicking at once share the one run,\n * and the finished status stays readable until the next start.\n */\nexport interface UpdateJobStatus {\n state: \"idle\" | \"running\" | \"done\";\n /** The release the run targets — the update check's newest version when the run started; null when none was known. */\n targetVersion: string | null;\n /** Running only. */\n phase?: UpdateJobPhase;\n /** Running, `downloading` only: 0–100 read off the installer's progress bar; null until its first tick. */\n percent?: number | null;\n /** Tail of the update command's combined stdout+stderr so far (capped; empty when nothing ran). */\n output: string;\n /** Done only. */\n result?: UpdateRunResponse;\n startedAt?: string;\n finishedAt?: string;\n}\n\n/**\n * POST /api/version/restart (admin only): asks the process to exit with the supervisor's\n * restart code after a graceful shutdown, so `penguin server|web` relaunches it on the\n * installed release. `restarting: false` when nothing supervises this process — it was\n * started some other way than through the CLI, or it is a dev run — and the page shows the\n * manual restart hint instead.\n */\nexport interface RestartResponse {\n restarting: boolean;\n reason?: \"no_supervisor\";\n}\n\n/** One `Host` entry of the server's `~/.ssh/config`, as the Machines page lists it. */\nexport interface MachineInfo {\n /** `ssh:<alias>` — the id the install route is asked for. */\n id: string;\n /**\n * The alias exactly as written in the config. The list is the config text and nothing\n * else — no `ssh -G`, no processes, no network — so a config declaring hundreds of hosts\n * costs one file read; an alias is resolved only when it is actually installed to.\n */\n alias: string;\n /**\n * The last install THIS server carried out there FOR THIS PROJECT, remembered in web.db so\n * it survives a restart, a hot push, and installing on some other machine. Null when this\n * Project has never installed there — a host another Project did is `elsewhere` below.\n *\n * A record of what was done, not a survey of the far side: a machine wiped by hand still\n * reads as installed until the next install probes it and corrects the record. Asking the\n * remote instead would cost an ssh round trip per host at page load, which is the price\n * the config-text list exists to avoid.\n */\n installed: { version: string; at: string } | null;\n /**\n * Installed by this server, but not this Project's machine — another Project's, or nobody's\n * since it was released — and so not a host nobody has touched either. Absent in every\n * other case, including when it IS this Project's (where `installed` carries the same record).\n *\n * Reported rather than folded into `installed` because the two lead to different actions:\n * one is a machine to use, the other is a machine to adopt, which costs a row and no ssh.\n * Reported rather than hidden because a row that silently looked uninstalled would send\n * someone to spend a 30 MB transfer re-doing what is already done.\n */\n elsewhere?: { version: string; at: string };\n /**\n * The machine's OWN id — 16 base64url characters minted by the server that runs there,\n * stable across renames, re-aliasing and reinstalls. Null until a server has started on\n * that machine, since nothing has minted one yet.\n *\n * This is what anything stored should point at; `id` above is an ADDRESS (`ssh:<alias>`),\n * and `alias` is what people read. Two aliases for one host share a `machineId`, and an\n * alias repointed at a different host answers a different one — an id never changes for a\n * machine, so a change of id is a change of machine.\n */\n machineId: string | null;\n /** The host this server itself runs on. Always present, always installed, never a target. */\n local: boolean;\n /**\n * The connection this server holds to it — the one ssh session everything to the machine\n * rides (machines/transport/ssh-session.ts): a fact about a process on THIS side, which\n * outlives the far server. Present means `/server/<id>/api/…` has somewhere to go; whether\n * a server ANSWERS over there is `status`'s word, from the last probe — and the two must not\n * be read for each other: taking the connection for the machine's liveness is the mistake\n * behind the connect loop (#561). Always null for `local`, which needs no connection.\n */\n connection: { pid: number } | null;\n /**\n * The machine's API as last seen by this server's proxy — stamped by traffic passing\n * through, never by a probe of its own. `answeredAt` when the last forwarded request got\n * an HTTP answer (any status: a server that refuses is still answering); `failedAt` and\n * the transport's own words when the connection had nowhere to deliver. Null until a first\n * request flows, and only as fresh as the last one — no traffic, no measurement, which is\n * honest: nothing burns ssh for a page nobody is looking at. Always null for `local`;\n * this server answering the request that fetched this list is that measurement.\n */\n api: { answeredAt: string } | { failedAt: string; detail: string } | null;\n /**\n * What the last probe found over there, or null when none has been taken. Never filled in\n * at list time: a probe costs an ssh round trip per machine, so the list reports the last\n * answer and the page asks for a fresh one when it wants one — on a widening schedule,\n * since each probe is an ssh round trip while the list is only the config's text.\n */\n status: MachineServerStatus | null;\n}\n\n/**\n * One machine's server state. There is deliberately no separate \"ssh\" status: ssh is the\n * transport, so a machine it cannot reach reads as `unreachable` with OpenSSH's own\n * diagnostic in `detail` rather than as two statuses a reader has to combine.\n */\nexport interface MachineServerStatus {\n state: \"running\" | \"stopped\" | \"unreachable\";\n /** ISO timestamp of the probe this answer came from. */\n checkedAt: string;\n /** The port it is serving on (`running`). */\n port?: number;\n /** Why the machine could not be reached (`unreachable`) — ssh's own words. */\n detail?: string;\n}\n\n/**\n * The running or last job on a machine — an install, or a connect — polled by GET\n * /api/machines while one runs. One at a time. `log` carries the far side's own words where\n * there are any: ssh's diagnostics and the remote installer's output say more about a\n * refused key or an unusable Node than a paraphrase would.\n */\nexport interface MachineJob {\n kind: \"install\" | \"connect\" | \"restart\";\n machineId: string;\n alias: string;\n running: boolean;\n log: string[];\n result:\n | null\n | { ok: true; installed: \"installed\" | \"already-installed\"; version: string | null }\n | { ok: true; connected: true }\n | {\n ok: false;\n step: string;\n message: string;\n /**\n * The failure has a next step this side can take, and it needs saying yes to:\n * installing the PROGRAM over there and restarting it. Set when a hot update could\n * not be handed over — the machine's store holds no CLI this server can talk to, and\n * installing is what replicates one. Offered rather than done, because it restarts a\n * server this Project does not own alone.\n */\n canReplaceProgram?: true;\n };\n}\n\n/** GET /api/machines, and the 202 body of POST /api/machines/:machineId/install. */\nexport interface MachinesResponse {\n machines: MachineInfo[];\n /**\n * The version an install would leave on the remote — the base release, plus a `+hmr.<sha>`\n * suffix when this server carries a pushed version to replicate. Null for a development\n * checkout, which stands on no release the remote could download.\n */\n imageVersion: string | null;\n job: MachineJob | null;\n}\n\n// ---------------------------------------------------------------------------\n// Company mode: organizations (files are the truth; every DTO here is a projection)\n// ---------------------------------------------------------------------------\n\n/**\n * Organization status: `paused` stops every automatic trigger; humans can still talk to any\n * desk. These two values are the whole lifecycle — no route deletes an organization, so a\n * paused one keeps its conversations, employees, desks and tickets.\n */\nexport type OrgStatus = \"active\" | \"paused\";\n/** Approval mode for desk and ticket sessions; unattended runs never get always-ask. */\nexport type OrgApprovalMode = \"allow-all\" | \"read-only\" | \"deny-all\";\n/** The five kanban columns, each a directory under `tickets/<yyyy-mm>/`. */\nexport type OrgTicketStatus = \"proposed\" | \"in_progress\" | \"review\" | \"done\" | \"rejected\";\nexport type OrgTicketPriority = \"P0\" | \"P1\" | \"P2\";\n/** Live employee state: running when the desk or any ticket session has a Task in progress; paused when budget-paused. */\nexport type OrgEmployeeState = \"running\" | \"idle\" | \"paused\";\n/**\n * The trigger kinds an `[org_trigger]` block carries. `ticket_notice` is read-only: a ticket\n * change starts no run of its own, so nothing writes that kind any more, and it stays in the\n * union because Traces recorded while it did still carry it.\n */\nexport type OrgTriggerKind = \"init\" | \"event\" | \"mention\" | \"ticket_notice\" | \"ticket_work\";\n/** The ticket changes an employee is told about, listed in the body of its next calendar sweep. */\nexport type OrgTicketChange = \"assigned\" | \"blocked\" | \"blocker_closed\" | \"done\" | \"rejected\";\n/** What the last evaluation of a calendar event did. */\nexport type OrgCalendarOutcome = \"fired\" | \"queued\" | \"paused\" | \"missed\" | \"error\";\n/**\n * The organization's working language: the language its handbook, its CEO's initialization\n * run, every employee brief and every desk and ticket run are written in. Detected from the\n * mission at creation (CJK text → `zh`, anything else → `en`) unless the request names one.\n */\nexport type OrgLanguage = \"zh\" | \"en\";\n\n/** The organization's settings as `org_config.toml` records them. */\nexport interface OrganizationSettings {\n name: string;\n mission: string;\n status: OrgStatus;\n /** IANA timezone: budget periods (natural months) and chat day files follow it. */\n timezone: string;\n approvalMode: OrgApprovalMode;\n /** Chat @-chain limit: a message whose hop reaches it records its mentions without triggering anyone. */\n mentionChainLimit: number;\n budgetWarnRatio: number;\n budgetPauseRatio: number;\n createdBy: string;\n /** The shared workspace root when it is not the organization's own `workspace/` (absolute path). */\n workspace?: string;\n /** The model desks and ticket sessions run on when the employee names none; absent = the Project default. */\n model?: { provider: string; modelId: string };\n /** The working language (`language` in `org_config.toml`); absent on an organization written before the field existed, which reads as `en`. */\n language?: OrgLanguage;\n}\n\n/** Period spend against the CEO's budget (= the whole organization). */\nexport interface OrgSpendSummary {\n /** `yyyy-mm` in the organization's timezone. */\n period: string;\n cost: number;\n budget?: number;\n /** cost / budget; absent without a budget. */\n ratio?: number;\n}\n\nexport interface OrganizationSummary {\n projectId: string;\n orgId: string;\n name: string;\n mission: string;\n status: OrgStatus;\n employeeCount: number;\n runningCount: number;\n pausedCount: number;\n /** proposed + in_progress + review. */\n openTickets: number;\n blockedTickets: number;\n createdBy: string;\n spend: OrgSpendSummary;\n /** Present when `org_config.toml` / `org_chart.yaml` fail validation: the organization is listed but every automatic trigger is held until it is fixed. */\n invalid?: string;\n}\n\nexport interface OrganizationsResponse {\n organizations: OrganizationSummary[];\n}\n\nexport interface OrgEmployeeItem {\n agentId: string;\n /** Agent display name (system_config.yaml); falls back to the id. */\n name: string;\n title: string;\n /** null for the CEO (the root). */\n reportsTo: string | null;\n duties?: string;\n /** As written in the chart: a sub-directory of the shared workspace (`.` = all of it) or an absolute path. */\n workspace: string;\n /** Where that resolves to; absent when the directory does not exist (the entry is then invalid). */\n resolvedWorkspace?: string;\n /** Monthly budget in USD for this employee plus all subordinates; absent = unbounded. */\n budget?: number;\n model?: { provider: string; modelId: string };\n state: OrgEmployeeState;\n desk?: { sessionId: string; workspace: string; openedAt: string };\n /** Period spend: own sessions, and cumulative (own + every subordinate). */\n spend: { own: number; cumulative: number; ratio?: number };\n /** Why the entry cannot be triggered (missing Agent, missing workspace directory). */\n invalid?: string;\n}\n\nexport interface OrgChartResponse {\n ceoAgentId: string;\n employees: OrgEmployeeItem[];\n}\n\nexport interface OrgCalendarItem {\n agentId: string;\n name: string;\n title?: string;\n prompt: string;\n enabled: boolean;\n startAt: string;\n period?: string;\n endAt?: string;\n status: ScheduleStatus;\n invalidReason?: string;\n nextFireAt?: string;\n lastFiredAt?: string;\n /** What the most recent evaluation did (absent until the event has been evaluated once). */\n lastOutcome?: OrgCalendarOutcome;\n /** The organization or this employee is paused, so due slots are skipped, not fired. */\n paused: boolean;\n}\n\nexport interface OrgCalendarResponse {\n events: OrgCalendarItem[];\n invalidFiles: Array<{ agentId: string; name: string; error: string }>;\n}\n\n/**\n * One line of a ticket's operation history, kept in the file's frontmatter apart from the\n * progress prose: what was done, by whom (`agent:<id>` / `user:<id>` — an employee is recognised\n * from the Agent id its command subprocesses carry, a person otherwise), and when.\n */\nexport type OrgTicketHistoryAction =\n | \"created\"\n | \"assigned\"\n | \"moved\"\n | \"blocked\"\n | \"unblocked\"\n | \"progress\"\n | \"session_started\"\n | \"session_attached\"\n | \"edited\";\n\nexport interface OrgTicketHistoryEntry {\n at: string;\n by: string;\n action: OrgTicketHistoryAction;\n /** The action's detail: the column moved to, the new owner, the block reason, the session id. */\n note?: string;\n}\n\n/**\n * The ticket id's slug: lowercase letters in hyphen-joined words, no digits (the date prefix\n * already carries the numbers), chosen for meaning — derived from an ASCII title, proposed by\n * the Project's model for a title in another language, or passed explicitly.\n */\nexport const TICKET_SLUG_PATTERN = /^[a-z]+(?:-[a-z]+)*$/;\n\nexport interface OrgTicketItem {\n ticketId: string;\n title: string;\n status: OrgTicketStatus;\n /** The ONE responsible principal (`agent:<id>` / `user:<id>`); who filed it is the history's `created` entry. */\n owner: string;\n parent?: string;\n notify: string[];\n priority: OrgTicketPriority;\n due?: string;\n /** Non-empty = blocked; the ticket stays in its column. */\n blocked?: string;\n blockedBy?: string;\n /** Contributing session ids, in the order they were attached. */\n sessions: string[];\n /** Any contributing session has a Task in progress. */\n running: boolean;\n /** Period cost of the contributing sessions (a session attached to n tickets counts 1/n here). */\n cost: number;\n /** Header/column disagreement or a duplicate id: shown with a danger mark, left where it is. */\n invalid?: string;\n}\n\nexport interface OrgTicketSessionItem {\n sessionId: string;\n agentId: string;\n title?: string;\n status: SessionStatus;\n lastActiveAt?: string;\n}\n\nexport interface OrgTicketDetail extends OrgTicketItem {\n goal: string;\n acceptanceCriteria: string;\n /** `## Progress` as plain sentences; who wrote one and when is the matching history entry. */\n progress: string[];\n result: string;\n /** The operation history from the frontmatter, oldest first. */\n history: OrgTicketHistoryEntry[];\n /** The whole file, for the Markdown view and for clients that prefer to edit it as text. */\n body: string;\n children: string[];\n /** Own cost plus every descendant's along `Parent`. */\n rolledUpCost: number;\n sessionItems: OrgTicketSessionItem[];\n}\n\nexport interface OrgTicketsResponse {\n columns: Record<OrgTicketStatus, OrgTicketItem[]>;\n /** Files that failed to parse (skipped; also recorded as errors). */\n invalidFiles: Array<{ path: string; error: string }>;\n}\n\n/**\n * What a `system` line records, structured: the kind of event and its parameters, so a client\n * renders the sentence in the reader's language and with the principals' display names instead\n * of showing the English `text` verbatim. `text` stays the English sentence (the CLI, older\n * clients and the file itself read it); `notice` is the same fact for a client that can do better.\n */\nexport type OrgChannelNoticeKind =\n | \"employee_joined\"\n | \"employee_left\"\n | \"channel_created\"\n | \"channel_archived\"\n | \"channel_unarchived\"\n | \"channel_joined\"\n | \"channel_invited\"\n | \"channel_left\"\n | \"channel_removed\"\n | \"budget_warned\"\n | \"budget_paused\"\n /**\n * Legacy, read-only: ticket changes no longer write into a channel — the board is read from\n * the board and the overview's inbox. These three kinds stay so the lines already in an\n * organization's message files keep rendering; nothing writes them any more.\n */\n | \"ticket_blocked\"\n | \"ticket_done\"\n | \"ticket_rejected\";\n\n/**\n * The parameters each kind carries, all strings: principals as `agent:<id>` / `user:<id>`\n * (`agent`, `principal`, `by`, `reportsTo`), a ticket as `ticket` + `title`, a budget event as\n * `agent`, `period`, `percent`, `cost`, `budget`.\n */\nexport interface OrgChannelNotice {\n kind: OrgChannelNoticeKind;\n params: Record<string, string>;\n}\n\nexport interface OrgChannelMessage {\n id: string;\n /** ISO 8601 UTC. */\n time: string;\n /** `agent:<id>` / `user:<id>` / `system`. */\n sender: string;\n hop: number;\n text: string;\n /** Principals mentioned, `all` included. */\n mentions: string[];\n refs?: { ticket?: string; session?: string; replyTo?: string };\n /** Present on `system` lines the server wrote with a structured notice; absent on lines from before the field existed. */\n notice?: OrgChannelNotice;\n}\n\n/**\n * One channel as the API reports it. The all-hands channel (`default_channel`,\n * `everyone: true`) exists for as long as the organization does and every employee and\n * Project member is in it; every other channel carries the membership its members edit.\n */\nexport interface OrgChannelItem {\n channelId: string;\n /** As stored; the UI renders the all-hands channel's label itself. */\n name: string;\n /** \"\" when unset. */\n purpose: string;\n /** True only for `default_channel`: membership is implicit. */\n everyone: boolean;\n /** An archived channel is read-only and folded away. */\n archived: boolean;\n /** `user:<id>` / `agent:<id>` / `system`. */\n createdBy: string;\n /** ISO 8601 UTC. */\n createdAt: string;\n /** Implicit membership counted for the all-hands channel. */\n memberCount: number;\n /** Whether the caller (person or employee) is a member. */\n isMember: boolean;\n /** People only; 0 for an employee caller. */\n unread: number;\n /** People only; 0 for an employee caller. */\n mentionsMe: number;\n lastMessageAt: string | null;\n}\n\nexport interface OrgChannelMember {\n /** `agent:<id>` or `user:<id>`. */\n principal: string;\n name: string;\n kind: \"agent\" | \"user\";\n}\n\nexport interface OrgChannelDetail extends OrgChannelItem {\n /** The all-hands channel resolves to every employee plus every Project member. */\n members: OrgChannelMember[];\n}\n\nexport interface OrgChannelsResponse {\n /** `default_channel` first, then by name. */\n channels: OrgChannelItem[];\n}\n\nexport interface OrgChannelCreateRequest {\n channelId: string;\n name?: string;\n purpose?: string;\n}\n\nexport interface OrgChannelPatchRequest {\n name?: string;\n purpose?: string;\n archived?: boolean;\n}\n\nexport interface OrgChannelMemberRequest {\n /** `agent:<id>` (an employee) or `user:<id>` (a Project member). */\n principal: string;\n}\n\nexport interface OrgChannelMessagesResponse {\n /** The channel served. */\n channelId: string;\n /** The day file served (`yyyy-mm-dd` in the organization's timezone). */\n date: string;\n /** The days this channel has a file for, newest first, for paging back. */\n days: string[];\n messages: OrgChannelMessage[];\n /** Messages of this channel after the caller's read cursor in it, across the recent days. */\n unread: number;\n /** Of those, the ones that mention the caller (or all). */\n mentionsMe: number;\n lastReadId?: string;\n}\n\nexport interface OrgBudgetAlert {\n agentId: string;\n period: string;\n warnedAt?: string;\n pausedAt?: string;\n}\n\nexport interface OrgFinanceEmployee {\n agentId: string;\n name: string;\n title: string;\n reportsTo: string | null;\n own: number;\n cumulative: number;\n budget?: number;\n ratio?: number;\n warned: boolean;\n paused: boolean;\n}\n\nexport interface OrgFinanceTicket {\n ticketId: string;\n title: string;\n status: OrgTicketStatus;\n parent?: string;\n cost: number;\n rolledUp: number;\n}\n\nexport interface OrgFinanceResponse {\n period: string;\n currency: \"USD\";\n employees: OrgFinanceEmployee[];\n tickets: OrgFinanceTicket[];\n /** Daily cost of the organization's sessions over the period. */\n daily: Array<{ date: string; cost: number }>;\n alerts: OrgBudgetAlert[];\n total: number;\n /** Some usage ran on a model without pricing: tokens were counted, cost is a lower bound. */\n unpriced: boolean;\n}\n\nexport interface OrgDeskItem {\n agentId: string;\n name: string;\n sessionId: string;\n title?: string;\n status: SessionStatus;\n workspace: string;\n lastActiveAt?: string;\n}\n\nexport interface OrgSessionsResponse {\n desks: OrgDeskItem[];\n tickets: Array<{\n ticketId: string;\n title: string;\n status: OrgTicketStatus;\n sessions: OrgTicketSessionItem[];\n }>;\n}\n\nexport interface OrgDeskResponse {\n agentId: string;\n sessionId: string;\n workspace: string;\n openedAt: string;\n /** True when this call created the desk session. */\n created: boolean;\n}\n\nexport interface OrganizationDetail extends OrganizationSummary {\n settings: OrganizationSettings;\n board: Record<OrgTicketStatus, number>;\n /** Today's calendar events (organization timezone) with their outcomes. */\n today: OrgCalendarItem[];\n pending: {\n /** Unread messages mentioning the caller (or all). */\n mentions: number;\n reviewTickets: OrgTicketItem[];\n blockedByMe: OrgTicketItem[];\n };\n /** The last messages of the all-hands channel. */\n recentMessages: OrgChannelMessage[];\n alerts: OrgBudgetAlert[];\n /** What the overview's inbox lists; absent only from a server older than the field. */\n inbox?: OrgInbox;\n /** The CEO's desk session once opened (creation opens it). */\n ceoDeskSessionId?: string;\n}\n\n/**\n * The overview's inbox: the three things a person is waited on or told about — messages\n * that name them (or `@all`) in the all-hands channel, the tickets that are blocked (all of\n * them, whoever they wait on), and the tickets closed as done this period. Newest first in\n * each list; each capped at a page.\n */\nexport interface OrgInbox {\n mentions: OrgChannelMessage[];\n blockedTickets: OrgTicketItem[];\n doneTickets: Array<OrgTicketItem & { closedAt?: string }>;\n}\n\nexport interface OrganizationCreateRequest {\n /** Semantic id, unique within the Project; also the directory name. */\n orgId: string;\n name?: string;\n mission: string;\n timezone?: string;\n /** An existing absolute directory to use as the shared workspace; default = the organization's own `workspace/`. */\n workspace?: string;\n /** The model for desks and ticket sessions (a configured pair); default = the Project default. */\n model?: { provider: string; modelId: string };\n /**\n * The CEO's monthly budget in USD, written as the `budget` of its `org_chart.yaml` entry.\n * Budgets are compared on the cumulative line, so the CEO's is the whole company's.\n * Omitted = 100; 0 is a real (zero) budget, not \"unbounded\" — only clearing the field\n * later (`PATCH …/employees/:agentId` with `budget: null`) leaves the CEO unbounded.\n */\n ceoBudget?: number;\n /** The working language; omitted = detected from the mission. */\n language?: OrgLanguage;\n}\n\nexport interface OrganizationPatchRequest {\n name?: string;\n mission?: string;\n status?: OrgStatus;\n approvalMode?: OrgApprovalMode;\n timezone?: string;\n mentionChainLimit?: number;\n budgetWarnRatio?: number;\n budgetPauseRatio?: number;\n /** null returns to the organization's own `workspace/`. */\n workspace?: string | null;\n /** null returns to the Project default. */\n model?: { provider: string; modelId: string } | null;\n language?: OrgLanguage;\n}\n\n/**\n * A semantic id proposed for a display name — the organization and channel dialogs let the\n * user name the thing first and derive the id from that name. The server asks the Project's\n * default model for a short English snake_case id (a Chinese name has no mechanical\n * transliteration), falling back to an ASCII slug of the name when the model is unavailable,\n * and to a dated placeholder when neither can name it. The request never fails for a name it\n * cannot translate: a dialog that asked for an id always gets one back.\n */\nexport interface SemanticIdSuggestRequest {\n /** The display name typed so far (or the mission, when nothing else names the thing). */\n name: string;\n /** What the id is for: decides the prompt's examples and the fallback's prefix. */\n kind: \"org\" | \"channel\";\n /** Ids already in use in the target scope; the proposal avoids them. */\n taken?: string[];\n}\n\n/**\n * Why a proposal fell all the way through to a placeholder — what the client tells the user to\n * explain the id it was just handed. `no_default_model`: the Project has no default model to\n * ask. `model_failed`: it was asked and the request failed (no credential, a rejection, a\n * timeout). `unusable_answer`: it answered twice and neither answer yielded an id.\n * `no_ascii`: no model was consulted at all and the name carries no ASCII to transliterate.\n */\nexport type SemanticIdSuggestReason =\n \"no_default_model\" | \"model_failed\" | \"unusable_answer\" | \"no_ascii\";\n\nexport interface SemanticIdSuggestResponse {\n /** A valid semantic id (`^[a-z][a-z0-9_]{1,63}$`), not in `taken`. */\n id: string;\n /** Who produced it: the model, the ASCII fallback, or the dated placeholder that names nothing. */\n source: \"model\" | \"fallback\" | \"placeholder\";\n /** Present only with `source: \"placeholder\"`: why the two real paths produced nothing. */\n reason?: SemanticIdSuggestReason;\n}\n\nexport interface OrgHireRequest {\n /** Employ an existing Agent … */\n agentId?: string;\n /** … or create one (the two are exclusive). Plugins default to agent-company + agent-development. */\n newAgent?: { agentId: string; name?: string; description?: string; plugins?: string[] };\n title: string;\n reportsTo: string;\n workspace?: string;\n budget?: number;\n duties?: string;\n model?: { provider: string; modelId: string };\n}\n\nexport interface OrgEmployeePatchRequest {\n title?: string;\n reportsTo?: string;\n workspace?: string;\n /** null clears the budget. */\n budget?: number | null;\n duties?: string;\n /** null clears the model (back to the Project default). */\n model?: { provider: string; modelId: string } | null;\n}\n\nexport interface OrgCalendarUpsertRequest {\n /** POST only: the employee the event belongs to. */\n agentId?: string;\n /** POST only: the file name. */\n name?: string;\n title?: string;\n prompt: string;\n enabled: boolean;\n startAt: string;\n period?: string;\n endAt?: string;\n}\n\n/**\n * What a calendar write answers: the stored event, plus advisory `warnings` — one line each —\n * about the rota: another employee's recurring event on the same start minute, or the same\n * employee already holding a recurring event (desks that fire together compete for the same\n * budget minute and the same tickets). The write succeeds regardless; the CLI prints the\n * lines so the scheduling employee can stagger.\n */\nexport interface OrgCalendarWriteResponse extends OrgCalendarItem {\n warnings?: string[];\n}\n\nexport interface OrgTicketCreateRequest {\n title: string;\n /** Overrides the slug derived from the title; lowercase English words joined by hyphens. */\n slug?: string;\n goal?: string;\n acceptanceCriteria?: string;\n /** The whole Markdown body instead of goal + acceptanceCriteria (the frontmatter is still generated). */\n body?: string;\n /**\n * The responsible principal: an employee's `agent:<id>` (or bare Agent id) or a member's\n * `user:<id>`. Default = the caller — the session's employee inside a desk or ticket\n * session, else the token's or cookie's user.\n */\n owner?: string;\n parent?: string;\n notify?: string[];\n priority?: OrgTicketPriority;\n due?: string;\n}\n\nexport interface OrgTicketUpdateRequest {\n title?: string;\n /** The new responsible principal; never null — a ticket always has an owner. */\n owner?: string;\n parent?: string | null;\n notify?: string[];\n priority?: OrgTicketPriority;\n due?: string | null;\n goal?: string;\n acceptanceCriteria?: string;\n result?: string;\n}\n\nexport interface OrgTicketMoveRequest {\n status: OrgTicketStatus;\n /** Required when moving into rejected; recorded under Result. */\n reason?: string;\n}\n\nexport interface OrgTicketBlockRequest {\n reason: string;\n /** A ticket id or a principal. */\n by?: string;\n}\n\nexport interface OrgTicketProgressRequest {\n text: string;\n /**\n * The calling session (CLI: PENGUIN_SESSION_ID); the session is booked as a contributing\n * session and the history entry is attributed to its employee. Honoured only for a request\n * carrying the local API token — the control environment's credential; a signed-in user's\n * write is attributed to the user.\n */\n sessionId?: string;\n /**\n * The calling employee's Agent id (CLI: PENGUIN_AGENT_ID from the control environment), the\n * identity a write is recorded under; it wins over the session's employee, is honoured only\n * with the local API token, like sessionId, and is ignored — the write falls back to the\n * session's employee, then to the person — when it names no employee.\n */\n agentId?: string;\n}\n\nexport interface OrgTicketStartRequest {\n /** The employee the ticket session runs as (CLI: PENGUIN_AGENT_ID); defaults to the ticket owner. */\n agentId?: string;\n message?: string;\n /** Another directory inside the shared workspace; defaults to the employee's desk workspace. */\n workspace?: string;\n}\n\nexport interface OrgTicketStartResponse {\n sessionId: string;\n}\n\nexport interface OrgTicketAttachRequest {\n sessionId: string;\n}\n\nexport interface OrgChannelMessageSendRequest {\n text: string;\n refs?: { ticket?: string; session?: string; replyTo?: string };\n /**\n * The calling session (CLI: PENGUIN_SESSION_ID): the message is sent as its Agent and\n * inherits its hop. Honoured only for a request carrying the local API token — the control\n * environment's credential; a signed-in user's message is sent as the user, at hop 0.\n */\n sessionId?: string;\n}\n\nexport interface OrgChannelReadRequest {\n /** Mark everything up to this message id as read. */\n upTo: string;\n}\n\n/** The handbook index (`handbook/README.md`), the file every work run reads first. */\nexport interface OrgHandbookResponse {\n content: string;\n}\n\n/** One file of the organization handbook (`handbook/`, the company's knowledge base); `path` is relative to that directory. */\nexport interface OrgHandbookFile {\n path: string;\n size: number;\n updatedAt: string;\n}\n\nexport interface OrgHandbookFilesResponse {\n /** The index first, then the other documents by path. */\n files: OrgHandbookFile[];\n}\n\nexport interface OrgHandbookFileResponse {\n path: string;\n content: string;\n}\n\nexport interface OrgHandbookFileWriteRequest {\n content: string;\n}\n\n/** Company-mode notifications on the user-level event stream (best effort; the query routes carry the durable state). */\nexport type CompanyServerEvent =\n /** A work run (desk session) or ticket session was started by the organization scheduler or a ticket start. */\n | {\n type: \"org_run\";\n projectId: string;\n orgId: string;\n agentId: string;\n sessionId: string;\n kind: OrgTriggerKind;\n }\n /** A new channel message (mentions included, so the client can tell whether it is addressed). */\n | {\n type: \"org_channel\";\n projectId: string;\n orgId: string;\n channelId: string;\n message: OrgChannelMessage;\n }\n /** A ticket's status, owner, blocked state or contributing sessions changed. */\n | { type: \"org_ticket\"; projectId: string; orgId: string; ticketId: string; change: string }\n /** Budget warning, pause or resume for an employee. */\n | {\n type: \"org_budget\";\n projectId: string;\n orgId: string;\n agentId: string;\n state: \"warned\" | \"paused\" | \"resumed\";\n ratio: number;\n };\n\n// ---------------------------------------------------------------------------\n// Web contributions (GET /api/contributions)\n// ---------------------------------------------------------------------------\n\n/** How the web app renders a contributed surface: a name from its own registry, or an iframe. */\nexport type RendererRef = { builtin: string } | { iframe: { src: string; namespace: string } };\n\n/** One contribution to a web slot: its id, the contributing module, and the slot's data. */\nexport interface WebContribution {\n id: string;\n from: string;\n [key: string]: unknown;\n}\n\nexport interface ContributionsResponse {\n pages: WebContribution[];\n agentTabs: WebContribution[];\n sessionTabs: WebContribution[];\n}\n"],"mappings":";AAw+HO,IAAM,sBAAsB;","names":[]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// ../../node_modules/.pnpm/@prismshadow+penguin-hmr@file+packages+hmr_supports-color@10.2.2_ws@8.21.0/node_modules/@prismshadow/penguin-hmr/dist/chunk-HC5WPFTZ.js
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import fsp from "fs/promises";
|
|
4
|
+
import path from "path";
|
|
5
|
+
var MATERIALIZED = ".materialized";
|
|
6
|
+
function str(value) {
|
|
7
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
8
|
+
}
|
|
9
|
+
async function readHarnessInfo(root) {
|
|
10
|
+
const manifest = await readManifest(root);
|
|
11
|
+
if (manifest === null) return null;
|
|
12
|
+
const bundles = {
|
|
13
|
+
platform: str(manifest.platform?.bundle),
|
|
14
|
+
cli: str(manifest.cli?.bundle),
|
|
15
|
+
web: str(manifest.web?.manifest)
|
|
16
|
+
};
|
|
17
|
+
if (bundles.platform === null && bundles.cli === null && bundles.web === null) return null;
|
|
18
|
+
const repo = str(manifest.source?.repo);
|
|
19
|
+
const revision = str(manifest.source?.revision);
|
|
20
|
+
return {
|
|
21
|
+
// Both halves or neither: half a provenance names nothing.
|
|
22
|
+
source: repo !== null && revision !== null ? { repo, revision } : null,
|
|
23
|
+
pushedAt: str(manifest.pushedAt),
|
|
24
|
+
bundles
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
async function readManifestFile(root) {
|
|
28
|
+
const file = path.join(root, "hmr", "harness.json");
|
|
29
|
+
let raw;
|
|
30
|
+
try {
|
|
31
|
+
raw = await fsp.readFile(file, "utf8");
|
|
32
|
+
} catch (err) {
|
|
33
|
+
if (err.code === "ENOENT") return { kind: "none" };
|
|
34
|
+
return { kind: "broken", reason: `${file} could not be read: ${msg(err)}` };
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
return { kind: "manifest", manifest: JSON.parse(raw) };
|
|
38
|
+
} catch (err) {
|
|
39
|
+
return { kind: "broken", reason: `${file} is not readable JSON: ${msg(err)}` };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function msg(err) {
|
|
43
|
+
return err instanceof Error ? err.message : String(err);
|
|
44
|
+
}
|
|
45
|
+
async function readManifest(root) {
|
|
46
|
+
const read = await readManifestFile(root);
|
|
47
|
+
return read.kind === "manifest" ? read.manifest : null;
|
|
48
|
+
}
|
|
49
|
+
async function readPushedCli(root) {
|
|
50
|
+
const read = await readManifestFile(root);
|
|
51
|
+
if (read.kind === "none") return { kind: "none" };
|
|
52
|
+
if (read.kind === "broken") return { kind: "broken", reason: read.reason };
|
|
53
|
+
if (read.manifest.cli === void 0) return { kind: "none" };
|
|
54
|
+
const bundle = read.manifest.cli.bundle;
|
|
55
|
+
if (typeof bundle !== "string" || bundle.length === 0) {
|
|
56
|
+
return { kind: "broken", reason: "harness.json has a `cli` entry with no bundle path" };
|
|
57
|
+
}
|
|
58
|
+
const hmrDir = path.join(root, "hmr");
|
|
59
|
+
const abs = path.resolve(hmrDir, bundle);
|
|
60
|
+
if (abs !== hmrDir && !abs.startsWith(hmrDir + path.sep)) {
|
|
61
|
+
return {
|
|
62
|
+
kind: "broken",
|
|
63
|
+
reason: `harness.json points \`cli.bundle\` outside ${hmrDir}: ${bundle}`
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (!fs.existsSync(abs)) {
|
|
67
|
+
return { kind: "broken", reason: `the committed CLI bundle is missing from the store: ${abs}` };
|
|
68
|
+
}
|
|
69
|
+
return { kind: "bundle", file: abs };
|
|
70
|
+
}
|
|
71
|
+
async function resolveCliBundlePath(root) {
|
|
72
|
+
const cli = await readPushedCli(root);
|
|
73
|
+
return cli.kind === "bundle" ? cli.file : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export {
|
|
77
|
+
MATERIALIZED,
|
|
78
|
+
readHarnessInfo,
|
|
79
|
+
readManifest,
|
|
80
|
+
readPushedCli,
|
|
81
|
+
resolveCliBundlePath
|
|
82
|
+
};
|
|
83
|
+
//# sourceMappingURL=chunk-LPPVGHYD.js.map
|