@xiaolikt/ai-vault 0.0.0-stage → 0.5.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.
Files changed (41) hide show
  1. package/Cargo.lock +784 -0
  2. package/Cargo.toml +8 -0
  3. package/LICENSE +21 -0
  4. package/README.md +244 -2
  5. package/bin/ai-vault.cjs +71 -0
  6. package/crates/ai-vault/Cargo.toml +26 -0
  7. package/crates/ai-vault/src/audit.rs +77 -0
  8. package/crates/ai-vault/src/cli.rs +1129 -0
  9. package/crates/ai-vault/src/config.rs +77 -0
  10. package/crates/ai-vault/src/crypto.rs +265 -0
  11. package/crates/ai-vault/src/dialog.rs +222 -0
  12. package/crates/ai-vault/src/import.rs +175 -0
  13. package/crates/ai-vault/src/main.rs +22 -0
  14. package/crates/ai-vault/src/paths.rs +68 -0
  15. package/crates/ai-vault/src/session.rs +280 -0
  16. package/crates/ai-vault/src/store.rs +219 -0
  17. package/install.sh +21 -0
  18. package/package.json +76 -5
  19. package/packages/pi-ai-vault/README.md +62 -0
  20. package/packages/pi-ai-vault/package.json +47 -0
  21. package/packages/pi-ai-vault/src/bitwarden.ts +1482 -0
  22. package/packages/pi-ai-vault/src/cli.ts +171 -0
  23. package/packages/pi-ai-vault/src/host.ts +76 -0
  24. package/packages/pi-ai-vault/src/import-map.ts +91 -0
  25. package/packages/pi-ai-vault/src/index.ts +976 -0
  26. package/packages/pi-ai-vault/src/prompt.ts +195 -0
  27. package/packages/pi-ai-vault/src/scrub.ts +157 -0
  28. package/test/cli.sh +135 -0
  29. package/test/npm.sh +70 -0
  30. package/test/smoke.sh +77 -0
  31. package/tests/bitwarden-tools.test.mjs +330 -0
  32. package/tests/helpers.mjs +131 -0
  33. package/tests/import-map.test.mjs +74 -0
  34. package/tests/mocks/bin/bw +41 -0
  35. package/tests/mocks/bin/wl-copy +15 -0
  36. package/tests/mocks/bin/wl-paste +9 -0
  37. package/tests/mocks/bin/zenity +51 -0
  38. package/tests/prompt.test.mjs +200 -0
  39. package/tests/register.test.mjs +48 -0
  40. package/tests/scrub.test.mjs +98 -0
  41. package/tests/vault-cli.test.mjs +217 -0
