@open-document/core 0.14.3 → 0.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-4K9V8ysT.js → build-CBMroMqd.js} +1 -1
- package/dist/{check-B40JlWME.js → check-C2kIZr3f.js} +3 -3
- package/dist/cli/bin.js +9 -9
- package/dist/{context-Clm_nmr1.js → context-DGp1jwN5.js} +1 -1
- package/dist/{dev-De3pLYn_.js → dev-DmzGncKf.js} +1 -1
- package/dist/{diff-nU9ybiMk.js → diff-CMI_PVzz.js} +2 -2
- package/dist/{export-B9rrNBx2.js → export-BQMUBoBB.js} +3 -3
- package/dist/{import-C3542Wry.js → import-CiSRqZyo.js} +3 -3
- package/dist/ops/index.js +2 -2
- package/dist/{ops-ByJnGyuE.js → ops-DQbZmYRF.js} +1 -1
- package/dist/{preview-id9mj3IU.js → preview-CERhZ_FX.js} +1 -1
- package/dist/{session-CdkoJhi1.js → session-DdaKKd7_.js} +1007 -4
- package/dist/{templates-UJ_v7H-a.js → templates-CBeC-v7e.js} +3 -3
- package/dist/vite/index.js +1 -1
- package/package.json +1 -1
- package/skills/doc-authoring/SKILL.md +14 -62
- package/skills/doc-authoring/references/diagrams.md +32 -0
- package/skills/doc-authoring/references/runtime.md +15 -0
- package/src/agent/consent.ts +42 -0
- package/src/agent/provider.ts +24 -1
- package/src/agent/providers/antigravity-local.ts +193 -0
- package/src/agent/providers/antigravity.ts +656 -0
- package/src/agent/providers/index.ts +2 -1
- package/src/agent/runner.ts +4 -0
- package/src/agent/sandbox-sync.ts +178 -0
- package/src/agent/status.ts +33 -1
- package/src/agent/types.ts +21 -3
- package/src/app/components/agent/agent-panel.tsx +180 -42
- package/src/app/components/agent/connect-view.tsx +294 -26
- package/src/app/components/agent/provider-logo.tsx +4 -0
- package/src/app/lib/agent/use-agent.ts +14 -1
- package/src/app/lib/i18n-ja/agent-panel.ts +49 -0
- package/src/app/lib/i18n-ko/agent-panel.ts +48 -0
- package/src/app/lib/i18n-zh-cn/agent-panel.ts +46 -0
- package/src/app/lib/i18n-zh-tw/agent-panel.ts +46 -0
- package/src/app/lib/use-locale.ts +43 -0
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { hasConsent } from '../consent.ts';
|
|
4
|
+
import { extractQuestionBlock, TEXT_QUESTIONS_INSTRUCTION } from '../prompt.ts';
|
|
5
|
+
import {
|
|
6
|
+
type AgentProvider,
|
|
7
|
+
clipDetail,
|
|
8
|
+
isInsideRoots,
|
|
9
|
+
type ProviderEvent,
|
|
10
|
+
type ProviderRunOptions,
|
|
11
|
+
} from '../provider.ts';
|
|
12
|
+
import {
|
|
13
|
+
collectUploads,
|
|
14
|
+
decideWrites,
|
|
15
|
+
hashBytes,
|
|
16
|
+
readTar,
|
|
17
|
+
SANDBOX_ROOT,
|
|
18
|
+
snapshotRel,
|
|
19
|
+
type UploadPlan,
|
|
20
|
+
} from '../sandbox-sync.ts';
|
|
21
|
+
import type { AgentModelOption } from '../types.ts';
|
|
22
|
+
import {
|
|
23
|
+
ensureEnvironment,
|
|
24
|
+
ensureWorker,
|
|
25
|
+
forgetEnvironment,
|
|
26
|
+
installCli,
|
|
27
|
+
installedCliVersion,
|
|
28
|
+
localModeSupported,
|
|
29
|
+
stopWorker,
|
|
30
|
+
} from './antigravity-local.ts';
|
|
31
|
+
|
|
32
|
+
export const ANTIGRAVITY_AGENT = 'antigravity-preview-09-2026';
|
|
33
|
+
export const ANTIGRAVITY_CONSENT_VERSION = '2026-11-14.2';
|
|
34
|
+
const API_BASE = 'https://generativelanguage.googleapis.com/v1beta';
|
|
35
|
+
const KEY_ENV = 'GEMINI_API_KEY';
|
|
36
|
+
// A cap per turn, so a runaway loop costs cents rather than dollars.
|
|
37
|
+
const MAX_TOTAL_TOKENS = 500_000;
|
|
38
|
+
const SNAPSHOT_ATTEMPTS = 4;
|
|
39
|
+
|
|
40
|
+
// Antigravity's own default comes first.
|
|
41
|
+
const MODELS: AgentModelOption[] = [
|
|
42
|
+
{ id: 'gemini-4-hydrogen', label: 'Gemini 4 Hydrogen', efforts: [] },
|
|
43
|
+
{ id: 'gemini-4-carbon', label: 'Gemini 4 Carbon', efforts: [] },
|
|
44
|
+
{ id: 'gemini-4-argon', label: 'Gemini 4 Argon', efforts: [] },
|
|
45
|
+
{ id: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash', efforts: [] },
|
|
46
|
+
{ id: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash', efforts: [] },
|
|
47
|
+
{ id: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash-Lite', efforts: [] },
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
// USD per million tokens, Standard tier, from the Gemini API price list; a model
|
|
51
|
+
// missing here gets no estimate.
|
|
52
|
+
const PRICES: Record<string, { from: string; input: number; cached: number; output: number }[]> = {
|
|
53
|
+
'gemini-4-hydrogen': [{ from: '', input: 1.5, cached: 0.075, output: 7.5 }],
|
|
54
|
+
'gemini-4-carbon': [
|
|
55
|
+
{ from: '2026-12-01', input: 4, cached: 0.2, output: 20 },
|
|
56
|
+
{ from: '', input: 2, cached: 0.1, output: 10 },
|
|
57
|
+
],
|
|
58
|
+
'gemini-4-argon': [
|
|
59
|
+
{ from: '2026-12-01', input: 4, cached: 0.2, output: 20 },
|
|
60
|
+
{ from: '', input: 2, cached: 0.1, output: 10 },
|
|
61
|
+
],
|
|
62
|
+
'gemini-3.8-flash': [
|
|
63
|
+
{ from: '2027-01-01', input: 1.5, cached: 0.15, output: 7.5 },
|
|
64
|
+
{ from: '', input: 0.75, cached: 0.075, output: 3.75 },
|
|
65
|
+
],
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
type Usage = {
|
|
69
|
+
total_input_tokens?: number;
|
|
70
|
+
total_cached_tokens?: number;
|
|
71
|
+
total_output_tokens?: number;
|
|
72
|
+
total_thought_tokens?: number;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export function estimateCostUsd(model: string | null, usage: Usage | undefined, now = new Date()) {
|
|
76
|
+
const tiers = model ? PRICES[model] : undefined;
|
|
77
|
+
if (!tiers || !usage) return null;
|
|
78
|
+
const day = now.toISOString().slice(0, 10);
|
|
79
|
+
const price = tiers.find((t) => day >= t.from);
|
|
80
|
+
if (!price) return null;
|
|
81
|
+
const input = usage.total_input_tokens ?? 0;
|
|
82
|
+
const cached = Math.min(usage.total_cached_tokens ?? 0, input);
|
|
83
|
+
const output = (usage.total_output_tokens ?? 0) + (usage.total_thought_tokens ?? 0);
|
|
84
|
+
return ((input - cached) * price.input + cached * price.cached + output * price.output) / 1e6;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function parseDotenv(source: string, key: string): string | null {
|
|
88
|
+
for (const line of source.split(/\r?\n/)) {
|
|
89
|
+
const match = /^\s*(?:export\s+)?([\w.]+)\s*=\s*(.*)\s*$/.exec(line);
|
|
90
|
+
if (!match || match[1] !== key) continue;
|
|
91
|
+
const value = match[2].replace(/\s+#.*$/, '').replace(/^(['"])(.*)\1$/, '$2');
|
|
92
|
+
return value || null;
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// The key never leaves the dev server: the panel only learns whether one exists.
|
|
98
|
+
export async function resolveApiKey(cwd: string): Promise<string | null> {
|
|
99
|
+
const fromEnv = process.env[KEY_ENV]?.trim();
|
|
100
|
+
if (fromEnv) return fromEnv;
|
|
101
|
+
for (const name of ['.env.local', '.env']) {
|
|
102
|
+
const source = await fs.readFile(path.join(cwd, name), 'utf8').catch(() => null);
|
|
103
|
+
const value = source ? parseDotenv(source, KEY_ENV) : null;
|
|
104
|
+
if (value) return value;
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function sandboxInstruction(docRel: string, skipped: string[]): string {
|
|
110
|
+
const lines = [
|
|
111
|
+
`You run in a cloud Linux sandbox, not on the user's machine. A copy of their open-doc workspace is at ${SANDBOX_ROOT}: work there (cd ${SANDBOX_ROOT}) and use paths relative to it.`,
|
|
112
|
+
`The project skills are at ${SANDBOX_ROOT}/.agents/skills/<name>/SKILL.md; read the ones you need from there.`,
|
|
113
|
+
`When your turn ends, only files under ${SANDBOX_ROOT}/${docRel}/ are copied back to the user's machine. Changes anywhere else are lost, so never edit other documents, and never delete files: deletions are not copied back.`,
|
|
114
|
+
'There is no dev server, open-doc CLI or browser here, and none is needed: do not install packages or try to run the project.',
|
|
115
|
+
'In replies, name files by their workspace-relative path as plain text, never as file:// links: the user cannot open sandbox paths.',
|
|
116
|
+
];
|
|
117
|
+
if (skipped.length > 0) {
|
|
118
|
+
const shown = skipped.slice(0, 20).join(', ');
|
|
119
|
+
lines.push(
|
|
120
|
+
`These files exist on the user's machine but were not uploaded (binary or too large): ${shown}${skipped.length > 20 ? ', …' : ''}. Reference them by path; do not recreate them.`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
return lines.join(' ');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function localInstruction(docRel: string): string {
|
|
127
|
+
return [
|
|
128
|
+
"Your file tools run on the user's own computer, confined to their open-doc project folder, and edits appear in their viewer as you save them.",
|
|
129
|
+
'The shell is disabled: never call execute_bash, it always fails. Commands, package installs and the dev server are unavailable, and none is needed.',
|
|
130
|
+
`Open ${docRel}/index.tsx directly as your first step: do not list folders or search for it. Work only in ${docRel}/, never in other documents or project files such as package.json or open-doc.config.ts.`,
|
|
131
|
+
'For a small change (wording, a translation, a value in a style) edit it straight away; that needs no skill. Read .agents/skills/doc-authoring/SKILL.md (or create-doc, apply-comments) only before adding pages, sections or structures you have not written here before. This overrides the general advice to read the skills before every edit.',
|
|
132
|
+
"view_file shows no line numbers, so never guess a line range: when you call replace_file_content, set StartLine to 1 and EndLine to the file's last line, and let a TargetContent that occurs once in the file pick the spot.",
|
|
133
|
+
'Never list, search or open node_modules, dist or out.',
|
|
134
|
+
'In replies, name files by their project-relative path as plain text, never as file:// links.',
|
|
135
|
+
].join(' ');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
type Step = {
|
|
139
|
+
type?: string;
|
|
140
|
+
id?: string;
|
|
141
|
+
call_id?: string;
|
|
142
|
+
name?: string;
|
|
143
|
+
arguments?: Record<string, unknown>;
|
|
144
|
+
is_error?: boolean;
|
|
145
|
+
result?: unknown;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
type StreamEvent = {
|
|
149
|
+
event_type?: string;
|
|
150
|
+
index?: number;
|
|
151
|
+
step?: Step;
|
|
152
|
+
delta?: { type?: string; text?: string; arguments?: string };
|
|
153
|
+
interaction?: {
|
|
154
|
+
id?: string;
|
|
155
|
+
status?: string;
|
|
156
|
+
environment_id?: string;
|
|
157
|
+
usage?: Usage;
|
|
158
|
+
};
|
|
159
|
+
interaction_id?: string;
|
|
160
|
+
status?: string;
|
|
161
|
+
error?: { message?: string };
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const TOOL_TITLES: Record<string, string> = {
|
|
165
|
+
view_file: 'Read',
|
|
166
|
+
list_dir: 'List folder',
|
|
167
|
+
replace_file_content: 'Edit',
|
|
168
|
+
multi_replace_file_content: 'Edit',
|
|
169
|
+
write_to_file: 'Write',
|
|
170
|
+
create_file: 'Write',
|
|
171
|
+
run_command: 'Run command',
|
|
172
|
+
execute_bash: 'Run command',
|
|
173
|
+
read_file: 'Read',
|
|
174
|
+
write_file: 'Write',
|
|
175
|
+
edit_file: 'Edit',
|
|
176
|
+
grep_search: 'Search',
|
|
177
|
+
find_by_name: 'Find files',
|
|
178
|
+
search_web: 'Web search',
|
|
179
|
+
read_url_content: 'Read URL',
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
function toolDetail(args: Record<string, unknown> | undefined, roots: string[]): string | null {
|
|
183
|
+
if (!args) return null;
|
|
184
|
+
const value =
|
|
185
|
+
args.TargetFile ??
|
|
186
|
+
args.AbsolutePath ??
|
|
187
|
+
args.DirectoryPath ??
|
|
188
|
+
args.SearchPath ??
|
|
189
|
+
args.SearchDirectory ??
|
|
190
|
+
args.path ??
|
|
191
|
+
args.file_path ??
|
|
192
|
+
args.CommandLine ??
|
|
193
|
+
args.command ??
|
|
194
|
+
args.Query ??
|
|
195
|
+
args.Pattern;
|
|
196
|
+
if (typeof value !== 'string') return null;
|
|
197
|
+
const root = roots.find((r) => value.startsWith(`${r.replace(/[\\/]+$/, '')}/`));
|
|
198
|
+
return clipDetail(root ? value.slice(root.replace(/[\\/]+$/, '').length + 1) : value);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const SHELL_TOOL = 'execute_bash';
|
|
202
|
+
|
|
203
|
+
function isBlockedShell(call: Step, result: Step): boolean {
|
|
204
|
+
if (call.name !== SHELL_TOOL || result.is_error !== true) return false;
|
|
205
|
+
return /disable-bash|is disabled/i.test(JSON.stringify(result.result ?? ''));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function createAntigravityMapper(
|
|
209
|
+
emit: (event: ProviderEvent) => void,
|
|
210
|
+
roots: string[] = [SANDBOX_ROOT],
|
|
211
|
+
) {
|
|
212
|
+
const steps = new Map<number, Step>();
|
|
213
|
+
const texts = new Map<number, string>();
|
|
214
|
+
let interactionId: string | null = null;
|
|
215
|
+
let environmentId: string | null = null;
|
|
216
|
+
let status: string | null = null;
|
|
217
|
+
let usage: Usage | undefined;
|
|
218
|
+
|
|
219
|
+
const textId = (index: number) => `${interactionId ?? 'agy'}-t${index}`;
|
|
220
|
+
|
|
221
|
+
// A call's arguments stream in as deltas after its start, so it is shown
|
|
222
|
+
// once they are complete: at its stop, or at its result if that comes first.
|
|
223
|
+
const calls = new Map<number, { step: Step; args: string }>();
|
|
224
|
+
const startCall = (index: number) => {
|
|
225
|
+
const call = calls.get(index);
|
|
226
|
+
if (!call?.step.id) return;
|
|
227
|
+
calls.delete(index);
|
|
228
|
+
let args = call.step.arguments;
|
|
229
|
+
if (call.args) {
|
|
230
|
+
try {
|
|
231
|
+
args = { ...args, ...(JSON.parse(call.args) as Record<string, unknown>) };
|
|
232
|
+
} catch {}
|
|
233
|
+
}
|
|
234
|
+
const name = call.step.name ?? 'tool';
|
|
235
|
+
emit({
|
|
236
|
+
type: 'tool-start',
|
|
237
|
+
id: call.step.id,
|
|
238
|
+
name,
|
|
239
|
+
title: TOOL_TITLES[name] ?? name,
|
|
240
|
+
detail: toolDetail(args, roots),
|
|
241
|
+
});
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const finishText = (index: number) => {
|
|
245
|
+
const text = texts.get(index);
|
|
246
|
+
if (text === undefined) return;
|
|
247
|
+
texts.delete(index);
|
|
248
|
+
const asked = extractQuestionBlock(text);
|
|
249
|
+
emit({ type: 'text-end', id: textId(index), text: asked ? asked.text : text });
|
|
250
|
+
if (asked) emit({ type: 'questions', questions: asked.questions });
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
return {
|
|
254
|
+
get interactionId() {
|
|
255
|
+
return interactionId;
|
|
256
|
+
},
|
|
257
|
+
get environmentId() {
|
|
258
|
+
return environmentId;
|
|
259
|
+
},
|
|
260
|
+
get status() {
|
|
261
|
+
return status;
|
|
262
|
+
},
|
|
263
|
+
get usage() {
|
|
264
|
+
return usage;
|
|
265
|
+
},
|
|
266
|
+
handle(event: StreamEvent): void {
|
|
267
|
+
switch (event.event_type) {
|
|
268
|
+
case 'interaction.created':
|
|
269
|
+
case 'interaction.completed': {
|
|
270
|
+
const it = event.interaction;
|
|
271
|
+
if (it?.id && it.id !== interactionId) {
|
|
272
|
+
interactionId = it.id;
|
|
273
|
+
emit({ type: 'session-id', id: it.id });
|
|
274
|
+
}
|
|
275
|
+
if (it?.environment_id) environmentId = it.environment_id;
|
|
276
|
+
if (it?.status) status = it.status;
|
|
277
|
+
if (it?.usage) usage = it.usage;
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
case 'interaction.status_update':
|
|
281
|
+
if (event.status) status = event.status;
|
|
282
|
+
return;
|
|
283
|
+
case 'step.start': {
|
|
284
|
+
const step = event.step;
|
|
285
|
+
if (event.index === undefined || !step) return;
|
|
286
|
+
steps.set(event.index, step);
|
|
287
|
+
if (step.type === 'function_call' && step.id) {
|
|
288
|
+
calls.set(event.index, { step, args: '' });
|
|
289
|
+
} else if (step.type === 'function_result' && step.call_id) {
|
|
290
|
+
const entry = [...calls].find(([, call]) => call.step.id === step.call_id);
|
|
291
|
+
// Local mode runs with --disable-bash on purpose; a call it turns
|
|
292
|
+
// away is not a failure worth showing.
|
|
293
|
+
if (entry && isBlockedShell(entry[1].step, step)) {
|
|
294
|
+
calls.delete(entry[0]);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
if (entry) startCall(entry[0]);
|
|
298
|
+
emit({ type: 'tool-end', id: step.call_id, ok: step.is_error !== true });
|
|
299
|
+
} else if (step.type === 'model_output') {
|
|
300
|
+
texts.set(event.index, '');
|
|
301
|
+
emit({ type: 'text-start', id: textId(event.index) });
|
|
302
|
+
}
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
case 'step.delta': {
|
|
306
|
+
if (event.index === undefined) return;
|
|
307
|
+
const call = calls.get(event.index);
|
|
308
|
+
if (call && event.delta?.type === 'arguments_delta') {
|
|
309
|
+
call.args += event.delta.arguments ?? '';
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (steps.get(event.index)?.type !== 'model_output') return;
|
|
313
|
+
const text = event.delta?.type === 'text' ? event.delta.text : undefined;
|
|
314
|
+
if (!text) return;
|
|
315
|
+
texts.set(event.index, (texts.get(event.index) ?? '') + text);
|
|
316
|
+
emit({ type: 'text-delta', id: textId(event.index), text });
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
case 'step.stop':
|
|
320
|
+
if (event.index === undefined) return;
|
|
321
|
+
// A shell call waits for its result: it may only be the disabled shell.
|
|
322
|
+
if (calls.get(event.index)?.step.name !== SHELL_TOOL) startCall(event.index);
|
|
323
|
+
finishText(event.index);
|
|
324
|
+
return;
|
|
325
|
+
case 'error':
|
|
326
|
+
emit({ type: 'error', text: event.error?.message ?? 'Antigravity reported an error.' });
|
|
327
|
+
return;
|
|
328
|
+
default:
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
},
|
|
332
|
+
flush(): void {
|
|
333
|
+
for (const index of Array.from(calls.keys())) startCall(index);
|
|
334
|
+
for (const index of Array.from(texts.keys())) finishText(index);
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async function* sseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<StreamEvent> {
|
|
340
|
+
const reader = body.getReader();
|
|
341
|
+
const decoder = new TextDecoder();
|
|
342
|
+
let buffer = '';
|
|
343
|
+
for (;;) {
|
|
344
|
+
const { done, value } = await reader.read();
|
|
345
|
+
buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
|
|
346
|
+
let newline = buffer.indexOf('\n');
|
|
347
|
+
while (newline !== -1) {
|
|
348
|
+
const line = buffer.slice(0, newline).trimEnd();
|
|
349
|
+
buffer = buffer.slice(newline + 1);
|
|
350
|
+
if (line.startsWith('data:')) {
|
|
351
|
+
try {
|
|
352
|
+
yield JSON.parse(line.slice(5));
|
|
353
|
+
} catch {}
|
|
354
|
+
}
|
|
355
|
+
newline = buffer.indexOf('\n');
|
|
356
|
+
}
|
|
357
|
+
if (done) return;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function apiError(res: Response): Promise<string> {
|
|
362
|
+
const text = await res.text().catch(() => '');
|
|
363
|
+
try {
|
|
364
|
+
const parsed = JSON.parse(text) as { error?: { message?: string } };
|
|
365
|
+
if (parsed.error?.message) return `Gemini API ${res.status}: ${parsed.error.message}`;
|
|
366
|
+
} catch {}
|
|
367
|
+
return `Gemini API ${res.status}${text ? `: ${text.slice(0, 300)}` : ''}`;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async function downloadSnapshot(key: string, environmentId: string, signal: AbortSignal) {
|
|
371
|
+
const url = `${API_BASE}/files/environment-${encodeURIComponent(environmentId)}:download?alt=media`;
|
|
372
|
+
let last = '';
|
|
373
|
+
for (let attempt = 0; attempt < SNAPSHOT_ATTEMPTS; attempt++) {
|
|
374
|
+
if (attempt > 0) await new Promise((r) => setTimeout(r, 1500 * attempt));
|
|
375
|
+
const res = await fetch(url, { headers: { 'x-goog-api-key': key }, signal });
|
|
376
|
+
if (res.ok) return new Uint8Array(await res.arrayBuffer());
|
|
377
|
+
last = await apiError(res);
|
|
378
|
+
}
|
|
379
|
+
throw new Error(`Could not download the sandbox: ${last}`);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function localHashes(cwd: string, rels: string[]): Promise<Map<string, string>> {
|
|
383
|
+
const out = new Map<string, string>();
|
|
384
|
+
for (const rel of rels) {
|
|
385
|
+
const data = await fs.readFile(path.join(cwd, rel)).catch(() => null);
|
|
386
|
+
if (data) out.set(rel, hashBytes(data));
|
|
387
|
+
}
|
|
388
|
+
return out;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function writeBack(
|
|
392
|
+
opts: ProviderRunOptions,
|
|
393
|
+
docRel: string,
|
|
394
|
+
plan: UploadPlan,
|
|
395
|
+
tar: Uint8Array,
|
|
396
|
+
interactionId: string,
|
|
397
|
+
) {
|
|
398
|
+
const entries = readTar(tar).flatMap((e) => {
|
|
399
|
+
const rel = snapshotRel(e.path, docRel);
|
|
400
|
+
return rel ? [{ rel, data: e.data }] : [];
|
|
401
|
+
});
|
|
402
|
+
const uploaded = new Map(plan.files.map((f) => [f.rel, f.hash]));
|
|
403
|
+
const local = await localHashes(
|
|
404
|
+
opts.cwd,
|
|
405
|
+
entries.map((e) => e.rel),
|
|
406
|
+
);
|
|
407
|
+
const written: string[] = [];
|
|
408
|
+
const conflicts: string[] = [];
|
|
409
|
+
const conflictDir = path.join(
|
|
410
|
+
opts.cwd,
|
|
411
|
+
'node_modules',
|
|
412
|
+
'.open-doc',
|
|
413
|
+
'antigravity-conflicts',
|
|
414
|
+
interactionId.replace(/[^\w-]/g, '').slice(-24),
|
|
415
|
+
);
|
|
416
|
+
for (const decision of decideWrites(entries, uploaded, local)) {
|
|
417
|
+
const target =
|
|
418
|
+
decision.action === 'write'
|
|
419
|
+
? path.join(opts.cwd, decision.rel)
|
|
420
|
+
: path.join(conflictDir, decision.rel);
|
|
421
|
+
const root = decision.action === 'write' ? opts.docDir : conflictDir;
|
|
422
|
+
if (!root || !isInsideRoots(opts.cwd, target, [root])) continue;
|
|
423
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
424
|
+
await fs.writeFile(target, decision.data);
|
|
425
|
+
(decision.action === 'write' ? written : conflicts).push(decision.rel);
|
|
426
|
+
}
|
|
427
|
+
return { written, conflicts, conflictDir };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
class EnvironmentGoneError extends Error {}
|
|
431
|
+
|
|
432
|
+
async function streamTurn(
|
|
433
|
+
opts: ProviderRunOptions,
|
|
434
|
+
key: string,
|
|
435
|
+
body: Record<string, unknown>,
|
|
436
|
+
roots: string[],
|
|
437
|
+
) {
|
|
438
|
+
const mapper = createAntigravityMapper(opts.emit, roots);
|
|
439
|
+
const cancel = () => {
|
|
440
|
+
const id = mapper.interactionId;
|
|
441
|
+
if (!id) return;
|
|
442
|
+
void fetch(`${API_BASE}/interactions/${encodeURIComponent(id)}:cancel`, {
|
|
443
|
+
method: 'POST',
|
|
444
|
+
headers: { 'x-goog-api-key': key },
|
|
445
|
+
}).catch(() => {});
|
|
446
|
+
};
|
|
447
|
+
opts.signal.addEventListener('abort', cancel, { once: true });
|
|
448
|
+
|
|
449
|
+
const res = await fetch(`${API_BASE}/interactions`, {
|
|
450
|
+
method: 'POST',
|
|
451
|
+
headers: { 'x-goog-api-key': key, 'content-type': 'application/json' },
|
|
452
|
+
body: JSON.stringify(body),
|
|
453
|
+
signal: opts.signal,
|
|
454
|
+
});
|
|
455
|
+
if (!res.ok || !res.body) {
|
|
456
|
+
const message = await apiError(res);
|
|
457
|
+
if (typeof body.environment === 'string' && (res.status === 404 || res.status === 403)) {
|
|
458
|
+
throw new EnvironmentGoneError(
|
|
459
|
+
`${message} The local environment was reset; send the message again.`,
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
throw new Error(message);
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
for await (const event of sseEvents(res.body)) mapper.handle(event);
|
|
466
|
+
} catch (err) {
|
|
467
|
+
if (opts.signal.aborted) return null;
|
|
468
|
+
throw err;
|
|
469
|
+
} finally {
|
|
470
|
+
mapper.flush();
|
|
471
|
+
}
|
|
472
|
+
if (opts.signal.aborted) return null;
|
|
473
|
+
if (mapper.status === 'failed' || mapper.status === 'cancelled') {
|
|
474
|
+
throw new Error(`The Antigravity turn ${mapper.status}.`);
|
|
475
|
+
}
|
|
476
|
+
if (mapper.status === 'incomplete') {
|
|
477
|
+
opts.emit({
|
|
478
|
+
type: 'error',
|
|
479
|
+
text: `Stopped at the ${MAX_TOTAL_TOKENS.toLocaleString('en-US')}-token budget for one turn. Send "continue" to go on.`,
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
return mapper;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export function createAntigravityProvider(): AgentProvider {
|
|
486
|
+
return {
|
|
487
|
+
id: 'antigravity',
|
|
488
|
+
name: 'Antigravity',
|
|
489
|
+
sdkPackage: '',
|
|
490
|
+
cliCommand: '',
|
|
491
|
+
askInstruction: TEXT_QUESTIONS_INSTRUCTION,
|
|
492
|
+
canRewind: false,
|
|
493
|
+
canOpenBrowser: false,
|
|
494
|
+
auth: 'api-key',
|
|
495
|
+
preview: true,
|
|
496
|
+
consentVersion: ANTIGRAVITY_CONSENT_VERSION,
|
|
497
|
+
hasKey: async (cwd) => (await resolveApiKey(cwd)) !== null,
|
|
498
|
+
models: async () => MODELS,
|
|
499
|
+
async runtime(cwd) {
|
|
500
|
+
const version = await installedCliVersion(cwd);
|
|
501
|
+
return {
|
|
502
|
+
mode: version ? 'local' : 'cloud',
|
|
503
|
+
localSupported: localModeSupported(),
|
|
504
|
+
localVersion: version,
|
|
505
|
+
};
|
|
506
|
+
},
|
|
507
|
+
async install(cwd) {
|
|
508
|
+
await installCli(cwd);
|
|
509
|
+
},
|
|
510
|
+
dispose: stopWorker,
|
|
511
|
+
async run(opts: ProviderRunOptions): Promise<void> {
|
|
512
|
+
if (!(await hasConsent(opts.cwd, 'antigravity', ANTIGRAVITY_CONSENT_VERSION))) {
|
|
513
|
+
throw new Error('Accept the Antigravity preview terms in the agent panel first.');
|
|
514
|
+
}
|
|
515
|
+
const key = await resolveApiKey(opts.cwd);
|
|
516
|
+
if (!key) throw new Error(`Set ${KEY_ENV} in the environment or .env to use Antigravity.`);
|
|
517
|
+
if (!opts.docDir) {
|
|
518
|
+
throw new Error('Open a document first: Antigravity works on one document at a time.');
|
|
519
|
+
}
|
|
520
|
+
const docRel = path.relative(opts.cwd, opts.docDir).split(path.sep).join('/');
|
|
521
|
+
const turn = Date.now().toString(36);
|
|
522
|
+
const local = (await installedCliVersion(opts.cwd)) !== null;
|
|
523
|
+
const model = opts.model || null;
|
|
524
|
+
const agentConfig = {
|
|
525
|
+
type: 'antigravity',
|
|
526
|
+
max_total_tokens: MAX_TOTAL_TOKENS,
|
|
527
|
+
...(model ? { model } : {}),
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
if (local) {
|
|
531
|
+
const step = `agy-local-${turn}`;
|
|
532
|
+
opts.emit({
|
|
533
|
+
type: 'tool-start',
|
|
534
|
+
id: step,
|
|
535
|
+
name: 'sandbox',
|
|
536
|
+
title: 'Run on this computer',
|
|
537
|
+
detail: docRel,
|
|
538
|
+
});
|
|
539
|
+
let environment: Awaited<ReturnType<typeof ensureEnvironment>>;
|
|
540
|
+
try {
|
|
541
|
+
environment = await ensureEnvironment(opts.cwd, key);
|
|
542
|
+
await ensureWorker(opts.cwd, environment);
|
|
543
|
+
opts.emit({ type: 'tool-end', id: step, ok: true });
|
|
544
|
+
} catch (err) {
|
|
545
|
+
opts.emit({ type: 'tool-end', id: step, ok: false });
|
|
546
|
+
throw err;
|
|
547
|
+
}
|
|
548
|
+
const body = {
|
|
549
|
+
agent: ANTIGRAVITY_AGENT,
|
|
550
|
+
input: opts.prompt,
|
|
551
|
+
system_instruction: `${opts.systemPromptAppend} ${localInstruction(docRel)}`,
|
|
552
|
+
agent_config: agentConfig,
|
|
553
|
+
environment: environment.id,
|
|
554
|
+
...(opts.resume ? { previous_interaction_id: opts.resume } : {}),
|
|
555
|
+
stream: true,
|
|
556
|
+
};
|
|
557
|
+
let mapper: Awaited<ReturnType<typeof streamTurn>>;
|
|
558
|
+
try {
|
|
559
|
+
mapper = await streamTurn(opts, key, body, [opts.cwd]);
|
|
560
|
+
} catch (err) {
|
|
561
|
+
// A stale environment (deleted, or made under another key) is
|
|
562
|
+
// recreated on the next turn rather than failing every turn.
|
|
563
|
+
if (err instanceof EnvironmentGoneError) await forgetEnvironment(opts.cwd);
|
|
564
|
+
throw err;
|
|
565
|
+
}
|
|
566
|
+
if (opts.signal.aborted || !mapper) return;
|
|
567
|
+
opts.emit({
|
|
568
|
+
type: 'result',
|
|
569
|
+
durationMs: null,
|
|
570
|
+
costUsd: estimateCostUsd(model, mapper.usage),
|
|
571
|
+
});
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const upload = `agy-upload-${turn}`;
|
|
576
|
+
opts.emit({
|
|
577
|
+
type: 'tool-start',
|
|
578
|
+
id: upload,
|
|
579
|
+
name: 'sandbox',
|
|
580
|
+
title: 'Upload to cloud sandbox',
|
|
581
|
+
detail: docRel,
|
|
582
|
+
});
|
|
583
|
+
const plan = await collectUploads(opts.cwd, [
|
|
584
|
+
opts.docDir,
|
|
585
|
+
path.join(opts.cwd, '.agents', 'skills'),
|
|
586
|
+
]);
|
|
587
|
+
opts.emit({ type: 'tool-end', id: upload, ok: true });
|
|
588
|
+
|
|
589
|
+
const body = {
|
|
590
|
+
agent: ANTIGRAVITY_AGENT,
|
|
591
|
+
input: opts.prompt,
|
|
592
|
+
system_instruction: `${opts.systemPromptAppend} ${sandboxInstruction(docRel, plan.skipped)}`,
|
|
593
|
+
agent_config: agentConfig,
|
|
594
|
+
environment: {
|
|
595
|
+
type: 'remote',
|
|
596
|
+
sources: plan.files.map((f) => ({
|
|
597
|
+
type: 'inline',
|
|
598
|
+
content: f.content,
|
|
599
|
+
target: `${SANDBOX_ROOT}/${f.rel}`,
|
|
600
|
+
})),
|
|
601
|
+
},
|
|
602
|
+
...(opts.resume ? { previous_interaction_id: opts.resume } : {}),
|
|
603
|
+
stream: true,
|
|
604
|
+
};
|
|
605
|
+
const mapper = await streamTurn(opts, key, body, [SANDBOX_ROOT]);
|
|
606
|
+
if (opts.signal.aborted || !mapper) return;
|
|
607
|
+
|
|
608
|
+
const environmentId = mapper.environmentId;
|
|
609
|
+
if (environmentId && mapper.interactionId) {
|
|
610
|
+
const sync = `agy-sync-${turn}`;
|
|
611
|
+
opts.emit({
|
|
612
|
+
type: 'tool-start',
|
|
613
|
+
id: sync,
|
|
614
|
+
name: 'sandbox',
|
|
615
|
+
title: 'Copy changes back',
|
|
616
|
+
detail: docRel,
|
|
617
|
+
});
|
|
618
|
+
try {
|
|
619
|
+
const tar = await downloadSnapshot(key, environmentId, opts.signal);
|
|
620
|
+
const { written, conflicts, conflictDir } = await writeBack(
|
|
621
|
+
opts,
|
|
622
|
+
docRel,
|
|
623
|
+
plan,
|
|
624
|
+
tar,
|
|
625
|
+
mapper.interactionId,
|
|
626
|
+
);
|
|
627
|
+
opts.emit({ type: 'tool-end', id: sync, ok: true });
|
|
628
|
+
if (written.length > 0) {
|
|
629
|
+
opts.emit({
|
|
630
|
+
type: 'tool-start',
|
|
631
|
+
id: `agy-written-${turn}`,
|
|
632
|
+
name: 'file_change',
|
|
633
|
+
title: 'Edit',
|
|
634
|
+
detail: clipDetail(written.join(', ')),
|
|
635
|
+
});
|
|
636
|
+
opts.emit({ type: 'tool-end', id: `agy-written-${turn}`, ok: true });
|
|
637
|
+
}
|
|
638
|
+
if (conflicts.length > 0) {
|
|
639
|
+
opts.emit({
|
|
640
|
+
type: 'error',
|
|
641
|
+
text: `Not copied back, because they changed on this machine during the turn: ${conflicts.join(', ')}. The agent's versions are in ${path.relative(opts.cwd, conflictDir)}.`,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
} catch (err) {
|
|
645
|
+
opts.emit({ type: 'tool-end', id: sync, ok: false });
|
|
646
|
+
throw err;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
opts.emit({
|
|
650
|
+
type: 'result',
|
|
651
|
+
durationMs: null,
|
|
652
|
+
costUsd: estimateCostUsd(model, mapper.usage),
|
|
653
|
+
});
|
|
654
|
+
},
|
|
655
|
+
};
|
|
656
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { AgentProvider } from '../provider.ts';
|
|
2
2
|
import type { AgentProviderId } from '../types.ts';
|
|
3
|
+
import { createAntigravityProvider } from './antigravity.ts';
|
|
3
4
|
import { createCodexProvider } from './codex.ts';
|
|
4
5
|
|
|
5
6
|
export function createProviders(): Record<AgentProviderId, AgentProvider> {
|
|
6
|
-
return { codex: createCodexProvider() };
|
|
7
|
+
return { codex: createCodexProvider(), antigravity: createAntigravityProvider() };
|
|
7
8
|
}
|
package/src/agent/runner.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
1
2
|
import {
|
|
2
3
|
answersPrompt,
|
|
3
4
|
buildTurnPrompt,
|
|
@@ -289,9 +290,12 @@ export function createAgentRunner(opts: {
|
|
|
289
290
|
|
|
290
291
|
const promptOpts = promptOptions();
|
|
291
292
|
const prompt = buildTurnPrompt(promptText, context, promptOpts.docsDir);
|
|
293
|
+
const docId = context?.docId ?? session.docId;
|
|
292
294
|
void provider
|
|
293
295
|
.run({
|
|
294
296
|
cwd: userCwd,
|
|
297
|
+
docsDir: promptOpts.docsDir,
|
|
298
|
+
docDir: docId ? path.join(userCwd, promptOpts.docsDir, docId) : null,
|
|
295
299
|
writableRoots,
|
|
296
300
|
prompt,
|
|
297
301
|
systemPromptAppend: systemPromptAppend(provider.askInstruction, {
|