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/** Expose shell/web Allow Always _meta warnings as option text for both clients. */
73function antigravitySecurityWarning(option: EffectAcpSchema.PermissionOption): string | undefined {
74 const meta = option._meta;
75 if (!Predicate.isObject(meta)) return undefined;
76 const warning = Option.getOrUndefined(decodeSecurityWarning(meta[SECURITY_WARNING_META_KEY]));
77 const text = warning?.message?.trim() || warning?.title?.trim();
78 if (!text) return undefined;
79 return text.length > WARNING_TEXT_LIMIT
80 ? copyBoundedText(`${text.slice(0, WARNING_TEXT_LIMIT - 3)}...`)
81 : text;
82}
83
84export function antigravityApprovalOptions(
85 request: EffectAcpSchema.RequestPermissionRequest,
86): ReadonlyArray<ProviderApprovalOption> {
87 if (isAntigravityUserInputRequest(request)) return [];
88 const options: ProviderApprovalOption[] = [];
89 const optionWithKind = (kind: EffectAcpSchema.PermissionOption["kind"]) =>
90 request.options.find((entry) => entry.kind === kind && entry.optionId.trim());
91 const once = optionWithKind("allow_once");
92 if (once) {
93 options.push({ decision: "accept", label: "Allow once" });
94 }
95 const always = optionWithKind("allow_always");
96 if (always) {
97 const warning = antigravitySecurityWarning(always);
98 options.push({
99 decision: "acceptForSession",
100 label: "Allow for this thread",
101 ...(warning ? { warning } : {}),
102 });
103 }
104 if (optionWithKind("reject_once")) {
105 options.push({ decision: "decline", label: "Deny" });
106 }
107 options.push({ decision: "cancel", label: "Cancel" });
108 return options;
109}
110
111function copyBoundedText(text: string): string {
112 return Buffer.from(text, "utf16le").toString("utf16le");
113}
114
115function questionLabel(option: EffectAcpSchema.PermissionOption): string {
116 const label = option.name.trim() || option.optionId;
117 return label.length > QUESTION_LABEL_LIMIT
118 ? copyBoundedText(`${label.slice(0, QUESTION_LABEL_LIMIT - 3)}...`)
119 : label;
120}
121
122export function extractAntigravityUserInputQuestion(
123 request: EffectAcpSchema.RequestPermissionRequest,
124): UserInputQuestion | undefined {
125 if (!isAntigravityUserInputRequest(request) || request.options.length === 0) {
126 return undefined;
127 }
128 const ids = new Set<string>();
129 for (const option of request.options) {
130 if (!option.optionId.trim() || ids.has(option.optionId)) {
131 return undefined;
132 }
133 ids.add(option.optionId);
134 }
135 const question = request.toolCall.title?.trim() || "Choose an option.";
136 return {
137 id: request.toolCall.toolCallId,
138 header: "Question",
139 question:
140 question.length > TOOL_TEXT_LIMIT
141 ? copyBoundedText(`${question.slice(0, TOOL_TEXT_LIMIT - 3)}...`)
142 : question,
143 multiSelect: false,
144 allowCustomAnswer: false,
145 options: request.options.map((option) => ({
146 value: option.optionId,
147 label: questionLabel(option),
148 description: questionLabel(option),
149 })),
150 };
151}
152
153export function makeAntigravityUserInputResponse(
154 request: EffectAcpSchema.RequestPermissionRequest,
155 answers: ProviderUserInputAnswers,
156): EffectAcpSchema.RequestPermissionResponse | undefined {
157 if (extractAntigravityUserInputQuestion(request) === undefined) {
158 return undefined;
159 }
160 const answer = Option.getOrUndefined(decodeSingleAnswer(answers[request.toolCall.toolCallId]));
161 const value = typeof answer === "string" ? answer : answer?.[0];
162 if (value === undefined) {
163 return undefined;
164 }
165 const exact = request.options.find((option) => option.optionId === value);
166 if (exact) {
167 return { outcome: { outcome: "selected", optionId: exact.optionId } };
168 }
169 const matchingLabels = request.options.filter((option) => questionLabel(option) === value);
170 const option = matchingLabels.length === 1 ? matchingLabels[0] : undefined;
171 return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : undefined;
172}
173
174function boundText(text: string, limit = TOOL_TEXT_LIMIT): string {
175 return text.length <= limit
176 ? text
177 : copyBoundedText(`${TOOL_TEXT_TRUNCATED}${text.slice(-limit)}`);
178}
179
180interface ToolPayloadBudget {
181 nodes: number;
182 text: number;
183}
184
185function sanitizeToolValue(value: unknown, budget: ToolPayloadBudget, depth: number): unknown {
186 if (depth > 12 || budget.nodes-- <= 0) {
187 return undefined;
188 }
189 if (typeof value === "string") {
190 if (/^data:image\//i.test(value) || budget.text <= 0) {
191 return undefined;
192 }
193 const text = boundText(value, Math.min(TOOL_TEXT_LIMIT, budget.text));
194 budget.text -= text.length;
195 return text;
196 }
197 if (Array.isArray(value)) {
198 const result: unknown[] = [];
199 for (const entry of value) {
200 if (budget.nodes <= 0) break;
201 const sanitized = sanitizeToolValue(entry, budget, depth + 1);
202 if (sanitized !== undefined) result.push(sanitized);
203 }
204 return result;
205 }
206 if (!Predicate.isObject(value)) {
207 return value;
208 }
209 const entries: Array<readonly [string, unknown]> = [];
210 for (const [key, entry] of Object.entries(value)) {
211 if (budget.nodes <= 0) break;
212 if (
213 (value.type === "image" && (key === "data" || key === "blob")) ||
214 (key === "blob" &&
215 typeof value.mimeType === "string" &&
216 value.mimeType.startsWith("image/")) ||
217 ((key === "formatted_output" || key === "formattedOutput") &&
218 (entry === value.combinedOutput || entry === value.combined_output))
219 ) {
220 continue;
221 }
222 const sanitized = sanitizeToolValue(entry, budget, depth + 1);
223 if (sanitized !== undefined) entries.push([key, sanitized]);
224 }
225 return Object.fromEntries(entries);
226}
227
228export function sanitizeAntigravityToolPayload(payload: unknown): unknown {
229 return sanitizeToolValue(payload, { nodes: 512, text: 64_000 }, 0);
230}
231
232export function normalizeAntigravitySessionUpdate(
233 notification: EffectAcpSchema.SessionNotification,
234): EffectAcpSchema.SessionNotification {
235 const update = notification.update;
236 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
237 return notification;
238 }
239 const contentBudget = { nodes: 512, text: 32_000 };
240 const content = update.content?.flatMap((entry) => {
241 const decoded = Option.getOrUndefined(
242 decodeToolCallContent(sanitizeToolValue(entry, contentBudget, 0)),
243 );
244 return decoded === undefined ? [] : [decoded];
245 });
246 const meta = sanitizeAntigravityToolPayload(update._meta);
247 return {
248 ...notification,
249 update: {
250 ...update,
251 ...(typeof update.title === "string" ? { title: boundText(update.title) } : {}),
252 ...(update.rawInput !== undefined
253 ? { rawInput: sanitizeAntigravityToolPayload(update.rawInput) }
254 : {}),
255 ...(update.rawOutput !== undefined
256 ? { rawOutput: sanitizeAntigravityToolPayload(update.rawOutput) }
257 : {}),
258 ...(update.content !== undefined ? { content: content ?? [] } : {}),
259 ...(update._meta !== undefined
260 ? { _meta: Schema.is(Schema.Record(Schema.String, Schema.Json))(meta) ? meta : null }
261 : {}),
262 },
263 };
264}
265
266function localImagePath(imagePath: string | undefined): string | undefined {
267 if (!imagePath || imagePath.length > TOOL_TEXT_LIMIT) {
268 return undefined;
269 }
270 const path = imagePath.trim();
271 if (!isWorkspaceImagePreviewPath(path)) {
272 return undefined;
273 }
274 if (/^file:\/\//i.test(path)) {
275 try {
276 const url = new URL(path);
277 if (url.hostname && url.hostname !== "localhost") return undefined;
278 const pathname = decodeURIComponent(url.pathname);
279 return /^\/[a-z]:\//i.test(pathname) ? pathname.slice(1) : pathname;
280 } catch {
281 return undefined;
282 }
283 }
284 return /^[a-z][a-z\d+.-]*:/i.test(path) && !/^[a-z]:[\\/]/i.test(path) ? undefined : path;
285}
286
287export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToolCallState {
288 const input = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawInput));
289 const output = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawOutput));
290 const nativeCommand =
291 input?.CommandLine ??
292 input?.command_line ??
293 input?.commandLine ??
294 input?.command ??
295 output?.commandLine ??
296 output?.command_line ??
297 toolCall.command;
298 const command = nativeCommand?.trim() ? boundText(nativeCommand.trim()) : undefined;
299 const nativeCwd =
300 input?.Cwd ??
301 input?.WorkingDirectory ??
302 input?.working_dir ??
303 input?.workingDir ??
304 input?.cwd ??
305 output?.workingDir ??
306 output?.working_dir;
307 const cwd = nativeCwd?.trim() ? boundText(nativeCwd.trim()) : undefined;
308 const nativeOutput = output?.combinedOutput ?? output?.combined_output;
309 const aggregatedOutput = nativeOutput === undefined ? undefined : boundText(nativeOutput);
310 const exitCode = output?.exitCode ?? output?.exit_code;
311 const imagePath = localImagePath(output?.imagePath);
312 const sanitizedData = sanitizeAntigravityToolPayload(toolCall.data);
313 const data: Record<string, unknown> = Predicate.isObject(sanitizedData) ? sanitizedData : {};
314 const kind = toolCall.kind ?? (command !== undefined ? "execute" : undefined);
315 if (kind !== undefined) data.kind = kind;
316 if (command !== undefined) data.command = command;
317 if (cwd !== undefined) data.cwd = cwd;
318 if (imagePath !== undefined) data.imagePath = imagePath;
319 if (kind === "execute") {
320 data.item = {
321 ...(Predicate.isObject(data.item) ? data.item : {}),
322 ...(command !== undefined ? { command } : {}),
323 ...(cwd !== undefined ? { cwd } : {}),
324 ...(aggregatedOutput !== undefined ? { aggregatedOutput } : {}),
325 ...(exitCode !== undefined ? { exitCode } : {}),
326 };
327 }
328 return {
329 ...toolCall,
330 ...(kind !== undefined ? { kind } : {}),
331 ...(command !== undefined ? { command } : {}),
332 ...(toolCall.title !== undefined ? { title: boundText(toolCall.title) } : {}),
333 ...(command !== undefined
334 ? { detail: command }
335 : toolCall.detail !== undefined
336 ? { detail: boundText(toolCall.detail) }
337 : {}),
338 data,
339 };
340}
341
342export function isAntigravityOpenCommand(toolCall: AcpToolCallState): boolean {
343 return toolCall.kind === "execute" && toolCall.status === "inProgress";
344}
345
346/** ACP 1.1.1 reports subagent calls as ordinary tools without child IDs or models. */
347export function classifyAntigravitySubagentToolCall(
348 toolCall: AcpToolCallState,
349 rawPayload?: unknown,
350): "subagent" | "mcp" | undefined {
351 if (
352 (toolCall.kind !== undefined && toolCall.kind !== "other") ||
353 (toolCall.title !== "Running start_subagent" && toolCall.title !== "Run start_subagent?")
354 )
355 return undefined;
356 const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined;
357 const meta = Predicate.isObject(update) ? update._meta : toolCall.data.meta;
358 return Predicate.isObject(meta) && meta.is_mcp_tool_call === true ? "mcp" : "subagent";
359}
360
361/** History sends a completed start before the separate result and its final status. */
362export function isAntigravitySubagentReplayStart(rawPayload: unknown): boolean {
363 const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined;
364 return (
365 Predicate.isObject(update) &&
366 update.sessionUpdate === "tool_call" &&
367 update.status === "completed" &&
368 (update.rawOutput === undefined || update.rawOutput === null)
369 );
370}
371
372export function antigravitySubagentOutput(toolCall: AcpToolCallState): string | undefined {
373 const output = toolCall.data.rawOutput;
374 return typeof output === "string" && output.trim() ? boundText(output.trim()) : undefined;
375}