mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-24 00:50:44 +00:00
* feat(ai): unify capability registry, harness tools, and agent runtime Centralize MCP/CLI/Catty tool surfaces in the capability catalog with codegen, move Catty-only harness tools into catalog with local execution, converge mcpServerBridge builtin dispatch via registry, and wire AgentRuntime with vault bridge, permission grants, and Round 2 catalog parity. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(ai): vault host tools, artifact cards, and external agent vault guidance Unify vault host create/import with capability RPC routing, add chat artifact cards with Vault navigation, and align external MCP agents with Catty rules so host creation never falls back to Vault Notes. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(ai): address Bugbot findings for streaming, vault bridge, and grants Clear Catty streaming by chat sessionId, read latest vault state via getters on agent mutations, and stack grant persisters so unmounting one AI panel does not break others. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(vault): clear pending openNoteId after chat navigation focus NotesManager notifies VaultView once the one-shot openNoteId request is applied so the id does not stick for the rest of the session. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(vault): serialize vault agent IPC mutations to prevent lost writes Queue vault agent bridge handlers so concurrent hosts.create or note.create tool calls cannot overwrite each other via stale read-modify-write snapshots. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(vault): keep synchronous vault snapshot for agent IPC reads Mirror hosts, notes, and groups in a ref updated immediately on agent writes so serialized mutations see the latest state before React re-renders. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(ai): sync Catty MCP sessions and defer runtime cleanup on delete Register terminal sessions with the main process before Catty tool calls, and clear ToolOutputStore only after stopping an active turn when deleting a chat session. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(ai): avoid deleting a newer abort controller on late stop Only remove the session abort-controller entry when stop finishes if it still refers to the controller that was stopped. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(ai): sync vault snapshot on render and await active turn on stop Refresh vault agent reads when React props change without clobbering in-flight agent writes, and wait for runTurn to finish before clearing ToolOutputStore on session delete. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(ai): reload permission grants from storage before auto-approve Re-read persisted grant rules on each approval check so revocations in Settings take effect without requiring a chat hook remount. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(ai): sync permission grants to main process immediately on write Push MCP permissionGrantsSnapshot as soon as Always allow persists a rule so the next tool call in the same agent turn sees the grant without waiting for useEffect. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
410 lines
13 KiB
TypeScript
410 lines
13 KiB
TypeScript
/**
|
|
* approvalGate — Promise-based approval system for tool execution.
|
|
*
|
|
* Tools call `requestApproval()` inside their `execute` function. This returns
|
|
* a Promise that resolves when the user approves/rejects from the UI, or after
|
|
* a timeout (default 5 minutes) to prevent indefinite hangs.
|
|
*
|
|
* Also supports MCP/SDK-agent tool calls from the Electron main process:
|
|
* the main process sends an IPC approval request, and we route it
|
|
* through the same listener/UI system. MCP approvals are stored in
|
|
* the same pendingApprovals map so they survive ChatMessageList
|
|
* unmount/remount cycles via replayPendingApprovals().
|
|
*
|
|
* Approvals are scoped by optional chatSessionId to prevent cross-session
|
|
* interference when stopping or cancelling sessions.
|
|
*/
|
|
|
|
import { CATTY_APPROVAL_TIMEOUT_MS } from './approvalConstants';
|
|
import { localStorageAdapter } from '../../persistence/localStorageAdapter';
|
|
import { STORAGE_KEY_AI_PERMISSION_GRANTS } from '../../config/storageKeys';
|
|
import { globalTraceStore } from '../harness/traceStore';
|
|
import {
|
|
getActivePermissionGrants,
|
|
matchPermissionGrant,
|
|
resolveCapabilityId,
|
|
sanitizePermissionGrants,
|
|
setActivePermissionGrants,
|
|
type PermissionGrantRule,
|
|
} from '../harness/permissionGrants';
|
|
|
|
export interface ApprovalRequest {
|
|
toolCallId: string;
|
|
toolName: string;
|
|
args: Record<string, unknown>;
|
|
/** Optional chat session scope — used to clear only relevant approvals on stop */
|
|
chatSessionId?: string;
|
|
capabilityId?: string;
|
|
}
|
|
|
|
export interface ResolveApprovalOptions {
|
|
approved: boolean;
|
|
persistGrant?: PermissionGrantRule;
|
|
persistGrants?: PermissionGrantRule[];
|
|
}
|
|
|
|
export type GrantPersister = (rule: PermissionGrantRule) => void;
|
|
|
|
let grantPersister: GrantPersister | null = null;
|
|
const grantPersisterStack: GrantPersister[] = [];
|
|
let grantsHydrated = false;
|
|
|
|
function refreshPermissionGrantsFromStorage(): void {
|
|
if (typeof window === 'undefined') return;
|
|
setActivePermissionGrants(
|
|
sanitizePermissionGrants(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_PERMISSION_GRANTS)),
|
|
);
|
|
grantsHydrated = true;
|
|
}
|
|
|
|
function ensureGrantsHydrated(): void {
|
|
if (grantsHydrated) return;
|
|
refreshPermissionGrantsFromStorage();
|
|
}
|
|
|
|
export function setGrantPersister(persister: GrantPersister | null): void {
|
|
grantPersisterStack.length = 0;
|
|
if (persister) {
|
|
grantPersisterStack.push(persister);
|
|
}
|
|
grantPersister = persister;
|
|
}
|
|
|
|
/** Register a grant persister; supports multiple mounted AI panels via a stack. */
|
|
export function registerGrantPersister(persister: GrantPersister): () => void {
|
|
grantPersisterStack.push(persister);
|
|
grantPersister = persister;
|
|
return () => {
|
|
const idx = grantPersisterStack.lastIndexOf(persister);
|
|
if (idx >= 0) {
|
|
grantPersisterStack.splice(idx, 1);
|
|
}
|
|
grantPersister = grantPersisterStack[grantPersisterStack.length - 1] ?? null;
|
|
};
|
|
}
|
|
|
|
// Pending approval entries keyed by toolCallId.
|
|
// SDK approvals have a real `resolve` callback; MCP approvals use a no-op
|
|
// (the real resolution goes via IPC in resolveApproval).
|
|
const pendingApprovals = new Map<string, {
|
|
resolve: (approved: boolean) => void;
|
|
request: ApprovalRequest;
|
|
}>();
|
|
|
|
// Subscribers for approval request events (UI listens here)
|
|
type ApprovalRequestListener = (request: ApprovalRequest) => void;
|
|
const listeners = new Set<ApprovalRequestListener>();
|
|
|
|
// Subscribers for approval cleared/removed events (UI listens to clean up cards)
|
|
type ApprovalClearedListener = (toolCallIds: string[]) => void;
|
|
const clearedListeners = new Set<ApprovalClearedListener>();
|
|
|
|
let approvalEventCounter = 0;
|
|
|
|
function nextApprovalEventId(prefix: string): string {
|
|
approvalEventCounter += 1;
|
|
return `${prefix}-${Date.now()}-${approvalEventCounter}`;
|
|
}
|
|
|
|
function emitApprovalEvent(
|
|
type: 'approval_requested' | 'approval_resolved',
|
|
request: ApprovalRequest,
|
|
extra?: { outcome?: 'approved' | 'denied' | 'timeout'; persistedGrantId?: string },
|
|
): void {
|
|
const sessionId = request.chatSessionId ?? 'global';
|
|
const capabilityId = request.capabilityId ?? resolveCapabilityId(request.toolName);
|
|
const base = {
|
|
sessionId,
|
|
chatSessionId: request.chatSessionId,
|
|
backend: 'catty' as const,
|
|
timestamp: Date.now(),
|
|
toolCallId: request.toolCallId,
|
|
toolName: request.toolName,
|
|
};
|
|
|
|
if (type === 'approval_requested') {
|
|
globalTraceStore.append({
|
|
...base,
|
|
id: nextApprovalEventId('approval-requested'),
|
|
type: 'approval_requested',
|
|
args: request.args,
|
|
});
|
|
return;
|
|
}
|
|
|
|
globalTraceStore.append({
|
|
...base,
|
|
id: nextApprovalEventId('approval-resolved'),
|
|
type: 'approval_resolved',
|
|
outcome: extra?.outcome ?? 'denied',
|
|
persistedGrantId: extra?.persistedGrantId,
|
|
});
|
|
}
|
|
|
|
function isGrantedByRules(request: ApprovalRequest): boolean {
|
|
refreshPermissionGrantsFromStorage();
|
|
const capabilityId = request.capabilityId ?? resolveCapabilityId(request.toolName);
|
|
return matchPermissionGrant(getActivePermissionGrants(), {
|
|
capabilityId,
|
|
chatSessionId: request.chatSessionId,
|
|
sessionId: typeof request.args.sessionId === 'string' ? request.args.sessionId : undefined,
|
|
args: request.args,
|
|
}) !== null;
|
|
}
|
|
|
|
/**
|
|
* Called from a tool's `execute` function when it needs user approval.
|
|
* Returns a Promise<boolean> that resolves to `true` (approved) or `false` (denied).
|
|
* The UI is notified via the listener system to render approval buttons.
|
|
*
|
|
* If the user does not respond within `timeoutMs` (default 5 minutes), the
|
|
* approval is auto-denied to prevent the session from hanging indefinitely.
|
|
*/
|
|
export function requestApproval(
|
|
toolCallId: string,
|
|
toolName: string,
|
|
args: Record<string, unknown>,
|
|
chatSessionId?: string,
|
|
timeoutMs: number = CATTY_APPROVAL_TIMEOUT_MS,
|
|
capabilityId?: string,
|
|
): Promise<boolean> {
|
|
const request: ApprovalRequest = {
|
|
toolCallId,
|
|
toolName,
|
|
args,
|
|
chatSessionId,
|
|
capabilityId: capabilityId ?? resolveCapabilityId(toolName),
|
|
};
|
|
|
|
if (isGrantedByRules(request)) {
|
|
return Promise.resolve(true);
|
|
}
|
|
|
|
emitApprovalEvent('approval_requested', request);
|
|
|
|
return new Promise<boolean>((resolve) => {
|
|
let timerId: ReturnType<typeof setTimeout> | null = null;
|
|
|
|
const wrappedResolve = (approved: boolean) => {
|
|
if (timerId) { clearTimeout(timerId); timerId = null; }
|
|
resolve(approved);
|
|
};
|
|
|
|
pendingApprovals.set(toolCallId, { resolve: wrappedResolve, request });
|
|
|
|
// Auto-deny after timeout so the session doesn't hang indefinitely
|
|
timerId = setTimeout(() => {
|
|
if (pendingApprovals.has(toolCallId)) {
|
|
pendingApprovals.delete(toolCallId);
|
|
wrappedResolve(false);
|
|
emitApprovalEvent('approval_resolved', request, { outcome: 'timeout' });
|
|
// Notify UI to remove the stale card
|
|
for (const cl of clearedListeners) {
|
|
try { cl([toolCallId]); } catch { /* ignore */ }
|
|
}
|
|
}
|
|
}, timeoutMs);
|
|
|
|
// Notify all UI listeners
|
|
for (const listener of listeners) {
|
|
try { listener(request); } catch { /* ignore listener errors */ }
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Called from the UI when the user approves or rejects a tool execution.
|
|
* Handles both SDK tool calls (local Promise) and MCP tool calls (IPC to main process).
|
|
*/
|
|
export function resolveApproval(
|
|
toolCallId: string,
|
|
decision: boolean | ResolveApprovalOptions,
|
|
): void {
|
|
const approved = typeof decision === 'boolean' ? decision : decision.approved;
|
|
const persistGrant = typeof decision === 'boolean' ? undefined : decision.persistGrant;
|
|
const persistGrants = typeof decision === 'boolean'
|
|
? undefined
|
|
: (decision.persistGrants ?? (persistGrant ? [persistGrant] : undefined));
|
|
|
|
const entry = pendingApprovals.get(toolCallId);
|
|
const request = entry?.request;
|
|
|
|
if (entry) {
|
|
pendingApprovals.delete(toolCallId);
|
|
entry.resolve(approved);
|
|
}
|
|
|
|
if (request) {
|
|
let persistedGrantId: string | undefined;
|
|
if (approved && persistGrants?.length) {
|
|
for (const grant of persistGrants) {
|
|
grantPersister?.(grant);
|
|
persistedGrantId = grant.id;
|
|
}
|
|
}
|
|
emitApprovalEvent('approval_resolved', request, {
|
|
outcome: approved ? 'approved' : 'denied',
|
|
persistedGrantId,
|
|
});
|
|
}
|
|
|
|
// MCP tool call: also forward response to main process via IPC
|
|
if (toolCallId.startsWith('mcp_approval_')) {
|
|
const bridge = (window as unknown as { netcatty?: { respondMcpApproval?: (id: string, approved: boolean) => Promise<unknown> } }).netcatty;
|
|
bridge?.respondMcpApproval?.(toolCallId, approved);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Subscribe to approval request events. Returns an unsubscribe function.
|
|
*/
|
|
export function onApprovalRequest(listener: ApprovalRequestListener): () => void {
|
|
listeners.add(listener);
|
|
return () => { listeners.delete(listener); };
|
|
}
|
|
|
|
/**
|
|
* Subscribe to approval cleared/removed events. Returns an unsubscribe function.
|
|
* Fired when approvals are cleared (e.g. on session stop) or timed out,
|
|
* so the UI can remove stale approval cards.
|
|
*/
|
|
export function onApprovalCleared(listener: ApprovalClearedListener): () => void {
|
|
clearedListeners.add(listener);
|
|
return () => { clearedListeners.delete(listener); };
|
|
}
|
|
|
|
/**
|
|
* Replay all currently pending approval requests to a listener.
|
|
* Useful when ChatMessageList remounts after being unmounted — without this,
|
|
* approvals that fired while unmounted would be silently missed and the
|
|
* corresponding execute Promises would hang indefinitely.
|
|
*
|
|
* This covers both SDK and MCP approvals since both are stored in the same map.
|
|
*/
|
|
export function replayPendingApprovals(listener: ApprovalRequestListener): void {
|
|
for (const [, entry] of pendingApprovals) {
|
|
try { listener(entry.request); } catch { /* ignore */ }
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if a specific toolCallId has a pending approval.
|
|
*/
|
|
export function hasPendingApproval(toolCallId: string): boolean {
|
|
return pendingApprovals.has(toolCallId);
|
|
}
|
|
|
|
/**
|
|
* Clear pending approvals, optionally scoped to a specific chatSessionId.
|
|
* Resolves matching entries with `false` (denied) so execute functions don't hang.
|
|
* Also notifies cleared-listeners so the UI can remove stale approval cards.
|
|
*
|
|
* When chatSessionId is provided, only approvals belonging to that session
|
|
* are cleared — preventing cross-session interference in concurrent chats.
|
|
* When omitted, all pending approvals are cleared (backward-compatible).
|
|
*/
|
|
export function clearAllPendingApprovals(chatSessionId?: string): void {
|
|
const clearedIds: string[] = [];
|
|
|
|
if (!chatSessionId) {
|
|
// Clear everything (legacy / global stop)
|
|
for (const [id, entry] of pendingApprovals) {
|
|
entry.resolve(false);
|
|
clearedIds.push(id);
|
|
}
|
|
pendingApprovals.clear();
|
|
} else {
|
|
// Scoped clear: only remove approvals for this chatSessionId
|
|
for (const [id, entry] of pendingApprovals) {
|
|
if (entry.request.chatSessionId === chatSessionId) {
|
|
pendingApprovals.delete(id);
|
|
entry.resolve(false);
|
|
clearedIds.push(id);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Notify UI listeners to remove the cards
|
|
if (clearedIds.length > 0) {
|
|
for (const cl of clearedListeners) {
|
|
try { cl(clearedIds); } catch { /* ignore */ }
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Set up a bridge to receive MCP/SDK-agent approval requests from the Electron main process.
|
|
* Subscribes to IPC events and stores them in the same pendingApprovals map,
|
|
* so the same ToolCall UI handles both SDK and MCP approvals, and approvals
|
|
* survive ChatMessageList unmount/remount cycles via replayPendingApprovals().
|
|
*
|
|
* IMPORTANT: Call this from a component that stays mounted for the lifetime of
|
|
* the AI panel (e.g. AIChatSidePanel), NOT from ChatMessageList which unmounts
|
|
* on tab switches.
|
|
*
|
|
* Returns an unsubscribe function.
|
|
*/
|
|
export function setupMcpApprovalBridge(): () => void {
|
|
const bridge = (window as unknown as {
|
|
netcatty?: {
|
|
onMcpApprovalRequest?: (cb: (payload: {
|
|
approvalId: string;
|
|
toolName: string;
|
|
args: Record<string, unknown>;
|
|
chatSessionId?: string;
|
|
}) => void) => () => void;
|
|
onMcpApprovalCleared?: (cb: (payload: {
|
|
approvalIds: string[];
|
|
}) => void) => () => void;
|
|
};
|
|
}).netcatty;
|
|
if (!bridge?.onMcpApprovalRequest) return () => {};
|
|
|
|
const unsubRequest = bridge.onMcpApprovalRequest((payload) => {
|
|
const request: ApprovalRequest = {
|
|
toolCallId: payload.approvalId,
|
|
toolName: payload.toolName,
|
|
args: payload.args,
|
|
chatSessionId: payload.chatSessionId,
|
|
capabilityId: resolveCapabilityId(payload.toolName),
|
|
};
|
|
|
|
// Store in pendingApprovals so it survives unmount/remount
|
|
// The resolve is a no-op because MCP approval resolution goes through IPC
|
|
// (handled in resolveApproval when toolCallId starts with 'mcp_approval_')
|
|
if (!pendingApprovals.has(payload.approvalId)) {
|
|
pendingApprovals.set(payload.approvalId, {
|
|
resolve: () => {}, // no-op; real resolution is via IPC
|
|
request,
|
|
});
|
|
}
|
|
|
|
// Notify all UI listeners
|
|
for (const listener of listeners) {
|
|
try { listener(request); } catch { /* ignore listener errors */ }
|
|
}
|
|
});
|
|
|
|
// Subscribe to main-process approval cleared events (timeout, cancel)
|
|
// so stale approval cards are removed from the renderer UI.
|
|
const unsubCleared = bridge.onMcpApprovalCleared?.((payload) => {
|
|
const clearedIds: string[] = [];
|
|
for (const id of payload.approvalIds) {
|
|
if (pendingApprovals.has(id)) {
|
|
pendingApprovals.delete(id);
|
|
clearedIds.push(id);
|
|
}
|
|
}
|
|
if (clearedIds.length > 0) {
|
|
for (const cl of clearedListeners) {
|
|
try { cl(clearedIds); } catch { /* ignore */ }
|
|
}
|
|
}
|
|
});
|
|
|
|
return () => {
|
|
unsubRequest();
|
|
unsubCleared?.();
|
|
};
|
|
}
|