@causyne/agent 1.20.8 → 1.20.10

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 (74) hide show
  1. package/package.json +2 -1
  2. package/src/agentLoop.js +291 -103
  3. package/src/agentLoop.ts +322 -109
  4. package/src/browser/causyneBrowser.js +36 -0
  5. package/src/browser/causyneBrowser.ts +36 -1
  6. package/src/commands.js +25 -0
  7. package/src/compiledSkills.js +7330 -319
  8. package/src/computerUse/types.js +8 -0
  9. package/src/computerUse/types.ts +121 -0
  10. package/src/computerUse/visionGrounding.js +87 -29
  11. package/src/computerUse/visionGrounding.ts +108 -36
  12. package/src/contextManager.js +16 -0
  13. package/src/decisionPolicy.js +7 -9
  14. package/src/decisionPolicy.ts +7 -9
  15. package/src/documentEngine/antiSlopAuditor.js +13 -43
  16. package/src/documentEngine/antiSlopAuditor.ts +15 -47
  17. package/src/documentEngine/documentForge.js +3 -3
  18. package/src/documentEngine/documentForge.ts +3 -3
  19. package/src/launchIntent.js +3 -3
  20. package/src/launchIntent.ts +3 -3
  21. package/src/planCache.js +4 -14
  22. package/src/planCache.ts +4 -14
  23. package/src/providers/acp.js +4 -2
  24. package/src/providers/acp.ts +4 -2
  25. package/src/providers/antigravity.js +191 -28
  26. package/src/providers/antigravity.ts +192 -27
  27. package/src/providers/base.d.ts +2 -0
  28. package/src/providers/pi.js +3 -1
  29. package/src/providers/pi.ts +4 -2
  30. package/src/provisioning/capabilityProvisioner.js +2 -7
  31. package/src/provisioning/npmInstall.js +19 -0
  32. package/src/provisioning/npmInstall.ts +19 -0
  33. package/src/sandbox.js +7 -10
  34. package/src/smartToolsUse.js +223 -0
  35. package/src/smartToolsUse.ts +284 -0
  36. package/src/stallGuard.js +356 -0
  37. package/src/stallGuard.ts +432 -0
  38. package/src/taskShape.js +7 -7
  39. package/src/taskShape.ts +7 -7
  40. package/src/toolPacks.js +5 -5
  41. package/src/tools/blenderAutomator.js +198 -11
  42. package/src/tools/browserAutomator.js +3 -3
  43. package/src/tools/browserAutomator.ts +3 -3
  44. package/src/tools/documentForge.js +1 -1
  45. package/src/tools/documentForge.ts +1 -1
  46. package/src/tools/fsRead.js +91 -80
  47. package/src/tools/fsRead.ts +125 -0
  48. package/src/tools/peerAgent.js +1 -1
  49. package/src/tools/peerAgent.ts +1 -1
  50. package/src/tools/screenshot.js +5 -1
  51. package/src/tools/screenshot.ts +5 -1
  52. package/src/tools/toolScanner.js +19 -0
  53. package/src/tools/toolScanner.ts +17 -0
  54. package/src/tools/toolSelfRepair.js +63 -1
  55. package/src/tools/toolSelfRepair.ts +61 -1
  56. package/src/tools/visionInspector.js +80 -142
  57. package/src/tools/visionInspector.ts +110 -0
  58. package/src/tui/chatboxClipboard.js +152 -0
  59. package/src/tui/chatboxClipboard.ts +201 -0
  60. package/src/tui/clipboardSync.js +38 -7
  61. package/src/tui/clipboardSync.ts +39 -7
  62. package/src/tui/codeProgress.js +89 -18
  63. package/src/tui/codeProgress.ts +102 -17
  64. package/src/tui/codeStreamRenderer.js +7 -2
  65. package/src/tui/codeStreamRenderer.ts +7 -2
  66. package/src/tui/composerControls.js +9 -0
  67. package/src/tui/composerControls.ts +9 -0
  68. package/src/tui/dialogs.js +8 -3
  69. package/src/tui/diff.d.ts +1 -0
  70. package/src/tui/lineEditor.js +166 -14
  71. package/src/tui/mouseHover.js +6 -2
  72. package/src/tui/mouseHover.ts +7 -2
  73. package/src/tui/prompt.js +96 -19
  74. package/src/tui/stageSurface.js +3 -1
