@xiaolikt/ai-vault 0.10.0 → 0.12.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.
@@ -3,26 +3,142 @@
3
3
 
4
4
  use serde::{Deserialize, Serialize};
5
5
 
6
+ /// The item types, numbered exactly as Bitwarden numbers them, so an import is
7
+ /// a copy and a manual entry is the same shape. `login` is what the store held
8
+ /// before types existed; a file without `type` is read as all-login.
9
+ #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
10
+ #[serde(rename_all = "camelCase")]
11
+ pub enum ItemType {
12
+ #[default]
13
+ Login,
14
+ SecureNote,
15
+ Card,
16
+ Identity,
17
+ SshKey,
18
+ /// Behind Bitwarden's "new item types" flag; stored the same way.
19
+ BankAccount,
20
+ DriversLicense,
21
+ Passport,
22
+ }
23
+
24
+ impl ItemType {
25
+ pub fn from_code(code: u8) -> Option<ItemType> {
26
+ Some(match code {
27
+ 1 => ItemType::Login,
28
+ 2 => ItemType::SecureNote,
29
+ 3 => ItemType::Card,
30
+ 4 => ItemType::Identity,
31
+ 5 => ItemType::SshKey,
32
+ 6 => ItemType::BankAccount,
33
+ 7 => ItemType::DriversLicense,
34
+ 8 => ItemType::Passport,
35
+ _ => return None,
36
+ })
37
+ }
38
+
39
+ /// The key Bitwarden puts the type's own fields under.
40
+ pub fn data_key(self) -> &'static str {
41
+ match self {
42
+ ItemType::Login => "login",
43
+ ItemType::SecureNote => "secureNote",
44
+ ItemType::Card => "card",
45
+ ItemType::Identity => "identity",
46
+ ItemType::SshKey => "sshKey",
47
+ ItemType::BankAccount => "bankAccount",
48
+ ItemType::DriversLicense => "driversLicense",
49
+ ItemType::Passport => "passport",
50
+ }
51
+ }
52
+
53
+ /// Every field of this type, in Bitwarden's order. A secure note has none
54
+ /// of its own: its content is the item's `notes`.
55
+ pub fn fields(self) -> &'static [&'static str] {
56
+ match self {
57
+ ItemType::Login => &["username", "password", "totp"],
58
+ ItemType::SecureNote => &[],
59
+ ItemType::Card => &["cardholderName", "brand", "number", "expMonth", "expYear", "code"],
60
+ ItemType::Identity => &[
61
+ "title", "firstName", "middleName", "lastName", "address1", "address2", "address3", "city",
62
+ "state", "postalCode", "country", "company", "email", "phone", "ssn", "username",
63
+ "passportNumber", "licenseNumber",
64
+ ],
65
+ ItemType::SshKey => &["privateKey", "publicKey", "keyFingerprint"],
66
+ ItemType::BankAccount => &[
67
+ "bankName", "nameOnAccount", "accountType", "accountNumber", "routingNumber",
68
+ "branchNumber", "pin", "swiftCode", "iban", "bankContactPhone",
69
+ ],
70
+ ItemType::DriversLicense => &[
71
+ "firstName", "middleName", "lastName", "dateOfBirth", "licenseNumber", "issuingCountry",
72
+ "issuingState", "issueDate", "expirationDate", "issuingAuthority", "licenseClass",
73
+ ],
74
+ ItemType::Passport => &[
75
+ "surname", "givenName", "dateOfBirth", "sex", "birthPlace", "nationality", "issuingCountry",
76
+ "passportNumber", "passportType", "nationalIdentificationNumber", "issuingAuthority",
77
+ "issueDate", "expirationDate",
78
+ ],
79
+ }
80
+ }
81
+
82
+ /// The one field a human means by "the secret" of this type, when they
83
+ /// read one entry with `get` or add one by hand. The others are in `data`.
84
+ pub fn primary_field(self) -> Option<&'static str> {
85
+ match self {
86
+ ItemType::Login => Some("password"),
87
+ ItemType::Card => Some("code"),
88
+ ItemType::SshKey => Some("privateKey"),
89
+ ItemType::BankAccount => Some("pin"),
90
+ // A secure note's secret is its body; an identity's and a document's
91
+ // are spread over many fields, so there is no single one to pick.
92
+ _ => None,
93
+ }
94
+ }
95
+ }
96
+
97
+ /// A custom field, as Bitwarden stores it: 0 text, 1 hidden, 2 boolean, 3 linked.
98
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
99
+ #[serde(rename_all = "camelCase")]
100
+ pub struct Field {
101
+ pub name: String,
102
+ #[serde(default)]
103
+ pub value: String,
104
+ #[serde(default)]
105
+ pub r#type: u8,
106
+ #[serde(default, skip_serializing_if = "Option::is_none")]
107
+ pub linked_id: Option<String>,
108
+ }
109
+
6
110
  #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
