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

AntigravityProtocol.ts

380 lines14.3 KB

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 * as EffectAcpSchema from "effect-acp/schema";
12​
13import type { AcpToolCallState } from "./AcpRuntimeModel.ts";
14​
15const TOOL_TEXT_LIMIT = 8_000;
16const TOOL_TEXT_TRUNCATED = "[Earlier output truncated]\n\n";
17const QUESTION_LABEL_LIMIT = 512;
18​
19const NativeToolFields = Schema.Struct({
20 command: Schema.optional(Schema.String),
21 CommandLine: Schema.optional(Schema.String),
22 command_line: Schema.optional(Schema.String),
23 commandLine: Schema.optional(Schema.String),
24 cwd: Schema.optional(Schema.String),
25 Cwd: Schema.optional(Schema.String),
26 WorkingDirectory: Schema.optional(Schema.String),
27 working_dir: Schema.optional(Schema.String),
28 workingDir: Schema.optional(Schema.String),
29 combinedOutput: Schema.optional(Schema.String),
30 combined_output: Schema.optional(Schema.String),
31 exitCode: Schema.optional(Schema.Int),
32 exit_code: Schema.optional(Schema.Int),
33 imagePath: Schema.optional(Schema.String),
34});
35const decodeNativeToolFields = Schema.decodeUnknownOption(NativeToolFields);
36const decodeSingleAnswer = Schema.decodeUnknownOption(
37 Schema.Union([Schema.String, Schema.Tuple([Schema.String])]),
38);
39const decodeToolCallContent = Schema.decodeUnknownOption(EffectAcpSchema.ToolCallContent);
40​
41/** Native questions share the permission method, but their choices are not approvals. */
42export function isAntigravityUserInputRequest(
43 request: EffectAcpSchema.RequestPermissionRequest,
44): boolean {
45 return request.toolCall.toolCallId.startsWith("interaction_");
47​
48export function selectAntigravityPermissionOptionId(
49 request: EffectAcpSchema.RequestPermissionRequest,
50 decision: ProviderApprovalDecision,
51): string | undefined {
52 if (decision === "cancel" || isAntigravityUserInputRequest(request)) {
53 return undefined;
54 }
55 const kind =
56 decision === "accept" ? "allow_once" : decision === "decline" ? "reject_once" : "allow_always";
57 const option = request.options.find((entry) => entry.kind === kind);
58 return option?.optionId.trim() ? option.optionId : undefined;
60​
61/** Copy truncated text so V8 cannot retain the original large string. */
62const SECURITY_WARNING_META_KEY = "agy.security.warning";
63const WARNING_TEXT_LIMIT = 512;
64const decodeSecurityWarning = Schema.decodeUnknownOption(
65 Schema.Struct({
66 title: Schema.optional(Schema.String),
67 message: Schema.optional(Schema.String),
68 }),
69);
70​
71/**
72 * The agent marks "Allow Always" on shell and web tools with a prompt injection
73 * warning in `_meta`. Surface it as option text so both clients can show it.
74 */
75function antigravitySecurityWarning(option: EffectAcpSchema.PermissionOption): string | undefined {
76 const meta = option._meta;
77 if (!Predicate.isObject(meta)) return undefined;
78 const warning = Option.getOrUndefined(decodeSecurityWarning(meta[SECURITY_WARNING_META_KEY]));
79 const text = warning?.message?.trim() || warning?.title?.trim();
80 if (!text) return undefined;
81 return text.length > WARNING_TEXT_LIMIT
82 ? copyBoundedText(`${text.slice(0, WARNING_TEXT_LIMIT - 3)}...`)
83 : text;
85​
86/** Only advertise decisions that the native request can honor. */
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;
113​
114function copyBoundedText(text: string): string {
115 return Buffer.from(text, "utf16le").toString("utf16le");
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;
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 };
155​
156/** Return undefined for an invalid answer so the adapter keeps the question open. */
157export function makeAntigravityUserInputResponse(
158 request: EffectAcpSchema.RequestPermissionRequest,
159 answers: ProviderUserInputAnswers,
160): EffectAcpSchema.RequestPermissionResponse | undefined {
161 if (extractAntigravityUserInputQuestion(request) === undefined) {
162 return undefined;
163 }
164 const answer = Option.getOrUndefined(decodeSingleAnswer(answers[request.toolCall.toolCallId]));
165 const value = typeof answer === "string" ? answer : answer?.[0];
166 if (value === undefined) {
167 return undefined;
168 }
169 const exact = request.options.find((option) => option.optionId === value);
170 if (exact) {
171 return { outcome: { outcome: "selected", optionId: exact.optionId } };
172 }
173 const matchingLabels = request.options.filter((option) => questionLabel(option) === value);
174 const option = matchingLabels.length === 1 ? matchingLabels[0] : undefined;
175 return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : undefined;
177​
178function boundText(text: string, limit = TOOL_TEXT_LIMIT): string {
179 return text.length <= limit
180 ? text
181 : copyBoundedText(`${TOOL_TEXT_TRUNCATED}${text.slice(-limit)}`);
183​
184interface ToolPayloadBudget {
185 nodes: number;
186 text: number;
188​
189function sanitizeToolValue(value: unknown, budget: ToolPayloadBudget, depth: number): unknown {
190 if (depth > 12 || budget.nodes-- <= 0) {
191 return undefined;
192 }
193 if (typeof value === "string") {
194 if (/^data:image\//i.test(value) || budget.text <= 0) {
195 return undefined;
196 }
197 const text = boundText(value, Math.min(TOOL_TEXT_LIMIT, budget.text));
198 budget.text -= text.length;
199 return text;
200 }
201 if (Array.isArray(value)) {
202 const result: unknown[] = [];
203 for (const entry of value) {
204 if (budget.nodes <= 0) break;
205 const sanitized = sanitizeToolValue(entry, budget, depth + 1);
206 if (sanitized !== undefined) result.push(sanitized);
207 }
208 return result;
209 }
210 if (!Predicate.isObject(value)) {
211 return value;
212 }
213 const entries: Array<readonly [string, unknown]> = [];
214 for (const [key, entry] of Object.entries(value)) {
215 if (budget.nodes <= 0) break;
216 if (
217 (value.type === "image" && (key === "data" || key === "blob")) ||
218 (key === "blob" &&
219 typeof value.mimeType === "string" &&
220 value.mimeType.startsWith("image/")) ||
221 ((key === "formatted_output" || key === "formattedOutput") &&
222 (entry === value.combinedOutput || entry === value.combined_output))
223 ) {
224 continue;
225 }
226 const sanitized = sanitizeToolValue(entry, budget, depth + 1);
227 if (sanitized !== undefined) entries.push([key, sanitized]);
228 }
229 return Object.fromEntries(entries);
231​
232/** Bound both retained raw events and display data before they enter the event stream. */
233export function sanitizeAntigravityToolPayload(payload: unknown): unknown {
234 return sanitizeToolValue(payload, { nodes: 512, text: 64_000 }, 0);
236​
237/** The runtime uses this before it retains tool state or dispatches raw callbacks. */
238export function normalizeAntigravitySessionUpdate(
239 notification: EffectAcpSchema.SessionNotification,
240): EffectAcpSchema.SessionNotification {
241 const update = notification.update;
242 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
243 return notification;
244 }
245 const contentBudget = { nodes: 512, text: 32_000 };
246 const content = update.content?.flatMap((entry) => {
247 const decoded = Option.getOrUndefined(
248 decodeToolCallContent(sanitizeToolValue(entry, contentBudget, 0)),
249 );
250 return decoded === undefined ? [] : [decoded];
251 });
252 const meta = sanitizeAntigravityToolPayload(update._meta);
253 return {
254 ...notification,
255 update: {
256 ...update,
257 ...(typeof update.title === "string" ? { title: boundText(update.title) } : {}),
258 ...(update.rawInput !== undefined
259 ? { rawInput: sanitizeAntigravityToolPayload(update.rawInput) }
260 : {}),
261 ...(update.rawOutput !== undefined
262 ? { rawOutput: sanitizeAntigravityToolPayload(update.rawOutput) }
263 : {}),
264 ...(update.content !== undefined ? { content: content ?? [] } : {}),
265 ...(update._meta !== undefined ? { _meta: Predicate.isObject(meta) ? meta : null } : {}),
266 },
267 };
269​
270function localImagePath(imagePath: string | undefined): string | undefined {
271 if (!imagePath || imagePath.length > TOOL_TEXT_LIMIT) {
272 return undefined;
273 }
274 const path = imagePath.trim();
275 if (!isWorkspaceImagePreviewPath(path)) {
276 return undefined;
277 }
278 if (/^file:\/\//i.test(path)) {
279 try {
280 const url = new URL(path);
281 if (url.hostname && url.hostname !== "localhost") return undefined;
282 const pathname = decodeURIComponent(url.pathname);
283 return /^\/[a-z]:\//i.test(pathname) ? pathname.slice(1) : pathname;
284 } catch {
285 return undefined;
286 }
287 }
288 return /^[a-z][a-z\d+.-]*:/i.test(path) && !/^[a-z]:[\\/]/i.test(path) ? undefined : path;
290​
291export function normalizeAntigravityToolCall(toolCall: AcpToolCallState): AcpToolCallState {
292 const input = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawInput));
293 const output = Option.getOrUndefined(decodeNativeToolFields(toolCall.data.rawOutput));
294 const nativeCommand =
295 input?.CommandLine ??
296 input?.command_line ??
297 input?.commandLine ??
298 input?.command ??
299 output?.commandLine ??
300 output?.command_line ??
301 toolCall.command;
302 const command = nativeCommand?.trim() ? boundText(nativeCommand.trim()) : undefined;
303 const nativeCwd =
304 input?.Cwd ??
305 input?.WorkingDirectory ??
306 input?.working_dir ??
307 input?.workingDir ??
308 input?.cwd ??
309 output?.workingDir ??
310 output?.working_dir;
311 const cwd = nativeCwd?.trim() ? boundText(nativeCwd.trim()) : undefined;
312 const nativeOutput = output?.combinedOutput ?? output?.combined_output;
313 const aggregatedOutput = nativeOutput === undefined ? undefined : boundText(nativeOutput);
314 const exitCode = output?.exitCode ?? output?.exit_code;
315 const imagePath = localImagePath(output?.imagePath);
316 const sanitizedData = sanitizeAntigravityToolPayload(toolCall.data);
317 const data: Record<string, unknown> = Predicate.isObject(sanitizedData) ? sanitizedData : {};
318 const kind = toolCall.kind ?? (command !== undefined ? "execute" : undefined);
319 if (kind !== undefined) data.kind = kind;
320 if (command !== undefined) data.command = command;
321 if (cwd !== undefined) data.cwd = cwd;
322 if (imagePath !== undefined) data.imagePath = imagePath;
323 if (kind === "execute") {
324 data.item = {
325 ...(Predicate.isObject(data.item) ? data.item : {}),
326 ...(command !== undefined ? { command } : {}),
327 ...(cwd !== undefined ? { cwd } : {}),
328 ...(aggregatedOutput !== undefined ? { aggregatedOutput } : {}),
329 ...(exitCode !== undefined ? { exitCode } : {}),
330 };
331 }
332 return {
333 ...toolCall,
334 ...(kind !== undefined ? { kind } : {}),
335 ...(command !== undefined ? { command } : {}),
336 ...(toolCall.title !== undefined ? { title: boundText(toolCall.title) } : {}),
337 ...(command !== undefined
338 ? { detail: command }
339 : toolCall.detail !== undefined
340 ? { detail: boundText(toolCall.detail) }
341 : {}),
342 data,
343 };
345​
346/** Only commands still running after end_turn become background tasks. */
347export function isAntigravityOpenCommand(toolCall: AcpToolCallState): boolean {
348 return toolCall.kind === "execute" && toolCall.status === "inProgress";
350​
351/** ACP 1.1.1 exposes subagent invocations as ordinary tools, without child IDs or models. */
352export function classifyAntigravitySubagentToolCall(
353 toolCall: AcpToolCallState,
354 rawPayload: unknown,
355): "subagent" | "mcp" | undefined {
356 if (
357 (toolCall.kind !== undefined && toolCall.kind !== "other") ||
358 (toolCall.title !== "Running start_subagent" && toolCall.title !== "Run start_subagent?")
359 )
360 return undefined;
361 const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined;
362 const meta = Predicate.isObject(update) ? update._meta : undefined;
363 return Predicate.isObject(meta) && meta.is_mcp_tool_call === true ? "mcp" : "subagent";
365​
366/** History sends a completed start before the separate result and its final status. */
367export function isAntigravitySubagentReplayStart(rawPayload: unknown): boolean {
368 const update = Predicate.isObject(rawPayload) ? rawPayload.update : undefined;
369 return (
370 Predicate.isObject(update) &&
371 update.sessionUpdate === "tool_call" &&
372 update.status === "completed" &&
373 (update.rawOutput === undefined || update.rawOutput === null)
374 );
376​
377export function antigravitySubagentOutput(toolCall: AcpToolCallState): string | undefined {
378 const output = toolCall.data.rawOutput;
379 return typeof output === "string" && output.trim() ? boundText(output.trim()) : undefined;