@xiaolikt/ai-vault 0.4.1 → 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.
@@ -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
+ }
package/test/cli.sh CHANGED
@@ -113,6 +113,42 @@ assert not any("p1ssw0rd" in json.dumps(e) or "exp-pass" in json.dumps(e) for e
113
113
  PY
114
114
  grep -q 'p1ssw0rd' "$AI_VAULT_DIR/audit.log" && bad "a secret reached the audit log" || ok "no secret in audit.log"
115
115
 
116
+ echo "== unlock modes =="
117
+ check "mode get works without a token" 0 "$BIN" mode --json
118
+ check "switching the mode needs the password" 3 "$BIN" mode set never
119
+ check "a wrong password does not switch it" 5 bash -c "printf 'wrong password' | '$BIN' mode set never --password-stdin"
120
+ check "never mode is set with the password" 0 bash -c "printf 'correct horse' | '$BIN' mode set never --password-stdin --json"
121
+ check "never mode needs no token" 0 "$BIN" status --json
122
+ printf 'correct horse' | "$BIN" unlock --password-stdin --json >"$TMP/u2" 2>&1
123
+ python3 - "$TMP/u2" <<'PY' && ok "unlock reports the mode" || bad "unlock output is wrong"
124
+ import json,sys
125
+ d = json.load(open(sys.argv[1]))
126
+ assert d["mode"] == "never" and d["auto"] is True, d
127
+ PY
128
+ check "back to session mode" 0 bash -c "printf 'correct horse' | '$BIN' mode set session --password-stdin --json"
129
+ check "session mode needs a token again" 5 "$BIN" status
130
+
131
+ echo "== settings =="
132
+ check "settings prints everything" 0 "$BIN" settings --json
133
+ check "set bitwarden.import" 0 "$BIN" settings bitwarden.import never --json
134
+ "$BIN" settings bitwarden.import --json >"$TMP/set1"
135
+ python3 - "$TMP/set1" <<'PY' && ok "the import policy was stored" || bad "the import policy was not stored"
136
+ import json,sys
137
+ assert json.load(open(sys.argv[1]))["value"] == "never"
138
+ PY
139
+ check "an unknown setting is a usage error" 2 "$BIN" settings nope.value 1
140
+ check "bw-session put is refused in session mode" 1 bash -c "printf 'K' | '$BIN' bw-session put"
141
+ check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
142
+ check "bw-session put stores the key" 0 bash -c "printf 'GOOD_SESSION' | '$BIN' bw-session put --json"
143
+ [[ "$(stat -c %a "$AI_VAULT_DIR/bitwarden.session.json")" == "600" ]] && ok "the bw session file is 0600" || bad "the bw session file is not 0600"
144
+ check "bw-session get returns it" 0 "$BIN" bw-session get --json
145
+ check "switch back to session" 0 "$BIN" settings bitwarden.unlock session --json
146
+ check "the stored key is gone" 5 "$BIN" bw-session get
147
+ check "bitwarden.unlock time keeps an expiry" 0 "$BIN" settings bitwarden.unlock time --json
148
+ check "bw-session put in time mode" 0 bash -c "printf 'K2' | '$BIN' bw-session put --json"
149
+ grep -q '"expiresAt": *[0-9]' "$AI_VAULT_DIR/bitwarden.session.json" && ok "time mode writes a deadline" || bad "time mode wrote no deadline"
150
+ "$BIN" settings bitwarden.unlock session --json >/dev/null
151
+
116
152
  echo "== doctor =="
117
153
  check "doctor runs" 0 "$BIN" doctor --json
118
154
 
package/test/smoke.sh CHANGED
@@ -35,13 +35,13 @@ case "$HOST" in
35
35
  MODEL_ARGS=()
36
36
  [[ -n "${OMP_MODEL:-}" ]] && MODEL_ARGS=(--model "$OMP_MODEL")
37
37
  (cd "$STATE/cwd" && timeout 300 omp --session-dir "$STATE/sessions" --no-extensions \
38
- -e "$ROOT/src/index.ts" "${MODEL_ARGS[@]}" --auto-approve --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
38
+ -e "$ROOT/packages/pi-ai-vault/src/index.ts" "${MODEL_ARGS[@]}" --auto-approve --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
39
39
  ;;
40
40
  pi)
41
41
  MODEL_ARGS=()
42
42
  [[ -n "${PI_MODEL:-}" ]] && MODEL_ARGS=(--model "$PI_MODEL")
43
43
  (cd "$STATE/cwd" && timeout 300 pi --no-session --no-extensions \
44
- -e "$ROOT/src/index.ts" "${MODEL_ARGS[@]}" --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
44
+ -e "$ROOT/packages/pi-ai-vault/src/index.ts" "${MODEL_ARGS[@]}" --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
45
45
  ;;
46
46
  *)
47
47
  echo "usage: $0 [omp|pi]" >&2
@@ -8,7 +8,7 @@ import { spawnSync } from "node:child_process";
8
8
  import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, passwordPrompts, subCtx, textOf, useMocks } from "./helpers.mjs";