@@ -0,0 +1,976 @@
1
+ /**
2
+ * ai-vault — the pi/omp extension.
3
+ *
4
+ * The store itself lives in the `ai-vault` Rust binary, in one machine-wide
5
+ * directory (~/.ai-vault), so pi, omp, and anything else on this computer
6
+ * share the same imported passwords. This file only registers tools and a
7
+ * command, keeps one session token per binding, and opens host dialogs when
8
+ * the CLI has no desktop window of its own.
9
+ *
10
+ * Bitwarden stays here: `bw_*` tools query the live vault through the `bw`
11
+ * CLI, and `vault_import` copies login items into the local store via
12
+ * `ai-vault save`.
13
+ */
14
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
15
+ import { Type } from "typebox";
16
+ import {
17
+ lookupBitwardenLogin,
18
+ newBwState,
19
+ pullBitwardenLogins,
20
+ queryBitwarden,
21
+ registerBitwarden,
22
+ type BitwardenMeta,
23
+ type BwState,
24
+ } from "./bitwarden.js";
25
+ import { CliError, VaultCli } from "./cli.js";
26
+ import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
27
+ import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
28
+
29
+ type Ctx = ExtensionToolContext | ExtensionCommandContext;
30
+
31
+ const GRANT_MS_DEFAULT = 5 * 60_000;
32
+
33
+ type UnlockModeName = "never" | "time" | "session";
34
+
35
+ interface StatusResult {
36
+ ok: boolean;
37
+ unlocked: boolean;
38
+ items: number;
39
+ requester: string;
40
+ idleMs: number;
41
+ expiresAt: number | null;
42
+ mode: UnlockModeName;
43
+ hours: number;
44
+ auto: boolean;
45
+ grants: Record<string, { expiresAt: number; leftMs: number }>;
46
+ }
47
+
48
+ interface UnlockResult {
49
+ ok: boolean;
50
+ token: string;
51
+ expiresAt: number | null;
52
+ items: number;
53
+ mode?: UnlockModeName;
54
+ auto?: boolean;
55
+ }
56
+
57
+ interface ListResult {
58
+ ok: boolean;
59
+ count: number;
60
+ items: { name: string; username?: string | null; uris: string[]; updatedAt: string }[];
61
+ }
62
+
63
+ interface RemovingResult {
64
+ ok: boolean;
65
+ removed: boolean;
66
+ }
67
+
68
+ interface SaveResult {
69
+ ok: boolean;
70
+ count: number;
71
+ names: string[];
72
+ }
73
+
74
+ interface AuditResult {
75
+ ok: boolean;
76
+ entries: { ts: string; session: string; event: string; item?: string; reason?: string }[];
77
+ }
78
+
79
+ /**
80
+ * One binding (a session, or a subagent) and the CLI session token it holds.
81
+ * The token is not the key: the key never leaves the ai-vault process tree.
82
+ */
83
+ interface Scope {
84
+ token?: string;
85
+ /** Bumped when access is dropped; an unlock prompt opened before is discarded. */
86
+ epoch: number;
87
+ /** Cached entry count for the status line. */
88
+ items: number;
89
+ /** The machine-wide unlock policy, as the CLI last reported it. */
90
+ mode?: UnlockModeName;
91
+ /** True when reads use the machine-wide session instead of a token. */
92
+ auto?: boolean;
93
+ unlocking?: Promise<boolean>;
94
+ }
95
+
96
+ const cli = new VaultCli();
97
+
98
+ const CLI_MISSING =
99
+ "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)";
100
+ const NOT_INITIALIZED = "本地库还没初始化 — 运行 /vault init";
101
+ const LOCKED = "local vault is locked (no master password entered, or the window was cancelled)";
102
+
103
+ const dialogs = (ctx: Ctx): PromptHost => ctx as unknown as PromptHost;
104
+ const note = (ctx: Ctx, text: string, level: "info" | "warning" | "error" = "info"): void => ctx.ui.notify(text, level);
105
+
106
+ const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
107
+
108
+ /** What a tool call hands back; every error path uses the same shape. */
109
+ interface ToolOutcome {
110
+ content: { type: "text"; text: string }[];
111
+ details: { ok?: boolean; denied?: boolean; item?: string; via?: string; count?: number };
112
+ isError?: boolean;
113
+ }
114
+
115
+ type Failure = ToolOutcome;
116
+
117
+ const fail = (text: string, denied = false): Failure => ({
118
+ content: [{ type: "text" as const, text }],
119
+ details: { ok: false, ...(denied ? { denied: true } : {}) },
120
+ isError: true,
121
+ });
122
+
123
+ /** Turn a CLI error into a tool result, dropping a token the CLI rejected. */
124
+ function failure(scope: Scope, error: unknown): Failure {
125
+ if (error instanceof CliError && error.auth) {
126
+ scope.token = undefined;
127
+ return fail(LOCKED);
128
+ }
129
+ if (error instanceof CliError && error.denied) return fail(error.message, true);
130
+ return fail(describe(error));
131
+ }
132
+
133
+ const setStatus = (ctx: Ctx, scope: Scope, suffix = ""): void => {
134
+ const base = scope.token ? `vault:open(${scope.items})` : "vault:locked";
135
+ ctx.ui.setStatus("ai-vault", `${base}${suffix}`);
136
+ };
137
+
138
+ /** End this binding's CLI session. The CLI deletes the token file. */
139
+ async function lockNow(scope: Scope): Promise<void> {
140
+ const token = scope.token;
141
+ scope.token = undefined;
142
+ scope.epoch++;
143
+ scope.items = 0;
144
+ if (!token || !cli.available) return;
145
+ try {
146
+ await cli.run(["lock", "--token", token]);
147
+ } catch {
148
+ /* the token dies on its own idle timeout */
149
+ }
150
+ }
151
+
152
+ /** Args for a CLI call: this binding's token, or the machine-wide session. */
153
+ const tokenArgs = (scope: Scope): string[] => (scope.token ? ["--token", scope.token] : []);
154
+
155
+ /** Make this binding's unlock happen; never throws. */
156
+ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Promise<boolean> {
157
+ if (!cli.available) {
158
+ note(ctx, CLI_MISSING, "error");
159
+ return false;
160
+ }
161
+ if (scope.unlocking) return scope.unlocking;
162
+ const epoch = scope.epoch;
163
+ scope.unlocking = (async (): Promise<boolean> => {
164
+ if (scope.token) {
165
+ try {
166
+ const status = await cli.json<StatusResult>(["status", "--token", scope.token], { signal });
167
+ scope.items = status.items;
168
+ scope.mode = status.mode;
169
+ scope.auto = false;
170
+ return true;
171
+ } catch (error) {
172
+ if (!(error instanceof CliError) || !error.auth) {
173
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
174
+ return false;
175
+ }
176
+ scope.token = undefined;
177
+ if (/not initialized/i.test(error.message)) {
178
+ note(ctx, NOT_INITIALIZED, "warning");
179
+ return false;
180
+ }
181
+ }
182
+ }
183
+ // `never` mode keeps a machine-wide session: no token, no window. Ask the
184
+ // CLI before opening anything, so that mode really is password-free.
185
+ try {
186
+ const status = await cli.json<StatusResult>(["status"], { signal });
187
+ scope.items = status.items;
188
+ scope.mode = status.mode;
189
+ scope.auto = status.auto;
190
+ return true;
191
+ } catch (error) {
192
+ if (error instanceof CliError && /not initialized/i.test(error.message)) {
193
+ note(ctx, NOT_INITIALIZED, "warning");
194
+ return false;
195
+ }
196
+ if (!(error instanceof CliError) || !error.auth) {
197
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
198
+ return false;
199
+ }
200
+ }
201
+ const attempt = async (password?: string): Promise<UnlockResult> => {
202
+ const args = ["unlock", "--requester", sessionLabel(ctx)];
203
+ if (password !== undefined) args.push("--password-stdin");
204
+ return cli.json<UnlockResult>(args, {
205
+ stdin: password === undefined ? undefined : `${password}\n`,
206
+ signal,
207
+ });
208
+ };
209
+ try {
210
+ let result: UnlockResult;
211
+ try {
212
+ result = await attempt();
213
+ } catch (error) {
214
+ if (!(error instanceof CliError) || !error.needsUi) throw error;
215
+ const password = await promptSecret(dialogs(ctx), "ai-vault · 解锁", "本地库主密码", signal);
216
+ if (!password) {
217
+ if (!signal?.aborted) note(ctx, "没有输入主密码(窗口已取消,或没有桌面/界面)", "warning");
218
+ return false;
219
+ }
220
+ result = await attempt(password);
221
+ }
222
+ // /vault lock or a session switch ran while the window was open.
223
+ if (epoch !== scope.epoch || signal?.aborted) {
224
+ await cli.run(["lock", "--token", result.token]).catch(() => undefined);
225
+ return false;
226
+ }
227
+ scope.mode = result.mode;
228
+ scope.auto = result.mode === "never";
229
+ // In `never` mode the CLI wrote the machine-wide session; keeping a
230
+ // per-binding token would bring back a confirm window on every read.
231
+ scope.token = result.mode === "never" ? undefined : result.token;
232
+ scope.items = result.items;
233
+ return true;
234
+ } catch (error) {
235
+ if (error instanceof CliError && error.auth) {
236
+ note(ctx, "ai-vault: 主密码错误", "error");
237
+ return false;
238
+ }
239
+ if (error instanceof CliError && /not initialized/i.test(error.message)) {
240
+ note(ctx, NOT_INITIALIZED, "warning");
241
+ return false;
242
+ }
243
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
244
+ return false;
245
+ }
246
+ })().finally(() => {
247
+ scope.unlocking = undefined;
248
+ });
249
+ return scope.unlocking;
250
+ }
251
+
252
+ // ---------------------------------------------------------------- local vault
253
+
254
+ const vaultListParams = Type.Object({});
255
+ function vaultListTool(scope: Scope): ToolDefinition<typeof vaultListParams, { ok?: boolean; count?: number }> {
256
+ const tool: ToolDefinition<typeof vaultListParams, { ok?: boolean; count?: number }> = {
257
+ name: "vault_list",
258
+ label: "Vault: list local entries",
259
+ description:
260
+ "List entries in the machine-wide ai-vault store (metadata only: name, username, uris). " +
261
+ "This is NOT Bitwarden — use bw_list to query Bitwarden live, and vault_import to copy Bitwarden logins into this store. " +
262
+ "Use vault_get to read a secret; that opens a confirm window and the grant expires.",
263
+ promptSnippet: "List local vault metadata; secrets need vault_get plus a user grant.",
264
+ parameters: vaultListParams,
265
+ async execute(_id, _params, signal, _onUpdate, ctx) {
266
+ if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
267
+ try {
268
+ const result = await cli.json<ListResult>(["list", "--token", scope.token!], { signal });
269
+ scope.items = result.count;
270
+ setStatus(ctx, scope);
271
+ return {
272
+ content: [{ type: "text" as const, text: JSON.stringify(result.items, null, 1) }],
273
+ details: { count: result.count },
274
+ };
275
+ } catch (error) {
276
+ return failure(scope, error);
277
+ }
278
+ },
279
+ };
280
+ return withTier(tool, "read");
281
+ }
282
+
283
+ const vaultGetParams = Type.Object({
284
+ name: Type.String({ description: "Entry name, e.g. 'cloudcone-panel'" }),
285
+ reason: Type.Optional(Type.String({ description: "Why this secret is needed (shown to the user in the confirm window)" })),
286
+ });
287
+ type VaultGetDetails = { ok?: boolean; denied?: boolean; item?: string; via?: string };
288
+
289
+ /**
290
+ * The local vault is the first stop; Bitwarden is the fallback. A hit there is
291
+ * offered to the user twice: read it this once, then optionally import it so
292
+ * later reads never touch Bitwarden.
293
+ */
294
+ async function bitwardenFallback(
295
+ scope: Scope,
296
+ ctx: Ctx,
297
+ bw: BwState,
298
+ name: string,
299
+ reason: string | undefined,
300
+ localMiss: string,
301
+ signal?: AbortSignal,
302
+ ): Promise<ToolOutcome> {
303
+ const missing = localMiss;
304
+ let hit;
305
+ try {
306
+ hit = await lookupBitwardenLogin(bw, ctx, name, signal);
307
+ } catch (error) {
308
+ return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
309
+ }
310
+ if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
311
+
312
+ const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
313
+ const allow = await confirmWindow(
314
+ dialogs(ctx),
315
+ "pi-ai-vault · Bitwarden 里找到",
316
+ `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
317
+ signal,
318
+ );
319
+ if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
320
+
321
+ const importIt = await confirmWindow(
322
+ dialogs(ctx),
323
+ "pi-ai-vault · 导入到 ai-vault",
324
+ `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
325
+ signal,
326
+ );
327
+ if (importIt) {
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 {
347
+ content: [
348
+ {
349
+ type: "text" as const,
350
+ text: JSON.stringify(
351
+ { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "imported-from-bitwarden" },
352
+ null,
353
+ 1,
354
+ ),
355
+ },
356
+ ],
357
+ details: { item: hit.name, via: "imported-from-bitwarden" },
358
+ };
359
+ }
360
+
361
+ return {
362
+ content: [
363
+ {
364
+ type: "text" as const,
365
+ text: JSON.stringify(
366
+ { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "bitwarden-once" },
367
+ null,
368
+ 1,
369
+ ),
370
+ },
371
+ ],
372
+ details: { item: hit.name, via: "bitwarden-once" },
373
+ };
374
+ }
375
+
376
+ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
377
+ const viaOf = (stdout: string): string => {
378
+ try {
379
+ return (JSON.parse(stdout) as { via?: string }).via ?? "grant";
380
+ } catch {
381
+ return "grant";
382
+ }
383
+ };
384
+ const tool: ToolDefinition<typeof vaultGetParams, VaultGetDetails> = {
385
+ name: "vault_get",
386
+ label: "Vault: read a secret (local first, Bitwarden second)",
387
+ description:
388
+ "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. " +
389
+ "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. " +
390
+ "If the user denies, do not retry. Use bw_run when the value must never enter the chat.",
391
+ promptSnippet: "Read a secret: local vault first, then Bitwarden (with an import offer).",
392
+ parameters: vaultGetParams,
393
+ async execute(_id, params, signal, _onUpdate, ctx) {
394
+ if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
395
+ const base = ["get", params.name, ...(params.reason ? ["--reason", params.reason] : []), ...tokenArgs(scope)];
396
+ try {
397
+ try {
398
+ const run = await cli.run([...base, "--json"], { signal });
399
+ setStatus(ctx, scope, "·ok");
400
+ return {
401
+ content: [{ type: "text" as const, text: run.stdout.trim() }],
402
+ details: { item: params.name, via: viaOf(run.stdout) },
403
+ };
404
+ } catch (error) {
405
+ if (error instanceof CliError && error.needsUi === "confirm") {
406
+ const sub = subagentId(ctx);
407
+ const allowed = await confirmWindow(
408
+ dialogs(ctx),
409
+ "ai-vault · 读取本地密码",
410
+ `条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
411
+ "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
412
+ signal,
413
+ );
414
+ const run = await cli.run([...base, "--json", "--answer-stdin"], {
415
+ stdin: allowed ? "y\n" : "n\n",
416
+ signal,
417
+ });
418
+ setStatus(ctx, scope, "·granted");
419
+ return {
420
+ content: [{ type: "text" as const, text: run.stdout.trim() }],
421
+ details: { item: params.name, via: viaOf(run.stdout) },
422
+ };
423
+ }
424
+ if (error instanceof CliError && /^no such entry/.test(error.message)) {
425
+ return await bitwardenFallback(scope, ctx, bw, params.name, params.reason, error.message, signal);
426
+ }
427
+ throw error;
428
+ }
429
+ } catch (error) {
430
+ if (error instanceof CliError && error.denied) setStatus(ctx, scope, "·denied");
431
+ return failure(scope, error);
432
+ }
433
+ },
434
+ };
435
+ return tool;
436
+ }
437
+
438
+ const vaultAddParams = Type.Object({
439
+ name: Type.String({ description: "Entry name to create or update, e.g. 'github'" }),
440
+ username: Type.Optional(Type.String({ description: "Account username. Omit to let the user type it in a dialog." })),
441
+ uri: Type.Optional(Type.String({ description: "Optional site or host URI" })),
442
+ notes: Type.Optional(Type.String({ description: "Optional non-secret note. Do NOT put the password here." })),
443
+ });
444
+ function vaultAddTool(scope: Scope): ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> {
445
+ const tool: ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> = {
446
+ name: "vault_add",
447
+ label: "Vault: store a secret via dialog",
448
+ description:
449
+ "Create or update an entry in the machine-wide ai-vault store. You supply the name and optional username, URI, and notes. " +
450
+ "The password is typed by the user in a desktop window and is NEVER accepted from you and NEVER returned. " +
451
+ "Do not ask the user to paste a password into the chat.",
452
+ promptSnippet: "Save a local vault entry; the user types the password in a window.",
453
+ parameters: vaultAddParams,
454
+ async execute(_id, params, signal, _onUpdate, ctx) {
455
+ const result = await saveLocalEntry(scope, ctx, {
456
+ name: params.name,
457
+ username: params.username,
458
+ uri: params.uri,
459
+ notes: params.notes,
460
+ signal,
461
+ });
462
+ const ok = result.startsWith("saved ");
463
+ return {
464
+ content: [{ type: "text" as const, text: result }],
465
+ details: ok ? { item: params.name } : { ok: false },
466
+ isError: ok ? undefined : true,
467
+ };
468
+ },
469
+ };
470
+ return withTier(tool, "write");
471
+ }
472
+
473
+ const vaultImportParams = Type.Object({
474
+ search: Type.Optional(
475
+ Type.String({ description: "Only import items whose name, username, or URI contains this text. Omit for every login that has a password." }),
476
+ ),
477
+ });
478
+ function vaultImportTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultImportParams, { ok?: boolean; count?: number }> {
479
+ const tool: ToolDefinition<typeof vaultImportParams, { ok?: boolean; count?: number }> = {
480
+ name: "vault_import",
481
+ label: "Vault: import from Bitwarden",
482
+ description:
483
+ "Copy Bitwarden login items into the machine-wide encrypted ai-vault store. " +
484
+ "Asks the user to approve in a window, then stores passwords locally. Does not return secret values. " +
485
+ "Use bw_list to query Bitwarden without copying it. Same-name local entries are updated.",
486
+ promptSnippet: "Import Bitwarden logins into the local vault after the user confirms.",
487
+ parameters: vaultImportParams,
488
+ async execute(_id, params, signal, _onUpdate, ctx) {
489
+ const result = await importBitwarden(scope, ctx, bw, params.search, signal);
490
+ return {
491
+ content: [{ type: "text" as const, text: result.text }],
492
+ details: { ok: result.ok, count: result.count },
493
+ isError: result.ok ? undefined : true,
494
+ };
495
+ },
496
+ };
497
+ return withTier(tool, "write");
498
+ }
499
+
500
+ interface SaveRequest {
501
+ name?: string;
502
+ username?: string;
503
+ uri?: string;
504
+ notes?: string;
505
+ signal?: AbortSignal;
506
+ }
507
+
508
+ /** Save one entry, following the CLI's dialog windows through the host UI. */
509
+ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise<string> {
510
+ if (!(await ensureUnlocked(scope, ctx, req.signal))) return LOCKED;
511
+ let name = req.name?.trim() ?? "";
512
+ if (!name) {
513
+ const entered = await promptText(dialogs(ctx), "ai-vault · 新条目", "名称", req.signal);
514
+ name = entered?.trim() ?? "";
515
+ }
516
+ if (!name) return "cancelled: no entry name";
517
+
518
+ const args = ["add", "--name", name, "--token", scope.token!];
519
+ if (req.username !== undefined) args.push("--username", req.username);
520
+ if (req.uri?.trim()) args.push("--uri", req.uri.trim());
521
+ if (req.notes?.trim()) args.push("--notes", req.notes.trim());
522
+ let stdin: string | undefined;
523
+ for (let attempt = 0; attempt < 5; attempt++) {
524
+ try {
525
+ const run = await cli.run([...args, "--json"], { stdin, signal: req.signal });
526
+ const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean };
527
+ if (saved.created) scope.items += 1;
528
+ setStatus(ctx, scope);
529
+ return `saved "${saved.item ?? name}" (password entered in the dialog, not shown)`;
530
+ } catch (error) {
531
+ if (!(error instanceof CliError) || !error.needsUi) {
532
+ if (error instanceof CliError && error.auth) scope.token = undefined;
533
+ return error instanceof CliError && error.denied ? error.message : `ai-vault: ${describe(error)}`;
534
+ }
535
+ if (error.needsUi === "confirm") {
536
+ const meta = [
537
+ req.username?.trim() ? `用户名: ${req.username.trim()}` : "",
538
+ req.uri?.trim() ? `URI: ${req.uri.trim()}` : "",
539
+ req.notes?.trim() ? `备注: ${req.notes.trim()}` : "",
540
+ ]
541
+ .filter(Boolean)
542
+ .join("\n");
543
+ const ok = await confirmWindow(
544
+ dialogs(ctx),
545
+ "ai-vault · 保存到本地库",
546
+ `保存条目「${name}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
547
+ req.signal,
548
+ );
549
+ if (!ok) return `user denied saving "${name}"`;
550
+ args.push("--yes");
551
+ continue;
552
+ }
553
+ if (error.needsUi === "text") {
554
+ const entered = await promptText(dialogs(ctx), `ai-vault · ${name}`, "用户名(可留空)", req.signal);
555
+ if (entered === undefined) return "cancelled";
556
+ args.push("--username", entered);
557
+ continue;
558
+ }
559
+ const password = await promptSecret(dialogs(ctx), "ai-vault · 密码", name, req.signal);
560
+ if (!password) return "cancelled: no password entered";
561
+ args.push("--password-stdin");
562
+ stdin = `${password}\n`;
563
+ }
564
+ }
565
+ return "cancelled: the save dialog did not settle";
566
+ }
567
+
568
+ async function importBitwarden(
569
+ scope: Scope,
570
+ ctx: Ctx,
571
+ bw: BwState,
572
+ search: string | undefined,
573
+ signal?: AbortSignal,
574
+ ): Promise<{ text: string; ok: boolean; count: number }> {
575
+ if (!(await ensureUnlocked(scope, ctx, signal))) return { text: LOCKED, ok: false, count: 0 };
576
+ let meta: BitwardenMeta[];
577
+ try {
578
+ meta = await queryBitwarden(bw, ctx, search, signal);
579
+ } catch (error) {
580
+ return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
581
+ }
582
+ if (meta.length === 0) {
583
+ return { text: search ? `no Bitwarden items match "${search}"` : "Bitwarden vault has no items", ok: false, count: 0 };
584
+ }
585
+ const shown = meta
586
+ .slice(0, 15)
587
+ .map((item) => `• ${item.name}${item.username ? ` user:${item.username}` : ""}${item.uri ? ` ${item.uri}` : ""}`)
588
+ .join("\n");
589
+ const more = meta.length > 15 ? `\n… 还有 ${meta.length - 15} 条` : "";
590
+ const allowed = await confirmWindow(
591
+ dialogs(ctx),
592
+ "ai-vault · 从 Bitwarden 导入",
593
+ `匹配 ${meta.length} 条。其中带密码的登录项会写入本地加密库,同名条目会被更新。\n\n${shown}${more}\n\n允许导入?`,
594
+ signal,
595
+ );
596
+ if (!allowed) return { text: "user denied the Bitwarden import", ok: false, count: 0 };
597
+ let drafts;
598
+ try {
599
+ drafts = await pullBitwardenLogins(bw, ctx, search, signal);
600
+ } catch (error) {
601
+ return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
602
+ }
603
+ if (drafts.length === 0) {
604
+ return { text: "matched items have no login password; nothing imported", ok: false, count: 0 };
605
+ }
606
+ try {
607
+ const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
608
+ stdin: JSON.stringify(drafts),
609
+ signal,
610
+ });
611
+ scope.items += saved.count;
612
+ setStatus(ctx, scope);
613
+ const listed = saved.names.slice(0, 40).join(", ");
614
+ const extra = saved.names.length > 40 ? ` … +${saved.names.length - 40}` : "";
615
+ return {
616
+ text: `imported ${saved.count} login item(s) into the local vault: ${listed}${extra}`,
617
+ ok: true,
618
+ count: saved.count,
619
+ };
620
+ } catch (error) {
621
+ return { text: `ai-vault: ${describe(error)}`, ok: false, count: 0 };
622
+ }
623
+ }
624
+
625
+ // ---------------------------------------------------------------- commands
626
+
627
+ const HELP = [
628
+ "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
629
+ "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
630
+ "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
631
+ "/vault status 状态与授权剩余时间",
632
+ "/vault list 本地条目元数据",
633
+ "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
634
+ '/vault remove <名称> 删除本地条目(带空格的名称加引号:"GitHub (2)")',
635
+ "/vault grant <名称> [分钟] 手动授权读取(默认 5 分钟,上限 60)",
636
+ "/vault revoke <名称|all> 撤销授权",
637
+ "/vault audit [n] 最近 n 条审计(默认 30)",
638
+ "/vault import <bitwarden.json> 从 Bitwarden 未加密 JSON 导出导入",
639
+ "/vault import-bw [搜索词] 直接从 bw CLI 导入登录项(先弹窗确认)",
640
+ "/bw status|unlock|lock|clear 在线 Bitwarden 会话(见 bw_* 工具)",
641
+ ].join("\n");
642
+
643
+ /** Split a command line into words; quotes keep a name such as "GitHub (2)" intact. */
644
+ function words(args: string): string[] {
645
+ const out: string[] = [];
646
+ for (const m of args.trim().matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)) out.push(m[1] ?? m[2] ?? m[3] ?? "");
647
+ return out;
648
+ }
649
+
650
+ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
651
+ if (!cli.available) {
652
+ note(ctx, CLI_MISSING, "error");
653
+ return;
654
+ }
655
+ const finish = (result: UnlockResult): void => {
656
+ scope.token = result.token;
657
+ scope.items = 0;
658
+ setStatus(ctx, scope);
659
+ note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
660
+ };
661
+ try {
662
+ finish(await cli.json<UnlockResult>(["init", "--requester", label]));
663
+ return;
664
+ } catch (error) {
665
+ if (!(error instanceof CliError)) {
666
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
667
+ return;
668
+ }
669
+ if (!error.needsUi) {
670
+ note(ctx, `ai-vault: ${error.message}`, "warning");
671
+ return;
672
+ }
673
+ }
674
+ const pass = await promptSecret(dialogs(ctx), "ai-vault · 创建主密码", "至少 8 位");
675
+ if (!pass || pass.length < 8) {
676
+ note(ctx, "已取消,或密码短于 8 位", "warning");
677
+ return;
678
+ }
679
+ const again = await promptSecret(dialogs(ctx), "ai-vault · 确认主密码", "再输入一次");
680
+ if (again !== pass) {
681
+ note(ctx, "两次主密码不一致,已取消", "warning");
682
+ return;
683
+ }
684
+ try {
685
+ finish(await cli.json<UnlockResult>(["init", "--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
686
+ } catch (error) {
687
+ note(ctx, `ai-vault: ${error instanceof CliError ? error.message : describe(error)}`, "error");
688
+ }
689
+ }
690
+
691
+ function commandHandler(scope: Scope, bw: BwState) {
692
+ return async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
693
+ const [sub = "status", ...rest] = words(args);
694
+ const label = sessionLabel(ctx);
695
+
696
+ switch (sub) {
697
+ case "help": {
698
+ note(ctx, HELP);
699
+ return;
700
+ }
701
+ case "init": {
702
+ await initStore(scope, ctx, label);
703
+ return;
704
+ }
705
+ case "unlock": {
706
+ if (await ensureUnlocked(scope, ctx)) setStatus(ctx, scope);
707
+ return;
708
+ }
709
+ case "lock": {
710
+ await lockNow(scope);
711
+ setStatus(ctx, scope);
712
+ note(ctx, "本地库已锁定,授权已清空");
713
+ return;
714
+ }
715
+ case "status": {
716
+ try {
717
+ const status = await cli.json<StatusResult>(["status", ...tokenArgs(scope)]);
718
+ scope.items = status.items;
719
+ scope.mode = status.mode;
720
+ scope.auto = status.auto;
721
+ setStatus(ctx, scope);
722
+ const expiry = status.expiresAt
723
+ ? `${Math.max(0, Math.round((status.expiresAt - Date.now()) / 1000))}s`
724
+ : "never";
725
+ const how =
726
+ status.mode === "never"
727
+ ? "never(免密)"
728
+ : status.mode === "time"
729
+ ? `time(每 ${status.hours}h 要一次密码)`
730
+ : "session(每个会话一次)";
731
+ const lines = [
732
+ `store: ${cli.dir}/store.json`,
733
+ `session: ${status.requester}`,
734
+ "state: unlocked",
735
+ `mode: ${how}`,
736
+ `items: ${status.items}`,
737
+ `expires: ${expiry}`,
738
+ ];
739
+ for (const [name, grant] of Object.entries(status.grants)) {
740
+ lines.push(`grant: ${name} (${Math.ceil(grant.leftMs / 1000)}s left)`);
741
+ }
742
+ note(ctx, lines.join("\n"));
743
+ } catch (error) {
744
+ scope.token = undefined;
745
+ note(
746
+ ctx,
747
+ [
748
+ `store: ${cli.dir}/store.json`,
749
+ `session: ${label}`,
750
+ "state: locked",
751
+ `ai-vault: ${describe(error)}`,
752
+ ].join("\n"),
753
+ "warning",
754
+ );
755
+ setStatus(ctx, scope);
756
+ }
757
+ return;
758
+ }
759
+ case "mode": {
760
+ const [sub, hoursArg] = rest;
761
+ if (!sub || sub === "get" || sub === "status") {
762
+ try {
763
+ const current = await cli.json<{ mode: string; hours: number; auto: boolean }>(["mode"]);
764
+ note(
765
+ ctx,
766
+ [
767
+ `mode: ${current.mode}`,
768
+ `hours: ${current.hours}(time 模式用)`,
769
+ `machine-wide session: ${current.auto ? "yes(免密)" : "no"}`,
770
+ "",
771
+ "/vault mode never|time|session [小时] 切换(要主密码)",
772
+ ].join("\n"),
773
+ );
774
+ } catch (error) {
775
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
776
+ }
777
+ return;
778
+ }
779
+ if (!["never", "time", "session", "no-password"].includes(sub)) {
780
+ note(ctx, "用法: /vault mode [never|time|session] [小时]", "warning");
781
+ return;
782
+ }
783
+ const args = ["mode", "set", sub];
784
+ if (hoursArg) args.push("--hours", hoursArg);
785
+ try {
786
+ const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), "ai-vault · 主密码", "切换解锁模式"));
787
+ const result = JSON.parse(run.stdout) as { mode: UnlockModeName; hours: number; auto: boolean };
788
+ await lockNow(scope);
789
+ scope.mode = result.mode;
790
+ scope.auto = result.auto;
791
+ setStatus(ctx, scope);
792
+ const how =
793
+ result.mode === "never"
794
+ ? "以后免密(密钥已写盘,任何能读你文件的程序都能读到库里的密码)"
795
+ : result.mode === "time"
796
+ ? `以后每 ${result.hours} 小时要一次密码`
797
+ : "以后每个会话要一次密码";
798
+ note(ctx, `mode → ${result.mode},${how}`);
799
+ } catch (error) {
800
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
801
+ }
802
+ return;
803
+ }
804
+ case "list": {
805
+ if (!(await ensureUnlocked(scope, ctx))) return;
806
+ try {
807
+ const result = await cli.json<ListResult>(["list", "--token", scope.token!]);
808
+ scope.items = result.count;
809
+ const rows = result.items.map((i) => `${i.name}\t${i.username ?? ""}\t${i.uris[0] ?? ""}`);
810
+ note(ctx, rows.join("\n") || "(empty)");
811
+ } catch (error) {
812
+ note(ctx, `ai-vault: ${describe(error)}`, "warning");
813
+ }
814
+ return;
815
+ }
816
+ case "add": {
817
+ const text = await saveLocalEntry(scope, ctx, { name: rest.join(" ") || undefined });
818
+ note(ctx, text, text.startsWith("saved ") ? "info" : "warning");
819
+ return;
820
+ }
821
+ case "remove": {
822
+ const name = rest.join(" ");
823
+ if (!(await ensureUnlocked(scope, ctx))) return;
824
+ if (!name) {
825
+ note(ctx, "用法: /vault remove <名称>", "warning");
826
+ return;
827
+ }
828
+ const args = ["remove", name, "--token", scope.token!];
829
+ try {
830
+ const result = await cli.json<RemovingResult>(args);
831
+ if (result.removed) scope.items = Math.max(0, scope.items - 1);
832
+ setStatus(ctx, scope);
833
+ note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
834
+ } catch (error) {
835
+ if (!(error instanceof CliError) || error.needsUi !== "confirm") {
836
+ note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
837
+ return;
838
+ }
839
+ const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${name}」?删除后无法恢复。`);
840
+ if (!sure) return;
841
+ try {
842
+ const result = await cli.json<RemovingResult>([...args, "--yes"]);
843
+ if (result.removed) scope.items = Math.max(0, scope.items - 1);
844
+ setStatus(ctx, scope);
845
+ note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
846
+ } catch (inner) {
847
+ note(ctx, `ai-vault: ${describe(inner)}`, "error");
848
+ }
849
+ }
850
+ return;
851
+ }
852
+ case "grant": {
853
+ const last = rest.at(-1) ?? "";
854
+ // A single numeric token is the entry name ("/vault grant 123");
855
+ // minutes are only read when a name comes before them.
856
+ const minutes = rest.length > 1 && /^\d+$/.test(last) ? rest.pop() : undefined;
857
+ const name = rest.join(" ");
858
+ if (!(await ensureUnlocked(scope, ctx)) || !name) {
859
+ note(ctx, "先解锁;用法: /vault grant <名称> [分钟](带空格的名称加引号)", "warning");
860
+ return;
861
+ }
862
+ const args = ["grant", name, "--token", scope.token!];
863
+ if (minutes) args.push("--minutes", minutes);
864
+ try {
865
+ const result = await cli.json<{ name: string; minutes: number }>(args);
866
+ setStatus(ctx, scope, "·granted");
867
+ note(ctx, `granted "${result.name}" for ${result.minutes}m`);
868
+ } catch (error) {
869
+ note(ctx, `ai-vault: ${describe(error)}`, "warning");
870
+ }
871
+ return;
872
+ }
873
+ case "revoke": {
874
+ if (!(await ensureUnlocked(scope, ctx))) return;
875
+ const target = rest[0] === "all" ? "all" : rest.join(" ").trim();
876
+ const args = ["revoke", "--token", scope.token!];
877
+ if (target === "all") args.push("--all");
878
+ else if (target) args.push(target);
879
+ else {
880
+ note(ctx, "用法: /vault revoke <名称|all>", "warning");
881
+ return;
882
+ }
883
+ try {
884
+ await cli.json(args);
885
+ setStatus(ctx, scope);
886
+ note(ctx, "revoked");
887
+ } catch (error) {
888
+ note(ctx, `ai-vault: ${describe(error)}`, "warning");
889
+ }
890
+ return;
891
+ }
892
+ case "audit": {
893
+ const asked = Number(rest[0] ?? 30);
894
+ const n = Number.isFinite(asked) && asked > 0 ? Math.min(Math.trunc(asked), 1000) : 30;
895
+ try {
896
+ const result = await cli.json<AuditResult>(["audit", String(n)]);
897
+ const rows = result.entries.map(
898
+ (e) => `${e.ts} ${e.session} ${e.event}${e.item ? ` ${e.item}` : ""}${e.reason ? ` (${e.reason})` : ""}`,
899
+ );
900
+ note(ctx, rows.join("\n") || "(no entries)");
901
+ } catch (error) {
902
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
903
+ }
904
+ return;
905
+ }
906
+ case "import": {
907
+ const path = rest.join(" ");
908
+ if (!path) {
909
+ note(ctx, "用法: /vault import <bitwarden-export.json>", "warning");
910
+ return;
911
+ }
912
+ if (!(await ensureUnlocked(scope, ctx))) return;
913
+ const args = ["import", path, "--token", scope.token!];
914
+ try {
915
+ const result = await cli.json<SaveResult>(args);
916
+ scope.items += result.count;
917
+ setStatus(ctx, scope);
918
+ note(ctx, `imported ${result.count} login items`);
919
+ } catch (error) {
920
+ if (!(error instanceof CliError) || error.needsUi !== "confirm") {
921
+ note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
922
+ return;
923
+ }
924
+ const sure = await confirmWindow(
925
+ dialogs(ctx),
926
+ "ai-vault · 从 Bitwarden 导入",
927
+ `导入 ${path} 里的 Bitwarden 登录项?同名条目会被更新。`,
928
+ );
929
+ if (!sure) return;
930
+ try {
931
+ const result = await cli.json<SaveResult>([...args, "--yes"]);
932
+ scope.items += result.count;
933
+ setStatus(ctx, scope);
934
+ note(ctx, `imported ${result.count} login items`);
935
+ } catch (inner) {
936
+ note(ctx, `ai-vault: ${describe(inner)}`, "error");
937
+ }
938
+ }
939
+ return;
940
+ }
941
+ case "import-bw": {
942
+ const search = rest.join(" ").trim() || undefined;
943
+ const result = await importBitwarden(scope, ctx, bw, search);
944
+ note(ctx, result.text, result.ok ? "info" : "warning");
945
+ return;
946
+ }
947
+ default: {
948
+ note(ctx, `unknown subcommand "${sub}"\n${HELP}`, "warning");
949
+ }
950
+ }
951
+ };
952
+ }
953
+
954
+ export default function aiVault(pi: ExtensionAPI): void {
955
+ const omp = isOmpHost(pi);
956
+ const scope: Scope = { token: undefined, epoch: 0, items: 0, unlocking: undefined };
957
+ const bw = newBwState();
958
+ pi.registerTool(vaultListTool(scope));
959
+ pi.registerTool(vaultGetTool(scope, bw));
960
+ pi.registerTool(vaultAddTool(scope));
961
+ pi.registerTool(vaultImportTool(scope, bw));
962
+ registerBitwarden(pi, bw, omp);
963
+ pi.registerCommand("vault", {
964
+ description: "本地密码库 + Bitwarden 导入(/vault help)",
965
+ handler: commandHandler(scope, bw),
966
+ });
967
+ // A transcript that starts fresh (/new, /fork) must not inherit this unlock
968
+ // or its grants. A /resume keeps them: same process, same user.
969
+ onSessionLeave(pi, omp, (reason) => {
970
+ if (reason === "resume") return;
971
+ void lockNow(scope);
972
+ });
973
+ }
974
+
975
+ /** Exported for tests: the shared grant window. */
976
+ export const grantMs = GRANT_MS_DEFAULT;