Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(core,server,web): 用户级全局密钥——可整段 JSON 导入,也能分配给某个 Agent

lmlihenga278262943ec
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index d1ec9ec4..257bd0bd 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -82,9 +82,15 @@ import {
toolsDir,
} from "./paths.js";
-/** project_id / agent_id / skill_name only allow letters, digits, underscore `_`, and hyphen `-` (prevents path traversal). */
+/**
+ * project_id / agent_id / skill_name / user_id only allow letters, digits, underscore `_`, and
+ * hyphen `-` (prevents path traversal). `user_id` is here because a user-level vault names the
+ * account's own directory under `<root>/users/` (see state/user-vault.ts): the ids are minted
+ * by the server (`^[a-z][a-z0-9_]{1,31}$`) and this is the belt-and-braces check before any
+ * path is built from one.
+ */
const ID_PATTERN = /^[A-Za-z0-9_-]+$/;
-export type IdKind = "project_id" | "agent_id" | "skill_name";
+export type IdKind = "project_id" | "agent_id" | "skill_name" | "user_id";
export function isValidId(id: string): boolean {
return ID_PATTERN.test(id);
diff --git a/packages/core/src/state/index.ts b/packages/core/src/state/index.ts
index 54c281a1..1ccacf9d 100644
--- a/packages/core/src/state/index.ts
+++ b/packages/core/src/state/index.ts
@@ -17,5 +17,6 @@ export * from "./project-config.js";
export * from "./agent-state.js";
export * from "./plugin-store.js";
export * from "./agent-vault.js";
+export * from "./user-vault.js";
export * from "./memory.js";
export * from "./example-benchmark.js";
diff --git a/packages/core/src/state/paths.ts b/packages/core/src/state/paths.ts
index c6f58a7f..db949f0c 100644
--- a/packages/core/src/state/paths.ts
+++ b/packages/core/src/state/paths.ts
@@ -150,6 +150,17 @@ export function agentVaultPath(root: string, projectId: string, agentId: string)
return path.join(agentStateDir(root, projectId, agentId), ".vault.toml");
}
+/**
+ * `<root>/users/<userId>/.vault.toml`, the user-level vault (see state/user-vault.ts): the
+ * secrets one USER owns, a peer of the Project directories rather than something inside one —
+ * the same credential is usually wanted in several Projects, and it must outlive any of them.
+ * Hidden and 0600 like the Agent-level `.vault.toml` (same trade-offs, one scope up); the
+ * `users/` directory itself does not exist until the first entry is written.
+ */
+export function userVaultPath(root: string, userId: string): string {
+ return path.join(root, "users", userId, ".vault.toml");
+}
+
/** `<agentStateDir>/tools`, reserved for user-defined Tool config. */
export function toolsDir(root: string, projectId: string, agentId: string): string {
return path.join(agentStateDir(root, projectId, agentId), "tools");
diff --git a/packages/core/src/state/user-vault.ts b/packages/core/src/state/user-vault.ts
new file mode 100644
index 00000000..31f279c0
--- /dev/null
+++ b/packages/core/src/state/user-vault.ts
@@ -0,0 +1,72 @@
+/**
+ * User-level environment-variable vault (`<root>/users/<user_id>/.vault.toml`).
+ *
+ * The Agent-level vault's shape (state/agent-vault.ts: third-party credentials, key names
+ * following shell variable rules, values capped so a child process can still be spawned), one
+ * scope up: the secrets one USER owns, shared by every Project they can see, because the same
+ * gateway key is usually wanted in several of them. Stored beside the Project directories
+ * rather than inside one, so nothing here is owned by a Project or deleted with it.
+ *
+ * Nothing injects this file into a Session. A user-level entry only reaches an Agent by being
+ * copied into that Agent's own vault (the "assign" step the API offers), which keeps the
+ * runtime's single injection path — the Agent vault — unchanged: no reader of this file exists
+ * outside the API layer.
+ *
+ * Carries the same trade-offs as a credential: plaintext on disk, masked at the API layer,
+ * written 0600 and hidden (a hidden file blocks `ls`, not reads). A missing file is an empty
+ * table; once emptied, the file is removed rather than left as a stray empty .vault.toml.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
+import { atomicWriteFile } from "../internal/atomic-write.js";
+import { userVaultPath } from "./paths.js";
+import { assertValidId } from "./agent-state.js";
+import { assertValidVaultKey, isValidVaultKey } from "./agent-vault.js";
+
+/**
+ * Reads the user vault: returns an empty table if the file doesn't exist.
+ * A hand-edited file is filtered by the same rule as the write side — only string values with
+ * shell-legal key names are read (see loadAgentVault for why an invalid key is ignored rather
+ * than surfaced).
+ */
+export async function loadUserVault(root: string, userId: string): Promise<Record<string, string>> {
+ assertValidId("user_id", userId);
+ let raw: string;
+ try {
+ raw = await fs.readFile(userVaultPath(root, userId), "utf8");
+ } catch {
+ return {};
+ }
+ const parsed: unknown = parseToml(raw) ?? {};
+ const vault: Record<string, string> = {};
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
+ for (const [k, v] of Object.entries(parsed)) {
+ if (typeof v === "string" && isValidVaultKey(k)) vault[k] = v;
+ }
+ }
+ return vault;
+}
+
+/**
+ * Writes the full table to the user vault: validates all key names first; an empty table
+ * deletes the file (idempotent if it doesn't exist). The `users/<id>/` directory is created
+ * automatically if it doesn't exist, and is left behind when the table empties (removing it
+ * would be a second, unrelated deletion).
+ */
+export async function saveUserVault(
+ root: string,
+ userId: string,
+ vault: Record<string, string>,
+): Promise<void> {
+ assertValidId("user_id", userId);
+ for (const key of Object.keys(vault)) assertValidVaultKey(key);
+ const file = userVaultPath(root, userId);
+ if (Object.keys(vault).length === 0) {
+ await fs.rm(file, { force: true });
+ return;
+ }
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ // 0600 on every replacement (the atomic write applies the mode), like the Agent vault's.
+ await atomicWriteFile(file, `${stringifyToml(vault)}\n`, { mode: 0o600, followSymlinks: true });
+}
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index b6723136..a8034f34 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1084,6 +1084,33 @@ export interface VaultUpdateRequest {
entries: VaultEntryUpdate[];
}
+// ---------------------------------------------------------------------------
+// User-level vault (the signed-in user's own secrets: <root>/users/<userId>/.vault.toml)
+// Read as {@link VaultResponse} and written through {@link VaultUpdateRequest}, exactly like
+// the Agent-level table: one entry shape, one set of rules, masked on the way out.
+// ---------------------------------------------------------------------------
+
+/**
+ * POST /api/me/vault/import body: the whole import in one object, as the pasted JSON TEXT.
+ * Parsed and validated server-side rather than in the browser, so a syntax error and a bad
+ * entry both come back as a 400 naming what is wrong with which entry. The import merges into
+ * the stored table (a key already there is overwritten, keys absent from the body stay) — the
+ * paste flow is additive; removing an entry is the table's own delete, i.e. the PUT above.
+ */
+export interface UserVaultImportRequest {
+ json: string;
+}
+
+/**
+ * POST …/agents/:agentId/vault/assign-user-vault body: the user-level entries to copy into
+ * that Agent's vault. A one-off copy, not a link — the Agent keeps the value it was given, and
+ * a later change to the user-level entry does not reach it.
+ */
+export interface UserVaultAssignRequest {
+ /** Vault key names; every one must exist in the caller's own user-level vault. */
+ keys: string[];
+}
+
// ---------------------------------------------------------------------------
// Agent and its config (system_config.yaml + AGENTS.md)
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 90d73980..c45c1a32 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -144,6 +144,7 @@ import type { TraceIndex, Traces } from "../../mechanisms/traces.js";
import type { FileReveal, WorkspaceFiles } from "../../mechanisms/workspace.js";
import type { Machines } from "../../machines/service.js";
import type { AgentConfig, AgentLifecycle } from "../../mechanisms/agents.js";
+import type { UserVault } from "../../mechanisms/vault.js";
import type { Settings } from "../../mechanisms/settings.js";
import type { LiveStreams } from "../../auth/live-streams.js";
import type { Auth } from "../../mechanisms/identity.js";
@@ -1628,6 +1629,7 @@ export class SessionApiRoutes {
@Use() private readonly machines!: Machines;
@Use() private readonly sessionService!: SessionServiceIface;
@Use() private readonly agentConfig!: AgentConfig;
+ @Use() private readonly userVault!: UserVault;
@Use() private readonly agents!: AgentLifecycle;
@Use() private readonly messaging!: Messaging;
@Use() private readonly schedulesRepo!: Schedules;
@@ -1740,7 +1742,12 @@ export class SessionApiRoutes {
traceIndex: this.traceIndex,
});
this.agentConfigRoutes = agentConfigRoutes({ agentConfigService, manager, access });
- this.vaultRoutes = vaultRoutes({ agentConfigService, manager, access });
+ this.vaultRoutes = vaultRoutes({
+ agentConfigService,
+ manager,
+ access,
+ userVault: this.userVault,
+ });
this.agentSessionsRoutes = agentSessionsRoutes(sessionsDeps);
this.usageRoutes = usageRoutes({ access, usageService: this.usage });
this.workspaceFilesRoutes = workspaceFilesRoutes({
diff --git a/packages/server/src/http/routes/user-vault.ts b/packages/server/src/http/routes/user-vault.ts
new file mode 100644
index 00000000..30532b2b
--- /dev/null
+++ b/packages/server/src/http/routes/user-vault.ts
@@ -0,0 +1,106 @@
+/**
+ * User-level vault routes: GET|PUT /api/me/vault, POST /api/me/vault/import.
+ *
+ * The caller's OWN secrets, one scope above the Agent vault
+ * (`/api/projects/:p/agents/:a/vault`): there is no Project in the path and no membership to
+ * check, because the file belongs to the account — reading and writing are both the signed-in
+ * user, and one account can never see another's. The routes therefore sit under /api/me, beside
+ * the other per-account resources (prefs, profile).
+ *
+ * Values are masked on the way out exactly like the Agent vault's, so plaintext never reaches
+ * the browser. PUT carries whole-table replace semantics (the same body as the Agent vault's —
+ * its parser is shared); the import endpoint takes a whole JSON object and MERGES it, because
+ * the paste flow is additive by nature.
+ *
+ * Same `auth: "user"` group as every other route; the Hono app is bound by its own component,
+ * so this file owns everything the endpoints need.
+ */
+import { Hono } from "hono";
+import type { AppEnv } from "../../auth/middleware.js";
+import { parseVaultUpdate } from "./vault.js";
+import { badRequest, readJson } from "../validate.js";
+import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";
+import type { UserVault } from "../../mechanisms/vault.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface UserVaultRouteDeps {
+ userVault: UserVault;
+}
+
+/** Whether a parsed JSON value is a plain object (what an import has to be). */
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return v !== null && typeof v === "object" && !Array.isArray(v);
+}
+
+/**
+ * Turns the import body into the not-yet-checked table the service validates, in either shape:
+ * `{ json: "<text>" }` — what the paste box sends, parsed here so a syntax error is a 400 with
+ * the parser's own message rather than a silent no-op — or the `{"KEY": "value"}` object itself.
+ * The wrapper wins, so a vault key literally named `json` is imported through the text form.
+ */
+export function parseVaultImport(body: Record<string, unknown>): Record<string, unknown> {
+ if (body.json !== undefined) {
+ if (typeof body.json !== "string") throw badRequest("json must be the pasted JSON text.");
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(body.json);
+ } catch (err) {
+ throw badRequest(
+ `json is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!isPlainObject(parsed)) {
+ throw badRequest('json must be an object of "KEY": "value" pairs.');
+ }
+ return parsed;
+ }
+ // No `json` field: the body IS the table. It is always an object by the time it gets here
+ // (readJson rejects anything else), so this is the one-key-at-a-time shape.
+ return body;
+}
+
+export function userVaultRoutes(deps: UserVaultRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ // The caller's own vault; there is nothing to authorize beyond being signed in.
+ app.get("/", async (c) => {
+ return c.json(await deps.userVault.getVault(c.var.user.userId));
+ });
+
+ app.put("/", async (c) => {
+ const req = parseVaultUpdate(await readJson(c));
+ return c.json(await deps.userVault.updateVault(c.var.user.userId, req));
+ });
+
+ // Whole-object import (a pasted JSON key-value table), merged into the stored one.
+ app.post("/import", async (c) => {
+ const table = parseVaultImport(await readJson(c));
+ return c.json(await deps.userVault.importVault(c.var.user.userId, table));
+ });
+ return app;
+}
+
+/**
+ * The per-account vault, mounted beside /api/me (MeRoutes): its own group because the path is
+ * `/api/me/vault` and a group owns one prefix. Order 12 puts it right after the me group's 10,
+ * which is only a mount position — each prefix matches its own routes.
+ */
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "UserVaultRoutes.routes",
+ prefix: "/api/me/vault",
+ auth: "user",
+ order: 12,
+ },
+ ],
+ },
+})
+export class UserVaultRoutes {
+ @Use() private readonly userVault!: UserVault;
+ @Bind("UserVaultRoutes.routes") routes!: Hono<AppEnv>;
+ setup() {
+ this.routes = userVaultRoutes({ userVault: this.userVault });
+ }
+}
diff --git a/packages/server/src/http/routes/vault.ts b/packages/server/src/http/routes/vault.ts
index 0aba6242..9dcaa225 100644
--- a/packages/server/src/http/routes/vault.ts
+++ b/packages/server/src/http/routes/vault.ts
@@ -1,9 +1,13 @@
/**
* Vault environment variable routes:
* GET|PUT /api/projects/:p/agents/:a/vault (Agent-level, agent_state/.vault.toml).
+ * POST …/vault/assign-user-vault copies the caller's user-level entries into this Agent.
* POST …/vault/template-placeholder inserts/migrates the {{VAULT}} placeholder in the
* prompt template.
* Any member can read (values masked); only the owner can modify; 404 if the Agent doesn't exist.
+ *
+ * The PUT body parser is exported for the user-level vault routes (user-vault.ts), which take
+ * the same request shape for the caller's own file.
*/
import { Hono } from "hono";
import type { VaultEntryUpdate, VaultUpdateRequest } from "../../api/types.js";
@@ -11,6 +15,7 @@ import type { AppEnv } from "../../auth/middleware.js";
import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
import type { SessionManager } from "../../runtime/session-manager.js";
import type { AgentConfig } from "../../mechanisms/agents.js";
+import type { UserVault } from "../../mechanisms/vault.js";
import type { Access } from "../../mechanisms/projects.js";
/** What this route group reaches — bound by its module (src/modules). */
@@ -18,10 +23,12 @@ export interface VaultRouteDeps {
agentConfigService: AgentConfig;
manager: SessionManager;
access: Access;
+ /** The caller's own user-level vault: the source of the assign endpoint's copy. */
+ userVault: UserVault;
}
/** Validate the PUT request body and shape it into a VaultUpdateRequest (semantic checks like key-name rules live in the service layer). */
-function parseVaultUpdate(body: Record<string, unknown>): VaultUpdateRequest {
+export function parseVaultUpdate(body: Record<string, unknown>): VaultUpdateRequest {
if (!Array.isArray(body.entries)) throw badRequest("entries must be an array.");
const entries: VaultEntryUpdate[] = body.entries.map((item, i) => {
if (item === null || typeof item !== "object" || Array.isArray(item)) {
@@ -42,6 +49,24 @@ function parseVaultUpdate(body: Record<string, unknown>): VaultUpdateRequest {
return { entries };
}
+/**
+ * Validate the assign request body: the key names to copy out of the caller's own vault. An
+ * empty list is refused rather than answered with the unchanged table — the client asked for a
+ * copy of nothing, which is never what its checkbox list meant to say.
+ */
+function parseAssignKeys(body: Record<string, unknown>): string[] {
+ const raw = body.keys;
+ if (!Array.isArray(raw)) throw badRequest("keys must be an array.");
+ const keys = raw.map((item, i) => {
+ if (typeof item !== "string" || item.length === 0) {
+ throw badRequest(`keys[${i}] must be a non-empty string.`);
+ }
+ return item;
+ });
+ if (keys.length === 0) throw badRequest("keys must name at least one user-level entry.");
+ return keys;
+}
+
export function vaultRoutes(deps: VaultRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@@ -65,6 +90,17 @@ export function vaultRoutes(deps: VaultRouteDeps): Hono<AppEnv> {
return c.json(res);
});
+ // Assign user-level (global) entries to this Agent: a one-off COPY into its own vault —
+ // same key overwrites, the Agent's other entries stay. Owner-level like every other write
+ // here, and the source table is always the caller's own (never another account's).
+ app.post("/assign-user-vault", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ const keys = parseAssignKeys(await readJson(c));
+ return c.json(await deps.userVault.assignToAgent(c.var.user.userId, projectId, agentId, keys));
+ });
+
// Insert (or migrate a legacy hardcoded # Vault section to) the {{VAULT}} placeholder —
// the explicit adoption path mirroring memory's endpoint; idempotent config write,
// owner-level like this router's other mutation.
diff --git a/packages/server/src/mechanisms/vault.ts b/packages/server/src/mechanisms/vault.ts
new file mode 100644
index 00000000..a42f549b
--- /dev/null
+++ b/packages/server/src/mechanisms/vault.ts
@@ -0,0 +1,34 @@
+/**
+ * The vault mechanisms: what a node may require, declared apart from what implements it.
+ *
+ * The Agent-level vault is a method pair on {@link AgentConfig} (services/agent-config-service.ts),
+ * because it is one field of that Agent's state. The user-level vault is its own mechanism here:
+ * it belongs to an ACCOUNT rather than to any Agent, and the two write different files.
+ */
+import { Interface } from "@lmliheng/penguin-core/kernel";
+import type { VaultResponse, VaultUpdateRequest } from "../api/types.js";
+
+/** UserVault: the mechanism UserVaultService implements — the signed-in user's own secrets (`<root>/users/<userId>/.vault.toml`). */
+@Interface()
+export abstract class UserVault {
+ abstract getVault(userId: string): Promise<VaultResponse>;
+ abstract updateVault(userId: string, req: VaultUpdateRequest): Promise<VaultResponse>;
+ /**
+ * Merges a whole import (see UserVaultImportRequest) into the user's table: keys and values
+ * are still unvalidated at this point — the semantic rules (shell-legal key names, value
+ * length, non-empty string) live in the service, which is where a bad entry becomes the 400
+ * that names it.
+ */
+ abstract importVault(userId: string, table: Record<string, unknown>): Promise<VaultResponse>;
+ /**
+ * Copies the named keys from the caller's own user-level vault into one Agent's vault
+ * (existing Agent entries are kept, a same-named key is overwritten). Returns the Agent's
+ * refreshed masked view — what the Agent settings tab shows after the copy.
+ */
+ abstract assignToAgent(
+ userId: string,
+ projectId: string,
+ agentId: string,
+ keys: string[],
+ ): Promise<VaultResponse>;
+}
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
index 15c567c0..afb89744 100644
--- a/packages/server/src/platform.ts
+++ b/packages/server/src/platform.ts
@@ -105,6 +105,7 @@ import { AuthService, InitialProjectProvisioner } from "./auth/service.js";
import { AdminService } from "./services/admin-service.js";
import { Scheduler, ScheduleSessionCreator, ScheduleTaskRunner } from "./runtime/scheduler.js";
import { AgentConfigService } from "./services/agent-config-service.js";
+import { UserVaultService } from "./services/user-vault-service.js";
import { SnapshotService } from "./services/snapshot-service.js";
import { AgentRoutes } from "./services/agent-routes.js";
import { AgentService } from "./services/agent-service.js";
@@ -122,6 +123,7 @@ import { TerminalRelay } from "./machines/terminal-relay.js";
import { ProjectAdminRoutes } from "./http/routes/projects.js";
import { AdminRoutes } from "./http/routes/admin.js";
import { MeRoutes } from "./http/routes/me.js";
+import { UserVaultRoutes } from "./http/routes/user-vault.js";
import { AuthRoutes } from "./http/routes/auth.js";
import {
DesktopPrivacySettingsRoutes,
@@ -162,6 +164,7 @@ import {
} from "./mechanisms/observability.js";
import { TraceIndex, TraceIndexStore, Traces } from "./mechanisms/traces.js";
import { AgentConfig, AgentLifecycle, Benchmarks, Memory, Snapshots } from "./mechanisms/agents.js";
+import { UserVault } from "./mechanisms/vault.js";
import { FileReveal, WorkspaceFiles } from "./mechanisms/workspace.js";
import { Settings, UiPrefsStore } from "./mechanisms/settings.js";
import { MessagingBindings } from "./mechanisms/messaging.js";
@@ -277,6 +280,7 @@ export class RuntimeModule {}
AdminService,
AdminRoutes,
MeRoutes,
+ UserVaultRoutes,
AuthRoutes,
],
exports: [Users, AuthSessions, Auth, Admin, PasswordHasher, LiveStreams],
@@ -391,13 +395,14 @@ export class TracesModule {}
@Module({
children: [
AgentConfigService,
+ UserVaultService,
SnapshotService,
AgentService,
MemoryService,
BenchmarkService,
AgentRoutes,
],
- exports: [AgentConfig, Snapshots, AgentLifecycle, Memory, Benchmarks],
+ exports: [AgentConfig, UserVault, Snapshots, AgentLifecycle, Memory, Benchmarks],
})
export class AgentsModule {}
diff --git a/packages/server/src/services/user-vault-service.ts b/packages/server/src/services/user-vault-service.ts
new file mode 100644
index 00000000..9d51ff8f
--- /dev/null
+++ b/packages/server/src/services/user-vault-service.ts
@@ -0,0 +1,153 @@
+/**
+ * The user-level vault: the secrets one account owns
+ * (`<root>/users/<userId>/.vault.toml`, read/written through core's loadUserVault/saveUserVault),
+ * one scope above the Agent vault this same package already serves.
+ *
+ * Same rules and same display discipline as the Agent vault: key names follow shell variable
+ * naming, values are capped at what a child process can still be spawned with, and every
+ * response carries masked values only — plaintext never leaves the server, the responses of a
+ * write included.
+ *
+ * "Assign to an Agent" is the one cross-scope operation here, and it is a COPY: the named entries
+ * are written into that Agent's own `.vault.toml` by the Agent config service — this service never
+ * touches that file, and the Agent vault keeps its single writer. Same key overwrites, the Agent's
+ * other entries stay. Nothing reads the user vault at Session time, so a later change to a
+ * user-level entry does not reach an Agent that was assigned before it: the Agent keeps what it
+ * was given until the user assigns again.
+ *
+ * Lives in the Agents module because assigning reaches the Agent config service (the Agent's own
+ * vault), whose existence check and masked read both come from there; the API layer reaches the
+ * user vault through the UserVault mechanism either way.
+ */
+import {
+ VAULT_VALUE_MAX_LENGTH,
+ isValidVaultKey,
+ loadUserVault,
+ saveUserVault,
+} from "@lmliheng/penguin-core";
+import type { VaultResponse, VaultUpdateRequest } from "../api/types.js";
+import { badRequest } from "../http/validate.js";
+import { Component, Use } from "@lmliheng/penguin-core/kernel";
+import type { Paths } from "../hmr/capabilities.js";
+import type { AgentConfig } from "../mechanisms/agents.js";
+import type { UserVault } from "../mechanisms/vault.js";
+import { maskApiKey } from "./project-config-service.js";
+
+/** The masked view every response carries: key names with their values masked (never plaintext). */
+function maskTable(vault: Record<string, string>): VaultResponse {
+ return {
+ entries: Object.entries(vault).map(([key, value]) => ({ key, valueMasked: maskApiKey(value) })),
+ };
+}
+
+/** The key-name rule (core's, shared with the Agent vault): a 400 that names the offending entry. */
+function assertImportKey(key: string): void {
+ if (!isValidVaultKey(key)) {
+ throw badRequest(
+ `Invalid vault key name: ${JSON.stringify(key)} (letters, digits and underscores only, and must not start with a digit).`,
+ );
+ }
+}
+
+/** The value rules (non-empty, and short enough for a child-process environment): a 400 that names the entry. */
+function assertImportValue(key: string, value: unknown): string {
+ if (typeof value !== "string" || value.length === 0) {
+ throw badRequest(`Import value for ${key} must be a non-empty string.`);
+ }
+ if (value.length > VAULT_VALUE_MAX_LENGTH) {
+ throw badRequest(`Vault value too long: ${key} (limit ${VAULT_VALUE_MAX_LENGTH} characters).`);
+ }
+ return value;
+}
+
+@Component()
+export class UserVaultService implements UserVault {
+ @Use() private readonly paths!: Paths;
+ @Use() private readonly agentConfig!: AgentConfig;
+ private get root(): string {
+ return this.paths.root;
+ }
+
+ /** Read the user's vault: masked values only (see the module doc). */
+ async getVault(userId: string): Promise<VaultResponse> {
+ return maskTable(await loadUserVault(this.root, userId));
+ }
+
+ /**
+ * PUT replaces the whole user vault table: keys absent from the body are deleted; omitting a
+ * value keeps the stored one (a new key must provide one). The rules are the Agent vault's
+ * (services/agent-config-service.ts `updateVault`), applied to the user's own file.
+ */
+ async updateVault(userId: string, req: VaultUpdateRequest): Promise<VaultResponse> {
+ const prev = await loadUserVault(this.root, userId);
+ const seen = new Set<string>();
+ const next: Record<string, string> = {};
+ for (const entry of req.entries) {
+ assertImportKey(entry.key);
+ if (seen.has(entry.key)) throw badRequest(`entries contains a duplicate key: ${entry.key}.`);
+ seen.add(entry.key);
+ const prevValue = prev[entry.key];
+ if (entry.value !== undefined) {
+ next[entry.key] = assertImportValue(entry.key, entry.value);
+ } else if (prevValue !== undefined) {
+ next[entry.key] = prevValue;
+ } else {
+ throw badRequest(`New key ${entry.key} must provide a value.`);
+ }
+ }
+ await saveUserVault(this.root, userId, next);
+ return maskTable(next);
+ }
+
+ /**
+ * Merges a whole import into the user vault: the pasted JSON object, one entry at a time
+ * included. Every entry is checked BEFORE anything is written, so a rejected import changes
+ * nothing (the same all-or-nothing rule the PUT has).
+ */
+ async importVault(userId: string, table: Record<string, unknown>): Promise<VaultResponse> {
+ const entries = Object.entries(table);
+ if (entries.length === 0) throw badRequest("The imported object contains no entries.");
+ const checked: Record<string, string> = {};
+ for (const [key, value] of entries) {
+ assertImportKey(key);
+ checked[key] = assertImportValue(key, value);
+ }
+ const prev = await loadUserVault(this.root, userId);
+ const next = { ...prev, ...checked };
+ await saveUserVault(this.root, userId, next);
+ return maskTable(next);
+ }
+
+ /** Copy named user-level entries into one Agent's vault (see the module doc: a copy, not a link). */
+ async assignToAgent(
+ userId: string,
+ projectId: string,
+ agentId: string,
+ keys: string[],
+ ): Promise<VaultResponse> {
+ const wanted = [...new Set(keys)];
+ const userVault = await loadUserVault(this.root, userId);
+ // Every named key must be in the caller's own vault: assigning a key that is not there would
+ // silently write nothing, and a browser tab showing a key the server no longer has is exactly
+ // the stale read this check turns into a named failure.
+ const copied: { key: string; value: string }[] = [];
+ const missing: string[] = [];
+ for (const key of wanted) {
+ const value = userVault[key];
+ if (value === undefined) missing.push(key);
+ else copied.push({ key, value });
+ }
+ if (missing.length > 0) {
+ throw badRequest(`Not in your user vault: ${missing.join(", ")}.`);
+ }
+ // The Agent's table as its own service reports it: the key names (never the values, and none
+ // are needed — an entry resent without a value keeps the stored one). That read also 404s an
+ // Agent that does not exist, and the write below goes through the same service, so the Agent
+ // vault file keeps one writer.
+ const current = await this.agentConfig.getVault(projectId, agentId);
+ const kept = current.entries
+ .filter((entry) => !wanted.includes(entry.key))
+ .map((entry) => ({ key: entry.key }));
+ return this.agentConfig.updateVault(projectId, agentId, { entries: [...kept, ...copied] });
+ }
+}
diff --git a/packages/server/test/user-vault.test.ts b/packages/server/test/user-vault.test.ts
new file mode 100644
index 00000000..c98aab56
--- /dev/null
+++ b/packages/server/test/user-vault.test.ts
@@ -0,0 +1,254 @@
+/**
+ * The user-level vault API: the signed-in user's OWN secrets
+ * (`<root>/users/<userId>/.vault.toml`), its JSON import, and the copy into one Agent.
+ *
+ * - GET masks every value and never sends plaintext; it answers about the caller only — another
+ * account's table is never visible, and an empty vault is an empty table.
+ * - PUT is whole-table replace, the same rules as the Agent vault: an entry without a value keeps
+ * the stored one, an absent key is deleted, a new key without a value is a 400.
+ * - POST …/vault/import takes the pasted JSON text or the object itself and MERGES it; a bad entry
+ * is a 400 naming that entry, and a rejected import writes nothing.
+ * - POST …/agents/:a/vault/assign-user-vault is owner-only and copies: the same key overwrites the
+ * Agent's own value, the Agent's other entries stay, and the user's table is left untouched.
+ * - The file lands under the data root's `users/` (outside any Project), 0600.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import type { ProjectCreateResponse, VaultResponse } from "../src/api/types.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** key → masked value, so an assertion is about content rather than file order. */
+function masked(entries: VaultResponse["entries"]): Record<string, string> {
+ return Object.fromEntries(entries.map((e) => [e.key, e.valueMasked]));
+}
+
+describe("user vault api", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ let other: ReturnType<typeof apiClient>;
+ let outsider: ReturnType<typeof apiClient>;
+ let projectId: string;
+ /** The caller's user-level table on disk, and the Agent-level one the assign cases write. */
+ let userVaultFile: string;
+ let agentVaultFile: string;
+ /** The Agent-level route, for both the table itself and the assign endpoint under it. */
+ let agentVaultPath: string;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_a");
+ const b = await provisionUser(t.app, "member_b");
+ const c = await provisionUser(t.app, "outsider_c");
+ owner = apiClient(t.app, a.cookie);
+ other = apiClient(t.app, b.cookie);
+ outsider = apiClient(t.app, c.cookie);
+ const created = (await (
+ await owner.post("/api/projects", { projectId: "owner_a-uservault", name: "vault project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ agentVaultPath = `/api/projects/${projectId}/agents/default_agent/vault`;
+ agentVaultFile = path.join(
+ t.root,
+ projectId,
+ "agents",
+ "default_agent",
+ "agent_state",
+ ".vault.toml",
+ );
+ userVaultFile = path.join(t.root, "users", "owner_a", ".vault.toml");
+ expect(
+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,
+ ).toBe(201);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(async () => {
+ expect((await owner.put("/api/me/vault", { entries: [] })).status).toBe(200);
+ expect((await owner.put(agentVaultPath, { entries: [] })).status).toBe(200);
+ });
+
+ it("GET masks values, never sends plaintext, and answers about the caller only", async () => {
+ expect(((await (await owner.get("/api/me/vault")).json()) as VaultResponse).entries).toEqual(
+ [],
+ );
+
+ const put = await owner.put("/api/me/vault", {
+ entries: [
+ { key: "OPENAI_API_KEY", value: "sk-user-secret-123456" },
+ { key: "SHORT", value: "sk-short-1" },
+ ],
+ });
+ expect(put.status).toBe(200);
+ // The write response is masked too: plaintext never comes back, not even to its owner.
+ expect(JSON.stringify(await put.json())).not.toContain("sk-user-secret-123456");
+
+ const body = (await (await owner.get("/api/me/vault")).json()) as VaultResponse;
+ expect(masked(body.entries)).toEqual({
+ OPENAI_API_KEY: "sk-u…3456",
+ SHORT: "***", // ≤12 chars are masked entirely
+ });
+ expect(JSON.stringify(body)).not.toContain("sk-user-secret-123456");
+
+ // Another account's table is its own: the same route answers empty, holding nothing of owner_a's.
+ expect(((await (await other.get("/api/me/vault")).json()) as VaultResponse).entries).toEqual(
+ [],
+ );
+
+ // On disk: under the data root's users/, outside every Project, 0600.
+ expect((await fs.stat(userVaultFile)).mode & 0o777).toBe(0o600);
+ expect(await fs.readFile(userVaultFile, "utf8")).toContain("sk-user-secret-123456");
+ });
+
+ it("GET is behind the cookie gate", async () => {
+ expect((await t.app.request("/api/me/vault")).status).toBe(401);
+ expect((await t.app.request("/api/me/vault/import", { method: "POST" })).status).toBe(401);
+ });
+
+ it("PUT replaces the whole table: omitted values are kept, absent keys deleted, bad input a named 400", async () => {
+ await owner.put("/api/me/vault", {
+ entries: [
+ { key: "KEEP_ME", value: "keep-secret-000111" },
+ { key: "DROP_ME", value: "drop-secret" },
+ ],
+ });
+ const second = (await (
+ await owner.put("/api/me/vault", { entries: [{ key: "KEEP_ME" }] })
+ ).json()) as VaultResponse;
+ expect(second.entries).toEqual([{ key: "KEEP_ME", valueMasked: "keep…0111" }]);
+
+ const cases: unknown[] = [
+ { entries: [{ key: "1BAD", value: "v" }] }, // starts with a digit
+ { entries: [{ key: "BAD-DASH", value: "v" }] }, // hyphen
+ { entries: [{ key: "BAD KEY", value: "v" }] }, // space
+ { entries: [{ key: "OK_KEY", value: "" }] }, // empty value
+ {
+ entries: [
+ { key: "DUP", value: "a" },
+ { key: "DUP", value: "b" },
+ ],
+ }, // duplicate key
+ { entries: [{ key: "BIG", value: "x".repeat(8193) }] }, // over the 8192 cap (exec E2BIG)
+ { entries: [{ key: "BRAND_NEW" }] }, // new key without a value
+ { entries: { K: "v" } }, // entries is not an array
+ { entries: [42] }, // entry is not an object
+ ];
+ for (const body of cases) {
+ expect((await owner.put("/api/me/vault", body)).status).toBe(400);
+ }
+
+ // None of the rejected writes landed: the table is still the one KEEP_ME entry.
+ const after = (await (await owner.get("/api/me/vault")).json()) as VaultResponse;
+ expect(after.entries.map((e) => e.key)).toEqual(["KEEP_ME"]);
+ });
+
+ it("POST /vault/import takes the pasted JSON text or the object, merges, and names the bad entry", async () => {
+ const first = await owner.post("/api/me/vault/import", {
+ json: '{"A_KEY": "secret-a-123456", "B_KEY": "secret-b-123456"}',
+ });
+ expect(first.status).toBe(200);
+ expect(JSON.stringify(await first.json())).not.toContain("secret-a-123456");
+
+ // A second import is additive: A_KEY is overwritten, B_KEY stays, C_KEY is added.
+ const merged = (await (
+ await owner.post("/api/me/vault/import", {
+ json: '{"A_KEY": "secret-a2-123456", "C_KEY": "secret-c-123456"}',
+ })
+ ).json()) as VaultResponse;
+ expect(Object.keys(masked(merged.entries)).sort()).toEqual(["A_KEY", "B_KEY", "C_KEY"]);
+ // The mask cannot tell the two A_KEY values apart — the file can.
+ expect(await fs.readFile(userVaultFile, "utf8")).toContain("secret-a2-123456");
+
+ // The object form: the body IS the table (importing one key-value pair at a time included).
+ const one = (await (
+ await owner.post("/api/me/vault/import", { D_KEY: "secret-d-123456" })
+ ).json()) as VaultResponse;
+ expect(Object.keys(masked(one.entries)).sort()).toEqual(["A_KEY", "B_KEY", "C_KEY", "D_KEY"]);
+
+ const bad: unknown[] = [
+ { json: "not json at all" }, // not JSON
+ { json: '["A_KEY"]' }, // JSON, but not an object
+ { json: "{}" }, // an empty import has nothing to do
+ { json: '{"1BAD": "v"}' }, // key rule
+ { json: '{"OK": ""}' }, // empty value
+ { json: '{"NUM": 5}' }, // value is not a string
+ { json: `{"BIG": "${"x".repeat(8193)}"}` }, // over the value cap
+ { json: 42 }, // the wrapper is not text
+ ];
+ for (const body of bad) {
+ expect((await owner.post("/api/me/vault/import", body)).status, JSON.stringify(body)).toBe(
+ 400,
+ );
+ }
+
+ // An entry that fails names itself, and the failed call wrote nothing.
+ const named = await owner.post("/api/me/vault/import", {
+ json: '{"GOOD": "v-1", "1BAD": "v"}',
+ });
+ expect(named.status).toBe(400);
+ expect(await named.text()).toContain("1BAD");
+ expect(await fs.readFile(userVaultFile, "utf8")).not.toContain("GOOD");
+ });
+
+ it("assign copies the selected entries into the Agent's vault and leaves the rest alone", async () => {
+ await owner.put("/api/me/vault", {
+ entries: [
+ { key: "SHARED_KEY", value: "user-value-123456" },
+ { key: "ONLY_USER", value: "user-only-123456" },
+ ],
+ });
+ await owner.put(agentVaultPath, {
+ entries: [
+ { key: "SHARED_KEY", value: "agent-old-value" },
+ { key: "AGENT_ONLY", value: "agent-only-1" },
+ ],
+ });
+
+ const res = await owner.post(`${agentVaultPath}/assign-user-vault`, {
+ keys: ["SHARED_KEY", "ONLY_USER"],
+ });
+ expect(res.status).toBe(200);
+
+ // The Agent's file: the same key overwritten with the user's value, its own entry kept.
+ const agentDisk = await fs.readFile(agentVaultFile, "utf8");
+ expect(agentDisk).toContain("user-value-123456");
+ expect(agentDisk).toContain("AGENT_ONLY");
+ expect(agentDisk).toContain("agent-only-1");
+ expect(agentDisk).not.toContain("agent-old-value");
+
+ // The response is the Agent's refreshed table, masked.
+ const body = (await res.json()) as VaultResponse;
+ expect(JSON.stringify(body)).not.toContain("user-value-123456");
+ expect(Object.keys(masked(body.entries)).sort()).toEqual([
+ "AGENT_ONLY",
+ "ONLY_USER",
+ "SHARED_KEY",
+ ]);
+
+ // A copy, not a link: the user's own table still holds its entry.
+ const user = (await (await owner.get("/api/me/vault")).json()) as VaultResponse;
+ expect(Object.keys(masked(user.entries)).sort()).toEqual(["ONLY_USER", "SHARED_KEY"]);
+ });
+
+ it("assign is owner-only, names keys the caller does not have, and rejects malformed bodies", async () => {
+ await owner.put("/api/me/vault", { entries: [{ key: "MINE", value: "mine-secret-123456" }] });
+ const assign = (client: ReturnType<typeof apiClient>, keys: unknown) =>
+ client.post(`${agentVaultPath}/assign-user-vault`, { keys });
+
+ expect((await assign(owner, ["NOPE"])).status).toBe(400);
+ expect((await assign(owner, [])).status).toBe(400);
+ expect((await assign(owner, "MINE")).status).toBe(400);
+ expect((await assign(owner, [42])).status).toBe(400);
+ // A member cannot write the Agent's vault (the same owner-level gate the PUT has), and an
+ // outsider cannot see the Agent at all: neither gets to copy their keys into it.
+ expect((await assign(other, ["MINE"])).status).toBe(403);
+ expect((await assign(outsider, ["MINE"])).status).toBe(404);
+ const noAgent = await owner.post(
+ `/api/projects/${projectId}/agents/no-such-agent/vault/assign-user-vault`,
+ { keys: ["MINE"] },
+ );
+ expect(noAgent.status).toBe(404);
+ });
+});
diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.ts
index f326e47f..a5874f44 100644
--- a/packages/ui-gallery/src/app/mock/fixtures.ts
+++ b/packages/ui-gallery/src/app/mock/fixtures.ts
@@ -112,6 +112,8 @@ export interface DemoFixtures {
update: UpdateCheckResponse;
memory: Record<string, { overview: MemoryOverviewResponse; files: MemoryFileResponse[] }>;
vault: Record<string, VaultResponse>;
+ /** The signed-in account's own vault — the user-level table `/api/me/vault` serves. */
+ userVault: VaultResponse;
workspace: { entries: Record<string, WorkspaceFileEntry[]>; content: Record<string, string> };
chatDefaults: ChatDefaultsDto;
commandPolicy: CommandPolicyDto;
@@ -1097,6 +1099,15 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
[IDS.agents.notes]: { entries: [] },
};
+ // One entry the docs Agent already has (the assign step overwrites it) and one it does not, so
+ // the picker in the Agent settings tab has both a "name already there" and a new key to show.
+ const userVault: VaultResponse = {
+ entries: [
+ { key: "GITHUB_TOKEN", valueMasked: "ghp_…9x2Q" },
+ { key: "OPENAI_API_KEY", valueMasked: "sk-…4f7a" },
+ ],
+ };
+
const file = (name: string, sizeBytes: number, days: number): WorkspaceFileEntry => ({
name,
kind: "file",
@@ -1435,6 +1446,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
update,
memory,
vault,
+ userVault,
workspace,
chatDefaults,
commandPolicy,
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 84673944..d17d6581 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -479,6 +479,63 @@ router
ctx.store.f.vault[agentId] = next;
return next;
})
+ // The signed-in account's own vault (the account menu's dialog) and the assign step that copies
+ // from it into an Agent's table. Values are masked on the way out here too — the fixture holds
+ // no plaintext at all, which is the same promise the server makes.
+ .get("/api/me/vault", (ctx): VaultResponse => ctx.store.f.userVault)
+ .put("/api/me/vault", (ctx): VaultResponse => {
+ const entries = record(ctx.body).entries;
+ const previous = ctx.store.f.userVault.entries;
+ if (!Array.isArray(entries)) return ctx.store.f.userVault;
+ const next: VaultResponse = {
+ entries: (entries as Array<{ key: string; value?: string }>).map((e) => ({
+ key: e.key,
+ valueMasked:
+ typeof e.value === "string"
+ ? `${e.value.slice(0, 3)}…${e.value.slice(-3)}`
+ : (previous.find((p) => p.key === e.key)?.valueMasked ?? "***"),
+ })),
+ };
+ ctx.store.f.userVault = next;
+ return next;
+ })
+ .post("/api/me/vault/import", (ctx): VaultResponse => {
+ const body = record(ctx.body);
+ const table: unknown =
+ typeof body.json === "string" ? (JSON.parse(body.json) as unknown) : body;
+ if (table === null || typeof table !== "object" || Array.isArray(table))
+ fail(400, "bad_request", 'json must be an object of "KEY": "value" pairs.');
+ const stored = new Map(ctx.store.f.userVault.entries.map((e) => [e.key, e.valueMasked]));
+ for (const [key, value] of Object.entries(table as Record<string, unknown>)) {
+ stored.set(
+ key,
+ typeof value === "string" ? `${value.slice(0, 3)}…${value.slice(-3)}` : "***",
+ );
+ }
+ const next: VaultResponse = {
+ entries: [...stored].map(([key, valueMasked]) => ({ key, valueMasked })),
+ };
+ ctx.store.f.userVault = next;
+ return next;
+ })
+ .post(
+ "/api/projects/:projectId/agents/:agentId/vault/assign-user-vault",
+ (ctx): VaultResponse => {
+ const agentId = agentOf(ctx).agentId;
+ const wanted = record(ctx.body).keys;
+ const keys = Array.isArray(wanted) ? (wanted as string[]) : [];
+ const userEntries = ctx.store.f.userVault.entries;
+ const missing = keys.filter((key) => !userEntries.some((e) => e.key === key));
+ if (missing.length > 0)
+ fail(400, "bad_request", `Not in your user vault: ${missing.join(", ")}.`);
+ const previous = ctx.store.f.vault[agentId]?.entries ?? [];
+ const kept = previous.filter((entry) => !keys.includes(entry.key));
+ const copied = userEntries.filter((entry) => keys.includes(entry.key));
+ const next: VaultResponse = { entries: [...kept, ...copied] };
+ ctx.store.f.vault[agentId] = next;
+ return next;
+ },
+ )
.post(
"/api/projects/:projectId/agents/:agentId/vault/template-placeholder",
(ctx): AgentVaultConfigDto => {
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 335d65ad..1c7d5ad2 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -210,6 +210,8 @@ import type {
UsageResponse,
VaultResponse,
VaultUpdateRequest,
+ UserVaultAssignRequest,
+ UserVaultImportRequest,
InstalledPluginsResponse,
VersionHistoryDiffResponse,
VersionHistoryResponse,
@@ -550,6 +552,30 @@ export const insertVaultPlaceholder = (projectId: string, agentId: string) =>
{ method: "POST", body: {} },
);
+// The signed-in user's own vault (user-level: `<root>/users/<userId>/.vault.toml`) ---------------
+// No Project in the path: it is the account's own table, readable and writable by nobody else.
+
+export const getUserVault = () => apiFetch<VaultResponse>("/api/me/vault");
+
+/** Whole-table replace, the same body as {@link putVault}: keys absent from the body are deleted, an entry without a value keeps the stored one. */
+export const putUserVault = (body: VaultUpdateRequest) =>
+ apiFetch<VaultResponse>("/api/me/vault", { method: "PUT", body });
+
+/** Imports a whole pasted JSON object into the table (merged: a same-named key is overwritten, the rest stay); the server parses and validates it, so a bad entry comes back as a 400 naming it. */
+export const importUserVault = (body: UserVaultImportRequest) =>
+ apiFetch<VaultResponse>("/api/me/vault/import", { method: "POST", body });
+
+/** Copies the named keys from the caller's own user vault into this agent's vault — a one-off copy (same key overwrites, the agent's other entries stay). */
+export const assignUserVaultToAgent = (
+ projectId: string,
+ agentId: string,
+ body: UserVaultAssignRequest,
+) =>
+ apiFetch<VaultResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/vault/assign-user-vault`,
+ { method: "POST", body },
+ );
+
/** Inserts the {{SKILLS}} placeholder into the agent's prompt template — migrating a legacy hardcoded # Skills section verbatim when one is present (idempotent). */
export const insertSkillsPlaceholder = (projectId: string, agentId: string) =>
apiFetch<AgentSkillsConfigDto>(
diff --git a/packages/web/src/components/account/user-vault-dialog.tsx b/packages/web/src/components/account/user-vault-dialog.tsx
new file mode 100644
index 00000000..7fc94c4c
--- /dev/null
+++ b/packages/web/src/components/account/user-vault-dialog.tsx
@@ -0,0 +1,366 @@
+/**
+ * The user-level vault dialog, opened from the account menu (bottom-left avatar) — the
+ * signed-in account's OWN secrets (`<root>/users/<userId>/.vault.toml`), one scope above the
+ * per-Agent vault on the Agent settings page.
+ *
+ * Same shape as the Agent vault tab's table (key, masked value, delete + Add), plus the one
+ * thing this table has and that one does not: a whole JSON object can be pasted in at once.
+ * Every write is whole-table replace through PUT except the import, which merges — the same
+ * semantics the server has, so the dialog never has to explain a second set of rules: an Add
+ * keeps the other rows (they are resent by key name, values never come back to the browser), a
+ * Delete drops one row, an Import merges the pasted object.
+ *
+ * Mounted outside the menu that opens it (the panel's children unmount when the menu closes);
+ * the account menu's own row closes the menu as it opens this.
+ */
+import { useCallback, useEffect, useState } from "react";
+import type { VaultEntryInfo, VaultUpdateRequest } from "@lmliheng/penguin-server/api";
+import {
+ Button,
+ ConfirmModal,
+ Input,
+ Modal,
+ NoticeStrip,
+ PasswordInput,
+ SettingsEmpty,
+ SkeletonList,
+ Textarea,
+ toastError,
+ toastSuccess,
+} from "@lmliheng/penguin-ui";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+
+/** Vault key naming rule (consistent with core/server): shell environment variable name. */
+const VAULT_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+export function UserVaultDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
+ const [entries, setEntries] = useState<VaultEntryInfo[] | null>(null);
+ // Dialog-level error is only the initial load failure; saves/deletes report via toast, and a
+ // failed form submission lands on the form that produced it.
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [adding, setAdding] = useState(false);
+ const [importing, setImporting] = useState(false);
+ const [keyInput, setKeyInput] = useState("");
+ const [valueInput, setValueInput] = useState("");
+ const [jsonInput, setJsonInput] = useState("");
+ const [addErrors, setAddErrors] = useState<{ key?: string; value?: string }>({});
+ const [importError, setImportError] = useState<string | null>(null);
+ /** Key pending deletion / overwrite confirmation (non-null shows the confirm modal). */
+ const [deleting, setDeleting] = useState<string | null>(null);
+ const [overwriting, setOverwriting] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ setEntries(null);
+ setError(null);
+ try {
+ setEntries((await api.getUserVault()).entries);
+ } catch (e) {
+ setError(apiErrorText(e));
+ }
+ }, []);
+
+ // Reloaded on every open: this table can also be changed from another tab, and the dialog is
+ // cheap to fill (one request) compared with showing a stale key list.
+ useEffect(() => {
+ if (open) void load();
+ }, [open, load]);
+
+ /** Persist a change immediately (add / delete): returns an error message, or null on success. */
+ const persist = async (body: VaultUpdateRequest): Promise<string | null> => {
+ setBusy(true);
+ try {
+ const res = await api.putUserVault(body);
+ setEntries(res.entries);
+ toastSuccess(S.common.saved);
+ return null;
+ } catch (e) {
+ return apiErrorText(e);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ /** Keep existing keys (resending only the key name = keep the original value), excluding excludeKey. */
+ const keepEntries = (excludeKey?: string) =>
+ (entries ?? [])
+ .filter((e) => e.key !== excludeKey)
+ .map((e): VaultUpdateRequest["entries"][number] => ({ key: e.key }));
+
+ const openAdd = () => {
+ setKeyInput("");
+ setValueInput("");
+ setAddErrors({});
+ setAdding(true);
+ };
+
+ const addEntry = async () => {
+ const key = keyInput.trim();
+ const next: { key?: string; value?: string } = {};
+ if (!key) next.key = S.common.requiredField;
+ else if (!VAULT_KEY_PATTERN.test(key)) next.key = S.vault.keyInvalid;
+ if (!valueInput) next.value = S.vault.valueRequired;
+ if (next.key || next.value) {
+ setAddErrors(next);
+ return;
+ }
+ setAddErrors({});
+ // Submitting an already-configured key overwrites its value (unrecoverable): confirm first.
+ if (overwriting !== key && (entries ?? []).some((e) => e.key === key)) {
+ setOverwriting(key);
+ return;
+ }
+ setOverwriting(null);
+ const err = await persist({ entries: [...keepEntries(key), { key, value: valueInput }] });
+ if (err !== null) {
+ setAddErrors({ key: err });
+ return;
+ }
+ setAdding(false);
+ };
+
+ const confirmRemove = async () => {
+ if (deleting === null) return;
+ const err = await persist({ entries: keepEntries(deleting) });
+ if (err !== null) toastError(err);
+ setDeleting(null);
+ };
+
+ const importJson = async () => {
+ if (!jsonInput.trim()) {
+ setImportError(S.common.requiredField);
+ return;
+ }
+ setImportError(null);
+ setBusy(true);
+ try {
+ const res = await api.importUserVault({ json: jsonInput });
+ setEntries(res.entries);
+ toastSuccess(S.common.saved);
+ setImporting(false);
+ } catch (e) {
+ // The server names the entry that failed (and writes nothing): show it in the dialog
+ // rather than as a toast, since the text to fix is right above it.
+ setImportError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <>
+ <Modal
+ open={open}
+ title={S.account.userVault.title}
+ onClose={onClose}
+ widthClass="sm:max-w-2xl"
+ footer={
+ <Button size="sm" onClick={onClose}>
+ {S.common.close}
+ </Button>
+ }
+ >
+ <div className="space-y-4">
+ {/* What this table is, and the one thing a reader has to know to get anything out of
+ it: it reaches no agent by itself. */}
+ <p className="text-xs leading-relaxed text-gray-500 dark:text-gray-400">
+ {S.account.userVault.desc}
+ </p>
+
+ {entries === null ? (
+ <SkeletonList rows={3} />
+ ) : entries.length === 0 ? (
+ <SettingsEmpty>{S.account.userVault.empty}</SettingsEmpty>
+ ) : (
+ <div className="overflow-x-auto overflow-y-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
+ <table className="w-full min-w-[420px] text-left text-sm">
+ <thead>
+ <tr className="border-b border-gray-200 bg-gray-50/80 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900">
+ <th className="px-3 py-2.5">{S.vault.key}</th>
+ <th className="px-3 py-2.5">{S.vault.valueMasked}</th>
+ <th className="px-3 py-2.5" />
+ </tr>
+ </thead>
+ <tbody>
+ {entries.map((entry) => (
+ <tr
+ key={entry.key}
+ className="border-b border-gray-100 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40"
+ >
+ <td className="px-3 py-2 font-mono text-xs">{entry.key}</td>
+ <td className="px-3 py-2 font-mono text-xs text-gray-500 dark:text-gray-400">
+ {entry.valueMasked}
+ </td>
+ <td className="px-3 py-2 text-right">
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => setDeleting(entry.key)}
+ >
+ {S.account.userVault.remove}
+ </Button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ {entries !== null && (
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="primary" disabled={busy} onClick={openAdd}>
+ {S.account.userVault.add}
+ </Button>
+ <Button
+ size="sm"
+ disabled={busy}
+ onClick={() => {
+ setJsonInput("");
+ setImportError(null);
+ setImporting(true);
+ }}
+ >
+ {S.account.userVault.import}
+ </Button>
+ </div>
+ )}
+
+ {error && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}
+ </div>
+ </Modal>
+
+ {/* Add: one key + value at a time. A value typed here never leaves the vault — unlike the
+ agent tab there is no AI path, because these secrets are not an agent's to ask about. */}
+ <Modal
+ open={adding}
+ title={S.account.userVault.addTitle}
+ onClose={() => setAdding(false)}
+ footer={
+ <>
+ <Button size="sm" onClick={() => setAdding(false)}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void addEntry()}>
+ {S.account.userVault.add}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <Input
+ size="sm"
+ label={S.vault.key}
+ required
+ hint={S.vault.keyHint}
+ error={addErrors.key}
+ value={keyInput}
+ onChange={(e) => {
+ setKeyInput(e.target.value);
+ if (addErrors.key || addErrors.value) setAddErrors({});
+ }}
+ className="font-mono"
+ placeholder="OPENAI_API_KEY"
+ autoComplete="off"
+ />
+ <PasswordInput
+ size="sm"
+ label={S.vault.value}
+ required
+ error={addErrors.value}
+ value={valueInput}
+ onChange={(e) => {
+ setValueInput(e.target.value);
+ if (addErrors.key || addErrors.value) setAddErrors({});
+ }}
+ className="font-mono"
+ autoComplete="off"
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !busy) void addEntry();
+ }}
+ />
+ </div>
+ </Modal>
+
+ {/* Import: the whole pasted object, merged by the server (which is what names the entry
+ that fails). A plain textarea and not a field: the paste is JSON with its own layout,
+ and no browser control here has a JSON mode. */}
+ <Modal
+ open={importing}
+ title={S.account.userVault.importTitle}
+ onClose={() => setImporting(false)}
+ footer={
+ <>
+ <Button size="sm" onClick={() => setImporting(false)}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void importJson()}>
+ {S.account.userVault.importSubmit}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <p className="text-xs leading-relaxed text-gray-500 dark:text-gray-400">
+ {S.account.userVault.importHint}
+ </p>
+ {/* A plain multi-line field rather than a styled textarea: the paste is JSON with its
+ own layout, and the mono rung is what the rest of this dialog's key/value text uses. */}
+ <Textarea
+ label={S.account.userVault.jsonLabel}
+ rows={8}
+ size="sm"
+ mono
+ spellCheck={false}
+ autoComplete="off"
+ invalid={importError !== null}
+ value={jsonInput}
+ onChange={(e) => {
+ setJsonInput(e.target.value);
+ setImportError(null);
+ }}
+ placeholder={S.account.userVault.importPlaceholder}
+ />
+ {importError && (
+ <NoticeStrip tone="attention" className="rounded-md border px-2.5 py-1.5">
+ {importError}
+ </NoticeStrip>
+ )}
+ </div>
+ </Modal>
+
+ {/* Overwrite confirmation: the add modal stays underneath, so cancel returns to the form. */}
+ <ConfirmModal
+ open={overwriting !== null}
+ title={S.account.userVault.overwriteTitle}
+ tone="primary"
+ confirmLabel={S.common.save}
+ cancelLabel={S.common.cancel}
+ busy={busy}
+ onClose={() => setOverwriting(null)}
+ onConfirm={() => void addEntry()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {overwriting !== null ? S.account.userVault.overwriteConfirm(overwriting) : ""}
+ </p>
+ </ConfirmModal>
+
+ <ConfirmModal
+ open={deleting !== null}
+ title={S.account.userVault.deleteTitle}
+ busy={busy}
+ onClose={() => setDeleting(null)}
+ onConfirm={() => void confirmRemove()}
+ confirmLabel={S.common.confirm}
+ cancelLabel={S.common.cancel}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {deleting !== null ? S.account.userVault.deleteConfirm(deleting) : ""}
+ </p>
+ </ConfirmModal>
+ </>
+ );
+}
diff --git a/packages/web/src/components/layout/user-menu.tsx b/packages/web/src/components/layout/user-menu.tsx
index 65f77403..49838fa5 100644
--- a/packages/web/src/components/layout/user-menu.tsx
+++ b/packages/web/src/components/layout/user-menu.tsx
@@ -1,15 +1,15 @@
/**
* The account menu, shared by both avatars that open one: the pinned sidebar's user row and
* the collapsed rail's avatar. One component rather than a copy per anchor — the rows
- * (Settings, the scheduled-tasks page, the update entry, sign out) and the dialog behind the
- * first of them must stay the same menu from either side, and a second copy is how two menus
- * drift apart.
+ * (Settings, the user-level vault, the scheduled-tasks page, the update entry, sign out) and the
+ * dialog behind the first of them must stay the same menu from either side, and a second copy is
+ * how two menus drift apart.
*
* Only the trigger differs, so the trigger is the caller's: it is handed the menu's own open
* state, which is what keeps "what opening means" here rather than in two places.
*
- * The settings dialog is mounted OUTSIDE the panel: the panel's children unmount the moment
- * the menu closes, and the settings row closes the menu as it opens the dialog.
+ * The dialogs are mounted OUTSIDE the panel: the panel's children unmount the moment the menu
+ * closes, and a row closes the menu as it opens its dialog.
*
* The panel heads itself with the account it belongs to — avatar, nickname, and the id under
* it once a nickname stands in for it. Both anchors are avatars, and the rail's is nothing but
@@ -23,6 +23,7 @@ import type { DropdownPortal } from "@lmliheng/penguin-ui";
import { S } from "../../lib/strings";
import { useAuth } from "../../state/auth";
import { UpdateRow } from "../account/update-row";
+import { UserVaultDialog } from "../account/user-vault-dialog";
import { openUpdateModal } from "../../lib/use-update-flow";
import { SettingsDialog } from "../../features/settings/settings-dialog";
import { onSettingsRequest } from "../../features/settings/settings-request";
@@ -53,6 +54,8 @@ export function UserMenu({
const { user, logout, desktopMode } = useAuth();
const [open, setOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
+ /** The account's own global secrets, the one row here that edits data rather than navigating. */
+ const [vaultOpen, setVaultOpen] = useState(false);
/** The page a request asked for; the menu's own row asks for none (the viewer's first). */
const [settingsSection, setSettingsSection] = useState<SettingsSectionKey | undefined>(undefined);
const [confirmingLogout, setConfirmingLogout] = useState(false);
@@ -115,6 +118,16 @@ export function UserMenu({
setSettingsOpen(true);
}}
/>
+ {/* The account's own global secrets. A row here rather than a settings page because
+ it is not a preference: it is the table of secrets the Agent vault's "assign"
+ step reads from, and it belongs next to the account it belongs to. */}
+ <MenuItem
+ label={S.account.userVault.title}
+ onSelect={() => {
+ setOpen(false);
+ setVaultOpen(true);
+ }}
+ />
{/* The Project's scheduled tasks, the one page reached from here rather than from
the sidebar: it is a Project-wide inventory visited now and then, not a
workspace. A plain row of its own, right under the settings dialog's entry —
@@ -159,6 +172,9 @@ export function UserMenu({
onClose={() => setSettingsOpen(false)}
{...(settingsSection !== undefined ? { section: settingsSection } : {})}
/>
+ {/* The account's own secrets, mounted here like the settings dialog so it outlives the
+ menu that opened it. */}
+ <UserVaultDialog open={vaultOpen} onClose={() => setVaultOpen(false)} />
{/* Signing out is confirmed first: the row sits in a menu of harmless entries, and a
slip would end the session and land on the login page. Mounted beside the settings
dialog, outside the dropdown, so it outlives the menu that opened it. */}
diff --git a/packages/web/src/features/agents/vault-tab.tsx b/packages/web/src/features/agents/vault-tab.tsx
index 28b07a06..b2e583d7 100644
--- a/packages/web/src/features/agents/vault-tab.tsx
+++ b/packages/web/src/features/agents/vault-tab.tsx
@@ -9,6 +9,12 @@
* value is injected only into the exec_command subprocess environment, never into
* the model context.
*
+ * "Assign user secrets" copies the account's own global secrets (the user-level vault behind the
+ * account menu's User secrets row) into this table, one selected key at a time, and says in its
+ * own copy that it is a copy: the Agent keeps the value it was given, so a later change to the
+ * global entry has to be assigned again. Nothing here links the two tables — the runtime injects
+ * this file and only this file.
+ *
* Prompt-injection controls (usePromptInjection): the vault.enabled switch, the
* {{VAULT}}-placeholder alert (with legacy-template migration) and the editable
* vault.prompt section, mirroring the Memory tab — owner-only, like the table edits.
@@ -17,6 +23,7 @@ import { useCallback, useEffect, useState } from "react";
import type { VaultEntryInfo, VaultUpdateRequest } from "@lmliheng/penguin-server/api";
import {
Button,
+ Checkbox,
ConfirmModal,
HelpFold,
Input,
@@ -75,6 +82,15 @@ export function VaultTab({
const [deleting, setDeleting] = useState<string | null>(null);
// Existing key pending overwrite confirmation (adding a key that's already configured replaces its value).
const [overwriting, setOverwriting] = useState<string | null>(null);
+ /**
+ * Assign-user-secrets dialog: the account's global table (null while loading, and after a
+ * failed load) and the key names ticked in it. Read fresh on every open rather than cached —
+ * the global table is edited from the account menu, which this tab has no way to hear about.
+ */
+ const [assigning, setAssigning] = useState(false);
+ const [globalEntries, setGlobalEntries] = useState<VaultEntryInfo[] | null>(null);
+ const [globalError, setGlobalError] = useState<string | null>(null);
+ const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const load = useCallback(async () => {
if (!projectId || !agentId) return;
@@ -164,6 +180,49 @@ export function VaultTab({
setDeleting(null);
};
+ /** Open the assign dialog: an empty selection and a fresh read of the account's global table. */
+ const openAssign = async () => {
+ setAssigning(true);
+ setGlobalEntries(null);
+ setGlobalError(null);
+ setSelected(new Set());
+ try {
+ setGlobalEntries((await api.getUserVault()).entries);
+ } catch (e) {
+ setGlobalError(apiErrorText(e));
+ }
+ };
+
+ const toggleSelected = (key: string, on: boolean) => {
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (on) next.add(key);
+ else next.delete(key);
+ return next;
+ });
+ };
+
+ /**
+ * Assign the ticked global secrets to this Agent: a copy into its own vault, so the response is
+ * this tab's refreshed table. The global table is untouched and no later edit to it follows —
+ * see the dialog's own note.
+ */
+ const confirmAssign = async () => {
+ if (!projectId || !agentId || selected.size === 0) return;
+ setBusy(true);
+ try {
+ const res = await api.assignUserVaultToAgent(projectId, agentId, { keys: [...selected] });
+ setEntries(res.entries);
+ toastSuccess(S.vault.assign.done(selected.size));
+ void reloadAgents();
+ setAssigning(false);
+ } catch (e) {
+ setGlobalError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
if (!projectId) return null;
return (
@@ -233,6 +292,17 @@ export function VaultTab({
/>
)}
+ {/* Assigning the account's own global secrets. Its own line under the add buttons, with the
+ one sentence that decides whether a user trusts it: what it does is copy. */}
+ {isOwner && entries !== null && (
+ <div className="space-y-1.5">
+ <Button size="sm" disabled={busy} onClick={() => void openAssign()}>
+ {S.vault.assign.open}
+ </Button>
+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.vault.assign.hint}</p>
+ </div>
+ )}
+
{promptSection}
<Modal
@@ -285,6 +355,84 @@ export function VaultTab({
</div>
</Modal>
+ {/* Assign user secrets: the account's global table, ticked per key. Read-only here — this
+ dialog copies, it does not edit the source (that is the account menu's dialog). Every
+ global key is offered, including one this Agent already has: a same-named key replaces
+ this table's value, which is the whole point of assigning again after a rotation. */}
+ <Modal
+ open={assigning}
+ title={S.vault.assign.title}
+ onClose={() => setAssigning(false)}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button size="sm" onClick={() => setAssigning(false)}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy || selected.size === 0}
+ onClick={() => void confirmAssign()}
+ >
+ {S.vault.assign.confirm}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <p className="text-xs leading-relaxed text-gray-500 dark:text-gray-400">
+ {S.vault.assign.overwritten}
+ </p>
+ {globalError !== null ? (
+ <p className="text-xs text-red-600 dark:text-red-400">{globalError}</p>
+ ) : globalEntries === null ? (
+ <SkeletonList rows={3} />
+ ) : globalEntries.length === 0 ? (
+ <SettingsEmpty>{S.vault.assign.empty}</SettingsEmpty>
+ ) : (
+ <>
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-gray-500 dark:text-gray-400">
+ {S.vault.assign.selected(selected.size)}
+ </span>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy}
+ onClick={() =>
+ setSelected(
+ selected.size === globalEntries.length
+ ? new Set()
+ : new Set(globalEntries.map((e) => e.key)),
+ )
+ }
+ >
+ {S.vault.assign.all}
+ </Button>
+ </div>
+ <div className="overflow-y-auto rounded-md border border-gray-200 dark:border-gray-800">
+ {globalEntries.map((entry) => (
+ <div
+ key={entry.key}
+ className="flex items-center justify-between gap-3 border-b border-gray-100 px-3 py-2 last:border-b-0 dark:border-gray-800/60"
+ >
+ <Checkbox
+ checked={selected.has(entry.key)}
+ onChange={(on) => toggleSelected(entry.key, on)}
+ label={<span className="font-mono text-xs">{entry.key}</span>}
+ />
+ <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">
+ {entry.valueMasked}
+ </span>
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ </Modal>
+
{/* The AI path. Its lead is an honest warning: a value typed into the prompt is recorded in
the conversation's Trace, whereas a value typed into the form never leaves the vault. The
dialog's one exit already agrees with that warning — the prompt lands in a composer and is
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index af5a42df..197e7b35 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -917,6 +917,33 @@ export const en: Strings = {
passwordMismatch: "New passwords do not match",
initialPasswordBanner: "This account is using its initial password. Please change it soon.",
changeNow: "Change now",
+ /**
+ * The user-level vault dialog (the account menu's "User secrets" row): this account's own
+ * key-value table, stored outside every Project. The copy explains what the table is and,
+ * just as important, that it reaches no agent on its own — assigning is a separate step
+ * taken in the agent's own settings.
+ */
+ userVault: {
+ title: "User secrets",
+ desc: "Your own global secrets (stored in the users directory of the data root). They belong to no Project, and they can be added one at a time or pasted in as one JSON object. Nothing here reaches an agent by itself — assign them to an agent under Agent settings › Vault, and note that assigning is a one-off copy.",
+ add: "Add",
+ addTitle: "Add global secret",
+ import: "Import JSON",
+ importTitle: "Import JSON",
+ importHint:
+ 'Paste a whole JSON object, e.g. {"OPENAI_API_KEY": "sk-…"}. The import merges into the stored secrets: a same-named key is overwritten, the rest stay; one invalid entry fails the whole import and is named.',
+ importPlaceholder: '{\n "OPENAI_API_KEY": "sk-…",\n "GITHUB_TOKEN": "ghp_…"\n}',
+ importSubmit: "Import",
+ jsonLabel: "JSON object",
+ empty: "No global secrets yet",
+ remove: "Remove",
+ deleteTitle: "Delete global secret",
+ deleteConfirm: (key: string): string =>
+ `Delete the global secret "${key}"? Its value cannot be recovered.`,
+ overwriteTitle: "Overwrite existing global secret",
+ overwriteConfirm: (key: string): string =>
+ `"${key}" already exists — saving will overwrite its value, which cannot be recovered.`,
+ },
},
admin: {
@@ -1844,6 +1871,24 @@ export const en: Strings = {
"- Never repeat a value back in your reply, and never read .vault.toml.",
`- Finish with \`penguin config vault list --agent-id ${agentId} --project-id ${projectId} --root <data root>\` to list the key names.`,
].join("\n"),
+ /**
+ * Assigning the account's own global secrets into this Agent (the user-level vault dialog
+ * lives in the account menu). The copy says what the operation IS — a one-off copy into this
+ * Agent's own vault, not a link to the global entry — because that is the one thing a user
+ * cannot see from the table that results.
+ */
+ assign: {
+ open: "Assign user secrets",
+ title: "Assign user secrets",
+ hint: "Copies your global secrets into this agent; a later change to a global secret needs another assign to reach it.",
+ empty:
+ "Your user secrets are empty — add some under the account menu first (bottom left) › User secrets.",
+ selected: (n: number): string => `${n} selected`,
+ all: "Select all",
+ confirm: "Assign",
+ done: (n: number): string => `Assigned ${n} to this agent`,
+ overwritten: "A same-named key overwrites the agent's own value",
+ },
/** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
injection: {
enable: "Enable vault",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index dfe0f629..fb64a558 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -969,6 +969,31 @@ export const zh = {
passwordMismatch: "两次输入的新密码不一致",
initialPasswordBanner: "当前账号正在使用初始密码,建议尽快修改",
changeNow: "去修改",
+ /**
+ * The user-level vault dialog (the account menu's 用户密钥 row): this account's own
+ * key-value table, stored outside every Project. The copy explains what the table is and,
+ * just as important, that it reaches no agent on its own — assigning is a separate step
+ * taken in the agent's own settings.
+ */
+ userVault: {
+ title: "用户密钥",
+ desc: "你自己的全局密钥(存于数据根的 users 目录)。它们不属于任何项目,可以一条条添加,也可以整段 JSON 导入。写在这里不会自动进入任何智能体——在「智能体设置 › 密钥保险柜」里把它「分配」给某个智能体,分配是一次性拷贝。",
+ add: "添加",
+ addTitle: "添加全局密钥",
+ import: "导入 JSON",
+ importTitle: "导入 JSON",
+ importHint:
+ '粘贴整段 JSON 对象,例如 {"OPENAI_API_KEY": "sk-…"}。导入会合并进现有密钥:同名覆盖,其余保留;某一条不合法时整次导入不生效,并指出是哪一条。',
+ importPlaceholder: '{\n "OPENAI_API_KEY": "sk-…",\n "GITHUB_TOKEN": "ghp_…"\n}',
+ importSubmit: "导入",
+ jsonLabel: "JSON 对象",
+ empty: "还没有全局密钥",
+ remove: "删除",
+ deleteTitle: "删除全局密钥",
+ deleteConfirm: (key: string): string => `确认删除全局密钥「${key}」?值不可恢复。`,
+ overwriteTitle: "覆盖已有全局密钥",
+ overwriteConfirm: (key: string): string => `「${key}」已存在,保存将覆盖原值且不可恢复。`,
+ },
},
admin: {
@@ -1902,6 +1927,23 @@ export const zh = {
"- 不要在回复里复述任何值,不要读取 .vault.toml。",
`- 最后运行 \`penguin config vault list --agent-id ${agentId} --project-id ${projectId} --root <数据根目录>\` 列出键名。`,
].join("\n"),
+ /**
+ * Assigning the account's own global secrets into this Agent (the user-level vault dialog
+ * lives in the account menu). The copy says what the operation IS — a one-off copy into this
+ * Agent's own vault, not a link to the global entry — because that is the one thing a user
+ * cannot see from the table that results.
+ */
+ assign: {
+ open: "从用户密钥分配",
+ title: "分配用户密钥",
+ hint: "把你的全局密钥拷贝进本智能体;之后全局密钥改了,要重新分配才会同步。",
+ empty: "你的用户密钥里还没有条目——先在左下角账号菜单 ›「用户密钥」里添加。",
+ selected: (n: number): string => `已选 ${n} 条`,
+ all: "全选",
+ confirm: "分配",
+ done: (n: number): string => `已分配 ${n} 条到本智能体`,
+ overwritten: "同名密钥会覆盖本智能体原有的值",
+ },
/** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
injection: {
enable: "启用密钥保险柜",