@causyne/agent 1.20.23 → 1.20.26

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.
@@ -10,7 +10,9 @@
10
10
  * 4. Ring-buffered output truncation (50KB cap) to protect LLM context windows.
11
11
  */
12
12
  import { spawn } from 'node:child_process';
13
+ import fs from 'node:fs';
13
14
  import os from 'node:os';
15
+ import path from 'node:path';
14
16
  import { isLaunchOnlyPrompt, isServerLaunchCommand } from '../launchIntent.js';
15
17
  /**
16
18
  * Strips ANSI escape sequences and terminal control codes from string output.
@@ -39,7 +41,148 @@ export function cleanSubprocessOutput(str) {
39
41
  * Commands whose exit code 1 indicates a normal query result (e.g. no matches found,
40
42
  * differences found, or condition evaluated to false) rather than a system error.
41
43
  */
42
- export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test|which|cmp|find)(\s|$)/;
44
+ export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test|which|where|cmp|find|pidof|pgrep)(\s|$)/;
45
+ /**
46
+ * Resolves an enriched environment for subprocess execution with full toolchain
47
+ * awareness. Automatically discovers Android SDK, Homebrew, local user binaries,
48
+ * and language runtimes so ADB, emulator, and build tools function out-of-the-box.
49
+ */
50
+ export function getEnhancedEnv(baseEnv) {
51
+ const env = { ...(baseEnv || process.env) };
52
+ // 1. Discover ANDROID_HOME / ANDROID_SDK_ROOT across standard platform locations
53
+ if (!env.ANDROID_HOME && !env.ANDROID_SDK_ROOT) {
54
+ const candidateDirs = [
55
+ path.join(os.homedir(), 'Library', 'Android', 'sdk'), // macOS
56
+ path.join(os.homedir(), 'Android', 'Sdk'), // Linux
57
+ '/usr/lib/android-sdk', // Linux package
58
+ path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') // Windows
59
+ ];
60
+ for (const dir of candidateDirs) {
61
+ if (dir && fs.existsSync(dir)) {
62
+ env.ANDROID_HOME = dir;
63
+ env.ANDROID_SDK_ROOT = dir;
64
+ break;
65
+ }
66
+ }
67
+ }
68
+ else if (!env.ANDROID_HOME && env.ANDROID_SDK_ROOT) {
69
+ env.ANDROID_HOME = env.ANDROID_SDK_ROOT;
70
+ }
71
+ else if (env.ANDROID_HOME && !env.ANDROID_SDK_ROOT) {
72
+ env.ANDROID_SDK_ROOT = env.ANDROID_HOME;
73
+ }
74
+ // 2. Build enriched PATH including dev tools, package managers, and Android toolchains
75
+ // Find case-insensitive PATH key (on Windows it is often 'Path')
76
+ const pathKey = Object.keys(env).find(k => k.toUpperCase() === 'PATH') || 'PATH';
77
+ const currentPath = env[pathKey] || process.env[pathKey] || process.env.PATH || process.env.Path || '';
78
+ const pathParts = currentPath.split(path.delimiter).filter(Boolean);
79
+ const addIfMissing = (dir, checkExists = true) => {
80
+ if (dir && (!checkExists || fs.existsSync(dir)) && !pathParts.includes(dir)) {
81
+ pathParts.unshift(dir);
82
+ }
83
+ };
84
+ // Node runtime directory
85
+ if (process.execPath) {
86
+ addIfMissing(path.dirname(process.execPath));
87
+ }
88
+ // Windows system binaries (guarantee cmd.exe and powershell resolve)
89
+ if (process.platform === 'win32') {
90
+ const sysRoot = env.SystemRoot || env.SYSTEMROOT || process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows';
91
+ addIfMissing(path.join(sysRoot, 'System32'));
92
+ addIfMissing(sysRoot);
93
+ }
94
+ // Local user binaries (where Google's official android CLI lives)
95
+ addIfMissing(path.join(os.homedir(), '.local', 'bin'), false);
96
+ // Package managers and developer toolchains
97
+ addIfMissing('/opt/homebrew/bin');
98
+ addIfMissing('/opt/homebrew/sbin');
99
+ addIfMissing('/usr/local/bin');
100
+ addIfMissing(path.join(os.homedir(), '.cargo', 'bin'));
101
+ // Android SDK binaries
102
+ const androidHome = env.ANDROID_HOME;
103
+ if (androidHome) {
104
+ addIfMissing(path.join(androidHome, 'platform-tools'), false);
105
+ addIfMissing(path.join(androidHome, 'cmdline-tools', 'latest', 'bin'), false);
106
+ addIfMissing(path.join(androidHome, 'emulator'), false);
107
+ addIfMissing(path.join(androidHome, 'tools', 'bin'), false);
108
+ addIfMissing(path.join(androidHome, 'tools'), false);
109
+ const buildToolsDir = path.join(androidHome, 'build-tools');
110
+ if (fs.existsSync(buildToolsDir)) {
111
+ try {
112
+ const versions = fs.readdirSync(buildToolsDir).filter(v => !v.startsWith('.')).sort();
113
+ const latest = versions.at(-1);
114
+ if (latest) {
115
+ addIfMissing(path.join(buildToolsDir, latest));
116
+ }
117
+ }
118
+ catch { }
119
+ }
120
+ }
121
+ // 3. Discover JAVA_HOME across Homebrew, macOS JVMs, Linux, and Windows
122
+ if (!env.JAVA_HOME) {
123
+ const javaCandidates = [
124
+ '/opt/homebrew/opt/openjdk@17',
125
+ '/opt/homebrew/opt/openjdk@21',
126
+ '/opt/homebrew/opt/openjdk',
127
+ '/usr/local/opt/openjdk@17',
128
+ '/usr/local/opt/openjdk@21',
129
+ '/usr/local/opt/openjdk',
130
+ '/usr/lib/jvm/java-17-openjdk-amd64',
131
+ '/usr/lib/jvm/java-17-openjdk',
132
+ '/usr/lib/jvm/java-21-openjdk-amd64',
133
+ '/usr/lib/jvm/default-java',
134
+ 'C:\\Program Files\\Java\\jdk-17',
135
+ 'C:\\Program Files\\Java\\jdk-21'
136
+ ];
137
+ const macJvmRoot = '/Library/Java/JavaVirtualMachines';
138
+ if (fs.existsSync(macJvmRoot)) {
139
+ try {
140
+ const jvms = fs.readdirSync(macJvmRoot).filter(d => !d.startsWith('.')).sort().reverse();
141
+ for (const jvm of jvms) {
142
+ javaCandidates.unshift(path.join(macJvmRoot, jvm, 'Contents', 'Home'));
143
+ }
144
+ }
145
+ catch { }
146
+ }
147
+ for (const jDir of javaCandidates) {
148
+ if (jDir && fs.existsSync(jDir)) {
149
+ env.JAVA_HOME = jDir;
150
+ break;
151
+ }
152
+ }
153
+ }
154
+ if (env.JAVA_HOME) {
155
+ addIfMissing(path.join(env.JAVA_HOME, 'bin'), false);
156
+ }
157
+ const enrichedPath = pathParts.join(path.delimiter);
158
+ env[pathKey] = enrichedPath;
159
+ if (process.platform === 'win32') {
160
+ env.PATH = enrichedPath;
161
+ env.Path = enrichedPath;
162
+ }
163
+ else {
164
+ env.PATH = enrichedPath;
165
+ }
166
+ return env;
167
+ }
168
+ /**
169
+ * Determines whether the terminal command in a pipeline, compound statement,
170
+ * or shell wrapper is a search/inspection tool whose exit code 1 represents
171
+ * zero matches rather than a failure.
172
+ */
173
+ export function isFinalCommandSearch(rawCommand) {
174
+ if (rawCommand.includes('||'))
175
+ return false;
176
+ const statements = rawCommand.split(/&&|;/);
177
+ let lastStmt = statements.at(-1)?.trim() || '';
178
+ const subshellMatch = lastStmt.match(/(?:(?:adb\s+(?:-s\s+\S+\s+)?shell|ssh\s+\S+|sh\s+-c|bash\s+-c)\s+["'])(.+?)(?:["']\s*[\)]*\s*$)/);
179
+ if (subshellMatch && subshellMatch[1]) {
180
+ lastStmt = subshellMatch[1].trim();
181
+ }
182
+ const pipeParts = lastStmt.split('|');
183
+ const finalCmd = pipeParts.at(-1)?.trim().replace(/["'\)\s]+$/, '') || '';
184
+ return /(?:^|\s)(grep|egrep|fgrep|diff|test|which|where|cmp|pidof|pgrep|find)\b/.test(finalCmd);
185
+ }
43
186
  /**
44
187
  * Commands that are strictly read-only and idempotent.
45
188
  * Repeated identical executions within a short TTL window return cached output.
@@ -78,7 +221,7 @@ export function clearSysRunCache() {
78
221
  export const sysRun = {
79
222
  schema: {
80
223
  name: 'sysRun',
81
- description: 'Execute a shell command. CRITICAL CONSTRAINTS: 1. NEVER use interactive flags (like git rebase -i). 2. Always use non-interactive flags (--yes, -y). 3. If running git commit, always run git status, git diff, and git log first.',
224
+ description: 'Execute a shell command. Environment is automatically enriched with PATH for Android SDK (adb, emulator), Java (JAVA_HOME), and local developer tools (no manual export needed). CRITICAL CONSTRAINTS: 1. NEVER use interactive flags (like git rebase -i). 2. Always use non-interactive flags (--yes, -y). 3. If running git commit, always run git status, git diff, and git log first.',
82
225
  parameters: {
83
226
  type: 'object',
84
227
  properties: {
@@ -133,6 +276,7 @@ export const sysRun = {
133
276
  child = spawn(shell, shellArgs, {
134
277
  cwd,
135
278
  signal,
279
+ env: getEnhancedEnv(),
136
280
  ...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
137
281
  });
138
282
  }
@@ -247,9 +391,8 @@ export const sysRun = {
247
391
  }
248
392
  resolve(res);
249
393
  }
250
- else if (exitCode === 1 && !/[;&<>`$\r\n]/.test(rawCommand) && !rawCommand.includes('||')
251
- && /^(grep|egrep|fgrep|diff|test|which|cmp)\b/.test(rawCommand.split('|').at(-1)?.trim() || '')) {
252
- // Semantic Exit Code Normalization: POSIX search tool found 0 matching lines.
394
+ else if (exitCode === 1 && isFinalCommandSearch(rawCommand)) {
395
+ // Semantic Exit Code Normalization: Search tool found 0 matching lines.
253
396
  const res = {
254
397
  success: true,
255
398
  output: cleanOutput || '(no matches found)',
@@ -268,11 +411,15 @@ export const sysRun = {
268
411
  resolve(res);
269
412
  }
270
413
  else {
414
+ let errorMsg = `Command exited with code ${exitCode}`;
415
+ if (cleanOutput.includes('more than one device/emulator')) {
416
+ errorMsg = 'adb failed: multiple devices/emulators connected. Pass `-s <serial>` (e.g. `adb -s emulator-5554 ...`) or set `export ANDROID_SERIAL=<serial>`.';
417
+ }
271
418
  if (signal && signal.aborted) {
272
419
  resolve({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
273
420
  }
274
421
  else {
275
- resolve({ success: false, output: cleanOutput, error: `Command exited with code ${exitCode}`, exitCode });
422
+ resolve({ success: false, output: cleanOutput, error: errorMsg, exitCode });
276
423
  }
277
424
  }
278
425
  });
@@ -304,6 +451,7 @@ export const sysRunBg = {
304
451
  cwd,
305
452
  detached: true,
306
453
  stdio: 'ignore',
454
+ env: getEnhancedEnv(),
307
455
  ...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
308
456
  });
309
457
  child.once('error', error => resolve({ success: false, error: error.message }));
@@ -11,7 +11,9 @@
11
11
  */
12
12
 
13
13
  import { spawn } from 'node:child_process';
14
+ import fs from 'node:fs';
14
15
  import os from 'node:os';
16
+ import path from 'node:path';
15
17
  import { isLaunchOnlyPrompt, isServerLaunchCommand } from '../launchIntent.js';
16
18
 
17
19
  export interface SysRunArgs {
@@ -81,7 +83,160 @@ export function cleanSubprocessOutput(str: string): string {
81
83
  * Commands whose exit code 1 indicates a normal query result (e.g. no matches found,
82
84
  * differences found, or condition evaluated to false) rather than a system error.
83
85
  */
84
- export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test|which|cmp|find)(\s|$)/;
86
+ export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test|which|where|cmp|find|pidof|pgrep)(\s|$)/;
87
+
88
+ /**
89
+ * Resolves an enriched environment for subprocess execution with full toolchain
90
+ * awareness. Automatically discovers Android SDK, Homebrew, local user binaries,
91
+ * and language runtimes so ADB, emulator, and build tools function out-of-the-box.
92
+ */
93
+ export function getEnhancedEnv(baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
94
+ const env: NodeJS.ProcessEnv = { ...(baseEnv || process.env) };
95
+
96
+ // 1. Discover ANDROID_HOME / ANDROID_SDK_ROOT across standard platform locations
97
+ if (!env.ANDROID_HOME && !env.ANDROID_SDK_ROOT) {
98
+ const candidateDirs = [
99
+ path.join(os.homedir(), 'Library', 'Android', 'sdk'), // macOS
100
+ path.join(os.homedir(), 'Android', 'Sdk'), // Linux
101
+ '/usr/lib/android-sdk', // Linux package
102
+ path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') // Windows
103
+ ];
104
+ for (const dir of candidateDirs) {
105
+ if (dir && fs.existsSync(dir)) {
106
+ env.ANDROID_HOME = dir;
107
+ env.ANDROID_SDK_ROOT = dir;
108
+ break;
109
+ }
110
+ }
111
+ } else if (!env.ANDROID_HOME && env.ANDROID_SDK_ROOT) {
112
+ env.ANDROID_HOME = env.ANDROID_SDK_ROOT;
113
+ } else if (env.ANDROID_HOME && !env.ANDROID_SDK_ROOT) {
114
+ env.ANDROID_SDK_ROOT = env.ANDROID_HOME;
115
+ }
116
+
117
+ // 2. Build enriched PATH including dev tools, package managers, and Android toolchains
118
+ // Find case-insensitive PATH key (on Windows it is often 'Path')
119
+ const pathKey = Object.keys(env).find(k => k.toUpperCase() === 'PATH') || 'PATH';
120
+ const currentPath = env[pathKey] || process.env[pathKey] || process.env.PATH || process.env.Path || '';
121
+ const pathParts = currentPath.split(path.delimiter).filter(Boolean);
122
+ const addIfMissing = (dir: string, checkExists = true) => {
123
+ if (dir && (!checkExists || fs.existsSync(dir)) && !pathParts.includes(dir)) {
124
+ pathParts.unshift(dir);
125
+ }
126
+ };
127
+
128
+ // Node runtime directory
129
+ if (process.execPath) {
130
+ addIfMissing(path.dirname(process.execPath));
131
+ }
132
+
133
+ // Windows system binaries (guarantee cmd.exe and powershell resolve)
134
+ if (process.platform === 'win32') {
135
+ const sysRoot = env.SystemRoot || env.SYSTEMROOT || process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows';
136
+ addIfMissing(path.join(sysRoot, 'System32'));
137
+ addIfMissing(sysRoot);
138
+ }
139
+
140
+ // Local user binaries (where Google's official android CLI lives)
141
+ addIfMissing(path.join(os.homedir(), '.local', 'bin'), false);
142
+
143
+ // Package managers and developer toolchains
144
+ addIfMissing('/opt/homebrew/bin');
145
+ addIfMissing('/opt/homebrew/sbin');
146
+ addIfMissing('/usr/local/bin');
147
+ addIfMissing(path.join(os.homedir(), '.cargo', 'bin'));
148
+
149
+ // Android SDK binaries
150
+ const androidHome = env.ANDROID_HOME;
151
+ if (androidHome) {
152
+ addIfMissing(path.join(androidHome, 'platform-tools'), false);
153
+ addIfMissing(path.join(androidHome, 'cmdline-tools', 'latest', 'bin'), false);
154
+ addIfMissing(path.join(androidHome, 'emulator'), false);
155
+ addIfMissing(path.join(androidHome, 'tools', 'bin'), false);
156
+ addIfMissing(path.join(androidHome, 'tools'), false);
157
+
158
+ const buildToolsDir = path.join(androidHome, 'build-tools');
159
+ if (fs.existsSync(buildToolsDir)) {
160
+ try {
161
+ const versions = fs.readdirSync(buildToolsDir).filter(v => !v.startsWith('.')).sort();
162
+ const latest = versions.at(-1);
163
+ if (latest) {
164
+ addIfMissing(path.join(buildToolsDir, latest));
165
+ }
166
+ } catch {}
167
+ }
168
+ }
169
+
170
+ // 3. Discover JAVA_HOME across Homebrew, macOS JVMs, Linux, and Windows
171
+ if (!env.JAVA_HOME) {
172
+ const javaCandidates = [
173
+ '/opt/homebrew/opt/openjdk@17',
174
+ '/opt/homebrew/opt/openjdk@21',
175
+ '/opt/homebrew/opt/openjdk',
176
+ '/usr/local/opt/openjdk@17',
177
+ '/usr/local/opt/openjdk@21',
178
+ '/usr/local/opt/openjdk',
179
+ '/usr/lib/jvm/java-17-openjdk-amd64',
180
+ '/usr/lib/jvm/java-17-openjdk',
181
+ '/usr/lib/jvm/java-21-openjdk-amd64',
182
+ '/usr/lib/jvm/default-java',
183
+ 'C:\\Program Files\\Java\\jdk-17',
184
+ 'C:\\Program Files\\Java\\jdk-21'
185
+ ];
186
+ const macJvmRoot = '/Library/Java/JavaVirtualMachines';
187
+ if (fs.existsSync(macJvmRoot)) {
188
+ try {
189
+ const jvms = fs.readdirSync(macJvmRoot).filter(d => !d.startsWith('.')).sort().reverse();
190
+ for (const jvm of jvms) {
191
+ javaCandidates.unshift(path.join(macJvmRoot, jvm, 'Contents', 'Home'));
192
+ }
193
+ } catch {}
194
+ }
195
+
196
+ for (const jDir of javaCandidates) {
197
+ if (jDir && fs.existsSync(jDir)) {
198
+ env.JAVA_HOME = jDir;
199
+ break;
200
+ }
201
+ }
202
+ }
203
+
204
+ if (env.JAVA_HOME) {
205
+ addIfMissing(path.join(env.JAVA_HOME, 'bin'), false);
206
+ }
207
+
208
+ const enrichedPath = pathParts.join(path.delimiter);
209
+ env[pathKey] = enrichedPath;
210
+ if (process.platform === 'win32') {
211
+ env.PATH = enrichedPath;
212
+ env.Path = enrichedPath;
213
+ } else {
214
+ env.PATH = enrichedPath;
215
+ }
216
+ return env;
217
+ }
218
+
219
+ /**
220
+ * Determines whether the terminal command in a pipeline, compound statement,
221
+ * or shell wrapper is a search/inspection tool whose exit code 1 represents
222
+ * zero matches rather than a failure.
223
+ */
224
+ export function isFinalCommandSearch(rawCommand: string): boolean {
225
+ if (rawCommand.includes('||')) return false;
226
+
227
+ const statements = rawCommand.split(/&&|;/);
228
+ let lastStmt = statements.at(-1)?.trim() || '';
229
+
230
+ const subshellMatch = lastStmt.match(/(?:(?:adb\s+(?:-s\s+\S+\s+)?shell|ssh\s+\S+|sh\s+-c|bash\s+-c)\s+["'])(.+?)(?:["']\s*[\)]*\s*$)/);
231
+ if (subshellMatch && subshellMatch[1]) {
232
+ lastStmt = subshellMatch[1].trim();
233
+ }
234
+
235
+ const pipeParts = lastStmt.split('|');
236
+ const finalCmd = pipeParts.at(-1)?.trim().replace(/["'\)\s]+$/, '') || '';
237
+
238
+ return /(?:^|\s)(grep|egrep|fgrep|diff|test|which|where|cmp|pidof|pgrep|find)\b/.test(finalCmd);
239
+ }
85
240
 
86
241
  /**
87
242
  * Commands that are strictly read-only and idempotent.
@@ -136,7 +291,7 @@ export const sysRun = {
136
291
  schema: {
137
292
  name: 'sysRun',
138
293
  description:
139
- 'Execute a shell command. CRITICAL CONSTRAINTS: 1. NEVER use interactive flags (like git rebase -i). 2. Always use non-interactive flags (--yes, -y). 3. If running git commit, always run git status, git diff, and git log first.',
294
+ 'Execute a shell command. Environment is automatically enriched with PATH for Android SDK (adb, emulator), Java (JAVA_HOME), and local developer tools (no manual export needed). CRITICAL CONSTRAINTS: 1. NEVER use interactive flags (like git rebase -i). 2. Always use non-interactive flags (--yes, -y). 3. If running git commit, always run git status, git diff, and git log first.',
140
295
  parameters: {
141
296
  type: 'object',
142
297
  properties: {
@@ -197,6 +352,7 @@ export const sysRun = {
197
352
  child = spawn(shell, shellArgs, {
198
353
  cwd,
199
354
  signal,
355
+ env: getEnhancedEnv(),
200
356
  ...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
201
357
  });
202
358
  } catch (err: unknown) {
@@ -306,9 +462,8 @@ export const sysRun = {
306
462
  });
307
463
  }
308
464
  resolve(res);
309
- } else if (exitCode === 1 && !/[;&<>`$\r\n]/.test(rawCommand) && !rawCommand.includes('||')
310
- && /^(grep|egrep|fgrep|diff|test|which|cmp)\b/.test(rawCommand.split('|').at(-1)?.trim() || '')) {
311
- // Semantic Exit Code Normalization: POSIX search tool found 0 matching lines.
465
+ } else if (exitCode === 1 && isFinalCommandSearch(rawCommand)) {
466
+ // Semantic Exit Code Normalization: Search tool found 0 matching lines.
312
467
  const res: SysRunResult = {
313
468
  success: true,
314
469
  output: cleanOutput || '(no matches found)',
@@ -326,10 +481,14 @@ export const sysRun = {
326
481
  }
327
482
  resolve(res);
328
483
  } else {
484
+ let errorMsg = `Command exited with code ${exitCode}`;
485
+ if (cleanOutput.includes('more than one device/emulator')) {
486
+ errorMsg = 'adb failed: multiple devices/emulators connected. Pass `-s <serial>` (e.g. `adb -s emulator-5554 ...`) or set `export ANDROID_SERIAL=<serial>`.';
487
+ }
329
488
  if (signal && signal.aborted) {
330
489
  resolve({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
331
490
  } else {
332
- resolve({ success: false, output: cleanOutput, error: `Command exited with code ${exitCode}`, exitCode });
491
+ resolve({ success: false, output: cleanOutput, error: errorMsg, exitCode });
333
492
  }
334
493
  }
335
494
  });
@@ -363,6 +522,7 @@ export const sysRunBg = {
363
522
  cwd,
364
523
  detached: true,
365
524
  stdio: 'ignore',
525
+ env: getEnhancedEnv(),
366
526
  ...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
367
527
  });
368
528
  child.once('error', error => resolve({ success: false, error: error.message }));