Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpClientPolicy.ts

370 lines13.2 KB

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​
7/**
8 * Runtime-policy decisions for ACP work that T3 mediates.
9 *
10 * ACP agents touch the machine two ways: provider-owned execution inside the
11 * agent process, which T3 can only gate through `session/request_permission`,
12 * and client-mediated `fs/*` and `terminal/*` requests, which run with the T3
13 * server's own privileges. Both paths resolve through
14 * {@link acpOperationDisposition} so a client-mediated request can never do
15 * more than the equivalent permission request would be allowed to do.
16 */
17​
18/** Structural subset of the adapter runtime policy that decisions read. */
19export interface AcpRuntimePolicy {
20 readonly runtimeMode: RuntimeMode;
21 readonly cwd: string | null;
22 readonly approvalPolicy?: unknown;
23 readonly sandboxPolicy?: unknown;
25​
26export type AcpPermissionDisposition = "allow" | "ask" | "deny";
27​
28export function unknownRecord(value: unknown): Record<string, unknown> | undefined {
29 return typeof value === "object" && value !== null && !Array.isArray(value)
30 ? (value as Record<string, unknown>)
31 : undefined;
33​
34function resolveAcpPermissionPath(path: string, cwd: string | null): string | undefined {
35 const trimmed = path.trim();
36 if (trimmed.length === 0) return undefined;
37 if (NodePath.isAbsolute(trimmed)) return trimmed;
38 if (cwd === null || cwd.trim().length === 0) return undefined;
39 return `${cwd}${cwd.endsWith(NodePath.sep) ? "" : NodePath.sep}${trimmed}`;
41​
42function acpPathIsWithinRoot(path: string, root: string): boolean {
43 const relative = NodePath.relative(root, path);
44 return (
45 relative === "" ||
46 (relative !== ".." &&
47 !relative.startsWith(`..${NodePath.sep}`) &&
48 !NodePath.isAbsolute(relative))
49 );
51​
52/**
53 * Canonicalize a path for an authorization containment check.
54 *
55 * `realpath` cannot resolve a file that has not been created yet, so walk up
56 * to the deepest existing ancestor and append the missing suffix to that
57 * ancestor's canonical path. This follows symlinked directories while still
58 * allowing normal writes to new files. If an existing entry cannot be
59 * canonicalized (for example, a broken symlink), fail closed.
60 */
61function acpCanonicalPathForContainment(path: string): string | undefined {
62 // Do not lexically normalize before realpath. For a path such as
63 // `workspace/link/../file`, the kernel resolves `link` before `..`; an
64 // eager NodePath.resolve would erase that symlink traversal and could turn
65 // an outside target into an apparently in-workspace path.
66 let candidate = path;
67 const missingSuffix: Array<string> = [];
68​
69 while (true) {
70 try {
71 return NodePath.resolve(NodeFS.realpathSync.native(candidate), ...missingSuffix);
72 } catch (cause) {
73 if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
74 return undefined;
75 }
76 }
77​
78 try {
79 NodeFS.lstatSync(candidate);
80 // The entry exists but realpath could not resolve it, as with a broken
81 // symlink. Treat it as untrusted rather than authorizing its lexical path.
82 return undefined;
83 } catch (cause) {
84 if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
85 return undefined;
86 }
87 }
88​
89 const parent = NodePath.dirname(candidate);
90 if (parent === candidate) return undefined;
91 missingSuffix.unshift(NodePath.basename(candidate));
92 candidate = parent;
93 }
95​
96/** The parts of a native operation the disposition logic reads. */
97interface AcpPolicyOperation {
98 readonly kind: string | null | undefined;
99 readonly locations: ReadonlyArray<{ readonly path: string }> | null | undefined;
101​
102function acpPolicyRequiresApproval(runtimePolicy: AcpRuntimePolicy): boolean {
103 return runtimePolicy.approvalPolicy === undefined
104 ? runtimePolicy.runtimeMode === "approval-required"
105 : runtimePolicy.approvalPolicy !== "never";
107​
108function acpWorkspaceWriteAllowsMutation(
109 runtimePolicy: AcpRuntimePolicy,
110 sandboxPolicy: Record<string, unknown>,
111 locations: AcpPolicyOperation["locations"],
112): boolean {
113 const cwd =
114 typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0
115 ? (resolveAcpPermissionPath(runtimePolicy.cwd, process.cwd()) ?? null)
116 : null;
117 const roots: Array<string> = [];
118 if (cwd !== null) {
119 const canonicalCwd = acpCanonicalPathForContainment(cwd);
120 if (canonicalCwd !== undefined) roots.push(canonicalCwd);
121 }
122 const writableRoots = sandboxPolicy.writableRoots;
123 if (Array.isArray(writableRoots)) {
124 for (const writableRoot of writableRoots) {
125 if (typeof writableRoot !== "string") continue;
126 const resolved = resolveAcpPermissionPath(writableRoot, cwd);
127 if (resolved === undefined) continue;
128 const canonicalRoot = acpCanonicalPathForContainment(resolved);
129 if (canonicalRoot !== undefined) roots.push(canonicalRoot);
130 }
131 }
132 if (roots.length === 0) return false;
133​
134 if (locations === undefined || locations === null || locations.length === 0) {
135 return false;
136 }
137 for (const location of locations) {
138 const resolved = resolveAcpPermissionPath(location.path, cwd);
139 const canonicalPath =
140 resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved);
141 if (
142 canonicalPath === undefined ||
143 !roots.some((root) => acpPathIsWithinRoot(canonicalPath, root))
144 ) {
145 return false;
146 }
147 }
148 return true;
150​
151/**
152 * Disposition of one native operation under the active runtime policy. Shared
153 * by provider permission requests and the client fs/terminal handlers.
154 */
155function acpOperationDisposition(
156 runtimePolicy: AcpRuntimePolicy,
157 operation: AcpPolicyOperation,
158): AcpPermissionDisposition {
159 if (acpPolicyRequiresApproval(runtimePolicy)) {
160 return "ask";
161 }
162​
163 const sandboxPolicy = unknownRecord(runtimePolicy.sandboxPolicy);
164 const sandboxType = sandboxPolicy?.type;
165 const toolKind = operation.kind ?? "other";
166 switch (sandboxType) {
167 case "readOnly":
168 return toolKind === "read" || toolKind === "search" || toolKind === "think"
169 ? "allow"
170 : "deny";
171 case "workspaceWrite":
172 if (toolKind === "read" || toolKind === "search" || toolKind === "think") {
173 return "allow";
174 }
175 if (toolKind === "edit" || toolKind === "delete" || toolKind === "move") {
176 return acpWorkspaceWriteAllowsMutation(
177 runtimePolicy,
178 sandboxPolicy ?? {},
179 operation.locations,
180 )
181 ? "allow"
182 : "deny";
183 }
184 return "deny";
185 case "dangerFullAccess":
186 case "externalSandbox":
187 return "allow";
188 case undefined:
189 return runtimePolicy.runtimeMode === "approval-required" ? "deny" : "allow";
190 default:
191 return "deny";
192 }
194​
195export function acpPermissionDisposition(
196 runtimePolicy: AcpRuntimePolicy,
197 request: EffectAcpSchema.RequestPermissionRequest,
198): AcpPermissionDisposition {
199 return acpOperationDisposition(runtimePolicy, {
200 kind: request.toolCall.kind,
201 locations: request.toolCall.locations,
202 });
204​
205/** Resolve explicitly tagged MCP approvals through the thread's normal policy. */
206export function acpMcpToolApprovalElicitationDisposition(
207 runtimePolicy: AcpRuntimePolicy,
208 request: EffectAcpSchema.CreateElicitationRequest,
209 nativeRequestId?: string,
210): AcpPermissionDisposition | undefined {
211 if (
212 request.mode !== "form" ||
213 (unknownRecord(request._meta)?.codex_approval_kind !== "mcp_tool_call" &&
214 nativeRequestId?.startsWith("mcp_tool_call_approval_") !== true)
215 ) {
216 return undefined;
217 }
218 // This request comes from T3's authenticated, scope-checked MCP endpoint,
219 // not an arbitrary provider command. Let explicit approval mode surface it
220 // to the user and otherwise allow the endpoint to enforce its own policy.
221 return acpPolicyRequiresApproval(runtimePolicy) ? "ask" : "allow";
223​
224/** Disposition of a client-mediated `fs/write_text_file` to one path. */
225export function acpClientWriteDisposition(
226 runtimePolicy: AcpRuntimePolicy,
227 path: string,
228): AcpPermissionDisposition {
229 return acpOperationDisposition(runtimePolicy, { kind: "edit", locations: [{ path }] });
231​
232/** Disposition of a client-mediated `fs/read_text_file` from one path. */
233export function acpClientReadDisposition(
234 runtimePolicy: AcpRuntimePolicy,
235 path: string,
236): AcpPermissionDisposition {
237 return acpOperationDisposition(runtimePolicy, { kind: "read", locations: [{ path }] });
239​
240/** Disposition of a client-mediated `terminal/create`. */
241export function acpClientExecuteDisposition(
242 runtimePolicy: AcpRuntimePolicy,
243): AcpPermissionDisposition {
244 return acpOperationDisposition(runtimePolicy, { kind: "execute", locations: undefined });
246​
247const MAX_GRANTED_WRITE_ROOTS = 128;
248​
249export interface AcpApprovalGrantInput {
250 readonly kind: ProviderRequestKind;
251 readonly locations: ReadonlyArray<string>;
252 readonly cwd: string | null;
253 readonly scope: "session" | "turn";
254 readonly turnKey: string;
256​
257export interface AcpClientPolicyGrants {
258 readonly recordApproval: (input: AcpApprovalGrantInput) => void;
259 readonly allowsRead: (input: {
260 readonly path: string;
261 readonly cwd: string | null;
262 readonly turnKey: string | null;
263 }) => boolean;
264 readonly allowsWrite: (input: {
265 readonly path: string;
266 readonly cwd: string | null;
267 readonly turnKey: string | null;
268 }) => boolean;
269 readonly allowsExecute: (turnKey: string | null) => boolean;
271​
272/**
273 * Approval grants recorded when the user accepts a `session/request_permission`,
274 * so an "ask" disposition at the client fs/terminal boundary can honor what the
275 * user already approved.
276 *
277 * ACP carries no linkage between an approved tool call and the client-mediated
278 * requests the agent issues to carry it out, so grants are scoped as tightly as
279 * the protocol allows: an accepted file change authorizes client writes to its
280 * canonical reported locations (or the whole scope when the agent reported
281 * none), an accepted file read does the same for reads, and an accepted command
282 * authorizes client terminals. Grants last for the approving turn, or for the
283 * session on accept-for-session.
284 */
285export function makeAcpClientPolicyGrants(): AcpClientPolicyGrants {
286 interface ScopeGrants {
287 execute: boolean;
288 unscopedRead: boolean;
289 unscopedWrite: boolean;
290 readRoots: Array<string>;
291 writeRoots: Array<string>;
292 }
293 const emptyScope = (): ScopeGrants => ({
294 execute: false,
295 unscopedRead: false,
296 unscopedWrite: false,
297 readRoots: [],
298 writeRoots: [],
299 });
300 const session = emptyScope();
301 let turn: { readonly key: string; readonly grants: ScopeGrants } | null = null;
302​
303 const scopeFor = (input: AcpApprovalGrantInput): ScopeGrants => {
304 if (input.scope === "session") return session;
305 if (turn === null || turn.key !== input.turnKey) {
306 turn = { key: input.turnKey, grants: emptyScope() };
307 }
308 return turn.grants;
309 };
310​
311 const activeScopes = (turnKey: string | null): Array<ScopeGrants> =>
312 turn !== null && turnKey !== null && turn.key === turnKey ? [session, turn.grants] : [session];
313​
314 const recordPathGrant = (roots: Array<string>, input: AcpApprovalGrantInput): void => {
315 for (const location of input.locations) {
316 const resolved = resolveAcpPermissionPath(location, input.cwd);
317 const canonical =
318 resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved);
319 if (canonical === undefined) continue;
320 roots.push(canonical);
321 if (roots.length > MAX_GRANTED_WRITE_ROOTS) roots.shift();
322 }
323 };
324​
325 const allowsPath = (input: {
326 readonly path: string;
327 readonly cwd: string | null;
328 readonly turnKey: string | null;
329 readonly unscoped: keyof Pick<ScopeGrants, "unscopedRead" | "unscopedWrite">;
330 readonly roots: keyof Pick<ScopeGrants, "readRoots" | "writeRoots">;
331 }): boolean => {
332 const scopes = activeScopes(input.turnKey);
333 if (scopes.some((scope) => scope[input.unscoped])) return true;
334 const resolved = resolveAcpPermissionPath(input.path, input.cwd);
335 const canonical = resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved);
336 if (canonical === undefined) return false;
337 return scopes.some((scope) =>
338 scope[input.roots].some((root) => acpPathIsWithinRoot(canonical, root)),
339 );
340 };
341​
342 return {
343 recordApproval: (input) => {
344 const grants = scopeFor(input);
345 if (input.kind === "command") {
346 grants.execute = true;
347 return;
348 }
349 if (input.kind === "file-read") {
350 if (input.locations.length === 0) {
351 grants.unscopedRead = true;
352 return;
353 }
354 recordPathGrant(grants.readRoots, input);
355 return;
356 }
357 if (input.kind !== "file-change") return;
358 if (input.locations.length === 0) {
359 grants.unscopedWrite = true;
360 return;
361 }
362 recordPathGrant(grants.writeRoots, input);
363 },
364 allowsRead: ({ path, cwd, turnKey }) =>
365 allowsPath({ path, cwd, turnKey, unscoped: "unscopedRead", roots: "readRoots" }),
366 allowsWrite: ({ path, cwd, turnKey }) =>
367 allowsPath({ path, cwd, turnKey, unscoped: "unscopedWrite", roots: "writeRoots" }),
368 allowsExecute: (turnKey) => activeScopes(turnKey).some((scope) => scope.execute),
369 };