@causyne/agent 1.20.11 → 1.20.13
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/LICENSE +1 -1
- package/docs/ARCHITECTURE.md +24 -1
- package/package.json +1 -1
- package/src/acp/client.js +9 -2
- package/src/acp/client.ts +11 -2
- package/src/acp/protocol.ts +9 -0
- package/src/agentLoop.js +504 -119
- package/src/agentLoop.ts +477 -121
- package/src/browser/browserRuntime.js +47 -0
- package/src/browser/browserRuntime.ts +45 -0
- package/src/browser/causyneBrowser.js +60 -31
- package/src/browser/causyneBrowser.ts +37 -12
- package/src/browser/workspacePreview.js +52 -0
- package/src/browser/workspacePreview.ts +49 -0
- package/src/core/planCache.js +5 -0
- package/src/core/planCache.ts +5 -0
- package/src/decisionPolicy.js +9 -0
- package/src/decisionPolicy.ts +8 -0
- package/src/historyPruner.js +251 -0
- package/src/historyPruner.ts +263 -0
- package/src/infra/atomicWriter.js +49 -0
- package/src/infra/atomicWriter.ts +63 -0
- package/src/infra/telemetry.js +38 -0
- package/src/infra/telemetry.ts +68 -0
- package/src/observer/coldObserver.js +12 -7
- package/src/observer/coldObserver.ts +12 -7
- package/src/observer/evidence.js +8 -2
- package/src/observer/evidence.ts +9 -2
- package/src/outputRecovery.js +36 -0
- package/src/outputRecovery.ts +33 -0
- package/src/providers/acp.js +114 -46
- package/src/providers/acp.ts +129 -46
- package/src/providers/antigravity.js +264 -82
- package/src/providers/antigravity.ts +273 -87
- package/src/providers/antigravityBridge.js +58 -0
- package/src/providers/antigravityBridge.ts +51 -0
- package/src/providers/base.d.ts +9 -0
- package/src/providers/budgetEnforcer.js +110 -0
- package/src/providers/budgetEnforcer.ts +122 -0
- package/src/providers/collaborationPolicy.js +6 -0
- package/src/providers/collaborationPolicy.ts +7 -0
- package/src/providers/loopGuard.js +84 -0
- package/src/providers/loopGuard.ts +105 -0
- package/src/providers/pi.js +19 -6
- package/src/providers/pi.ts +19 -7
- package/src/providers/toolContracts.js +36 -0
- package/src/providers/toolContracts.ts +48 -0
- package/src/session/sidechainEvents.js +49 -0
- package/src/session/sidechainEvents.ts +98 -0
- package/src/skillsManager.d.ts +1 -0
- package/src/smartToolsUse.js +123 -4
- package/src/smartToolsUse.ts +136 -4
- package/src/subagent/sidechainHarness.js +66 -0
- package/src/subagent/sidechainHarness.ts +91 -0
- package/src/taskContinuation.js +12 -0
- package/src/taskContinuation.ts +13 -0
- package/src/tokenTracker.js +406 -539
- package/src/tokenTracker.ts +569 -0
- package/src/toolPacks.d.ts +2 -0
- package/src/toolPacks.js +1 -1
- package/src/tools/argumentValidation.js +56 -0
- package/src/tools/argumentValidation.ts +50 -0
- package/src/tools/browserAutomator.js +2 -2
- package/src/tools/browserAutomator.ts +3 -2
- package/src/tools/deferredMcpSearch.js +188 -201
- package/src/tools/deferredMcpSearch.ts +250 -0
- package/src/tools/generateMediaViaApi.js +305 -331
- package/src/tools/generateMediaViaApi.ts +330 -0
- package/src/tools/historyPruner.js +5 -0
- package/src/tools/historyPruner.ts +5 -0
- package/src/tools/payloadSanitizer.js +92 -0
- package/src/tools/payloadSanitizer.ts +113 -0
- package/src/tools/registry.d.ts +1 -0
- package/src/tools/sysRun.js +47 -18
- package/src/tools/sysRun.ts +52 -20
- package/src/tools/toolOutputStore.js +180 -0
- package/src/tools/toolOutputStore.ts +209 -0
- package/src/tools/toolSelfRepair.js +26 -1
- package/src/tools/toolSelfRepair.ts +25 -1
- package/src/tui/chatRenderer.d.ts +1 -0
- package/src/tui/chatRenderer.js +4 -2
- package/src/tui/codeStreamRenderer.js +36 -8
- package/src/tui/codeStreamRenderer.ts +38 -8
- package/src/tui/stageSurface.js +1 -0
- package/src/tui/text.js +4 -1
- package/src/tokenTracker.d.ts +0 -1
package/src/tools/sysRun.js
CHANGED
|
@@ -22,6 +22,19 @@ export function stripAnsi(str) {
|
|
|
22
22
|
].join('|');
|
|
23
23
|
return str.replace(new RegExp(pattern, 'g'), '');
|
|
24
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* Strips ANSI escape sequences, normalizes carriage returns, and filters
|
|
27
|
+
* transient progress meters (curl, wget) so agent history and split-panes never glitch.
|
|
28
|
+
*/
|
|
29
|
+
export function cleanSubprocessOutput(str) {
|
|
30
|
+
const normalized = stripAnsi(str)
|
|
31
|
+
.replace(/\r\n/g, '\n')
|
|
32
|
+
.replace(/\r/g, '\n');
|
|
33
|
+
return normalized
|
|
34
|
+
.split('\n')
|
|
35
|
+
.filter(line => !/^\s*(?:%\s+Total\b|Dload\s+Upload\b|\d+\s+\d+(?:\.[0-9kKmM]+)?\s+\d+\s+.*--:--:--)/i.test(line))
|
|
36
|
+
.join('\n');
|
|
37
|
+
}
|
|
25
38
|
/**
|
|
26
39
|
* Commands whose exit code 1 indicates a normal query result (e.g. no matches found,
|
|
27
40
|
* differences found, or condition evaluated to false) rather than a system error.
|
|
@@ -31,7 +44,9 @@ export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test
|
|
|
31
44
|
* Commands that are strictly read-only and idempotent.
|
|
32
45
|
* Repeated identical executions within a short TTL window return cached output.
|
|
33
46
|
*/
|
|
34
|
-
|
|
47
|
+
// Git inspection commands can invoke configured helpers or write --output
|
|
48
|
+
// files. Execute them normally instead of memoizing a name-based assumption.
|
|
49
|
+
export const IDEMPOTENT_COMMAND_PATTERN = /^(?!.*[;&|<>`$\r\n])(?:(?:python[0-9.]*|node|bun|npm|pnpm)\s+(?:-v|-V|--version)|pwd|(?:ls|dir|cat|type|head|tail|grep|which|where|echo)(?:\s+[^;&|<>`$\r\n]+)?)$/;
|
|
35
50
|
/**
|
|
36
51
|
* Detect long-running dev servers and web application listeners that must not block foreground loops.
|
|
37
52
|
*/
|
|
@@ -39,7 +54,9 @@ export function isPersistentServerCommand(cmd) {
|
|
|
39
54
|
if (!cmd || typeof cmd !== 'string')
|
|
40
55
|
return false;
|
|
41
56
|
const trimmed = cmd.trim();
|
|
42
|
-
|
|
57
|
+
// A chained launch/check command must run through its actual final exit.
|
|
58
|
+
// Returning at a readiness-looking line would skip later checks or failures.
|
|
59
|
+
if (/[;&|<>`$\r\n]/.test(trimmed) || /^(?:cat|head|tail|grep|lsof|ps|kill|pkill|pgrep|curl|wget|echo|test)\b/i.test(trimmed)) {
|
|
43
60
|
return false;
|
|
44
61
|
}
|
|
45
62
|
const patterns = [
|
|
@@ -80,14 +97,16 @@ export const sysRun = {
|
|
|
80
97
|
// A foreground server waits forever for requests. Keep launch-only turns
|
|
81
98
|
// responsive and make it explicit that starting is not a readiness check.
|
|
82
99
|
const taskPrompt = context.parentLoop?.currentTaskPrompt || context.parentLoop?.userPrompt || '';
|
|
83
|
-
if (isLaunchOnlyPrompt(taskPrompt) && isServerLaunchCommand(rawCommand)) {
|
|
100
|
+
if (isLaunchOnlyPrompt(taskPrompt) && !/[;&|<>`$\r\n]/.test(rawCommand) && isServerLaunchCommand(rawCommand)) {
|
|
84
101
|
const started = await sysRunBg.execute({ command: rawCommand, cwd, label: 'local-server' });
|
|
85
102
|
return started.success
|
|
86
|
-
? { success: true, output: `Started server process ${started.pid} in background. Readiness and browser opening have not been verified.`, exitCode:
|
|
103
|
+
? { success: true, output: `Started server process ${started.pid} in background. Readiness and browser opening have not been verified.`, exitCode: null, running: true, ...(started.pid !== undefined ? { pid: started.pid } : {}), note: 'Check the server URL before reporting it accessible.' }
|
|
87
104
|
: { success: false, output: '', error: started.error || 'Unable to start server process.', exitCode: 1 };
|
|
88
105
|
}
|
|
89
106
|
// Fast-path: Return cached output for identical read-only idempotent commands
|
|
90
107
|
const isIdempotent = IDEMPOTENT_COMMAND_PATTERN.test(rawCommand);
|
|
108
|
+
if (!isIdempotent)
|
|
109
|
+
commandCache.clear();
|
|
91
110
|
const cacheKey = `${cwd}:::${rawCommand}`;
|
|
92
111
|
if (!context.skipCache && isIdempotent && commandCache.has(cacheKey)) {
|
|
93
112
|
const cached = commandCache.get(cacheKey);
|
|
@@ -111,7 +130,11 @@ export const sysRun = {
|
|
|
111
130
|
const shellArgs = os.platform() === 'win32' ? ['/c', executedCommand] : ['-c', executedCommand];
|
|
112
131
|
let child;
|
|
113
132
|
try {
|
|
114
|
-
child = spawn(shell, shellArgs, {
|
|
133
|
+
child = spawn(shell, shellArgs, {
|
|
134
|
+
cwd,
|
|
135
|
+
signal,
|
|
136
|
+
...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
|
|
137
|
+
});
|
|
115
138
|
}
|
|
116
139
|
catch (err) {
|
|
117
140
|
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
@@ -130,7 +153,7 @@ export const sysRun = {
|
|
|
130
153
|
const checkServerDetach = () => {
|
|
131
154
|
if (isDetached)
|
|
132
155
|
return;
|
|
133
|
-
if (isPersistentServerCommand(rawCommand)
|
|
156
|
+
if (isPersistentServerCommand(rawCommand)) {
|
|
134
157
|
if (SERVER_READY_PATTERN.test(outputBuffer)) {
|
|
135
158
|
isDetached = true;
|
|
136
159
|
if (timeoutId)
|
|
@@ -140,9 +163,9 @@ export const sysRun = {
|
|
|
140
163
|
child.unref();
|
|
141
164
|
resolve({
|
|
142
165
|
success: true,
|
|
143
|
-
output:
|
|
144
|
-
exitCode:
|
|
145
|
-
note: '
|
|
166
|
+
output: cleanSubprocessOutput(outputBuffer),
|
|
167
|
+
exitCode: null, running: true, ...(child.pid ? { pid: child.pid } : {}),
|
|
168
|
+
note: 'The server reported startup. This process is still running; an independent readiness check is required.'
|
|
146
169
|
});
|
|
147
170
|
}
|
|
148
171
|
}
|
|
@@ -157,7 +180,7 @@ export const sysRun = {
|
|
|
157
180
|
child.stdout?.on('data', appendToBuffer);
|
|
158
181
|
child.stderr?.on('data', appendToBuffer);
|
|
159
182
|
let serverGraceTimer;
|
|
160
|
-
if (isPersistentServerCommand(rawCommand)
|
|
183
|
+
if (isPersistentServerCommand(rawCommand)) {
|
|
161
184
|
serverGraceTimer = setTimeout(() => {
|
|
162
185
|
if (!isDetached && child.exitCode === null) {
|
|
163
186
|
isDetached = true;
|
|
@@ -166,9 +189,9 @@ export const sysRun = {
|
|
|
166
189
|
child.unref();
|
|
167
190
|
resolve({
|
|
168
191
|
success: true,
|
|
169
|
-
output:
|
|
170
|
-
exitCode:
|
|
171
|
-
note: '
|
|
192
|
+
output: cleanSubprocessOutput(outputBuffer) || 'Server process started and running in background.',
|
|
193
|
+
exitCode: null, running: true, ...(child.pid ? { pid: child.pid } : {}),
|
|
194
|
+
note: 'The process is still running. No final exit status or readiness check is available.'
|
|
172
195
|
});
|
|
173
196
|
}
|
|
174
197
|
}, 2500);
|
|
@@ -183,7 +206,7 @@ export const sysRun = {
|
|
|
183
206
|
child.kill('SIGKILL');
|
|
184
207
|
resolve({
|
|
185
208
|
success: false,
|
|
186
|
-
output:
|
|
209
|
+
output: cleanSubprocessOutput(outputBuffer),
|
|
187
210
|
error: `Process timed out after ${timeoutMs}ms`,
|
|
188
211
|
exitCode: 124
|
|
189
212
|
});
|
|
@@ -198,7 +221,7 @@ export const sysRun = {
|
|
|
198
221
|
clearTimeout(serverGraceTimer);
|
|
199
222
|
resolve({
|
|
200
223
|
success: false,
|
|
201
|
-
output:
|
|
224
|
+
output: cleanSubprocessOutput(outputBuffer),
|
|
202
225
|
error: err.message,
|
|
203
226
|
exitCode: 1
|
|
204
227
|
});
|
|
@@ -210,7 +233,7 @@ export const sysRun = {
|
|
|
210
233
|
clearTimeout(timeoutId);
|
|
211
234
|
if (serverGraceTimer)
|
|
212
235
|
clearTimeout(serverGraceTimer);
|
|
213
|
-
const cleanOutput =
|
|
236
|
+
const cleanOutput = cleanSubprocessOutput(outputBuffer);
|
|
214
237
|
const exitCode = typeof code === 'number' ? code : 1;
|
|
215
238
|
if (exitCode === 0) {
|
|
216
239
|
const res = { success: true, output: cleanOutput, exitCode: 0 };
|
|
@@ -224,7 +247,8 @@ export const sysRun = {
|
|
|
224
247
|
}
|
|
225
248
|
resolve(res);
|
|
226
249
|
}
|
|
227
|
-
else if (exitCode === 1 &&
|
|
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() || '')) {
|
|
228
252
|
// Semantic Exit Code Normalization: POSIX search tool found 0 matching lines.
|
|
229
253
|
const res = {
|
|
230
254
|
success: true,
|
|
@@ -276,7 +300,12 @@ export const sysRunBg = {
|
|
|
276
300
|
const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
|
|
277
301
|
const shellArgs = os.platform() === 'win32' ? ['/c', args.command] : ['-c', args.command];
|
|
278
302
|
return await new Promise(resolve => {
|
|
279
|
-
const child = spawn(shell, shellArgs, {
|
|
303
|
+
const child = spawn(shell, shellArgs, {
|
|
304
|
+
cwd,
|
|
305
|
+
detached: true,
|
|
306
|
+
stdio: 'ignore',
|
|
307
|
+
...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
|
|
308
|
+
});
|
|
280
309
|
child.once('error', error => resolve({ success: false, error: error.message }));
|
|
281
310
|
child.once('spawn', () => {
|
|
282
311
|
child.unref();
|
package/src/tools/sysRun.ts
CHANGED
|
@@ -24,7 +24,9 @@ export interface SysRunResult {
|
|
|
24
24
|
success: boolean;
|
|
25
25
|
output: string;
|
|
26
26
|
error?: string | undefined;
|
|
27
|
-
exitCode: number;
|
|
27
|
+
exitCode: number | null;
|
|
28
|
+
running?: boolean;
|
|
29
|
+
pid?: number;
|
|
28
30
|
note?: string | undefined;
|
|
29
31
|
cached?: boolean | undefined;
|
|
30
32
|
}
|
|
@@ -60,6 +62,21 @@ export function stripAnsi(str: string): string {
|
|
|
60
62
|
return str.replace(new RegExp(pattern, 'g'), '');
|
|
61
63
|
}
|
|
62
64
|
|
|
65
|
+
/**
|
|
66
|
+
* Strips ANSI escape sequences, normalizes carriage returns, and filters
|
|
67
|
+
* transient progress meters (curl, wget) so agent history and split-panes never glitch.
|
|
68
|
+
*/
|
|
69
|
+
export function cleanSubprocessOutput(str: string): string {
|
|
70
|
+
const normalized = stripAnsi(str)
|
|
71
|
+
.replace(/\r\n/g, '\n')
|
|
72
|
+
.replace(/\r/g, '\n');
|
|
73
|
+
|
|
74
|
+
return normalized
|
|
75
|
+
.split('\n')
|
|
76
|
+
.filter(line => !/^\s*(?:%\s+Total\b|Dload\s+Upload\b|\d+\s+\d+(?:\.[0-9kKmM]+)?\s+\d+\s+.*--:--:--)/i.test(line))
|
|
77
|
+
.join('\n');
|
|
78
|
+
}
|
|
79
|
+
|
|
63
80
|
/**
|
|
64
81
|
* Commands whose exit code 1 indicates a normal query result (e.g. no matches found,
|
|
65
82
|
* differences found, or condition evaluated to false) rather than a system error.
|
|
@@ -70,8 +87,10 @@ export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test
|
|
|
70
87
|
* Commands that are strictly read-only and idempotent.
|
|
71
88
|
* Repeated identical executions within a short TTL window return cached output.
|
|
72
89
|
*/
|
|
73
|
-
|
|
74
|
-
|
|
90
|
+
// Git inspection commands can invoke configured helpers or write --output
|
|
91
|
+
// files. Execute them normally instead of memoizing a name-based assumption.
|
|
92
|
+
export const IDEMPOTENT_COMMAND_PATTERN = /^(?!.*[;&|<>`$\r\n])(?:(?:python[0-9.]*|node|bun|npm|pnpm)\s+(?:-v|-V|--version)|pwd|(?:ls|dir|cat|type|head|tail|grep|which|where|echo)(?:\s+[^;&|<>`$\r\n]+)?)$/;
|
|
93
|
+
|
|
75
94
|
|
|
76
95
|
/**
|
|
77
96
|
* Detect long-running dev servers and web application listeners that must not block foreground loops.
|
|
@@ -79,7 +98,9 @@ export const IDEMPOTENT_COMMAND_PATTERN =
|
|
|
79
98
|
export function isPersistentServerCommand(cmd: string): boolean {
|
|
80
99
|
if (!cmd || typeof cmd !== 'string') return false;
|
|
81
100
|
const trimmed = cmd.trim();
|
|
82
|
-
|
|
101
|
+
// A chained launch/check command must run through its actual final exit.
|
|
102
|
+
// Returning at a readiness-looking line would skip later checks or failures.
|
|
103
|
+
if (/[;&|<>`$\r\n]/.test(trimmed) || /^(?:cat|head|tail|grep|lsof|ps|kill|pkill|pgrep|curl|wget|echo|test)\b/i.test(trimmed)) {
|
|
83
104
|
return false;
|
|
84
105
|
}
|
|
85
106
|
const patterns = [
|
|
@@ -136,15 +157,16 @@ export const sysRun = {
|
|
|
136
157
|
// A foreground server waits forever for requests. Keep launch-only turns
|
|
137
158
|
// responsive and make it explicit that starting is not a readiness check.
|
|
138
159
|
const taskPrompt = context.parentLoop?.currentTaskPrompt || context.parentLoop?.userPrompt || '';
|
|
139
|
-
if (isLaunchOnlyPrompt(taskPrompt) && isServerLaunchCommand(rawCommand)) {
|
|
160
|
+
if (isLaunchOnlyPrompt(taskPrompt) && !/[;&|<>`$\r\n]/.test(rawCommand) && isServerLaunchCommand(rawCommand)) {
|
|
140
161
|
const started = await sysRunBg.execute({ command: rawCommand, cwd, label: 'local-server' });
|
|
141
162
|
return started.success
|
|
142
|
-
? { success: true, output: `Started server process ${started.pid} in background. Readiness and browser opening have not been verified.`, exitCode:
|
|
163
|
+
? { success: true, output: `Started server process ${started.pid} in background. Readiness and browser opening have not been verified.`, exitCode: null, running: true, ...(started.pid !== undefined ? { pid: started.pid } : {}), note: 'Check the server URL before reporting it accessible.' }
|
|
143
164
|
: { success: false, output: '', error: started.error || 'Unable to start server process.', exitCode: 1 };
|
|
144
165
|
}
|
|
145
166
|
|
|
146
167
|
// Fast-path: Return cached output for identical read-only idempotent commands
|
|
147
168
|
const isIdempotent = IDEMPOTENT_COMMAND_PATTERN.test(rawCommand);
|
|
169
|
+
if (!isIdempotent) commandCache.clear();
|
|
148
170
|
const cacheKey = `${cwd}:::${rawCommand}`;
|
|
149
171
|
|
|
150
172
|
if (!context.skipCache && isIdempotent && commandCache.has(cacheKey)) {
|
|
@@ -172,7 +194,11 @@ export const sysRun = {
|
|
|
172
194
|
|
|
173
195
|
let child: ReturnType<typeof spawn>;
|
|
174
196
|
try {
|
|
175
|
-
child = spawn(shell, shellArgs, {
|
|
197
|
+
child = spawn(shell, shellArgs, {
|
|
198
|
+
cwd,
|
|
199
|
+
signal,
|
|
200
|
+
...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
|
|
201
|
+
});
|
|
176
202
|
} catch (err: unknown) {
|
|
177
203
|
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
178
204
|
resolve({
|
|
@@ -191,7 +217,7 @@ export const sysRun = {
|
|
|
191
217
|
|
|
192
218
|
const checkServerDetach = (): void => {
|
|
193
219
|
if (isDetached) return;
|
|
194
|
-
if (isPersistentServerCommand(rawCommand)
|
|
220
|
+
if (isPersistentServerCommand(rawCommand)) {
|
|
195
221
|
if (SERVER_READY_PATTERN.test(outputBuffer)) {
|
|
196
222
|
isDetached = true;
|
|
197
223
|
if (timeoutId) clearTimeout(timeoutId);
|
|
@@ -199,9 +225,9 @@ export const sysRun = {
|
|
|
199
225
|
child.unref();
|
|
200
226
|
resolve({
|
|
201
227
|
success: true,
|
|
202
|
-
output:
|
|
203
|
-
exitCode:
|
|
204
|
-
note: '
|
|
228
|
+
output: cleanSubprocessOutput(outputBuffer),
|
|
229
|
+
exitCode: null, running: true, ...(child.pid ? { pid: child.pid } : {}),
|
|
230
|
+
note: 'The server reported startup. This process is still running; an independent readiness check is required.'
|
|
205
231
|
});
|
|
206
232
|
}
|
|
207
233
|
}
|
|
@@ -219,7 +245,7 @@ export const sysRun = {
|
|
|
219
245
|
child.stderr?.on('data', appendToBuffer);
|
|
220
246
|
|
|
221
247
|
let serverGraceTimer: NodeJS.Timeout | undefined;
|
|
222
|
-
if (isPersistentServerCommand(rawCommand)
|
|
248
|
+
if (isPersistentServerCommand(rawCommand)) {
|
|
223
249
|
serverGraceTimer = setTimeout(() => {
|
|
224
250
|
if (!isDetached && child.exitCode === null) {
|
|
225
251
|
isDetached = true;
|
|
@@ -227,9 +253,9 @@ export const sysRun = {
|
|
|
227
253
|
child.unref();
|
|
228
254
|
resolve({
|
|
229
255
|
success: true,
|
|
230
|
-
output:
|
|
231
|
-
exitCode:
|
|
232
|
-
note: '
|
|
256
|
+
output: cleanSubprocessOutput(outputBuffer) || 'Server process started and running in background.',
|
|
257
|
+
exitCode: null, running: true, ...(child.pid ? { pid: child.pid } : {}),
|
|
258
|
+
note: 'The process is still running. No final exit status or readiness check is available.'
|
|
233
259
|
});
|
|
234
260
|
}
|
|
235
261
|
}, 2500);
|
|
@@ -243,7 +269,7 @@ export const sysRun = {
|
|
|
243
269
|
child.kill('SIGKILL');
|
|
244
270
|
resolve({
|
|
245
271
|
success: false,
|
|
246
|
-
output:
|
|
272
|
+
output: cleanSubprocessOutput(outputBuffer),
|
|
247
273
|
error: `Process timed out after ${timeoutMs}ms`,
|
|
248
274
|
exitCode: 124
|
|
249
275
|
});
|
|
@@ -256,7 +282,7 @@ export const sysRun = {
|
|
|
256
282
|
if (serverGraceTimer) clearTimeout(serverGraceTimer);
|
|
257
283
|
resolve({
|
|
258
284
|
success: false,
|
|
259
|
-
output:
|
|
285
|
+
output: cleanSubprocessOutput(outputBuffer),
|
|
260
286
|
error: err.message,
|
|
261
287
|
exitCode: 1
|
|
262
288
|
});
|
|
@@ -266,7 +292,7 @@ export const sysRun = {
|
|
|
266
292
|
if (isDetached) return;
|
|
267
293
|
if (timeoutId) clearTimeout(timeoutId);
|
|
268
294
|
if (serverGraceTimer) clearTimeout(serverGraceTimer);
|
|
269
|
-
const cleanOutput =
|
|
295
|
+
const cleanOutput = cleanSubprocessOutput(outputBuffer);
|
|
270
296
|
const exitCode = typeof code === 'number' ? code : 1;
|
|
271
297
|
|
|
272
298
|
if (exitCode === 0) {
|
|
@@ -280,7 +306,8 @@ export const sysRun = {
|
|
|
280
306
|
});
|
|
281
307
|
}
|
|
282
308
|
resolve(res);
|
|
283
|
-
} else if (exitCode === 1 &&
|
|
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() || '')) {
|
|
284
311
|
// Semantic Exit Code Normalization: POSIX search tool found 0 matching lines.
|
|
285
312
|
const res: SysRunResult = {
|
|
286
313
|
success: true,
|
|
@@ -332,7 +359,12 @@ export const sysRunBg = {
|
|
|
332
359
|
const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
|
|
333
360
|
const shellArgs = os.platform() === 'win32' ? ['/c', args.command] : ['-c', args.command];
|
|
334
361
|
return await new Promise<SysRunBgResult>(resolve => {
|
|
335
|
-
const child = spawn(shell, shellArgs, {
|
|
362
|
+
const child = spawn(shell, shellArgs, {
|
|
363
|
+
cwd,
|
|
364
|
+
detached: true,
|
|
365
|
+
stdio: 'ignore',
|
|
366
|
+
...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
|
|
367
|
+
});
|
|
336
368
|
child.once('error', error => resolve({ success: false, error: error.message }));
|
|
337
369
|
child.once('spawn', () => {
|
|
338
370
|
child.unref();
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { causyneHome } from '../utils/paths.js';
|
|
5
|
+
function sanitizeIdentifier(id) {
|
|
6
|
+
const cleaned = String(id || '').replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
7
|
+
return cleaned.length > 0 ? cleaned.slice(0, 64) : 'tool';
|
|
8
|
+
}
|
|
9
|
+
export class ToolOutputStore {
|
|
10
|
+
config;
|
|
11
|
+
constructor(customConfig) {
|
|
12
|
+
this.config = {
|
|
13
|
+
maxChars: customConfig?.maxChars ?? 2500,
|
|
14
|
+
maxLines: customConfig?.maxLines ?? 100,
|
|
15
|
+
maxBytes: customConfig?.maxBytes ?? 50 * 1024,
|
|
16
|
+
headLines: customConfig?.headLines ?? 35,
|
|
17
|
+
tailLines: customConfig?.tailLines ?? 35,
|
|
18
|
+
storageDir: customConfig?.storageDir ?? path.join(causyneHome(), 'tool-output')
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
getConfig() {
|
|
22
|
+
return { ...this.config };
|
|
23
|
+
}
|
|
24
|
+
processToolOutput(sessionId, toolCallId, rawOutput) {
|
|
25
|
+
const text = typeof rawOutput === 'string' ? rawOutput : String(rawOutput ?? '');
|
|
26
|
+
const totalBytes = Buffer.byteLength(text, 'utf8');
|
|
27
|
+
const lines = text.split('\n');
|
|
28
|
+
const totalLines = lines.length;
|
|
29
|
+
const contentHash = crypto.createHash('sha256').update(text).digest('hex').slice(0, 12);
|
|
30
|
+
if (process.env.CAUSYNE_OUTPUT_SPILL === '0'
|
|
31
|
+
|| (text.length <= this.config.maxChars && totalLines <= this.config.maxLines && totalBytes <= this.config.maxBytes)) {
|
|
32
|
+
return {
|
|
33
|
+
contentForModel: text,
|
|
34
|
+
isTruncated: false,
|
|
35
|
+
totalLines,
|
|
36
|
+
totalBytes,
|
|
37
|
+
contentHash
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const safeSession = sanitizeIdentifier(sessionId);
|
|
41
|
+
const safeToolId = sanitizeIdentifier(toolCallId);
|
|
42
|
+
const sessionDir = path.join(this.config.storageDir, safeSession);
|
|
43
|
+
const diskPath = path.join(sessionDir, `${safeToolId}_${contentHash}.log`);
|
|
44
|
+
let temporaryPath;
|
|
45
|
+
try {
|
|
46
|
+
fs.mkdirSync(sessionDir, { recursive: true, mode: 0o700 });
|
|
47
|
+
if (fs.lstatSync(sessionDir).isSymbolicLink())
|
|
48
|
+
throw new Error('Output directory is a symlink');
|
|
49
|
+
temporaryPath = path.join(sessionDir, `.${crypto.randomUUID()}.tmp`);
|
|
50
|
+
fs.writeFileSync(temporaryPath, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
51
|
+
fs.renameSync(temporaryPath, diskPath);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
if (temporaryPath) {
|
|
55
|
+
try {
|
|
56
|
+
fs.unlinkSync(temporaryPath);
|
|
57
|
+
}
|
|
58
|
+
catch { /* already renamed or unavailable */ }
|
|
59
|
+
}
|
|
60
|
+
// Never discard an observation when its recovery file could not be saved.
|
|
61
|
+
return { contentForModel: text, isTruncated: false, totalLines, totalBytes, contentHash };
|
|
62
|
+
}
|
|
63
|
+
// Line bounds alone do not bound a minified file or a single huge JSON line.
|
|
64
|
+
const omittedLines = Math.max(0, totalLines - (this.config.headLines + this.config.tailLines));
|
|
65
|
+
const notice = [
|
|
66
|
+
`\n[... Causyne ToolOutputStore: ${omittedLines} lines (${Math.max(1, Math.round(totalBytes / 1024))} KB) truncated. Content Hash: ${contentHash} ...]`,
|
|
67
|
+
`[... Full log persisted to: ${diskPath} ...]`,
|
|
68
|
+
'[... Read or search a relevant range with fs_read or code_search_ripgrep; do not rerun the original tool ...]\n'
|
|
69
|
+
].join('\n');
|
|
70
|
+
let head = '';
|
|
71
|
+
let tail = '';
|
|
72
|
+
if (lines.length === 1) {
|
|
73
|
+
const budget = Math.max(0, this.config.maxChars - notice.length);
|
|
74
|
+
const half = Math.floor(budget / 2);
|
|
75
|
+
head = text.slice(0, half);
|
|
76
|
+
tail = text.slice(-half);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
const rawHead = lines.slice(0, this.config.headLines).join('\n');
|
|
80
|
+
const rawTail = lines.slice(-this.config.tailLines).join('\n');
|
|
81
|
+
const maxBudget = this.config.maxChars;
|
|
82
|
+
if (rawHead.length + rawTail.length + notice.length > maxBudget) {
|
|
83
|
+
const budget = Math.max(0, maxBudget - notice.length);
|
|
84
|
+
const half = Math.floor(budget / 2);
|
|
85
|
+
head = rawHead.slice(0, half);
|
|
86
|
+
tail = rawTail.slice(-half);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
head = rawHead;
|
|
90
|
+
tail = rawTail;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const contentForModel = head + notice + tail;
|
|
94
|
+
return {
|
|
95
|
+
contentForModel,
|
|
96
|
+
isTruncated: true,
|
|
97
|
+
totalLines,
|
|
98
|
+
totalBytes,
|
|
99
|
+
contentHash,
|
|
100
|
+
diskPath
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
readSlice(diskPath, startLine, endLine) {
|
|
104
|
+
const resolvedPath = path.resolve(diskPath);
|
|
105
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
106
|
+
throw new Error(`ToolOutputStore: Log file not found at ${resolvedPath}`);
|
|
107
|
+
}
|
|
108
|
+
const relative = path.relative(fs.realpathSync(this.config.storageDir), fs.realpathSync(resolvedPath));
|
|
109
|
+
if (relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
|
|
110
|
+
throw new Error('ToolOutputStore: Requested file is outside the output store');
|
|
111
|
+
}
|
|
112
|
+
const lines = fs.readFileSync(resolvedPath, 'utf8').split('\n');
|
|
113
|
+
const clampedStart = Math.max(1, Math.min(startLine, lines.length));
|
|
114
|
+
const clampedEnd = Math.max(clampedStart, Math.min(endLine, lines.length));
|
|
115
|
+
return lines.slice(clampedStart - 1, clampedEnd).join('\n');
|
|
116
|
+
}
|
|
117
|
+
pruneOldOutputs(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
118
|
+
if (!fs.existsSync(this.config.storageDir))
|
|
119
|
+
return 0;
|
|
120
|
+
let pruned = 0;
|
|
121
|
+
const now = Date.now();
|
|
122
|
+
try {
|
|
123
|
+
const sessions = fs.readdirSync(this.config.storageDir);
|
|
124
|
+
for (const session of sessions) {
|
|
125
|
+
const sessionPath = path.join(this.config.storageDir, session);
|
|
126
|
+
const stat = fs.lstatSync(sessionPath);
|
|
127
|
+
if (stat.isDirectory()) {
|
|
128
|
+
const files = fs.readdirSync(sessionPath);
|
|
129
|
+
for (const file of files) {
|
|
130
|
+
const filePath = path.join(sessionPath, file);
|
|
131
|
+
const fileStat = fs.statSync(filePath);
|
|
132
|
+
if (now - fileStat.mtimeMs > maxAgeMs) {
|
|
133
|
+
fs.unlinkSync(filePath);
|
|
134
|
+
pruned++;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (fs.readdirSync(sessionPath).length === 0) {
|
|
138
|
+
fs.rmdirSync(sessionPath);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// Non-fatal cleanup
|
|
145
|
+
}
|
|
146
|
+
return pruned;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
export const defaultToolOutputStore = new ToolOutputStore();
|
|
150
|
+
export function processToolOutputWithStore(sessionId, toolCallId, rawOutput, store = defaultToolOutputStore) {
|
|
151
|
+
return store.processToolOutput(sessionId, toolCallId, rawOutput);
|
|
152
|
+
}
|
|
153
|
+
export function renderSpillDocument(result, meta = {}) {
|
|
154
|
+
if (typeof result === 'string')
|
|
155
|
+
return result;
|
|
156
|
+
if (result === null || typeof result !== 'object')
|
|
157
|
+
return String(result);
|
|
158
|
+
const header = [
|
|
159
|
+
'=== CAUSYNE TOOL OUTPUT (full, untruncated) ===',
|
|
160
|
+
`tool : ${meta.tool || 'unknown'}`,
|
|
161
|
+
`task : ${meta.taskId || 'unknown'} step: ${meta.step == null ? 'unknown' : meta.step}`,
|
|
162
|
+
`saved: ${new Date().toISOString()}`
|
|
163
|
+
];
|
|
164
|
+
const sections = [];
|
|
165
|
+
const scalars = [];
|
|
166
|
+
for (const [key, value] of Object.entries(result)) {
|
|
167
|
+
if (typeof value === 'string' && value.length > 500) {
|
|
168
|
+
sections.push(`\n--- field: ${key} (${value.length} chars) ---\n${value}`);
|
|
169
|
+
}
|
|
170
|
+
else if (value !== null && typeof value === 'object') {
|
|
171
|
+
sections.push(`\n--- field: ${key} (JSON) ---\n${JSON.stringify(value, null, 2)}`);
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
scalars.push(`${key}: ${JSON.stringify(value)}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (scalars.length > 0)
|
|
178
|
+
header.push('', ...scalars);
|
|
179
|
+
return header.join('\n') + '\n' + sections.join('\n') + '\n';
|
|
180
|
+
}
|