Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import type { ProviderRequestKind, RuntimeMode } from "@t3tools/contracts";
3import type * as EffectAcpSchema from "effect-acp/compat";
4import * as NodeFS from "node:fs";
5import * as NodePath from "node:path";
6
7export interface AcpRuntimePolicy {
8 readonly runtimeMode: RuntimeMode;
9 readonly cwd: string | null;
10 readonly approvalPolicy?: unknown;
11 readonly sandboxPolicy?: unknown;
12}
13
14export type AcpPermissionDisposition = "allow" | "ask" | "deny";
15
16export function unknownRecord(value: unknown): Record<string, unknown> | undefined {
17 return typeof value === "object" && value !== null && !Array.isArray(value)
18 ? (value as Record<string, unknown>)
19 : undefined;
20}
21
22function resolveAcpPermissionPath(path: string, cwd: string | null): string | undefined {
23 const trimmed = path.trim();
24 if (trimmed.length === 0) return undefined;
25 if (NodePath.isAbsolute(trimmed)) return trimmed;
26 if (cwd === null || cwd.trim().length === 0) return undefined;
27 return `${cwd}${cwd.endsWith(NodePath.sep) ? "" : NodePath.sep}${trimmed}`;
28}
29
30function acpPathIsWithinRoot(path: string, root: string): boolean {
31 const relative = NodePath.relative(root, path);
32 return (
33 relative === "" ||
34 (relative !== ".." &&
35 !relative.startsWith(`..${NodePath.sep}`) &&
36 !NodePath.isAbsolute(relative))
37 );
38}
39
40/**
41 * `realpath` cannot resolve a file that has not been created yet, so walk up to the deepest
42 * existing ancestor and append the missing suffix to that ancestor's canonical path. If an
43 * existing entry cannot be canonicalized (for example, a broken symlink), fail closed.
44 */
45function acpCanonicalPathForContainment(path: string): string | undefined {
46 // Do not lexically normalize before realpath. For a path such as
47 // `workspace/link/../file`, the kernel resolves `link` before `..`; an
48 // eager NodePath.resolve would erase that symlink traversal and could turn
49 // an outside target into an apparently in-workspace path.
50 let candidate = path;
51 const missingSuffix: Array<string> = [];
52
53 while (true) {
54 try {
55 return NodePath.resolve(NodeFS.realpathSync.native(candidate), ...missingSuffix);
56 } catch (cause) {
57 if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
58 return undefined;
59 }
60 }
61
62 try {
63 NodeFS.lstatSync(candidate);
64 return undefined;
65 } catch (cause) {
66 if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
67 return undefined;
68 }
69 }
70
71 const parent = NodePath.dirname(candidate);
72 if (parent === candidate) return undefined;
73 missingSuffix.unshift(NodePath.basename(candidate));
74 candidate = parent;
75 }
76}
77
78interface AcpPolicyOperation {
79 readonly kind: string | null | undefined;
80 readonly locations: ReadonlyArray<{ readonly path: string }> | null | undefined;
81}
82
83function acpPolicyRequiresApproval(runtimePolicy: AcpRuntimePolicy): boolean {
84 return runtimePolicy.approvalPolicy === undefined
85 ? runtimePolicy.runtimeMode === "approval-required"
86 : runtimePolicy.approvalPolicy !== "never";
87}
88
89function isAcpReadKind(toolKind: string): boolean {
90 return toolKind === "read" || toolKind === "search" || toolKind === "think";
91}
92
93/**
94 * Reads follow the sandbox alone and never ask. That includes no explicit sandbox, since the
95 * strictest runtime mode (approval-required) implies a read-only one.
96 */
97function acpReadDisposition(runtimePolicy: AcpRuntimePolicy): "allow" | "deny" {
98 switch (unknownRecord(runtimePolicy.sandboxPolicy)?.type) {
99 case undefined:
100 case "readOnly":
101 case "workspaceWrite":
102 case "dangerFullAccess":
103 case "externalSandbox":
104 return "allow";
105 default:
106 return "deny";
107 }
108}
109
110function acpWorkspaceWriteAllowsMutation(
111 runtimePolicy: AcpRuntimePolicy,
112 sandboxPolicy: Record<string, unknown>,
113 locations: AcpPolicyOperation["locations"],
114): boolean {
115 const cwd =
116 typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0
117 ? (resolveAcpPermissionPath(runtimePolicy.cwd, process.cwd()) ?? null)
118 : null;
119 const roots: Array<string> = [];
120 if (cwd !== null) {
121 const canonicalCwd = acpCanonicalPathForContainment(cwd);
122 if (canonicalCwd !== undefined) roots.push(canonicalCwd);
123 }
124 const writableRoots = sandboxPolicy.writableRoots;
125 if (Array.isArray(writableRoots)) {
126 for (const writableRoot of writableRoots) {
127 if (typeof writableRoot !== "string") continue;
128 const resolved = resolveAcpPermissionPath(writableRoot, cwd);
129 if (resolved === undefined) continue;
130 const canonicalRoot = acpCanonicalPathForContainment(resolved);
131 if (canonicalRoot !== undefined) roots.push(canonicalRoot);
132 }
133 }
134 if (roots.length === 0) return false;
135
136 if (locations === undefined || locations === null || locations.length === 0) {
137 return false;
138 }
139 for (const location of locations) {
140 const resolved = resolveAcpPermissionPath(location.path, cwd);
141 const canonicalPath =
142 resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved);
143 if (
144 canonicalPath === undefined ||
145 !roots.some((root) => acpPathIsWithinRoot(canonicalPath, root))
146 ) {
147 return false;
148 }
149 }
150 return true;
151}
152
153function acpOperationDisposition(
154 runtimePolicy: AcpRuntimePolicy,
155 operation: AcpPolicyOperation,
156): AcpPermissionDisposition {
157 const toolKind = operation.kind ?? "other";
158 if (isAcpReadKind(toolKind)) {
159 return acpReadDisposition(runtimePolicy);
160 }
161 if (acpPolicyRequiresApproval(runtimePolicy)) {
162 return "ask";
163 }
164
165 const sandboxPolicy = unknownRecord(runtimePolicy.sandboxPolicy);
166 switch (sandboxPolicy?.type) {
167 case "readOnly":
168 return "deny";
169 case "workspaceWrite":
170 if (isAcpMutationKind(toolKind)) {
171 return acpWorkspaceWriteAllowsMutation(
172 runtimePolicy,
173 sandboxPolicy ?? {},
174 operation.locations,
175 )
176 ? "allow"
177 : "deny";
178 }
179 return "deny";
180 case "dangerFullAccess":
181 case "externalSandbox":
182 return "allow";
183 case undefined:
184 if (runtimePolicy.runtimeMode === "approval-required") return "deny";
185 if (
186 runtimePolicy.runtimeMode === "auto-accept-edits" &&
187 runtimePolicy.approvalPolicy === undefined &&
188 !isAcpMutationKind(toolKind)
189 ) {
190 return "ask";
191 }
192 return "allow";
193 default:
194 return "deny";
195 }
196}
197
198function isAcpMutationKind(toolKind: string): boolean {
199 return toolKind === "edit" || toolKind === "delete" || toolKind === "move";
200}
201
202export function acpPermissionDisposition(
203 runtimePolicy: AcpRuntimePolicy,
204 request: EffectAcpSchema.RequestPermissionRequest,
205): AcpPermissionDisposition {
206 return acpOperationDisposition(runtimePolicy, {
207 kind: request.toolCall.kind,
208 locations: request.toolCall.locations,
209 });
210}
211
212export function acpMcpToolApprovalElicitationDisposition(
213 runtimePolicy: AcpRuntimePolicy,
214 request: EffectAcpSchema.CreateElicitationRequest,
215 nativeRequestId?: string,
216): AcpPermissionDisposition | undefined {
217 if (
218 request.mode !== "form" ||
219 (unknownRecord(request._meta)?.codex_approval_kind !== "mcp_tool_call" &&
220 nativeRequestId?.startsWith("mcp_tool_call_approval_") !== true)
221 ) {
222 return undefined;
223 }
224 // This request comes from T3's authenticated, scope-checked MCP endpoint,
225 // not an arbitrary provider command. Let explicit approval mode surface it
226 // to the user and otherwise allow the endpoint to enforce its own policy.
227 return acpPolicyRequiresApproval(runtimePolicy) ? "ask" : "allow";
228}
229
230export function acpClientExecuteDisposition(
231 runtimePolicy: AcpRuntimePolicy,
232): AcpPermissionDisposition {
233 return acpOperationDisposition(runtimePolicy, { kind: "execute", locations: undefined });
234}
235
236export interface AcpApprovalGrantInput {
237 readonly kind: ProviderRequestKind;
238 readonly scope: "session" | "turn";
239 readonly turnKey: string;
240}
241
242export interface AcpClientPolicyGrants {
243 readonly recordApproval: (input: AcpApprovalGrantInput) => void;
244 readonly allowsExecute: (turnKey: string | null) => boolean;
245}
246
247/**
248 * ACP does not link an approved tool call to the terminals the agent then creates, so an
249 * approved command authorizes client terminals for the approving turn, or for the session on
250 * accept-for-session.
251 */
252export function makeAcpClientPolicyGrants(): AcpClientPolicyGrants {
253 let sessionExecute = false;
254 let turnExecute: string | null = null;
255 return {
256 recordApproval: (input) => {
257 if (input.kind !== "command") return;
258 if (input.scope === "session") {
259 sessionExecute = true;
260 } else {
261 turnExecute = input.turnKey;
262 }
263 },
264 allowsExecute: (turnKey) => sessionExecute || (turnKey !== null && turnExecute === turnKey),
265 };
266}