@causyne/agent 1.20.124 → 1.20.128
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/bin/causyne.js +1 -1
- package/docs/THIRD_PARTY_NOTICES.md +36 -2
- package/package.json +6 -4
- package/src/acp/protocol.ts +19 -1
- package/src/acp/server.js +282 -8
- package/src/acp/server.ts +284 -8
- package/src/agent/abortableDelay.js +2 -2
- package/src/agent/abortableDelay.ts +2 -2
- package/src/agent/errorClassifier.js +9 -1
- package/src/agent/errorClassifier.ts +8 -1
- package/src/agentLoop.js +142 -53
- package/src/agentLoop.ts +151 -50
- package/src/approvalPolicy.js +34 -10
- package/src/approvalPolicy.ts +42 -11
- package/src/browser/causyneBrowser.js +61 -3
- package/src/browser/causyneBrowser.ts +65 -3
- package/src/browser/urlPolicy.js +14 -1
- package/src/browser/urlPolicy.ts +12 -1
- package/src/cliMode.js +21 -9
- package/src/cliMode.ts +20 -8
- package/src/commands.js +365 -45
- package/src/commands.ts +403 -45
- package/src/config.js +19 -4
- package/src/config.ts +18 -4
- package/src/core/contextCompactor.js +54 -7
- package/src/core/contextCompactor.ts +63 -7
- package/src/core/goalLoop.js +257 -0
- package/src/core/goalLoop.ts +310 -0
- package/src/entrypoint.js +135 -3
- package/src/entrypoint.ts +136 -3
- package/src/game/causyneCoreBridge.js +686 -0
- package/src/game/causyneCoreBridge.ts +702 -0
- package/src/game/gameLauncher.js +287 -0
- package/src/game/gameLauncher.ts +352 -0
- package/src/game/gameProvisioner.js +425 -0
- package/src/game/gameProvisioner.ts +488 -0
- package/src/headlessCli.js +19 -12
- package/src/headlessCli.ts +22 -8
- package/src/infra/atomicWriter.js +40 -4
- package/src/infra/atomicWriter.ts +36 -4
- package/src/launchIntent.js +73 -3
- package/src/launchIntent.ts +76 -3
- package/src/lsp/lspClient.js +83 -12
- package/src/lsp/lspClient.ts +75 -12
- package/src/mcp/mcpRegistry.js +75 -8
- package/src/mcp/mcpRegistry.ts +70 -7
- package/src/memory/contextBudget.js +2 -0
- package/src/memory/contextBudget.ts +1 -0
- package/src/memory/episodicStore.js +40 -0
- package/src/memory/episodicStore.ts +46 -0
- package/src/memory.js +67 -0
- package/src/memory.ts +65 -0
- package/src/modelVariants.js +45 -0
- package/src/modelVariants.ts +54 -0
- package/src/outputRecovery.js +3 -2
- package/src/outputRecovery.ts +4 -2
- package/src/permissionPresets.js +327 -0
- package/src/permissionPresets.ts +361 -0
- package/src/personalization.js +365 -0
- package/src/personalization.ts +471 -0
- package/src/projectInstructions.js +30 -10
- package/src/projectInstructions.ts +31 -12
- package/src/providers/acp.js +3 -2
- package/src/providers/acp.ts +3 -2
- package/src/providers/antigravity.js +64 -9
- package/src/providers/antigravity.ts +75 -9
- package/src/providers/byokHttp.js +7 -1
- package/src/providers/byokHttp.ts +6 -1
- package/src/providers/byokStream.js +21 -8
- package/src/providers/byokStream.ts +17 -7
- package/src/providers/dashscope-byok.js +21 -5
- package/src/providers/dashscope-byok.ts +29 -11
- package/src/providers/moonshot.js +26 -7
- package/src/providers/moonshot.ts +34 -13
- package/src/providers/muse.js +6 -0
- package/src/providers/muse.ts +8 -0
- package/src/providers/ollama.js +39 -7
- package/src/providers/ollama.ts +36 -7
- package/src/providers/openai-compatible.js +16 -3
- package/src/providers/openai-compatible.ts +13 -3
- package/src/providers/openai.js +62 -4
- package/src/providers/openai.ts +50 -4
- package/src/providers/openrouter.js +19 -4
- package/src/providers/openrouter.ts +21 -4
- package/src/providers/qwen-byok.js +21 -5
- package/src/providers/qwen-byok.ts +29 -11
- package/src/providers/xai.js +26 -10
- package/src/providers/xai.ts +34 -16
- package/src/reporting.js +4 -2
- package/src/reporting.ts +4 -2
- package/src/sandbox.js +34 -0
- package/src/sandbox.ts +43 -0
- package/src/scheduler/scheduler.js +372 -0
- package/src/scheduler/scheduler.ts +433 -0
- package/src/sessionSearchIndex.js +267 -0
- package/src/sessionSearchIndex.ts +311 -0
- package/src/skillsManager.js +2 -3
- package/src/skillsManager.ts +2 -3
- package/src/toolPacks.js +6 -0
- package/src/toolPacks.ts +6 -0
- package/src/tools/applyPatch.js +1 -1
- package/src/tools/applyPatch.ts +1 -1
- package/src/tools/generateMediaViaApi.js +4 -3
- package/src/tools/generateMediaViaApi.ts +4 -3
- package/src/tools/memoryWrite.js +15 -1
- package/src/tools/memoryWrite.ts +16 -1
- package/src/tools/nativeEngine.js +2 -2
- package/src/tools/nativeEngine.ts +2 -2
- package/src/tools/openSourceToolProvisioner.js +2 -2
- package/src/tools/openSourceToolProvisioner.ts +2 -2
- package/src/tools/osSandbox.js +1 -1
- package/src/tools/osSandbox.ts +1 -1
- package/src/tools/payloadSanitizer.js +0 -1
- package/src/tools/payloadSanitizer.ts +0 -1
- package/src/tools/pdfReader.js +122 -20
- package/src/tools/pdfReader.ts +111 -20
- package/src/tools/presentDeliverable.js +103 -0
- package/src/tools/presentDeliverable.ts +127 -0
- package/src/tools/ptcRuntime.js +444 -0
- package/src/tools/ptcRuntime.ts +490 -0
- package/src/tools/ptyTerminal.js +1108 -0
- package/src/tools/ptyTerminal.ts +1245 -0
- package/src/tools/registry.js +21 -12
- package/src/tools/registry.ts +21 -12
- package/src/tools/toolOutputStore.js +26 -4
- package/src/tools/toolOutputStore.ts +22 -4
- package/src/tools/webFetch.js +158 -11
- package/src/tools/webFetch.ts +145 -11
- package/src/tools/webSearch.js +123 -36
- package/src/tools/webSearch.ts +124 -33
- package/src/tui/banner.js +5 -1
- package/src/tui/banner.ts +6 -1
- package/src/tui/chatRenderer.js +1 -2
- package/src/tui/chatRenderer.ts +1 -2
- package/src/tui/completion.js +1 -0
- package/src/tui/completion.ts +1 -0
- package/src/tui/composerControls.js +111 -27
- package/src/tui/composerControls.ts +124 -28
- package/src/tui/dialogs.js +3 -16
- package/src/tui/dialogs.ts +3 -16
- package/src/tui/home.js +1 -0
- package/src/tui/home.ts +1 -0
- package/src/tui/invocation.js +1 -2
- package/src/tui/invocation.ts +1 -2
- package/src/tui/modelPicker.js +22 -12
- package/src/tui/modelPicker.ts +22 -12
- package/src/tui/overlay.js +2 -5
- package/src/tui/overlay.ts +2 -5
- package/src/tui/prompt.js +6 -4
- package/src/tui/prompt.ts +6 -4
- package/src/tui/selectList.js +4 -12
- package/src/tui/selectList.ts +4 -12
- package/src/tui/setup.js +22 -9
- package/src/tui/setup.ts +26 -9
- package/src/tui/statusLine.ts +2 -0
- package/src/web/client/browserPanel.js +905 -0
- package/src/web/client/browserPanel.ts +872 -0
- package/src/web/client/chatStream.js +321 -0
- package/src/web/client/chatStream.ts +297 -0
- package/src/web/client/cliPanel.js +165 -0
- package/src/web/client/cliPanel.ts +171 -0
- package/src/web/client/composer.js +204 -0
- package/src/web/client/composer.ts +209 -0
- package/src/web/client/diffPanel.js +176 -0
- package/src/web/client/diffPanel.ts +203 -0
- package/src/web/client/dom.js +271 -0
- package/src/web/client/dom.ts +272 -0
- package/src/web/client/filesAndCanvas.js +233 -0
- package/src/web/client/filesAndCanvas.ts +240 -0
- package/src/web/client/gameLauncherUi.js +78 -0
- package/src/web/client/gameLauncherUi.ts +78 -0
- package/src/web/client/main.js +316 -0
- package/src/web/client/main.ts +391 -0
- package/src/web/client/markdown.js +364 -0
- package/src/web/client/markdown.ts +373 -0
- package/src/web/client/modelPicker.js +455 -0
- package/src/web/client/modelPicker.ts +451 -0
- package/src/web/client/permissionPresetsUi.js +307 -0
- package/src/web/client/permissionPresetsUi.ts +333 -0
- package/src/web/client/sessions.js +353 -0
- package/src/web/client/sessions.ts +372 -0
- package/src/web/client/settingsModal.js +824 -0
- package/src/web/client/settingsModal.ts +959 -0
- package/src/web/client/state.js +280 -0
- package/src/web/client/state.ts +259 -0
- package/src/web/client/streamSmoother.js +127 -0
- package/src/web/client/streamSmoother.ts +119 -0
- package/src/web/client/studioLayout.js +89 -0
- package/src/web/client/studioLayout.ts +103 -0
- package/src/web/client/studioShell.js +660 -0
- package/src/web/client/studioShell.ts +672 -0
- package/src/web/client/studioStart.js +77 -0
- package/src/web/client/studioStart.ts +89 -0
- package/src/web/client/terminalPanel.js +606 -0
- package/src/web/client/terminalPanel.ts +632 -0
- package/src/web/client/terminalTheme.js +249 -0
- package/src/web/client/terminalTheme.ts +258 -0
- package/src/web/client/turnView.js +934 -0
- package/src/web/client/turnView.ts +981 -0
- package/src/web/client/types.js +1 -0
- package/src/web/client/types.ts +322 -0
- package/src/web/client/validators.js +147 -0
- package/src/web/client/validators.ts +140 -0
- package/src/web/server/activeRuns.js +152 -0
- package/src/web/server/activeRuns.ts +171 -0
- package/src/web/server/routesBrowser.js +409 -0
- package/src/web/server/routesBrowser.ts +435 -0
- package/src/web/server/routesChat.js +304 -0
- package/src/web/server/routesChat.ts +347 -0
- package/src/web/server/routesCore.js +472 -0
- package/src/web/server/routesCore.ts +522 -0
- package/src/web/server/routesSettings.js +344 -0
- package/src/web/server/routesSettings.ts +397 -0
- package/src/web/server/routesTerminal.js +162 -0
- package/src/web/server/routesTerminal.ts +182 -0
- package/src/web/server/routesWorkspace.js +510 -0
- package/src/web/server/routesWorkspace.ts +546 -0
- package/src/web/server/security.js +98 -0
- package/src/web/server/security.ts +108 -0
- package/src/web/server/sessionTranscript.js +586 -0
- package/src/web/server/sessionTranscript.ts +566 -0
- package/src/web/server/staticAssets.js +104 -0
- package/src/web/server/staticAssets.ts +116 -0
- package/src/web/server/types.js +1 -0
- package/src/web/server/types.ts +135 -0
- package/src/web/server/workspaceFiles.js +368 -0
- package/src/web/server/workspaceFiles.ts +363 -0
- package/src/web/skybridgeServer.js +78 -2448
- package/src/web/skybridgeServer.ts +120 -2600
- package/src/web/skybridgeUi.js +20 -450
- package/src/web/skybridgeUi.ts +24 -455
- package/src/web/styles/agent.css +380 -0
- package/src/web/styles/composer.css +193 -0
- package/src/web/styles/overlays.css +935 -0
- package/src/web/styles/shell.css +387 -0
- package/src/web/styles/studio.css +951 -0
- package/src/web/styles/thread.css +221 -0
- package/src/web/styles/tokens.css +94 -0
- package/src/web/ui/brandMark.js +73 -0
- package/src/web/ui/brandMark.ts +82 -0
- package/src/web/ui/modalsTemplate.js +388 -0
- package/src/web/ui/modalsTemplate.ts +388 -0
- package/src/web/ui/sidebarTemplate.js +63 -0
- package/src/web/ui/sidebarTemplate.ts +64 -0
- package/src/web/ui/studioTemplate.js +256 -0
- package/src/web/ui/studioTemplate.ts +256 -0
- package/src/web/ui/workspaceTemplate.js +72 -0
- package/src/web/ui/workspaceTemplate.ts +73 -0
- package/src/worktreeManager.js +16 -1
- package/src/worktreeManager.ts +22 -1
- package/src/web/skybridgeClientScript.js +0 -3951
- package/src/web/skybridgeClientScript.ts +0 -3952
- package/src/web/skybridgeStyles.js +0 -827
- package/src/web/skybridgeStyles.ts +0 -828
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Programmatic Tool Calling Runtime (`run_code`)
|
|
3
|
+
*
|
|
4
|
+
* Executes bounded TypeScript/JavaScript orchestration scripts inside an isolated
|
|
5
|
+
* Node child process (OS-sandboxed via `osSandbox.ts`, scrubbed `process.env = {}`,
|
|
6
|
+
* V8 heap cap `--max-old-space-size=256`, wall-clock timeout, and dedicated
|
|
7
|
+
* NDJSON-RPC control pipe).
|
|
8
|
+
*
|
|
9
|
+
* Inside the script:
|
|
10
|
+
* - `await tools.<tool_name>(args)` invokes safe, sandbox-validated Causyne tools
|
|
11
|
+
* (including `Promise.all(...)` concurrent reads and programmatic filtering).
|
|
12
|
+
* - `inspect(...values)` records only the final distilled results to return to the
|
|
13
|
+
* model context, preventing large intermediate payloads from polluting history.
|
|
14
|
+
*
|
|
15
|
+
* Security invariants:
|
|
16
|
+
* - Every host tool sub-call passes through workspace sandbox validation and refuses
|
|
17
|
+
* recursive `run_code` or unapproved destructive/shell operations.
|
|
18
|
+
* - Strictly additive per ACP capability policy; never strips peer-native tools.
|
|
19
|
+
*/
|
|
20
|
+
import { spawn } from 'node:child_process';
|
|
21
|
+
import { createRequire } from 'node:module';
|
|
22
|
+
import { resolveOsSandboxMode, wrapCommandWithOsSandbox } from './osSandbox.js';
|
|
23
|
+
import { boundedInteger, getErrorMessage, resolveToolWorkspaceRoots, sanitizeToolError } from './toolPathSafety.js';
|
|
24
|
+
import { redactTextSecrets } from '../providers/byokHttp.js';
|
|
25
|
+
import { fsRead } from './fsRead.js';
|
|
26
|
+
import { fsList } from './fsList.js';
|
|
27
|
+
import { fsFind } from './fsFind.js';
|
|
28
|
+
import { fsSearch } from './fsSearch.js';
|
|
29
|
+
import { codeSearcher } from './codeSearcher.js';
|
|
30
|
+
import { codebaseSearch } from './codebaseSearch.js';
|
|
31
|
+
import { codeVerifySyntax, codeListSymbols } from './codeTools.js';
|
|
32
|
+
import { codeSearchAst } from './codeSearchAst.js';
|
|
33
|
+
import { repoMapTool } from './repoMap.js';
|
|
34
|
+
import { pdfRead } from './pdfReader.js';
|
|
35
|
+
import { webSearch } from './webSearch.js';
|
|
36
|
+
import { webFetch } from './webFetch.js';
|
|
37
|
+
const MAX_CODE_CHARS = 32_000;
|
|
38
|
+
const MAX_OUTPUT_CHARS = 24_000;
|
|
39
|
+
const MAX_SUB_CALLS_PER_RUN = 40;
|
|
40
|
+
const MAX_PENDING_CALLS = 8;
|
|
41
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
42
|
+
const MAX_TIMEOUT_MS = 60_000;
|
|
43
|
+
const PTC_ALLOWED_TOOLS = Object.freeze({
|
|
44
|
+
fs_read: fsRead,
|
|
45
|
+
fs_list: fsList,
|
|
46
|
+
fs_find: fsFind,
|
|
47
|
+
fs_search: fsSearch,
|
|
48
|
+
code_search_ripgrep: codeSearcher,
|
|
49
|
+
codebase_search: codebaseSearch,
|
|
50
|
+
code_verify_syntax: codeVerifySyntax,
|
|
51
|
+
code_list_symbols: codeListSymbols,
|
|
52
|
+
code_search_ast: codeSearchAst,
|
|
53
|
+
code_repo_map: repoMapTool,
|
|
54
|
+
pdf_read: pdfRead,
|
|
55
|
+
web_search: webSearch,
|
|
56
|
+
web_fetch: webFetch
|
|
57
|
+
});
|
|
58
|
+
const PTC_WORKER_SCRIPT = `
|
|
59
|
+
'use strict';
|
|
60
|
+
const fs = require('node:fs');
|
|
61
|
+
const vm = require('node:vm');
|
|
62
|
+
const mod = require('node:module');
|
|
63
|
+
|
|
64
|
+
const rpcIn = fs.createReadStream(null, { fd: 3, encoding: 'utf8' });
|
|
65
|
+
const rpcOut = fs.createWriteStream(null, { fd: 4 });
|
|
66
|
+
|
|
67
|
+
let nextId = 1;
|
|
68
|
+
const pending = new Map();
|
|
69
|
+
const inspected = [];
|
|
70
|
+
let inspectedChars = 0;
|
|
71
|
+
const MAX_INSPECT_CHARS = 24000;
|
|
72
|
+
|
|
73
|
+
function sendRpc(obj) {
|
|
74
|
+
try {
|
|
75
|
+
rpcOut.write(JSON.stringify(obj) + '\\n');
|
|
76
|
+
} catch {}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let inBuf = '';
|
|
80
|
+
rpcIn.on('data', (chunk) => {
|
|
81
|
+
inBuf += chunk;
|
|
82
|
+
let nl = inBuf.indexOf('\\n');
|
|
83
|
+
while (nl !== -1) {
|
|
84
|
+
const line = inBuf.slice(0, nl).trim();
|
|
85
|
+
inBuf = inBuf.slice(nl + 1);
|
|
86
|
+
if (line) {
|
|
87
|
+
try {
|
|
88
|
+
const msg = JSON.parse(line);
|
|
89
|
+
if (msg.type === 'run') {
|
|
90
|
+
void executeScript(msg.code, msg.toolNames || []);
|
|
91
|
+
} else if (msg.type === 'tool_result') {
|
|
92
|
+
const slot = pending.get(msg.id);
|
|
93
|
+
if (slot) {
|
|
94
|
+
pending.delete(msg.id);
|
|
95
|
+
if (msg.ok) slot.resolve(msg.result);
|
|
96
|
+
else slot.reject(new Error(msg.error || 'Tool call failed'));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
} catch {}
|
|
100
|
+
}
|
|
101
|
+
nl = inBuf.indexOf('\\n');
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
function callHostTool(name, args) {
|
|
106
|
+
const id = nextId++;
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
pending.set(id, { resolve, reject });
|
|
109
|
+
sendRpc({ type: 'tool_call', id, name, args: args && typeof args === 'object' ? args : {} });
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function formatInspectValue(val) {
|
|
114
|
+
if (typeof val === 'string') return val;
|
|
115
|
+
try {
|
|
116
|
+
return JSON.stringify(val, null, 2);
|
|
117
|
+
} catch {
|
|
118
|
+
return String(val);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function inspect(...values) {
|
|
123
|
+
for (const val of values) {
|
|
124
|
+
const text = formatInspectValue(val);
|
|
125
|
+
if (inspectedChars + text.length > MAX_INSPECT_CHARS) {
|
|
126
|
+
const remaining = Math.max(0, MAX_INSPECT_CHARS - inspectedChars);
|
|
127
|
+
if (remaining > 0) inspected.push(text.slice(0, remaining) + '\\n...[truncated]');
|
|
128
|
+
inspectedChars = MAX_INSPECT_CHARS;
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
inspected.push(text);
|
|
132
|
+
inspectedChars += text.length;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function executeScript(rawCode, toolNames) {
|
|
137
|
+
try {
|
|
138
|
+
const wrappedSrc = 'async (tools, inspect, console) => {\\n' + String(rawCode || '') + '\\n}';
|
|
139
|
+
const jsCode = typeof mod.stripTypeScriptTypes === 'function'
|
|
140
|
+
? mod.stripTypeScriptTypes(wrappedSrc, { mode: 'strip' })
|
|
141
|
+
: wrappedSrc;
|
|
142
|
+
|
|
143
|
+
const toolsObj = Object.create(null);
|
|
144
|
+
for (const name of toolNames) {
|
|
145
|
+
toolsObj[name] = (args) => callHostTool(name, args);
|
|
146
|
+
}
|
|
147
|
+
Object.freeze(toolsObj);
|
|
148
|
+
|
|
149
|
+
const safeConsole = Object.freeze({
|
|
150
|
+
log: (...a) => inspect(...a),
|
|
151
|
+
info: (...a) => inspect(...a),
|
|
152
|
+
warn: (...a) => inspect('[warn]', ...a),
|
|
153
|
+
error: (...a) => inspect('[error]', ...a)
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
const script = new vm.Script('(' + jsCode + ')', { filename: 'causyne-ptc.ts' });
|
|
157
|
+
const fn = script.runInNewContext({
|
|
158
|
+
Promise,
|
|
159
|
+
JSON,
|
|
160
|
+
Math,
|
|
161
|
+
Date,
|
|
162
|
+
Array,
|
|
163
|
+
Object,
|
|
164
|
+
Map,
|
|
165
|
+
Set,
|
|
166
|
+
RegExp,
|
|
167
|
+
Number,
|
|
168
|
+
String,
|
|
169
|
+
Boolean,
|
|
170
|
+
Error,
|
|
171
|
+
TypeError,
|
|
172
|
+
RangeError,
|
|
173
|
+
URL,
|
|
174
|
+
URLSearchParams,
|
|
175
|
+
TextEncoder,
|
|
176
|
+
TextDecoder,
|
|
177
|
+
Intl,
|
|
178
|
+
setTimeout,
|
|
179
|
+
clearTimeout
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
const returned = await fn(toolsObj, inspect, safeConsole);
|
|
183
|
+
if (returned !== undefined && inspected.length === 0) {
|
|
184
|
+
inspect(returned);
|
|
185
|
+
}
|
|
186
|
+
sendRpc({ type: 'done', ok: true, output: inspected.join('\\n') });
|
|
187
|
+
rpcOut.end(() => process.exit(0));
|
|
188
|
+
setTimeout(() => process.exit(0), 50).unref?.();
|
|
189
|
+
} catch (err) {
|
|
190
|
+
sendRpc({
|
|
191
|
+
type: 'done',
|
|
192
|
+
ok: false,
|
|
193
|
+
error: err && err.message ? String(err.message) : String(err),
|
|
194
|
+
output: inspected.join('\\n')
|
|
195
|
+
});
|
|
196
|
+
rpcOut.end(() => process.exit(0));
|
|
197
|
+
setTimeout(() => process.exit(0), 50).unref?.();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
sendRpc({ type: 'ready' });
|
|
202
|
+
`;
|
|
203
|
+
export async function executeProgrammaticScript(code, context = {}, options = {}) {
|
|
204
|
+
if (typeof code !== 'string' || !code.trim()) {
|
|
205
|
+
return { success: false, error: 'code must be a non-empty TypeScript/JavaScript snippet.' };
|
|
206
|
+
}
|
|
207
|
+
if (code.length > MAX_CODE_CHARS) {
|
|
208
|
+
return { success: false, error: `code exceeds maximum size (${MAX_CODE_CHARS} characters).` };
|
|
209
|
+
}
|
|
210
|
+
if (code.includes('\0')) {
|
|
211
|
+
return { success: false, error: 'code cannot contain NUL bytes.' };
|
|
212
|
+
}
|
|
213
|
+
const scope = resolveToolWorkspaceRoots(context);
|
|
214
|
+
const workspaceRoot = scope.primaryRoot || process.cwd();
|
|
215
|
+
const timeoutMs = boundedInteger(options.timeoutMs, DEFAULT_TIMEOUT_MS, 1000, MAX_TIMEOUT_MS);
|
|
216
|
+
const toolNames = Object.keys(PTC_ALLOWED_TOOLS);
|
|
217
|
+
const nodeArgs = ['--max-old-space-size=256', '-e', PTC_WORKER_SCRIPT];
|
|
218
|
+
const sandboxRes = resolveOsSandboxMode(process.env, typeof context.osSandbox === 'string' ? context.osSandbox : undefined);
|
|
219
|
+
const wrapped = wrapCommandWithOsSandbox(process.execPath, nodeArgs, {
|
|
220
|
+
mode: sandboxRes.mode,
|
|
221
|
+
strict: sandboxRes.strict,
|
|
222
|
+
allowNetwork: false,
|
|
223
|
+
cwd: workspaceRoot,
|
|
224
|
+
workspaceRoots: scope.roots.length > 0 ? scope.roots : [workspaceRoot]
|
|
225
|
+
});
|
|
226
|
+
// Use Node extra fds 3 (host->worker) and 4 (worker->host) so RPC never collides with stdout/stderr
|
|
227
|
+
const proc = spawn(wrapped.command, wrapped.args, {
|
|
228
|
+
cwd: workspaceRoot,
|
|
229
|
+
env: {},
|
|
230
|
+
stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'],
|
|
231
|
+
windowsHide: true
|
|
232
|
+
});
|
|
233
|
+
const hostToWorker = proc.stdio[3];
|
|
234
|
+
const workerToHost = proc.stdio[4];
|
|
235
|
+
if (!hostToWorker || !workerToHost) {
|
|
236
|
+
try {
|
|
237
|
+
proc.kill('SIGKILL');
|
|
238
|
+
}
|
|
239
|
+
catch { /* ignore */ }
|
|
240
|
+
return { success: false, error: 'Failed to initialize programmatic runtime RPC pipes.' };
|
|
241
|
+
}
|
|
242
|
+
let subCallsExecuted = 0;
|
|
243
|
+
let activeSubCalls = 0;
|
|
244
|
+
let settled = false;
|
|
245
|
+
let stderrTail = '';
|
|
246
|
+
proc.stderr?.on('data', (chunk) => {
|
|
247
|
+
stderrTail = (stderrTail + chunk.toString('utf8')).slice(-4096);
|
|
248
|
+
});
|
|
249
|
+
return new Promise((resolve) => {
|
|
250
|
+
const finish = (result) => {
|
|
251
|
+
if (settled)
|
|
252
|
+
return;
|
|
253
|
+
settled = true;
|
|
254
|
+
clearTimeout(timer);
|
|
255
|
+
context.signal?.removeEventListener('abort', onAbort);
|
|
256
|
+
try {
|
|
257
|
+
hostToWorker.end();
|
|
258
|
+
}
|
|
259
|
+
catch { /* ignore */ }
|
|
260
|
+
if (proc.exitCode !== null || proc.killed) {
|
|
261
|
+
resolve(result);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
let resolved = false;
|
|
265
|
+
const done = () => {
|
|
266
|
+
if (resolved)
|
|
267
|
+
return;
|
|
268
|
+
resolved = true;
|
|
269
|
+
clearTimeout(killTimer);
|
|
270
|
+
clearTimeout(waitTimer);
|
|
271
|
+
resolve(result);
|
|
272
|
+
};
|
|
273
|
+
proc.once('close', done);
|
|
274
|
+
proc.once('exit', done);
|
|
275
|
+
try {
|
|
276
|
+
proc.kill('SIGTERM');
|
|
277
|
+
}
|
|
278
|
+
catch { /* ignore */ }
|
|
279
|
+
const killTimer = setTimeout(() => {
|
|
280
|
+
try {
|
|
281
|
+
if (proc.exitCode === null)
|
|
282
|
+
proc.kill('SIGKILL');
|
|
283
|
+
}
|
|
284
|
+
catch { /* ignore */ }
|
|
285
|
+
}, 250);
|
|
286
|
+
killTimer.unref?.();
|
|
287
|
+
const waitTimer = setTimeout(done, 800);
|
|
288
|
+
waitTimer.unref?.();
|
|
289
|
+
};
|
|
290
|
+
const onAbort = () => {
|
|
291
|
+
finish({ success: false, error: 'Programmatic script execution aborted.', subCallsExecuted });
|
|
292
|
+
};
|
|
293
|
+
if (context.signal?.aborted) {
|
|
294
|
+
onAbort();
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
context.signal?.addEventListener('abort', onAbort, { once: true });
|
|
298
|
+
const timer = setTimeout(() => {
|
|
299
|
+
finish({
|
|
300
|
+
success: false,
|
|
301
|
+
error: `Programmatic script timed out after ${timeoutMs}ms.`,
|
|
302
|
+
subCallsExecuted
|
|
303
|
+
});
|
|
304
|
+
}, timeoutMs);
|
|
305
|
+
timer.unref?.();
|
|
306
|
+
const sendToWorker = (obj) => {
|
|
307
|
+
if (settled)
|
|
308
|
+
return;
|
|
309
|
+
try {
|
|
310
|
+
hostToWorker.write(`${JSON.stringify(obj)}\n`);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
// Worker pipe closed
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
let rpcBuf = '';
|
|
317
|
+
workerToHost.on('data', (chunk) => {
|
|
318
|
+
rpcBuf += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
|
|
319
|
+
let nl = rpcBuf.indexOf('\n');
|
|
320
|
+
while (nl !== -1) {
|
|
321
|
+
const line = rpcBuf.slice(0, nl).trim();
|
|
322
|
+
rpcBuf = rpcBuf.slice(nl + 1);
|
|
323
|
+
if (line) {
|
|
324
|
+
try {
|
|
325
|
+
const msg = JSON.parse(line);
|
|
326
|
+
if (msg.type === 'ready') {
|
|
327
|
+
sendToWorker({ type: 'run', code, toolNames });
|
|
328
|
+
}
|
|
329
|
+
else if (msg.type === 'tool_call' && typeof msg.id === 'number' && typeof msg.name === 'string') {
|
|
330
|
+
const callId = msg.id;
|
|
331
|
+
const toolName = msg.name;
|
|
332
|
+
const callArgs = msg.args && typeof msg.args === 'object' ? msg.args : {};
|
|
333
|
+
if (subCallsExecuted >= MAX_SUB_CALLS_PER_RUN) {
|
|
334
|
+
sendToWorker({
|
|
335
|
+
type: 'tool_result',
|
|
336
|
+
id: callId,
|
|
337
|
+
ok: false,
|
|
338
|
+
error: `Sub-call budget exceeded (${MAX_SUB_CALLS_PER_RUN} calls per script).`
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
else if (activeSubCalls >= MAX_PENDING_CALLS) {
|
|
342
|
+
sendToWorker({
|
|
343
|
+
type: 'tool_result',
|
|
344
|
+
id: callId,
|
|
345
|
+
ok: false,
|
|
346
|
+
error: `Too many concurrent tool calls (limit ${MAX_PENDING_CALLS}).`
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
else if (!Object.hasOwn(PTC_ALLOWED_TOOLS, toolName)) {
|
|
350
|
+
sendToWorker({
|
|
351
|
+
type: 'tool_result',
|
|
352
|
+
id: callId,
|
|
353
|
+
ok: false,
|
|
354
|
+
error: `Tool "${toolName}" is not permitted inside run_code.`
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
else {
|
|
358
|
+
subCallsExecuted++;
|
|
359
|
+
activeSubCalls++;
|
|
360
|
+
const impl = PTC_ALLOWED_TOOLS[toolName];
|
|
361
|
+
void impl.execute(callArgs, context)
|
|
362
|
+
.then((res) => {
|
|
363
|
+
sendToWorker({ type: 'tool_result', id: callId, ok: true, result: res });
|
|
364
|
+
})
|
|
365
|
+
.catch((err) => {
|
|
366
|
+
sendToWorker({ type: 'tool_result', id: callId, ok: false, error: getErrorMessage(err) });
|
|
367
|
+
})
|
|
368
|
+
.finally(() => {
|
|
369
|
+
activeSubCalls = Math.max(0, activeSubCalls - 1);
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
else if (msg.type === 'done') {
|
|
374
|
+
const rawOut = redactTextSecrets(String(msg.output || '')).slice(0, MAX_OUTPUT_CHARS);
|
|
375
|
+
if (msg.ok) {
|
|
376
|
+
finish({
|
|
377
|
+
success: true,
|
|
378
|
+
output: rawOut || '(script completed with no inspected output)',
|
|
379
|
+
subCallsExecuted,
|
|
380
|
+
availableTools: toolNames
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
else {
|
|
384
|
+
finish({
|
|
385
|
+
success: false,
|
|
386
|
+
error: redactTextSecrets(msg.error || 'Programmatic script failed.'),
|
|
387
|
+
...(rawOut ? { output: rawOut } : {}),
|
|
388
|
+
subCallsExecuted
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
// Ignore malformed line
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
nl = rpcBuf.indexOf('\n');
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
proc.on('exit', (exitCode) => {
|
|
401
|
+
if (!settled) {
|
|
402
|
+
finish({
|
|
403
|
+
success: false,
|
|
404
|
+
error: `Programmatic runtime exited unexpectedly (code ${String(exitCode)})${stderrTail ? `: ${redactTextSecrets(stderrTail.trim()).slice(0, 300)}` : ''}`,
|
|
405
|
+
subCallsExecuted
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
proc.on('error', (err) => {
|
|
410
|
+
finish({ success: false, error: sanitizeToolError(err), subCallsExecuted });
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
// Keep unused-import lint clean for optional CJS bridge reference
|
|
415
|
+
void createRequire;
|
|
416
|
+
export const runCodeTool = {
|
|
417
|
+
schema: {
|
|
418
|
+
name: 'run_code',
|
|
419
|
+
description: 'Execute a sandboxed TypeScript/JavaScript orchestration script that calls read/search workspace tools programmatically via `await tools.<name>(args)` (including `Promise.all`) and emits only concise distilled output via `inspect(...)`. Eliminates multi-turn context bloat for batch audits and aggregations.',
|
|
420
|
+
parameters: {
|
|
421
|
+
type: 'object',
|
|
422
|
+
properties: {
|
|
423
|
+
code: {
|
|
424
|
+
type: 'string',
|
|
425
|
+
description: 'Async function body in TypeScript or JavaScript. Available globals: `tools` (`fs_read`, `fs_list`, `fs_find`, `fs_search`, `code_search_ripgrep`, `codebase_search`, `code_verify_syntax`, `code_list_symbols`, `code_search_ast`, `code_repo_map`, `pdf_read`, `web_search`, `web_fetch`), `inspect(...values)`, and `console.log`.'
|
|
426
|
+
},
|
|
427
|
+
timeoutMs: {
|
|
428
|
+
type: 'integer',
|
|
429
|
+
description: 'Optional execution timeout in ms (1000-60000, default 30000).'
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
required: ['code'],
|
|
433
|
+
additionalProperties: false
|
|
434
|
+
}
|
|
435
|
+
},
|
|
436
|
+
async execute(args, context = {}) {
|
|
437
|
+
try {
|
|
438
|
+
return await executeProgrammaticScript(args?.code ?? '', context, { timeoutMs: args?.timeoutMs });
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
return { success: false, error: sanitizeToolError(error) };
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
};
|