Open History to see the last commit
1import type {
2 ProviderApprovalDecision,
3 ProviderApprovalOption,
4 ProviderUserInputAnswers,
5 UserInputQuestion,
6} from "@t3tools/contracts";
7import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
8import * as Option from "effect/Option";
9import * as Predicate from "effect/Predicate";
10import * as Schema from "effect/Schema";
11import type * as EffectAcpSchema from "effect-acp/compat";
12import * as AcpWireSchema from "effect-acp/schema-v1";
13
14import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
15
16const TOOL_TEXT_LIMIT = 8_000;
17const TOOL_TEXT_TRUNCATED = "[Earlier output truncated]\n\n";
18const QUESTION_LABEL_LIMIT = 512;
19
20const NativeToolFields = Schema.Struct({
21 command: Schema.optional(Schema.String),
22 CommandLine: Schema.optional(Schema.String),
23 command_line: Schema.optional(Schema.String),
24 commandLine: Schema.optional(Schema.String),
25 cwd: Schema.optional(Schema.String),
26 Cwd: Schema.optional(Schema.String),
27 WorkingDirectory: Schema.optional(Schema.String),
28 working_dir: Schema.optional(Schema.String),
29 workingDir: Schema.optional(Schema.String),
30 combinedOutput: Schema.optional(Schema.String),
31 combined_output: Schema.optional(Schema.String),
32 exitCode: Schema.optional(Schema.Int),
33 exit_code: Schema.optional(Schema.Int),
34 imagePath: Schema.optional(Schema.String),
35});
36const decodeNativeToolFields = Schema.decodeUnknownOption(NativeToolFields);
37const decodeSingleAnswer = Schema.decodeUnknownOption(
38 Schema.Union([Schema.String, Schema.Tuple([Schema.String])]),
39);
40const decodeToolCallContent = Schema.decodeUnknownOption(AcpWireSchema.ToolCallContent);
41
42/** Native questions share the permission method, but their choices are not approvals. */
43export function isAntigravityUserInputRequest(
44 request: EffectAcpSchema.RequestPermissionRequest,
45): boolean {
46 return request.toolCall.toolCallId.startsWith("interaction_");
47}
48
49export function selectAntigravityPermissionOptionId(
50 request: EffectAcpSchema.RequestPermissionRequest,
51 decision: ProviderApprovalDecision,
52): string | undefined {
53 if (decision === "cancel" || isAntigravityUserInputRequest(request)) {
54 return undefined;
55 }
56 const kind =
57 decision === "accept" ? "allow_once" : decision === "decline" ? "reject_once" : "allow_always";
58 const option = request.options.find((entry) => entry.kind === kind);
59 return option?.optionId.trim() ? option.optionId : undefined;
60}
61
62/** Copy truncated text so V8 cannot retain the original large string. */
63const SECURITY_WARNING_META_KEY = "agy.security.warning";
64const WARNING_TEXT_LIMIT = 512;
65const decodeSecurityWarning = Schema.decodeUnknownOption(
66 Schema.Struct({
67 title: Schema.optional(Schema.String),
68 message: Schema.optional(Schema.String),
69 }),
70);
71
72/**
73 * The agent marks "Allow Always" on shell and web tools with a prompt injection
74 * warning in `_meta`. Surface it as option text so both clients can show it.
75 */
76function antigravitySecurityWarning(option: EffectAcpSchema.PermissionOption): string | undefined {
77 const meta = option._meta;
78 if (!Predicate.isObject(meta)) return undefined;
79 const warning = Option.getOrUndefined(decodeSecurityWarning(meta[SECURITY_WARNING_META_KEY]));
80 const text = warning?.message?.trim() || warning?.title?.trim();
81 if (!text) return undefined;
82 return text.length > WARNING_TEXT_LIMIT
83 ? copyBoundedText(`${text.slice(0, WARNING_TEXT_LIMIT - 3)}...`)
84 : text;
85}
86
87export function antigravityApprovalOptions(
88 request: EffectAcpSchema.RequestPermissionRequest,
89): ReadonlyArray<ProviderApprovalOption> {
90 if (isAntigravityUserInputRequest(request)) return [];
91 const options: ProviderApprovalOption[] = [];
92 const optionWithKind = (kind: EffectAcpSchema.PermissionOption["kind"]) =>
93 request.options.find((entry) => entry.kind === kind && entry.optionId.trim());
94 const once = optionWithKind("allow_once");
95 if (once) {
96 options.push({ decision: "accept", label: "Allow once" });
97 }
98 const always = optionWithKind("allow_always");
99 if (always) {
100 const warning = antigravitySecurityWarning(always);
101 options.push({
102 decision: "acceptForSession",
103 label: "Allow for this thread",
104 ...(warning ? { warning } : {}),
105 });
106 }
107 if (optionWithKind("reject_once")) {
108 options.push({ decision: "decline", label: "Deny" });
109 }
110 options.push({ decision: "cancel", label: "Cancel" });
111 return options;
112}
113
114function copyBoundedText(text: string): string {
115 return Buffer.from(text, "utf16le").toString("utf16le");
116}
117
118function questionLabel(option: EffectAcpSchema.PermissionOption): string {
119 const label = option.name.trim() || option.optionId;
120 return label.length > QUESTION_LABEL_LIMIT
121 ? copyBoundedText(`${label.slice(0, QUESTION_LABEL_LIMIT - 3)}...`)
122 : label;
123}
124
125export function extractAntigravityUserInputQuestion(
126 request: EffectAcpSchema.RequestPermissionRequest,
127): UserInputQuestion | undefined {
128 if (!isAntigravityUserInputRequest(request) || request.options.length === 0) {
129 return undefined;
130 }
131 const ids = new Set<string>();
132 for (const option of request.options) {
133 if (!option.optionId.trim() || ids.has(option.optionId)) {
134 return undefined;
135 }
136 ids.add(option.optionId);
137 }
138 const question = request.toolCall.title?.trim() || "Choose an option.";
139 return {
140 id: request.toolCall.toolCallId,
141 header: "Question",
142 question:
143 question.length > TOOL_TEXT_LIMIT
144 ? copyBoundedText(`${question.slice(0, TOOL_TEXT_LIMIT - 3)}...`)
145 : question,
146 multiSelect: false,
147 allowCustomAnswer: false,
148 options: request.options.map((option) => ({
149 value: option.optionId,
150 label: questionLabel(option),
151 description: questionLabel(option),
152 })),
153 };
154}
155
156export function makeAntigravityUserInputResponse(
157 request: EffectAcpSchema.RequestPermissionRequest,
158 answers: ProviderUserInputAnswers,
159): EffectAcpSchema.RequestPermissionResponse | undefined {
160 if (extractAntigravityUserInputQuestion(request) === undefined) {
161 return undefined;
162 }
163 const answer = Option.getOrUndefined(decodeSingleAnswer(answers[request.toolCall.toolCallId]));
164 const value = typeof answer === "string" ? answer : answer?.[0];
165 if (value === undefined) {
166 return undefined;
167 }
168 const exact = request.options.find((option) => option.optionId === value);
169 if (exact) {
170 return { outcome: { outcome: "selected", optionId: exact.optionId } };
171 }
172 const matchingLabels = request.options.filter((option) => questionLabel(option) === value);
173 const option = matchingLabels.length === 1 ? matchingLabels[0] : undefined;
174 return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : undefined;
175}
176
177function boundText(text: string, limit = TOOL_TEXT_LIMIT): string {
178 return text.length <= limit
179 ? text
180 : copyBoundedText(`${TOOL_TEXT_TRUNCATED}${text.slice(-limit)}`);
181}
182
183interface ToolPayloadBudget {
184 nodes: number;
185 text: number;
186}
187
188function sanitizeToolValue(value: unknown, budget: ToolPayloadBudget, depth: number): unknown {
189 if (depth > 12 || budget.nodes-- <= 0) {
190 return undefined;
191 }
192 if (typeof value === "string") {
193 if (/^data:image\//i.test(value) || budget.text <= 0) {
194 return undefined;
195 }
196 const text = boundText(value, Math.min(TOOL_TEXT_LIMIT, budget.text));
197 budget.text -= text.length;
198 return text;
199 }
200 if (Array.isArray(value)) {
201 const result: unknown[] = [];
202 for (const entry of value) {
203 if (budget.nodes <= 0) break;
204 const sanitized = sanitizeToolValue(entry, budget, depth + 1);
205 if (sanitized !== undefined) result.push(sanitized);
206 }
207 return result;
208 }
209 if (!Predicate.isObject(value)) {
210 return value;
211 }
212 const entries: Array<readonly [string, unknown]> = [];
213 for (const [key, entry] of Object.entries(value)) {
214 if (budget.nodes <= 0) break;
215 if (
216 (value.type === "image" && (key === "data" || key === "blob")) ||
217 (key === "blob" &&
218 typeof value.mimeType === "string" &&
219 value.mimeType.startsWith("image/")) ||
220 ((key === "formatted_output" || key === "formattedOutput") &&
221 (entry === value.combinedOutput || entry === value.combined_output))
222 ) {
223 continue;
224 }
225 const sanitized = sanitizeToolValue(entry, budget, depth + 1);
226 if (sanitized !== undefined) entries.push([key, sanitized]);
227 }
228 return Object.fromEntries(entries);
229}
230
231export function sanitizeAntigravityToolPayload(payload: unknown): unknown {
232 return sanitizeToolValue(payload, { nodes: 512, text: 64_000 }, 0);
233}
234
235export function normalizeAntigravitySessionUpdate(
236 notification: EffectAcpSchema.SessionNotification,
237): EffectAcpSchema.SessionNotification {
238 const update = notification.update;
239 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
240 return notification;
241 }
242 const contentBudget = { nodes: 512, text: 32_000 };
243 const content = update.content?.flatMap((entry) => {
244 const decoded = Option.getOrUndefined(
245 decodeToolCallContent(sanitizeToolValue(entry, contentBudget, 0)),
246 );
247 return decoded === undefined ? [] : [decoded];
248 });
249 const meta = sanitizeAntigravityToolPayload(update._meta);
250 return {
251 ...notification,
252 update: {
253 ...update,
254 ...(typeof update.title === "string" ? { title: boundText(update.title) } : {}),
255 ...(update.rawInput !== undefined
256 ? { rawInput: sanitizeAntigravityToolPayload(update.rawInput) }
257 : {}),
258 ...(update.rawOutput !== undefined
259 ? { rawOutput: sanitizeAntigravityToolPayload(update.rawOutput) }
260 : {}),
261 ...(update.content !== undefined ? { content: content ?? [] } : {}),
262 ...(update._meta !== undefined
263 ? { _meta: Schema.is(Schema.Record(Schema.String, Schema.Json))(meta) ? meta : null }
264 : {}),
265 },
266 };
267}
268
269function localImagePath(imagePath: string | undefined): string | undefined {
270 if (!imagePath || imagePath.length > TOOL_TEXT_LIMIT) {
271 return undefined;
272 }
273 const path = imagePath.trim();
274 if (!isWorkspaceImagePreviewPath(path)) {
275 return undefined;
276 }
277 if (/^file:\/\//i.test(path)) {
278 try {
279 const url = new URL(path);
280 if (url.hostname && url.hostname !== "localhost") return undefined;
281 const pathname = decodeURIComponent(url.pathname);
282 return /^\/[a-z]:\//i.test(pathname) ? pathname.slice(1) : pathname;
283 } catch {
284 return undefined;
285 }
286 }
287 return /^[a-z][a-z\d+.-]*:/i.test(path) && !/^[a-z]:[\\/]/i.test(path) ? undefined : path;
288}
289
290export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToolCallState {
291 const input = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawInput));
292 const output = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawOutput));
293 const nativeCommand =
294 input?.CommandLine ??
295 input?.command_line ??
296 input?.commandLine ??
297 input?.command ??
298 output?.commandLine ??
299 output?.command_line ??
300 toolCall.command;
301 const command = nativeCommand?.trim() ? boundText(nativeCommand.trim()) : undefined;
302 const nativeCwd =
303 input?.Cwd ??
304 input?.WorkingDirectory ??
305 input?.working_dir ??
306 input?.workingDir ??
307 input?.cwd ??
308 output?.workingDir ??
309 output?.working_dir;
310 const cwd = nativeCwd?.trim() ? boundText(nativeCwd.trim()) : undefined;
311 const nativeOutput = output?.combinedOutput ?? output?.combined_output;
312 const aggregatedOutput = nativeOutput === undefined ? undefined : boundText(nativeOutput);
313 const exitCode = output?.exitCode ?? output?.exit_code;
314 const imagePath = localImagePath(output?.imagePath);
315 const sanitizedData = sanitizeAntigravityToolPayload(toolCall.data);
316 const data: Record<string, unknown> = Predicate.isObject(sanitizedData) ? sanitizedData : {};
317 const kind = toolCall.kind ?? (command !== undefined ? "execute" : undefined);
318 if (kind !== undefined) data.kind = kind;
319 if (command !== undefined) data.command = command;
320 if (cwd !== undefined) data.cwd = cwd;
321 if (imagePath !== undefined) data.imagePath = imagePath;
322 if (kind === "execute") {
323 data.item = {
324 ...(Predicate.isObject(data.item) ? data.item : {}),
325 ...(command !== undefined ? { command } : {}),
326 ...(cwd !== undefined ? { cwd } : {}),
327 ...(aggregatedOutput !== undefined ? { aggregatedOutput } : {}),
328 ...(exitCode !== undefined ? { exitCode } : {}),
329 };
330 }
331 return {
332 ...toolCall,
333 ...(kind !== undefined ? { kind } : {}),
334 ...(command !== undefined ? { command } : {}),
335 ...(toolCall.title !== undefined ? { title: boundText(toolCall.title) } : {}),
336 ...(command !== undefined
337 ? { detail: command }
338 : toolCall.detail !== undefined
339 ? { detail: boundText(toolCall.detail) }
340 : {}),
341 data,
342 };
343}
344
345export function isAntigravityOpenCommand(toolCall: AcpToolCallState): boolean {
346 return toolCall.kind === "execute" && toolCall.status === "inProgress";
347}
348
349/**
350 * ACP 1.1.1 exposes subagent invocations as ordinary tools, without child IDs
351 * or models.
352 */
353export function classifyAntigravitySubagentToolCall(
354 toolCall: AcpToolCallState,
355 rawPayload?: unknown,
356): "subagent" | "mcp" | undefined {
357 if (
358 (toolCall.kind !== undefined && toolCall.kind !== "other") ||
359 (toolCall.title !== "Running start_subagent" && toolCall.title !== "Run start_subagent?")
360 )
361 return undefined;
362 const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined;
363 const meta = Predicate.isObject(update) ? update._meta : toolCall.data.meta;
364 return Predicate.isObject(meta) && meta.is_mcp_tool_call === true ? "mcp" : "subagent";
365}
366
367/** History sends a completed start before the separate result and its final status. */
368export function isAntigravitySubagentReplayStart(rawPayload: unknown): boolean {
369 const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined;
370 return (
371 Predicate.isObject(update) &&
372 update.sessionUpdate === "tool_call" &&
373 update.status === "completed" &&
374 (update.rawOutput === undefined || update.rawOutput === null)
375 );
376}
377
378export function antigravitySubagentOutput(toolCall: AcpToolCallState): string | undefined {
379 const output = toolCall.data.rawOutput;
380 return typeof output === "string" && output.trim() ? boundText(output.trim()) : undefined;
381}