@causyne/agent 1.19.0 → 1.20.5

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.
Files changed (128) hide show
  1. package/README.md +0 -18
  2. package/package.json +1 -1
  3. package/src/acp/client.js +2 -1
  4. package/src/acp/client.ts +2 -1
  5. package/src/acp/server.js +5 -6
  6. package/src/acp/server.ts +4 -6
  7. package/src/agentLoop.d.ts +1 -0
  8. package/src/agentLoop.js +505 -241
  9. package/src/agentLoop.ts +527 -258
  10. package/src/agentPolicy.js +9 -0
  11. package/src/agentPolicy.ts +9 -0
  12. package/src/approvalPolicy.js +55 -0
  13. package/src/approvalPolicy.ts +66 -0
  14. package/src/browser/browserRuntime.js +217 -14
  15. package/src/browser/browserRuntime.ts +255 -14
  16. package/src/browser/causyneBrowser.js +1215 -68
  17. package/src/browser/causyneBrowser.ts +1340 -72
  18. package/src/cliMode.js +66 -37
  19. package/src/commands.js +343 -72
  20. package/src/config.js +22 -12
  21. package/src/continuum/ingest.js +1 -1
  22. package/src/continuum/ingest.ts +1 -1
  23. package/src/continuum/ui/continuumPicker.js +18 -1
  24. package/src/continuum/ui/continuumPicker.ts +19 -1
  25. package/src/dynamicCatalogue.js +87 -20
  26. package/src/dynamicCatalogue.ts +85 -15
  27. package/src/launchIntent.js +40 -0
  28. package/src/launchIntent.ts +49 -0
  29. package/src/memoryManager.js +36 -8
  30. package/src/modelCatalogue.js +2 -0
  31. package/src/planCache.js +320 -11
  32. package/src/planCache.ts +402 -13
  33. package/src/providers/acp.js +67 -1
  34. package/src/providers/acp.ts +65 -2
  35. package/src/providers/antigravity.d.ts +5 -1
  36. package/src/providers/antigravity.js +643 -32
  37. package/src/providers/antigravity.ts +671 -33
  38. package/src/providers/base.d.ts +9 -0
  39. package/src/providers/factory.js +2 -0
  40. package/src/providers/pi.js +157 -0
  41. package/src/providers/pi.ts +144 -0
  42. package/src/provisioning/capabilityProvisioner.js +17 -0
  43. package/src/provisioning/capabilityTools.js +1 -1
  44. package/src/sandbox.js +30 -39
  45. package/src/sessionJournal.js +66 -10
  46. package/src/sessionJournal.ts +84 -10
  47. package/src/taskShape.js +9 -9
  48. package/src/taskShape.ts +9 -9
  49. package/src/timeMachine.js +124 -0
  50. package/src/timeMachine.ts +141 -0
  51. package/src/toolPacks.js +4 -10
  52. package/src/tools/archive.js +196 -59
  53. package/src/tools/archive.ts +220 -0
  54. package/src/tools/browserAutomator.js +78 -9
  55. package/src/tools/browserAutomator.ts +90 -9
  56. package/src/tools/desktopOpen.js +114 -31
  57. package/src/tools/desktopOpen.ts +144 -0
  58. package/src/tools/gitExec.js +5 -3
  59. package/src/tools/nativeEngine.js +4 -3
  60. package/src/tools/nativeEngine.ts +5 -3
  61. package/src/tools/openSourceToolProvisioner.js +5 -4
  62. package/src/tools/openSourceToolProvisioner.ts +5 -4
  63. package/src/tools/registry.js +3 -0
  64. package/src/tools/screenshot.js +55 -71
  65. package/src/tools/screenshot.ts +70 -0
  66. package/src/tools/sysRun.js +284 -117
  67. package/src/tools/sysRun.ts +347 -0
  68. package/src/tools/toolSelfRepair.js +109 -2
  69. package/src/tools/toolSelfRepair.ts +100 -2
  70. package/src/tools/updatePlan.js +49 -1
  71. package/src/tools/updatePlan.ts +43 -1
  72. package/src/tools/viewImage.js +93 -78
  73. package/src/tools/viewImage.ts +116 -0
  74. package/src/tools/webFetch.js +20 -6
  75. package/src/tools/webFetch.ts +26 -6
  76. package/src/tui/block.d.ts +1 -0
  77. package/src/tui/chatRenderer.d.ts +21 -0
  78. package/src/tui/chatRenderer.js +118 -45
  79. package/src/tui/clipboardSync.js +28 -1
  80. package/src/tui/clipboardSync.ts +26 -1
  81. package/src/tui/codeProgress.js +299 -0
  82. package/src/tui/codeProgress.ts +304 -0
  83. package/src/tui/codeStreamRenderer.js +116 -0
  84. package/src/tui/codeStreamRenderer.ts +124 -0
  85. package/src/tui/commandPresentation.js +11 -0
  86. package/src/tui/commandPresentation.ts +18 -0
  87. package/src/tui/completion.js +45 -13
  88. package/src/tui/composerControls.js +66 -0
  89. package/src/tui/composerControls.ts +78 -0
  90. package/src/tui/diff.d.ts +2 -0
  91. package/src/tui/home.js +4 -2
  92. package/src/tui/homeTransition.js +21 -0
  93. package/src/tui/homeTransition.ts +27 -0
  94. package/src/tui/homeView.js +62 -0
  95. package/src/tui/homeView.ts +91 -0
  96. package/src/tui/layout.js +46 -0
  97. package/src/tui/layout.ts +52 -0
  98. package/src/tui/messageActionPlacement.js +16 -0
  99. package/src/tui/messageActionPlacement.ts +25 -0
  100. package/src/tui/messageInteraction.js +221 -0
  101. package/src/tui/messageInteraction.ts +275 -0
  102. package/src/tui/modelPicker.js +13 -0
  103. package/src/tui/modelPicker.ts +12 -0
  104. package/src/tui/mouseHover.js +6 -0
  105. package/src/tui/mouseHover.ts +5 -0
  106. package/src/tui/prompt.js +199 -52
  107. package/src/tui/resizeRecovery.js +15 -0
  108. package/src/tui/resizeRecovery.ts +27 -0
  109. package/src/tui/scrollInteraction.js +97 -0
  110. package/src/tui/scrollInteraction.ts +189 -0
  111. package/src/tui/sessionLayout.js +12 -0
  112. package/src/tui/sessionLayout.ts +12 -0
  113. package/src/tui/sessionPicker.js +280 -0
  114. package/src/tui/sessionPicker.ts +364 -0
  115. package/src/tui/sessionSidebar.js +78 -0
  116. package/src/tui/sessionSidebar.ts +95 -0
  117. package/src/tui/setup.js +1 -1
  118. package/src/tui/setup.ts +1 -1
  119. package/src/tui/stageSurface.js +128 -57
  120. package/src/tui/statusLine.js +5 -5
  121. package/src/tui/text.d.ts +5 -0
  122. package/src/tui/textLayout.js +23 -0
  123. package/src/tui/textLayout.ts +28 -0
  124. package/src/tui/viewport.js +204 -279
  125. package/src/tui/viewport.ts +326 -0
  126. package/src/types/contracts.ts +54 -0
  127. package/src/utils/paths.js +5 -4
  128. 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