7
111
  pub struct Source {
8
112
  pub kind: String,
9
113
  pub id: String,
10
114
  }
11
115
 
116
+ /// One entry. The top of the struct is Bitwarden's item envelope; the type's
117
+ /// own fields live in `data`, and `notes` / `fields` are shared by every type.
12
118
  #[derive(Debug, Clone, Serialize, Deserialize)]
13
119
  #[serde(rename_all = "camelCase")]
14
120
  pub struct Item {
15
121
  pub id: String,
16
122
  pub name: String,
123
+ #[serde(default = "default_item_type")]
124
+ pub r#type: ItemType,
125
+ /// Login only, kept at the top level too so `vault_get` and the old
126
+ /// flat format agree; it mirrors `data.username`.
17
127
  #[serde(default, skip_serializing_if = "Option::is_none")]
18
128
  pub username: Option<String>,
129
+ /// Login only, same as `data.password`; empty for the other types.
19
130
  #[serde(default)]
20
131
  pub password: String,
21
132
  #[serde(default, skip_serializing_if = "Option::is_none")]
22
133
  pub uris: Option<Vec<String>>,
134
+ /// The type's own fields, by Bitwarden's names.
135
+ #[serde(default, skip_serializing_if = "Option::is_none")]
136
+ pub data: Option<serde_json::Map<String, serde_json::Value>>,
23
137
  #[serde(default, skip_serializing_if = "Option::is_none")]
24
138
  pub notes: Option<String>,
25
139
  #[serde(default, skip_serializing_if = "Option::is_none")]
140
+ pub fields: Option<Vec<Field>>,
141
+ #[serde(default, skip_serializing_if = "Option::is_none")]
26
142
  pub source: Option<Source>,
27
143
  #[serde(rename = "createdAt")]
28
144
  pub created_at: String,
@@ -30,28 +146,85 @@ pub struct Item {
30
146
  pub updated_at: String,
31
147
  }
32
148
 
33
- /// Metadata only: what `list` shows. The password is left out.
149
+ fn default_item_type() -> ItemType {
150
+ ItemType::Login
151
+ }
152
+
153
+ impl Item {
154
+ /// Keep the flat login mirrors and the typed block in step.
155
+ pub fn sync_login_mirrors(&mut self) {
156
+ if self.r#type == ItemType::Login {
157
+ let data = self.data.get_or_insert_with(serde_json::Map::new);
158
+ if let Some(user) = &self.username {
159
+ data.insert("username".into(), serde_json::Value::String(user.clone()));
160
+ } else {
161
+ data.remove("username");
162
+ }
163
+ data.insert("password".into(), serde_json::Value::String(self.password.clone()));
164
+ } else {
165
+ self.username = None;
166
+ self.password = String::new();
167
+ }
168
+ }
169
+ }
170
+
171
+ /// Metadata only: what `list` shows. Every secret is left out: passwords,
172
+ /// card numbers and codes, keys, PINs, SSNs, and the value of any custom
173
+ /// field marked hidden. A secure note shows no body (the body *is* the secret).
34
174
  #[derive(Debug, Serialize)]
175
+ #[serde(rename_all = "camelCase")]
35
176
  pub struct ItemSummary {
36
177
  pub name: String,
178
+ #[serde(rename = "type")]
179
+ pub kind: ItemType,
180
+ #[serde(default, skip_serializing_if = "Option::is_none")]
37
181
  pub username: Option<String>,
38
182
  pub uris: Vec<String>,
183
+ /// Non-secret fields of the type, shown so a card or an identity can be
184
+ /// told apart in a listing (cardholder, brand, expiry; name, email…).
185
+ #[serde(default)]
186
+ pub fields: serde_json::Map<String, serde_json::Value>,
187
+ #[serde(default, skip_serializing_if = "Option::is_none")]
188
+ pub has_notes: Option<bool>,
39
189
  #[serde(rename = "updatedAt")]
40
190
  pub updated_at: String,
41
191
  }
