Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

permissions.ts

71 lines2.4 KB

1import { approvalId } from '@tanstack/ai-sandbox'
2import { matchBridgedToolName } from './stream/translate'
3import type {
4 AcpPermissionMode,
5 AcpPermissionOutcome,
6 AcpPermissionRequest,
7 PermissionHandler,
8} from './types/acp-types'
9​
10export type { AcpPermissionMode, PermissionHandler }
11​
12const EDIT_KINDS = new Set(['edit', 'move', 'delete'])
13​
14function pickOption(
15 request: AcpPermissionRequest,
16 kinds: Array<string>,
17): AcpPermissionOutcome {
18 for (const kind of kinds) {
19 const option = request.options.find((candidate) => candidate.kind === kind)
20 if (option) return { outcome: 'selected', optionId: option.optionId }
21 }
22 return { outcome: 'cancelled' }
24​
25export function resolvePermission(
26 request: AcpPermissionRequest,
27 mode: AcpPermissionMode,
28 bridgedToolNames: ReadonlySet<string> | undefined,
29): AcpPermissionOutcome {
30 const allow = () => pickOption(request, ['allow_once', 'allow_always'])
31 const reject = () => pickOption(request, ['reject_once', 'reject_always'])
32​
33 if (
34 matchBridgedToolName(request.toolCall.title, bridgedToolNames) !== undefined
35 ) {
36 return allow()
37 }
38 if (mode === 'bypassPermissions') return allow()
39 if (mode === 'acceptEdits' && EDIT_KINDS.has(request.toolCall.kind ?? '')) {
40 return allow()
41 }
42 return reject()
44​
45export function resolveInteractivePermission(
46 request: AcpPermissionRequest,
47 mode: AcpPermissionMode,
48 bridgedToolNames: ReadonlySet<string> | undefined,
49 approvals: ReadonlyMap<string, boolean> | undefined,
50 provider: string,
51): { outcome: AcpPermissionOutcome; approvalId?: string; title?: string } {
52 const allow = (): AcpPermissionOutcome =>
53 pickOption(request, ['allow_once', 'allow_always'])
54 const reject = (): AcpPermissionOutcome =>
55 pickOption(request, ['reject_once', 'reject_always'])
56 const title = request.toolCall.title ?? request.toolCall.toolCallId
57​
58 if (matchBridgedToolName(title, bridgedToolNames) !== undefined) {
59 return { outcome: allow() }
60 }
61 if (mode === 'bypassPermissions') return { outcome: allow() }
62 if (mode === 'acceptEdits' && EDIT_KINDS.has(request.toolCall.kind ?? '')) {
63 return { outcome: allow() }
64 }
65​
66 const id = approvalId({ provider, kind: 'tool', target: title })
67 const granted = approvals?.get(id)
68 if (granted === true) return { outcome: allow() }
69 if (granted === false) return { outcome: reject() }
70 return { outcome: reject(), approvalId: id, title }