pi-ai-vault 0.10.0 → 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.
package/README.md CHANGED
@@ -31,7 +31,7 @@ Do not install `pi-bitwarden` or `omp-vault` as well: they register the same `bw
31
31
  |---|---|---|
32
32
  | `vault_list` | local store metadata | no |
33
33
  | `vault_get` | read one: local store first, then Bitwarden; a Bitwarden hit follows `bitwarden.import` (ask / import / read once) | yes, user-approved on the spot |
34
- | `vault_add` | store one; the password is typed in a dialog | no |
34
+ | `vault_add` | store one, any Bitwarden type (login, note, card, identity, sshkey, bankaccount, driverslicense, passport); secret fields are typed in a dialog | no |
35
35
  | `vault_import` | copy Bitwarden logins into the local store (asks first) | no |
36
36
  | `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | live Bitwarden through the `bw` CLI | no (`bw_reveal` excepted) |
37
37
  | `bw_inject` | inject into the bash env (**pi only**; omp does not register it) | no |
package/README.zh.md CHANGED
@@ -29,7 +29,7 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
29
29
  |---|---|---|
30
30
  | `vault_list` | 本地库条目元数据 | 否 |
31
31
  | `vault_get` | 读一条:**先本地库,再 Bitwarden**;Bitwarden 命中会问「读一次 / 导入 ai-vault」 | 是,用户当场允许 |
32
- | `vault_add` | 存一条;密码由用户在弹出的窗口里输入 | 否 |
32
+ | `vault_add` | 存一条,Bitwarden 的全部类型(登录、笔记、银行卡、身份、SSH 密钥、银行账户、驾照、护照);秘密字段在弹窗里输 | 否 |
33
33
  | `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | 否 |
34
34
  | `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | 在线 Bitwarden(`bw` CLI) | 否,`bw_reveal` 除外 |
35
35
  | `bw_inject` | 注入 bash 环境(**仅 pi**,omp 不注册) | 否 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store, live Bitwarden and Ente Auth. Works in pi and in omp (the omp fork reads the same manifest).",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "security"
26
26
  ],