42
192
 
43
193
  impl From<&Item> for ItemSummary {
44
194
  fn from(item: &Item) -> Self {
195
+ let mut fields = serde_json::Map::new();
196
+ if let Some(data) = &item.data {
197
+ for (key, value) in data {
198
+ if !crate::cli::is_secret_field(item.r#type, key) && key != "username" && key != "password" {
199
+ if let Some(text) = value.as_str().filter(|t| !t.is_empty()) {
200
+ fields.insert(key.clone(), serde_json::Value::String(crate::dialog::for_dialog(text, 80)));
201
+ }
202
+ }
203
+ }
204
+ }
205
+ if let Some(custom) = &item.fields {
206
+ for field in custom {
207
+ // 1 = hidden in Bitwarden's field types
208
+ if field.r#type != 1 && !field.value.is_empty() {
209
+ fields.insert(field.name.clone(), serde_json::Value::String(crate::dialog::for_dialog(&field.value, 80)));
210
+ }
211
+ }
212
+ }
45
213
  ItemSummary {
46
214
  name: item.name.clone(),
215
+ kind: item.r#type,
47
216
  username: item.username.clone(),
48
217
  uris: item.uris.clone().unwrap_or_default(),
218
+ fields,
219
+ has_notes: item.notes.as_ref().filter(|n| !n.is_empty()).map(|_| true),
49
220
  updated_at: item.updated_at.clone(),
50
221
  }
51
222
  }
52
223
  }
53
224
 
54
225
  /// One entry to insert or merge, from `ai-vault add`, `save`, or an import.
226
+ /// The same envelope as [`Item`]; a missing `type` means a login, which is
227
+ /// also how files written before types existed are read.
55
228
  #[derive(Debug, Clone, Default, Deserialize)]
56
229
  #[serde(rename_all = "camelCase")]
57
230
  pub struct Draft {
@@ -60,17 +233,50 @@ pub struct Draft {
60
233
  #[serde(default)]
61
234
  pub name: String,
62
235
  #[serde(default)]
236
+ pub r#type: ItemType,
237
+ #[serde(default)]
63
238
  pub username: Option<String>,
64
239
  #[serde(default)]
65
240
  pub password: String,
66
241
  #[serde(default)]
67
242
  pub uris: Option<Vec<String>>,
68
243
  #[serde(default)]
244
+ pub data: Option<serde_json::Map<String, serde_json::Value>>,
245
+ #[serde(default)]
69
246
  pub notes: Option<String>,
70
247
  #[serde(default)]
248
+ pub fields: Option<Vec<Field>>,
249
+ #[serde(default)]
71
250
  pub source: Option<Source>,
72
251
  }
73
252
 
253
+ impl Draft {
254
+ /// Fill `data` from the flat login mirrors when a caller (the old `add`
255
+ /// path, an old JSON payload) gave only `username`/`password`.
256
+ pub fn normalise(mut self) -> Draft {
257
+ if self.r#type == ItemType::Login {
258
+ let data = self.data.get_or_insert_with(serde_json::Map::new);
259
+ if let Some(user) = &self.username {
260
+ data.entry("username").or_insert_with(|| serde_json::Value::String(user.clone()));
261
+ }
262
+ if !self.password.is_empty() {
263
+ data.insert("password".into(), serde_json::Value::String(self.password.clone()));
264
+ }
265
+ if let Some(password) = data.get("password").and_then(|v| v.as_str()) {
266
+ self.password = password.to_string();
267
+ }
268
+ if let Some(user) = data.get("username").and_then(|v| v.as_str()) {
269
+ self.username = Some(user.to_string());
270
+ }
271
+ } else {
272
+ // Only a login has the flat mirrors; for the rest the secret is in `data`.
273
+ self.username = None;
274
+ self.password = String::new();
275
+ }
276
+ self
277
+ }
278
+ }
279
+
74
280
  pub fn now_iso() -> String {
75
281
  chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
76
282
  }
