@xiaolikt/ai-vault 0.0.0-stage → 0.4.1

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/src/index.ts ADDED
@@ -0,0 +1,772 @@
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 { newBwState, pullBitwardenLogins, queryBitwarden, registerBitwarden, type BitwardenMeta, type BwState } from "./bitwarden.js";
17
+ import { CliError, VaultCli } from "./cli.js";
18
+ import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
19
+ import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
20
+
21
+ type Ctx = ExtensionToolContext | ExtensionCommandContext;
22
+
23
+ const GRANT_MS_DEFAULT = 5 * 60_000;
24
+
25
+ interface StatusResult {
26
+ ok: boolean;
27
+ unlocked: boolean;
28
+ items: number;
29
+ requester: string;
30
+ idleMs: number;
31
+ expiresAt: number;
32
+ grants: Record<string, { expiresAt: number; leftMs: number }>;
33
+ }
34
+
35
+ interface UnlockResult {
36
+ ok: boolean;
37
+ token: string;
38
+ expiresAt: number;
39
+ items: number;
40
+ }
41
+
42
+ interface ListResult {
43
+ ok: boolean;
44
+ count: number;
45
+ items: { name: string; username?: string | null; uris: string[]; updatedAt: string }[];
46
+ }
47
+
48
+ interface RemovingResult {
49
+ ok: boolean;
50
+ removed: boolean;
51
+ }
52
+
53
+ interface SaveResult {
54
+ ok: boolean;
55
+ count: number;
56
+ names: string[];
57
+ }
58
+
59
+ interface AuditResult {
60
+ ok: boolean;
61
+ entries: { ts: string; session: string; event: string; item?: string; reason?: string }[];
62
+ }
63
+
64
+ /**
65
+ * One binding (a session, or a subagent) and the CLI session token it holds.
66
+ * The token is not the key: the key never leaves the ai-vault process tree.
67
+ */
68
+ interface Scope {
69
+ token?: string;
70
+ /** Bumped when access is dropped; an unlock prompt opened before is discarded. */
71
+ epoch: number;
72
+ /** Cached entry count for the status line. */
73
+ items: number;
74
+ unlocking?: Promise<boolean>;
75
+ }
76
+
77
+ const cli = new VaultCli();
78
+
79
+ const CLI_MISSING =
80
+ "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)";
81
+ const NOT_INITIALIZED = "本地库还没初始化 — 运行 /vault init";
82
+ const LOCKED = "local vault is locked (no master password entered, or the window was cancelled)";
83
+
84
+ const dialogs = (ctx: Ctx): PromptHost => ctx as unknown as PromptHost;
85
+ const note = (ctx: Ctx, text: string, level: "info" | "warning" | "error" = "info"): void => ctx.ui.notify(text, level);
86
+
87
+ const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
88
+
89
+ interface Failure {
90
+ content: { type: "text"; text: string }[];
91
+ details: { ok: false; denied?: boolean };
92
+ isError: true;
93
+ }
94
+
95
+ const fail = (text: string, denied = false): Failure => ({
96
+ content: [{ type: "text" as const, text }],
97
+ details: { ok: false, ...(denied ? { denied: true } : {}) },
98
+ isError: true,
99
+ });
100
+
101
+ /** Turn a CLI error into a tool result, dropping a token the CLI rejected. */
102
+ function failure(scope: Scope, error: unknown): Failure {
103
+ if (error instanceof CliError && error.auth) {
104
+ scope.token = undefined;
105
+ return fail(LOCKED);
106
+ }
107
+ if (error instanceof CliError && error.denied) return fail(error.message, true);
108
+ return fail(describe(error));
109
+ }
110
+
111
+ const setStatus = (ctx: Ctx, scope: Scope, suffix = ""): void => {
112
+ const base = scope.token ? `vault:open(${scope.items})` : "vault:locked";
113
+ ctx.ui.setStatus("ai-vault", `${base}${suffix}`);
114
+ };
115
+
116
+ /** End this binding's CLI session. The CLI deletes the token file. */
117
+ async function lockNow(scope: Scope): Promise<void> {
118
+ const token = scope.token;
119
+ scope.token = undefined;
120
+ scope.epoch++;
121
+ scope.items = 0;
122
+ if (!token || !cli.available) return;
123
+ try {
124
+ await cli.run(["lock", "--token", token]);
125
+ } catch {
126
+ /* the token dies on its own idle timeout */
127
+ }
128
+ }
129
+
130
+ /** Make this binding's unlock happen; never throws. */
131
+ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Promise<boolean> {
132
+ if (!cli.available) {
133
+ note(ctx, CLI_MISSING, "error");
134
+ return false;
135
+ }
136
+ if (scope.unlocking) return scope.unlocking;
137
+ const epoch = scope.epoch;
138
+ scope.unlocking = (async (): Promise<boolean> => {
139
+ if (scope.token) {
140
+ try {
141
+ const status = await cli.json<StatusResult>(["status", "--token", scope.token], { signal });
142
+ scope.items = status.items;
143
+ return true;
144
+ } catch (error) {
145
+ if (!(error instanceof CliError) || !error.auth) {
146
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
147
+ return false;
148
+ }
149
+ scope.token = undefined;
150
+ if (/not initialized/i.test(error.message)) {
151
+ note(ctx, NOT_INITIALIZED, "warning");
152
+ return false;
153
+ }
154
+ }
155
+ }
156
+ const attempt = async (password?: string): Promise<UnlockResult> => {
157
+ const args = ["unlock", "--requester", sessionLabel(ctx)];
158
+ if (password !== undefined) args.push("--password-stdin");
159
+ return cli.json<UnlockResult>(args, {
160
+ stdin: password === undefined ? undefined : `${password}\n`,
161
+ signal,
162
+ });
163
+ };
164
+ try {
165
+ let result: UnlockResult;
166
+ try {
167
+ result = await attempt();
168
+ } catch (error) {
169
+ if (!(error instanceof CliError) || !error.needsUi) throw error;
170
+ const password = await promptSecret(dialogs(ctx), "ai-vault · 解锁", "本地库主密码", signal);
171
+ if (!password) {
172
+ if (!signal?.aborted) note(ctx, "没有输入主密码(窗口已取消,或没有桌面/界面)", "warning");
173
+ return false;
174
+ }
175
+ result = await attempt(password);
176
+ }
177
+ // /vault lock or a session switch ran while the window was open.
178
+ if (epoch !== scope.epoch || signal?.aborted) {
179
+ await cli.run(["lock", "--token", result.token]).catch(() => undefined);
180
+ return false;
181
+ }
182
+ scope.token = result.token;
183
+ scope.items = result.items;
184
+ return true;
185
+ } catch (error) {
186
+ if (error instanceof CliError && error.auth) {
187
+ note(ctx, "ai-vault: 主密码错误", "error");
188
+ return false;
189
+ }
190
+ if (error instanceof CliError && /not initialized/i.test(error.message)) {
191
+ note(ctx, NOT_INITIALIZED, "warning");
192
+ return false;
193
+ }
194
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
195
+ return false;
196
+ }
197
+ })().finally(() => {
198
+ scope.unlocking = undefined;
199
+ });
200
+ return scope.unlocking;
201
+ }
202
+
203
+ // ---------------------------------------------------------------- local vault
204
+
205
+ const vaultListParams = Type.Object({});
206
+ function vaultListTool(scope: Scope): ToolDefinition<typeof vaultListParams, { ok?: boolean; count?: number }> {
207
+ const tool: ToolDefinition<typeof vaultListParams, { ok?: boolean; count?: number }> = {
208
+ name: "vault_list",
209
+ label: "Vault: list local entries",
210
+ description:
211
+ "List entries in the machine-wide ai-vault store (metadata only: name, username, uris). " +
212
+ "This is NOT Bitwarden — use bw_list to query Bitwarden live, and vault_import to copy Bitwarden logins into this store. " +
213
+ "Use vault_get to read a secret; that opens a confirm window and the grant expires.",
214
+ promptSnippet: "List local vault metadata; secrets need vault_get plus a user grant.",
215
+ parameters: vaultListParams,
216
+ async execute(_id, _params, signal, _onUpdate, ctx) {
217
+ if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
218
+ try {
219
+ const result = await cli.json<ListResult>(["list", "--token", scope.token!], { signal });
220
+ scope.items = result.count;
221
+ setStatus(ctx, scope);
222
+ return {
223
+ content: [{ type: "text" as const, text: JSON.stringify(result.items, null, 1) }],
224
+ details: { count: result.count },
225
+ };
226
+ } catch (error) {
227
+ return failure(scope, error);
228
+ }
229
+ },
230
+ };
231
+ return withTier(tool, "read");
232
+ }
233
+
234
+ const vaultGetParams = Type.Object({
235
+ name: Type.String({ description: "Entry name, e.g. 'cloudcone-panel'" }),
236
+ reason: Type.Optional(Type.String({ description: "Why this secret is needed (shown to the user in the confirm window)" })),
237
+ });
238
+ type VaultGetDetails = { ok?: boolean; denied?: boolean; item?: string; via?: string };
239
+ function vaultGetTool(scope: Scope): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
240
+ const tool: ToolDefinition<typeof vaultGetParams, VaultGetDetails> = {
241
+ name: "vault_get",
242
+ label: "Vault: read a local secret",
243
+ 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.",
247
+ parameters: vaultGetParams,
248
+ async execute(_id, params, signal, _onUpdate, ctx) {
249
+ 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);
252
+ 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
+ try {
261
+ const run = await cli.run([...args, "--json"], { signal });
262
+ setStatus(ctx, scope, "·granted");
263
+ return {
264
+ content: [{ type: "text" as const, text: run.stdout.trim() }],
265
+ details: { item: params.name, via: viaOf(run.stdout) },
266
+ };
267
+ } 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
+ };
286
+ }
287
+ } catch (error) {
288
+ if (error instanceof CliError && error.denied) setStatus(ctx, scope, "·denied");
289
+ return failure(scope, error);
290
+ }
291
+ },
292
+ };
293
+ return tool;
294
+ }
295
+
296
+ const vaultAddParams = Type.Object({
297
+ name: Type.String({ description: "Entry name to create or update, e.g. 'github'" }),
298
+ username: Type.Optional(Type.String({ description: "Account username. Omit to let the user type it in a dialog." })),
299
+ uri: Type.Optional(Type.String({ description: "Optional site or host URI" })),
300
+ notes: Type.Optional(Type.String({ description: "Optional non-secret note. Do NOT put the password here." })),
301
+ });
302
+ function vaultAddTool(scope: Scope): ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> {
303
+ const tool: ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> = {
304
+ name: "vault_add",
305
+ label: "Vault: store a secret via dialog",
306
+ description:
307
+ "Create or update an entry in the machine-wide ai-vault store. You supply the name and optional username, URI, and notes. " +
308
+ "The password is typed by the user in a desktop window and is NEVER accepted from you and NEVER returned. " +
309
+ "Do not ask the user to paste a password into the chat.",
310
+ promptSnippet: "Save a local vault entry; the user types the password in a window.",
311
+ parameters: vaultAddParams,
312
+ async execute(_id, params, signal, _onUpdate, ctx) {
313
+ const result = await saveLocalEntry(scope, ctx, {
314
+ name: params.name,
315
+ username: params.username,
316
+ uri: params.uri,
317
+ notes: params.notes,
318
+ signal,
319
+ });
320
+ const ok = result.startsWith("saved ");
321
+ return {
322
+ content: [{ type: "text" as const, text: result }],
323
+ details: ok ? { item: params.name } : { ok: false },
324
+ isError: ok ? undefined : true,
325
+ };
326
+ },
327
+ };
328
+ return withTier(tool, "write");
329
+ }
330
+
331
+ const vaultImportParams = Type.Object({
332
+ search: Type.Optional(
333
+ Type.String({ description: "Only import items whose name, username, or URI contains this text. Omit for every login that has a password." }),
334
+ ),
335
+ });
336
+ function vaultImportTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultImportParams, { ok?: boolean; count?: number }> {
337
+ const tool: ToolDefinition<typeof vaultImportParams, { ok?: boolean; count?: number }> = {
338
+ name: "vault_import",
339
+ label: "Vault: import from Bitwarden",
340
+ description:
341
+ "Copy Bitwarden login items into the machine-wide encrypted ai-vault store. " +
342
+ "Asks the user to approve in a window, then stores passwords locally. Does not return secret values. " +
343
+ "Use bw_list to query Bitwarden without copying it. Same-name local entries are updated.",
344
+ promptSnippet: "Import Bitwarden logins into the local vault after the user confirms.",
345
+ parameters: vaultImportParams,
346
+ async execute(_id, params, signal, _onUpdate, ctx) {
347
+ const result = await importBitwarden(scope, ctx, bw, params.search, signal);
348
+ return {
349
+ content: [{ type: "text" as const, text: result.text }],
350
+ details: { ok: result.ok, count: result.count },
351
+ isError: result.ok ? undefined : true,
352
+ };
353
+ },
354
+ };
355
+ return withTier(tool, "write");
356
+ }
357
+
358
+ interface SaveRequest {
359
+ name?: string;
360
+ username?: string;
361
+ uri?: string;
362
+ notes?: string;
363
+ signal?: AbortSignal;
364
+ }
365
+
366
+ /** Save one entry, following the CLI's dialog windows through the host UI. */
367
+ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise<string> {
368
+ if (!(await ensureUnlocked(scope, ctx, req.signal))) return LOCKED;
369
+ let name = req.name?.trim() ?? "";
370
+ if (!name) {
371
+ const entered = await promptText(dialogs(ctx), "ai-vault · 新条目", "名称", req.signal);
372
+ name = entered?.trim() ?? "";
373
+ }
374
+ if (!name) return "cancelled: no entry name";
375
+
376
+ const args = ["add", "--name", name, "--token", scope.token!];
377
+ if (req.username !== undefined) args.push("--username", req.username);
378
+ if (req.uri?.trim()) args.push("--uri", req.uri.trim());
379
+ if (req.notes?.trim()) args.push("--notes", req.notes.trim());
380
+ let stdin: string | undefined;
381
+ for (let attempt = 0; attempt < 5; attempt++) {
382
+ try {
383
+ const run = await cli.run([...args, "--json"], { stdin, signal: req.signal });
384
+ const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean };
385
+ if (saved.created) scope.items += 1;
386
+ setStatus(ctx, scope);
387
+ return `saved "${saved.item ?? name}" (password entered in the dialog, not shown)`;
388
+ } catch (error) {
389
+ if (!(error instanceof CliError) || !error.needsUi) {
390
+ if (error instanceof CliError && error.auth) scope.token = undefined;
391
+ return error instanceof CliError && error.denied ? error.message : `ai-vault: ${describe(error)}`;
392
+ }
393
+ if (error.needsUi === "confirm") {
394
+ const meta = [
395
+ req.username?.trim() ? `用户名: ${req.username.trim()}` : "",
396
+ req.uri?.trim() ? `URI: ${req.uri.trim()}` : "",
397
+ req.notes?.trim() ? `备注: ${req.notes.trim()}` : "",
398
+ ]
399
+ .filter(Boolean)
400
+ .join("\n");
401
+ const ok = await confirmWindow(
402
+ dialogs(ctx),
403
+ "ai-vault · 保存到本地库",
404
+ `保存条目「${name}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
405
+ req.signal,
406
+ );
407
+ if (!ok) return `user denied saving "${name}"`;
408
+ args.push("--yes");
409
+ continue;
410
+ }
411
+ if (error.needsUi === "text") {
412
+ const entered = await promptText(dialogs(ctx), `ai-vault · ${name}`, "用户名(可留空)", req.signal);
413
+ if (entered === undefined) return "cancelled";
414
+ args.push("--username", entered);
415
+ continue;
416
+ }
417
+ const password = await promptSecret(dialogs(ctx), "ai-vault · 密码", name, req.signal);
418
+ if (!password) return "cancelled: no password entered";
419
+ args.push("--password-stdin");
420
+ stdin = `${password}\n`;
421
+ }
422
+ }
423
+ return "cancelled: the save dialog did not settle";
424
+ }
425
+
426
+ async function importBitwarden(
427
+ scope: Scope,
428
+ ctx: Ctx,
429
+ bw: BwState,
430
+ search: string | undefined,
431
+ signal?: AbortSignal,
432
+ ): Promise<{ text: string; ok: boolean; count: number }> {
433
+ if (!(await ensureUnlocked(scope, ctx, signal))) return { text: LOCKED, ok: false, count: 0 };
434
+ let meta: BitwardenMeta[];
435
+ try {
436
+ meta = await queryBitwarden(bw, ctx, search, signal);
437
+ } catch (error) {
438
+ return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
439
+ }
440
+ if (meta.length === 0) {
441
+ return { text: search ? `no Bitwarden items match "${search}"` : "Bitwarden vault has no items", ok: false, count: 0 };
442
+ }
443
+ const shown = meta
444
+ .slice(0, 15)
445
+ .map((item) => `• ${item.name}${item.username ? ` user:${item.username}` : ""}${item.uri ? ` ${item.uri}` : ""}`)
446
+ .join("\n");
447
+ const more = meta.length > 15 ? `\n… 还有 ${meta.length - 15} 条` : "";
448
+ const allowed = await confirmWindow(
449
+ dialogs(ctx),
450
+ "ai-vault · 从 Bitwarden 导入",
451
+ `匹配 ${meta.length} 条。其中带密码的登录项会写入本地加密库,同名条目会被更新。\n\n${shown}${more}\n\n允许导入?`,
452
+ signal,
453
+ );
454
+ if (!allowed) return { text: "user denied the Bitwarden import", ok: false, count: 0 };
455
+ let drafts;
456
+ try {
457
+ drafts = await pullBitwardenLogins(bw, ctx, search, signal);
458
+ } catch (error) {
459
+ return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
460
+ }
461
+ if (drafts.length === 0) {
462
+ return { text: "matched items have no login password; nothing imported", ok: false, count: 0 };
463
+ }
464
+ try {
465
+ const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
466
+ stdin: JSON.stringify(drafts),
467
+ signal,
468
+ });
469
+ scope.items += saved.count;
470
+ setStatus(ctx, scope);
471
+ const listed = saved.names.slice(0, 40).join(", ");
472
+ const extra = saved.names.length > 40 ? ` … +${saved.names.length - 40}` : "";
473
+ return {
474
+ text: `imported ${saved.count} login item(s) into the local vault: ${listed}${extra}`,
475
+ ok: true,
476
+ count: saved.count,
477
+ };
478
+ } catch (error) {
479
+ return { text: `ai-vault: ${describe(error)}`, ok: false, count: 0 };
480
+ }
481
+ }
482
+
483
+ // ---------------------------------------------------------------- commands
484
+
485
+ const HELP = [
486
+ "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
487
+ "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
488
+ "/vault status 状态与授权剩余时间",
489
+ "/vault list 本地条目元数据",
490
+ "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
491
+ '/vault remove <名称> 删除本地条目(带空格的名称加引号:"GitHub (2)")',
492
+ "/vault grant <名称> [分钟] 手动授权读取(默认 5 分钟,上限 60)",
493
+ "/vault revoke <名称|all> 撤销授权",
494
+ "/vault audit [n] 最近 n 条审计(默认 30)",
495
+ "/vault import <bitwarden.json> 从 Bitwarden 未加密 JSON 导出导入",
496
+ "/vault import-bw [搜索词] 直接从 bw CLI 导入登录项(先弹窗确认)",
497
+ "/bw status|unlock|lock|clear 在线 Bitwarden 会话(见 bw_* 工具)",
498
+ ].join("\n");
499
+
500
+ /** Split a command line into words; quotes keep a name such as "GitHub (2)" intact. */
501
+ function words(args: string): string[] {
502
+ const out: string[] = [];
503
+ for (const m of args.trim().matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)) out.push(m[1] ?? m[2] ?? m[3] ?? "");
504
+ return out;
505
+ }
506
+
507
+ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
508
+ if (!cli.available) {
509
+ note(ctx, CLI_MISSING, "error");
510
+ return;
511
+ }
512
+ const finish = (result: UnlockResult): void => {
513
+ scope.token = result.token;
514
+ scope.items = 0;
515
+ setStatus(ctx, scope);
516
+ note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
517
+ };
518
+ try {
519
+ finish(await cli.json<UnlockResult>(["init", "--requester", label]));
520
+ return;
521
+ } catch (error) {
522
+ if (!(error instanceof CliError)) {
523
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
524
+ return;
525
+ }
526
+ if (!error.needsUi) {
527
+ note(ctx, `ai-vault: ${error.message}`, "warning");
528
+ return;
529
+ }
530
+ }
531
+ const pass = await promptSecret(dialogs(ctx), "ai-vault · 创建主密码", "至少 8 位");
532
+ if (!pass || pass.length < 8) {
533
+ note(ctx, "已取消,或密码短于 8 位", "warning");
534
+ return;
535
+ }
536
+ const again = await promptSecret(dialogs(ctx), "ai-vault · 确认主密码", "再输入一次");
537
+ if (again !== pass) {
538
+ note(ctx, "两次主密码不一致,已取消", "warning");
539
+ return;
540
+ }
541
+ try {
542
+ finish(await cli.json<UnlockResult>(["init", "--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
543
+ } catch (error) {
544
+ note(ctx, `ai-vault: ${error instanceof CliError ? error.message : describe(error)}`, "error");
545
+ }
546
+ }
547
+
548
+ function commandHandler(scope: Scope, bw: BwState) {
549
+ return async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
550
+ const [sub = "status", ...rest] = words(args);
551
+ const label = sessionLabel(ctx);
552
+
553
+ switch (sub) {
554
+ case "help": {
555
+ note(ctx, HELP);
556
+ return;
557
+ }
558
+ case "init": {
559
+ await initStore(scope, ctx, label);
560
+ return;
561
+ }
562
+ case "unlock": {
563
+ if (await ensureUnlocked(scope, ctx)) setStatus(ctx, scope);
564
+ return;
565
+ }
566
+ case "lock": {
567
+ await lockNow(scope);
568
+ setStatus(ctx, scope);
569
+ note(ctx, "本地库已锁定,授权已清空");
570
+ return;
571
+ }
572
+ 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
+ try {
579
+ const status = await cli.json<StatusResult>(["status", "--token", scope.token]);
580
+ scope.items = status.items;
581
+ const lines = [
582
+ `store: ${cli.dir}/store.json`,
583
+ `session: ${status.requester}`,
584
+ "state: unlocked",
585
+ `items: ${status.items}`,
586
+ `expires: ${Math.max(0, Math.round((status.expiresAt - Date.now()) / 1000))}s (idle lock ${Math.round(status.idleMs / 1000)}s)`,
587
+ ];
588
+ for (const [name, grant] of Object.entries(status.grants)) {
589
+ lines.push(`grant: ${name} (${Math.ceil(grant.leftMs / 1000)}s left)`);
590
+ }
591
+ note(ctx, lines.join("\n"));
592
+ setStatus(ctx, scope);
593
+ } catch (error) {
594
+ scope.token = undefined;
595
+ note(ctx, `ai-vault: ${describe(error)}`, "warning");
596
+ setStatus(ctx, scope);
597
+ }
598
+ return;
599
+ }
600
+ case "list": {
601
+ if (!(await ensureUnlocked(scope, ctx))) return;
602
+ try {
603
+ const result = await cli.json<ListResult>(["list", "--token", scope.token!]);
604
+ scope.items = result.count;
605
+ const rows = result.items.map((i) => `${i.name}\t${i.username ?? ""}\t${i.uris[0] ?? ""}`);
606
+ note(ctx, rows.join("\n") || "(empty)");
607
+ } catch (error) {
608
+ note(ctx, `ai-vault: ${describe(error)}`, "warning");
609
+ }
610
+ return;
611
+ }
612
+ case "add": {
613
+ const text = await saveLocalEntry(scope, ctx, { name: rest.join(" ") || undefined });
614
+ note(ctx, text, text.startsWith("saved ") ? "info" : "warning");
615
+ return;
616
+ }
617
+ case "remove": {
618
+ const name = rest.join(" ");
619
+ if (!(await ensureUnlocked(scope, ctx))) return;
620
+ if (!name) {
621
+ note(ctx, "用法: /vault remove <名称>", "warning");
622
+ return;
623
+ }
624
+ const args = ["remove", name, "--token", scope.token!];
625
+ try {
626
+ const result = await cli.json<RemovingResult>(args);
627
+ if (result.removed) scope.items = Math.max(0, scope.items - 1);
628
+ setStatus(ctx, scope);
629
+ note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
630
+ } catch (error) {
631
+ if (!(error instanceof CliError) || error.needsUi !== "confirm") {
632
+ note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
633
+ return;
634
+ }
635
+ const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${name}」?删除后无法恢复。`);
636
+ if (!sure) return;
637
+ try {
638
+ const result = await cli.json<RemovingResult>([...args, "--yes"]);
639
+ if (result.removed) scope.items = Math.max(0, scope.items - 1);
640
+ setStatus(ctx, scope);
641
+ note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
642
+ } catch (inner) {
643
+ note(ctx, `ai-vault: ${describe(inner)}`, "error");
644
+ }
645
+ }
646
+ return;
647
+ }
648
+ case "grant": {
649
+ const last = rest.at(-1) ?? "";
650
+ // A single numeric token is the entry name ("/vault grant 123");
651
+ // minutes are only read when a name comes before them.
652
+ const minutes = rest.length > 1 && /^\d+$/.test(last) ? rest.pop() : undefined;
653
+ const name = rest.join(" ");
654
+ if (!(await ensureUnlocked(scope, ctx)) || !name) {
655
+ note(ctx, "先解锁;用法: /vault grant <名称> [分钟](带空格的名称加引号)", "warning");
656
+ return;
657
+ }
658
+ const args = ["grant", name, "--token", scope.token!];
659
+ if (minutes) args.push("--minutes", minutes);
660
+ try {
661
+ const result = await cli.json<{ name: string; minutes: number }>(args);
662
+ setStatus(ctx, scope, "·granted");
663
+ note(ctx, `granted "${result.name}" for ${result.minutes}m`);
664
+ } catch (error) {
665
+ note(ctx, `ai-vault: ${describe(error)}`, "warning");
666
+ }
667
+ return;
668
+ }
669
+ case "revoke": {
670
+ if (!(await ensureUnlocked(scope, ctx))) return;
671
+ const target = rest[0] === "all" ? "all" : rest.join(" ").trim();
672
+ const args = ["revoke", "--token", scope.token!];
673
+ if (target === "all") args.push("--all");
674
+ else if (target) args.push(target);
675
+ else {
676
+ note(ctx, "用法: /vault revoke <名称|all>", "warning");
677
+ return;
678
+ }
679
+ try {
680
+ await cli.json(args);
681
+ setStatus(ctx, scope);
682
+ note(ctx, "revoked");
683
+ } catch (error) {
684
+ note(ctx, `ai-vault: ${describe(error)}`, "warning");
685
+ }
686
+ return;
687
+ }
688
+ case "audit": {
689
+ const asked = Number(rest[0] ?? 30);
690
+ const n = Number.isFinite(asked) && asked > 0 ? Math.min(Math.trunc(asked), 1000) : 30;
691
+ try {
692
+ const result = await cli.json<AuditResult>(["audit", String(n)]);
693
+ const rows = result.entries.map(
694
+ (e) => `${e.ts} ${e.session} ${e.event}${e.item ? ` ${e.item}` : ""}${e.reason ? ` (${e.reason})` : ""}`,
695
+ );
696
+ note(ctx, rows.join("\n") || "(no entries)");
697
+ } catch (error) {
698
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
699
+ }
700
+ return;
701
+ }
702
+ case "import": {
703
+ const path = rest.join(" ");
704
+ if (!path) {
705
+ note(ctx, "用法: /vault import <bitwarden-export.json>", "warning");
706
+ return;
707
+ }
708
+ if (!(await ensureUnlocked(scope, ctx))) return;
709
+ const args = ["import", path, "--token", scope.token!];
710
+ try {
711
+ const result = await cli.json<SaveResult>(args);
712
+ scope.items += result.count;
713
+ setStatus(ctx, scope);
714
+ note(ctx, `imported ${result.count} login items`);
715
+ } catch (error) {
716
+ if (!(error instanceof CliError) || error.needsUi !== "confirm") {
717
+ note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
718
+ return;
719
+ }
720
+ const sure = await confirmWindow(
721
+ dialogs(ctx),
722
+ "ai-vault · 从 Bitwarden 导入",
723
+ `导入 ${path} 里的 Bitwarden 登录项?同名条目会被更新。`,
724
+ );
725
+ if (!sure) return;
726
+ try {
727
+ const result = await cli.json<SaveResult>([...args, "--yes"]);
728
+ scope.items += result.count;
729
+ setStatus(ctx, scope);
730
+ note(ctx, `imported ${result.count} login items`);
731
+ } catch (inner) {
732
+ note(ctx, `ai-vault: ${describe(inner)}`, "error");
733
+ }
734
+ }
735
+ return;
736
+ }
737
+ case "import-bw": {
738
+ const search = rest.join(" ").trim() || undefined;
739
+ const result = await importBitwarden(scope, ctx, bw, search);
740
+ note(ctx, result.text, result.ok ? "info" : "warning");
741
+ return;
742
+ }
743
+ default: {
744
+ note(ctx, `unknown subcommand "${sub}"\n${HELP}`, "warning");
745
+ }
746
+ }
747
+ };
748
+ }
749
+
750
+ export default function aiVault(pi: ExtensionAPI): void {
751
+ const omp = isOmpHost(pi);
752
+ const scope: Scope = { token: undefined, epoch: 0, items: 0, unlocking: undefined };
753
+ const bw = newBwState();
754
+ pi.registerTool(vaultListTool(scope));
755
+ pi.registerTool(vaultGetTool(scope));
756
+ pi.registerTool(vaultAddTool(scope));
757
+ pi.registerTool(vaultImportTool(scope, bw));
758
+ registerBitwarden(pi, bw, omp);
759
+ pi.registerCommand("vault", {
760
+ description: "本地密码库 + Bitwarden 导入(/vault help)",
761
+ handler: commandHandler(scope, bw),
762
+ });
763
+ // A transcript that starts fresh (/new, /fork) must not inherit this unlock
764
+ // or its grants. A /resume keeps them: same process, same user.
765
+ onSessionLeave(pi, omp, (reason) => {
766
+ if (reason === "resume") return;
767
+ void lockNow(scope);
768
+ });
769
+ }
770
+
771
+ /** Exported for tests: the shared grant window. */
772
+ export const grantMs = GRANT_MS_DEFAULT;