27
27
  "dependencies": {
28
- "@xiaolikt/ai-vault": "0.10.0"
28
+ "@xiaolikt/ai-vault": "0.11.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
package/src/bitwarden.ts CHANGED
@@ -52,7 +52,8 @@ import path from "node:path";
52
52
  import type { ExtensionAPI, ExtensionContext, ToolDefinition, ToolResultEventResult } from "@earendil-works/pi-coding-agent";
53
53
  import { createBashTool } from "@earendil-works/pi-coding-agent";
54
54
  import { Type } from "typebox";
55
- import { bitwardenLogins, filterLogins, type LoginDraft } from "./import-map.js";
55
+ import { bitwardenItems, filterItems } from "./import-map.js";
56
+ import type { Draft } from "./types.js";
56
57
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
57
58
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
58
59
  import { getSettingsSafe, settingsCli } from "./settings.js";
@@ -152,12 +153,16 @@ const BW_LOGIN_HINT =
152
153
  type BwItem = {
153
154
  id?: string;
154
155
  name?: string;
156
+ type?: number;
155
157
  notes?: string;
156
158
  login?: { username?: string; password?: string; totp?: string; uris?: { uri?: string }[] };
157
- fields?: { name?: string; value?: string }[];
159
+ card?: { cardholderName?: string; brand?: string; number?: string; code?: string };
160
+ identity?: { title?: string; firstName?: string; lastName?: string; email?: string; phone?: string };
161
+ sshKey?: { publicKey?: string; keyFingerprint?: string };
162
+ fields?: { name?: string; value?: string; type?: number }[];
158
163
  };
159
164
  /** Only metadata is cached; secrets stay in the vault process until needed. */
160
- type LiteItem = { id: string; name: string; username: string; uri: string };
165
+ type LiteItem = { id: string; name: string; username: string; uri: string; type: string };
161
166
  type InjectedSecret = { value: string; item: string; field: string; at: number };
162
167
 
163
168
  /**
@@ -624,12 +629,23 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
624
629
  return pending;
625
630
  }
626
631
 
632
+ const BW_TYPE_NAMES: Record<number, string> = { 1: "login", 2: "note", 3: "card", 4: "identity", 5: "sshKey", 6: "bankAccount", 7: "driversLicense", 8: "passport" };
633
+
627
634
  function toLite(raw: BwItem): LiteItem {
635
+ const type = BW_TYPE_NAMES[raw.type ?? 1] ?? `type-${raw.type}`;
636
+ // The identifying, non-secret line of each type: username for a login,
637
+ // cardholder for a card, a person's name for an identity, and so on.
638
+ const who =
639
+ raw.login?.username ??
640
+ raw.card?.cardholderName ??
641
+ (raw.identity ? [raw.identity.title, raw.identity.firstName, raw.identity.lastName].filter(Boolean).join(" ") : "") ??
642
+ "";
628
643
  return {
629
644
  id: raw.id ?? "",
630
645
  name: raw.name ?? "",
631
- username: raw.login?.username ?? "",
646
+ username: who,
632
647
  uri: raw.login?.uris?.[0]?.uri ?? "",
648
+ type,
633
649
  };
634
650
  }
635
651
 
@@ -796,34 +812,35 @@ export async function queryBitwarden(
796
812
  }
797
813
 
798
814
  /**
799
- * Login items that have a password, ready to store in the local vault.
800
- * Call only after the user has agreed to the import — this reads secrets.
815
+ * Every item that matches `search`, ready to store in the local vault: all
816
+ * types, field for field. Call only after the user has agreed to the import —
817
+ * this reads secrets.
801
818
  */
802
- export async function pullBitwardenLogins(
819
+ export async function pullBitwardenItems(
803
820
  st: BwState,
804
821
  ctx: ExtensionContext | undefined,
805
822
  search: string | undefined,
806
823
  signal?: AbortSignal,
807
- ): Promise<LoginDraft[]> {
824
+ ): Promise<Draft[]> {
808
825
  const session = await ensureUnlocked(st, ctx, signal);
809
826
  const raw: unknown = await runBwJson(["list", "items"], session, signal);
810
- return filterLogins(bitwardenLogins(raw), search);
827
+ return filterItems(bitwardenItems(raw), search);
811
828
  }
812
829
 
813
- export type BitwardenLoginHit = { id: string; name: string; username: string; password: string; uris: string[] };
830
+ export type BitwardenHit = { draft: Draft; label: string };
814
831
 
815
832
  /**
816
- * Look one login up by name/URI and return its password, with no window of its
817
- * own: the caller shows the user what was found and asks whether to read it.
818
- * `undefined` means "no such item"; an ambiguous reference throws with the
819
- * candidates so the model can pick one.
833
+ * Look one item up, of any type, and return it as a draft with its secrets,
834
+ * with no window of its own: the caller shows the user what was found and asks
835
+ * whether to read it. `undefined` means "no such item"; an ambiguous reference
836
+ * throws with the candidates so the model can pick one.
820
837
  */
821
- export async function lookupBitwardenLogin(
838
+ export async function lookupBitwardenItem(
822
839
  st: BwState,
823
840
  ctx: ExtensionContext | undefined,
824
841
  ref: string,
825
842
  signal?: AbortSignal,
826
- ): Promise<BitwardenLoginHit | undefined> {
843
+ ): Promise<BitwardenHit | undefined> {
827
844
  const session = await ensureUnlocked(st, ctx, signal);
828
845
  let item: LiteItem;
829
846
  try {
@@ -832,14 +849,12 @@ export async function lookupBitwardenLogin(
832
849
  if (e instanceof Error && /^No Bitwarden item matches/.test(e.message)) return undefined;
833
850
  throw e;
834
851
  }
835
- const secret = await secretOf(session, item, "password", signal);
836
- return {
837
- id: item.id ?? "",
838
- name: item.name || "unnamed",
839
- username: item.username,
840
- password: secret.value,
841
- uris: item.uri ? [item.uri] : [],
842
- };
852
+ if (!item.id) throw new Error(`Bitwarden item "${item.name}" has no id, so it cannot be read.`);
853
+ const full = (await runBwJson(["get", "item", item.id], session, signal)) as unknown;
854
+ const [draft] = bitwardenItems([full]);
855
+ if (!draft) return undefined;
856
+ const who = item.username ? ` ${item.username}` : "";
857
+ return { draft, label: `${draft.name}${who} (${item.type})` };
843
858
  }
844
859
 
845
860
  function normalizeEnvName(raw: string): string {
package/src/cli.ts CHANGED
@@ -34,14 +34,19 @@ export interface CliRun {
34
34
 
35
35
  /** Non-zero exit from the CLI, with the meaning of the code preserved. */
36
36
  export class CliError extends Error {
37
+ /** For `needsUi === "password"`: the hidden field the CLI wants next. */
38
+ readonly field: string | undefined;
39
+
37
40
  constructor(
38
41
  readonly code: number,
39
42
  readonly needsUi: UiStep | undefined,
40
43
  message: string,
41
44
  readonly stderr: string,
45
+ field?: string,
42
46
  ) {
43
47
  super(message);
44
48
  this.name = "CliError";
49
+ this.field = field;
45
50
  }
46
51
 
47
52
  get denied(): boolean {
@@ -92,7 +97,7 @@ export function resolveBinary(): string | undefined {
92
97
  return undefined;
93
98
  }
94
99
 
95
- const NEEDS_UI = /^needs-ui:\s*(\w+)/m;
100
+ const NEEDS_UI = /^needs-ui:\s*(\w+)(?:\s+field=(\S+))?/m;
96
101
 
97
102
  function message(stderr: string, fallback: string): string {
98
103
  const lines = stderr
@@ -194,8 +199,9 @@ export class VaultCli {
194
199
  else child.stdin?.end();
195
200
  });
196
201
  if (run.code !== 0) {
197
- const step = NEEDS_UI.exec(run.stderr)?.[1] as UiStep | undefined;
198
- throw new CliError(run.code, step, message(run.stderr, `ai-vault exited with ${run.code}`), run.stderr);
202
+ const match = NEEDS_UI.exec(run.stderr);
203
+ const step = match?.[1] as UiStep | undefined;
204
+ throw new CliError(run.code, step, message(run.stderr, `ai-vault exited with ${run.code}`), run.stderr, match?.[2]);
199
205
  }
200
206
  return run;
201
207
  }
package/src/import-map.ts CHANGED
@@ -1,91 +1,199 @@
1
1
  /**
2
- * Map a Bitwarden JSON export or `bw list items` payload onto local vault
3
- * entries. Secrets stay in the returned objects for the caller to encrypt;
4
- * this module never writes them.
2
+ * Map a Bitwarden item onto a local vault entry, for every item type, field
3
+ * for field — the same table the CLI's `import.rs` uses, so both import paths
4
+ * (the CLI's `import` and this extension's `import-bw` / `vault_get` fallback)
5
+ * write identical entries.
6
+ *
7
+ * Type numbers and field names are Bitwarden's own, read out of its CLI:
8
+ * 1 login · 2 secureNote · 3 card · 4 identity · 5 sshKey
9
+ * 6 bankAccount · 7 driversLicense · 8 passport (behind its "new item types" flag)
10
+ * A secure note has no fields of its own: its content is the item's `notes`.
5
11
  */
6
- export interface LoginDraft {
7
- name: string;
8
- username?: string;
9
- password: string;
10
- uris: string[];
11
- notes?: string;
12
- /** Bitwarden item id: a re-import updates the same entry even after a rename. */
13
- source?: { kind: "bitwarden"; id: string };
12
+ import type { Draft, Field, ItemType } from "./types.js";
13
+
14
+ export const ITEM_TYPES: Record<ItemType, { code: number; key: string; fields: string[]; primary?: string }> = {
15
+ login: { code: 1, key: "login", fields: ["username", "password", "totp"], primary: "password" },
16
+ secureNote: { code: 2, key: "secureNote", fields: [] },
17
+ card: { code: 3, key: "card", fields: ["cardholderName", "brand", "number", "expMonth", "expYear", "code"], primary: "code" },
18
+ identity: {
19
+ code: 4,
20
+ key: "identity",
21
+ fields: [
22
+ "title", "firstName", "middleName", "lastName", "address1", "address2", "address3", "city", "state",
23
+ "postalCode", "country", "company", "email", "phone", "ssn", "username", "passportNumber", "licenseNumber",
24
+ ],
25
+ },
26
+ sshKey: { code: 5, key: "sshKey", fields: ["privateKey", "publicKey", "keyFingerprint"], primary: "privateKey" },
27
+ bankAccount: {
28
+ code: 6,
29
+ key: "bankAccount",
30
+ fields: ["bankName", "nameOnAccount", "accountType", "accountNumber", "routingNumber", "branchNumber", "pin", "swiftCode", "iban", "bankContactPhone"],
31
+ primary: "pin",
32
+ },
33
+ driversLicense: {
34
+ code: 7,
35
+ key: "driversLicense",
36
+ fields: ["firstName", "middleName", "lastName", "dateOfBirth", "licenseNumber", "issuingCountry", "issuingState", "issueDate", "expirationDate", "issuingAuthority", "licenseClass"],
37
+ },
38
+ passport: {
39
+ code: 8,
40
+ key: "passport",
41
+ fields: [
42
+ "surname", "givenName", "dateOfBirth", "sex", "birthPlace", "nationality", "issuingCountry", "passportNumber",
43
+ "passportType", "nationalIdentificationNumber", "issuingAuthority", "issueDate", "expirationDate",
44
+ ],
45
+ },
46
+ };
47
+
48
+ const BY_CODE = new Map(Object.entries(ITEM_TYPES).map(([name, spec]) => [spec.code, name as ItemType]));
49
+
50
+ /** The item type for Bitwarden's `.type`, as a human types it: note, ssh key, … */
51
+ export function parseItemType(raw: string | undefined): ItemType | undefined {
52
+ if (!raw) return "login";
53
+ const key = raw.toLowerCase().replace(/[^a-z0-9]/g, "");
54
+ const aliases: Record<string, ItemType> = {
55
+ login: "login",
56
+ password: "login",
57
+ note: "secureNote",
58
+ securenote: "secureNote",
59
+ card: "card",
60
+ creditcard: "card",
61
+ identity: "identity",
62
+ person: "identity",
63
+ sshkey: "sshKey",
64
+ ssh: "sshKey",
65
+ key: "sshKey",
66
+ bankaccount: "bankAccount",
67
+ bank: "bankAccount",
68
+ driverslicense: "driversLicense",
69
+ driverlicense: "driversLicense",
70
+ driverslicence: "driversLicense",
71
+ drivinglicence: "driversLicense",
72
+ license: "driversLicense",
73
+ passport: "passport",
74
+ };
75
+ return aliases[key] ?? (key === "" ? "login" : undefined);
14
76
  }
15
77
 
78
+ /** Fields whose value never appears in a listing or a confirm window. */
79
+ export function isSecretField(type: ItemType, field: string): boolean {
80
+ if (["password", "privateKey", "totp", "ssn", "licenseNumber", "passportNumber"].includes(field)) return true;
81
+ if (type === "card") return field === "code" || field === "number";
82
+ if (type === "bankAccount") return ["pin", "accountNumber", "routingNumber"].includes(field);
83
+ if (type === "passport") return field === "nationalIdentificationNumber";
84
+ return false;
85
+ }
86
+
87
+ const asRecord = (value: unknown): Record<string, unknown> | undefined =>
88
+ value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
89
+ const text = (value: unknown): string | undefined => (typeof value === "string" && value.length > 0 ? value : undefined);
90
+
16
91
  function asItems(raw: unknown): unknown[] {
17
92
  if (Array.isArray(raw)) return raw;
18
- if (raw && typeof raw === "object") {
19
- const rec = raw as { encrypted?: unknown; items?: unknown };
20
- // An encrypted export carries ciphertext under `data`, not entries.
93
+ const rec = asRecord(raw);
94
+ if (rec) {
21
95
  if (rec.encrypted === true) {
22
- throw new Error(
23
- "This is an encrypted Bitwarden export. Use `bw export --format json` (password-protected, unencrypted) or /vault import-bw.",
24
- );
96
+ throw new Error("This is an encrypted Bitwarden export. Use `bw export --format json` (unencrypted) or /vault import-bw.");
25
97
  }
26
98
  if (Array.isArray(rec.items)) return rec.items;
27
99
  }
28
100
  throw new Error("Not a Bitwarden export: expected an array of items or an object with `items`.");
29
101
  }
30
102
 
31
- function uriList(login: Record<string, unknown>): string[] {
32
- if (!Array.isArray(login.uris)) return [];
33
- return login.uris.flatMap((entry) => {
34
- if (!entry || typeof entry !== "object" || !("uri" in entry)) return [];
35
- const uri = (entry as { uri?: unknown }).uri;
36
- return typeof uri === "string" && uri ? [uri] : [];
37
- });
103
+ /** Custom fields as Bitwarden stores them: 0 text · 1 hidden · 2 boolean · 3 linked. */
104
+ function customFields(rec: Record<string, unknown>): Field[] | undefined {
105
+ const list = Array.isArray(rec.fields) ? rec.fields : [];
106
+ const out: Field[] = [];
107
+ for (const raw of list) {
108
+ const f = asRecord(raw);
109
+ if (!f) continue;
110
+ out.push({
111
+ name: text(f.name) ?? "",
112
+ value: typeof f.value === "string" ? f.value : "",
113
+ type: typeof f.type === "number" ? f.type : 0,
114
+ ...(typeof f.linkedId === "number" ? { linkedId: String(f.linkedId) } : {}),
115
+ });
116
+ }
117
+ return out.length > 0 ? out : undefined;
38
118
  }
39
119
 
120
+ const cleanName = (raw: unknown): string => {
121
+ const cleaned = (typeof raw === "string" ? raw : "").replace(/[\r\n]+/g, " ").trim().slice(0, 200);
122
+ return cleaned || "unnamed";
123
+ };
124
+
40
125
  /**
41
- * Login items that have a password. Names are sorted, then duplicates become
42
- * `Name (2)`, `Name (3)`, … Each entry keeps its Bitwarden id, so a later
43
- * import updates the same row even when the numbering shifts.
126
+ * Every item of a Bitwarden export (or `bw list items` payload) as a draft.
127
+ * Items are matched to local entries by Bitwarden id, so a re-import updates
128
+ * the same row after a rename. Duplicate names within a type become `Name (2)`.
44
129
  */
45
- export function bitwardenLogins(raw: unknown): LoginDraft[] {
46
- const drafts: LoginDraft[] = [];
130
+ export function bitwardenItems(raw: unknown): Draft[] {
131
+ const drafts: Draft[] = [];
47
132
  for (const item of asItems(raw)) {
48
- if (!item || typeof item !== "object") continue;
49
- const rec = item as Record<string, unknown>;
50
- if (!rec.login || typeof rec.login !== "object") continue;
51
- const login = rec.login as Record<string, unknown>;
52
- const password = typeof login.password === "string" ? login.password : "";
53
- if (!password) continue;
54
- const username = typeof login.username === "string" && login.username ? login.username : undefined;
55
- const notes = typeof rec.notes === "string" && rec.notes ? rec.notes : undefined;
56
- const nameRaw = typeof rec.name === "string" ? rec.name : "";
57
- const name = nameRaw.replace(/[\r\n]+/g, " ").trim().slice(0, 200) || "unnamed";
58
- const id = typeof rec.id === "string" && rec.id ? rec.id : undefined;
133
+ const rec = asRecord(item);
134
+ if (!rec) continue;
135
+ const code = typeof rec.type === "number" ? rec.type : 1;
136
+ const type = BY_CODE.get(code);
137
+ if (!type) throw new Error(`unsupported Bitwarden item type ${code}`);
138
+ const spec = ITEM_TYPES[type];
139
+
140
+ const data: Record<string, string> = {};
141
+ const block = asRecord(rec[spec.key]);
142
+ if (block) {
143
+ for (const [field, value] of Object.entries(block)) {
144
+ if (field === "uris") continue;
145
+ const t = text(value);
146
+ if (t !== undefined) data[field] = t;
147
+ }
148
+ }
149
+ // A login carries username/password at the top level as well; the CLI
150
+ // mirrors those into `data`, so the block here keeps only `totp`.
151
+ if (type === "login") {
152
+ delete data.username;
153
+ delete data.password;
154
+ }
155
+ const loginUsername = type === "login" ? block?.username : undefined;
156
+ const loginPassword = type === "login" ? block?.password : undefined;
157
+ const uris = block && Array.isArray(block.uris)
158
+ ? block.uris.map((u) => text(asRecord(u)?.uri)).filter((u): u is string => u !== undefined)
159
+ : undefined;
160
+ const notes = text(rec.notes);
161
+ const source = text(rec.id) ? { kind: "bitwarden", id: text(rec.id) as string } : undefined;
162
+ const fields = customFields(rec);
163
+
59
164
  drafts.push({
60
- name,
61
- username,
62
- password,
63
- uris: uriList(login),
64
- notes,
65
- ...(id ? { source: { kind: "bitwarden" as const, id } } : {}),
165
+ name: cleanName(rec.name),
166
+ type,
167
+ ...(text(loginUsername) !== undefined ? { username: text(loginUsername) } : {}),
168
+ ...(text(loginPassword) !== undefined ? { password: text(loginPassword) } : {}),
169
+ ...(uris && uris.length > 0 ? { uris } : {}),
170
+ ...(Object.keys(data).length > 0 ? { data } : {}),
171
+ ...(notes !== undefined ? { notes } : {}),
172
+ ...(fields ? { fields } : {}),
173
+ ...(source ? { source } : {}),
66
174
  });
67
175
  }
68
- drafts.sort(
69
- (a, b) =>
70
- a.name.localeCompare(b.name) ||
71
- (a.username ?? "").localeCompare(b.username ?? "") ||
72
- (a.uris[0] ?? "").localeCompare(b.uris[0] ?? ""),
176
+
177
+ drafts.sort((a, b) =>
178
+ a.name.localeCompare(b.name) ||
179
+ a.type.localeCompare(b.type) ||
180
+ (a.username ?? "").localeCompare(b.username ?? ""),
73
181
  );
74
182
  const seen = new Map<string, number>();
75
- for (const item of drafts) {
76
- const key = item.name.toLowerCase();
77
- const n = (seen.get(key) ?? 0) + 1;
78
- seen.set(key, n);
79
- if (n > 1) item.name = `${item.name} (${n})`;
183
+ for (const d of drafts) {
184
+ const k = `${d.name.toLowerCase()}\n${d.type}`;
185
+ const n = (seen.get(k) ?? 0) + 1;
186
+ seen.set(k, n);
187
+ if (n > 1) d.name = `${d.name} (${n})`;
80
188
  }
81
189
  return drafts;
82
190
  }
83
191
 
84
192
  /** Case-insensitive substring match on name, username, and URIs. */
85
- export function filterLogins(items: LoginDraft[], search?: string): LoginDraft[] {
193
+ export function filterItems(items: Draft[], search?: string): Draft[] {
86
194
  const query = (search ?? "").trim().toLowerCase();
87
195
  if (!query) return items;
88
196
  return items.filter((item) =>
89
- `${item.name}\n${item.username ?? ""}\n${item.uris.join("\n")}`.toLowerCase().includes(query),
197
+ `${item.name}\n${item.username ?? ""}\n${(item.uris ?? []).join("\n")}`.toLowerCase().includes(query),
90
198
  );
91
199
  }
package/src/index.ts CHANGED
@@ -15,15 +15,17 @@ import { tr } from "./i18n.js";
15
15
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
16
16
  import { Type } from "typebox";
17
17
  import {
18
- lookupBitwardenLogin,
18
+ lookupBitwardenItem,
19
19
  newBwState,
20
- pullBitwardenLogins,
20
+ pullBitwardenItems,
21
21
  queryBitwarden,
22
22
  registerBitwarden,
23
23
  type BitwardenMeta,
24
24
  type BwState,
25
25
  } from "./bitwarden.js";
26
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";
27
29
  import { registerEnte } from "./ente.js";
28
30
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
29
31
  import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
@@ -308,44 +310,34 @@ async function bitwardenFallback(
308
310
  const missing = localMiss;
309
311
  let hit;
310
312
  try {
311
- hit = await lookupBitwardenLogin(bw, ctx, name, signal);
313
+ hit = await lookupBitwardenItem(bw, ctx, name, signal);
312
314
  } catch (error) {
313
315
  return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
314
316
  }
315
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 ?? ""] ?? "");
316
320
 
317
321
  const asValue = (via: string): ToolOutcome => ({
318
322
  content: [
319
323
  {
320
324
  type: "text" as const,
321
- text: JSON.stringify(
322
- { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
323
- null,
324
- 1,
325
- ),
325
+ text: JSON.stringify({ ...draft, password: secret ?? draft.password, via }, null, 1),
326
326
  },
327
327
  ],
328
- details: { item: hit.name, via },
328
+ details: { item: draft.name, via },
329
329
  });
330
330
 
331
331
  const importIt = async (): Promise<ToolOutcome> => {
332
332
  try {
333
333
  const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
334
- stdin: JSON.stringify([
335
- {
336
- name: hit.name,
337
- username: hit.username || undefined,
338
- password: hit.password,
339
- uris: hit.uris,
340
- source: { kind: "bitwarden", id: hit.id },
341
- },
342
- ]),
334
+ stdin: JSON.stringify([draft]),
343
335
  signal,
344
336
  });
345
337
  scope.items += saved.count;
346
338
  setStatus(ctx, scope);
347
339
  } catch (error) {
348
- 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)}`);
349
341
  }
350
342
  return asValue("imported-from-bitwarden");
351
343
  };
@@ -356,20 +348,25 @@ async function bitwardenFallback(
356
348
  return importIt();
357
349
  }
358
350
 
359
- const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
360
351
  const allow = await confirmWindow(
361
352
  dialogs(ctx),
362
353
  tr("pi-ai-vault · found in Bitwarden", "pi-ai-vault · Bitwarden 里找到"),
363
- tr(`Not in the local store as "${forDialog(name)}」,Bitwarden 里yes:\n${forDialog(label)}\n\n读取这一次吗?`, `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`),
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
+ ),
364
358
  signal,
365
359
  );
366
- 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);
367
361
  if (policy === "never") return asValue("bitwarden-once");
368
362
 
369
363
  const confirmed = await confirmWindow(
370
364
  dialogs(ctx),
371
365
  tr("pi-ai-vault · import into ai-vault", "pi-ai-vault · 导入到 ai-vault"),
372
- tr(`Write "${forDialog(hit.name)}」写进 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`, `把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`),
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
+ ),
373
370
  signal,
374
371
  );
375
372
  return confirmed ? importIt() : asValue("bitwarden-once");
@@ -446,26 +443,62 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
446
443
 
447
444
  const vaultAddParams = Type.Object({
448
445
  name: Type.String({ description: "Entry name to create or update, e.g. 'github'" }),
449
- username: Type.Optional(Type.String({ description: "Account username. Omit to let the user type it in a dialog." })),
450
- uri: Type.Optional(Type.String({ description: "Optional site or host URI" })),
451
- 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
+ ),
452
469
  });
453
470
  function vaultAddTool(scope: Scope): ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> {
454
471
  const tool: ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> = {
455
472
  name: "vault_add",
456
473
  label: "Vault: store a secret via dialog",
457
474
  description:
458
- "Create or update an entry in the machine-wide ai-vault store. You supply the name and optional username, URI, and notes. " +
459
- "The password is typed by the user in a desktop window and is NEVER accepted from you and NEVER returned. " +
460
- "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.",
461
479
  promptSnippet: "Save a local vault entry; the user types the password in a window.",
462
480
  parameters: vaultAddParams,
463
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
+ }
464
495
  const result = await saveLocalEntry(scope, ctx, {
465
496
  name: params.name,
497
+ type: kind,
466
498
  username: params.username,
467
499
  uri: params.uri,
468
500
  notes: params.notes,
501
+ fields,
469
502
  signal,
470
503
  });
471
504
  const ok = result.startsWith("saved ");
@@ -508,9 +541,12 @@ function vaultImportTool(scope: Scope, bw: BwState): ToolDefinition<typeof vault
508
541
 
509
542
  interface SaveRequest {
510
543
  name?: string;
544
+ type?: ItemType;
511
545
  username?: string;
512
546
  uri?: string;
513
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>;
514
550
  signal?: AbortSignal;
515
551
  }
516
552
 
@@ -524,18 +560,33 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
524
560
  }
525
561
  if (!name) return "cancelled: no entry name";
526
562
 
527
- 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!];
528
565
  if (req.username !== undefined) args.push("--username", req.username);
529
566
  if (req.uri?.trim()) args.push("--uri", req.uri.trim());
530
567
  if (req.notes?.trim()) args.push("--notes", req.notes.trim());
531
- let stdin: string | undefined;
532
- 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();
533
584
  try {
534
- const run = await cli.run([...args, "--json"], { stdin, signal: req.signal });
535
- 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 };
536
587
  if (saved.created) scope.items += 1;
537
588
  setStatus(ctx, scope);
538
- 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)`;
539
590
  } catch (error) {
540
591
  if (!(error instanceof CliError) || !error.needsUi) {
541
592
  if (error instanceof CliError && error.auth) scope.token = undefined;
@@ -543,6 +594,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
543
594
  }
544
595
  if (error.needsUi === "confirm") {
545
596
  const meta = [
597
+ ...shown,
546
598
  req.username?.trim() ? tr(`Username: ${forDialog(req.username, 60)}`, `用户名: ${forDialog(req.username, 60)}`) : "",
547
599
  req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
548
600
  req.notes?.trim() ? tr(`Notes: ${forDialog(req.notes, 120)}`, `备注: ${forDialog(req.notes, 120)}`) : "",
@@ -552,7 +604,10 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
552
604
  const ok = await confirmWindow(
553
605
  dialogs(ctx),
554
606
  tr("ai-vault · save to local store", "ai-vault · 保存到本地库"),
555
- tr(`Save the entry "${forDialog(name)}".${meta ? `\n${meta}` : ""}\nA window opens next for you to type the password. It never enters the conversation.`, `保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`),
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
+ ),
556
611
  req.signal,
557
612
  );
558
613
  if (!ok) return `user denied saving "${name}"`;
@@ -565,10 +620,11 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
565
620
  args.push("--username", entered);
566
621
  continue;
567
622
  }
568
- const password = await promptSecret(dialogs(ctx), tr("ai-vault · password", "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);
569
626
  if (!password) return "cancelled: no password entered";
570
- args.push("--password-stdin");
571
- stdin = `${password}\n`;
627
+ secrets.set(field, password);
572
628
  }
573
629
  }
574
630
  return "cancelled: the save dialog did not settle";
@@ -605,12 +661,12 @@ async function importBitwarden(
605
661
  if (!allowed) return { text: "user denied the Bitwarden import", ok: false, count: 0 };
606
662
  let drafts;
607
663
  try {
608
- drafts = await pullBitwardenLogins(bw, ctx, search, signal);
664
+ drafts = await pullBitwardenItems(bw, ctx, search, signal);
609
665
  } catch (error) {
610
666
  return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
611
667
  }
612
668
  if (drafts.length === 0) {
613
- 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 };
614
670
  }
615
671
  try {
616
672
  const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
@@ -891,7 +947,30 @@ function commandHandler(scope: Scope, bw: BwState) {
891
947
  return;
892
948
  }
893
949
  case "add": {
894
- 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 });
895
974
  note(ctx, text, text.startsWith("saved ") ? "info" : "warning");
896
975
  return;
897
976
  }
package/src/types.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The shape of a vault entry, shared by the extension's import mapping and
3
+ * its tools. Mirrors the CLI's `store.rs` and Bitwarden's own item envelope:
4
+ * a type, the type's own fields under `data`, plus `notes` and custom
5
+ * `fields` that every type carries.
6
+ */
7
+ export type ItemType =
8
+ | "login"
9
+ | "secureNote"
10
+ | "card"
11
+ | "identity"
12
+ | "sshKey"
13
+ | "bankAccount"
14
+ | "driversLicense"
15
+ | "passport";
16
+
17
+ /** A custom field, as Bitwarden stores it: 0 text · 1 hidden · 2 boolean · 3 linked. */
18
+ export interface Field {
19
+ name: string;
20
+ value: string;
21
+ type: number;
22
+ linkedId?: string;
23
+ }
24
+
25
+ export interface Source {
26
+ kind: string;
27
+ id: string;
28
+ }
29
+
30
+ /** What a tool hands to `ai-vault save` / `add`: the same envelope, sparse. */
31
+ export interface Draft {
32
+ name: string;
33
+ type: ItemType;
34
+ username?: string;
35
+ password?: string;
36
+ uris?: string[];
37
+ data?: Record<string, string>;
38
+ notes?: string;
39
+ fields?: Field[];
40
+ source?: Source;
41
+ }
42
+
43
+ /** What `list` returns: metadata only, every secret masked. */
44
+ export interface ItemSummary {
45
+ name: string;
46
+ type: ItemType;
47
+ username?: string | null;
48
+ uris: string[];
49
+ fields: Record<string, string>;
50
+ hasNotes?: boolean;
51
+ updatedAt: string;
52
+ }