@causyne/agent 1.20.0 → 1.20.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -9
- package/SECURITY.md +1 -4
- package/package.json +1 -1
- package/src/acp/client.js +176 -26
- package/src/acp/client.ts +167 -25
- package/src/acp/protocol.js +116 -0
- package/src/acp/protocol.ts +163 -0
- package/src/acp/server.js +5 -6
- package/src/acp/server.ts +4 -6
- package/src/agentLoop.d.ts +1 -0
- package/src/agentLoop.js +681 -245
- package/src/agentLoop.ts +708 -262
- package/src/agentPolicy.js +9 -0
- package/src/agentPolicy.ts +9 -0
- package/src/approvalPolicy.js +55 -0
- package/src/approvalPolicy.ts +66 -0
- package/src/browser/browserRuntime.js +217 -14
- package/src/browser/browserRuntime.ts +255 -14
- package/src/browser/causyneBrowser.js +1215 -68
- package/src/browser/causyneBrowser.ts +1340 -72
- package/src/cliMode.js +52 -29
- package/src/commands.js +141 -17
- package/src/config.js +22 -12
- package/src/continuum/ui/continuumPicker.js +18 -1
- package/src/continuum/ui/continuumPicker.ts +19 -1
- package/src/dynamicCatalogue.js +87 -20
- package/src/dynamicCatalogue.ts +85 -15
- package/src/launchIntent.js +40 -0
- package/src/launchIntent.ts +49 -0
- package/src/memoryManager.js +26 -2
- package/src/modelCatalogue.js +2 -0
- package/src/planCache.js +320 -11
- package/src/planCache.ts +402 -13
- package/src/providers/acp.js +173 -18
- package/src/providers/acp.ts +169 -19
- package/src/providers/antigravity.d.ts +5 -1
- package/src/providers/antigravity.js +674 -34
- package/src/providers/antigravity.ts +707 -35
- package/src/providers/base.d.ts +10 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/pi.js +161 -0
- package/src/providers/pi.ts +148 -0
- package/src/provisioning/capabilityProvisioner.js +17 -0
- package/src/provisioning/capabilityTools.js +1 -1
- package/src/sandbox.js +30 -39
- package/src/sessionJournal.js +53 -10
- package/src/sessionJournal.ts +64 -10
- package/src/taskShape.js +9 -9
- package/src/taskShape.ts +9 -9
- package/src/timeMachine.js +124 -0
- package/src/timeMachine.ts +141 -0
- package/src/toolPacks.js +4 -10
- package/src/tools/archive.js +196 -59
- package/src/tools/archive.ts +220 -0
- package/src/tools/browserAutomator.js +78 -9
- package/src/tools/browserAutomator.ts +90 -9
- package/src/tools/desktopOpen.js +114 -31
- package/src/tools/desktopOpen.ts +144 -0
- package/src/tools/gitExec.js +5 -3
- package/src/tools/nativeEngine.js +4 -3
- package/src/tools/nativeEngine.ts +5 -3
- package/src/tools/openSourceToolProvisioner.js +5 -4
- package/src/tools/openSourceToolProvisioner.ts +5 -4
- package/src/tools/registry.js +3 -0
- package/src/tools/screenshot.js +55 -71
- package/src/tools/screenshot.ts +70 -0
- package/src/tools/sysRun.js +284 -117
- package/src/tools/sysRun.ts +347 -0
- package/src/tools/toolSelfRepair.js +109 -2
- package/src/tools/toolSelfRepair.ts +100 -2
- package/src/tools/updatePlan.js +49 -1
- package/src/tools/updatePlan.ts +43 -1
- package/src/tools/viewImage.js +93 -78
- package/src/tools/viewImage.ts +116 -0
- package/src/tools/webFetch.js +20 -6
- package/src/tools/webFetch.ts +26 -6
- package/src/tui/activityLayout.js +9 -0
- package/src/tui/activityLayout.ts +10 -0
- package/src/tui/block.d.ts +1 -0
- package/src/tui/chatRenderer.d.ts +23 -0
- package/src/tui/chatRenderer.js +49 -49
- package/src/tui/clipboardSync.js +28 -1
- package/src/tui/clipboardSync.ts +26 -1
- package/src/tui/codeProgress.js +299 -0
- package/src/tui/codeProgress.ts +304 -0
- package/src/tui/codeStreamRenderer.js +132 -0
- package/src/tui/codeStreamRenderer.ts +141 -0
- package/src/tui/commandPresentation.js +11 -0
- package/src/tui/commandPresentation.ts +18 -0
- package/src/tui/completion.js +45 -13
- package/src/tui/composerControls.js +131 -0
- package/src/tui/composerControls.ts +184 -0
- package/src/tui/diff.d.ts +2 -0
- package/src/tui/home.js +4 -2
- package/src/tui/homeTransition.js +21 -0
- package/src/tui/homeTransition.ts +27 -0
- package/src/tui/homeView.js +62 -0
- package/src/tui/homeView.ts +91 -0
- package/src/tui/layout.js +46 -0
- package/src/tui/layout.ts +52 -0
- package/src/tui/messageActionPlacement.js +16 -0
- package/src/tui/messageActionPlacement.ts +25 -0
- package/src/tui/messageInteraction.js +221 -0
- package/src/tui/messageInteraction.ts +275 -0
- package/src/tui/modelPicker.js +4 -24
- package/src/tui/modelPicker.ts +4 -20
- package/src/tui/mouseHover.js +6 -0
- package/src/tui/mouseHover.ts +5 -0
- package/src/tui/prompt.js +175 -101
- package/src/tui/resizeRecovery.js +15 -0
- package/src/tui/resizeRecovery.ts +27 -0
- package/src/tui/scrollInteraction.js +97 -0
- package/src/tui/scrollInteraction.ts +189 -0
- package/src/tui/sessionLayout.js +12 -0
- package/src/tui/sessionLayout.ts +12 -0
- package/src/tui/sessionPicker.js +111 -16
- package/src/tui/sessionPicker.ts +121 -16
- package/src/tui/sessionSidebar.js +78 -0
- package/src/tui/sessionSidebar.ts +95 -0
- package/src/tui/setup.js +1 -1
- package/src/tui/setup.ts +1 -1
- package/src/tui/stageSurface.js +120 -58
- package/src/tui/text.d.ts +6 -0
- package/src/tui/textLayout.js +23 -0
- package/src/tui/textLayout.ts +28 -0
- package/src/tui/viewport.js +204 -279
- package/src/tui/viewport.ts +326 -0
- package/src/types/contracts.ts +54 -0
- package/src/utils/paths.js +5 -4
- package/src/utils/paths.ts +5 -5
package/src/tools/screenshot.js
CHANGED
|
@@ -1,75 +1,59 @@
|
|
|
1
|
-
import fs from 'fs/promises';
|
|
2
|
-
import
|
|
3
|
-
import
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
4
|
import { ensureCapability, loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
|
|
5
|
-
|
|
6
5
|
export const screenshot = {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
6
|
+
schema: {
|
|
7
|
+
name: 'screenshot',
|
|
8
|
+
description: 'Capture the local desktop after the vision capability is granted and pass the image to the active vision model. Optional OCR extracts visible text.',
|
|
9
|
+
parameters: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
analyzeText: { type: 'boolean', description: 'Return OCR text instead of the image.' }
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
async execute(args = {}) {
|
|
17
|
+
const vision = await ensureCapability('vision');
|
|
18
|
+
if (!vision.ok)
|
|
19
|
+
return { success: false, error: vision.reason, requiresConsent: vision.requiresConsent };
|
|
20
|
+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'causyne-vision-'));
|
|
21
|
+
const imagePath = path.join(tempDir, 'screen.png');
|
|
22
|
+
try {
|
|
23
|
+
const capture = await loadCapabilityPackage('screenshot-desktop');
|
|
24
|
+
await capture({ filename: imagePath });
|
|
25
|
+
const bytes = await fs.readFile(imagePath);
|
|
26
|
+
if (bytes.length > 20 * 1024 * 1024)
|
|
27
|
+
return { success: false, error: 'Screenshot exceeds 20 MB' };
|
|
28
|
+
if (args.analyzeText) {
|
|
29
|
+
const ocr = await ensureCapability('ocr');
|
|
30
|
+
if (!ocr.ok)
|
|
31
|
+
return { success: false, error: ocr.reason, requiresConsent: ocr.requiresConsent };
|
|
32
|
+
const Tesseract = await loadCapabilityPackage('tesseract.js');
|
|
33
|
+
const worker = await Tesseract.createWorker('eng');
|
|
34
|
+
try {
|
|
35
|
+
const recognized = await worker.recognize(imagePath);
|
|
36
|
+
const words = (recognized.data?.words ?? []);
|
|
37
|
+
const output = words.filter(word => word.confidence > 75).slice(0, 50).map(word => `${word.text} at ${Math.floor((word.bbox.x0 + word.bbox.x1) / 2)},${Math.floor((word.bbox.y0 + word.bbox.y1) / 2)}`).join('\n');
|
|
38
|
+
return { success: true, output: output || 'Screenshot captured; no readable text detected.' };
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
await worker.terminate();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
success: true,
|
|
46
|
+
_is_image_marker: true,
|
|
47
|
+
mimeType: 'image/png',
|
|
48
|
+
base64: bytes.toString('base64'),
|
|
49
|
+
filename: 'desktop screenshot'
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
return { success: false, error: `Screen capture failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
await fs.rm(tempDir, { recursive: true, force: true });
|
|
57
|
+
}
|
|
15
58
|
}
|
|
16
|
-
},
|
|
17
|
-
async execute(args) {
|
|
18
|
-
try {
|
|
19
|
-
const vision = await ensureCapability('vision');
|
|
20
|
-
if (!vision.ok) return { success: false, error: vision.reason, requiresConsent: vision.requiresConsent };
|
|
21
|
-
const screenshotDesktop = await loadCapabilityPackage('screenshot-desktop');
|
|
22
|
-
|
|
23
|
-
const tempDir = path.join(os.tmpdir(), 'causyne_vision');
|
|
24
|
-
await fs.mkdir(tempDir, { recursive: true });
|
|
25
|
-
const dest = path.join(tempDir, `vision_${Date.now()}.png`);
|
|
26
|
-
|
|
27
|
-
// Phase 5 AGI Upgrade: Cross-Platform Native Capture
|
|
28
|
-
await screenshotDesktop({ filename: dest });
|
|
29
|
-
|
|
30
|
-
if (!args.analyzeText) {
|
|
31
|
-
return { success: true, output: `Screenshot saved to ${dest}` };
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// Phase 5 AGI Upgrade: OCR Bounding Box Integration
|
|
35
|
-
const ocr = await ensureCapability('ocr');
|
|
36
|
-
if (!ocr.ok) {
|
|
37
|
-
await fs.unlink(dest);
|
|
38
|
-
return { success: false, error: ocr.reason, requiresConsent: ocr.requiresConsent };
|
|
39
|
-
}
|
|
40
|
-
const Tesseract = await loadCapabilityPackage('tesseract.js');
|
|
41
|
-
|
|
42
|
-
// Tesseract runs in its own Worker thread automatically
|
|
43
|
-
const worker = await Tesseract.createWorker('eng');
|
|
44
|
-
const { data: { words } } = await worker.recognize(dest);
|
|
45
|
-
await worker.terminate();
|
|
46
|
-
|
|
47
|
-
// Delete temporary image to protect privacy
|
|
48
|
-
await fs.unlink(dest);
|
|
49
|
-
|
|
50
|
-
if (!words || words.length === 0) {
|
|
51
|
-
return { success: true, output: "Screenshot taken, but no readable text found on screen." };
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
let markdownMap = `👁️ OS Visual Spatial Map:\n\n`;
|
|
55
|
-
// We'll return the top 50 most confident words to prevent context overload
|
|
56
|
-
const confidentWords = words.filter(w => w.confidence > 75).slice(0, 50);
|
|
57
|
-
|
|
58
|
-
for (const w of confidentWords) {
|
|
59
|
-
const { x0, y0, x1, y1 } = w.bbox;
|
|
60
|
-
const centerX = Math.floor((x0 + x1) / 2);
|
|
61
|
-
const centerY = Math.floor((y0 + y1) / 2);
|
|
62
|
-
markdownMap += `- Text: "${w.text}" | Center Coordinates: X:${centerX}, Y:${centerY} | Confidence: ${w.confidence.toFixed(1)}%\n`;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
if (words.length > 50) {
|
|
66
|
-
markdownMap += `\n[... Truncated ${words.length - 50} elements to protect AGI Context ...]`;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
return { success: true, output: markdownMap };
|
|
70
|
-
|
|
71
|
-
} catch (e) {
|
|
72
|
-
return { success: false, error: `Vision Error: ${e.message}` };
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
59
|
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { ensureCapability, loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
|
|
6
|
+
|
|
7
|
+
interface ScreenshotArgs { analyzeText?: boolean }
|
|
8
|
+
|
|
9
|
+
export const screenshot = {
|
|
10
|
+
schema: {
|
|
11
|
+
name: 'screenshot',
|
|
12
|
+
description: 'Capture the local desktop after the vision capability is granted and pass the image to the active vision model. Optional OCR extracts visible text.',
|
|
13
|
+
parameters: {
|
|
14
|
+
type: 'object',
|
|
15
|
+
properties: {
|
|
16
|
+
analyzeText: { type: 'boolean', description: 'Return OCR text instead of the image.' }
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
|
|
21
|
+
async execute(args: ScreenshotArgs = {}) {
|
|
22
|
+
const vision = await ensureCapability('vision');
|
|
23
|
+
if (!vision.ok) return { success: false, error: vision.reason, requiresConsent: vision.requiresConsent };
|
|
24
|
+
|
|
25
|
+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'causyne-vision-'));
|
|
26
|
+
const imagePath = path.join(tempDir, 'screen.png');
|
|
27
|
+
try {
|
|
28
|
+
const capture = await loadCapabilityPackage('screenshot-desktop') as (options: { filename: string }) => Promise<void>;
|
|
29
|
+
await capture({ filename: imagePath });
|
|
30
|
+
const bytes = await fs.readFile(imagePath);
|
|
31
|
+
if (bytes.length > 20 * 1024 * 1024) return { success: false, error: 'Screenshot exceeds 20 MB' };
|
|
32
|
+
|
|
33
|
+
if (args.analyzeText) {
|
|
34
|
+
const ocr = await ensureCapability('ocr');
|
|
35
|
+
if (!ocr.ok) return { success: false, error: ocr.reason, requiresConsent: ocr.requiresConsent };
|
|
36
|
+
const Tesseract = await loadCapabilityPackage('tesseract.js') as {
|
|
37
|
+
createWorker(language: string): Promise<{
|
|
38
|
+
recognize(file: string): Promise<{ data?: { words?: unknown[] } }>;
|
|
39
|
+
terminate(): Promise<void>;
|
|
40
|
+
}>;
|
|
41
|
+
};
|
|
42
|
+
const worker = await Tesseract.createWorker('eng');
|
|
43
|
+
try {
|
|
44
|
+
const recognized = await worker.recognize(imagePath);
|
|
45
|
+
const words = (recognized.data?.words ?? []) as Array<{
|
|
46
|
+
text: string; confidence: number; bbox: { x0: number; y0: number; x1: number; y1: number };
|
|
47
|
+
}>;
|
|
48
|
+
const output = words.filter(word => word.confidence > 75).slice(0, 50).map(word =>
|
|
49
|
+
`${word.text} at ${Math.floor((word.bbox.x0 + word.bbox.x1) / 2)},${Math.floor((word.bbox.y0 + word.bbox.y1) / 2)}`
|
|
50
|
+
).join('\n');
|
|
51
|
+
return { success: true, output: output || 'Screenshot captured; no readable text detected.' };
|
|
52
|
+
} finally {
|
|
53
|
+
await worker.terminate();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
success: true,
|
|
59
|
+
_is_image_marker: true,
|
|
60
|
+
mimeType: 'image/png',
|
|
61
|
+
base64: bytes.toString('base64'),
|
|
62
|
+
filename: 'desktop screenshot'
|
|
63
|
+
};
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return { success: false, error: `Screen capture failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
66
|
+
} finally {
|
|
67
|
+
await fs.rm(tempDir, { recursive: true, force: true });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
package/src/tools/sysRun.js
CHANGED
|
@@ -1,125 +1,292 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — System Command Execution (sysRun & sysRunBg)
|
|
3
|
+
*
|
|
4
|
+
* Provides robust subprocess execution with:
|
|
5
|
+
* 1. Semantic exit code normalization (POSIX grep, diff, test, which, cmp exit codes
|
|
6
|
+
* treated as valid non-error queries rather than fatal crashes).
|
|
7
|
+
* 2. In-memory execution deduplication cache for read-only / diagnostic commands
|
|
8
|
+
* to prevent infinite retry thrashing.
|
|
9
|
+
* 3. ANSI color/control sequence stripping for clean tool output.
|
|
10
|
+
* 4. Ring-buffered output truncation (50KB cap) to protect LLM context windows.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import { isLaunchOnlyPrompt, isServerLaunchCommand } from '../launchIntent.js';
|
|
15
|
+
/**
|
|
16
|
+
* Strips ANSI escape sequences and terminal control codes from string output.
|
|
17
|
+
*/
|
|
18
|
+
export function stripAnsi(str) {
|
|
19
|
+
const pattern = [
|
|
20
|
+
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
|
|
21
|
+
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))'
|
|
22
|
+
].join('|');
|
|
23
|
+
return str.replace(new RegExp(pattern, 'g'), '');
|
|
11
24
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Commands whose exit code 1 indicates a normal query result (e.g. no matches found,
|
|
27
|
+
* differences found, or condition evaluated to false) rather than a system error.
|
|
28
|
+
*/
|
|
29
|
+
export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test|which|cmp|find)(\s|$)/;
|
|
30
|
+
/**
|
|
31
|
+
* Commands that are strictly read-only and idempotent.
|
|
32
|
+
* Repeated identical executions within a short TTL window return cached output.
|
|
33
|
+
*/
|
|
34
|
+
export const IDEMPOTENT_COMMAND_PATTERN = /^(python3?|node|bun|pnpm|npm)\s+(-v|--version|(-c|-e)\s+["'].*?["'])$|^ls\b|^cat\b|^head\b|^tail\b|^grep\b|^find\b|^which\b|^where\b|^pwd$|^git\s+(status|log|diff|branch|tag|show\b)|^echo\b/;
|
|
35
|
+
/**
|
|
36
|
+
* Detect long-running dev servers and web application listeners that must not block foreground loops.
|
|
37
|
+
*/
|
|
38
|
+
export function isPersistentServerCommand(cmd) {
|
|
39
|
+
if (!cmd || typeof cmd !== 'string')
|
|
40
|
+
return false;
|
|
41
|
+
const trimmed = cmd.trim();
|
|
42
|
+
if (/^(?:cat|head|tail|grep|lsof|ps|kill|pkill|pgrep|curl|wget|echo|test)\b/i.test(trimmed)) {
|
|
43
|
+
return false;
|
|
26
44
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
45
|
+
const patterns = [
|
|
46
|
+
/(?:^|[;&|\s])(?:python[0-9.]*|node|deno|bun)\s+.*(?:server|app|main)\.(?:py|js|ts|mjs|cjs)\b/i,
|
|
47
|
+
/(?:^|[;&|\s])python[0-9.]*\s+-m\s+http\.server\b/i,
|
|
48
|
+
/(?:^|[;&|\s])(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b/i,
|
|
49
|
+
/(?:^|[;&|\s])(?:npx\s+)?(?:serve|vite|live-server|http-server)\b/i,
|
|
50
|
+
/(?:^|[;&|\s])(?:flask\s+run|uvicorn|gunicorn)\b/i,
|
|
51
|
+
/(?:^|[;&|\s])(?:\.\/start\.sh|bash\s+start\.sh|sh\s+start\.sh)\b/i
|
|
52
|
+
];
|
|
53
|
+
return patterns.some(pattern => pattern.test(trimmed));
|
|
54
|
+
}
|
|
55
|
+
export const SERVER_READY_PATTERN = /(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):[0-9]+|serving\s+http\s+on|server\s+(?:running|started)|ready\s+in\s+[0-9]+|terra_server_running)/i;
|
|
56
|
+
const COMMAND_CACHE_TTL_MS = 60_000;
|
|
57
|
+
const commandCache = new Map();
|
|
58
|
+
export function clearSysRunCache() {
|
|
59
|
+
commandCache.clear();
|
|
60
|
+
}
|
|
61
|
+
export const sysRun = {
|
|
62
|
+
schema: {
|
|
63
|
+
name: 'sysRun',
|
|
64
|
+
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.',
|
|
65
|
+
parameters: {
|
|
66
|
+
type: 'object',
|
|
67
|
+
properties: {
|
|
68
|
+
command: { type: 'string', description: 'The shell command to run' },
|
|
69
|
+
cwd: { type: 'string', description: 'Working directory' },
|
|
70
|
+
timeout: { type: 'number', description: 'Timeout in ms (default 60000)' }
|
|
71
|
+
},
|
|
72
|
+
required: ['command']
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
async execute(args, context = {}) {
|
|
76
|
+
const rawCommand = (args?.command || '').trim();
|
|
77
|
+
const cwd = args?.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
|
|
78
|
+
const timeoutMs = args?.timeout || 60000;
|
|
79
|
+
const signal = context.signal;
|
|
80
|
+
// A foreground server waits forever for requests. Keep launch-only turns
|
|
81
|
+
// responsive and make it explicit that starting is not a readiness check.
|
|
82
|
+
const taskPrompt = context.parentLoop?.currentTaskPrompt || context.parentLoop?.userPrompt || '';
|
|
83
|
+
if (isLaunchOnlyPrompt(taskPrompt) && isServerLaunchCommand(rawCommand)) {
|
|
84
|
+
const started = await sysRunBg.execute({ command: rawCommand, cwd, label: 'local-server' });
|
|
85
|
+
return started.success
|
|
86
|
+
? { success: true, output: `Started server process ${started.pid} in background. Readiness and browser opening have not been verified.`, exitCode: 0, note: 'Check the server URL before reporting it accessible.' }
|
|
87
|
+
: { success: false, output: '', error: started.error || 'Unable to start server process.', exitCode: 1 };
|
|
88
|
+
}
|
|
89
|
+
// Fast-path: Return cached output for identical read-only idempotent commands
|
|
90
|
+
const isIdempotent = IDEMPOTENT_COMMAND_PATTERN.test(rawCommand);
|
|
91
|
+
const cacheKey = `${cwd}:::${rawCommand}`;
|
|
92
|
+
if (!context.skipCache && isIdempotent && commandCache.has(cacheKey)) {
|
|
93
|
+
const cached = commandCache.get(cacheKey);
|
|
94
|
+
if (Date.now() - cached.timestamp < COMMAND_CACHE_TTL_MS) {
|
|
95
|
+
return {
|
|
96
|
+
success: cached.success,
|
|
97
|
+
output: cached.output,
|
|
98
|
+
exitCode: cached.exitCode,
|
|
99
|
+
cached: true,
|
|
100
|
+
note: cached.note || 'Returned cached output from recent identical execution.'
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
commandCache.delete(cacheKey);
|
|
49
104
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
child.stderr.on('data', appendToBuffer);
|
|
54
|
-
|
|
55
|
-
let timeoutId;
|
|
56
|
-
if (timeoutMs > 0) {
|
|
57
|
-
timeoutId = setTimeout(() => {
|
|
58
|
-
child.kill('SIGKILL');
|
|
59
|
-
resolve({ success: false, output: stripAnsi(outputBuffer), error: `Process timed out after ${timeoutMs}ms`, exitCode: 124 });
|
|
60
|
-
}, timeoutMs);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
child.on('error', (err) => {
|
|
64
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
65
|
-
resolve({ success: false, output: stripAnsi(outputBuffer), error: err.message, exitCode: 1 });
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
child.on('close', (code) => {
|
|
69
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
70
|
-
const cleanOutput = stripAnsi(outputBuffer);
|
|
71
|
-
|
|
72
|
-
if (code === 0) {
|
|
73
|
-
resolve({ success: true, output: cleanOutput, exitCode: 0 });
|
|
74
|
-
} else {
|
|
75
|
-
if (signal && signal.aborted) {
|
|
76
|
-
resolve({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
|
|
77
|
-
} else {
|
|
78
|
-
resolve({ success: false, output: cleanOutput, error: `Command exited with code ${code}`, exitCode: code });
|
|
79
|
-
}
|
|
105
|
+
let executedCommand = rawCommand;
|
|
106
|
+
if (os.platform() !== 'win32' && /(?:^|\s)&\s*$/.test(rawCommand) && !/[><]/.test(rawCommand)) {
|
|
107
|
+
executedCommand = rawCommand.replace(/\s*&\s*$/, ' >/dev/null 2>&1 &');
|
|
80
108
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
109
|
+
return new Promise((resolve) => {
|
|
110
|
+
const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
|
|
111
|
+
const shellArgs = os.platform() === 'win32' ? ['/c', executedCommand] : ['-c', executedCommand];
|
|
112
|
+
let child;
|
|
113
|
+
try {
|
|
114
|
+
child = spawn(shell, shellArgs, { cwd, signal });
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
118
|
+
resolve({
|
|
119
|
+
success: false,
|
|
120
|
+
output: '',
|
|
121
|
+
error: errorMsg,
|
|
122
|
+
exitCode: 1
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
// Phase 1 AGI Upgrade: 50KB Ring Buffer (FIFO)
|
|
127
|
+
const MAX_LENGTH = 50000;
|
|
128
|
+
let outputBuffer = '';
|
|
129
|
+
let isDetached = false;
|
|
130
|
+
const checkServerDetach = () => {
|
|
131
|
+
if (isDetached)
|
|
132
|
+
return;
|
|
133
|
+
if (isPersistentServerCommand(rawCommand) || isServerLaunchCommand(rawCommand)) {
|
|
134
|
+
if (SERVER_READY_PATTERN.test(outputBuffer)) {
|
|
135
|
+
isDetached = true;
|
|
136
|
+
if (timeoutId)
|
|
137
|
+
clearTimeout(timeoutId);
|
|
138
|
+
if (serverGraceTimer)
|
|
139
|
+
clearTimeout(serverGraceTimer);
|
|
140
|
+
child.unref();
|
|
141
|
+
resolve({
|
|
142
|
+
success: true,
|
|
143
|
+
output: stripAnsi(outputBuffer),
|
|
144
|
+
exitCode: 0,
|
|
145
|
+
note: 'Server readiness verified. Running in background.'
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const appendToBuffer = (data) => {
|
|
151
|
+
outputBuffer += data.toString();
|
|
152
|
+
if (outputBuffer.length > MAX_LENGTH) {
|
|
153
|
+
outputBuffer = '...[OUTPUT TRUNCATED]...\n' + outputBuffer.slice(outputBuffer.length - MAX_LENGTH);
|
|
154
|
+
}
|
|
155
|
+
checkServerDetach();
|
|
156
|
+
};
|
|
157
|
+
child.stdout?.on('data', appendToBuffer);
|
|
158
|
+
child.stderr?.on('data', appendToBuffer);
|
|
159
|
+
let serverGraceTimer;
|
|
160
|
+
if (isPersistentServerCommand(rawCommand) || isServerLaunchCommand(rawCommand)) {
|
|
161
|
+
serverGraceTimer = setTimeout(() => {
|
|
162
|
+
if (!isDetached && child.exitCode === null) {
|
|
163
|
+
isDetached = true;
|
|
164
|
+
if (timeoutId)
|
|
165
|
+
clearTimeout(timeoutId);
|
|
166
|
+
child.unref();
|
|
167
|
+
resolve({
|
|
168
|
+
success: true,
|
|
169
|
+
output: stripAnsi(outputBuffer) || 'Server process started and running in background.',
|
|
170
|
+
exitCode: 0,
|
|
171
|
+
note: 'Server detached after clean execution.'
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}, 2500);
|
|
175
|
+
}
|
|
176
|
+
let timeoutId;
|
|
177
|
+
if (timeoutMs > 0) {
|
|
178
|
+
timeoutId = setTimeout(() => {
|
|
179
|
+
if (isDetached)
|
|
180
|
+
return;
|
|
181
|
+
if (serverGraceTimer)
|
|
182
|
+
clearTimeout(serverGraceTimer);
|
|
183
|
+
child.kill('SIGKILL');
|
|
184
|
+
resolve({
|
|
185
|
+
success: false,
|
|
186
|
+
output: stripAnsi(outputBuffer),
|
|
187
|
+
error: `Process timed out after ${timeoutMs}ms`,
|
|
188
|
+
exitCode: 124
|
|
189
|
+
});
|
|
190
|
+
}, timeoutMs);
|
|
191
|
+
}
|
|
192
|
+
child.on('error', (err) => {
|
|
193
|
+
if (isDetached)
|
|
194
|
+
return;
|
|
195
|
+
if (timeoutId)
|
|
196
|
+
clearTimeout(timeoutId);
|
|
197
|
+
if (serverGraceTimer)
|
|
198
|
+
clearTimeout(serverGraceTimer);
|
|
199
|
+
resolve({
|
|
200
|
+
success: false,
|
|
201
|
+
output: stripAnsi(outputBuffer),
|
|
202
|
+
error: err.message,
|
|
203
|
+
exitCode: 1
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
child.on('close', (code) => {
|
|
207
|
+
if (isDetached)
|
|
208
|
+
return;
|
|
209
|
+
if (timeoutId)
|
|
210
|
+
clearTimeout(timeoutId);
|
|
211
|
+
if (serverGraceTimer)
|
|
212
|
+
clearTimeout(serverGraceTimer);
|
|
213
|
+
const cleanOutput = stripAnsi(outputBuffer);
|
|
214
|
+
const exitCode = typeof code === 'number' ? code : 1;
|
|
215
|
+
if (exitCode === 0) {
|
|
216
|
+
const res = { success: true, output: cleanOutput, exitCode: 0 };
|
|
217
|
+
if (isIdempotent) {
|
|
218
|
+
commandCache.set(cacheKey, {
|
|
219
|
+
output: cleanOutput,
|
|
220
|
+
exitCode: 0,
|
|
221
|
+
success: true,
|
|
222
|
+
timestamp: Date.now()
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
resolve(res);
|
|
226
|
+
}
|
|
227
|
+
else if (exitCode === 1 && SEARCH_COMMAND_PATTERN.test(rawCommand)) {
|
|
228
|
+
// Semantic Exit Code Normalization: POSIX search tool found 0 matching lines.
|
|
229
|
+
const res = {
|
|
230
|
+
success: true,
|
|
231
|
+
output: cleanOutput || '(no matches found)',
|
|
232
|
+
exitCode: 1,
|
|
233
|
+
note: 'Command executed successfully with 0 search matches.'
|
|
234
|
+
};
|
|
235
|
+
if (isIdempotent) {
|
|
236
|
+
commandCache.set(cacheKey, {
|
|
237
|
+
output: res.output,
|
|
238
|
+
exitCode: 1,
|
|
239
|
+
success: true,
|
|
240
|
+
note: res.note,
|
|
241
|
+
timestamp: Date.now()
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
resolve(res);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
if (signal && signal.aborted) {
|
|
248
|
+
resolve({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
resolve({ success: false, output: cleanOutput, error: `Command exited with code ${exitCode}`, exitCode });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
}
|
|
84
257
|
};
|
|
85
|
-
|
|
86
258
|
export const sysRunBg = {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
pid: child.pid
|
|
120
|
-
};
|
|
121
|
-
} catch (e) {
|
|
122
|
-
return { success: false, error: e.message };
|
|
259
|
+
schema: {
|
|
260
|
+
name: 'sysRunBg',
|
|
261
|
+
description: 'Start a long-running process in background (dev servers, watchers)',
|
|
262
|
+
parameters: {
|
|
263
|
+
type: 'object',
|
|
264
|
+
properties: {
|
|
265
|
+
command: { type: 'string' },
|
|
266
|
+
cwd: { type: 'string' },
|
|
267
|
+
label: { type: 'string' },
|
|
268
|
+
maxDuration: { type: 'number' }
|
|
269
|
+
},
|
|
270
|
+
required: ['command', 'label']
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
async execute(args) {
|
|
274
|
+
try {
|
|
275
|
+
const cwd = args.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
|
|
276
|
+
const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
|
|
277
|
+
const shellArgs = os.platform() === 'win32' ? ['/c', args.command] : ['-c', args.command];
|
|
278
|
+
return await new Promise(resolve => {
|
|
279
|
+
const child = spawn(shell, shellArgs, { cwd, detached: true, stdio: 'ignore' });
|
|
280
|
+
child.once('error', error => resolve({ success: false, error: error.message }));
|
|
281
|
+
child.once('spawn', () => {
|
|
282
|
+
child.unref();
|
|
283
|
+
resolve({ success: true, output: `Background process launched [${args.label}]; readiness not verified.`, pid: child.pid });
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
catch (e) {
|
|
288
|
+
const errorMsg = e instanceof Error ? e.message : String(e);
|
|
289
|
+
return { success: false, error: errorMsg };
|
|
290
|
+
}
|
|
123
291
|
}
|
|
124
|
-
}
|
|
125
292
|
};
|