@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,14 +1,14 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
4
5
|
import { LLMProvider } from './base.js';
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* resolve here rather than failing at the provider.
|
|
7
|
+
* Baseline fallback models for instant offline availability.
|
|
8
|
+
* Live models are autodetected dynamically from `agy models`
|
|
9
|
+
* and cached in ~/.causyne/models_cache.json.
|
|
10
10
|
*/
|
|
11
|
-
export const
|
|
11
|
+
export const BASELINE_ANTIGRAVITY_MODELS = {
|
|
12
12
|
'Gemini 3.8 Flash (Low)': 'gemini-3.8-flash-low',
|
|
13
13
|
'Gemini 3.8 Flash (Medium)': 'gemini-3.8-flash-medium',
|
|
14
14
|
'Gemini 3.8 Flash (High)': 'gemini-3.8-flash-high',
|
|
@@ -23,13 +23,100 @@ export const ANTIGRAVITY_MODEL_IDS = {
|
|
|
23
23
|
'Claude Opus 5.5 (High)': 'claude-opus-5-5-high',
|
|
24
24
|
'GPT-OSS 120B (Medium)': 'gpt-oss-120b-medium'
|
|
25
25
|
};
|
|
26
|
+
export const ANTIGRAVITY_MODEL_IDS = {
|
|
27
|
+
...BASELINE_ANTIGRAVITY_MODELS
|
|
28
|
+
};
|
|
26
29
|
export const ANTIGRAVITY_LABEL_BY_ID = Object.fromEntries(Object.entries(ANTIGRAVITY_MODEL_IDS).map(([label, id]) => [id, label]));
|
|
27
30
|
export const ANTIGRAVITY_MODELS = Object.keys(ANTIGRAVITY_MODEL_IDS);
|
|
31
|
+
export function registerAntigravityModel(slug, label) {
|
|
32
|
+
if (!slug || typeof slug !== 'string')
|
|
33
|
+
return;
|
|
34
|
+
const cleanSlug = slug.trim();
|
|
35
|
+
const cleanLabel = (label && typeof label === 'string' && label.trim()) || cleanSlug;
|
|
36
|
+
ANTIGRAVITY_MODEL_IDS[cleanLabel] = cleanSlug;
|
|
37
|
+
ANTIGRAVITY_MODEL_IDS[cleanSlug] = cleanSlug;
|
|
38
|
+
ANTIGRAVITY_LABEL_BY_ID[cleanSlug] = cleanLabel;
|
|
39
|
+
if (!ANTIGRAVITY_MODELS.includes(cleanLabel)) {
|
|
40
|
+
ANTIGRAVITY_MODELS.push(cleanLabel);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function parseAgyModelsOutput(stdout) {
|
|
44
|
+
const result = [];
|
|
45
|
+
if (!stdout || typeof stdout !== 'string')
|
|
46
|
+
return result;
|
|
47
|
+
const lines = stdout.replace(/\r/g, '\n').split(/\n+/);
|
|
48
|
+
for (const rawLine of lines) {
|
|
49
|
+
const line = rawLine.replace(/\u001b\[[0-9;]*[A-Za-z]/g, '').trim();
|
|
50
|
+
if (!line)
|
|
51
|
+
continue;
|
|
52
|
+
if (/^(fetching|loading|no models|error)/i.test(line))
|
|
53
|
+
continue;
|
|
54
|
+
if (line.endsWith('…') || line.endsWith('...'))
|
|
55
|
+
continue;
|
|
56
|
+
const cleanLine = line.replace(/^[^a-zA-Z0-9_-]+/, '');
|
|
57
|
+
const match = cleanLine.match(/^([a-z0-9_.-]+)(?:\s+(.+))?$/i);
|
|
58
|
+
if (!match)
|
|
59
|
+
continue;
|
|
60
|
+
const id = match[1].trim();
|
|
61
|
+
const label = (match[2] && match[2].trim()) || id;
|
|
62
|
+
result.push({ id, label });
|
|
63
|
+
registerAntigravityModel(id, label);
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
function hydrateModelsFromDiskCache() {
|
|
68
|
+
try {
|
|
69
|
+
const home = process.env.HOME || process.env.USERPROFILE || '';
|
|
70
|
+
const cacheFile = path.join(home, '.causyne', 'models_cache.json');
|
|
71
|
+
if (!fs.existsSync(cacheFile))
|
|
72
|
+
return;
|
|
73
|
+
const content = fs.readFileSync(cacheFile, 'utf8');
|
|
74
|
+
const parsed = JSON.parse(content);
|
|
75
|
+
const agyModels = parsed?.providers?.antigravity?.models;
|
|
76
|
+
if (Array.isArray(agyModels)) {
|
|
77
|
+
for (const item of agyModels) {
|
|
78
|
+
if (typeof item === 'string' && item.trim()) {
|
|
79
|
+
const trimmed = item.trim();
|
|
80
|
+
if (!ANTIGRAVITY_MODEL_IDS[trimmed]) {
|
|
81
|
+
registerAntigravityModel(trimmed, trimmed);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Ignore cache read errors
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
hydrateModelsFromDiskCache();
|
|
28
92
|
export function resolveAgyModelId(model) {
|
|
29
93
|
if (typeof model !== 'string')
|
|
30
94
|
return '';
|
|
31
95
|
const trimmed = model.trim();
|
|
32
|
-
|
|
96
|
+
if (!trimmed)
|
|
97
|
+
return '';
|
|
98
|
+
if (ANTIGRAVITY_MODEL_IDS[trimmed]) {
|
|
99
|
+
return ANTIGRAVITY_MODEL_IDS[trimmed];
|
|
100
|
+
}
|
|
101
|
+
const lower = trimmed.toLowerCase();
|
|
102
|
+
for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
|
|
103
|
+
if (key.toLowerCase() === lower || slug.toLowerCase() === lower) {
|
|
104
|
+
return slug;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const effort = resolveAgyEffort(trimmed);
|
|
108
|
+
const candidateWithEffort = `${lower}-${effort}`;
|
|
109
|
+
for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
|
|
110
|
+
if (slug.toLowerCase() === candidateWithEffort || key.toLowerCase() === candidateWithEffort) {
|
|
111
|
+
return slug;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
|
|
115
|
+
if (slug.toLowerCase().startsWith(lower) || key.toLowerCase().startsWith(lower)) {
|
|
116
|
+
return slug;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return trimmed;
|
|
33
120
|
}
|
|
34
121
|
export function resolveAgyEffort(model) {
|
|
35
122
|
if (typeof model !== 'string')
|
|
@@ -81,23 +168,315 @@ export function resolveAgyBinary() {
|
|
|
81
168
|
}
|
|
82
169
|
return 'agy';
|
|
83
170
|
}
|
|
171
|
+
function describeNativeAction(toolInfo) {
|
|
172
|
+
const parameters = toolInfo && typeof toolInfo === 'object' ? toolInfo.parameters : null;
|
|
173
|
+
if (parameters && typeof parameters === 'object') {
|
|
174
|
+
for (const key of ['Path', 'path', 'file_path', 'TargetFile', 'target_file', 'CommandLine', 'command', 'url']) {
|
|
175
|
+
const value = parameters[key];
|
|
176
|
+
if (typeof value === 'string' && value.trim())
|
|
177
|
+
return value.trim();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
for (const key of ['toolAction', 'tool_action', 'toolSummary', 'tool_summary']) {
|
|
181
|
+
const value = toolInfo && toolInfo[key];
|
|
182
|
+
if (typeof value === 'string' && value.trim())
|
|
183
|
+
return value.trim();
|
|
184
|
+
}
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
export function mapNativeToolToCausyne(name, rawParams, index) {
|
|
188
|
+
if (!name || typeof name !== 'string')
|
|
189
|
+
return null;
|
|
190
|
+
const lowerName = name.toLowerCase().replace(/[_-]/g, '');
|
|
191
|
+
const params = rawParams && typeof rawParams === 'object' ? rawParams : {};
|
|
192
|
+
if (lowerName === 'runcommand' || lowerName === 'command' || lowerName === 'sysrun' || lowerName === 'terminal' || lowerName === 'bash' || lowerName === 'shell') {
|
|
193
|
+
const rawCmd = params.CommandLine ?? params.command ?? params.cmd ?? params.input ?? params.detail ?? '';
|
|
194
|
+
let cmd = typeof rawCmd === 'string' ? rawCmd.trim() : '';
|
|
195
|
+
if (!cmd && typeof params.parameters === 'object' && params.parameters) {
|
|
196
|
+
cmd = String(params.parameters.CommandLine || params.parameters.command || params.parameters.cmd || '').trim();
|
|
197
|
+
}
|
|
198
|
+
if (cmd) {
|
|
199
|
+
const isDaemon = Boolean(params.IsDaemon ?? params.isDaemon ?? params.daemon);
|
|
200
|
+
const cwd = params.Cwd ?? params.cwd;
|
|
201
|
+
if (isDaemon) {
|
|
202
|
+
const bgArgs = { command: cmd, label: 'daemon' };
|
|
203
|
+
if (typeof cwd === 'string' && cwd.trim())
|
|
204
|
+
bgArgs.cwd = cwd.trim();
|
|
205
|
+
return {
|
|
206
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
207
|
+
type: 'function',
|
|
208
|
+
function: {
|
|
209
|
+
name: 'sysRunBg',
|
|
210
|
+
arguments: JSON.stringify(bgArgs)
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
const args = { command: cmd };
|
|
215
|
+
if (typeof cwd === 'string' && cwd.trim())
|
|
216
|
+
args.cwd = cwd.trim();
|
|
217
|
+
return {
|
|
218
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
219
|
+
type: 'function',
|
|
220
|
+
function: {
|
|
221
|
+
name: 'sysRun',
|
|
222
|
+
arguments: JSON.stringify(args)
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (lowerName === 'viewfile' || lowerName === 'readfile' || lowerName === 'read' || lowerName === 'view' || lowerName === 'fsread') {
|
|
228
|
+
const filePath = params.AbsolutePath ?? params.path ?? params.file_path ?? params.TargetFile ?? '';
|
|
229
|
+
if (typeof filePath === 'string' && filePath.trim()) {
|
|
230
|
+
return {
|
|
231
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
232
|
+
type: 'function',
|
|
233
|
+
function: {
|
|
234
|
+
name: 'fs_read',
|
|
235
|
+
arguments: JSON.stringify({ path: filePath.trim() })
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (lowerName === 'listdir' || lowerName === 'fslist' || lowerName === 'list') {
|
|
241
|
+
const dirPath = params.DirectoryPath ?? params.path ?? '.';
|
|
242
|
+
return {
|
|
243
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
244
|
+
type: 'function',
|
|
245
|
+
function: {
|
|
246
|
+
name: 'fs_list',
|
|
247
|
+
arguments: JSON.stringify({ path: String(dirPath).trim() || '.' })
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
if (lowerName === 'grepsearch' || lowerName === 'searchworkspace') {
|
|
252
|
+
const query = params.Query ?? params.query ?? '';
|
|
253
|
+
if (typeof query === 'string' && query.trim()) {
|
|
254
|
+
return {
|
|
255
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
256
|
+
type: 'function',
|
|
257
|
+
function: {
|
|
258
|
+
name: 'workspace_search',
|
|
259
|
+
arguments: JSON.stringify({
|
|
260
|
+
query: query.trim(),
|
|
261
|
+
path: params.SearchPath ?? params.path ?? '.'
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (lowerName === 'writetofile' || lowerName === 'fswrite') {
|
|
268
|
+
const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
|
|
269
|
+
const content = params.CodeContent ?? params.content ?? '';
|
|
270
|
+
if (typeof filePath === 'string' && filePath.trim()) {
|
|
271
|
+
return {
|
|
272
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
273
|
+
type: 'function',
|
|
274
|
+
function: {
|
|
275
|
+
name: 'fs_write',
|
|
276
|
+
arguments: JSON.stringify({ path: filePath.trim(), content: String(content) })
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (lowerName === 'replacefilecontent' || lowerName === 'fsedit') {
|
|
282
|
+
const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
|
|
283
|
+
const oldText = params.TargetContent ?? params.oldText ?? '';
|
|
284
|
+
const newText = params.ReplacementContent ?? params.newText ?? '';
|
|
285
|
+
if (typeof filePath === 'string' && filePath.trim()) {
|
|
286
|
+
return {
|
|
287
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
288
|
+
type: 'function',
|
|
289
|
+
function: {
|
|
290
|
+
name: 'fs_edit',
|
|
291
|
+
arguments: JSON.stringify({ path: filePath.trim(), oldText: String(oldText), newText: String(newText) })
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (lowerName === 'openbrowserurl') {
|
|
297
|
+
const url = params.Url ?? params.url ?? '';
|
|
298
|
+
if (typeof url === 'string' && url.trim()) {
|
|
299
|
+
return {
|
|
300
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
301
|
+
type: 'function',
|
|
302
|
+
function: {
|
|
303
|
+
name: 'desktop.open',
|
|
304
|
+
arguments: JSON.stringify({ target: url.trim() })
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (lowerName === 'readurlcontent') {
|
|
310
|
+
const url = params.Url ?? params.url ?? '';
|
|
311
|
+
if (typeof url === 'string' && url.trim()) {
|
|
312
|
+
return {
|
|
313
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
314
|
+
type: 'function',
|
|
315
|
+
function: {
|
|
316
|
+
name: 'web_fetch',
|
|
317
|
+
arguments: JSON.stringify({ url: url.trim() })
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
if (lowerName === 'searchweb') {
|
|
323
|
+
const query = params.query ?? params.Query ?? '';
|
|
324
|
+
if (typeof query === 'string' && query.trim()) {
|
|
325
|
+
return {
|
|
326
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
327
|
+
type: 'function',
|
|
328
|
+
function: {
|
|
329
|
+
name: 'web_search',
|
|
330
|
+
arguments: JSON.stringify({ query: query.trim() })
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (lowerName === 'multireplacefilecontent' || lowerName === 'multireplace') {
|
|
336
|
+
const filePath = params.TargetFile ?? params.path ?? params.file_path ?? '';
|
|
337
|
+
const rawChunks = Array.isArray(params.ReplacementChunks) ? params.ReplacementChunks : [];
|
|
338
|
+
const edits = rawChunks.map((chunk) => ({
|
|
339
|
+
old_string: String(chunk.TargetContent ?? chunk.old_string ?? ''),
|
|
340
|
+
new_string: String(chunk.ReplacementContent ?? chunk.new_string ?? '')
|
|
341
|
+
})).filter((e) => e.old_string);
|
|
342
|
+
if (typeof filePath === 'string' && filePath.trim() && edits.length > 0) {
|
|
343
|
+
return {
|
|
344
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
345
|
+
type: 'function',
|
|
346
|
+
function: {
|
|
347
|
+
name: 'MultiEdit',
|
|
348
|
+
arguments: JSON.stringify({ file_path: filePath.trim(), edits })
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (lowerName === 'browsersubagent' || lowerName === 'browseragent') {
|
|
354
|
+
const textToSearch = [
|
|
355
|
+
params.Url, params.url, params.Task, params.task, params.TaskName, params.taskName, params.TaskSummary
|
|
356
|
+
].filter(Boolean).join(' ');
|
|
357
|
+
const urlMatch = textToSearch.match(/https?:\/\/[^\s'")]+/i) || textToSearch.match(/localhost:\d+[^\s'")]*/i);
|
|
358
|
+
if (urlMatch) {
|
|
359
|
+
let targetUrl = urlMatch[0];
|
|
360
|
+
if (!targetUrl.startsWith('http'))
|
|
361
|
+
targetUrl = `http://${targetUrl}`;
|
|
362
|
+
return {
|
|
363
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
364
|
+
type: 'function',
|
|
365
|
+
function: {
|
|
366
|
+
name: 'desktop.open',
|
|
367
|
+
arguments: JSON.stringify({ target: targetUrl })
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (lowerName === 'managetask') {
|
|
373
|
+
const action = String(params.Action ?? params.action ?? '').toLowerCase();
|
|
374
|
+
if (action === 'list') {
|
|
375
|
+
return {
|
|
376
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
377
|
+
type: 'function',
|
|
378
|
+
function: {
|
|
379
|
+
name: 'process_list',
|
|
380
|
+
arguments: JSON.stringify({})
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
if (action === 'kill') {
|
|
385
|
+
const pid = Number(params.TaskId ?? params.taskId ?? params.pid);
|
|
386
|
+
if (!Number.isNaN(pid) && pid > 0) {
|
|
387
|
+
return {
|
|
388
|
+
id: `agy_native_${Date.now()}_${index}`,
|
|
389
|
+
type: 'function',
|
|
390
|
+
function: {
|
|
391
|
+
name: 'proc_term',
|
|
392
|
+
arguments: JSON.stringify({ pid })
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
84
400
|
export class AntigravityProvider extends LLMProvider {
|
|
85
401
|
command;
|
|
402
|
+
printTimeout;
|
|
403
|
+
currentConversationId = null;
|
|
404
|
+
lastTaskId = null;
|
|
86
405
|
constructor(config = {}) {
|
|
87
406
|
super(config);
|
|
88
407
|
this.model = config.model || 'Gemini 3.8 Flash (Low)';
|
|
89
408
|
this.command = config.command || resolveAgyBinary();
|
|
90
|
-
this.
|
|
409
|
+
this.printTimeout = typeof config.printTimeout === 'string' && config.printTimeout.trim()
|
|
410
|
+
? config.printTimeout.trim()
|
|
411
|
+
: '1800s';
|
|
412
|
+
this.visionModels = ['*'];
|
|
91
413
|
this.audioModels = [];
|
|
92
414
|
}
|
|
415
|
+
formatDelta(messages) {
|
|
416
|
+
const lines = [];
|
|
417
|
+
for (const msg of messages) {
|
|
418
|
+
const role = msg.role === 'user'
|
|
419
|
+
? 'User'
|
|
420
|
+
: (msg.role === 'assistant'
|
|
421
|
+
? 'Assistant'
|
|
422
|
+
: (msg.role === 'system'
|
|
423
|
+
? 'System Instructions'
|
|
424
|
+
: (msg.role === 'tool'
|
|
425
|
+
? `Tool Result (${msg.name || 'tool'})`
|
|
426
|
+
: 'Context')));
|
|
427
|
+
let text = '';
|
|
428
|
+
if (typeof msg.content === 'string') {
|
|
429
|
+
text = msg.content;
|
|
430
|
+
}
|
|
431
|
+
else if (Array.isArray(msg.content)) {
|
|
432
|
+
text = msg.content.map((c) => {
|
|
433
|
+
if (typeof c === 'string')
|
|
434
|
+
return c;
|
|
435
|
+
if (c?.text)
|
|
436
|
+
return c.text;
|
|
437
|
+
if (c?.type === 'image_url' || c?.type === 'image') {
|
|
438
|
+
const url = c?.image_url?.url || '';
|
|
439
|
+
const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
|
|
440
|
+
return `[Visual Content: ${mime}]`;
|
|
441
|
+
}
|
|
442
|
+
return '';
|
|
443
|
+
}).filter(Boolean).join('\n');
|
|
444
|
+
}
|
|
445
|
+
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
446
|
+
for (const tc of msg.tool_calls) {
|
|
447
|
+
const fn = tc.function || {};
|
|
448
|
+
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
449
|
+
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (text.trim()) {
|
|
453
|
+
lines.push(`[${role}]\n${text.trim()}`);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return lines.join('\n\n');
|
|
457
|
+
}
|
|
93
458
|
formatConversation(messages, tools = []) {
|
|
94
459
|
const lines = [];
|
|
95
|
-
//
|
|
460
|
+
// Host capabilities must be learned from real tool results in this session.
|
|
96
461
|
lines.push('[System Instructions]\n' +
|
|
97
|
-
'You are
|
|
98
|
-
'
|
|
462
|
+
'You are the execution engine for Causyne Agent, operating inside the user\'s workspace. ' +
|
|
463
|
+
'Do not claim a tool action succeeded without evidence. Use Causyne tools for file changes, terminal commands, and browser actions. ' +
|
|
464
|
+
'When a command, browser action, or other external action is required, output an explicit tool call in this exact format:\n' +
|
|
99
465
|
'<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n' +
|
|
100
|
-
'Causyne Agent will execute the tool in its secure environment and return the results back to you
|
|
466
|
+
'Causyne Agent will execute the tool in its secure environment and return the results back to you.\n\n' +
|
|
467
|
+
'[Action Directive]\n' +
|
|
468
|
+
'1. When the user requests to create, build, code, fix, write, optimize, or implement anything, invoke the relevant file or command tools immediately.\n' +
|
|
469
|
+
'2. When the user requests to OPEN, LAUNCH, RUN, SERVE, or PLAY an application, project, or game:\n' +
|
|
470
|
+
' - 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' +
|
|
471
|
+
' - 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' +
|
|
472
|
+
' - 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' +
|
|
473
|
+
' - Confirm the application is accessible only after a readiness check succeeds.\n' +
|
|
474
|
+
'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' +
|
|
475
|
+
'4. Create or edit files only when the current user request authorizes it.\n\n' +
|
|
476
|
+
'[Environment State & Idempotency Directive]\n' +
|
|
477
|
+
'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
|
|
478
|
+
'[Language & Communication Directive]\n' +
|
|
479
|
+
'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.');
|
|
101
480
|
if (tools && tools.length > 0) {
|
|
102
481
|
const toolSummaries = tools.map(t => {
|
|
103
482
|
const name = t.name || t.function?.name || 'unknown';
|
|
@@ -108,7 +487,11 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
108
487
|
}).join('\n');
|
|
109
488
|
lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
110
489
|
}
|
|
111
|
-
|
|
490
|
+
const seenToolOutputs = new Set();
|
|
491
|
+
const seenAssistantCalls = new Set();
|
|
492
|
+
for (let i = 0; i < messages.length; i++) {
|
|
493
|
+
const msg = messages[i];
|
|
494
|
+
const isRecent = messages.length - i <= 4;
|
|
112
495
|
const role = msg.role === 'user'
|
|
113
496
|
? 'User'
|
|
114
497
|
: (msg.role === 'assistant'
|
|
@@ -123,12 +506,36 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
123
506
|
text = msg.content;
|
|
124
507
|
}
|
|
125
508
|
else if (Array.isArray(msg.content)) {
|
|
126
|
-
text = msg.content.map((c) =>
|
|
509
|
+
text = msg.content.map((c) => {
|
|
510
|
+
if (typeof c === 'string')
|
|
511
|
+
return c;
|
|
512
|
+
if (c?.text)
|
|
513
|
+
return c.text;
|
|
514
|
+
if (c?.type === 'image_url' || c?.type === 'image') {
|
|
515
|
+
const url = c?.image_url?.url || '';
|
|
516
|
+
const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
|
|
517
|
+
return `[Visual Content: ${mime}]`;
|
|
518
|
+
}
|
|
519
|
+
return '';
|
|
520
|
+
}).filter(Boolean).join('\n');
|
|
521
|
+
}
|
|
522
|
+
// Compact duplicate identical tool outputs to prevent token ballooning
|
|
523
|
+
if (msg.role === 'tool' && text.trim()) {
|
|
524
|
+
const normalized = text.trim();
|
|
525
|
+
if (seenToolOutputs.has(normalized)) {
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
seenToolOutputs.add(normalized);
|
|
127
529
|
}
|
|
128
530
|
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
129
531
|
for (const tc of msg.tool_calls) {
|
|
130
532
|
const fn = tc.function || {};
|
|
131
533
|
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
534
|
+
const callSig = `${fn.name}:${fnArgs}`;
|
|
535
|
+
if (seenAssistantCalls.has(callSig)) {
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
seenAssistantCalls.add(callSig);
|
|
132
539
|
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
133
540
|
}
|
|
134
541
|
}
|
|
@@ -190,6 +597,34 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
190
597
|
}
|
|
191
598
|
}
|
|
192
599
|
}
|
|
600
|
+
// Unclosed tool_call recovery (when model generated large file content and closed turn)
|
|
601
|
+
if (calls.length === 0) {
|
|
602
|
+
const openIndex = text.lastIndexOf('<tool_call>');
|
|
603
|
+
if (openIndex !== -1 && text.indexOf('</tool_call>', openIndex) === -1) {
|
|
604
|
+
const partial = text.slice(openIndex + '<tool_call>'.length).trim();
|
|
605
|
+
for (const suffix of ['', '}', '}}', '}}}', '"}', '"}}', '"}}}', '"}]}}', '"]}}', '"]}}}']) {
|
|
606
|
+
try {
|
|
607
|
+
const parsed = JSON.parse(partial + suffix);
|
|
608
|
+
const name = parsed.name || parsed.tool || parsed.function?.name;
|
|
609
|
+
if (name) {
|
|
610
|
+
const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
|
|
611
|
+
calls.push({
|
|
612
|
+
id: `agy_call_${Date.now()}_0`,
|
|
613
|
+
type: 'function',
|
|
614
|
+
function: {
|
|
615
|
+
name,
|
|
616
|
+
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
617
|
+
}
|
|
618
|
+
});
|
|
619
|
+
break;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
catch {
|
|
623
|
+
// try next candidate
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
193
628
|
return calls;
|
|
194
629
|
}
|
|
195
630
|
_isTransientError(errMessage) {
|
|
@@ -208,32 +643,80 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
208
643
|
msg.includes('status 429');
|
|
209
644
|
}
|
|
210
645
|
async _executeOnce(messages, options = {}) {
|
|
211
|
-
const
|
|
646
|
+
const currentSessionKey = options.conversationId || options.taskId || null;
|
|
647
|
+
if (currentSessionKey && currentSessionKey !== this.lastTaskId) {
|
|
648
|
+
this.currentConversationId = null;
|
|
649
|
+
this.lastTaskId = currentSessionKey;
|
|
650
|
+
}
|
|
651
|
+
if (messages.length <= 1) {
|
|
652
|
+
this.currentConversationId = null;
|
|
653
|
+
}
|
|
654
|
+
const useConversation = Boolean(this.currentConversationId);
|
|
655
|
+
const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
|
|
656
|
+
const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
|
|
657
|
+
const launchOnly = options.taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
|
|
658
|
+
let promptText;
|
|
659
|
+
if (useConversation) {
|
|
660
|
+
let lastAssistantIndex = -1;
|
|
661
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
662
|
+
if (messages[i].role === 'assistant') {
|
|
663
|
+
lastAssistantIndex = i;
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
const deltaMessages = lastAssistantIndex >= 0 ? messages.slice(lastAssistantIndex + 1) : messages;
|
|
668
|
+
promptText = this.formatDelta(deltaMessages.length > 0 ? deltaMessages : [messages[messages.length - 1]]);
|
|
669
|
+
}
|
|
670
|
+
else {
|
|
671
|
+
promptText = this.formatConversation(messages, options.tools);
|
|
672
|
+
}
|
|
673
|
+
// A resumed agy conversation retains its old instructions. Reassert the
|
|
674
|
+
// current turn's narrower scope on every call, including formatDelta turns.
|
|
675
|
+
if (launchOnly) {
|
|
676
|
+
promptText = '[Current request: open existing project only]\n' +
|
|
677
|
+
'Inspect the selected project, start an existing server in the background if needed, verify readiness, and open it. ' +
|
|
678
|
+
'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
|
|
679
|
+
'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
|
|
680
|
+
}
|
|
212
681
|
const modelSlug = resolveAgyModelId(this.model);
|
|
213
682
|
const effort = resolveAgyEffort(this.model);
|
|
214
683
|
// Standard high-performance non-blocking CLI invocation:
|
|
215
684
|
// 1. stream-json output for real-time responsiveness and non-buffering progress.
|
|
216
685
|
// 2. --disable-slash-commands prevents sluggish filesystem and customization scans.
|
|
217
|
-
// 3.
|
|
218
|
-
//
|
|
686
|
+
// 3. agy only treats stdin as a prompt in stream-json input mode. Plain text
|
|
687
|
+
// stdin without --print starts an interactive session and loses the task.
|
|
688
|
+
// Keep the prompt off the process command line by sending one user event.
|
|
689
|
+
// 4. --mode accept-edits lets agy create and edit workspace files in
|
|
690
|
+
// headless mode, where the default request-review policy cannot prompt
|
|
691
|
+
// and would auto-deny every write. --dangerously-skip-permissions must
|
|
692
|
+
// stay off: it would also grant shell commands and other host tools,
|
|
693
|
+
// bypassing Causyne. Native terminal/browser tools remain denied; those
|
|
694
|
+
// must go through Causyne XML tool calls.
|
|
695
|
+
// 5. Launch-only turns use a shorter limit because they should not spend
|
|
696
|
+
// several minutes generating code or holding a foreground server open.
|
|
697
|
+
// 6. --conversation links multi-turn steps to agy's local session memory to prevent re-reading files.
|
|
219
698
|
const args = [
|
|
699
|
+
'--mode',
|
|
700
|
+
launchOnly ? 'plan' : 'accept-edits',
|
|
701
|
+
'--input-format',
|
|
702
|
+
'stream-json',
|
|
220
703
|
'--output-format',
|
|
221
704
|
'stream-json',
|
|
222
705
|
'--disable-slash-commands',
|
|
223
706
|
'--print-timeout',
|
|
224
|
-
'
|
|
225
|
-
'--dangerously-skip-permissions',
|
|
707
|
+
launchOnly ? '90s' : this.printTimeout,
|
|
226
708
|
'--model',
|
|
227
709
|
modelSlug,
|
|
228
710
|
'--effort',
|
|
229
|
-
effort
|
|
230
|
-
'-p',
|
|
231
|
-
'-'
|
|
711
|
+
effort
|
|
232
712
|
];
|
|
713
|
+
if (useConversation && this.currentConversationId) {
|
|
714
|
+
args.push('--conversation', this.currentConversationId);
|
|
715
|
+
}
|
|
233
716
|
return new Promise((resolve, reject) => {
|
|
234
717
|
let isSettled = false;
|
|
235
718
|
const child = spawn(this.command, args, {
|
|
236
|
-
cwd: process.cwd(),
|
|
719
|
+
cwd: typeof options.workspaceRoot === 'string' ? options.workspaceRoot : process.cwd(),
|
|
237
720
|
env: process.env,
|
|
238
721
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
239
722
|
windowsHide: true
|
|
@@ -242,6 +725,10 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
242
725
|
let stderrBuffer = '';
|
|
243
726
|
let streamedResponse = '';
|
|
244
727
|
let finalResultObj = null;
|
|
728
|
+
let sawToolAfterLastText = false;
|
|
729
|
+
const nativeActions = [];
|
|
730
|
+
const attemptedNativeTools = [];
|
|
731
|
+
let childClosed = false;
|
|
245
732
|
const cleanup = () => {
|
|
246
733
|
if (options.signal) {
|
|
247
734
|
options.signal.removeEventListener('abort', onAbort);
|
|
@@ -265,14 +752,16 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
265
752
|
try {
|
|
266
753
|
child.kill('SIGTERM');
|
|
267
754
|
setTimeout(() => {
|
|
268
|
-
if (!
|
|
755
|
+
if (!childClosed)
|
|
269
756
|
child.kill('SIGKILL');
|
|
270
757
|
}, 1000).unref();
|
|
271
758
|
}
|
|
272
759
|
catch {
|
|
273
760
|
// ignore kill errors
|
|
274
761
|
}
|
|
275
|
-
|
|
762
|
+
const abortErr = new Error('Turn aborted by user or timeout.');
|
|
763
|
+
abortErr.name = 'AbortError';
|
|
764
|
+
safeReject(abortErr);
|
|
276
765
|
};
|
|
277
766
|
if (options.signal) {
|
|
278
767
|
if (options.signal.aborted) {
|
|
@@ -283,7 +772,8 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
283
772
|
}
|
|
284
773
|
// Feed prompt directly into child process stdin, then close stdin
|
|
285
774
|
try {
|
|
286
|
-
child.stdin.
|
|
775
|
+
child.stdin.on('error', () => { });
|
|
776
|
+
child.stdin.write(JSON.stringify({ event: 'user', message: { content: promptText } }) + '\n', 'utf8');
|
|
287
777
|
child.stdin.end();
|
|
288
778
|
}
|
|
289
779
|
catch (err) {
|
|
@@ -302,10 +792,71 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
302
792
|
continue;
|
|
303
793
|
try {
|
|
304
794
|
const event = JSON.parse(trimmed);
|
|
305
|
-
if (event.event === '
|
|
795
|
+
if (event.event === 'init') {
|
|
796
|
+
if (event.conversation_id) {
|
|
797
|
+
this.currentConversationId = event.conversation_id;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
else if (event.event === 'step_update') {
|
|
306
801
|
const stepUpdate = event.step_update;
|
|
307
802
|
const delta = stepUpdate?.text_delta;
|
|
308
803
|
const stepType = stepUpdate?.step_type;
|
|
804
|
+
if (stepType === 'tool') {
|
|
805
|
+
const state = stepUpdate?.state;
|
|
806
|
+
const toolInfo = stepUpdate?.tool_info || {};
|
|
807
|
+
const name = stepUpdate?.tool_name || toolInfo?.name;
|
|
808
|
+
const status = state === 'DONE'
|
|
809
|
+
? 'completed'
|
|
810
|
+
: (state === 'ERROR' ? 'failed' : 'running');
|
|
811
|
+
const rawParams = (toolInfo && typeof toolInfo === 'object' && toolInfo.parameters) ||
|
|
812
|
+
(stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
|
|
813
|
+
(toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
|
|
814
|
+
{};
|
|
815
|
+
if (name) {
|
|
816
|
+
const existingAttempt = attemptedNativeTools.find(a => a.name === name && a.status === 'running');
|
|
817
|
+
if (existingAttempt) {
|
|
818
|
+
existingAttempt.status = status;
|
|
819
|
+
if (rawParams && Object.keys(rawParams).length > 0) {
|
|
820
|
+
existingAttempt.parameters = { ...existingAttempt.parameters, ...rawParams };
|
|
821
|
+
}
|
|
822
|
+
if (toolInfo?.error?.message)
|
|
823
|
+
existingAttempt.error = toolInfo.error.message;
|
|
824
|
+
}
|
|
825
|
+
else {
|
|
826
|
+
attemptedNativeTools.push({
|
|
827
|
+
name,
|
|
828
|
+
parameters: { ...rawParams },
|
|
829
|
+
status,
|
|
830
|
+
error: toolInfo?.error?.message,
|
|
831
|
+
detail: describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams })
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
if (name && (state === 'ACTIVE' || state === 'DONE' || state === 'ERROR')) {
|
|
836
|
+
sawToolAfterLastText = true;
|
|
837
|
+
const detail = describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams });
|
|
838
|
+
const action = {
|
|
839
|
+
name,
|
|
840
|
+
status,
|
|
841
|
+
...(detail ? { detail } : {})
|
|
842
|
+
};
|
|
843
|
+
if (status !== 'running') {
|
|
844
|
+
const existing = nativeActions.find(a => a.name === action.name && a.detail === action.detail);
|
|
845
|
+
if (existing)
|
|
846
|
+
existing.status = status;
|
|
847
|
+
else
|
|
848
|
+
nativeActions.push(action);
|
|
849
|
+
}
|
|
850
|
+
// Stream the start; completion is reported only after the
|
|
851
|
+
// final result has checked for denied actions.
|
|
852
|
+
if (status === 'running' && typeof options.onNativeAction === 'function') {
|
|
853
|
+
const parameters = rawParams && typeof rawParams === 'object'
|
|
854
|
+
? rawParams
|
|
855
|
+
: {};
|
|
856
|
+
options.onNativeAction({ ...action, parameters });
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
309
860
|
if (delta && typeof delta === 'string') {
|
|
310
861
|
if (stepType === 'thought' || stepType === 'agent_thought') {
|
|
311
862
|
if (typeof options.onReasoningChunk === 'function') {
|
|
@@ -313,6 +864,15 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
313
864
|
}
|
|
314
865
|
}
|
|
315
866
|
else {
|
|
867
|
+
if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(delta)) {
|
|
868
|
+
streamedResponse += '\n';
|
|
869
|
+
if (typeof options.onChunk === 'function') {
|
|
870
|
+
options.onChunk('\n');
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
if (delta.trim().length > 0) {
|
|
874
|
+
sawToolAfterLastText = false;
|
|
875
|
+
}
|
|
316
876
|
streamedResponse += delta;
|
|
317
877
|
if (typeof options.onChunk === 'function') {
|
|
318
878
|
options.onChunk(delta);
|
|
@@ -322,8 +882,13 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
322
882
|
}
|
|
323
883
|
else if (event.event === 'result') {
|
|
324
884
|
finalResultObj = event.result;
|
|
885
|
+
if (event.result?.conversation_id) {
|
|
886
|
+
this.currentConversationId = event.result.conversation_id;
|
|
887
|
+
}
|
|
325
888
|
}
|
|
326
889
|
else if (event.status === 'ERROR') {
|
|
890
|
+
if (useConversation)
|
|
891
|
+
this.currentConversationId = null;
|
|
327
892
|
safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
|
|
328
893
|
return;
|
|
329
894
|
}
|
|
@@ -338,17 +903,25 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
338
903
|
stderrBuffer += chunk;
|
|
339
904
|
});
|
|
340
905
|
child.on('error', (err) => {
|
|
906
|
+
if (useConversation)
|
|
907
|
+
this.currentConversationId = null;
|
|
341
908
|
safeReject(new Error(`Antigravity Agent (agy) spawn error: ${err.message}. Make sure Antigravity CLI is installed.`));
|
|
342
909
|
});
|
|
343
910
|
child.on('close', (code) => {
|
|
911
|
+
childClosed = true;
|
|
344
912
|
// Process any remaining bytes in stdoutBuffer
|
|
345
913
|
if (stdoutBuffer.trim()) {
|
|
346
914
|
try {
|
|
347
915
|
const event = JSON.parse(stdoutBuffer.trim());
|
|
348
916
|
if (event.event === 'result') {
|
|
349
917
|
finalResultObj = event.result;
|
|
918
|
+
if (event.result?.conversation_id) {
|
|
919
|
+
this.currentConversationId = event.result.conversation_id;
|
|
920
|
+
}
|
|
350
921
|
}
|
|
351
922
|
else if (event.status === 'ERROR') {
|
|
923
|
+
if (useConversation)
|
|
924
|
+
this.currentConversationId = null;
|
|
352
925
|
safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
|
|
353
926
|
return;
|
|
354
927
|
}
|
|
@@ -357,8 +930,10 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
357
930
|
// ignore
|
|
358
931
|
}
|
|
359
932
|
}
|
|
360
|
-
if (code !== 0
|
|
361
|
-
|
|
933
|
+
if (code !== 0 || finalResultObj?.status === 'ERROR') {
|
|
934
|
+
if (useConversation)
|
|
935
|
+
this.currentConversationId = null;
|
|
936
|
+
const errDetail = finalResultObj?.error || stderrBuffer.trim() || `exit code ${code}`;
|
|
362
937
|
safeReject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
|
|
363
938
|
return;
|
|
364
939
|
}
|
|
@@ -373,17 +948,71 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
373
948
|
const toolCalls = this.extractToolCalls(rawContent);
|
|
374
949
|
// Strip tool call tags from prose so raw XML does not leak into chat display
|
|
375
950
|
let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
|
|
376
|
-
|
|
377
|
-
|
|
951
|
+
const deniedActions = Array.isArray(finalResultObj?.denied_actions)
|
|
952
|
+
? finalResultObj.denied_actions : [];
|
|
953
|
+
const normalizeAction = (value) => String(value || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
954
|
+
const deniedNames = new Set(deniedActions.flatMap(action => [normalizeAction(action?.action), normalizeAction(action?.display_name)]).filter(Boolean));
|
|
955
|
+
for (const action of nativeActions) {
|
|
956
|
+
if (deniedNames.has(normalizeAction(action.name)))
|
|
957
|
+
action.status = 'failed';
|
|
958
|
+
if (typeof options.onNativeAction === 'function') {
|
|
959
|
+
const attempt = [...attemptedNativeTools].reverse().find(candidate => normalizeAction(candidate.name) === normalizeAction(action.name));
|
|
960
|
+
options.onNativeAction({ ...action, parameters: attempt?.parameters || {} });
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
if (deniedActions.length > 0) {
|
|
964
|
+
const unmapped = [];
|
|
965
|
+
for (const denied of deniedActions) {
|
|
966
|
+
const name = String(denied?.action || denied?.display_name || 'unknown');
|
|
967
|
+
const attempt = [...attemptedNativeTools].reverse().find(candidate => normalizeAction(candidate.name) === normalizeAction(name)
|
|
968
|
+
|| normalizeAction(candidate.name) === normalizeAction(denied?.display_name));
|
|
969
|
+
const parameters = {
|
|
970
|
+
...(attempt?.parameters || {}),
|
|
971
|
+
...(denied?.parameters || {}),
|
|
972
|
+
...(attempt?.detail ? { detail: attempt.detail } : {})
|
|
973
|
+
};
|
|
974
|
+
const mapped = mapNativeToolToCausyne(attempt?.name || String(denied?.display_name || name), parameters, toolCalls.length);
|
|
975
|
+
if (!mapped) {
|
|
976
|
+
unmapped.push(String(denied?.display_name || name));
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
979
|
+
if (!toolCalls.some(call => call.function.name === mapped.function.name
|
|
980
|
+
&& call.function.arguments === mapped.function.arguments)) {
|
|
981
|
+
toolCalls.push(mapped);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
if (unmapped.length > 0) {
|
|
985
|
+
const error = new Error(`Antigravity could not perform: ${unmapped.join(', ')}. The denied action had no safe Causyne tool mapping.`);
|
|
986
|
+
error.code = 'AGY_NATIVE_ACTION_DENIED';
|
|
987
|
+
safeReject(error);
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
// Any prose produced alongside a denied action may claim work that
|
|
991
|
+
// did not occur. Wait for the mapped Causyne tool result instead.
|
|
992
|
+
content = '';
|
|
993
|
+
}
|
|
994
|
+
const completedNativeActions = nativeActions.filter((a) => a.status === 'completed');
|
|
995
|
+
if (!content && completedNativeActions.length > 0) {
|
|
996
|
+
content = `Antigravity completed: ${completedNativeActions
|
|
997
|
+
.map((a) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
|
|
998
|
+
.join(', ')}`;
|
|
378
999
|
}
|
|
379
1000
|
if (!content && toolCalls.length === 0) {
|
|
380
|
-
|
|
1001
|
+
const detail = stderrBuffer.trim();
|
|
1002
|
+
safeReject(new Error(detail
|
|
1003
|
+
? `Antigravity returned no response: ${detail}`
|
|
1004
|
+
: 'Antigravity returned no response.'));
|
|
1005
|
+
return;
|
|
381
1006
|
}
|
|
1007
|
+
const timedOutMidTurn = /print timeout after .* with turn in progress|returning partial output/i.test(stderrBuffer);
|
|
1008
|
+
const finalResponseText = typeof finalResultObj?.response === 'string' ? finalResultObj.response.trim() : '';
|
|
1009
|
+
const endedAfterToolWithoutFinalResponse = sawToolAfterLastText && !finalResponseText && deniedActions.length === 0 && toolCalls.length === 0;
|
|
1010
|
+
const missingResultEvent = finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
|
|
382
1011
|
const promptTokens = Number(finalResultObj?.usage?.input_tokens) || Math.ceil(promptText.length / 4);
|
|
383
1012
|
const completionTokens = Number(finalResultObj?.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
|
|
384
1013
|
const thinkingTokens = Number(finalResultObj?.usage?.thinking_tokens) || 0;
|
|
385
1014
|
const response = {
|
|
386
|
-
content
|
|
1015
|
+
content,
|
|
387
1016
|
usage: {
|
|
388
1017
|
promptTokens,
|
|
389
1018
|
completionTokens: completionTokens + thinkingTokens,
|
|
@@ -396,19 +1025,30 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
396
1025
|
if (toolCalls.length > 0) {
|
|
397
1026
|
response.toolCalls = toolCalls;
|
|
398
1027
|
}
|
|
1028
|
+
if (nativeActions.length > 0) {
|
|
1029
|
+
response.externalActions = nativeActions.filter((a) => a.status !== 'running');
|
|
1030
|
+
}
|
|
1031
|
+
if (timedOutMidTurn || endedAfterToolWithoutFinalResponse || missingResultEvent) {
|
|
1032
|
+
response.incompleteTurn = true;
|
|
1033
|
+
}
|
|
399
1034
|
safeResolve(response);
|
|
400
1035
|
});
|
|
401
1036
|
});
|
|
402
1037
|
}
|
|
403
1038
|
async chat(messages, options = {}) {
|
|
404
|
-
const maxRetries = options.maxRetries ?? 2;
|
|
1039
|
+
const maxRetries = options.maxRetries ?? (options.taskIntent === 'launch' ? 1 : 2);
|
|
405
1040
|
let attempt = 0;
|
|
406
1041
|
while (attempt <= maxRetries) {
|
|
1042
|
+
const hadConversation = Boolean(this.currentConversationId);
|
|
407
1043
|
try {
|
|
408
1044
|
return await this._executeOnce(messages, options);
|
|
409
1045
|
}
|
|
410
1046
|
catch (err) {
|
|
411
|
-
if (
|
|
1047
|
+
if (options.signal?.aborted || err?.name === 'AbortError') {
|
|
1048
|
+
throw err;
|
|
1049
|
+
}
|
|
1050
|
+
const canRetryResetConversation = hadConversation && !this.currentConversationId && err?.code !== 'AGY_NATIVE_ACTION_DENIED';
|
|
1051
|
+
if (attempt < maxRetries && (this._isTransientError(err.message) || canRetryResetConversation)) {
|
|
412
1052
|
attempt++;
|
|
413
1053
|
const delay = attempt * 1200;
|
|
414
1054
|
await new Promise(r => setTimeout(r, delay));
|