@xiaolikt/ai-vault 0.9.1 → 0.11.0

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.
@@ -1,3 +1,4 @@
1
+ import { tr } from "./i18n.js";
1
2
  /**
2
3
  * ai-vault — the pi/omp extension.
3
4
  *
@@ -14,15 +15,17 @@
14
15
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
15
16
  import { Type } from "typebox";
16
17
  import {
17
- lookupBitwardenLogin,
18
+ lookupBitwardenItem,
18
19
  newBwState,
19
- pullBitwardenLogins,
20
+ pullBitwardenItems,
20
21
  queryBitwarden,
21
22
  registerBitwarden,
22
23
  type BitwardenMeta,
23
24
  type BwState,
24
25
  } from "./bitwarden.js";
25
26
  import { CliError, VaultCli } from "./cli.js";
27
+ import { ITEM_TYPES, isSecretField, parseItemType } from "./import-map.js";
28
+ import type { Draft, ItemType } from "./types.js";
26
29
  import { registerEnte } from "./ente.js";
27
30
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
28
31
  import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
@@ -100,8 +103,8 @@ interface Scope {
100
103
  const cli = new VaultCli();
101
104
 
102
105
  const CLI_MISSING =
103
- "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)";
104
- const NOT_INITIALIZED = "本地库还没初始化 — 运行 /vault init";
106
+ tr("ai-vault CLI not found. Install it once for a machine-wide store: cargo install --path <repo>/crates/ai-vault (or point AI_VAULT_BIN at a compiled binary)", "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)");
107
+ const NOT_INITIALIZED = tr("the local store is not initialised — run /vault init", "本地库还没初始化 — 运行 /vault init");
105
108
  const LOCKED = "local vault is locked (no master password entered, or the window was cancelled)";
106
109
 
107
110
  const dialogs = (ctx: Ctx): PromptHost => ctx as unknown as PromptHost;
@@ -216,9 +219,9 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
216
219
  result = await attempt();
217
220
  } catch (error) {
218
221
  if (!(error instanceof CliError) || !error.needsUi) throw error;
219
- const password = await promptSecret(dialogs(ctx), "ai-vault · 解锁", "本地库主密码", signal);
222
+ const password = await promptSecret(dialogs(ctx), tr("ai-vault · unlock", "ai-vault · 解锁"), tr("local store master password", "本地库主密码"), signal);
220
223
  if (!password) {
221
- if (!signal?.aborted) note(ctx, "没有输入主密码(窗口已取消,或没有桌面/界面)", "warning");
224
+ if (!signal?.aborted) note(ctx, tr("no master password entered (the window was cancelled, or there is no desktop/UI)", "没有输入主密码(窗口已取消,或没有桌面/界面)"), "warning");
222
225
  return false;
223
226
  }
224
227
  result = await attempt(password);
@@ -237,7 +240,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
237
240
  return true;
238
241
  } catch (error) {
239
242
  if (error instanceof CliError && error.auth) {
240
- note(ctx, "ai-vault: 主密码错误", "error");
243
+ note(ctx, tr("ai-vault: wrong master password", "ai-vault: 主密码错误"), "error");
241
244
  return false;
242
245
  }
243
246
  if (error instanceof CliError && /not initialized/i.test(error.message)) {
@@ -307,44 +310,34 @@ async function bitwardenFallback(
307
310
  const missing = localMiss;
308
311
  let hit;
309
312
  try {
310
- hit = await lookupBitwardenLogin(bw, ctx, name, signal);
313
+ hit = await lookupBitwardenItem(bw, ctx, name, signal);
311
314
  } catch (error) {
312
315
  return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
313
316
  }
314
317
  if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
318
+ const draft = hit.draft;
319
+ const secret = draft.type === "login" ? draft.password : (draft.data?.[ITEM_TYPES[draft.type].primary ?? ""] ?? "");
315
320
 
316
321
  const asValue = (via: string): ToolOutcome => ({
317
322
  content: [
318
323
  {
319
324
  type: "text" as const,
320
- text: JSON.stringify(
321
- { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
322
- null,
323
- 1,
324
- ),
325
+ text: JSON.stringify({ ...draft, password: secret ?? draft.password, via }, null, 1),
325
326
  },
326
327
  ],
327
- details: { item: hit.name, via },
328
+ details: { item: draft.name, via },
328
329
  });
329
330
 
330
331
  const importIt = async (): Promise<ToolOutcome> => {
331
332
  try {
332
333
  const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
333
- stdin: JSON.stringify([
334
- {
335
- name: hit.name,
336
- username: hit.username || undefined,
337
- password: hit.password,
338
- uris: hit.uris,
339
- source: { kind: "bitwarden", id: hit.id },
340
- },
341
- ]),
334
+ stdin: JSON.stringify([draft]),
342
335
  signal,
343
336
  });
344
337
  scope.items += saved.count;
345
338
  setStatus(ctx, scope);
346
339
  } catch (error) {
347
- return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
340
+ return fail(`found "${draft.name}" in Bitwarden but could not import it: ${describe(error)}`);
348
341
  }
349
342
  return asValue("imported-from-bitwarden");
350
343
  };
@@ -355,20 +348,25 @@ async function bitwardenFallback(
355
348
  return importIt();
356
349
  }
357
350
 
358
- const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
359
351
  const allow = await confirmWindow(
360
352
  dialogs(ctx),
361
- "pi-ai-vault · Bitwarden 里找到",
362
- `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`,
353
+ tr("pi-ai-vault · found in Bitwarden", "pi-ai-vault · Bitwarden 里找到"),
354
+ tr(
355
+ `Not in the local store as "${forDialog(name)}", but Bitwarden has:\n${forDialog(hit.label)}\n\nRead it this once?`,
356
+ `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(hit.label)}\n\n读取这一次吗?`,
357
+ ),
363
358
  signal,
364
359
  );
365
- if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
360
+ if (!allow) return fail(`user denied reading "${draft.name}" from Bitwarden — do not retry`, true);
366
361
  if (policy === "never") return asValue("bitwarden-once");
367
362
 
368
363
  const confirmed = await confirmWindow(
369
364
  dialogs(ctx),
370
- "pi-ai-vault · 导入到 ai-vault",
371
- `把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
365
+ tr("pi-ai-vault · import into ai-vault", "pi-ai-vault · 导入到 ai-vault"),
366
+ tr(
367
+ `Write "${forDialog(draft.name)}" into ai-vault?\n\nAllow → read from the local store from now on (no password under the current unlock policy)\nDeny → use it once only; nothing is written to the local store`,
368
+ `把「${forDialog(draft.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
369
+ ),
372
370
  signal,
373
371
  );
374
372
  return confirmed ? importIt() : asValue("bitwarden-once");
@@ -407,9 +405,9 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
407
405
  const sub = subagentId(ctx);
408
406
  const allowed = await confirmWindow(
409
407
  dialogs(ctx),
410
- "ai-vault · 读取本地密码",
411
- `条目: ${forDialog(params.name)}\n请求方: ${sub ? `子代理 ${forDialog(sub, 32)}` : "主会话"}\n原因: ${forDialog(params.reason ?? "(未说明)", 120)}\n\n` +
412
- "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
408
+ tr("ai-vault · read local password", "ai-vault · 读取本地密码"),
409
+ tr(`Entry: ${forDialog(params.name)}\nRequester: ${sub ? `subagent ${forDialog(sub, 32)}` : "main session"}\nReason: ${forDialog(params.reason ?? "(none given)", 120)}\n\n`, `条目: ${forDialog(params.name)}\n请求方: ${sub ? `子代理 ${forDialog(sub, 32)}` : "主会话"}\n原因: ${forDialog(params.reason ?? "(未说明)", 120)}\n\n`) +
410
+ tr("Allowing lets the same requester read it again for 5 minutes. The password enters the conversation.", "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。"),
413
411
  signal,
414
412
  );
415
413
  // Relaying is our privilege as the host: sign the answer under the
@@ -445,26 +443,62 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
445
443
 
446
444
  const vaultAddParams = Type.Object({
447
445
  name: Type.String({ description: "Entry name to create or update, e.g. 'github'" }),
448
- username: Type.Optional(Type.String({ description: "Account username. Omit to let the user type it in a dialog." })),
449
- uri: Type.Optional(Type.String({ description: "Optional site or host URI" })),
450
- notes: Type.Optional(Type.String({ description: "Optional non-secret note. Do NOT put the password here." })),
446
+ type: Type.Optional(
447
+ Type.String({
448
+ description:
449
+ "Item type, as in Bitwarden: login (default), note, card, identity, sshkey, bankaccount, driverslicense, passport. " +
450
+ "A note's content goes in `notes`.",
451
+ }),
452
+ ),
453
+ username: Type.Optional(Type.String({ description: "Login: account username. Omit to let the user type it in a dialog." })),
454
+ uri: Type.Optional(Type.String({ description: "Login: site or host URI" })),
455
+ notes: Type.Optional(Type.String({ description: "Notes shared by every type. For a `note` entry this is its content." })),
456
+ fields: Type.Optional(
457
+ Type.Record(
458
+ Type.String(),
459
+ Type.Optional(Type.String()),
460
+ {
461
+ description:
462
+ "The type's own fields by Bitwarden's names (card: cardholderName, brand, number, expMonth, expYear, code; " +
463
+ "sshkey: publicKey, privateKey, keyFingerprint; identity: firstName, lastName, email, …). " +
464
+ "Give a non-secret field as text; give a secret field (password, code, number, privateKey, pin, ssn…) " +
465
+ "as null/undefined so the user types it in a dialog. NEVER put a secret value here.",
466
+ },
467
+ ),
468
+ ),
451
469
  });
452
470
  function vaultAddTool(scope: Scope): ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> {
453
471
  const tool: ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> = {
454
472
  name: "vault_add",
455
473
  label: "Vault: store a secret via dialog",
456
474
  description:
457
- "Create or update an entry in the machine-wide ai-vault store. You supply the name and optional username, URI, and notes. " +
458
- "The password is typed by the user in a desktop window and is NEVER accepted from you and NEVER returned. " +
459
- "Do not ask the user to paste a password into the chat.",
475
+ "Create or update an entry of any Bitwarden type in the machine-wide ai-vault store (login, note, card, identity, sshkey, " +
476
+ "bankaccount, driverslicense, passport). You supply the name, the type and its non-secret fields. " +
477
+ "Secret fields (password, card number and code, private key, PIN, SSN…) are typed by the user in a desktop window: " +
478
+ "leave them empty, they are NEVER accepted from you and NEVER returned. Do not ask the user to paste a secret into the chat.",
460
479
  promptSnippet: "Save a local vault entry; the user types the password in a window.",
461
480
  parameters: vaultAddParams,
462
481
  async execute(_id, params, signal, _onUpdate, ctx) {
482
+ const kind = parseItemType(params.type);
483
+ if (!kind) {
484
+ return fail(`unknown type "${params.type}" — login, note, card, identity, sshkey, bankaccount, driverslicense, passport`);
485
+ }
486
+ // A secret field the model filled in is refused rather than stored:
487
+ // only the user types secrets, in a dialog.
488
+ const fields: Record<string, string | undefined> = {};
489
+ for (const [field, value] of Object.entries(params.fields ?? {})) {
490
+ if (value !== undefined && value !== "" && isSecretField(kind, field)) {
491
+ return fail(`"${field}" is a secret field: leave it empty so the user types it in a dialog`);
492
+ }
493
+ fields[field] = value === "" ? undefined : value;
494
+ }
463
495
  const result = await saveLocalEntry(scope, ctx, {
464
496
  name: params.name,
497
+ type: kind,
465
498
  username: params.username,
466
499
  uri: params.uri,
467
500
  notes: params.notes,
501
+ fields,
468
502
  signal,
469
503
  });
470
504
  const ok = result.startsWith("saved ");
@@ -507,9 +541,12 @@ function vaultImportTool(scope: Scope, bw: BwState): ToolDefinition<typeof vault
507
541
 
508
542
  interface SaveRequest {
509
543
  name?: string;
544
+ type?: ItemType;
510
545
  username?: string;
511
546
  uri?: string;
512
547
  notes?: string;
548
+ /** The type's own fields, NAME=VALUE; a value of `undefined` means "typed in a dialog". */
549
+ fields?: Record<string, string | undefined>;
513
550
  signal?: AbortSignal;