9
9
 
10
10
  const dir = useMocks();
11
- const { default: ompVault } = await import("../src/index.ts");
11
+ const { default: ompVault } = await import("../packages/pi-ai-vault/src/index.ts");
12
12
  cleanUpOnExit(dir);
13
13
 
14
14
  const SECRET = "supersecret-value-123";
package/tests/helpers.mjs CHANGED
@@ -58,6 +58,8 @@ export const answers = {
58
58
  /** The dialog that types a new entry's password. */
59
59
  entryPassword: (dir, password) => writeFileSync(join(dir, "entry-passwords"), `${password}\n`),
60
60
  entries: (dir, ...lines) => writeFileSync(join(dir, "entries"), lines.map((l) => `${l}\n`).join("")),
61
+ /** --question answers, one per window ("y"/"n"). */
62
+ questions: (dir, ...lines) => writeFileSync(join(dir, "questions"), lines.map((l) => `${l}\n`).join("")),
61
63
  deny: (dir, on = true) =>
62
64
  on ? writeFileSync(join(dir, "deny"), "") : rmSync(join(dir, "deny"), { force: true }),
63
65
  };
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { bitwardenLogins, filterLogins } from "../src/import-map.ts";
3
+ import { bitwardenLogins, filterLogins } from "../packages/pi-ai-vault/src/import-map.ts";
4
4
 
5
5
  const item = (name, extra = {}) => ({
6
6
  id: extra.id,
@@ -6,7 +6,8 @@
6
6
  # when that file is missing or empty; any other password dialog
7
7
  # answers with the first line of $OMP_VAULT_MOCK/entry-passwords
8
8
  # --entry first line of $OMP_VAULT_MOCK/entries; empty when the file is gone
9
- # --question allow, unless $OMP_VAULT_MOCK/deny exists (then exit 1)
9
+ # --question first line of $OMP_VAULT_MOCK/questions ("n" denies), else
10
+ # allow unless $OMP_VAULT_MOCK/deny exists (then exit 1)
10
11
  DIR="${OMP_VAULT_MOCK:-/tmp/omp-vault-mock}"
11
12
  mkdir -p "$DIR"
12
13
  printf '%s\n' "${*//$'\n'/⏎}" >> "$DIR/zenity.log"
@@ -36,6 +37,13 @@ for arg in "$@"; do
36
37
  if [[ -f "$DIR/entries" ]]; then take_first "$DIR/entries"; else echo ""; fi
37
38
  exit 0 ;;
38
39
  --question)
40
+ # An explicit queue ("y"/"n" per line) wins, so a flow with two
41
+ # different questions can answer them differently.
42
+ if [[ -f "$DIR/questions" ]]; then
43
+ answer="$(take_first "$DIR/questions")"
44
+ [[ "$answer" == "n" || "$answer" == "no" ]] && exit 1
45
+ exit 0
46
+ fi
39
47
  [[ -f "$DIR/deny" ]] && exit 1
40
48
  exit 0 ;;
41
49
  esac
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
- import { confirmWindow, promptSecret, promptText } from "../src/prompt.ts";
6
+ import { confirmWindow, promptSecret, promptText } from "../packages/pi-ai-vault/src/prompt.ts";
7
7
 
8
8
  const saved = {
9
9
  PATH: process.env.PATH,