import { AgentBroker, AgentServer, ApprovalRequest, brokerVault, Decision, defaultSocketPath, Grant, serveAgent, } from '@decryption/agent'; import { app, BrowserWindow, dialog, systemPreferences } from 'electron'; import { existsSync, promises as fs, readFileSync } from 'fs'; import * as os from 'os'; import * as path from 'path'; import { describeApproval } from '../shared/agent-prompt'; import type { AgentActivity, AgentStatus } from '../shared/api'; import { appDataPath, VaultService } from './vault-service'; /** How long a prompt waits for an answer before it counts as a denial. */ const PROMPT_TIMEOUT_MS = 2 * 60 * 1000; const settingsFile = (): string => path.join(appDataPath(), 'config', 'agent.json'); const readEnabled = (): boolean => { try { if (!existsSync(settingsFile())) return false; return JSON.parse(readFileSync(settingsFile(), 'utf8')).enabled === true; } catch { return false; } }; const tildify = (dir: string): string => { const home = os.homedir(); return dir === home || dir.startsWith(home + path.sep) ? `~${dir.slice(home.length)}` : dir; }; /** * Serves vault secrets to local agents through `@decryption/agent`, while this * app holds the unlocked vault. Off until the person turns it on; every * request is approved here; locking the vault clears every grant. */ export class AgentService { private server: AgentServer | null = null; private error: string | null = null; private readonly broker: AgentBroker; private enabled = readEnabled(); constructor( private readonly vaults: VaultService, private readonly window: () => BrowserWindow | null, private readonly changed: () => void ) { const vault = brokerVault(() => { try { return vaults.current(); } catch { return null; } }); this.broker = new AgentBroker({ vault: { ...vault, // each release writes an audit row: persist it like any other edit reveal: async (itemId, field, actor) => { const value = await vault.reveal(itemId, field, actor); vaults.scheduleSave(); this.changed(); return value; }, }, approve: (request) => this.approve(request), }); this.broker.grants.onChange(() => this.changed()); vaults.onLock(() => this.broker.grants.clear()); } async start(): Promise { if (this.enabled) await this.listen(); } async stop(): Promise { this.broker.grants.clear(); const server = this.server; this.server = null; await server?.close(); } status(): AgentStatus { return { enabled: this.enabled, serving: this.server !== null, socketPath: defaultSocketPath(), error: this.error, unlocked: this.vaults.status().unlocked, }; } async setEnabled(enabled: boolean): Promise { this.enabled = enabled; await fs.mkdir(path.dirname(settingsFile()), { recursive: true }); await fs.writeFile(settingsFile(), JSON.stringify({ enabled }), { mode: 0o600 }); if (enabled) await this.listen(); else await this.stop(); this.changed(); return this.status(); } grants(): Grant[] { return this.broker.grants.list(); } revoke(id: string): void { this.broker.grants.revoke(id); } revokeAll(): void { this.broker.grants.clear(); } /** An item stopped being shared: its grants go with it. */ forgetItem(itemId: string): void { this.broker.grants.revokeItem(itemId); } /** Agent-related audit entries, newest first, with item titles attached. */ async activity(limit = 100): Promise { const vault = this.vaults.current(); const [log, items, trashed] = await Promise.all([ vault.auditLog(), vault.listItems(), vault.listItems({ trashed: true }), ]); const titles = new Map([...items, ...trashed].map((item) => [item.id, item.title])); return log .filter((entry) => entry.action.startsWith('agent_')) .slice(0, limit) .map((entry) => ({ ...entry, itemTitle: entry.itemId ? (titles.get(entry.itemId) ?? null) : null })); } private async listen(): Promise { if (this.server) return; try { this.server = await serveAgent({ socketPath: defaultSocketPath(), handle: (request) => this.broker.handle(request), }); this.error = null; } catch (error) { this.error = error instanceof Error ? error.message : String(error); } } /** * Ask in a native dialog, in front of everything. Touch ID, where there is * one, has to confirm an "allow": a click can be synthesized by any program * that drives the screen — an agent with computer use included — a finger * cannot. */ private async approve(request: ApprovalRequest): Promise { const window = this.window(); if (!window || window.isDestroyed()) return 'deny'; if (window.isMinimized()) window.restore(); window.show(); app.focus({ steal: true }); const text = describeApproval(request, tildify); const abort = new AbortController(); const timer = setTimeout(() => abort.abort(), PROMPT_TIMEOUT_MS); let response: number; try { ({ response } = await dialog.showMessageBox(window, { type: 'warning', title: 'Agent request', message: text.title, detail: text.detail, buttons: ['Deny', 'Allow once', 'Allow for 1 hour'], defaultId: 0, cancelId: 0, noLink: true, signal: abort.signal, })); } catch { return 'deny'; } finally { clearTimeout(timer); } if (abort.signal.aborted || response === 0) return 'deny'; if (process.platform === 'darwin' && systemPreferences.canPromptTouchID()) { try { await systemPreferences.promptTouchID(`let ${request.client.name} use ${text.what}`); } catch { return 'deny'; } } return response === 2 ? 'grant' : 'once'; } }