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

clientPolicy.ts

254 lines8.3 KB

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;
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;
22​
23function resolveAcpPermissionPath(path: string, cwd: string | null): string | undefined {
24 const trimmed = path.trim();
25 if (trimmed.length === 0) return undefined;
26 if (NodePath.isAbsolute(trimmed)) return trimmed;
27 if (cwd === null || cwd.trim().length === 0) return undefined;
28 return `${cwd}${cwd.endsWith(NodePath.sep) ? "" : NodePath.sep}${trimmed}`;
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 );
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 }
71​
72interface AcpPolicyOperation {
73 readonly kind: string | null | undefined;
74 readonly locations: ReadonlyArray<{ readonly path: string }> | null | undefined;
76​
77function acpPolicyRequiresApproval(runtimePolicy: AcpRuntimePolicy): boolean {
78 return runtimePolicy.approvalPolicy === undefined
79 ? runtimePolicy.runtimeMode === "approval-required"
80 : runtimePolicy.approvalPolicy !== "never";
82​
83function isAcpReadKind(toolKind: string): boolean {
84 return toolKind === "read" || toolKind === "search" || toolKind === "think";
86​
87/** Reads never ask; an absent sandbox implies read-only in approval-required mode. */
88function acpReadDisposition(runtimePolicy: AcpRuntimePolicy): "allow" | "deny" {
89 switch (unknownRecord(runtimePolicy.sandboxPolicy)?.type) {
90 case undefined:
91 case "readOnly":
92 case "workspaceWrite":
93 case "dangerFullAccess":
94 case "externalSandbox":
95 return "allow";
96 default:
97 return "deny";
98 }
100​
101function acpWorkspaceWriteAllowsMutation(
102 runtimePolicy: AcpRuntimePolicy,
103 sandboxPolicy: Record<string, unknown>,
104 locations: AcpPolicyOperation["locations"],
105): boolean {
106 const cwd =
107 typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0
108 ? (resolveAcpPermissionPath(runtimePolicy.cwd, process.cwd()) ?? null)
109 : null;
110 const roots: Array<string> = [];
111 if (cwd !== null) {
112 const canonicalCwd = acpCanonicalPathForContainment(cwd);
113 if (canonicalCwd !== undefined) roots.push(canonicalCwd);
114 }
115 const writableRoots = [
116 ...(Array.isArray(sandboxPolicy.writableRoots) ? sandboxPolicy.writableRoots : []),
117 ...(runtimePolicy.workspace?.extraRoots ?? []),
118 ];
119 for (const writableRoot of writableRoots) {
120 if (typeof writableRoot !== "string") continue;
121 const resolved = resolveAcpPermissionPath(writableRoot, cwd);
122 if (resolved === undefined) continue;
123 const canonicalRoot = acpCanonicalPathForContainment(resolved);
124 if (canonicalRoot !== undefined) roots.push(canonicalRoot);
125 }
126 if (roots.length === 0) return false;
127​
128 if (locations === undefined || locations === null || locations.length === 0) {
129 return false;
130 }
131 for (const location of locations) {
132 const resolved = resolveAcpPermissionPath(location.path, cwd);
133 const canonicalPath =
134 resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved);
135 if (
136 canonicalPath === undefined ||
137 !roots.some((root) => acpPathIsWithinRoot(canonicalPath, root))
138 ) {
139 return false;
140 }
141 }
142 return true;
144​
145function acpOperationDisposition(
146 runtimePolicy: AcpRuntimePolicy,
147 operation: AcpPolicyOperation,
148): AcpPermissionDisposition {
149 const toolKind = operation.kind ?? "other";
150 if (isAcpReadKind(toolKind)) {
151 return acpReadDisposition(runtimePolicy);
152 }
153 if (acpPolicyRequiresApproval(runtimePolicy)) {
154 return "ask";
155 }
156​
157 const sandboxPolicy = unknownRecord(runtimePolicy.sandboxPolicy);
158 switch (sandboxPolicy?.type) {
159 case "readOnly":
160 return "deny";
161 case "workspaceWrite":
162 if (isAcpMutationKind(toolKind)) {
163 return acpWorkspaceWriteAllowsMutation(
164 runtimePolicy,
165 sandboxPolicy ?? {},
166 operation.locations,
167 )
168 ? "allow"
169 : "deny";
170 }
171 return "deny";
172 case "dangerFullAccess":
173 case "externalSandbox":
174 return "allow";
175 case undefined:
176 if (runtimePolicy.runtimeMode === "approval-required") return "deny";
177 if (
178 runtimePolicy.runtimeMode === "auto-accept-edits" &&
179 runtimePolicy.approvalPolicy === undefined &&
180 !isAcpMutationKind(toolKind)
181 ) {
182 return "ask";
183 }
184 return "allow";
185 default:
186 return "deny";
187 }
189​
190function isAcpMutationKind(toolKind: string): boolean {
191 return toolKind === "edit" || toolKind === "delete" || toolKind === "move";
193​
194export function acpPermissionDisposition(
195 runtimePolicy: AcpRuntimePolicy,
196 request: EffectAcpSchema.RequestPermissionRequest,
197): AcpPermissionDisposition {
198 return acpOperationDisposition(runtimePolicy, {
199 kind: request.toolCall.kind,
200 locations: request.toolCall.locations,
201 });
203​
204export function acpMcpToolApprovalElicitationDisposition(
205 runtimePolicy: AcpRuntimePolicy,
206 request: EffectAcpSchema.CreateElicitationRequest,
207 nativeRequestId?: string,
208): "ask" | "allow" | undefined {
209 if (
210 request.mode !== "form" ||
211 (unknownRecord(request._meta)?.codex_approval_kind !== "mcp_tool_call" &&
212 nativeRequestId?.startsWith("mcp_tool_call_approval_") !== true)
213 ) {
214 return undefined;
215 }
216 // T3's authenticated MCP endpoint enforces scope; only explicit approval mode needs a user prompt.
217 return acpPolicyRequiresApproval(runtimePolicy) ? "ask" : "allow";
219​
220export function acpClientExecuteDisposition(
221 runtimePolicy: AcpRuntimePolicy,
222): AcpPermissionDisposition {
223 return acpOperationDisposition(runtimePolicy, { kind: "execute", locations: undefined });
225​
226export interface AcpApprovalGrantInput {
227 /** The approved request's ACP tool kind, after ID-only requests take their tracked call's kind. */
228 readonly toolKind: string;
229 readonly scope: "session" | "turn";
230 readonly turnKey: string;
232​
233export interface AcpClientPolicyGrants {
234 readonly recordApproval: (input: AcpApprovalGrantInput) => void;
235 readonly allowsExecute: (turnKey: string | null) => boolean;
237​
238/** ACP cannot link commands to terminals; approved execute requests grant execution for the turn or accepted session. */
239export function makeAcpClientPolicyGrants(): AcpClientPolicyGrants {
240 let sessionExecute = false;
241 let turnExecute: string | null = null;
242 return {
243 recordApproval: (input) => {
244 // Other kinds also show as command cards, but approving them must not open terminals.
245 if (input.toolKind !== "execute") return;
246 if (input.scope === "session") {
247 sessionExecute = true;
248 } else {
249 turnExecute = input.turnKey;
250 }
251 },
252 allowsExecute: (turnKey) => sessionExecute || (turnKey !== null && turnExecute === turnKey),
253 };