514
551
  }
515
552
 
@@ -518,23 +555,38 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
518
555
  if (!(await ensureUnlocked(scope, ctx, req.signal))) return LOCKED;
519
556
  let name = req.name?.trim() ?? "";
520
557
  if (!name) {
521
- const entered = await promptText(dialogs(ctx), "ai-vault · 新条目", "名称", req.signal);
558
+ const entered = await promptText(dialogs(ctx), tr("ai-vault · new entry", "ai-vault · 新条目"), tr("name", "名称"), req.signal);
522
559
  name = entered?.trim() ?? "";
523
560
  }
524
561
  if (!name) return "cancelled: no entry name";
525
562
 
526
- const args = ["add", "--name", name, "--token", scope.token!];
563
+ const kind = req.type ?? "login";
564
+ const args = ["add", "--name", name, "--type", kind, "--token", scope.token!];
527
565
  if (req.username !== undefined) args.push("--username", req.username);
528
566
  if (req.uri?.trim()) args.push("--uri", req.uri.trim());
529
567
  if (req.notes?.trim()) args.push("--notes", req.notes.trim());
530
- let stdin: string | undefined;
531
- for (let attempt = 0; attempt < 5; attempt++) {
568
+ const secrets = new Map<string, string>();
569
+ const shown: string[] = [];
570
+ for (const [field, value] of Object.entries(req.fields ?? {})) {
571
+ if (value === undefined) shown.push(`${field} ••••`);
572
+ else {
573
+ args.push("--field", `${field}=${value}`);
574
+ shown.push(`${field} ${isSecretField(kind, field) ? "••••" : forDialog(value, 120)}`);
575
+ }
576
+ }
577
+ const flush = () => {
578
+ // --secret args are re-added on every attempt: the CLI is stateless.
579
+ for (let i = args.length - 1; i >= 0; i--) if (args[i] === "--secret") args.splice(i, 2);
580
+ for (const [field, value] of secrets) args.push("--secret", `${field}=${value}`);
581
+ };
582
+ for (let attempt = 0; attempt < 8; attempt++) {
583
+ flush();
532
584
  try {
533
- const run = await cli.run([...args, "--json"], { stdin, signal: req.signal });
534
- const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean };
585
+ const run = await cli.run([...args, "--json"], { signal: req.signal });
586
+ const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean; type?: string };
535
587
  if (saved.created) scope.items += 1;
536
588
  setStatus(ctx, scope);
537
- return `saved "${saved.item ?? name}" (password entered in the dialog, not shown)`;
589
+ return `saved "${saved.item ?? name}" as a ${saved.type ?? kind} (hidden fields entered in dialogs, not shown)`;
538
590
  } catch (error) {
539
591
  if (!(error instanceof CliError) || !error.needsUi) {
540
592
  if (error instanceof CliError && error.auth) scope.token = undefined;
@@ -542,16 +594,20 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
542
594
  }
543
595
  if (error.needsUi === "confirm") {
544
596
  const meta = [
545
- req.username?.trim() ? `用户名: ${forDialog(req.username, 60)}` : "",
597
+ ...shown,
598
+ req.username?.trim() ? tr(`Username: ${forDialog(req.username, 60)}`, `用户名: ${forDialog(req.username, 60)}`) : "",
546
599
  req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
547
- req.notes?.trim() ? `备注: ${forDialog(req.notes, 120)}` : "",
600
+ req.notes?.trim() ? tr(`Notes: ${forDialog(req.notes, 120)}`, `备注: ${forDialog(req.notes, 120)}`) : "",
548
601
  ]
549
602
  .filter(Boolean)
550
603
  .join("\n");
551
604
  const ok = await confirmWindow(
552
605
  dialogs(ctx),
553
- "ai-vault · 保存到本地库",
554
- `保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
606
+ tr("ai-vault · save to local store", "ai-vault · 保存到本地库"),
607
+ tr(
608
+ `Save the ${kind} entry "${forDialog(name)}".${meta ? `\n${meta}` : ""}\nA window opens next for each hidden field. Nothing enters the conversation.`,
609
+ `保存${kind}条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n接下来每个隐藏字段弹一个窗口。密码不会进入对话。`,
610
+ ),
555
611
  req.signal,
556
612
  );
557
613
  if (!ok) return `user denied saving "${name}"`;
@@ -559,15 +615,16 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
559
615
  continue;
560
616
  }
561
617
  if (error.needsUi === "text") {
562
- const entered = await promptText(dialogs(ctx), `ai-vault · ${name}`, "用户名(可留空)", req.signal);
618
+ const entered = await promptText(dialogs(ctx), `ai-vault · ${name}`, tr("username (optional)", "用户名(可留空)"), req.signal);
563
619
  if (entered === undefined) return "cancelled";
564
620
  args.push("--username", entered);
565
621
  continue;
566
622
  }
567
- const password = await promptSecret(dialogs(ctx), "ai-vault · 密码", name, req.signal);
623
+ // needsUi === "password": one hidden field at a time, named by the CLI.
624
+ const field = error.field ?? ITEM_TYPES[kind].primary ?? "password";
625
+ const password = await promptSecret(dialogs(ctx), tr("ai-vault · password", "ai-vault · 密码"), `${name} · ${field}`, req.signal);
568
626
  if (!password) return "cancelled: no password entered";
569
- args.push("--password-stdin");
570
- stdin = `${password}\n`;
627
+ secrets.set(field, password);
571
628
  }
572
629
  }
573
630
  return "cancelled: the save dialog did not settle";
@@ -594,22 +651,22 @@ async function importBitwarden(
594
651
  .slice(0, 15)
595
652
  .map((item) => `• ${item.name}${item.username ? ` user:${item.username}` : ""}${item.uri ? ` ${item.uri}` : ""}`)
596
653
  .join("\n");
597
- const more = meta.length > 15 ? `\n… 还有 ${meta.length - 15} 条` : "";
654
+ const more = meta.length > 15 ? tr(`\n… 还yes ${meta.length - 15} 条`, `\n… 还有 ${meta.length - 15} 条`) : "";
598
655
  const allowed = await confirmWindow(
599
656
  dialogs(ctx),
600
- "ai-vault · 从 Bitwarden 导入",
601
- `匹配 ${meta.length} 条。其中带密码的登录项会写入本地加密库,同名条目会被更新。\n\n${shown}${more}\n\n允许导入?`,
657
+ tr("ai-vault · import from Bitwarden", "ai-vault · 从 Bitwarden 导入"),
658
+ tr(`Matched ${meta.length} 条。其中带密码的登录项会写入本地加密库,同名条目会被更新。\n\n${shown}${more}\n\nImport?`, `匹配 ${meta.length} 条。其中带密码的登录项会写入本地加密库,同名条目会被更新。\n\n${shown}${more}\n\n允许导入?`),
602
659
  signal,
603
660
  );
604
661
  if (!allowed) return { text: "user denied the Bitwarden import", ok: false, count: 0 };
605
662
  let drafts;
606
663
  try {
607
- drafts = await pullBitwardenLogins(bw, ctx, search, signal);
664
+ drafts = await pullBitwardenItems(bw, ctx, search, signal);
608
665
  } catch (error) {
609
666
  return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
610
667
  }
611
668
  if (drafts.length === 0) {
612
- return { text: "matched items have no login password; nothing imported", ok: false, count: 0 };
669
+ return { text: "nothing matched; nothing imported", ok: false, count: 0 };
613
670
  }
614
671
  try {
615
672
  const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
@@ -633,21 +690,21 @@ async function importBitwarden(
633
690
  // ---------------------------------------------------------------- commands
634
691
 
635
692
  const HELP = [
636
- "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
637
- "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
638
- "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
639
- "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)",
640
- "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)",
641
- "/vault status 状态与授权剩余时间",
642
- "/vault list 本地条目元数据",
643
- "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
644
- '/vault remove <名称> 删除本地条目(带空格的名称加引号:"GitHub (2)")',
645
- "/vault grant <名称> [分钟] 手动授权读取(默认 5 分钟,上限 60)",
646
- "/vault revoke <名称|all> 撤销授权",
647
- "/vault audit [n] 最近 n 条审计(默认 30)",
648
- "/vault import <bitwarden.json> 从 Bitwarden 未加密 JSON 导出导入",
649
- "/vault import-bw [搜索词] 直接从 bw CLI 导入登录项(先弹窗确认)",
650
- "/bw status|unlock|lock|clear 在线 Bitwarden 会话(见 bw_* 工具)",
693
+ tr("/vault init create the machine-wide encrypted store (a dialog sets the master password)", "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)"),
694
+ tr("/vault unlock | lock unlock / lock (clears this session's grants)", "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)"),
695
+ tr("/vault mode [never|time|session] show/switch the unlock policy (switching needs the master password)", "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)"),
696
+ tr("/vault settings [key value] show/change settings (vault.unlock, bitwarden.*, ente.* …)", "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)"),
697
+ tr("/vault ente-key save Ente's ENTE_CLI_VAULT_KEY (no keychain, no login)", "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)"),
698
+ tr("/vault status state and grants left", "/vault status 状态与授权剩余时间"),
699
+ tr("/vault list local entry metadata", "/vault list 本地条目元数据"),
700
+ tr("/vault add [name] add a local entry (username and password typed in a dialog)", "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)"),
701
+ tr('/vault remove <name> delete an entry (quote names with spaces: "GitHub (2)")', '/vault remove <名称> 删除本地条目(带空格的名称加引号:"GitHub (2)")'),
702
+ tr("/vault grant <name> [minutes] a standing read grant (default 5 min, max 60)", "/vault grant <名称> [分钟] 手动授权读取(默认 5 分钟,上限 60)"),
703
+ tr("/vault revoke <name|all> revoke grants", "/vault revoke <名称|all> 撤销授权"),
704
+ tr("/vault audit [n] the last n audit lines (default 30)", "/vault audit [n] 最近 n 条审计(默认 30)"),
705
+ tr("/vault import <bitwarden.json> import an unencrypted Bitwarden JSON export", "/vault import <bitwarden.json> 从 Bitwarden 未加密 JSON 导出导入"),
706
+ tr("/vault import-bw [search] import logins straight from the bw CLI (asks first)", "/vault import-bw [搜索词] 直接从 bw CLI 导入登录项(先弹窗确认)"),
707
+ tr("/bw status|unlock|lock|clear the live Bitwarden session (see the bw_* tools)", "/bw status|unlock|lock|clear 在线 Bitwarden 会话(见 bw_* 工具)"),
651
708
  ].join("\n");
652
709
 
653
710
  /** Split a command line into words; quotes keep a name such as "GitHub (2)" intact. */
@@ -666,7 +723,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
666
723
  scope.token = result.token;
667
724
  scope.items = 0;
668
725
  setStatus(ctx, scope);
669
- note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
726
+ note(ctx, tr(`ai-vault created: ${cli.dir}/store.json`, `ai-vault 已创建: ${cli.dir}/store.json`));
670
727
  };
671
728
  try {
672
729
  finish(await cli.open<UnlockResult>("init", ["--requester", label]));
@@ -681,14 +738,14 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
681
738
  return;
682
739
  }
683
740
  }
684
- const pass = await promptSecret(dialogs(ctx), "ai-vault · 创建主密码", "至少 8 位");
741
+ const pass = await promptSecret(dialogs(ctx), tr("ai-vault · set master password", "ai-vault · 创建主密码"), tr("at least 8 characters", "至少 8 位"));
685
742
  if (!pass || pass.length < 8) {
686
- note(ctx, "已取消,或密码短于 8 位", "warning");
743
+ note(ctx, tr("cancelled, or the password is shorter than 8 characters", "已取消,或密码短于 8 位"), "warning");
687
744
  return;
688
745
  }
689
- const again = await promptSecret(dialogs(ctx), "ai-vault · 确认主密码", "再输入一次");
746
+ const again = await promptSecret(dialogs(ctx), tr("ai-vault · confirm master password", "ai-vault · 确认主密码"), tr("type it again", "再输入一次"));
690
747
  if (again !== pass) {
691
- note(ctx, "两次主密码不一致,已取消", "warning");
748
+ note(ctx, tr("the two passwords do not match; cancelled", "两次主密码不一致,已取消"), "warning");
692
749
  return;
693
750
  }
694
751
  try {
@@ -701,20 +758,20 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
701
758
  function settingsText(s: Settings): string {
702
759
  const persisted = s.bitwarden.persisted
703
760
  ? s.bitwarden.expiresAt
704
- ? `有(${Math.max(0, Math.round((s.bitwarden.expiresAt - Date.now()) / 60_000))} 分钟后过期)`
705
- : "有(不过期)"
706
- : "无";
761
+ ? tr(`yes(${Math.max(0, Math.round((s.bitwarden.expiresAt - Date.now()) / 60_000))} 分钟后过期)`, `有(${Math.max(0, Math.round((s.bitwarden.expiresAt - Date.now()) / 60_000))} 分钟后过期)`)
762
+ : tr("yes (no expiry)", "有(不过期)")
763
+ : tr("no", "无");
707
764
  return [
708
765
  `vault.unlock: ${s.vault.unlock} (never | time | session)`,
709
- `vault.hours: ${s.vault.hours} (time 模式用)`,
710
- `vault 机器级会话: ${s.vault.auto ? "有(免密)" : "无"}`,
766
+ tr(`vault.hours: ${s.vault.hours} (time mode)`, `vault.hours: ${s.vault.hours} (time 模式用)`),
767
+ tr(`vault machine-wide session: ${s.vault.auto ? "yes (no password)" : "no"}`, `vault 机器级会话: ${s.vault.auto ? "有(免密)" : "无"}`),
711
768
  `bitwarden.unlock: ${s.bitwarden.unlock} (never | time | session)`,
712
769
  `bitwarden.hours: ${s.bitwarden.hours}`,
713
770
  `bitwarden.import: ${s.bitwarden.import} (ask | always | never)`,
714
- `bitwarden 已落盘的会话: ${persisted}`,
771
+ tr(`bitwarden persisted session: ${persisted}`, `bitwarden 已落盘的会话: ${persisted}`),
715
772
  `ente.unlock: ${s.ente.unlock} (never | time | session)`,
716
773
  `ente.hours: ${s.ente.hours}`,
717
- `ente 已落盘的密钥: ${s.ente.persisted ? "有" : "无"}`,
774
+ tr(`ente persisted key: ${s.ente.persisted ? "yes" : "no"}`, `ente 已落盘的密钥: ${s.ente.persisted ? "有" : "无"}`),
718
775
  ].join("\n");
719
776
  }
720
777
 
@@ -739,7 +796,7 @@ function commandHandler(scope: Scope, bw: BwState) {
739
796
  case "lock": {
740
797
  await lockNow(scope);
741
798
  setStatus(ctx, scope);
742
- note(ctx, "本地库已锁定,授权已清空");
799
+ note(ctx, tr("the local store is locked; grants cleared", "本地库已锁定,授权已清空"));
743
800
  return;
744
801
  }
745
802
  case "status": {
@@ -754,10 +811,10 @@ function commandHandler(scope: Scope, bw: BwState) {
754
811
  : "never";
755
812
  const how =
756
813
  status.mode === "never"
757
- ? "never(免密)"
814
+ ? tr("never (no password)", "never(免密)")
758
815
  : status.mode === "time"
759
- ? `time(每 ${status.hours}h 要一次密码)`
760
- : "session(每个会话一次)";
816
+ ? tr(`time (the password every ${status.hours}h)`, `time(每 ${status.hours}h 要一次密码)`)
817
+ : tr("session (once per session)", "session(每个会话一次)");
761
818
  const lines = [
762
819
  `store: ${cli.dir}/store.json`,
763
820
  `session: ${status.requester}`,
@@ -789,16 +846,16 @@ function commandHandler(scope: Scope, bw: BwState) {
789
846
  case "ente-key": {
790
847
  // Ente's unattended key: generated by `ente vault key generate`.
791
848
  // Saved sealed, so `ente.unlock = never | time` can use it.
792
- const key = await promptSecret(dialogs(ctx), "ai-vault · Ente 密钥", "ente vault key generate 输出的密钥");
849
+ const key = await promptSecret(dialogs(ctx), tr("ai-vault · Ente key", "ai-vault · Ente 密钥"), tr("the key printed by ente vault key generate", "ente vault key generate 输出的密钥"));
793
850
  if (!key) {
794
- note(ctx, "已取消", "warning");
851
+ note(ctx, tr("cancelled", "已取消"), "warning");
795
852
  return;
796
853
  }
797
854
  try {
798
855
  const args = ["ente-session", "put"];
799
856
  await cli.run(args, { stdin: key });
800
857
  forgetSettings();
801
- note(ctx, "已保存(封存)。现在可以设置 /vault settings ente.unlock never");
858
+ note(ctx, tr("saved (sealed). You can now set /vault settings ente.unlock never", "已保存(封存)。现在可以设置 /vault settings ente.unlock never"));
802
859
  } catch (error) {
803
860
  note(ctx, `ai-vault: ${describe(error)}`, "error");
804
861
  }
@@ -820,14 +877,14 @@ function commandHandler(scope: Scope, bw: BwState) {
820
877
  // `vault.unlock` opens its own password window (or answers
821
878
  // needs-ui); the other keys do not prompt at all.
822
879
  const run = await cli.withPassword(["settings", key, value], () =>
823
- promptSecret(dialogs(ctx), "ai-vault · 主密码", "改变解锁模式需要验证"),
880
+ promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
824
881
  );
825
882
  forgetSettings();
826
883
  const updated = JSON.parse(run.stdout) as Settings;
827
884
  if (key.startsWith("vault.")) await lockNow(scope);
828
885
  note(ctx, settingsText(updated));
829
886
  } catch (error) {
830
- note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
887
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
831
888
  }
832
889
  return;
833
890
  }
@@ -840,10 +897,10 @@ function commandHandler(scope: Scope, bw: BwState) {
840
897
  ctx,
841
898
  [
842
899
  `mode: ${current.mode}`,
843
- `hours: ${current.hours}(time 模式用)`,
844
- `machine-wide session: ${current.auto ? "yes(免密)" : "no"}`,
900
+ tr(`hours: ${current.hours}(time mode)`, `hours: ${current.hours}(time 模式用)`),
901
+ `machine-wide session: ${current.auto ? tr("yes (no password)", "yes(免密)") : "no"}`,
845
902
  "",
846
- "/vault mode never|time|session [小时] 切换(要主密码)",
903
+ tr("/vault mode never|time|session [hours] switch (needs the master password)", "/vault mode never|time|session [小时] 切换(要主密码)"),
847
904
  ].join("\n"),
848
905
  );
849
906
  } catch (error) {
@@ -852,13 +909,13 @@ function commandHandler(scope: Scope, bw: BwState) {
852
909
  return;
853
910
  }
854
911
  if (!["never", "time", "session", "no-password"].includes(sub)) {
855
- note(ctx, "用法: /vault mode [never|time|session] [小时]", "warning");
912
+ note(ctx, tr("usage: /vault mode [never|time|session] [hours]", "用法: /vault mode [never|time|session] [小时]"), "warning");
856
913
  return;
857
914
  }
858
915
  const args = ["mode", "set", sub];
859
916
  if (hoursArg) args.push("--hours", hoursArg);
860
917
  try {
861
- const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), "ai-vault · 主密码", "切换解锁模式"));
918
+ const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("switch the unlock policy", "切换解锁模式")));
862
919
  const result = JSON.parse(run.stdout) as { mode: UnlockModeName; hours: number; auto: boolean };
863
920
  forgetSettings();
864
921
  await lockNow(scope);
@@ -867,13 +924,13 @@ function commandHandler(scope: Scope, bw: BwState) {
867
924
  setStatus(ctx, scope);
868
925
  const how =
869
926
  result.mode === "never"
870
- ? "以后免密(密钥已写盘,任何能读你文件的程序都能读到库里的密码)"
927
+ ? tr("no password from now on (the key is on disk: anything that can read your files can read every password in the store)", "以后免密(密钥已写盘,任何能读你文件的程序都能读到库里的密码)")
871
928
  : result.mode === "time"
872
- ? `以后每 ${result.hours} 小时要一次密码`
873
- : "以后每个会话要一次密码";
929
+ ? tr(`the password is asked again every ${result.hours} hours from now on`, `以后每 ${result.hours} 小时要一次密码`)
930
+ : tr("the password is asked once per session from now on", "以后每个会话要一次密码");
874
931
  note(ctx, `mode → ${result.mode},${how}`);
875
932
  } catch (error) {
876
- note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
933
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
877
934
  }
878
935
  return;
879
936
  }
@@ -890,7 +947,30 @@ function commandHandler(scope: Scope, bw: BwState) {
890
947
  return;
891
948
  }
892
949
  case "add": {
893
- const text = await saveLocalEntry(scope, ctx, { name: rest.join(" ") || undefined });
950
+ // /vault add [type:]name [field=value ...] [field] — a bare
951
+ // `field` is typed in a dialog. /vault add card:Visa brand=Visa code
952
+ const [first, ...pairs] = rest;
953
+ let type: ItemType | undefined;
954
+ let name = first ?? "";
955
+ const m = /^([a-z]+):(.+)$/.exec(first ?? "");
956
+ if (m) {
957
+ const parsed = parseItemType(m[1]);
958
+ if (parsed) {
959
+ type = parsed;
960
+ name = m[2] ?? name;
961
+ }
962
+ }
963
+ const fields: Record<string, string | undefined> = {};
964
+ let notes: string | undefined;
965
+ for (const pair of pairs) {
966
+ const eq = pair.indexOf("=");
967
+ const key = eq < 0 ? pair : pair.slice(0, eq);
968
+ const value = eq < 0 ? "" : pair.slice(eq + 1);
969
+ if (!key) continue;
970
+ if (key === "notes" || key === "note") notes = value;
971
+ else fields[key] = value === "" ? undefined : value;
972
+ }
973
+ const text = await saveLocalEntry(scope, ctx, { name: name.trim() || undefined, type, fields, notes });
894
974
  note(ctx, text, text.startsWith("saved ") ? "info" : "warning");
895
975
  return;
896
976
  }
@@ -898,7 +978,7 @@ function commandHandler(scope: Scope, bw: BwState) {
898
978
  const name = rest.join(" ");
899
979
  if (!(await ensureUnlocked(scope, ctx))) return;
900
980
  if (!name) {
901
- note(ctx, "用法: /vault remove <名称>", "warning");
981
+ note(ctx, tr("usage: /vault remove <name>", "用法: /vault remove <名称>"), "warning");
902
982
  return;
903
983
  }
904
984
  const args = ["remove", name, "--token", scope.token!];
@@ -912,7 +992,7 @@ function commandHandler(scope: Scope, bw: BwState) {
912
992
  note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
913
993
  return;
914
994
  }
915
- const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${forDialog(name)}」?删除后无法恢复。`);
995
+ const sure = await confirmWindow(dialogs(ctx), tr("ai-vault · delete entry", "ai-vault · 删除条目"), tr(`Delete "${forDialog(name)}"? This cannot be undone.`, `删除「${forDialog(name)}」?删除后无法恢复。`));
916
996
  if (!sure) return;
917
997
  try {
918
998
  const result = await cli.json<RemovingResult>([...args, "--yes"]);
@@ -932,7 +1012,7 @@ function commandHandler(scope: Scope, bw: BwState) {
932
1012
  const minutes = rest.length > 1 && /^\d+$/.test(last) ? rest.pop() : undefined;
933
1013
  const name = rest.join(" ");
934
1014
  if (!(await ensureUnlocked(scope, ctx)) || !name) {
935
- note(ctx, "先解锁;用法: /vault grant <名称> [分钟](带空格的名称加引号)", "warning");
1015
+ note(ctx, tr("unlock first; usage: /vault grant <name> [minutes] (quote names with spaces)", "先解锁;用法: /vault grant <名称> [分钟](带空格的名称加引号)"), "warning");
936
1016
  return;
937
1017
  }
938
1018
  const args = ["grant", name, "--token", scope.token!];
@@ -940,7 +1020,7 @@ function commandHandler(scope: Scope, bw: BwState) {
940
1020
  try {
941
1021
  // A standing grant costs the master password, like a mode change.
942
1022
  const run = await cli.withPassword(args, () =>
943
- promptSecret(dialogs(ctx), "ai-vault · 授权读取", "主密码(给这条条目 N 分钟免确认)"),
1023
+ promptSecret(dialogs(ctx), tr("ai-vault · grant read", "ai-vault · 授权读取"), tr("master password (lets this entry be read without confirmation for N minutes)", "主密码(给这条条目 N 分钟免确认)")),
944
1024
  );
945
1025
  const result = JSON.parse(run.stdout) as { name: string; minutes: number };
946
1026
  setStatus(ctx, scope, "·granted");
@@ -957,7 +1037,7 @@ function commandHandler(scope: Scope, bw: BwState) {
957
1037
  if (target === "all") args.push("--all");
958
1038
  else if (target) args.push(target);
959
1039
  else {
960
- note(ctx, "用法: /vault revoke <名称|all>", "warning");
1040
+ note(ctx, tr("usage: /vault revoke <name|all>", "用法: /vault revoke <名称|all>"), "warning");
961
1041
  return;
962
1042
  }
963
1043
  try {
@@ -986,7 +1066,7 @@ function commandHandler(scope: Scope, bw: BwState) {
986
1066
  case "import": {
987
1067
  const path = rest.join(" ");
988
1068
  if (!path) {
989
- note(ctx, "用法: /vault import <bitwarden-export.json>", "warning");
1069
+ note(ctx, tr("usage: /vault import <bitwarden-export.json>", "用法: /vault import <bitwarden-export.json>"), "warning");
990
1070
  return;
991
1071
  }
992
1072
  if (!(await ensureUnlocked(scope, ctx))) return;
@@ -1003,8 +1083,8 @@ function commandHandler(scope: Scope, bw: BwState) {
1003
1083
  }
1004
1084
  const sure = await confirmWindow(
1005
1085
  dialogs(ctx),
1006
- "ai-vault · 从 Bitwarden 导入",
1007
- `导入 ${path} 里的 Bitwarden 登录项?同名条目会被更新。`,
1086
+ tr("ai-vault · import from Bitwarden", "ai-vault · 从 Bitwarden 导入"),
1087
+ tr(`Import ${path} Bitwarden logins? Same-name entries are updated.`, `导入 ${path} 里的 Bitwarden 登录项?同名条目会被更新。`),
1008
1088
  );
1009
1089
  if (!sure) return;
1010
1090
  try {
@@ -1043,7 +1123,7 @@ export default function aiVault(pi: ExtensionAPI): void {
1043
1123
  // Ente Auth: the `ente` CLI keeps its own login; these tools only read codes.
1044
1124
  registerEnte(pi);
1045
1125
  pi.registerCommand("vault", {
1046
- description: "本地密码库 + Bitwarden 导入(/vault help)",
1126
+ description: tr("local secret store + Bitwarden import (/vault help)", "本地密码库 + Bitwarden 导入(/vault help)"),
1047
1127
  handler: commandHandler(scope, bw),
1048
1128
  });
1049
1129
  // A transcript that starts fresh (/new, /fork) must not inherit this unlock