pi-ai-vault 0.4.2 → 0.6.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
@@ -26,7 +26,7 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
26
26
  | 工具 | 作用 | 模型看到密码? |
27
27
  |---|---|---|
28
28
  | `vault_list` | 本地库条目元数据 | 否 |
29
- | `vault_get` | 读一条;弹窗授权,5 分钟内同一请求方可复用 | 是,用户当场允许 |
29
+ | `vault_get` | 读一条:**先本地库,再 Bitwarden**;Bitwarden 命中会问「读一次 / 导入 ai-vault」 | 是,用户当场允许 |
30
30
  | `vault_add` | 存一条;密码由用户在弹出的窗口里输入 | 否 |
31
31
  | `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | 否 |
32
32
  | `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | 在线 Bitwarden(`bw` CLI) | 否,`bw_reveal` 除外 |
@@ -41,6 +41,26 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
41
41
  /bw status|unlock|lock|clear
42
42
  ```
43
43
 
44
+ ## 解锁模式
45
+
46
+ 本地库什么时候要主密码,由这台机器的模式决定(`/vault mode`,切换要主密码):
47
+
48
+ | 模式 | 行为 |
49
+ |---|---|
50
+ | `never` | 永远不问,读取也不弹确认窗——「agent 可以自由使用」的那批密码 |
51
+ | `time` | 解锁后 N 小时(默认 8)再问一次 |
52
+ | `session` | 每个会话一次,会话结束失效(默认) |
53
+
54
+ `vault_get` 找不到本地条目时会去 Bitwarden 搜;命中后按 `bitwarden.import` 处理:
55
+
56
+ | `bitwarden.import` | 行为 |
57
+ |---|---|
58
+ | `ask`(默认) | 给你看这一条 → 读一次 → 问「导入 ai-vault / 只用这一次」 |
59
+ | `always` | 命中直接导入并返回,不开窗口 |
60
+ | `never` | 只读一次,永不写入本地库 |
61
+
62
+ 所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
63
+
44
64
  ## 隔离
45
65
 
46
66
  每个会话、每个子代理各自 `ai-vault unlock`,拿自己的令牌和读授权;父会话的解锁子代理继承不到。空闲 10 分钟自动失效,`/new`、`/fork`、退出会清掉本绑定的令牌。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store plus live Bitwarden. 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.4.1"
28
+ "@xiaolikt/ai-vault": "0.6.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
package/src/bitwarden.ts CHANGED
@@ -55,6 +55,7 @@ import { Type } from "typebox";
55
55
  import { bitwardenLogins, filterLogins, type LoginDraft } from "./import-map.js";
56
56
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
57
57
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
58
+ import { getSettingsSafe, settingsCli } from "./settings.js";
58
59
  import { scrubDeep, scrubText } from "./scrub.js";
59
60
 
60
61
  // ---------------------------------------------------------------------------
@@ -492,6 +493,9 @@ function startAutoLock(st: BwState, ctx: ExtensionContext | undefined): void {
492
493
  /** Drop this binding's session key and injected variables, and the clipboard. */
493
494
  async function lock(st: BwState, reason: string): Promise<void> {
494
495
  const hadSession = !!st.key;
496
+ // A key kept for `bitwarden.unlock = never | time` must go with an explicit
497
+ // lock, or the next call would silently unlock again.
498
+ void settingsCli().run(["bw-session", "clear"]).catch(() => undefined);
495
499
  st.epoch++;
496
500
  st.key = undefined;
497
501
  st.verifiedAt = 0;
@@ -545,6 +549,27 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
545
549
 
546
550
  const epoch = st.epoch;
547
551
  const pending = (async () => {
552
+ const policy = (await getSettingsSafe(signal)).bitwarden;
553
+ // `never` / `time`: the CLI keeps the session key (0600, in the store
554
+ // directory), so Bitwarden costs no window at all.
555
+ if (policy.unlock !== "session") {
556
+ try {
557
+ const saved = await settingsCli().json<{ key: string }>(["bw-session", "get"], { signal });
558
+ if (saved?.key) {
559
+ const verify = await bwStatus(saved.key, signal);
560
+ if (verify?.status === "unlocked") {
561
+ st.key = saved.key;
562
+ st.verifiedAt = Date.now();
563
+ acquireSessionKey();
564
+ startAutoLock(st, ctx);
565
+ return saved.key;
566
+ }
567
+ }
568
+ } catch {
569
+ /* absent or expired: fall through to the password */
570
+ }
571
+ }
572
+
548
573
  const status = await bwStatus(undefined, signal); // no session env
549
574
  if (status?.status === "unauthenticated") throw new Error(BW_LOGIN_HINT);
550
575
 
@@ -569,6 +594,11 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
569
594
  st.verifiedAt = Date.now();
570
595
  acquireSessionKey();
571
596
  startAutoLock(st, ctx);
597
+ if (policy.unlock !== "session") {
598
+ // Keep the key where the CLI can hand it back; the file's expiry comes
599
+ // from the bitwarden.hours policy.
600
+ await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
601
+ }
572
602
  await audit("unlock", "ok", st.sessionLabel);
573
603
  // Refresh in the background: a full sync can take seconds on large vaults.
574
604
  const lastSync = Date.parse(status?.lastSync ?? "");
@@ -779,6 +809,38 @@ export async function pullBitwardenLogins(
779
809
  return filterLogins(bitwardenLogins(raw), search);
780
810
  }
781
811
 
812
+ export type BitwardenLoginHit = { id: string; name: string; username: string; password: string; uris: string[] };
813
+
814
+ /**
815
+ * Look one login up by name/URI and return its password, with no window of its
816
+ * own: the caller shows the user what was found and asks whether to read it.
817
+ * `undefined` means "no such item"; an ambiguous reference throws with the
818
+ * candidates so the model can pick one.
819
+ */
820
+ export async function lookupBitwardenLogin(
821
+ st: BwState,
822
+ ctx: ExtensionContext | undefined,
823
+ ref: string,
824
+ signal?: AbortSignal,
825
+ ): Promise<BitwardenLoginHit | undefined> {
826
+ const session = await ensureUnlocked(st, ctx, signal);
827
+ let item: LiteItem;
828
+ try {
829
+ item = await resolveItem(st, session, ref, signal);
830
+ } catch (e) {
831
+ if (e instanceof Error && /^No Bitwarden item matches/.test(e.message)) return undefined;
832
+ throw e;
833
+ }
834
+ const secret = await secretOf(session, item, "password", signal);
835
+ return {
836
+ id: item.id ?? "",
837
+ name: item.name || "unnamed",
838
+ username: item.username,
839
+ password: secret.value,
840
+ uris: item.uri ? [item.uri] : [],
841
+ };
842
+ }
843
+
782
844
  function normalizeEnvName(raw: string): string {
783
845
  const name = raw.trim().toUpperCase();
784
846
  if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) {
package/src/index.ts CHANGED
@@ -13,30 +13,46 @@
13
13
  */
14
14
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
15
15
  import { Type } from "typebox";
16
- import { newBwState, pullBitwardenLogins, queryBitwarden, registerBitwarden, type BitwardenMeta, type BwState } from "./bitwarden.js";
16
+ import {
17
+ lookupBitwardenLogin,
18
+ newBwState,
19
+ pullBitwardenLogins,
20
+ queryBitwarden,
21
+ registerBitwarden,
22
+ type BitwardenMeta,
23
+ type BwState,
24
+ } from "./bitwarden.js";
17
25
  import { CliError, VaultCli } from "./cli.js";
18
26
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
19
27
  import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
28
+ import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
20
29
 
21
30
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
22
31
 
23
32
  const GRANT_MS_DEFAULT = 5 * 60_000;
24
33
 
34
+ type UnlockModeName = "never" | "time" | "session";
35
+
25
36
  interface StatusResult {
26
37
  ok: boolean;
27
38
  unlocked: boolean;
28
39
  items: number;
29
40
  requester: string;
30
41
  idleMs: number;
31
- expiresAt: number;
42
+ expiresAt: number | null;
43
+ mode: UnlockModeName;
44
+ hours: number;
45
+ auto: boolean;
32
46
  grants: Record<string, { expiresAt: number; leftMs: number }>;
33
47
  }
34
48
 
35
49
  interface UnlockResult {
36
50
  ok: boolean;
37
51
  token: string;
38
- expiresAt: number;
52
+ expiresAt: number | null;
39
53
  items: number;
54
+ mode?: UnlockModeName;
55
+ auto?: boolean;
40
56
  }
41
57
 
42
58
  interface ListResult {
@@ -71,6 +87,10 @@ interface Scope {
71
87
  epoch: number;
72
88
  /** Cached entry count for the status line. */
73
89
  items: number;
90
+ /** The machine-wide unlock policy, as the CLI last reported it. */
91
+ mode?: UnlockModeName;
92
+ /** True when reads use the machine-wide session instead of a token. */
93
+ auto?: boolean;
74
94
  unlocking?: Promise<boolean>;
75
95
  }
76
96
 
@@ -86,12 +106,15 @@ const note = (ctx: Ctx, text: string, level: "info" | "warning" | "error" = "inf
86
106
 
87
107
  const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
88
108
 
89
- interface Failure {
109
+ /** What a tool call hands back; every error path uses the same shape. */
110
+ interface ToolOutcome {
90
111
  content: { type: "text"; text: string }[];
91
- details: { ok: false; denied?: boolean };
92
- isError: true;
112
+ details: { ok?: boolean; denied?: boolean; item?: string; via?: string; count?: number };
113
+ isError?: boolean;
93
114
  }
94
115
 
116
+ type Failure = ToolOutcome;
117
+
95
118
  const fail = (text: string, denied = false): Failure => ({
96
119
  content: [{ type: "text" as const, text }],
97
120
  details: { ok: false, ...(denied ? { denied: true } : {}) },
@@ -127,6 +150,9 @@ async function lockNow(scope: Scope): Promise<void> {
127
150
  }
128
151
  }
129
152
 
153
+ /** Args for a CLI call: this binding's token, or the machine-wide session. */
154
+ const tokenArgs = (scope: Scope): string[] => (scope.token ? ["--token", scope.token] : []);
155
+
130
156
  /** Make this binding's unlock happen; never throws. */
131
157
  async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Promise<boolean> {
132
158
  if (!cli.available) {
@@ -140,6 +166,8 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
140
166
  try {
141
167
  const status = await cli.json<StatusResult>(["status", "--token", scope.token], { signal });
142
168
  scope.items = status.items;
169
+ scope.mode = status.mode;
170
+ scope.auto = false;
143
171
  return true;
144
172
  } catch (error) {
145
173
  if (!(error instanceof CliError) || !error.auth) {
@@ -153,6 +181,24 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
153
181
  }
154
182
  }
155
183
  }
184
+ // `never` mode keeps a machine-wide session: no token, no window. Ask the
185
+ // CLI before opening anything, so that mode really is password-free.
186
+ try {
187
+ const status = await cli.json<StatusResult>(["status"], { signal });
188
+ scope.items = status.items;
189
+ scope.mode = status.mode;
190
+ scope.auto = status.auto;
191
+ return true;
192
+ } catch (error) {
193
+ if (error instanceof CliError && /not initialized/i.test(error.message)) {
194
+ note(ctx, NOT_INITIALIZED, "warning");
195
+ return false;
196
+ }
197
+ if (!(error instanceof CliError) || !error.auth) {
198
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
199
+ return false;
200
+ }
201
+ }
156
202
  const attempt = async (password?: string): Promise<UnlockResult> => {
157
203
  const args = ["unlock", "--requester", sessionLabel(ctx)];
158
204
  if (password !== undefined) args.push("--password-stdin");
@@ -179,7 +225,11 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
179
225
  await cli.run(["lock", "--token", result.token]).catch(() => undefined);
180
226
  return false;
181
227
  }
182
- scope.token = result.token;
228
+ scope.mode = result.mode;
229
+ scope.auto = result.mode === "never";
230
+ // In `never` mode the CLI wrote the machine-wide session; keeping a
231
+ // per-binding token would bring back a confirm window on every read.
232
+ scope.token = result.mode === "never" ? undefined : result.token;
183
233
  scope.items = result.items;
184
234
  return true;
185
235
  } catch (error) {
@@ -236,53 +286,143 @@ const vaultGetParams = Type.Object({
236
286
  reason: Type.Optional(Type.String({ description: "Why this secret is needed (shown to the user in the confirm window)" })),
237
287
  });
238
288
  type VaultGetDetails = { ok?: boolean; denied?: boolean; item?: string; via?: string };
239
- function vaultGetTool(scope: Scope): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
289
+
290
+ /**
291
+ * The local vault is the first stop; Bitwarden is the fallback. A hit there is
292
+ * offered to the user twice: read it this once, then optionally import it so
293
+ * later reads never touch Bitwarden.
294
+ */
295
+ async function bitwardenFallback(
296
+ scope: Scope,
297
+ ctx: Ctx,
298
+ bw: BwState,
299
+ name: string,
300
+ reason: string | undefined,
301
+ localMiss: string,
302
+ signal?: AbortSignal,
303
+ ): Promise<ToolOutcome> {
304
+ const missing = localMiss;
305
+ let hit;
306
+ try {
307
+ hit = await lookupBitwardenLogin(bw, ctx, name, signal);
308
+ } catch (error) {
309
+ return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
310
+ }
311
+ if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
312
+
313
+ const asValue = (via: string): ToolOutcome => ({
314
+ content: [
315
+ {
316
+ type: "text" as const,
317
+ text: JSON.stringify(
318
+ { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
319
+ null,
320
+ 1,
321
+ ),
322
+ },
323
+ ],
324
+ details: { item: hit.name, via },
325
+ });
326
+
327
+ const importIt = async (): Promise<ToolOutcome> => {
328
+ try {
329
+ const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
330
+ stdin: JSON.stringify([
331
+ {
332
+ name: hit.name,
333
+ username: hit.username || undefined,
334
+ password: hit.password,
335
+ uris: hit.uris,
336
+ source: { kind: "bitwarden", id: hit.id },
337
+ },
338
+ ]),
339
+ signal,
340
+ });
341
+ scope.items += saved.count;
342
+ setStatus(ctx, scope);
343
+ } catch (error) {
344
+ return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
345
+ }
346
+ return asValue("imported-from-bitwarden");
347
+ };
348
+
349
+ const policy = (await getSettingsSafe(signal)).bitwarden.import;
350
+ if (policy === "always") {
351
+ // bitwarden.import = always: the user opted into pulling hits in silently.
352
+ return importIt();
353
+ }
354
+
355
+ const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
356
+ const allow = await confirmWindow(
357
+ dialogs(ctx),
358
+ "pi-ai-vault · Bitwarden 里找到",
359
+ `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
360
+ signal,
361
+ );
362
+ if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
363
+ if (policy === "never") return asValue("bitwarden-once");
364
+
365
+ const confirmed = await confirmWindow(
366
+ dialogs(ctx),
367
+ "pi-ai-vault · 导入到 ai-vault",
368
+ `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
369
+ signal,
370
+ );
371
+ return confirmed ? importIt() : asValue("bitwarden-once");
372
+ }
373
+
374
+ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
375
+ const viaOf = (stdout: string): string => {
376
+ try {
377
+ return (JSON.parse(stdout) as { via?: string }).via ?? "grant";
378
+ } catch {
379
+ return "grant";
380
+ }
381
+ };
240
382
  const tool: ToolDefinition<typeof vaultGetParams, VaultGetDetails> = {
241
383
  name: "vault_get",
242
- label: "Vault: read a local secret",
384
+ label: "Vault: read a secret (local first, Bitwarden second)",
243
385
  description:
244
- "Read one secret from the machine-wide ai-vault store (not Bitwarden). " +
245
- "The user must approve a desktop confirm window; the grant then lasts 5 minutes for the session or subagent that asked. " +
246
- "If the user denies, do not retry. Prefer bw_run when the secret should stay out of the chat.",
386
+ "Read one secret. The machine-wide ai-vault store is asked first; that is the vault the agent may use freely, and in `never` unlock mode it answers without any window. " +
387
+ "If the entry is not local, Bitwarden is searched: the user is shown the hit, then asked whether to read it once or import it into ai-vault. " +
388
+ "If the user denies, do not retry. Use bw_run when the value must never enter the chat.",
389
+ promptSnippet: "Read a secret: local vault first, then Bitwarden (with an import offer).",
247
390
  parameters: vaultGetParams,
248
391
  async execute(_id, params, signal, _onUpdate, ctx) {
249
392
  if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
250
- const args = ["get", params.name, "--token", scope.token!];
251
- if (params.reason) args.push("--reason", params.reason);
393
+ const base = ["get", params.name, ...(params.reason ? ["--reason", params.reason] : []), ...tokenArgs(scope)];
252
394
  try {
253
- const viaOf = (stdout: string): string => {
254
- try {
255
- return (JSON.parse(stdout) as { via?: string }).via ?? "grant";
256
- } catch {
257
- return "grant";
258
- }
259
- };
260
395
  try {
261
- const run = await cli.run([...args, "--json"], { signal });
262
- setStatus(ctx, scope, "·granted");
396
+ const run = await cli.run([...base, "--json"], { signal });
397
+ setStatus(ctx, scope, "·ok");
263
398
  return {
264
399
  content: [{ type: "text" as const, text: run.stdout.trim() }],
265
400
  details: { item: params.name, via: viaOf(run.stdout) },
266
401
  };
267
402
  } catch (error) {
268
- if (!(error instanceof CliError) || error.needsUi !== "confirm") throw error;
269
- const sub = subagentId(ctx);
270
- const allowed = await confirmWindow(
271
- dialogs(ctx),
272
- "ai-vault · 读取本地密码",
273
- `条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
274
- "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
275
- signal,
276
- );
277
- const run = await cli.run([...args, "--json", "--answer-stdin"], {
278
- stdin: allowed ? "y\n" : "n\n",
279
- signal,
280
- });
281
- setStatus(ctx, scope, "·granted");
282
- return {
283
- content: [{ type: "text" as const, text: run.stdout.trim() }],
284
- details: { item: params.name, via: viaOf(run.stdout) },
285
- };
403
+ if (error instanceof CliError && error.needsUi === "confirm") {
404
+ const sub = subagentId(ctx);
405
+ const allowed = await confirmWindow(
406
+ dialogs(ctx),
407
+ "ai-vault · 读取本地密码",
408
+ `条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
409
+ "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
410
+ signal,
411
+ );
412
+ const run = await cli.run([...base, "--json", "--answer-stdin"], {
413
+ stdin: allowed ? "y\n" : "n\n",
414
+ signal,
415
+ });
416
+ setStatus(ctx, scope, "·granted");
417
+ return {
418
+ content: [{ type: "text" as const, text: run.stdout.trim() }],
419
+ details: { item: params.name, via: viaOf(run.stdout) },
420
+ };
421
+ }
422
+ if (error instanceof CliError && /^no such entry/.test(error.message)) {
423
+ return await bitwardenFallback(scope, ctx, bw, params.name, params.reason, error.message, signal);
424
+ }
425
+ throw error;
286
426
  }
287
427
  } catch (error) {
288
428
  if (error instanceof CliError && error.denied) setStatus(ctx, scope, "·denied");
@@ -485,6 +625,8 @@ async function importBitwarden(
485
625
  const HELP = [
486
626
  "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
487
627
  "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
628
+ "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
629
+ "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.unlock、bitwarden.import …)",
488
630
  "/vault status 状态与授权剩余时间",
489
631
  "/vault list 本地条目元数据",
490
632
  "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
@@ -545,6 +687,23 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
545
687
  }
546
688
  }
547
689
 
690
+ function settingsText(s: Settings): string {
691
+ const persisted = s.bitwarden.persisted
692
+ ? s.bitwarden.expiresAt
693
+ ? `有(${Math.max(0, Math.round((s.bitwarden.expiresAt - Date.now()) / 60_000))} 分钟后过期)`
694
+ : "有(不过期)"
695
+ : "无";
696
+ return [
697
+ `vault.unlock: ${s.vault.unlock} (never | time | session)`,
698
+ `vault.hours: ${s.vault.hours} (time 模式用)`,
699
+ `vault 机器级会话: ${s.vault.auto ? "有(免密)" : "无"}`,
700
+ `bitwarden.unlock: ${s.bitwarden.unlock} (never | time | session)`,
701
+ `bitwarden.hours: ${s.bitwarden.hours}`,
702
+ `bitwarden.import: ${s.bitwarden.import} (ask | always | never)`,
703
+ `bitwarden 已落盘的会话: ${persisted}`,
704
+ ].join("\n");
705
+ }
706
+
548
707
  function commandHandler(scope: Scope, bw: BwState) {
549
708
  return async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
550
709
  const [sub = "status", ...rest] = words(args);
@@ -570,33 +729,122 @@ function commandHandler(scope: Scope, bw: BwState) {
570
729
  return;
571
730
  }
572
731
  case "status": {
573
- if (!scope.token) {
574
- note(ctx, [`store: ${cli.dir}/store.json`, `session: ${label}`, "state: locked"].join("\n"));
575
- setStatus(ctx, scope);
576
- return;
577
- }
578
732
  try {
579
- const status = await cli.json<StatusResult>(["status", "--token", scope.token]);
733
+ const status = await cli.json<StatusResult>(["status", ...tokenArgs(scope)]);
580
734
  scope.items = status.items;
735
+ scope.mode = status.mode;
736
+ scope.auto = status.auto;
737
+ setStatus(ctx, scope);
738
+ const expiry = status.expiresAt
739
+ ? `${Math.max(0, Math.round((status.expiresAt - Date.now()) / 1000))}s`
740
+ : "never";
741
+ const how =
742
+ status.mode === "never"
743
+ ? "never(免密)"
744
+ : status.mode === "time"
745
+ ? `time(每 ${status.hours}h 要一次密码)`
746
+ : "session(每个会话一次)";
581
747
  const lines = [
582
748
  `store: ${cli.dir}/store.json`,
583
749
  `session: ${status.requester}`,
584
750
  "state: unlocked",
751
+ `mode: ${how}`,
585
752
  `items: ${status.items}`,
586
- `expires: ${Math.max(0, Math.round((status.expiresAt - Date.now()) / 1000))}s (idle lock ${Math.round(status.idleMs / 1000)}s)`,
753
+ `expires: ${expiry}`,
587
754
  ];
588
755
  for (const [name, grant] of Object.entries(status.grants)) {
589
756
  lines.push(`grant: ${name} (${Math.ceil(grant.leftMs / 1000)}s left)`);
590
757
  }
591
758
  note(ctx, lines.join("\n"));
592
- setStatus(ctx, scope);
593
759
  } catch (error) {
594
760
  scope.token = undefined;
595
- note(ctx, `ai-vault: ${describe(error)}`, "warning");
761
+ note(
762
+ ctx,
763
+ [
764
+ `store: ${cli.dir}/store.json`,
765
+ `session: ${label}`,
766
+ "state: locked",
767
+ `ai-vault: ${describe(error)}`,
768
+ ].join("\n"),
769
+ "warning",
770
+ );
596
771
  setStatus(ctx, scope);
597
772
  }
598
773
  return;
599
774
  }
775
+ case "settings": {
776
+ const [key, ...valueParts] = rest;
777
+ const value = valueParts.join(" ").trim();
778
+ try {
779
+ if (!key) {
780
+ note(ctx, settingsText(await cli.json<Settings>(["settings"])));
781
+ return;
782
+ }
783
+ if (!value) {
784
+ const one = await cli.json<{ key: string; value: string }>(["settings", key]);
785
+ note(ctx, `${one.key}: ${one.value}`);
786
+ return;
787
+ }
788
+ // `vault.unlock` opens its own password window (or answers
789
+ // needs-ui); the other keys do not prompt at all.
790
+ const run = await cli.withPassword(["settings", key, value], () =>
791
+ promptSecret(dialogs(ctx), "ai-vault · 主密码", "改变解锁模式需要验证"),
792
+ );
793
+ forgetSettings();
794
+ const updated = JSON.parse(run.stdout) as Settings;
795
+ if (key.startsWith("vault.")) await lockNow(scope);
796
+ note(ctx, settingsText(updated));
797
+ } catch (error) {
798
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
799
+ }
800
+ return;
801
+ }
802
+ case "mode": {
803
+ const [sub, hoursArg] = rest;
804
+ if (!sub || sub === "get" || sub === "status") {
805
+ try {
806
+ const current = await cli.json<{ mode: string; hours: number; auto: boolean }>(["mode"]);
807
+ note(
808
+ ctx,
809
+ [
810
+ `mode: ${current.mode}`,
811
+ `hours: ${current.hours}(time 模式用)`,
812
+ `machine-wide session: ${current.auto ? "yes(免密)" : "no"}`,
813
+ "",
814
+ "/vault mode never|time|session [小时] 切换(要主密码)",
815
+ ].join("\n"),
816
+ );
817
+ } catch (error) {
818
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
819
+ }
820
+ return;
821
+ }
822
+ if (!["never", "time", "session", "no-password"].includes(sub)) {
823
+ note(ctx, "用法: /vault mode [never|time|session] [小时]", "warning");
824
+ return;
825
+ }
826
+ const args = ["mode", "set", sub];
827
+ if (hoursArg) args.push("--hours", hoursArg);
828
+ try {
829
+ const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), "ai-vault · 主密码", "切换解锁模式"));
830
+ const result = JSON.parse(run.stdout) as { mode: UnlockModeName; hours: number; auto: boolean };
831
+ forgetSettings();
832
+ await lockNow(scope);
833
+ scope.mode = result.mode;
834
+ scope.auto = result.auto;
835
+ setStatus(ctx, scope);
836
+ const how =
837
+ result.mode === "never"
838
+ ? "以后免密(密钥已写盘,任何能读你文件的程序都能读到库里的密码)"
839
+ : result.mode === "time"
840
+ ? `以后每 ${result.hours} 小时要一次密码`
841
+ : "以后每个会话要一次密码";
842
+ note(ctx, `mode → ${result.mode},${how}`);
843
+ } catch (error) {
844
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
845
+ }
846
+ return;
847
+ }
600
848
  case "list": {
601
849
  if (!(await ensureUnlocked(scope, ctx))) return;
602
850
  try {
@@ -752,7 +1000,7 @@ export default function aiVault(pi: ExtensionAPI): void {
752
1000
  const scope: Scope = { token: undefined, epoch: 0, items: 0, unlocking: undefined };
753
1001
  const bw = newBwState();
754
1002
  pi.registerTool(vaultListTool(scope));
755
- pi.registerTool(vaultGetTool(scope));
1003
+ pi.registerTool(vaultGetTool(scope, bw));
756
1004
  pi.registerTool(vaultAddTool(scope));
757
1005
  pi.registerTool(vaultImportTool(scope, bw));
758
1006
  registerBitwarden(pi, bw, omp);
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Machine-wide settings, owned by the CLI (`ai-vault settings`), read here.
3
+ *
4
+ * The vault decides when to ask for its password; the Bitwarden side decides
5
+ * separately whether its `bw` session key may live on disk, and whether a hit
6
+ * may be imported into the vault without a window.
7
+ */
8
+ import { VaultCli } from "./cli.js";
9
+
10
+ export type UnlockModeName = "never" | "time" | "session";
11
+ export type ImportPolicy = "ask" | "always" | "never";
12
+
13
+ export interface Settings {
14
+ vault: { unlock: UnlockModeName; hours: number; auto: boolean };
15
+ bitwarden: {
16
+ unlock: UnlockModeName;
17
+ hours: number;
18
+ import: ImportPolicy;
19
+ persisted: boolean;
20
+ expiresAt: number | null;
21
+ };
22
+ }
23
+
24
+ export const DEFAULT_SETTINGS: Settings = {
25
+ vault: { unlock: "session", hours: 8, auto: false },
26
+ bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
27
+ };
28
+
29
+ const cli = new VaultCli();
30
+ let cache: { at: number; value: Settings } | undefined;
31
+
32
+ /** The shared CLI client, for the pieces that read and write the settings. */
33
+ export function settingsCli(): VaultCli {
34
+ return cli;
35
+ }
36
+
37
+ /**
38
+ * Settings change rarely, so a short cache keeps a Bitwarden call from paying
39
+ * for the read. `/vault settings ...` drops it explicitly.
40
+ */
41
+ export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
42
+ if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
43
+ const value = await cli.json<Settings>(["settings"], { signal });
44
+ cache = { at: Date.now(), value };
45
+ return value;
46
+ }
47
+
48
+ /** For paths that must keep working when the CLI is missing: defaults instead. */
49
+ export async function getSettingsSafe(signal?: AbortSignal): Promise<Settings> {
50
+ try {
51
+ return await getSettings(signal);
52
+ } catch {
53
+ return DEFAULT_SETTINGS;
54
+ }
55
+ }
56
+
57
+ export function forgetSettings(): void {
58
+ cache = undefined;
59
+ }