- * Display label → the id `agy --model` actually accepts, exactly as reported
7
- * by `agy models`. The CLI exposes slugs; the picker shows the readable label.
8
- * Passing the label through unchanged is what a user would try, so both forms
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 ANTIGRAVITY_MODEL_IDS = {
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
- return ANTIGRAVITY_MODEL_IDS[trimmed] || trimmed;
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,311 @@ 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
+ currentConversationId = null;
403
+ lastTaskId = null;
86
404
  constructor(config = {}) {
87
405
  super(config);
88
406
  this.model = config.model || 'Gemini 3.8 Flash (Low)';
89
407
  this.command = config.command || resolveAgyBinary();
90
- this.visionModels = [];
408
+ this.visionModels = ['*'];
91
409
  this.audioModels = [];
92
410
  }
411
+ formatDelta(messages) {
412
+ const lines = [];
413
+ for (const msg of messages) {
414
+ const role = msg.role === 'user'
415
+ ? 'User'
416
+ : (msg.role === 'assistant'
417
+ ? 'Assistant'
418
+ : (msg.role === 'system'
419
+ ? 'System Instructions'
420
+ : (msg.role === 'tool'
421
+ ? `Tool Result (${msg.name || 'tool'})`
422
+ : 'Context')));
423
+ let text = '';
424
+ if (typeof msg.content === 'string') {
425
+ text = msg.content;
426
+ }
427
+ else if (Array.isArray(msg.content)) {
428
+ text = msg.content.map((c) => {
429
+ if (typeof c === 'string')
430
+ return c;
431
+ if (c?.text)
432
+ return c.text;
433
+ if (c?.type === 'image_url' || c?.type === 'image') {
434
+ const url = c?.image_url?.url || '';
435
+ const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
436
+ return `[Visual Content: ${mime}]`;
437
+ }
438
+ return '';
439
+ }).filter(Boolean).join('\n');
440
+ }
441
+ if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
442
+ for (const tc of msg.tool_calls) {
443
+ const fn = tc.function || {};
444
+ const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
445
+ text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
446
+ }
447
+ }
448
+ if (text.trim()) {
449
+ lines.push(`[${role}]\n${text.trim()}`);
450
+ }
451
+ }
452
+ return lines.join('\n\n');
453
+ }
93
454
  formatConversation(messages, tools = []) {
94
455
  const lines = [];
95
- // Core System boundary instructions
456
+ // Host capabilities must be learned from real tool results in this session.
96
457
  lines.push('[System Instructions]\n' +
97
- 'You are acting as an AI reasoning engine for Causyne Agent. Do NOT invoke your own internal host CLI tools or execute commands directly. ' +
98
- 'When an action or tool is required, output an explicit tool call in this exact format:\n' +
458
+ 'You are the execution engine for Causyne Agent, operating inside the user\'s workspace. ' +
459
+ 'Do not claim a tool action succeeded without evidence. Use Causyne tools for file changes, terminal commands, and browser actions. ' +
460
+ 'When a command, browser action, or other external action is required, output an explicit tool call in this exact format:\n' +
99
461
  '<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.');
462
+ 'Causyne Agent will execute the tool in its secure environment and return the results back to you.\n\n' +
463
+ '[Action Directive]\n' +
464
+ '1. When the user requests to create, build, code, fix, write, optimize, or implement anything, invoke the relevant file or command tools immediately.\n' +
465
+ '2. When the user requests to OPEN, LAUNCH, RUN, SERVE, or PLAY an application, project, or game:\n' +
466
+ ' - 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' +
467
+ ' - 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' +
468
+ ' - 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' +
469
+ ' - Confirm the application is accessible only after a readiness check succeeds.\n' +
470
+ '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' +
471
+ '4. Create or edit files only when the current user request authorizes it.\n\n' +
472
+ '[Environment State & Idempotency Directive]\n' +
473
+ 'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
474
+ '[Language & Communication Directive]\n' +
475
+ '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
476
  if (tools && tools.length > 0) {
102
477
  const toolSummaries = tools.map(t => {
103
478
  const name = t.name || t.function?.name || 'unknown';
@@ -108,7 +483,11 @@ export class AntigravityProvider extends LLMProvider {
108
483
  }).join('\n');
109
484
  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
485
  }
111
- for (const msg of messages) {
486
+ const seenToolOutputs = new Set();
487
+ const seenAssistantCalls = new Set();
488
+ for (let i = 0; i < messages.length; i++) {
489
+ const msg = messages[i];
490
+ const isRecent = messages.length - i <= 4;
112
491
  const role = msg.role === 'user'
113
492
  ? 'User'
114
493
  : (msg.role === 'assistant'
@@ -123,12 +502,36 @@ export class AntigravityProvider extends LLMProvider {
123
502
  text = msg.content;
124
503
  }
125
504
  else if (Array.isArray(msg.content)) {
126
- text = msg.content.map((c) => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
505
+ text = msg.content.map((c) => {
506
+ if (typeof c === 'string')
507
+ return c;
508
+ if (c?.text)
509
+ return c.text;
510
+ if (c?.type === 'image_url' || c?.type === 'image') {
511
+ const url = c?.image_url?.url || '';
512
+ const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
513
+ return `[Visual Content: ${mime}]`;
514
+ }
515
+ return '';
516
+ }).filter(Boolean).join('\n');
517
+ }
518
+ // Compact duplicate identical tool outputs to prevent token ballooning
519
+ if (msg.role === 'tool' && text.trim()) {
520
+ const normalized = text.trim();
521
+ if (seenToolOutputs.has(normalized)) {
522
+ continue;
523
+ }
524
+ seenToolOutputs.add(normalized);
127
525
  }
128
526
  if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
129
527
  for (const tc of msg.tool_calls) {
130
528
  const fn = tc.function || {};
131
529
  const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
530
+ const callSig = `${fn.name}:${fnArgs}`;
531
+ if (seenAssistantCalls.has(callSig)) {
532
+ continue;
533
+ }
534
+ seenAssistantCalls.add(callSig);
132
535
  text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
133
536
  }
134
537
  }
@@ -190,6 +593,34 @@ export class AntigravityProvider extends LLMProvider {
190
593
  }
191
594
  }
192
595
  }
596
+ // Unclosed tool_call recovery (when model generated large file content and closed turn)
597
+ if (calls.length === 0) {
598
+ const openIndex = text.lastIndexOf('<tool_call>');
599
+ if (openIndex !== -1 && text.indexOf('</tool_call>', openIndex) === -1) {
600
+ const partial = text.slice(openIndex + '<tool_call>'.length).trim();
601
+ for (const suffix of ['', '}', '}}', '}}}', '"}', '"}}', '"}}}', '"}]}}', '"]}}', '"]}}}']) {
602
+ try {
603
+ const parsed = JSON.parse(partial + suffix);
604
+ const name = parsed.name || parsed.tool || parsed.function?.name;
605
+ if (name) {
606
+ const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
607
+ calls.push({
608
+ id: `agy_call_${Date.now()}_0`,
609
+ type: 'function',
610
+ function: {
611
+ name,
612
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
613
+ }
614
+ });
615
+ break;
616
+ }
617
+ }
618
+ catch {
619
+ // try next candidate
620
+ }
621
+ }
622
+ }
623
+ }
193
624
  return calls;
194
625
  }
195
626
  _isTransientError(errMessage) {
@@ -208,32 +639,80 @@ export class AntigravityProvider extends LLMProvider {
208
639
  msg.includes('status 429');
209
640
  }
210
641
  async _executeOnce(messages, options = {}) {
211
- const promptText = this.formatConversation(messages, options.tools);
642
+ const currentTaskId = options.taskId || options.conversationId || null;
643
+ if (currentTaskId && currentTaskId !== this.lastTaskId) {
644
+ this.currentConversationId = null;
645
+ this.lastTaskId = currentTaskId;
646
+ }
647
+ if (messages.length <= 1) {
648
+ this.currentConversationId = null;
649
+ }
650
+ const useConversation = Boolean(this.currentConversationId);
651
+ const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
652
+ const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
653
+ const launchOnly = options.taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
654
+ let promptText;
655
+ if (useConversation) {
656
+ let lastAssistantIndex = -1;
657
+ for (let i = messages.length - 1; i >= 0; i--) {
658
+ if (messages[i].role === 'assistant') {
659
+ lastAssistantIndex = i;
660
+ break;
661
+ }
662
+ }
663
+ const deltaMessages = lastAssistantIndex >= 0 ? messages.slice(lastAssistantIndex + 1) : messages;
664
+ promptText = this.formatDelta(deltaMessages.length > 0 ? deltaMessages : [messages[messages.length - 1]]);
665
+ }
666
+ else {
667
+ promptText = this.formatConversation(messages, options.tools);
668
+ }
669
+ // A resumed agy conversation retains its old instructions. Reassert the
670
+ // current turn's narrower scope on every call, including formatDelta turns.
671
+ if (launchOnly) {
672
+ promptText = '[Current request: open existing project only]\n' +
673
+ 'Inspect the selected project, start an existing server in the background if needed, verify readiness, and open it. ' +
674
+ 'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
675
+ 'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
676
+ }
212
677
  const modelSlug = resolveAgyModelId(this.model);
213
678
  const effort = resolveAgyEffort(this.model);
214
679
  // Standard high-performance non-blocking CLI invocation:
215
680
  // 1. stream-json output for real-time responsiveness and non-buffering progress.
216
681
  // 2. --disable-slash-commands prevents sluggish filesystem and customization scans.
217
- // 3. -p - pipes prompt from stdin to avoid OS argument length bottlenecks.
218
- // 4. --print-timeout 120s protects against unhandled deadlocks.
682
+ // 3. agy only treats stdin as a prompt in stream-json input mode. Plain text
683
+ // stdin without --print starts an interactive session and loses the task.
684
+ // Keep the prompt off the process command line by sending one user event.
685
+ // 4. --mode accept-edits lets agy create and edit workspace files in
686
+ // headless mode, where the default request-review policy cannot prompt
687
+ // and would auto-deny every write. --dangerously-skip-permissions must
688
+ // stay off: it would also grant shell commands and other host tools,
689
+ // bypassing Causyne. Native terminal/browser tools remain denied; those
690
+ // must go through Causyne XML tool calls.
691
+ // 5. Launch-only turns use a shorter limit because they should not spend
692
+ // several minutes generating code or holding a foreground server open.
693
+ // 6. --conversation links multi-turn steps to agy's local session memory to prevent re-reading files.
219
694
  const args = [
695
+ '--mode',
696
+ launchOnly ? 'plan' : 'accept-edits',
697
+ '--input-format',
698
+ 'stream-json',
220
699
  '--output-format',
221
700
  'stream-json',
222
701
  '--disable-slash-commands',
223
702
  '--print-timeout',
224
- '120s',
225
- '--dangerously-skip-permissions',
703
+ launchOnly ? '90s' : '300s',
226
704
  '--model',
227
705
  modelSlug,
228
706
  '--effort',
229
- effort,
230
- '-p',
231
- '-'
707
+ effort
232
708
  ];
709
+ if (useConversation && this.currentConversationId) {
710
+ args.push('--conversation', this.currentConversationId);
711
+ }
233
712
  return new Promise((resolve, reject) => {
234
713
  let isSettled = false;
235
714
  const child = spawn(this.command, args, {
236
- cwd: process.cwd(),
715
+ cwd: typeof options.workspaceRoot === 'string' ? options.workspaceRoot : process.cwd(),
237
716
  env: process.env,
238
717
  stdio: ['pipe', 'pipe', 'pipe'],
239
718
  windowsHide: true
@@ -242,6 +721,9 @@ export class AntigravityProvider extends LLMProvider {
242
721
  let stderrBuffer = '';
243
722
  let streamedResponse = '';
244
723
  let finalResultObj = null;
724
+ const nativeActions = [];
725
+ const attemptedNativeTools = [];
726
+ let childClosed = false;
245
727
  const cleanup = () => {
246
728
  if (options.signal) {
247
729
  options.signal.removeEventListener('abort', onAbort);
@@ -265,7 +747,7 @@ export class AntigravityProvider extends LLMProvider {
265
747
  try {
266
748
  child.kill('SIGTERM');
267
749
  setTimeout(() => {
268
- if (!child.killed)
750
+ if (!childClosed)
269
751
  child.kill('SIGKILL');
270
752
  }, 1000).unref();
271
753
  }
@@ -283,7 +765,8 @@ export class AntigravityProvider extends LLMProvider {
283
765
  }
284
766
  // Feed prompt directly into child process stdin, then close stdin
285
767
  try {
286
- child.stdin.write(promptText, 'utf8');
768
+ child.stdin.on('error', () => { });
769
+ child.stdin.write(JSON.stringify({ event: 'user', message: { content: promptText } }) + '\n', 'utf8');
287
770
  child.stdin.end();
288
771
  }
289
772
  catch (err) {
@@ -302,10 +785,70 @@ export class AntigravityProvider extends LLMProvider {
302
785
  continue;
303
786
  try {
304
787
  const event = JSON.parse(trimmed);
305
- if (event.event === 'step_update') {
788
+ if (event.event === 'init') {
789
+ if (event.conversation_id) {
790
+ this.currentConversationId = event.conversation_id;
791
+ }
792
+ }
793
+ else if (event.event === 'step_update') {
306
794
  const stepUpdate = event.step_update;
307
795
  const delta = stepUpdate?.text_delta;
308
796
  const stepType = stepUpdate?.step_type;
797
+ if (stepType === 'tool') {
798
+ const state = stepUpdate?.state;
799
+ const toolInfo = stepUpdate?.tool_info || {};
800
+ const name = stepUpdate?.tool_name || toolInfo?.name;
801
+ const status = state === 'DONE'
802
+ ? 'completed'
803
+ : (state === 'ERROR' ? 'failed' : 'running');
804
+ const rawParams = (toolInfo && typeof toolInfo === 'object' && toolInfo.parameters) ||
805
+ (stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
806
+ (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
807
+ {};
808
+ if (name) {
809
+ const existingAttempt = attemptedNativeTools.find(a => a.name === name && a.status === 'running');
810
+ if (existingAttempt) {
811
+ existingAttempt.status = status;
812
+ if (rawParams && Object.keys(rawParams).length > 0) {
813
+ existingAttempt.parameters = { ...existingAttempt.parameters, ...rawParams };
814
+ }
815
+ if (toolInfo?.error?.message)
816
+ existingAttempt.error = toolInfo.error.message;
817
+ }
818
+ else {
819
+ attemptedNativeTools.push({
820
+ name,
821
+ parameters: { ...rawParams },
822
+ status,
823
+ error: toolInfo?.error?.message,
824
+ detail: describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams })
825
+ });
826
+ }
827
+ }
828
+ if (name && (state === 'ACTIVE' || state === 'DONE' || state === 'ERROR')) {
829
+ const detail = describeNativeAction(toolInfo) || describeNativeAction({ parameters: rawParams });
830
+ const action = {
831
+ name,
832
+ status,
833
+ ...(detail ? { detail } : {})
834
+ };
835
+ if (status !== 'running') {
836
+ const existing = nativeActions.find(a => a.name === action.name && a.detail === action.detail);
837
+ if (existing)
838
+ existing.status = status;
839
+ else
840
+ nativeActions.push(action);
841
+ }
842
+ // Stream the start; completion is reported only after the
843
+ // final result has checked for denied actions.
844
+ if (status === 'running' && typeof options.onNativeAction === 'function') {
845
+ const parameters = rawParams && typeof rawParams === 'object'
846
+ ? rawParams
847
+ : {};
848
+ options.onNativeAction({ ...action, parameters });
849
+ }
850
+ }
851
+ }
309
852
  if (delta && typeof delta === 'string') {
310
853
  if (stepType === 'thought' || stepType === 'agent_thought') {
311
854
  if (typeof options.onReasoningChunk === 'function') {
@@ -322,8 +865,13 @@ export class AntigravityProvider extends LLMProvider {
322
865
  }
323
866
  else if (event.event === 'result') {
324
867
  finalResultObj = event.result;
868
+ if (event.result?.conversation_id) {
869
+ this.currentConversationId = event.result.conversation_id;
870
+ }
325
871
  }
326
872
  else if (event.status === 'ERROR') {
873
+ if (useConversation)
874
+ this.currentConversationId = null;
327
875
  safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
328
876
  return;
329
877
  }
@@ -338,17 +886,25 @@ export class AntigravityProvider extends LLMProvider {
338
886
  stderrBuffer += chunk;
339
887
  });
340
888
  child.on('error', (err) => {
889
+ if (useConversation)
890
+ this.currentConversationId = null;
341
891
  safeReject(new Error(`Antigravity Agent (agy) spawn error: ${err.message}. Make sure Antigravity CLI is installed.`));
342
892
  });
343
893
  child.on('close', (code) => {
894
+ childClosed = true;
344
895
  // Process any remaining bytes in stdoutBuffer
345
896
  if (stdoutBuffer.trim()) {
346
897
  try {
347
898
  const event = JSON.parse(stdoutBuffer.trim());
348
899
  if (event.event === 'result') {
349
900
  finalResultObj = event.result;
901
+ if (event.result?.conversation_id) {
902
+ this.currentConversationId = event.result.conversation_id;
903
+ }
350
904
  }
351
905
  else if (event.status === 'ERROR') {
906
+ if (useConversation)
907
+ this.currentConversationId = null;
352
908
  safeReject(new Error(`Antigravity Agent returned error: ${event.error || 'Unknown error'}`));
353
909
  return;
354
910
  }
@@ -357,8 +913,10 @@ export class AntigravityProvider extends LLMProvider {
357
913
  // ignore
358
914
  }
359
915
  }
360
- if (code !== 0 && !streamedResponse && !finalResultObj) {
361
- const errDetail = stderrBuffer.trim() || `exit code ${code}`;
916
+ if (code !== 0 || finalResultObj?.status === 'ERROR') {
917
+ if (useConversation)
918
+ this.currentConversationId = null;
919
+ const errDetail = finalResultObj?.error || stderrBuffer.trim() || `exit code ${code}`;
362
920
  safeReject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
363
921
  return;
364
922
  }
@@ -373,17 +931,67 @@ export class AntigravityProvider extends LLMProvider {
373
931
  const toolCalls = this.extractToolCalls(rawContent);
374
932
  // Strip tool call tags from prose so raw XML does not leak into chat display
375
933
  let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
376
- if (!content && Array.isArray(finalResultObj?.denied_actions) && finalResultObj.denied_actions.length > 0) {
377
- content = `Antigravity attempted action: ${finalResultObj.denied_actions.map((a) => a.display_name || a.action).join(', ')}`;
934
+ const deniedActions = Array.isArray(finalResultObj?.denied_actions)
935
+ ? finalResultObj.denied_actions : [];
936
+ const normalizeAction = (value) => String(value || '').toLowerCase().replace(/[^a-z0-9]/g, '');
937
+ const deniedNames = new Set(deniedActions.flatMap(action => [normalizeAction(action?.action), normalizeAction(action?.display_name)]).filter(Boolean));
938
+ for (const action of nativeActions) {
939
+ if (deniedNames.has(normalizeAction(action.name)))
940
+ action.status = 'failed';
941
+ if (typeof options.onNativeAction === 'function') {
942
+ const attempt = [...attemptedNativeTools].reverse().find(candidate => normalizeAction(candidate.name) === normalizeAction(action.name));
943
+ options.onNativeAction({ ...action, parameters: attempt?.parameters || {} });
944
+ }
945
+ }
946
+ if (deniedActions.length > 0) {
947
+ const unmapped = [];
948
+ for (const denied of deniedActions) {
949
+ const name = String(denied?.action || denied?.display_name || 'unknown');
950
+ const attempt = [...attemptedNativeTools].reverse().find(candidate => normalizeAction(candidate.name) === normalizeAction(name)
951
+ || normalizeAction(candidate.name) === normalizeAction(denied?.display_name));
952
+ const parameters = {
953
+ ...(attempt?.parameters || {}),
954
+ ...(denied?.parameters || {}),
955
+ ...(attempt?.detail ? { detail: attempt.detail } : {})
956
+ };
957
+ const mapped = mapNativeToolToCausyne(attempt?.name || String(denied?.display_name || name), parameters, toolCalls.length);
958
+ if (!mapped) {
959
+ unmapped.push(String(denied?.display_name || name));
960
+ continue;
961
+ }
962
+ if (!toolCalls.some(call => call.function.name === mapped.function.name
963
+ && call.function.arguments === mapped.function.arguments)) {
964
+ toolCalls.push(mapped);
965
+ }
966
+ }
967
+ if (unmapped.length > 0) {
968
+ const error = new Error(`Antigravity could not perform: ${unmapped.join(', ')}. The denied action had no safe Causyne tool mapping.`);
969
+ error.code = 'AGY_NATIVE_ACTION_DENIED';
970
+ safeReject(error);
971
+ return;
972
+ }
973
+ // Any prose produced alongside a denied action may claim work that
974
+ // did not occur. Wait for the mapped Causyne tool result instead.
975
+ content = '';
976
+ }
977
+ const completedNativeActions = nativeActions.filter((a) => a.status === 'completed');
978
+ if (!content && completedNativeActions.length > 0) {
979
+ content = `Antigravity completed: ${completedNativeActions
980
+ .map((a) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`)
981
+ .join(', ')}`;
378
982
  }
379
983
  if (!content && toolCalls.length === 0) {
380
- content = 'Turn completed by Antigravity Agent.';
984
+ const detail = stderrBuffer.trim();
985
+ safeReject(new Error(detail
986
+ ? `Antigravity returned no response: ${detail}`
987
+ : 'Antigravity returned no response.'));
988
+ return;
381
989
  }
382
990
  const promptTokens = Number(finalResultObj?.usage?.input_tokens) || Math.ceil(promptText.length / 4);
383
991
  const completionTokens = Number(finalResultObj?.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
384
992
  const thinkingTokens = Number(finalResultObj?.usage?.thinking_tokens) || 0;
385
993
  const response = {
386
- content: content || (toolCalls.length > 0 ? '' : 'Turn completed by Antigravity Agent.'),
994
+ content,
387
995
  usage: {
388
996
  promptTokens,
389
997
  completionTokens: completionTokens + thinkingTokens,
@@ -396,12 +1004,15 @@ export class AntigravityProvider extends LLMProvider {
396
1004
  if (toolCalls.length > 0) {
397
1005
  response.toolCalls = toolCalls;
398
1006
  }
1007
+ if (nativeActions.length > 0) {
1008
+ response.externalActions = nativeActions.filter((a) => a.status !== 'running');
1009
+ }
399
1010
  safeResolve(response);
400
1011
  });
401
1012
  });
402
1013
  }
403
1014
  async chat(messages, options = {}) {
404
- const maxRetries = options.maxRetries ?? 2;
1015
+ const maxRetries = options.maxRetries ?? (options.taskIntent === 'launch' ? 1 : 2);
405
1016
  let attempt = 0;
406
1017
  while (attempt <= maxRetries) {
407
1018
  try {