@@ -0,0 +1,125 @@
1
+ import fs from 'node:fs';
2
+ import readline from 'node:readline';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+
6
+ export interface FsReadArgs {
7
+ path: string;
8
+ startLine?: number;
9
+ endLine?: number;
10
+ }
11
+
12
+ export interface FsReadResult {
13
+ success: boolean;
14
+ output?: string;
15
+ error?: string;
16
+ isBinary?: boolean;
17
+ }
18
+
19
+ const BINARY_EXTENSIONS = /\.(png|jpe?g|webp|gif|svg|bmp|ico|blend\d?|glb|gltf|wasm|zip|tar|gz|bz2|xz|7z|rar|mp4|mov|avi|mkv|webm|mp3|wav|ogg|flac|aac|m4a|pdf|exe|dll|dylib|so|bin|iso|dmg)$/i;
20
+
21
+ /** Fast Binary Detection: inspect the first 1024 bytes for a null byte. */
22
+ async function isBinary(filePath: string): Promise<boolean> {
23
+ try {
24
+ const fd = await fs.promises.open(filePath, 'r');
25
+ const buffer = Buffer.alloc(1024);
26
+ const { bytesRead } = await fd.read(buffer, 0, 1024, 0);
27
+ await fd.close();
28
+
29
+ for (let i = 0; i < bytesRead; i++) {
30
+ if (buffer[i] === 0) return true;
31
+ }
32
+ return false;
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ export const fsRead = {
39
+ schema: {
40
+ name: 'fs.read',
41
+ description: 'Read file contents intelligently. Automatically pages large files to protect Context Window.',
42
+ parameters: {
43
+ type: 'object',
44
+ properties: {
45
+ path: { type: 'string' },
46
+ startLine: { type: 'number' },
47
+ endLine: { type: 'number' }
48
+ },
49
+ required: ['path']
50
+ }
51
+ },
52
+
53
+ async execute(args: FsReadArgs): Promise<FsReadResult> {
54
+ try {
55
+ if (!args || typeof args.path !== 'string' || !args.path.trim()) {
56
+ return { success: false, error: 'Missing required parameter: path' };
57
+ }
58
+
59
+ const target = args.path.replace(/^~\//, os.homedir() + '/');
60
+
61
+ if (!fs.existsSync(target)) {
62
+ return { success: false, error: 'File does not exist.' };
63
+ }
64
+
65
+ const ext = path.extname(target).toLowerCase();
66
+ const isKnownBinaryExt = BINARY_EXTENSIONS.test(ext);
67
+
68
+ // Fast check for binary media/executables to prevent token context blowup
69
+ if (isKnownBinaryExt || (await isBinary(target))) {
70
+ let stat: fs.Stats | null = null;
71
+ try {
72
+ stat = fs.statSync(target);
73
+ } catch {
74
+ // ignore stat error
75
+ }
76
+ const sizeStr = stat ? `${(stat.size / 1024).toFixed(1)} KB` : 'unknown size';
77
+ const isImage = /\.(png|jpe?g|webp|gif|svg|bmp|ico)$/i.test(ext);
78
+
79
+ return {
80
+ success: false,
81
+ isBinary: true,
82
+ error: isImage
83
+ ? `Cannot read image file '${path.basename(target)}' as plain text. Use view_image (or vision inspection). File metadata: ${sizeStr}, format: ${ext.replace('.', '').toUpperCase() || 'IMAGE'}.`
84
+ : `Cannot read binary file '${path.basename(target)}' as plain text. File size: ${sizeStr}.`
85
+ };
86
+ }
87
+
88
+ const start = typeof args.startLine === 'number' && args.startLine > 0 ? Math.floor(args.startLine) : 1;
89
+ let end = typeof args.endLine === 'number' && args.endLine >= start ? Math.floor(args.endLine) : start + 799;
90
+
91
+ // Mandatory Paging Limit: at most 800 lines per read to preserve context
92
+ if (end - start + 1 > 800) {
93
+ end = start + 799;
94
+ }
95
+
96
+ let currentLine = 1;
97
+ const outputLines: string[] = [];
98
+ let totalLines = 0;
99
+
100
+ const rl = readline.createInterface({
101
+ input: fs.createReadStream(target),
102
+ crlfDelay: Infinity
103
+ });
104
+
105
+ for await (const line of rl) {
106
+ totalLines++;
107
+ if (currentLine >= start && currentLine <= end) {
108
+ outputLines.push(line);
109
+ }
110
+ currentLine++;
111
+ }
112
+
113
+ let finalOutput = outputLines.join('\n');
114
+
115
+ if (totalLines > end) {
116
+ finalOutput += `\n\n[WARNING: File truncated at line ${end} out of ${totalLines}. Use { startLine: ${end + 1}, endLine: ${end + 800} } to read more.]`;
117
+ }
118
+
119
+ return { success: true, output: finalOutput };
120
+ } catch (e: unknown) {
121
+ const msg = e instanceof Error ? e.message : String(e);
122
+ return { success: false, error: msg };
123
+ }
124
+ }
125
+ };
@@ -13,7 +13,7 @@ import { AcpClient } from '../acp/client.js';
13
13
  import { getPeerProfile, listAllPeers, peerEnvironment } from '../acp/peerProfiles.js';
14
14
  import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
15
15
  const execFileAsync = promisify(execFile);
16
- const MAX_PROMPT_CHARS = 100_000;
16
+ const MAX_PROMPT_CHARS = 2_000_000;
17
17
  const READ_ONLY_KINDS = new Set(['read', 'search', 'fetch', 'think']);
18
18
  function selectPermission(profile, request, workspaceRoot) {
19
19
  const kind = request.toolCall.kind;
@@ -27,7 +27,7 @@ export interface PeerAgentArgs {
27
27
  mode?: string;
28
28
  }
29
29
 
30
- const MAX_PROMPT_CHARS = 100_000;
30
+ const MAX_PROMPT_CHARS = 2_000_000;
31
31
  const READ_ONLY_KINDS = new Set(['read', 'search', 'fetch', 'think']);
32
32
 
33
33
  function selectPermission(
@@ -50,7 +50,11 @@ export const screenshot = {
50
50
  };
51
51
  }
52
52
  catch (error) {
53
- return { success: false, error: `Screen capture failed: ${error instanceof Error ? error.message : String(error)}` };
53
+ const reason = error instanceof Error ? error.message : String(error);
54
+ const guidance = process.platform === 'darwin' && /could not create image from display/i.test(reason)
55
+ ? ' macOS could not capture the display. Check Screen Recording access for the terminal app and that a display session is available; then restart the terminal.'
56
+ : '';
57
+ return { success: false, error: `Screen capture failed: ${reason}.${guidance}` };
54
58
  }
55
59
  finally {
56
60
  await fs.rm(tempDir, { recursive: true, force: true });
@@ -62,7 +62,11 @@ export const screenshot = {
62
62
  filename: 'desktop screenshot'
63
63
  };
64
64
  } catch (error) {
65
- return { success: false, error: `Screen capture failed: ${error instanceof Error ? error.message : String(error)}` };
65
+ const reason = error instanceof Error ? error.message : String(error);
66
+ const guidance = process.platform === 'darwin' && /could not create image from display/i.test(reason)
67
+ ? ' macOS could not capture the display. Check Screen Recording access for the terminal app and that a display session is available; then restart the terminal.'
68
+ : '';
69
+ return { success: false, error: `Screen capture failed: ${reason}.${guidance}` };
66
70
  } finally {
67
71
  await fs.rm(tempDir, { recursive: true, force: true });
68
72
  }
@@ -240,6 +240,8 @@ export function scanAndAdaptToolsForProvider(tools, provider, options = {}) {
240
240
  const isGemini = normProvider === 'gemini';
241
241
  const isAnthropic = normProvider === 'anthropic';
242
242
  const isOllama = normProvider === 'ollama';
243
+ const isAntigravity = normProvider === 'antigravity' || normProvider === 'agy';
244
+ const isAcp = normProvider.startsWith('acp');
243
245
  for (let index = 0; index < tools.length; index++) {
244
246
  const t = tools[index];
245
247
  if (!t)
@@ -289,6 +291,23 @@ export function scanAndAdaptToolsForProvider(tools, provider, options = {}) {
289
291
  else if (isOllama) {
290
292
  adaptedTools.push(adaptSchemaForOllama(toolObj));
291
293
  }
294
+ else if (isAntigravity) {
295
+ const cleanParams = cleanUnionTypes(rawSchema || { type: 'object', properties: {} });
296
+ adaptedTools.push({
297
+ name,
298
+ description: toolObj.description || '',
299
+ parameters: cleanParams,
300
+ snippet: `<tool_call>{"name": "${name}", "arguments": { ... }}</tool_call>`
301
+ });
302
+ }
303
+ else if (isAcp) {
304
+ const cleanParams = cleanUnionTypes(rawSchema || { type: 'object', properties: {} });
305
+ adaptedTools.push({
306
+ name,
307
+ description: toolObj.description || '',
308
+ inputSchema: cleanParams
309
+ });
310
+ }
292
311
  else {
293
312
  // Default to OpenAI / OpenAI-Compatible (DeepSeek, XAI, Mistral, etc.)
294
313
  adaptedTools.push(adaptSchemaForOpenAI(toolObj));
@@ -328,6 +328,8 @@ export function scanAndAdaptToolsForProvider(
328
328
  const isGemini = normProvider === 'gemini';
329
329
  const isAnthropic = normProvider === 'anthropic';
330
330
  const isOllama = normProvider === 'ollama';
331
+ const isAntigravity = normProvider === 'antigravity' || normProvider === 'agy';
332
+ const isAcp = normProvider.startsWith('acp');
331
333
 
332
334
  for (let index = 0; index < tools.length; index++) {
333
335
  const t = tools[index];
@@ -381,6 +383,21 @@ export function scanAndAdaptToolsForProvider(
381
383
  adaptedTools.push(adaptSchemaForAnthropic(toolObj, { deferLoading }));
382
384
  } else if (isOllama) {
383
385
  adaptedTools.push(adaptSchemaForOllama(toolObj));
386
+ } else if (isAntigravity) {
387
+ const cleanParams = cleanUnionTypes(rawSchema || { type: 'object', properties: {} }) as Record<string, unknown>;
388
+ adaptedTools.push({
389
+ name,
390
+ description: toolObj.description || '',
391
+ parameters: cleanParams,
392
+ snippet: `<tool_call>{"name": "${name}", "arguments": { ... }}</tool_call>`
393
+ });
394
+ } else if (isAcp) {
395
+ const cleanParams = cleanUnionTypes(rawSchema || { type: 'object', properties: {} }) as Record<string, unknown>;
396
+ adaptedTools.push({
397
+ name,
398
+ description: toolObj.description || '',
399
+ inputSchema: cleanParams
400
+ });
384
401
  } else {
385
402
  // Default to OpenAI / OpenAI-Compatible (DeepSeek, XAI, Mistral, etc.)
386
403
  adaptedTools.push(adaptSchemaForOpenAI(toolObj));
@@ -8,6 +8,9 @@
8
8
  */
9
9
  import path from 'node:path';
10
10
  import os from 'node:os';
11
+ import fs from 'node:fs';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { randomUUID } from 'node:crypto';
11
14
  /**
12
15
  * Universal tool name alias dictionary. Maps hallucinations from OpenAI,
13
16
  * Anthropic, DeepSeek, Qwen, Ollama, etc. to Causyne Agent canonical tool names.
@@ -103,6 +106,18 @@ export const TOOL_NAME_ALIASES = {
103
106
  codeSearchAst: 'code_search_ast',
104
107
  codeSearcher: 'code_search_ripgrep',
105
108
  blenderAutomator: 'blender_act',
109
+ blender_automator: 'blender_act',
110
+ blender: 'blender_act',
111
+ blender_act: 'blender_act',
112
+ blender_batch: 'blender_act',
113
+ blender_render: 'blender_act',
114
+ blenderAct: 'blender_act',
115
+ render_3d: 'blender_act',
116
+ viewImage: 'view_image',
117
+ view_image: 'view_image',
118
+ show_image: 'view_image',
119
+ inspect_image: 'view_image',
120
+ open_image: 'view_image',
106
121
  resolveAutomator: 'resolve_act',
107
122
  palmierAutomator: 'palmier_act',
108
123
  godotAutomator: 'godot_act',
@@ -798,6 +813,48 @@ export function normalizePaths(args, cwd = process.cwd()) {
798
813
  repairs
799
814
  };
800
815
  }
816
+ function repairBrowserActions(args, cwd) {
817
+ const repairs = [];
818
+ let workspace;
819
+ try {
820
+ workspace = fs.realpathSync.native(cwd);
821
+ }
822
+ catch {
823
+ return { args, repaired: false, repairs };
824
+ }
825
+ const repairAction = (value) => {
826
+ if (!value || typeof value !== 'object' || Array.isArray(value))
827
+ return value;
828
+ const action = { ...value };
829
+ const actionType = typeof action.type === 'string' ? 'type' : 'action';
830
+ if ((action[actionType] === 'goto' || action[actionType] === 'navigate' || action[actionType] === 'open')
831
+ && typeof action.url === 'string' && action.url.startsWith('file:')) {
832
+ try {
833
+ const target = fs.realpathSync.native(fileURLToPath(action.url));
834
+ const relative = path.relative(workspace, target);
835
+ if (relative && !relative.startsWith(`..${path.sep}`) && relative !== '..'
836
+ && !path.isAbsolute(relative) && /\.html?$/i.test(target)) {
837
+ action[actionType] = 'preview';
838
+ action.filePath = relative;
839
+ delete action.url;
840
+ repairs.push('Converted workspace HTML file navigation to browser preview');
841
+ }
842
+ }
843
+ catch {
844
+ // Leave malformed or out-of-scope URLs for the browser sandbox to reject.
845
+ }
846
+ }
847
+ if (action[actionType] === 'screenshot' && !action.outputFile) {
848
+ action.outputFile = `browser-capture-${randomUUID()}.png`;
849
+ repairs.push('Added a unique workspace screenshot destination');
850
+ }
851
+ return action;
852
+ };
853
+ const updated = Array.isArray(args.actions)
854
+ ? { ...args, actions: args.actions.map(repairAction) }
855
+ : repairAction(args);
856
+ return { args: updated, repaired: repairs.length > 0, repairs };
857
+ }
801
858
  /**
802
859
  * Master self-repair entrypoint: heals raw tool call JSON, canonicalizes tool names,
803
860
  * resolves aliases, coerces argument types, and normalizes paths.
@@ -833,9 +890,14 @@ export function selfRepairToolCall(toolCall, toolSchema, options = {}) {
833
890
  // 4. Normalize filesystem paths
834
891
  const pathResult = normalizePaths(typeResult.args, options.cwd || process.cwd());
835
892
  allRepairs.push(...pathResult.repairs);
893
+ const browserResult = canonicalName === 'browser_act'
894
+ ? repairBrowserActions(pathResult.args, options.cwd || process.cwd())
895
+ : pathResult;
896
+ if (canonicalName === 'browser_act')
897
+ allRepairs.push(...browserResult.repairs);
836
898
  return {
837
899
  name: canonicalName,
838
- args: pathResult.args,
900
+ args: browserResult.args,
839
901
  repaired: allRepairs.length > 0,
840
902
  repairs: allRepairs
841
903
  };
@@ -9,6 +9,9 @@
9
9
 
10
10
  import path from 'node:path';
11
11
  import os from 'node:os';
12
+ import fs from 'node:fs';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { randomUUID } from 'node:crypto';
12
15
 
13
16
  export interface RepairResult {
14
17
  args: Record<string, unknown>;
@@ -132,6 +135,18 @@ export const TOOL_NAME_ALIASES: Record<string, string> = {
132
135
  codeSearchAst: 'code_search_ast',
133
136
  codeSearcher: 'code_search_ripgrep',
134
137
  blenderAutomator: 'blender_act',
138
+ blender_automator: 'blender_act',
139
+ blender: 'blender_act',
140
+ blender_act: 'blender_act',
141
+ blender_batch: 'blender_act',
142
+ blender_render: 'blender_act',
143
+ blenderAct: 'blender_act',
144
+ render_3d: 'blender_act',
145
+ viewImage: 'view_image',
146
+ view_image: 'view_image',
147
+ show_image: 'view_image',
148
+ inspect_image: 'view_image',
149
+ open_image: 'view_image',
135
150
  resolveAutomator: 'resolve_act',
136
151
  palmierAutomator: 'palmier_act',
137
152
  godotAutomator: 'godot_act',
@@ -854,6 +869,46 @@ export function normalizePaths(
854
869
  };
855
870
  }
856
871
 
872
+ function repairBrowserActions(args: Record<string, unknown>, cwd: string): RepairResult {
873
+ const repairs: string[] = [];
874
+ let workspace: string;
875
+ try {
876
+ workspace = fs.realpathSync.native(cwd);
877
+ } catch {
878
+ return { args, repaired: false, repairs };
879
+ }
880
+ const repairAction = (value: unknown): unknown => {
881
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
882
+ const action = { ...(value as Record<string, unknown>) };
883
+ const actionType = typeof action.type === 'string' ? 'type' : 'action';
884
+ if ((action[actionType] === 'goto' || action[actionType] === 'navigate' || action[actionType] === 'open')
885
+ && typeof action.url === 'string' && action.url.startsWith('file:')) {
886
+ try {
887
+ const target = fs.realpathSync.native(fileURLToPath(action.url));
888
+ const relative = path.relative(workspace, target);
889
+ if (relative && !relative.startsWith(`..${path.sep}`) && relative !== '..'
890
+ && !path.isAbsolute(relative) && /\.html?$/i.test(target)) {
891
+ action[actionType] = 'preview';
892
+ action.filePath = relative;
893
+ delete action.url;
894
+ repairs.push('Converted workspace HTML file navigation to browser preview');
895
+ }
896
+ } catch {
897
+ // Leave malformed or out-of-scope URLs for the browser sandbox to reject.
898
+ }
899
+ }
900
+ if (action[actionType] === 'screenshot' && !action.outputFile) {
901
+ action.outputFile = `browser-capture-${randomUUID()}.png`;
902
+ repairs.push('Added a unique workspace screenshot destination');
903
+ }
904
+ return action;
905
+ };
906
+ const updated = Array.isArray(args.actions)
907
+ ? { ...args, actions: args.actions.map(repairAction) }
908
+ : repairAction(args) as Record<string, unknown>;
909
+ return { args: updated, repaired: repairs.length > 0, repairs };
910
+ }
911
+
857
912
  /**
858
913
  * Master self-repair entrypoint: heals raw tool call JSON, canonicalizes tool names,
859
914
  * resolves aliases, coerces argument types, and normalizes paths.
@@ -903,9 +958,14 @@ export function selfRepairToolCall(
903
958
  const pathResult = normalizePaths(typeResult.args, options.cwd || process.cwd());
904
959
  allRepairs.push(...pathResult.repairs);
905
960
 
961
+ const browserResult = canonicalName === 'browser_act'
962
+ ? repairBrowserActions(pathResult.args, options.cwd || process.cwd())
963
+ : pathResult;
964
+ if (canonicalName === 'browser_act') allRepairs.push(...browserResult.repairs);
965
+
906
966
  return {
907
967
  name: canonicalName,
908
- args: pathResult.args,
968
+ args: browserResult.args,
909
969
  repaired: allRepairs.length > 0,
910
970
  repairs: allRepairs
911
971
  };
@@ -1,154 +1,92 @@
1
- import fs from 'fs/promises';
2
- import fsSync from 'fs';
3
- import path from 'path';
4
- import { execFile } from 'child_process';
5
- import { promisify } from 'util';
6
-
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
7
6
  import { ensureCapability, loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
8
-
9
7
  const execFileAsync = promisify(execFile);
10
-
11
- // Helper: Sovereign Workspace Buffer to prevent /tmp/ boundary errors
12
- function getWorkspaceTempDir() {
13
- const dir = path.join(process.cwd(), '.tmp_causyne_3d');
14
- if (!fsSync.existsSync(dir)) {
15
- fsSync.mkdirSync(dir, { recursive: true });
16
- }
17
- return dir;
18
- }
19
-
20
8
  export const visionInspector = {
21
- schema: {
22
- name: 'vision.inspect_ui',
23
- description: 'Captures live desktop (macOS/Windows) or mobile (Android via ADB) screenshots directly into the local workspace buffer (.tmp_causyne_3d/) and extracts spatial bounding box coordinates for visual layout verification, LCP debugging, and UI automation.',
24
- parameters: {
25
- type: 'object',
26
- properties: {
27
- target: {
28
- type: 'string',
29
- enum: ['desktop', 'android_adb'],
30
- description: 'Target device screen to capture: desktop (OS GUI) or android_adb (connected mobile screen).'
31
- },
32
- prompt: { type: 'string', description: 'The verification prompt describing what UI element, visual bug, alignment, or LCP state is being audited.' },
33
- deviceSerial: { type: 'string', description: 'Optional Android ADB device serial when target is android_adb.' }
34
- },
35
- required: ['target', 'prompt']
36
- }
37
- },
38
-
39
- async execute(args, context = {}) {
40
- try {
41
- const target = args.target || 'desktop';
42
- const prompt = args.prompt || 'Inspect UI spatial layout';
43
- const tempDir = getWorkspaceTempDir();
44
- const timestamp = Date.now();
45
- const destPath = path.join(tempDir, `ui_inspect_${target}_${timestamp}.png`);
46
-
47
- if (target === 'android_adb') {
48
- const adbArgs = [];
49
- if (args.deviceSerial) adbArgs.push('-s', args.deviceSerial);
50
- adbArgs.push('shell', 'screencap', '-p');
51
-
52
- try {
53
- const { stdout } = await execFileAsync('adb', adbArgs, { encoding: 'buffer', maxBuffer: 20 * 1024 * 1024 });
54
- // Handle CRLF on Windows ADB pipes
55
- let cleanBuffer = stdout;
56
- if (process.platform === 'win32') {
57
- cleanBuffer = Buffer.from(stdout.toString('binary').replace(/\r\n/g, '\n'), 'binary');
58
- }
59
- await fs.writeFile(destPath, cleanBuffer);
60
- } catch (adbErr) {
61
- return {
62
- success: false,
63
- error: `ADB Mobile Vision Capture Failed: ${adbErr.message}. Ensure device is connected via ADB USB/WiFi.`
64
- };
9
+ schema: {
10
+ name: 'vision.inspect_ui',
11
+ description: 'Capture a live desktop or Android screen and pass its pixels to a vision-capable model. OCR coordinates are included when the OCR capability is available. A capture failure is not visual verification.',
12
+ parameters: {
13
+ type: 'object',
14
+ properties: {
15
+ target: { type: 'string', enum: ['desktop', 'android_adb'] },
16
+ prompt: { type: 'string', description: 'What to inspect in the captured UI.' },
17
+ deviceSerial: { type: 'string', description: 'Optional Android ADB device serial.' }
18
+ },
19
+ required: ['target', 'prompt']
20
+ }
21
+ },
22
+ async execute(args) {
23
+ const target = args.target;
24
+ if (target !== 'desktop' && target !== 'android_adb') {
25
+ return { success: false, error: 'target must be desktop or android_adb' };
65
26
  }
66
- } else {
67
- // Desktop OS Screen Capture
27
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'causyne-vision-inspect-'));
28
+ const imagePath = path.join(tempDir, 'screen.png');
68
29
  try {
69
- if (process.platform === 'darwin') {
70
- await execFileAsync('screencapture', ['-x', destPath]);
71
- } else if (process.platform === 'win32') {
72
- const psCmd = `Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $screen = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds; $bitmap = New-Object System.Drawing.Bitmap $screen.Width, $screen.Height; $graphics = [System.Drawing.Graphics]::FromImage($bitmap); $graphics.CopyFromScreen($screen.Location, [System.Drawing.Point]::Empty, $screen.Size); $bitmap.Save('${destPath.replace(/\\/g, '\\\\')}', [System.Drawing.Imaging.ImageFormat]::Png); $graphics.Dispose(); $bitmap.Dispose();`;
73
- await execFileAsync('powershell.exe', ['-NoLogo', '-NoProfile', '-Command', psCmd]);
74
- } else {
75
- // macOS and Windows capture natively above; only this branch needs
76
- // the provisioned package.
77
- const vision = await ensureCapability('vision');
78
- if (!vision.ok) throw new Error(vision.reason);
79
- const screenshotDesktop = await loadCapabilityPackage('screenshot-desktop');
80
- await screenshotDesktop({ filename: destPath });
81
- }
82
- } catch (captureErr) {
83
-
84
- if (captureErr.message && (captureErr.message.includes('could not create image from display') || captureErr.message.includes('No display') || captureErr.message.includes('xclip'))) {
85
- // Check if any existing buffer image exists in tempDir to inspect
86
- const existingFiles = fsSync.readdirSync(tempDir).filter(f => f.endsWith('.png'));
87
- if (existingFiles.length > 0) {
88
- const fallbackFile = path.join(tempDir, existingFiles[existingFiles.length - 1]);
89
- return {
90
- success: true,
91
- output: JSON.stringify({
92
- status: 'Headless environment detected: GUI capture restricted. Returned latest buffered workspace visual frame.',
93
- target_device: target,
94
- verification_prompt: prompt,
95
- filepath: fallbackFile,
96
- workspace_boundary_safe: true,
97
- headless_notice: captureErr.message
98
- }, null, 2)
99
- };
30
+ if (target === 'android_adb') {
31
+ const adbArgs = args.deviceSerial ? ['-s', args.deviceSerial] : [];
32
+ const { stdout } = await execFileAsync('adb', [...adbArgs, 'shell', 'screencap', '-p'], {
33
+ encoding: 'buffer', maxBuffer: 20 * 1024 * 1024
34
+ });
35
+ const bytes = process.platform === 'win32'
36
+ ? Buffer.from(stdout.toString('binary').replace(/\r\n/g, '\n'), 'binary')
37
+ : stdout;
38
+ await fs.writeFile(imagePath, bytes);
39
+ }
40
+ else {
41
+ const vision = await ensureCapability('vision');
42
+ if (!vision.ok)
43
+ return { success: false, error: vision.reason, requiresConsent: vision.requiresConsent };
44
+ const capture = await loadCapabilityPackage('screenshot-desktop');
45
+ await capture({ filename: imagePath });
46
+ }
47
+ const bytes = await fs.readFile(imagePath);
48
+ if (bytes.length === 0 || bytes.length > 20 * 1024 * 1024) {
49
+ return { success: false, error: 'Captured image is empty or exceeds 20 MB' };
50
+ }
51
+ let ocrOutput = 'OCR was not available for this capture.';
52
+ try {
53
+ const ocr = await ensureCapability('ocr');
54
+ if (ocr.ok) {
55
+ const tesseract = await loadCapabilityPackage('tesseract.js');
56
+ const worker = await tesseract.createWorker('eng');
57
+ try {
58
+ const recognized = await worker.recognize(imagePath);
59
+ const words = (recognized.data?.words ?? []).filter(word => word.confidence > 75).slice(0, 30);
60
+ ocrOutput = words.length > 0
61
+ ? words.map(word => `- [${word.text}] X:${Math.floor((word.bbox.x0 + word.bbox.x1) / 2)}, Y:${Math.floor((word.bbox.y0 + word.bbox.y1) / 2)}`).join('\n')
62
+ : 'No confident OCR text tokens detected.';
63
+ }
64
+ finally {
65
+ await worker.terminate();
66
+ }
67
+ }
68
+ }
69
+ catch (error) {
70
+ ocrOutput = `OCR unavailable: ${error instanceof Error ? error.message : String(error)}`;
100
71
  }
101
72
  return {
102
- success: true,
103
- output: JSON.stringify({
104
- status: 'Live GUI capture is unavailable in this desktop session. Connect an active display or use an ADB mobile target.',
105
- target_device: target,
106
- verification_prompt: prompt,
107
- headless_notice: captureErr.message
108
- }, null, 2)
73
+ success: true,
74
+ _is_image_marker: true,
75
+ mimeType: 'image/png',
76
+ base64: bytes.toString('base64'),
77
+ filename: `${target} screenshot`,
78
+ output: `Capture prompt: ${args.prompt}\n${ocrOutput}`
109
79
  };
110
- }
111
- throw captureErr;
112
80
  }
113
- }
114
-
115
- // Check spatial OCR / bounding box extraction
116
- let textMap = '';
117
- try {
118
- const ocr = await ensureCapability('ocr');
119
- if (!ocr.ok) throw new Error(ocr.reason);
120
- const Tesseract = await loadCapabilityPackage('tesseract.js');
121
- const worker = await Tesseract.createWorker('eng');
122
- const { data: { words } } = await worker.recognize(destPath);
123
- await worker.terminate();
124
-
125
- const confidentWords = (words || []).filter(w => w.confidence > 75).slice(0, 30);
126
- if (confidentWords.length > 0) {
127
- textMap = confidentWords.map(w => {
128
- const centerX = Math.floor((w.bbox.x0 + w.bbox.x1) / 2);
129
- const centerY = Math.floor((w.bbox.y0 + w.bbox.y1) / 2);
130
- return `- [${w.text}] X:${centerX}, Y:${centerY}`;
131
- }).join('\n');
81
+ catch (error) {
82
+ const reason = error instanceof Error ? error.message : String(error);
83
+ const guidance = process.platform === 'darwin' && /could not create image from display/i.test(reason)
84
+ ? ' macOS could not capture the display. Check Screen Recording access for the terminal app and that a display session is available; then restart the terminal.'
85
+ : '';
86
+ return { success: false, error: `Live screen capture failed: ${reason}.${guidance}` };
87
+ }
88
+ finally {
89
+ await fs.rm(tempDir, { recursive: true, force: true });
132
90
  }
133
- } catch (ocrErr) {
134
- textMap = `[OCR Text Bounding extraction skipped: ${ocrErr.message}]`;
135
- }
136
-
137
- // Route notification to mobile app (`AgentScreen.kt`)
138
-
139
- return {
140
- success: true,
141
- output: JSON.stringify({
142
- status: 'Visual inspection frame captured cleanly inside workspace buffer',
143
- target_device: target,
144
- verification_prompt: prompt,
145
- filepath: destPath,
146
- workspace_boundary_safe: true,
147
- detected_spatial_elements: textMap || 'No confident OCR text tokens detected.'
148
- }, null, 2)
149
- };
150
- } catch (e) {
151
- return { success: false, error: e.message };
152
91
  }
153
- }
154
92
  };