@causyne/agent 1.20.0 → 1.20.7
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/README.md +13 -9
- package/SECURITY.md +1 -4
- package/package.json +1 -1
- package/src/acp/client.js +176 -26
- package/src/acp/client.ts +167 -25
- package/src/acp/protocol.js +116 -0
- package/src/acp/protocol.ts +163 -0
- package/src/acp/server.js +5 -6
- package/src/acp/server.ts +4 -6
- package/src/agentLoop.d.ts +1 -0
- package/src/agentLoop.js +681 -245
- package/src/agentLoop.ts +708 -262
- package/src/agentPolicy.js +9 -0
- package/src/agentPolicy.ts +9 -0
- package/src/approvalPolicy.js +55 -0
- package/src/approvalPolicy.ts +66 -0
- package/src/browser/browserRuntime.js +217 -14
- package/src/browser/browserRuntime.ts +255 -14
- package/src/browser/causyneBrowser.js +1215 -68
- package/src/browser/causyneBrowser.ts +1340 -72
- package/src/cliMode.js +52 -29
- package/src/commands.js +141 -17
- package/src/config.js +22 -12
- package/src/continuum/ui/continuumPicker.js +18 -1
- package/src/continuum/ui/continuumPicker.ts +19 -1
- package/src/dynamicCatalogue.js +87 -20
- package/src/dynamicCatalogue.ts +85 -15
- package/src/launchIntent.js +40 -0
- package/src/launchIntent.ts +49 -0
- package/src/memoryManager.js +26 -2
- package/src/modelCatalogue.js +2 -0
- package/src/planCache.js +320 -11
- package/src/planCache.ts +402 -13
- package/src/providers/acp.js +173 -18
- package/src/providers/acp.ts +169 -19
- package/src/providers/antigravity.d.ts +5 -1
- package/src/providers/antigravity.js +674 -34
- package/src/providers/antigravity.ts +707 -35
- package/src/providers/base.d.ts +10 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/pi.js +161 -0
- package/src/providers/pi.ts +148 -0
- package/src/provisioning/capabilityProvisioner.js +17 -0
- package/src/provisioning/capabilityTools.js +1 -1
- package/src/sandbox.js +30 -39
- package/src/sessionJournal.js +53 -10
- package/src/sessionJournal.ts +64 -10
- package/src/taskShape.js +9 -9
- package/src/taskShape.ts +9 -9
- package/src/timeMachine.js +124 -0
- package/src/timeMachine.ts +141 -0
- package/src/toolPacks.js +4 -10
- package/src/tools/archive.js +196 -59
- package/src/tools/archive.ts +220 -0
- package/src/tools/browserAutomator.js +78 -9
- package/src/tools/browserAutomator.ts +90 -9
- package/src/tools/desktopOpen.js +114 -31
- package/src/tools/desktopOpen.ts +144 -0
- package/src/tools/gitExec.js +5 -3
- package/src/tools/nativeEngine.js +4 -3
- package/src/tools/nativeEngine.ts +5 -3
- package/src/tools/openSourceToolProvisioner.js +5 -4
- package/src/tools/openSourceToolProvisioner.ts +5 -4
- package/src/tools/registry.js +3 -0
- package/src/tools/screenshot.js +55 -71
- package/src/tools/screenshot.ts +70 -0
- package/src/tools/sysRun.js +284 -117
- package/src/tools/sysRun.ts +347 -0
- package/src/tools/toolSelfRepair.js +109 -2
- package/src/tools/toolSelfRepair.ts +100 -2
- package/src/tools/updatePlan.js +49 -1
- package/src/tools/updatePlan.ts +43 -1
- package/src/tools/viewImage.js +93 -78
- package/src/tools/viewImage.ts +116 -0
- package/src/tools/webFetch.js +20 -6
- package/src/tools/webFetch.ts +26 -6
- package/src/tui/activityLayout.js +9 -0
- package/src/tui/activityLayout.ts +10 -0
- package/src/tui/block.d.ts +1 -0
- package/src/tui/chatRenderer.d.ts +23 -0
- package/src/tui/chatRenderer.js +49 -49
- package/src/tui/clipboardSync.js +28 -1
- package/src/tui/clipboardSync.ts +26 -1
- package/src/tui/codeProgress.js +299 -0
- package/src/tui/codeProgress.ts +304 -0
- package/src/tui/codeStreamRenderer.js +132 -0
- package/src/tui/codeStreamRenderer.ts +141 -0
- package/src/tui/commandPresentation.js +11 -0
- package/src/tui/commandPresentation.ts +18 -0
- package/src/tui/completion.js +45 -13
- package/src/tui/composerControls.js +131 -0
- package/src/tui/composerControls.ts +184 -0
- package/src/tui/diff.d.ts +2 -0
- package/src/tui/home.js +4 -2
- package/src/tui/homeTransition.js +21 -0
- package/src/tui/homeTransition.ts +27 -0
- package/src/tui/homeView.js +62 -0
- package/src/tui/homeView.ts +91 -0
- package/src/tui/layout.js +46 -0
- package/src/tui/layout.ts +52 -0
- package/src/tui/messageActionPlacement.js +16 -0
- package/src/tui/messageActionPlacement.ts +25 -0
- package/src/tui/messageInteraction.js +221 -0
- package/src/tui/messageInteraction.ts +275 -0
- package/src/tui/modelPicker.js +4 -24
- package/src/tui/modelPicker.ts +4 -20
- package/src/tui/mouseHover.js +6 -0
- package/src/tui/mouseHover.ts +5 -0
- package/src/tui/prompt.js +175 -101
- package/src/tui/resizeRecovery.js +15 -0
- package/src/tui/resizeRecovery.ts +27 -0
- package/src/tui/scrollInteraction.js +97 -0
- package/src/tui/scrollInteraction.ts +189 -0
- package/src/tui/sessionLayout.js +12 -0
- package/src/tui/sessionLayout.ts +12 -0
- package/src/tui/sessionPicker.js +111 -16
- package/src/tui/sessionPicker.ts +121 -16
- package/src/tui/sessionSidebar.js +78 -0
- package/src/tui/sessionSidebar.ts +95 -0
- package/src/tui/setup.js +1 -1
- package/src/tui/setup.ts +1 -1
- package/src/tui/stageSurface.js +120 -58
- package/src/tui/text.d.ts +6 -0
- package/src/tui/textLayout.js +23 -0
- package/src/tui/textLayout.ts +28 -0
- package/src/tui/viewport.js +204 -279
- package/src/tui/viewport.ts +326 -0
- package/src/types/contracts.ts +54 -0
- package/src/utils/paths.js +5 -4
- package/src/utils/paths.ts +5 -5
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import {
|
|
4
|
+
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
5
|
+
import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall } from './base.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* resolve here rather than failing at the provider.
|
|
8
|
+
* Baseline fallback models for instant offline availability.
|
|
9
|
+
* Live models are autodetected dynamically from `agy models`
|
|
10
|
+
* and cached in ~/.causyne/models_cache.json.
|
|
11
11
|
*/
|
|
12
|
-
export const
|
|
12
|
+
export const BASELINE_ANTIGRAVITY_MODELS: Record<string, string> = {
|
|
13
13
|
'Gemini 3.8 Flash (Low)': 'gemini-3.8-flash-low',
|
|
14
14
|
'Gemini 3.8 Flash (Medium)': 'gemini-3.8-flash-medium',
|
|
15
15
|
'Gemini 3.8 Flash (High)': 'gemini-3.8-flash-high',
|
|
@@ -25,16 +25,107 @@ export const ANTIGRAVITY_MODEL_IDS: Record<string, string> = {
|
|
|
25
25
|
'GPT-OSS 120B (Medium)': 'gpt-oss-120b-medium'
|
|
26
26
|
};
|
|
27
27
|
|
|
28
|
+
export const ANTIGRAVITY_MODEL_IDS: Record<string, string> = {
|
|
29
|
+
...BASELINE_ANTIGRAVITY_MODELS
|
|
30
|
+
};
|
|
31
|
+
|
|
28
32
|
export const ANTIGRAVITY_LABEL_BY_ID: Record<string, string> = Object.fromEntries(
|
|
29
33
|
Object.entries(ANTIGRAVITY_MODEL_IDS).map(([label, id]) => [id, label])
|
|
30
34
|
);
|
|
31
35
|
|
|
32
36
|
export const ANTIGRAVITY_MODELS: string[] = Object.keys(ANTIGRAVITY_MODEL_IDS);
|
|
33
37
|
|
|
38
|
+
export function registerAntigravityModel(slug: string, label?: string): void {
|
|
39
|
+
if (!slug || typeof slug !== 'string') return;
|
|
40
|
+
const cleanSlug = slug.trim();
|
|
41
|
+
const cleanLabel = (label && typeof label === 'string' && label.trim()) || cleanSlug;
|
|
42
|
+
|
|
43
|
+
ANTIGRAVITY_MODEL_IDS[cleanLabel] = cleanSlug;
|
|
44
|
+
ANTIGRAVITY_MODEL_IDS[cleanSlug] = cleanSlug;
|
|
45
|
+
ANTIGRAVITY_LABEL_BY_ID[cleanSlug] = cleanLabel;
|
|
46
|
+
if (!ANTIGRAVITY_MODELS.includes(cleanLabel)) {
|
|
47
|
+
ANTIGRAVITY_MODELS.push(cleanLabel);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function parseAgyModelsOutput(stdout: string): Array<{ id: string; label: string }> {
|
|
52
|
+
const result: Array<{ id: string; label: string }> = [];
|
|
53
|
+
if (!stdout || typeof stdout !== 'string') return result;
|
|
54
|
+
|
|
55
|
+
const lines = stdout.replace(/\r/g, '\n').split(/\n+/);
|
|
56
|
+
for (const rawLine of lines) {
|
|
57
|
+
const line = rawLine.replace(/\u001b\[[0-9;]*[A-Za-z]/g, '').trim();
|
|
58
|
+
if (!line) continue;
|
|
59
|
+
if (/^(fetching|loading|no models|error)/i.test(line)) continue;
|
|
60
|
+
if (line.endsWith('…') || line.endsWith('...')) continue;
|
|
61
|
+
|
|
62
|
+
const cleanLine = line.replace(/^[^a-zA-Z0-9_-]+/, '');
|
|
63
|
+
const match = cleanLine.match(/^([a-z0-9_.-]+)(?:\s+(.+))?$/i);
|
|
64
|
+
if (!match) continue;
|
|
65
|
+
|
|
66
|
+
const id = match[1]!.trim();
|
|
67
|
+
const label = (match[2] && match[2].trim()) || id;
|
|
68
|
+
result.push({ id, label });
|
|
69
|
+
registerAntigravityModel(id, label);
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function hydrateModelsFromDiskCache(): void {
|
|
75
|
+
try {
|
|
76
|
+
const home = process.env.HOME || process.env.USERPROFILE || '';
|
|
77
|
+
const cacheFile = path.join(home, '.causyne', 'models_cache.json');
|
|
78
|
+
if (!fs.existsSync(cacheFile)) return;
|
|
79
|
+
const content = fs.readFileSync(cacheFile, 'utf8');
|
|
80
|
+
const parsed = JSON.parse(content);
|
|
81
|
+
const agyModels = parsed?.providers?.antigravity?.models;
|
|
82
|
+
if (Array.isArray(agyModels)) {
|
|
83
|
+
for (const item of agyModels) {
|
|
84
|
+
if (typeof item === 'string' && item.trim()) {
|
|
85
|
+
const trimmed = item.trim();
|
|
86
|
+
if (!ANTIGRAVITY_MODEL_IDS[trimmed]) {
|
|
87
|
+
registerAntigravityModel(trimmed, trimmed);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
// Ignore cache read errors
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
hydrateModelsFromDiskCache();
|
|
98
|
+
|
|
34
99
|
export function resolveAgyModelId(model?: string | null): string {
|
|
35
100
|
if (typeof model !== 'string') return '';
|
|
36
101
|
const trimmed = model.trim();
|
|
37
|
-
|
|
102
|
+
if (!trimmed) return '';
|
|
103
|
+
|
|
104
|
+
if (ANTIGRAVITY_MODEL_IDS[trimmed]) {
|
|
105
|
+
return ANTIGRAVITY_MODEL_IDS[trimmed];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const lower = trimmed.toLowerCase();
|
|
109
|
+
for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
|
|
110
|
+
if (key.toLowerCase() === lower || slug.toLowerCase() === lower) {
|
|
111
|
+
return slug;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const effort = resolveAgyEffort(trimmed);
|
|
116
|
+
const candidateWithEffort = `${lower}-${effort}`;
|
|
117
|
+
for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
|
|
118
|
+
if (slug.toLowerCase() === candidateWithEffort || key.toLowerCase() === candidateWithEffort) {
|
|
119
|
+
return slug;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
|
|
123
|
+
if (slug.toLowerCase().startsWith(lower) || key.toLowerCase().startsWith(lower)) {
|
|
124
|
+
return slug;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return trimmed;
|
|
38
129
|
}
|
|
39
130
|
|
|
40
131
|
export function resolveAgyEffort(model?: string | null): string {
|
|
@@ -82,27 +173,333 @@ export function resolveAgyBinary(): string {
|
|
|
82
173
|
return 'agy';
|
|
83
174
|
}
|
|
84
175
|
|
|
176
|
+
function describeNativeAction(toolInfo: any): string | undefined {
|
|
177
|
+
const parameters = toolInfo && typeof toolInfo === 'object' ? toolInfo.parameters : null;
|
|
178
|
+
if (parameters && typeof parameters === 'object') {
|
|
179
|
+
for (const key of ['Path', 'path', 'file_path', 'TargetFile', 'target_file', 'CommandLine', 'command', 'url']) {
|
|
180
|
+
const value = parameters[key];
|
|
181
|
+
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
for (const key of ['toolAction', 'tool_action', 'toolSummary', 'tool_summary']) {
|
|
185
|
+
const value = toolInfo && toolInfo[key];
|
|
186
|
+
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
187
|
+
}
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function mapNativeToolToCausyne(
|
|
192
|
+
name: string,
|
|
193
|
+
rawParams: Record<string, any>,
|
|
194
|
+
index: number
|
|
195
|
+
): ChatResponseToolCall | null {
|
|
196
|
+
if (!name || typeof name !== 'string') return null;
|
|
197
|
+
const lowerName = name.toLowerCase().replace(/[_-]/g, '');
|
|
198
|
+
const params = rawParams && typeof rawParams === 'object' ? rawParams : {};
|
|
199
|
+
|
|
200
|
+
if (lowerName === 'runcommand' || lowerName === 'command' || lowerName === 'sysrun' || lowerName === 'terminal' || lowerName === 'bash' || lowerName === 'shell') {
|
|
201
|
+
const rawCmd = params.CommandLine ?? params.command ?? params.cmd ?? params.input ?? params.detail ?? '';
|
|
202
|
+
let cmd = typeof rawCmd === 'string' ? rawCmd.trim() : '';
|
|
203
|
+
if (!cmd && typeof params.parameters === 'object' && params.parameters) {
|
|
204
|
+
cmd = String(params.parameters.CommandLine || params.parameters.command || params.parameters.cmd || '').trim();
|
|
205
|
+
}
|
|
206
|
+
if (cmd) {
|
|
207
|
+
const isDaemon = Boolean(params.IsDaemon ?? params.isDaemon ?? params.daemon);
|
|
208
|
+
const cwd = params.Cwd ?? params.cwd;
|
|
209
|
+
if (isDaemon) {
|
|
210
|
+
const bgArgs: Record<string, any> = { command: cmd, label: 'daemon' };
|
|
211
|
+
if (typeof cwd === 'string' && cwd.trim()) bgArgs.cwd = cwd.trim();
|
|
212
|
+
return {
|
|
213
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
214
|
+
type: 'function',
|
|
215
|
+
function: {
|
|
216
|
+
name: 'sysRunBg',
|
|
217
|
+
arguments: JSON.stringify(bgArgs)
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
const args: Record<string, any> = { command: cmd };
|
|
222
|
+
if (typeof cwd === 'string' && cwd.trim()) args.cwd = cwd.trim();
|
|
223
|
+
return {
|
|
224
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
225
|
+
type: 'function',
|
|
226
|
+
function: {
|
|
227
|
+
name: 'sysRun',
|
|
228
|
+
arguments: JSON.stringify(args)
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (lowerName === 'viewfile' || lowerName === 'readfile' || lowerName === 'read' || lowerName === 'view' || lowerName === 'fsread') {
|
|
235
|
+
const filePath = params.AbsolutePath ?? params.path ?? params.file_path ?? params.TargetFile ?? '';
|
|
236
|
+
if (typeof filePath === 'string' && filePath.trim()) {
|
|
237
|
+
return {
|
|
238
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
239
|
+
type: 'function',
|
|
240
|
+
function: {
|
|
241
|
+
name: 'fs_read',
|
|
242
|
+
arguments: JSON.stringify({ path: filePath.trim() })
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (lowerName === 'listdir' || lowerName === 'fslist' || lowerName === 'list') {
|
|
249
|
+
const dirPath = params.DirectoryPath ?? params.path ?? '.';
|
|
250
|
+
return {
|
|
251
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
252
|
+
type: 'function',
|
|
253
|
+
function: {
|
|
254
|
+
name: 'fs_list',
|
|
255
|
+
arguments: JSON.stringify({ path: String(dirPath).trim() || '.' })
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (lowerName === 'grepsearch' || lowerName === 'searchworkspace') {
|
|
261
|
+
const query = params.Query ?? params.query ?? '';
|
|
262
|
+
if (typeof query === 'string' && query.trim()) {
|
|
263
|
+
return {
|
|
264
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
265
|
+
type: 'function',
|
|
266
|
+
function: {
|
|
267
|
+
name: 'workspace_search',
|
|
268
|
+
arguments: JSON.stringify({
|
|
269
|
+
query: query.trim(),
|
|
270
|
+
path: params.SearchPath ?? params.path ?? '.'
|
|
271
|
+
})
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (lowerName === 'writetofile' || lowerName === 'fswrite') {
|
|
278
|
+
const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
|
|
279
|
+
const content = params.CodeContent ?? params.content ?? '';
|
|
280
|
+
if (typeof filePath === 'string' && filePath.trim()) {
|
|
281
|
+
return {
|
|
282
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
283
|
+
type: 'function',
|
|
284
|
+
function: {
|
|
285
|
+
name: 'fs_write',
|
|
286
|
+
arguments: JSON.stringify({ path: filePath.trim(), content: String(content) })
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (lowerName === 'replacefilecontent' || lowerName === 'fsedit') {
|
|
293
|
+
const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
|
|
294
|
+
const oldText = params.TargetContent ?? params.oldText ?? '';
|
|
295
|
+
const newText = params.ReplacementContent ?? params.newText ?? '';
|
|
296
|
+
if (typeof filePath === 'string' && filePath.trim()) {
|
|
297
|
+
return {
|
|
298
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
299
|
+
type: 'function',
|
|
300
|
+
function: {
|
|
301
|
+
name: 'fs_edit',
|
|
302
|
+
arguments: JSON.stringify({ path: filePath.trim(), oldText: String(oldText), newText: String(newText) })
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (lowerName === 'openbrowserurl') {
|
|
309
|
+
const url = params.Url ?? params.url ?? '';
|
|
310
|
+
if (typeof url === 'string' && url.trim()) {
|
|
311
|
+
return {
|
|
312
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
313
|
+
type: 'function',
|
|
314
|
+
function: {
|
|
315
|
+
name: 'desktop.open',
|
|
316
|
+
arguments: JSON.stringify({ target: url.trim() })
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (lowerName === 'readurlcontent') {
|
|
323
|
+
const url = params.Url ?? params.url ?? '';
|
|
324
|
+
if (typeof url === 'string' && url.trim()) {
|
|
325
|
+
return {
|
|
326
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
327
|
+
type: 'function',
|
|
328
|
+
function: {
|
|
329
|
+
name: 'web_fetch',
|
|
330
|
+
arguments: JSON.stringify({ url: url.trim() })
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (lowerName === 'searchweb') {
|
|
337
|
+
const query = params.query ?? params.Query ?? '';
|
|
338
|
+
if (typeof query === 'string' && query.trim()) {
|
|
339
|
+
return {
|
|
340
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
341
|
+
type: 'function',
|
|
342
|
+
function: {
|
|
343
|
+
name: 'web_search',
|
|
344
|
+
arguments: JSON.stringify({ query: query.trim() })
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (lowerName === 'multireplacefilecontent' || lowerName === 'multireplace') {
|
|
351
|
+
const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
|
|
352
|
+
const rawChunks = Array.isArray(params.ReplacementChunks) ? params.ReplacementChunks : [];
|
|
353
|
+
const edits = rawChunks.map((chunk: any) => ({
|
|
354
|
+
old_string: String(chunk.TargetContent ?? chunk.old_string ?? ''),
|
|
355
|
+
new_string: String(chunk.ReplacementContent ?? chunk.new_string ?? '')
|
|
356
|
+
})).filter((e: any) => e.old_string);
|
|
357
|
+
if (typeof filePath === 'string' && filePath.trim() && edits.length > 0) {
|
|
358
|
+
return {
|
|
359
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
360
|
+
type: 'function',
|
|
361
|
+
function: {
|
|
362
|
+
name: 'MultiEdit',
|
|
363
|
+
arguments: JSON.stringify({ file_path: filePath.trim(), edits })
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (lowerName === 'browsersubagent' || lowerName === 'browseragent') {
|
|
370
|
+
const textToSearch = [
|
|
371
|
+
params.Url, params.url, params.Task, params.task, params.TaskName, params.taskName, params.TaskSummary
|
|
372
|
+
].filter(Boolean).join(' ');
|
|
373
|
+
const urlMatch = textToSearch.match(/https?:\/\/[^\s'")]+/i) || textToSearch.match(/localhost:\d+[^\s'")]*/i);
|
|
374
|
+
if (urlMatch) {
|
|
375
|
+
let targetUrl = urlMatch[0];
|
|
376
|
+
if (!targetUrl.startsWith('http')) targetUrl = `http://${targetUrl}`;
|
|
377
|
+
return {
|
|
378
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
379
|
+
type: 'function',
|
|
380
|
+
function: {
|
|
381
|
+
name: 'desktop.open',
|
|
382
|
+
arguments: JSON.stringify({ target: targetUrl })
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (lowerName === 'managetask') {
|
|
389
|
+
const action = String(params.Action ?? params.action ?? '').toLowerCase();
|
|
390
|
+
if (action === 'list') {
|
|
391
|
+
return {
|
|
392
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
393
|
+
type: 'function',
|
|
394
|
+
function: {
|
|
395
|
+
name: 'process_list',
|
|
396
|
+
arguments: JSON.stringify({})
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
if (action === 'kill') {
|
|
401
|
+
const pid = Number(params.TaskId ?? params.taskId ?? params.pid);
|
|
402
|
+
if (!Number.isNaN(pid) && pid > 0) {
|
|
403
|
+
return {
|
|
404
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
405
|
+
type: 'function',
|
|
406
|
+
function: {
|
|
407
|
+
name: 'proc_term',
|
|
408
|
+
arguments: JSON.stringify({ pid })
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
|
|
85
418
|
export class AntigravityProvider extends LLMProvider {
|
|
86
419
|
command: string;
|
|
420
|
+
printTimeout: string;
|
|
421
|
+
currentConversationId: string | null = null;
|
|
422
|
+
lastTaskId: string | null = null;
|
|
87
423
|
|
|
88
424
|
constructor(config: ProviderConfig = {}) {
|
|
89
425
|
super(config);
|
|
90
426
|
this.model = config.model || 'Gemini 3.8 Flash (Low)';
|
|
91
427
|
this.command = config.command || resolveAgyBinary();
|
|
92
|
-
this.
|
|
428
|
+
this.printTimeout = typeof config.printTimeout === 'string' && config.printTimeout.trim()
|
|
429
|
+
? config.printTimeout.trim()
|
|
430
|
+
: '1800s';
|
|
431
|
+
this.visionModels = ['*'];
|
|
93
432
|
this.audioModels = [];
|
|
94
433
|
}
|
|
95
434
|
|
|
435
|
+
formatDelta(messages: any[]): string {
|
|
436
|
+
const lines: string[] = [];
|
|
437
|
+
for (const msg of messages) {
|
|
438
|
+
const role = msg.role === 'user'
|
|
439
|
+
? 'User'
|
|
440
|
+
: (msg.role === 'assistant'
|
|
441
|
+
? 'Assistant'
|
|
442
|
+
: (msg.role === 'system'
|
|
443
|
+
? 'System Instructions'
|
|
444
|
+
: (msg.role === 'tool'
|
|
445
|
+
? `Tool Result (${msg.name || 'tool'})`
|
|
446
|
+
: 'Context')));
|
|
447
|
+
|
|
448
|
+
let text = '';
|
|
449
|
+
if (typeof msg.content === 'string') {
|
|
450
|
+
text = msg.content;
|
|
451
|
+
} else if (Array.isArray(msg.content)) {
|
|
452
|
+
text = msg.content.map((c: any) => {
|
|
453
|
+
if (typeof c === 'string') return c;
|
|
454
|
+
if (c?.text) return c.text;
|
|
455
|
+
if (c?.type === 'image_url' || c?.type === 'image') {
|
|
456
|
+
const url = c?.image_url?.url || '';
|
|
457
|
+
const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
|
|
458
|
+
return `[Visual Content: ${mime}]`;
|
|
459
|
+
}
|
|
460
|
+
return '';
|
|
461
|
+
}).filter(Boolean).join('\n');
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
465
|
+
for (const tc of msg.tool_calls) {
|
|
466
|
+
const fn = tc.function || {};
|
|
467
|
+
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
468
|
+
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (text.trim()) {
|
|
473
|
+
lines.push(`[${role}]\n${text.trim()}`);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return lines.join('\n\n');
|
|
477
|
+
}
|
|
478
|
+
|
|
96
479
|
formatConversation(messages: any[], tools: any[] = []): string {
|
|
97
480
|
const lines: string[] = [];
|
|
98
481
|
|
|
99
|
-
//
|
|
482
|
+
// Host capabilities must be learned from real tool results in this session.
|
|
100
483
|
lines.push(
|
|
101
484
|
'[System Instructions]\n' +
|
|
102
|
-
'You are
|
|
103
|
-
'
|
|
485
|
+
'You are the execution engine for Causyne Agent, operating inside the user\'s workspace. ' +
|
|
486
|
+
'Do not claim a tool action succeeded without evidence. Use Causyne tools for file changes, terminal commands, and browser actions. ' +
|
|
487
|
+
'When a command, browser action, or other external action is required, output an explicit tool call in this exact format:\n' +
|
|
104
488
|
'<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n' +
|
|
105
|
-
'Causyne Agent will execute the tool in its secure environment and return the results back to you
|
|
489
|
+
'Causyne Agent will execute the tool in its secure environment and return the results back to you.\n\n' +
|
|
490
|
+
'[Action Directive]\n' +
|
|
491
|
+
'1. When the user requests to create, build, code, fix, write, optimize, or implement anything, invoke the relevant file or command tools immediately.\n' +
|
|
492
|
+
'2. When the user requests to OPEN, LAUNCH, RUN, SERVE, or PLAY an application, project, or game:\n' +
|
|
493
|
+
' - If a background server is required (e.g. server.py, python -m http.server, npm run dev), start it using sysRunBg or a background command.\n' +
|
|
494
|
+
' - If the default port (e.g. 8080 or 3000) is already occupied or in use by another process, immediately use the next available port (e.g. 8081, 8082, 3001) rather than getting stuck in process-checking loops.\n' +
|
|
495
|
+
' - Immediately open the URL or project in the user\'s browser using desktop.open with {"target": "http://localhost:<port>"} or run the native open command.\n' +
|
|
496
|
+
' - Confirm the application is accessible only after a readiness check succeeds.\n' +
|
|
497
|
+
'3. NEVER reply with conversational pleasantries, canned greetings (e.g. "How can I help you today?"), or ask what the user wants when an instruction has already been provided.\n' +
|
|
498
|
+
'4. Create or edit files only when the current user request authorizes it.\n\n' +
|
|
499
|
+
'[Environment State & Idempotency Directive]\n' +
|
|
500
|
+
'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
|
|
501
|
+
'[Language & Communication Directive]\n' +
|
|
502
|
+
'Dynamically reflect and match the exact language used by the user in their prompt. If the user writes in English, you must respond strictly in English. Default to English for all responses and reasoning. Never default to Indonesian or send canned greetings in Indonesian.'
|
|
106
503
|
);
|
|
107
504
|
|
|
108
505
|
if (tools && tools.length > 0) {
|
|
@@ -118,7 +515,11 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
118
515
|
);
|
|
119
516
|
}
|
|
120
517
|
|
|
121
|
-
|
|
518
|
+
const seenToolOutputs = new Set<string>();
|
|
519
|
+
const seenAssistantCalls = new Set<string>();
|
|
520
|
+
for (let i = 0; i < messages.length; i++) {
|
|
521
|
+
const msg = messages[i];
|
|
522
|
+
const isRecent = messages.length - i <= 4;
|
|
122
523
|
const role = msg.role === 'user'
|
|
123
524
|
? 'User'
|
|
124
525
|
: (msg.role === 'assistant'
|
|
@@ -133,13 +534,36 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
133
534
|
if (typeof msg.content === 'string') {
|
|
134
535
|
text = msg.content;
|
|
135
536
|
} else if (Array.isArray(msg.content)) {
|
|
136
|
-
text = msg.content.map((c: any) =>
|
|
537
|
+
text = msg.content.map((c: any) => {
|
|
538
|
+
if (typeof c === 'string') return c;
|
|
539
|
+
if (c?.text) return c.text;
|
|
540
|
+
if (c?.type === 'image_url' || c?.type === 'image') {
|
|
541
|
+
const url = c?.image_url?.url || '';
|
|
542
|
+
const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
|
|
543
|
+
return `[Visual Content: ${mime}]`;
|
|
544
|
+
}
|
|
545
|
+
return '';
|
|
546
|
+
}).filter(Boolean).join('\n');
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// Compact duplicate identical tool outputs to prevent token ballooning
|
|
550
|
+
if (msg.role === 'tool' && text.trim()) {
|
|
551
|
+
const normalized = text.trim();
|
|
552
|
+
if (seenToolOutputs.has(normalized)) {
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
seenToolOutputs.add(normalized);
|
|
137
556
|
}
|
|
138
557
|
|
|
139
558
|
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
140
559
|
for (const tc of msg.tool_calls) {
|
|
141
560
|
const fn = tc.function || {};
|
|
142
561
|
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
562
|
+
const callSig = `${fn.name}:${fnArgs}`;
|
|
563
|
+
if (seenAssistantCalls.has(callSig)) {
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
seenAssistantCalls.add(callSig);
|
|
143
567
|
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
144
568
|
}
|
|
145
569
|
}
|
|
@@ -202,6 +626,34 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
202
626
|
}
|
|
203
627
|
}
|
|
204
628
|
|
|
629
|
+
// Unclosed tool_call recovery (when model generated large file content and closed turn)
|
|
630
|
+
if (calls.length === 0) {
|
|
631
|
+
const openIndex = text.lastIndexOf('<tool_call>');
|
|
632
|
+
if (openIndex !== -1 && text.indexOf('</tool_call>', openIndex) === -1) {
|
|
633
|
+
const partial = text.slice(openIndex + '<tool_call>'.length).trim();
|
|
634
|
+
for (const suffix of ['', '}', '}}', '}}}', '"}', '"}}', '"}}}', '"}]}}', '"]}}', '"]}}}']) {
|
|
635
|
+
try {
|
|
636
|
+
const parsed = JSON.parse(partial + suffix);
|
|
637
|
+
const name = parsed.name || parsed.tool || parsed.function?.name;
|
|
638
|
+
if (name) {
|
|
639
|
+
const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
|
|
640
|
+
calls.push({
|
|
641
|
+
id: `agy_call_${Date.now()}_0`,
|
|
642
|
+
type: 'function',
|
|
643
|
+
function: {
|
|
644
|
+
name,
|
|
645
|
+
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
646
|
+
}
|
|
647
|
+
});
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
} catch {
|
|
651
|
+
// try next candidate
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
205
657
|
return calls;
|
|
206
658
|
}
|
|
207
659
|
|
|
@@ -221,34 +673,86 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
221
673
|
}
|
|
222
674
|
|
|
223
675
|
async _executeOnce(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
|
|
224
|
-
const
|
|
676
|
+
const currentSessionKey = (options as any).conversationId || (options as any).taskId || null;
|
|
677
|
+
if (currentSessionKey && currentSessionKey !== this.lastTaskId) {
|
|
678
|
+
this.currentConversationId = null;
|
|
679
|
+
this.lastTaskId = currentSessionKey;
|
|
680
|
+
}
|
|
681
|
+
if (messages.length <= 1) {
|
|
682
|
+
this.currentConversationId = null;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
const useConversation = Boolean(this.currentConversationId);
|
|
686
|
+
const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
|
|
687
|
+
const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
|
|
688
|
+
const launchOnly = (options as any).taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
|
|
689
|
+
let promptText: string;
|
|
690
|
+
|
|
691
|
+
if (useConversation) {
|
|
692
|
+
let lastAssistantIndex = -1;
|
|
693
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
694
|
+
if (messages[i].role === 'assistant') {
|
|
695
|
+
lastAssistantIndex = i;
|
|
696
|
+
break;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
const deltaMessages = lastAssistantIndex >= 0 ? messages.slice(lastAssistantIndex + 1) : messages;
|
|
700
|
+
promptText = this.formatDelta(deltaMessages.length > 0 ? deltaMessages : [messages[messages.length - 1]]);
|
|
701
|
+
} else {
|
|
702
|
+
promptText = this.formatConversation(messages, options.tools);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// A resumed agy conversation retains its old instructions. Reassert the
|
|
706
|
+
// current turn's narrower scope on every call, including formatDelta turns.
|
|
707
|
+
if (launchOnly) {
|
|
708
|
+
promptText = '[Current request: open existing project only]\n' +
|
|
709
|
+
'Inspect the selected project, start an existing server in the background if needed, verify readiness, and open it. ' +
|
|
710
|
+
'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
|
|
711
|
+
'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
|
|
712
|
+
}
|
|
713
|
+
|
|
225
714
|
const modelSlug = resolveAgyModelId(this.model);
|
|
226
715
|
const effort = resolveAgyEffort(this.model);
|
|
227
716
|
|
|
228
717
|
// Standard high-performance non-blocking CLI invocation:
|
|
229
718
|
// 1. stream-json output for real-time responsiveness and non-buffering progress.
|
|
230
719
|
// 2. --disable-slash-commands prevents sluggish filesystem and customization scans.
|
|
231
|
-
// 3.
|
|
232
|
-
//
|
|
720
|
+
// 3. agy only treats stdin as a prompt in stream-json input mode. Plain text
|
|
721
|
+
// stdin without --print starts an interactive session and loses the task.
|
|
722
|
+
// Keep the prompt off the process command line by sending one user event.
|
|
723
|
+
// 4. --mode accept-edits lets agy create and edit workspace files in
|
|
724
|
+
// headless mode, where the default request-review policy cannot prompt
|
|
725
|
+
// and would auto-deny every write. --dangerously-skip-permissions must
|
|
726
|
+
// stay off: it would also grant shell commands and other host tools,
|
|
727
|
+
// bypassing Causyne. Native terminal/browser tools remain denied; those
|
|
728
|
+
// must go through Causyne XML tool calls.
|
|
729
|
+
// 5. Launch-only turns use a shorter limit because they should not spend
|
|
730
|
+
// several minutes generating code or holding a foreground server open.
|
|
731
|
+
// 6. --conversation links multi-turn steps to agy's local session memory to prevent re-reading files.
|
|
233
732
|
const args = [
|
|
733
|
+
'--mode',
|
|
734
|
+
launchOnly ? 'plan' : 'accept-edits',
|
|
735
|
+
'--input-format',
|
|
736
|
+
'stream-json',
|
|
234
737
|
'--output-format',
|
|
235
738
|
'stream-json',
|
|
236
739
|
'--disable-slash-commands',
|
|
237
740
|
'--print-timeout',
|
|
238
|
-
'
|
|
239
|
-
'--dangerously-skip-permissions',
|
|
741
|
+
launchOnly ? '90s' : this.printTimeout,
|
|
240
742
|
'--model',
|
|
241
743
|
modelSlug,
|
|
242
744
|
'--effort',
|
|
243
|
-
effort
|
|
244
|
-
'-p',
|
|
245
|
-
'-'
|
|
745
|
+
effort
|
|
246
746
|
];
|
|
247
747
|
|
|
748
|
+
if (useConversation && this.currentConversationId) {
|
|
749
|
+
args.push('--conversation', this.currentConversationId);
|
|
750
|
+
}
|
|
751
|
+
|
|
248
752
|
return new Promise<ChatResponse>((resolve, reject) => {
|
|
249
753
|
let isSettled = false;
|
|
250
754
|
const child = spawn(this.command, args, {
|
|
251
|
-
cwd: process.cwd(),
|
|
755
|
+
cwd: typeof (options as any).workspaceRoot === 'string' ? (options as any).workspaceRoot : process.cwd(),
|
|
252
756
|
env: process.env,
|
|
253
757
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
254
758
|
windowsHide: true
|
|
@@ -258,6 +762,16 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
258
762
|
let stderrBuffer = '';
|
|
259
763
|
let streamedResponse = '';
|
|
260
764
|
let finalResultObj: any = null;
|
|
765
|
+
let sawToolAfterLastText = false;
|
|
766
|
+
const nativeActions: ChatResponseAction[] = [];
|
|
767
|
+
const attemptedNativeTools: {
|
|
768
|
+
name: string;
|
|
769
|
+
parameters: Record<string, any>;
|
|
770
|
+
status: 'running' | 'completed' | 'failed';
|
|
771
|
+
error?: string | undefined;
|
|
772
|
+
detail?: string | undefined;
|
|
773
|
+
}[] = [];
|
|
774
|
+
let childClosed = false;
|
|
261
775
|
|
|
262
776
|
const cleanup = () => {
|
|
263
777
|
if (options.signal) {
|
|
@@ -283,12 +797,14 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
283
797
|
try {
|
|
284
798
|
child.kill('SIGTERM');
|
|
285
799
|
setTimeout(() => {
|
|
286
|
-
if (!
|
|
800
|
+
if (!childClosed) child.kill('SIGKILL');
|
|
287
801
|
}, 1000).unref();
|
|
288
802
|
} catch {
|
|
289
803
|
// ignore kill errors
|
|
290
804
|
}
|
|
291
|
-
|
|
805
|
+
const abortErr = new Error('Turn aborted by user or timeout.');
|
|
806
|
+
abortErr.name = 'AbortError';
|
|
807
|
+
safeReject(abortErr);
|
|
292
808
|
};
|
|
293
809
|
|
|
294
810
|
if (options.signal) {
|
|
@@ -301,7 +817,8 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
301
817
|
|
|
302
818
|
// Feed prompt directly into child process stdin, then close stdin
|
|
303
819
|
try {
|
|
304
|
-
child.stdin.
|
|
820
|
+
child.stdin.on('error', () => {});
|
|
821
|
+
child.stdin.write(JSON.stringify({ event: 'user', message: { content: promptText } }) + '\n', 'utf8');
|
|
305
822
|
child.stdin.end();
|
|
306
823
|
} catch (err: any) {
|
|
307
824
|
safeReject(new Error(`Failed to pipe prompt to Antigravity CLI: ${err.message}`));
|
|
@@ -321,16 +838,83 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
321
838
|
if (!trimmed) continue;
|
|
322
839
|
try {
|
|
323
840
|
const event = JSON.parse(trimmed);
|
|
324
|
-
if (event.event === '
|
|
841
|
+
if (event.event === 'init') {
|
|
842
|
+
if (event.conversation_id) {
|
|
843
|
+
this.currentConversationId = event.conversation_id;
|
|
844
|
+
}
|
|
845
|
+
} else if (event.event === 'step_update') {
|
|
325
846
|
const stepUpdate = event.step_update;
|
|
326
847
|
const delta = stepUpdate?.text_delta;
|
|
327
848
|
const stepType = stepUpdate?.step_type;
|
|
849
|
+
if (stepType === 'tool') {
|
|
850
|
+
const state = stepUpdate?.state;
|
|
851
|
+
const toolInfo = stepUpdate?.tool_info || {};
|
|
852
|
+
const name = stepUpdate?.tool_name || toolInfo?.name;
|
|
853
|
+
const status = state === 'DONE'
|
|
854
|
+
? 'completed'
|
|
855
|
+
: (state === 'ERROR' ? 'failed' : 'running');
|
|
856
|
+
const rawParams = (toolInfo && typeof toolInfo === 'object' && toolInfo.parameters) ||
|
|
857
|
+
(stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
|
|
858
|
+
(toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
|
|
859
|
+
{};
|
|
860
|
+
|
|
861
|
+
if (name) {
|
|
862
|
+
const existingAttempt = attemptedNativeTools.find(a => a.name === name && a.status === 'running');
|
|
863
|
+
if (existingAttempt) {
|
|
864
|
+
existingAttempt.status = status;
|
|
865
|
+
if (rawParams && Object.keys(rawParams).length > 0) {
|
|
866
|
+
existingAttempt.parameters = { ...existingAttempt.parameters, ...rawParams };
|
|
867
|
+
}
|
|
868
|
+
if (toolInfo?.error?.message) existingAttempt.error = toolInfo.error.message;
|
|
869
|
+
} else {
|
|
870
|
+
attemptedNativeTools.push({
|
|
871
|
+
name,
|
|
872
|
+
parameters: { ...rawParams },
|
|
873
|
+
status,
|
|
874
|
+
error: toolInfo?.error?.message,
|
|
875
|
+
detail: describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams })
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
if (name && (state === 'ACTIVE' || state === 'DONE' || state === 'ERROR')) {
|
|
881
|
+
sawToolAfterLastText = true;
|
|
882
|
+
const detail = describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams });
|
|
883
|
+
const action: ChatResponseAction = {
|
|
884
|
+
name,
|
|
885
|
+
status,
|
|
886
|
+
...(detail ? { detail } : {})
|
|
887
|
+
};
|
|
888
|
+
if (status !== 'running') {
|
|
889
|
+
const existing = nativeActions.find(a => a.name === action.name && a.detail === action.detail);
|
|
890
|
+
if (existing) existing.status = status;
|
|
891
|
+
else nativeActions.push(action);
|
|
892
|
+
}
|
|
893
|
+
// Stream the start; completion is reported only after the
|
|
894
|
+
// final result has checked for denied actions.
|
|
895
|
+
if (status === 'running' && typeof options.onNativeAction === 'function') {
|
|
896
|
+
const parameters = rawParams && typeof rawParams === 'object'
|
|
897
|
+
? rawParams as Record<string, unknown>
|
|
898
|
+
: {};
|
|
899
|
+
options.onNativeAction({ ...action, parameters });
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
328
903
|
if (delta && typeof delta === 'string') {
|
|
329
904
|
if (stepType === 'thought' || stepType === 'agent_thought') {
|
|
330
905
|
if (typeof options.onReasoningChunk === 'function') {
|
|
331
906
|
options.onReasoningChunk(delta);
|
|
332
907
|
}
|
|
333
908
|
} else {
|
|
909
|
+
if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(delta)) {
|
|
910
|
+
streamedResponse += '\n';
|
|
911
|
+
if (typeof options.onChunk === 'function') {
|
|
912
|
+
options.onChunk('\n');
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
if (delta.trim().length > 0) {
|
|
916
|
+
sawToolAfterLastText = false;
|
|
917
|
+
}
|
|
334
918
|
streamedResponse += delta;
|
|
335
919
|
if (typeof options.onChunk === 'function') {
|
|
336
920
|
options.onChunk(delta);
|
|
@@ -339,7 +923,11 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
339
923
|
}
|
|
340
924
|
} else if (event.event === 'result') {
|
|
341
925
|
finalResultObj = event.result;
|
|
926
|
+
if (event.result?.conversation_id) {
|
|
927
|
+
this.currentConversationId = event.result.conversation_id;
|
|
928
|
+
}
|
|
342
929
|
} else if (event.status === 'ERROR') {
|
|
930
|
+
if (useConversation) this.currentConversationId = null;
|
|
343
931
|
safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
|
|
344
932
|
return;
|
|
345
933
|
}
|
|
@@ -355,17 +943,23 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
355
943
|
});
|
|
356
944
|
|
|
357
945
|
child.on('error', (err: Error) => {
|
|
946
|
+
if (useConversation) this.currentConversationId = null;
|
|
358
947
|
safeReject(new Error(`Antigravity Agent (agy) spawn error: ${err.message}. Make sure Antigravity CLI is installed.`));
|
|
359
948
|
});
|
|
360
949
|
|
|
361
950
|
child.on('close', (code: number | null) => {
|
|
951
|
+
childClosed = true;
|
|
362
952
|
// Process any remaining bytes in stdoutBuffer
|
|
363
953
|
if (stdoutBuffer.trim()) {
|
|
364
954
|
try {
|
|
365
955
|
const event = JSON.parse(stdoutBuffer.trim());
|
|
366
956
|
if (event.event === 'result') {
|
|
367
957
|
finalResultObj = event.result;
|
|
958
|
+
if (event.result?.conversation_id) {
|
|
959
|
+
this.currentConversationId = event.result.conversation_id;
|
|
960
|
+
}
|
|
368
961
|
} else if (event.status === 'ERROR') {
|
|
962
|
+
if (useConversation) this.currentConversationId = null;
|
|
369
963
|
safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
|
|
370
964
|
return;
|
|
371
965
|
}
|
|
@@ -374,8 +968,9 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
374
968
|
}
|
|
375
969
|
}
|
|
376
970
|
|
|
377
|
-
if (code !== 0
|
|
378
|
-
|
|
971
|
+
if (code !== 0 || finalResultObj?.status === 'ERROR') {
|
|
972
|
+
if (useConversation) this.currentConversationId = null;
|
|
973
|
+
const errDetail = finalResultObj?.error || stderrBuffer.trim() || `exit code ${code}`;
|
|
379
974
|
safeReject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
|
|
380
975
|
return;
|
|
381
976
|
}
|
|
@@ -395,20 +990,83 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
395
990
|
// Strip tool call tags from prose so raw XML does not leak into chat display
|
|
396
991
|
let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
|
|
397
992
|
|
|
398
|
-
|
|
399
|
-
|
|
993
|
+
const deniedActions: any[] = Array.isArray(finalResultObj?.denied_actions)
|
|
994
|
+
? finalResultObj.denied_actions : [];
|
|
995
|
+
const normalizeAction = (value: unknown): string =>
|
|
996
|
+
String(value || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
997
|
+
const deniedNames = new Set(deniedActions.flatMap(action =>
|
|
998
|
+
[normalizeAction(action?.action), normalizeAction(action?.display_name)]).filter(Boolean));
|
|
999
|
+
for (const action of nativeActions) {
|
|
1000
|
+
if (deniedNames.has(normalizeAction(action.name))) action.status = 'failed';
|
|
1001
|
+
if (typeof options.onNativeAction === 'function') {
|
|
1002
|
+
const attempt = [...attemptedNativeTools].reverse().find(candidate =>
|
|
1003
|
+
normalizeAction(candidate.name) === normalizeAction(action.name));
|
|
1004
|
+
options.onNativeAction({ ...action, parameters: attempt?.parameters || {} });
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
if (deniedActions.length > 0) {
|
|
1009
|
+
const unmapped: string[] = [];
|
|
1010
|
+
for (const denied of deniedActions) {
|
|
1011
|
+
const name = String(denied?.action || denied?.display_name || 'unknown');
|
|
1012
|
+
const attempt = [...attemptedNativeTools].reverse().find(candidate =>
|
|
1013
|
+
normalizeAction(candidate.name) === normalizeAction(name)
|
|
1014
|
+
|| normalizeAction(candidate.name) === normalizeAction(denied?.display_name));
|
|
1015
|
+
const parameters = {
|
|
1016
|
+
...(attempt?.parameters || {}),
|
|
1017
|
+
...(denied?.parameters || {}),
|
|
1018
|
+
...(attempt?.detail ? { detail: attempt.detail } : {})
|
|
1019
|
+
};
|
|
1020
|
+
const mapped = mapNativeToolToCausyne(attempt?.name || String(denied?.display_name || name), parameters, toolCalls.length);
|
|
1021
|
+
if (!mapped) {
|
|
1022
|
+
unmapped.push(String(denied?.display_name || name));
|
|
1023
|
+
continue;
|
|
1024
|
+
}
|
|
1025
|
+
if (!toolCalls.some(call => call.function.name === mapped.function.name
|
|
1026
|
+
&& call.function.arguments === mapped.function.arguments)) {
|
|
1027
|
+
toolCalls.push(mapped);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
if (unmapped.length > 0) {
|
|
1031
|
+
const error = new Error(`Antigravity could not perform: ${unmapped.join(', ')}. The denied action had no safe Causyne tool mapping.`) as Error & { code: string };
|
|
1032
|
+
error.code = 'AGY_NATIVE_ACTION_DENIED';
|
|
1033
|
+
safeReject(error);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
// Any prose produced alongside a denied action may claim work that
|
|
1037
|
+
// did not occur. Wait for the mapped Causyne tool result instead.
|
|
1038
|
+
content = '';
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
const completedNativeActions = nativeActions.filter((a: ChatResponseAction) => a.status === 'completed');
|
|
1042
|
+
|
|
1043
|
+
if (!content && completedNativeActions.length > 0) {
|
|
1044
|
+
content = `Antigravity completed: ${completedNativeActions
|
|
1045
|
+
.map((a: ChatResponseAction) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
|
|
1046
|
+
.join(', ')}`;
|
|
400
1047
|
}
|
|
401
1048
|
|
|
402
1049
|
if (!content && toolCalls.length === 0) {
|
|
403
|
-
|
|
1050
|
+
const detail = stderrBuffer.trim();
|
|
1051
|
+
safeReject(new Error(detail
|
|
1052
|
+
? `Antigravity returned no response: ${detail}`
|
|
1053
|
+
: 'Antigravity returned no response.'));
|
|
1054
|
+
return;
|
|
404
1055
|
}
|
|
405
1056
|
|
|
1057
|
+
const timedOutMidTurn = /print timeout after .* with turn in progress|returning partial output/i.test(stderrBuffer);
|
|
1058
|
+
const finalResponseText = typeof finalResultObj?.response === 'string' ? finalResultObj.response.trim() : '';
|
|
1059
|
+
const endedAfterToolWithoutFinalResponse =
|
|
1060
|
+
sawToolAfterLastText && !finalResponseText && deniedActions.length === 0 && toolCalls.length === 0;
|
|
1061
|
+
const missingResultEvent =
|
|
1062
|
+
finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
|
|
1063
|
+
|
|
406
1064
|
const promptTokens = Number(finalResultObj?.usage?.input_tokens) || Math.ceil(promptText.length / 4);
|
|
407
1065
|
const completionTokens = Number(finalResultObj?.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
|
|
408
1066
|
const thinkingTokens = Number(finalResultObj?.usage?.thinking_tokens) || 0;
|
|
409
1067
|
|
|
410
1068
|
const response: ChatResponse = {
|
|
411
|
-
content
|
|
1069
|
+
content,
|
|
412
1070
|
usage: {
|
|
413
1071
|
promptTokens,
|
|
414
1072
|
completionTokens: completionTokens + thinkingTokens,
|
|
@@ -424,19 +1082,33 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
424
1082
|
response.toolCalls = toolCalls;
|
|
425
1083
|
}
|
|
426
1084
|
|
|
1085
|
+
if (nativeActions.length > 0) {
|
|
1086
|
+
response.externalActions = nativeActions.filter((a: ChatResponseAction) => a.status !== 'running');
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
if (timedOutMidTurn || endedAfterToolWithoutFinalResponse || missingResultEvent) {
|
|
1090
|
+
response.incompleteTurn = true;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
427
1093
|
safeResolve(response);
|
|
428
1094
|
});
|
|
429
1095
|
});
|
|
430
1096
|
}
|
|
431
1097
|
|
|
432
1098
|
override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
|
|
433
|
-
const maxRetries = options.maxRetries ?? 2;
|
|
1099
|
+
const maxRetries = options.maxRetries ?? ((options as any).taskIntent === 'launch' ? 1 : 2);
|
|
434
1100
|
let attempt = 0;
|
|
435
1101
|
while (attempt <= maxRetries) {
|
|
1102
|
+
const hadConversation = Boolean(this.currentConversationId);
|
|
436
1103
|
try {
|
|
437
1104
|
return await this._executeOnce(messages, options);
|
|
438
1105
|
} catch (err: any) {
|
|
439
|
-
if (
|
|
1106
|
+
if (options.signal?.aborted || err?.name === 'AbortError') {
|
|
1107
|
+
throw err;
|
|
1108
|
+
}
|
|
1109
|
+
const canRetryResetConversation =
|
|
1110
|
+
hadConversation && !this.currentConversationId && (err as any)?.code !== 'AGY_NATIVE_ACTION_DENIED';
|
|
1111
|
+
if (attempt < maxRetries && (this._isTransientError(err.message) || canRetryResetConversation)) {
|
|
440
1112
|
attempt++;
|
|
441
1113
|
const delay = attempt * 1200;
|
|
442
1114
|
await new Promise(r => setTimeout(r, delay));
|