@@ -100,6 +306,7 @@ pub fn remove(items: &mut Vec<Item>, name: &str) -> bool {
100
306
  /// An entry is matched by local id, else by its import source, else by name.
101
307
  /// Returns `true` when a new entry was pushed.
102
308
  pub fn apply(items: &mut Vec<Item>, draft: Draft, now: &str) -> bool {
309
+ let draft = draft.normalise();
103
310
  let lower = draft.name.to_lowercase();
104
311
  let existing_idx = if let Some(id) = draft.id.as_deref() {
105
312
  items.iter().position(|i| i.id == id)
@@ -120,10 +327,26 @@ pub fn apply(items: &mut Vec<Item>, draft: Draft, now: &str) -> bool {
120
327
  && items.iter().enumerate().any(|(i, other)| i != idx && other.name.to_lowercase() == lower);
121
328
  let item = &mut items[idx];
122
329
  item.name = draft.name.clone();
123
- if draft.username.is_some() {
330
+ item.r#type = draft.r#type;
331
+ // A field the draft does not mention keeps its stored value; one it
332
+ // mentions as null clears it. An empty `password` means "unchanged".
333
+ if let Some(incoming) = draft.data {
334
+ let data = item.data.get_or_insert_with(serde_json::Map::new);
335
+ for (key, value) in incoming {
336
+ if key == "password" && value.as_str() == Some("") {
337
+ continue;
338
+ }
339
+ if value.is_null() {
340
+ data.remove(&key);
341
+ } else {
342
+ data.insert(key, value);
343
+ }
344
+ }
345
+ }
346
+ if draft.username.is_some() || draft.r#type != ItemType::Login {
124
347
  item.username = draft.username.clone();
125
348
  }
126
- if !draft.password.is_empty() {
349
+ if !draft.password.is_empty() || draft.r#type != ItemType::Login {
127
350
  item.password = draft.password.clone();
128
351
  }
129
352
  if draft.uris.is_some() {
@@ -132,27 +355,36 @@ pub fn apply(items: &mut Vec<Item>, draft: Draft, now: &str) -> bool {
132
355
  if draft.notes.is_some() {
133
356
  item.notes = draft.notes.clone();
134
357
  }
358
+ if draft.fields.is_some() {
359
+ item.fields = draft.fields.clone();
360
+ }
135
361
  if draft.source.is_some() {
136
362
  item.source = draft.source.clone();
137
363
  }
138
364
  if keep_old_name {
139
365
  item.name = before;
140
366
  }
367
+ item.sync_login_mirrors();
141
368
  item.updated_at = now.to_string();
142
369
  return false;
143
370
  }
144
371
 
145
- items.push(Item {
372
+ let mut item = Item {
146
373
  id: draft.id.unwrap_or_else(random_id),
147
374
  name: draft.name,
375
+ r#type: draft.r#type,
148
376
  username: draft.username,
149
377
  password: draft.password,
150
378
  uris: draft.uris,
379
+ data: draft.data,
151
380
  notes: draft.notes,
381
+ fields: draft.fields,
152
382
  source: draft.source,
153
383
  created_at: now.to_string(),
154
384
  updated_at: now.to_string(),
155
- });
385
+ };
386
+ item.sync_login_mirrors();
387
+ items.push(item);
156
388
  true
157
389
  }
158
390
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaolikt/ai-vault",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable, Linux/macOS/Windows) plus the pi-ai-vault extension for pi and omp.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,9 +33,9 @@
33
33
  "access": "public"
34
34
  },
35
35
  "optionalDependencies": {
36
- "@xiaolikt/ai-vault-linux-x64": "0.10.0",
37
- "@xiaolikt/ai-vault-linux-arm64": "0.10.0",
38
- "@xiaolikt/ai-vault-win32-x64": "0.10.0"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.12.0",
37
+ "@xiaolikt/ai-vault-linux-arm64": "0.12.0",
38
+ "@xiaolikt/ai-vault-win32-x64": "0.12.0"
39
39
  },
40
40
  "files": [
41
41
  "bin",
@@ -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 |
@@ -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 不注册) | 否 |
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.10.0",
3
+ "version": "0.12.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.12.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
@@ -52,10 +52,11 @@ 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
- import { getSettingsSafe, settingsCli } from "./settings.js";
59
+ import { getSettingsSafe, settingsCli, settingsToken } from "./settings.js";
59
60
  import { tr } from "./i18n.js";
60
61
  import { scrubDeep, scrubText } from "./scrub.js";
61
62
 
@@ -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
  /**
@@ -598,7 +603,8 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
598
603
  if (policy.unlock !== "session") {
599
604
  // Keep the key where the CLI can hand it back; the file's expiry comes
600
605
  // from the bitwarden.hours policy.
601
- await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
606
+ const token = settingsToken();
607
+ await settingsCli().run(["bw-session", "put", ...(token ? ["--token", token] : [])], { stdin: key }).catch(() => undefined);
602
608
  }
603
609
  await auditEvent("unlock", "ok", st.sessionLabel);
604
610
  // Refresh in the background: a full sync can take seconds on large vaults.
@@ -624,12 +630,23 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
624
630
  return pending;
625
631
  }
626
632
 
633
+ const BW_TYPE_NAMES: Record<number, string> = { 1: "login", 2: "note", 3: "card", 4: "identity", 5: "sshKey", 6: "bankAccount", 7: "driversLicense", 8: "passport" };
634
+
627
635
  function toLite(raw: BwItem): LiteItem {
636
+ const type = BW_TYPE_NAMES[raw.type ?? 1] ?? `type-${raw.type}`;
637
+ // The identifying, non-secret line of each type: username for a login,
638
+ // cardholder for a card, a person's name for an identity, and so on.
639
+ const who =
640
+ raw.login?.username ??
641
+ raw.card?.cardholderName ??
642
+ (raw.identity ? [raw.identity.title, raw.identity.firstName, raw.identity.lastName].filter(Boolean).join(" ") : "") ??
643
+ "";
628
644
  return {
629
645
  id: raw.id ?? "",
630
646
  name: raw.name ?? "",
631
- username: raw.login?.username ?? "",
647
+ username: who,
632
648
  uri: raw.login?.uris?.[0]?.uri ?? "",
649
+ type,
633
650
  };
634
651
  }
635
652
 
@@ -796,34 +813,35 @@ export async function queryBitwarden(
796
813
  }
797
814
 
798
815
  /**
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.
816
+ * Every item that matches `search`, ready to store in the local vault: all
817
+ * types, field for field. Call only after the user has agreed to the import —
818
+ * this reads secrets.
801
819
  */
802
- export async function pullBitwardenLogins(
820
+ export async function pullBitwardenItems(
803
821
  st: BwState,
804
822
  ctx: ExtensionContext | undefined,
805
823
  search: string | undefined,
806
824
  signal?: AbortSignal,
807
- ): Promise<LoginDraft[]> {
825
+ ): Promise<Draft[]> {
808
826
  const session = await ensureUnlocked(st, ctx, signal);
809
827
  const raw: unknown = await runBwJson(["list", "items"], session, signal);
810
- return filterLogins(bitwardenLogins(raw), search);
828
+ return filterItems(bitwardenItems(raw), search);
811
829
  }
812
830
 
813
- export type BitwardenLoginHit = { id: string; name: string; username: string; password: string; uris: string[] };
831
+ export type BitwardenHit = { draft: Draft; label: string };
814
832
 
815
833
  /**
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.
834
+ * Look one item up, of any type, and return it as a draft with its secrets,
835
+ * with no window of its own: the caller shows the user what was found and asks
836
+ * whether to read it. `undefined` means "no such item"; an ambiguous reference
837
+ * throws with the candidates so the model can pick one.
820
838
  */
821
- export async function lookupBitwardenLogin(
839
+ export async function lookupBitwardenItem(
822
840
  st: BwState,
823
841
  ctx: ExtensionContext | undefined,
824
842
  ref: string,
825
843
  signal?: AbortSignal,
826
- ): Promise<BitwardenLoginHit | undefined> {
844
+ ): Promise<BitwardenHit | undefined> {
827
845
  const session = await ensureUnlocked(st, ctx, signal);
828
846
  let item: LiteItem;
829
847
  try {
@@ -832,14 +850,12 @@ export async function lookupBitwardenLogin(
832
850
  if (e instanceof Error && /^No Bitwarden item matches/.test(e.message)) return undefined;
833
851
  throw e;
834
852
  }
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
- };
853
+ if (!item.id) throw new Error(`Bitwarden item "${item.name}" has no id, so it cannot be read.`);
854
+ const full = (await runBwJson(["get", "item", item.id], session, signal)) as unknown;
855
+ const [draft] = bitwardenItems([full]);
856
+ if (!draft) return undefined;
857
+ const who = item.username ? ` ${item.username}` : "";
858
+ return { draft, label: `${draft.name}${who} (${item.type})` };
843
859
  }
844
860
 
845
861
  function normalizeEnvName(raw: string): string {
@@ -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
  }