Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import type { 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 readonly workspace?: { readonly extraRoots: ReadonlyArray<string> } | undefined;
13}
14
15export type AcpPermissionDisposition = "allow" | "ask" | "deny";
16
17export function unknownRecord(value: unknown): Record<string, unknown> | undefined {
18 return typeof value === "object" && value !== null && !Array.isArray(value)
19 ? (value as Record<string, unknown>)
20 : undefined;
21}
22
23// The path is joined and resolved exactly as written; only the operating system may read it differently.
24function resolveAcpPermissionPath(path: string, cwd: string | null): string | undefined {
25 if (path.trim().length === 0) return undefined;
26 if (NodePath.isAbsolute(path)) return path;
27 if (cwd === null || cwd.trim().length === 0) return undefined;
28 return `${cwd}${cwd.endsWith(NodePath.sep) ? "" : NodePath.sep}${path}`;
29}
30
31function acpPathIsWithinRoot(path: string, root: string): boolean {
32 const relative = NodePath.relative(root, path);
33 return (
34 relative === "" ||
35 (relative !== ".." &&
36 !relative.startsWith(`..${NodePath.sep}`) &&
37 !NodePath.isAbsolute(relative))
38 );
39}
40
41// Canonicalize existing ancestors for symlink-aware checks of new paths; fail closed on errors.
42function acpCanonicalPathForContainment(path: string): string | undefined {
43 // realpath must resolve symlinks before ..; lexical normalization can hide traversal.
44 let candidate = path;
45 const missingSuffix: Array<string> = [];
46
47 while (true) {
48 try {
49 return NodePath.resolve(NodeFS.realpathSync.native(candidate), ...missingSuffix);
50 } catch (cause) {
51 if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
52 return undefined;
53 }
54 }
55
56 try {
57 NodeFS.lstatSync(candidate);
58 return undefined;
59 } catch (cause) {
60 if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
61 return undefined;
62 }
63 }
64
65 const parent = NodePath.dirname(candidate);
66 if (parent === candidate) return undefined;
67 missingSuffix.unshift(NodePath.basename(candidate));
68 candidate = parent;
69 }
70}
71
72/**
73 * Every path a file change touches, each exactly as the agent sent it, or "unknown" when any
74 * part of the change could not be read. An unknown change is never approved by a folder check.
75 */
76export type AcpChangedPaths = ReadonlyArray<string> | "unknown";
77
78/** A change that names more paths than this is treated as unknown rather than resolved one by one. */
79const MAX_ACP_CHANGED_PATHS = 256;
80
81/**
82 * The path as given when policy can resolve it the way the agent will. Blank strings, non-strings
83 * and NUL bytes name no file. A relative path that starts with `~`, has a URL scheme or drive
84 * prefix, or uses backslashes on a POSIX host may mean another file to the agent than it does
85 * when joined to the working directory.
86 */
87function acpCheckablePath(value: unknown): string | undefined {
88 if (typeof value !== "string" || value.trim().length === 0 || value.includes("\0")) {
89 return undefined;
90 }
91 if (NodePath.isAbsolute(value)) return value;
92 if (value.startsWith("~") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(value)) return undefined;
93 if (NodePath.sep === "/" && value.includes("\\")) return undefined;
94 return value;
95}
96
97/** Both sets together; unknown stays unknown. */
98export function mergeAcpChangedPaths(
99 left: AcpChangedPaths | undefined,
100 right: AcpChangedPaths | undefined,
101): AcpChangedPaths {
102 if (left === "unknown" || right === "unknown") return "unknown";
103 if (left === undefined || left.length === 0) return right ?? [];
104 if (right === undefined || right.length === 0) return left;
105 const merged = [...new Set([...left, ...right])];
106 return merged.length > MAX_ACP_CHANGED_PATHS ? "unknown" : merged;
107}
108
109/** The keys of a tool call's raw input that name a file it changes. */
110export const ACP_RAW_INPUT_PATH_KEYS = ["path", "filePath", "file_path"] as const;
111
112/**
113 * The one reading of which files a tool call changes, for a permission request and for every
114 * notification of the call it names: its locations, its diffs and the path keys of its raw input.
115 * A part without a checkable path, or of a kind this client does not know, makes it all unknown.
116 */
117export function acpChangedPathsOfToolCall(toolCall: {
118 readonly locations?: unknown;
119 readonly content?: unknown;
120 readonly rawInput?: unknown;
121}): AcpChangedPaths {
122 const paths = new Set<string>();
123 let complete = true;
124 const requirePath = (value: unknown) => {
125 const path = acpCheckablePath(value);
126 if (path === undefined) complete = false;
127 else paths.add(path);
128 };
129 const { locations, content, rawInput } = toolCall;
130 if (Array.isArray(locations)) {
131 for (const location of locations) requirePath(unknownRecord(location)?.path);
132 } else if (locations !== undefined && locations !== null) {
133 complete = false;
134 }
135 if (Array.isArray(content)) {
136 for (const value of content) {
137 const entry = unknownRecord(value);
138 if (entry?.type === "content" || entry?.type === "terminal") continue;
139 if (entry?.type !== "diff") {
140 complete = false;
141 continue;
142 }
143 if (entry.changes === undefined || entry.changes === null) {
144 requirePath(entry.path);
145 continue;
146 }
147 if (!Array.isArray(entry.changes)) {
148 complete = false;
149 continue;
150 }
151 if (entry.path !== undefined && entry.path !== null) requirePath(entry.path);
152 for (const value of entry.changes) {
153 const change = unknownRecord(value);
154 switch (change?.operation) {
155 case "move":
156 requirePath(change.oldPath);
157 requirePath(change.path);
158 break;
159 case "add":
160 case "delete":
161 case "modify":
162 // A copy only reads its source.
163 case "copy":
164 requirePath(change.path);
165 break;
166 default:
167 // An operation this client does not know may write where its fields do not show.
168 complete = false;
169 }
170 }
171 }
172 } else if (content !== undefined && content !== null) {
173 complete = false;
174 }
175 const input = unknownRecord(rawInput);
176 if (input !== undefined) {
177 for (const key of ACP_RAW_INPUT_PATH_KEYS) {
178 const value = input[key];
179 if (value !== undefined && value !== null) requirePath(value);
180 }
181 }
182 return complete && paths.size <= MAX_ACP_CHANGED_PATHS ? [...paths] : "unknown";
183}
184
185interface AcpPolicyOperation {
186 readonly kind: string | null | undefined;
187 readonly changedPaths: AcpChangedPaths;
188}
189
190function acpPolicyRequiresApproval(runtimePolicy: AcpRuntimePolicy): boolean {
191 return runtimePolicy.approvalPolicy === undefined
192 ? runtimePolicy.runtimeMode === "approval-required"
193 : runtimePolicy.approvalPolicy !== "never";
194}
195
196function isAcpReadKind(toolKind: string): boolean {
197 return toolKind === "read" || toolKind === "search" || toolKind === "think";
198}
199
200/** Reads never ask; an absent sandbox implies read-only in approval-required mode. */
201function acpReadDisposition(runtimePolicy: AcpRuntimePolicy): "allow" | "deny" {
202 switch (unknownRecord(runtimePolicy.sandboxPolicy)?.type) {
203 case undefined:
204 case "readOnly":
205 case "workspaceWrite":
206 case "dangerFullAccess":
207 case "externalSandbox":
208 return "allow";
209 default:
210 return "deny";
211 }
212}
213
214/** True when the change names at least one path and every path is inside `cwd`, a sandbox writable root or one of the thread's other folders. */
215function acpMutationStaysInWorkspace(
216 runtimePolicy: AcpRuntimePolicy,
217 sandboxPolicy: Record<string, unknown>,
218 changedPaths: AcpChangedPaths,
219): boolean {
220 if (changedPaths === "unknown" || changedPaths.length === 0) return false;
221 const cwd =
222 typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0
223 ? (resolveAcpPermissionPath(runtimePolicy.cwd, process.cwd()) ?? null)
224 : null;
225 const roots: Array<string> = [];
226 if (cwd !== null) {
227 const canonicalCwd = acpCanonicalPathForContainment(cwd);
228 if (canonicalCwd !== undefined) roots.push(canonicalCwd);
229 }
230 const writableRoots = [
231 ...(Array.isArray(sandboxPolicy.writableRoots) ? sandboxPolicy.writableRoots : []),
232 ...(runtimePolicy.workspace?.extraRoots ?? []),
233 ];
234 for (const writableRoot of writableRoots) {
235 if (typeof writableRoot !== "string") continue;
236 const resolved = resolveAcpPermissionPath(writableRoot, cwd);
237 if (resolved === undefined) continue;
238 const canonicalRoot = acpCanonicalPathForContainment(resolved);
239 if (canonicalRoot !== undefined) roots.push(canonicalRoot);
240 }
241 if (roots.length === 0) return false;
242
243 for (const changedPath of changedPaths) {
244 const resolved = resolveAcpPermissionPath(changedPath, cwd);
245 const canonicalPath =
246 resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved);
247 if (
248 canonicalPath === undefined ||
249 !roots.some((root) => acpPathIsWithinRoot(canonicalPath, root))
250 ) {
251 return false;
252 }
253 }
254 return true;
255}
256
257function acpOperationDisposition(
258 runtimePolicy: AcpRuntimePolicy,
259 operation: AcpPolicyOperation,
260): AcpPermissionDisposition {
261 const toolKind = operation.kind ?? "other";
262 if (isAcpReadKind(toolKind)) {
263 return acpReadDisposition(runtimePolicy);
264 }
265 if (acpPolicyRequiresApproval(runtimePolicy)) {
266 return "ask";
267 }
268
269 const sandboxPolicy = unknownRecord(runtimePolicy.sandboxPolicy);
270 switch (sandboxPolicy?.type) {
271 case "readOnly":
272 return "deny";
273 case "workspaceWrite":
274 if (isAcpMutationKind(toolKind)) {
275 return acpMutationStaysInWorkspace(
276 runtimePolicy,
277 sandboxPolicy ?? {},
278 operation.changedPaths,
279 )
280 ? "allow"
281 : "deny";
282 }
283 return "deny";
284 case "dangerFullAccess":
285 case "externalSandbox":
286 return "allow";
287 case undefined:
288 if (runtimePolicy.runtimeMode === "approval-required") return "deny";
289 if (
290 runtimePolicy.runtimeMode === "auto-accept-edits" &&
291 runtimePolicy.approvalPolicy === undefined
292 ) {
293 // Auto-accept covers file changes in the thread's own folders; the user decides the rest.
294 return isAcpMutationKind(toolKind) &&
295 acpMutationStaysInWorkspace(runtimePolicy, {}, operation.changedPaths)
296 ? "allow"
297 : "ask";
298 }
299 return "allow";
300 default:
301 return "deny";
302 }
303}
304
305function isAcpMutationKind(toolKind: string): boolean {
306 return toolKind === "edit" || toolKind === "delete" || toolKind === "move";
307}
308
309export function acpPermissionDisposition(
310 runtimePolicy: AcpRuntimePolicy,
311 request: EffectAcpSchema.RequestPermissionRequest,
312): AcpPermissionDisposition {
313 return acpOperationDisposition(runtimePolicy, {
314 kind: request.toolCall.kind,
315 changedPaths: acpChangedPathsOfToolCall(request.toolCall),
316 });
317}
318
319export function acpMcpToolApprovalElicitationDisposition(
320 runtimePolicy: AcpRuntimePolicy,
321 request: EffectAcpSchema.CreateElicitationRequest,
322 nativeRequestId?: string,
323): "ask" | "allow" | undefined {
324 if (
325 request.mode !== "form" ||
326 (unknownRecord(request._meta)?.codex_approval_kind !== "mcp_tool_call" &&
327 nativeRequestId?.startsWith("mcp_tool_call_approval_") !== true)
328 ) {
329 return undefined;
330 }
331 // T3's authenticated MCP endpoint enforces scope; only explicit approval mode needs a user prompt.
332 return acpPolicyRequiresApproval(runtimePolicy) ? "ask" : "allow";
333}
334
335export function acpClientExecuteDisposition(
336 runtimePolicy: AcpRuntimePolicy,
337): AcpPermissionDisposition {
338 return acpOperationDisposition(runtimePolicy, { kind: "execute", changedPaths: [] });
339}
340
341export interface AcpApprovalGrantInput {
342 /** The approved request's ACP tool kind, after ID-only requests take their tracked call's kind. */
343 readonly toolKind: string;
344 readonly scope: "session" | "turn";
345 readonly turnKey: string;
346}
347
348export interface AcpClientPolicyGrants {
349 readonly recordApproval: (input: AcpApprovalGrantInput) => void;
350 readonly allowsExecute: (turnKey: string | null) => boolean;
351}
352
353/** ACP cannot link commands to terminals; approved execute requests grant execution for the turn or accepted session. */
354export function makeAcpClientPolicyGrants(): AcpClientPolicyGrants {
355 let sessionExecute = false;
356 let turnExecute: string | null = null;
357 return {
358 recordApproval: (input) => {
359 // Other kinds also show as command cards, but approving them must not open terminals.
360 if (input.toolKind !== "execute") return;
361 if (input.scope === "session") {
362 sessionExecute = true;
363 } else {
364 turnExecute = input.turnKey;
365 }
366 },
367 allowsExecute: (turnKey) => sessionExecute || (turnKey !== null && turnExecute === turnKey),
368 };
369}