plugin-agent-orchestrator 1.0.33 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/externalVersion.js +6 -6
  2. package/dist/server/collections/skill-executions.js +21 -0
  3. package/dist/server/plugin.js +132 -3
  4. package/dist/server/resources/agent-loop.js +1 -2
  5. package/dist/server/services/AgentLoopController.js +39 -1
  6. package/dist/server/services/AgentLoopService.js +3 -0
  7. package/dist/server/services/AgentRuntimeLifecycle.js +70 -0
  8. package/dist/server/services/FileManager.js +12 -0
  9. package/dist/server/services/NativeSubAgentObserver.js +20 -0
  10. package/dist/server/services/PlanningPromptService.js +95 -0
  11. package/dist/server/services/SandboxRunner.js +251 -56
  12. package/dist/server/services/TokenTracker.js +20 -0
  13. package/dist/server/services/WorkerEnvManager.js +76 -10
  14. package/dist/server/services/pythonGuardTemplate.js +105 -0
  15. package/dist/server/services/sandboxCapabilities.js +286 -0
  16. package/dist/server/skill-hub/plugin.js +98 -24
  17. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +53 -11
  18. package/dist/server/utils/skill-settings.js +1 -1
  19. package/package.json +47 -47
  20. package/src/server/__tests__/agent-runtime-lifecycle.test.ts +46 -0
  21. package/src/server/__tests__/planning-prompt-service.test.ts +23 -0
  22. package/src/server/__tests__/skill-sandbox-worker-mode.test.ts +15 -0
  23. package/src/server/collections/skill-executions.ts +21 -0
  24. package/src/server/plugin.ts +151 -0
  25. package/src/server/resources/agent-loop.ts +1 -2
  26. package/src/server/services/AgentLoopController.ts +50 -1
  27. package/src/server/services/AgentLoopService.ts +4 -0
  28. package/src/server/services/AgentRuntimeLifecycle.ts +64 -0
  29. package/src/server/services/FileManager.ts +16 -1
  30. package/src/server/services/NativeSubAgentObserver.ts +21 -0
  31. package/src/server/services/PlanningPromptService.ts +72 -0
  32. package/src/server/services/SandboxRunner.ts +341 -74
  33. package/src/server/services/TokenTracker.ts +26 -0
  34. package/src/server/services/WorkerEnvManager.ts +95 -9
  35. package/src/server/services/pythonGuardTemplate.ts +87 -0
  36. package/src/server/services/sandboxCapabilities.ts +348 -0
  37. package/src/server/skill-hub/plugin.ts +1099 -1016
  38. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +515 -470
  39. package/src/server/utils/skill-settings.ts +1 -0
@@ -0,0 +1,72 @@
1
+ const PLAN_KEYWORDS = [
2
+ 'kế hoạch',
3
+ 'lập kế hoạch',
4
+ 'lên kế hoạch',
5
+ 'kế hoạch hóa',
6
+ 'lập plan',
7
+ 'tạo kế hoạch',
8
+ 'xây dựng kế hoạch',
9
+ 'planning',
10
+ 'make a plan',
11
+ 'create a plan',
12
+ ];
13
+
14
+ // Word-boundary pattern for the standalone word "plan" to avoid matching
15
+ // "plane", "plank", "supplant", "explanation", etc.
16
+ const PLAN_WORD_PATTERN = /\bplan\b/i;
17
+
18
+ const PLANNING_PREFIX = `[PLAN MODE] The user's request may need a structured plan. First, analyze the request:
19
+
20
+ STEP 0 — Evaluate: Does this request truly require 3+ distinct steps (building, creating, deploying, researching, etc.)?
21
+ - NO → The user mentioned "plan" but this is a simple question or single action. Respond directly WITHOUT calling any agent_loop tools.
22
+ - YES → Proceed with the plan workflow below.
23
+
24
+ PLAN WORKFLOW (only if truly multi-step):
25
+ 1. Call \`agent_loop_start\` with a concrete step-by-step plan. Use small, executable steps with clear planKey values and proper dependsOn chains. Structure the user's goal clearly in the "goal" field.
26
+ 2. After the plan is approved, execute each step by calling \`agent_loop_update_step\` with status="running" before the action, then status="succeeded" or "failed" after.
27
+ 3. If execution diverges, call \`agent_loop_replan\` to update remaining steps.
28
+ 4. When all steps complete, call \`agent_loop_finish\`.
29
+
30
+ User request:
31
+ `;
32
+
33
+ export class PlanningPromptService {
34
+ static getMessageText(content: unknown): string {
35
+ if (typeof content === 'string') return content;
36
+ if (content && typeof content === 'object' && 'content' in content) {
37
+ const nested = (content as { content?: unknown }).content;
38
+ return typeof nested === 'string' ? nested : '';
39
+ }
40
+ return '';
41
+ }
42
+
43
+ shouldInjectPlanningPrompt(text: string): boolean {
44
+ if (!text) return false;
45
+ const normalized = text.toLowerCase();
46
+ if (PLAN_WORD_PATTERN.test(normalized)) return true;
47
+ return PLAN_KEYWORDS.some((keyword) => normalized.includes(keyword));
48
+ }
49
+
50
+ getPlanningPrefix(): string {
51
+ return PLANNING_PREFIX;
52
+ }
53
+
54
+ getPlanningInstructions(): string {
55
+ return PLANNING_PREFIX.replace(/User request:\s*$/, '').trim();
56
+ }
57
+
58
+ applyPlanningContext(messages: Array<{ role: string; content: unknown }>): boolean {
59
+ const shouldInject = messages.some(
60
+ (message) =>
61
+ message.role === 'user' &&
62
+ this.shouldInjectPlanningPrompt(PlanningPromptService.getMessageText(message.content)),
63
+ );
64
+ if (!shouldInject) return false;
65
+
66
+ messages.unshift({
67
+ role: 'system',
68
+ content: { type: 'text', content: this.getPlanningInstructions() },
69
+ });
70
+ return true;
71
+ }
72
+ }
@@ -1,12 +1,26 @@
1
- import { exec, ChildProcess, ExecException } from 'child_process';
2
- import { writeFileSync } from 'fs';
1
+ import { spawn } from 'child_process';
2
+ import { existsSync, writeFileSync } from 'fs';
3
3
  import { resolve, delimiter } from 'path';
4
4
  import { tmpdir } from 'os';
5
5
  import { FileManager, OutputFileInfo } from './FileManager';
6
6
  import { CodeValidator } from './CodeValidator';
7
+ import {
8
+ ensureSandboxCapabilities,
9
+ getPythonGuardDir,
10
+ SandboxCapabilities,
11
+ SandboxIdentity,
12
+ SandboxNetworkMode,
13
+ } from './sandboxCapabilities';
7
14
 
8
15
  const IS_WINDOWS = process.platform === 'win32';
9
16
 
17
+ /** stdout/stderr accumulation cap — matches the old exec() maxBuffer. */
18
+ const MAX_STDIO_BYTES = 10 * 1024 * 1024;
19
+
20
+ /** Only the head of stdout/stderr is ever returned to callers — don't retain more in memory. */
21
+ const MAX_STDOUT_CHARS = 5000;
22
+ const MAX_STDERR_CHARS = 2000;
23
+
10
24
  /** Resolve the python executable name per platform (python3 on *nix, python on Windows). */
11
25
  function pythonBinary() {
12
26
  return process.env.SKILL_HUB_PYTHON_BIN || (IS_WINDOWS ? 'python' : 'python3');
@@ -44,6 +58,120 @@ export interface ExecutionResult {
44
58
  timedOut?: boolean;
45
59
  }
46
60
 
61
+ export interface UlimitOptions {
62
+ language: 'node' | 'python';
63
+ memLimitMb: number;
64
+ timeoutSeconds: number;
65
+ maxOutputSizeMb: number;
66
+ /** Only apply -u when the child runs under the dedicated sandbox uid. */
67
+ includeNproc: boolean;
68
+ }
69
+
70
+ /**
71
+ * Fixed ulimit prefix for the POSIX shell wrapper. Every number is computed
72
+ * server-side and validated as a finite positive integer before interpolation;
73
+ * no per-execution user data ever enters this string.
74
+ */
75
+ export function buildUlimitPrefix(options: UlimitOptions): string {
76
+ const parts: string[] = [];
77
+ const add = (flag: string, value: number) => {
78
+ if (!Number.isFinite(value) || value <= 0) return;
79
+ parts.push(`ulimit ${flag} ${Math.floor(value)} 2>/dev/null;`);
80
+ };
81
+ if (options.language === 'python') {
82
+ // RLIMIT_AS would fatally crash modern Node at startup (V8 reserves a
83
+ // multi-GB virtual address space cage); Node memory is bounded by
84
+ // --max-old-space-size instead.
85
+ add('-v', options.memLimitMb * 1024); // KB
86
+ }
87
+ add('-t', options.timeoutSeconds + 5); // CPU-seconds safety net behind the wall-clock kill
88
+ add('-n', Number(process.env.SKILL_HUB_ULIMIT_NOFILE || 256));
89
+ add('-f', Math.ceil((options.maxOutputSizeMb * 1024 * 1024) / 512)); // POSIX 512-byte blocks, single file
90
+ if (options.includeNproc) {
91
+ // RLIMIT_NPROC is per real uid system-wide — only safe on the dedicated sandbox uid.
92
+ add('-u', Number(process.env.SKILL_HUB_ULIMIT_NPROC || 64));
93
+ }
94
+ return parts.join(' ');
95
+ }
96
+
97
+ export interface NodeArgsOptions {
98
+ memLimitMb: number;
99
+ scriptPath: string;
100
+ workDir: string;
101
+ outputDir: string;
102
+ skillDir?: string;
103
+ nodePathEntries: string[];
104
+ capabilities: SandboxCapabilities;
105
+ }
106
+
107
+ export function buildNodeArgs(options: NodeArgsOptions): string[] {
108
+ const args = [`--max-old-space-size=${options.memLimitMb}`];
109
+ const permissionEnabled = process.env.SKILL_HUB_NODE_PERMISSION !== 'false';
110
+ if (permissionEnabled && options.capabilities.nodePermissionFlag) {
111
+ args.push(options.capabilities.nodePermissionFlag);
112
+ const readDirs = new Set(
113
+ [options.workDir, tmpdir(), options.skillDir || '', ...options.nodePathEntries].filter(Boolean),
114
+ );
115
+ for (const dir of readDirs) {
116
+ args.push(`--allow-fs-read=${dir}`);
117
+ }
118
+ for (const dir of new Set([options.workDir, options.outputDir, tmpdir()])) {
119
+ args.push(`--allow-fs-write=${dir}`);
120
+ }
121
+ if (options.capabilities.nodePermissionAllowAddons) {
122
+ args.push('--allow-addons');
123
+ }
124
+ }
125
+ // Independent of the permission model and version-stable — always on.
126
+ args.push('--disallow-code-generation-from-strings');
127
+ args.push(options.scriptPath);
128
+ return args;
129
+ }
130
+
131
+ export interface BwrapArgsOptions {
132
+ workDir: string;
133
+ skillDir?: string;
134
+ sandboxWorkspace: string;
135
+ /** Extra host dirs (global NODE_PATH/PYTHONPATH entries) to expose read-only. */
136
+ extraReadOnlyDirs: string[];
137
+ env: Record<string, string>;
138
+ network: SandboxNetworkMode;
139
+ }
140
+
141
+ export function buildBwrapArgs(options: BwrapArgsOptions): string[] {
142
+ const args = ['--unshare-all', '--die-with-parent', '--new-session'];
143
+ const bound = new Set<string>();
144
+ const roBind = (path: string) => {
145
+ if (!path || bound.has(path) || !existsSync(path)) return;
146
+ bound.add(path);
147
+ args.push('--ro-bind', path, path);
148
+ };
149
+ // /bin and /lib are usually merged-usr symlinks on Debian; binding them
150
+ // explicitly keeps /bin/sh resolvable inside the mount namespace.
151
+ for (const path of ['/usr', '/bin', '/sbin', '/lib', '/lib64', '/etc/ssl', '/etc/alternatives']) {
152
+ roBind(path);
153
+ }
154
+ roBind(options.sandboxWorkspace); // node_modules, python_packages, py-guard
155
+ if (options.skillDir) roBind(options.skillDir);
156
+ for (const dir of options.extraReadOnlyDirs) roBind(dir);
157
+ if (options.network === 'inherit') {
158
+ args.push('--share-net');
159
+ for (const path of ['/etc/resolv.conf', '/etc/hosts', '/etc/nsswitch.conf']) {
160
+ roBind(path);
161
+ }
162
+ }
163
+ args.push('--bind', options.workDir, options.workDir); // covers workDir/output
164
+ args.push('--tmpfs', tmpdir());
165
+ args.push('--proc', '/proc');
166
+ args.push('--dev', '/dev');
167
+ args.push('--chdir', options.workDir);
168
+ args.push('--clearenv');
169
+ for (const [key, value] of Object.entries(options.env)) {
170
+ args.push('--setenv', key, value);
171
+ }
172
+ return args;
173
+ }
174
+
47
175
  export class SandboxRunner {
48
176
  private validator = new CodeValidator();
49
177
 
@@ -78,7 +206,10 @@ export class SandboxRunner {
78
206
  // which blocks stdlib-based network exfiltration (urllib/socket/etc.).
79
207
  this.validator.validateImports(code, language, packageWhitelist || []);
80
208
 
81
- // 2. Prepare workspace
209
+ // 2. Resolve worker capabilities (memoized after the first execution/boot).
210
+ const capabilities = await ensureSandboxCapabilities(this.logger, this.storagePath);
211
+
212
+ // 3. Prepare workspace
82
213
  const workDir = this.fileManager.createExecDir(execId);
83
214
  const outputDir = this.fileManager.getOutputDir(execId);
84
215
 
@@ -86,94 +217,225 @@ export class SandboxRunner {
86
217
  const scriptPath = resolve(workDir, filename);
87
218
  writeFileSync(scriptPath, code, 'utf-8');
88
219
 
220
+ // 3b. Privilege drop — only when the worker runs as root and the sandbox
221
+ // user resolved at init time. Hand the exec dir to that uid first.
222
+ let identity: SandboxIdentity | null =
223
+ !IS_WINDOWS && process.getuid?.() === 0 && capabilities.privilegeDropAvailable
224
+ ? capabilities.sandboxIdentity
225
+ : null;
226
+ if (identity) {
227
+ try {
228
+ this.fileManager.chownExecDir(execId, identity.uid, identity.gid);
229
+ } catch (error) {
230
+ this.logger.warn(
231
+ `[skill-hub] chown of exec dir failed for ${execId}; running without privilege drop: ${
232
+ (error as Error).message
233
+ }`,
234
+ );
235
+ identity = null;
236
+ }
237
+ }
238
+
89
239
  onProgress?.({ percent: 20, log: 'Code validated, executing...' });
90
240
 
91
- // 3. Resolve Node Modules Path using the local sandbox workspace
241
+ // 4. Resolve Node Modules Path using the local sandbox workspace
92
242
  const nodePath = resolve(this.sandboxWorkspace, 'node_modules');
93
243
  const finalNodePath = process.env.NODE_PATH ? `${nodePath}${delimiter}${process.env.NODE_PATH}` : nodePath;
244
+ const nodePathEntries = finalNodePath.split(delimiter).filter(Boolean);
245
+
246
+ // 5. Sanitized environment — only expose what's necessary.
247
+ const pythonGuardDir = getPythonGuardDir(this.storagePath);
248
+ const execEnv: Record<string, string> = {
249
+ PATH: process.env.PATH || '',
250
+ HOME: tmpdir(),
251
+ TMPDIR: tmpdir(),
252
+ OUTPUT_DIR: outputDir,
253
+ LANG: 'en_US.UTF-8',
254
+ // Node.js
255
+ NODE_PATH: finalNodePath,
256
+ // Python — audit-hook guard dir first, then bundled packages (svg_to_pptx etc.)
257
+ PYTHONPATH: [
258
+ capabilities.pythonGuardActive ? pythonGuardDir : '',
259
+ skillDir ? resolve(skillDir, 'scripts') : '',
260
+ resolve(this.sandboxWorkspace, 'python_packages'),
261
+ process.env.PYTHONPATH || '',
262
+ ]
263
+ .filter(Boolean)
264
+ .join(delimiter),
265
+ PYTHONIOENCODING: 'utf-8',
266
+ // Denied bytecode-cache writes are best-effort anyway; skip them entirely.
267
+ PYTHONDONTWRITEBYTECODE: '1',
268
+ // Consumed by the sitecustomize.py guard to scope file writes.
269
+ SKILL_HUB_WRITE_ROOTS: [workDir, outputDir, tmpdir()].join(delimiter),
270
+ SKILL_DIR: skillDir || '',
271
+ // DO NOT pass: DB credentials, API keys, APP_KEY, etc.
272
+ };
94
273
 
95
- // 4. Build command.
96
- // Memory cap (MB): node gets --max-old-space-size; on Linux/macOS the whole
97
- // process tree is additionally bounded with `ulimit -v` so a python skill
98
- // cannot exhaust host memory. Windows has no ulimit equivalent, so the cap
99
- // there is best-effort (node heap only) — production runs on Linux.
274
+ // 6. Build command + args — never interpolate per-execution values into a
275
+ // shell string; scriptPath/workDir travel as argv entries only.
100
276
  const memLimitMb = Math.max(64, Number(process.env.SKILL_HUB_MEM_LIMIT_MB || 512));
101
- const baseCmd =
277
+ const command = language === 'node' ? 'node' : pythonBinary();
278
+ const args =
102
279
  language === 'node'
103
- ? `node --max-old-space-size=${memLimitMb} "${scriptPath}"`
104
- : `${pythonBinary()} "${scriptPath}"`;
105
- const cmd = !IS_WINDOWS && memLimitMb > 0 ? `ulimit -v ${memLimitMb * 1024} 2>/dev/null; exec ${baseCmd}` : baseCmd;
280
+ ? buildNodeArgs({
281
+ memLimitMb,
282
+ scriptPath,
283
+ workDir,
284
+ outputDir,
285
+ skillDir,
286
+ nodePathEntries,
287
+ capabilities,
288
+ })
289
+ : [scriptPath];
106
290
 
107
- // 5. Execute via child_process with sanitized env
291
+ let spawnCommand = command;
292
+ let spawnArgs = args;
293
+ if (!IS_WINDOWS) {
294
+ // Tiny shell wrapper exists only for the ulimit builtins. "$0"/"$@" pass
295
+ // command/args through as argv — nothing user-controlled is parsed as shell.
296
+ const ulimitPrefix = buildUlimitPrefix({
297
+ language,
298
+ memLimitMb,
299
+ timeoutSeconds,
300
+ maxOutputSizeMb,
301
+ includeNproc: identity !== null,
302
+ });
303
+ spawnCommand = '/bin/sh';
304
+ spawnArgs = ['-c', `${ulimitPrefix} exec "$0" "$@"`, command, ...args];
305
+
306
+ if (capabilities.isolationLevel === 'bwrap') {
307
+ const extraReadOnlyDirs = [
308
+ ...nodePathEntries.filter((entry) => entry !== nodePath),
309
+ ...(process.env.PYTHONPATH || '').split(delimiter),
310
+ ].filter(Boolean);
311
+ spawnArgs = [
312
+ ...buildBwrapArgs({
313
+ workDir,
314
+ skillDir,
315
+ sandboxWorkspace: this.sandboxWorkspace,
316
+ extraReadOnlyDirs,
317
+ env: execEnv,
318
+ network: capabilities.network,
319
+ }),
320
+ '--',
321
+ spawnCommand,
322
+ ...spawnArgs,
323
+ ];
324
+ spawnCommand = 'bwrap';
325
+ }
326
+ }
327
+
328
+ // 7. Execute via spawn (no shell around user data, group-kill support)
108
329
  const startTime = Date.now();
109
- let childProc: ChildProcess | null = null;
110
330
  let wasCanceled = false;
331
+ let wasTimedOut = false;
332
+ let outputExceeded = false;
111
333
 
112
334
  const processResult = await new Promise<{
113
335
  exitCode: number;
114
336
  stdout: string;
115
337
  stderr: string;
116
338
  }>((_resolve) => {
117
- childProc = exec(
118
- cmd,
119
- {
120
- timeout: timeoutSeconds * 1000,
121
- maxBuffer: 10 * 1024 * 1024, // 10MB stdout/stderr buffer
122
- cwd: workDir,
123
- env: {
124
- // Sanitized environment — only expose what's necessary
125
- PATH: process.env.PATH,
126
- HOME: tmpdir(),
127
- TMPDIR: tmpdir(),
128
- OUTPUT_DIR: outputDir,
129
- LANG: 'en_US.UTF-8',
130
- // Node.js
131
- NODE_PATH: finalNodePath,
132
- // Python — include bundled packages (svg_to_pptx etc.)
133
- PYTHONPATH: [
134
- skillDir ? resolve(skillDir, 'scripts') : '',
135
- resolve(this.sandboxWorkspace, 'python_packages'),
136
- process.env.PYTHONPATH || '',
137
- ]
138
- .filter(Boolean)
139
- .join(delimiter),
140
- PYTHONIOENCODING: 'utf-8',
141
- SKILL_DIR: skillDir || '',
142
- // DO NOT pass: DB credentials, API keys, APP_KEY, etc.
143
- },
144
- },
145
- (error: ExecException | null, stdout: string, stderr: string) => {
146
- let exitCode = 0;
147
- if (error) {
148
- if (error.killed) {
149
- exitCode = -1; // Killed by timeout or abort
150
- } else {
151
- exitCode = error.code || 1;
152
- }
339
+ let stdout = '';
340
+ let stderr = '';
341
+ let totalBytes = 0;
342
+ let settled = false;
343
+ let timeoutTimer: NodeJS.Timeout | null = null;
344
+ let forceKillTimer: NodeJS.Timeout | null = null;
345
+
346
+ const child = spawn(spawnCommand, spawnArgs, {
347
+ cwd: workDir,
348
+ env: execEnv,
349
+ // Process-group leader on POSIX so kill(-pid) reaches every descendant.
350
+ detached: !IS_WINDOWS,
351
+ stdio: ['ignore', 'pipe', 'pipe'],
352
+ uid: identity?.uid,
353
+ gid: identity?.gid,
354
+ });
355
+
356
+ const finish = (exitCode: number) => {
357
+ if (settled) return;
358
+ settled = true;
359
+ if (timeoutTimer) clearTimeout(timeoutTimer);
360
+ if (forceKillTimer) clearTimeout(forceKillTimer);
361
+ _resolve({
362
+ exitCode,
363
+ stdout: stdout.slice(0, MAX_STDOUT_CHARS),
364
+ stderr: stderr.slice(0, MAX_STDERR_CHARS),
365
+ });
366
+ };
367
+
368
+ const killTree = (killSignal: 'SIGTERM' | 'SIGKILL') => {
369
+ if (!child.pid) return;
370
+ if (IS_WINDOWS) {
371
+ // Best-effort whole-tree kill on Windows (dev-only platform).
372
+ try {
373
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
374
+ } catch {
375
+ child.kill(killSignal);
376
+ }
377
+ return;
378
+ }
379
+ try {
380
+ process.kill(-child.pid, killSignal);
381
+ } catch {
382
+ // ESRCH: group already gone. Fall back to the direct child just in case.
383
+ try {
384
+ child.kill(killSignal);
385
+ } catch {
386
+ // already exited
153
387
  }
388
+ }
389
+ };
154
390
 
155
- _resolve({
156
- exitCode,
157
- stdout: (stdout || '').slice(0, 5000),
158
- stderr: (stderr || '').slice(0, 2000),
159
- });
160
- },
161
- );
391
+ const terminate = (reason: string) => {
392
+ this.logger.info(`[skill-hub] Killing process tree for exec ${execId} (${reason})`);
393
+ killTree('SIGTERM');
394
+ if (!forceKillTimer) {
395
+ // Same 3-second grace window as before, applied to the whole group.
396
+ forceKillTimer = setTimeout(() => killTree('SIGKILL'), 3000);
397
+ }
398
+ };
399
+
400
+ timeoutTimer = setTimeout(() => {
401
+ wasTimedOut = true;
402
+ terminate('timeout');
403
+ }, timeoutSeconds * 1000);
404
+
405
+ const onData = (isStdout: boolean) => (chunk: Buffer) => {
406
+ totalBytes += chunk.length;
407
+ if (totalBytes > MAX_STDIO_BYTES) {
408
+ if (!outputExceeded) {
409
+ outputExceeded = true;
410
+ terminate('output exceeded limit');
411
+ }
412
+ return;
413
+ }
414
+ // Retain only the head that finish() returns; totalBytes keeps counting
415
+ // so the runaway-output kill above still triggers.
416
+ if (isStdout) {
417
+ if (stdout.length < MAX_STDOUT_CHARS) stdout += chunk.toString();
418
+ } else if (stderr.length < MAX_STDERR_CHARS) {
419
+ stderr += chunk.toString();
420
+ }
421
+ };
422
+ child.stdout?.on('data', onData(true));
423
+ child.stderr?.on('data', onData(false));
424
+
425
+ child.on('error', (error: NodeJS.ErrnoException) => {
426
+ // Spawn-time failures (missing binary, EPERM on uid/gid, ...)
427
+ stderr = `Failed to start sandbox process: ${error.message}\n${stderr}`;
428
+ finish(1);
429
+ });
430
+
431
+ child.on('close', (exitCode, exitSignal) => {
432
+ finish(exitSignal !== null || exitCode === null ? -1 : exitCode);
433
+ });
162
434
 
163
- // 5. Wire abort signal → kill child process
164
435
  if (signal) {
165
436
  signal.addEventListener('abort', () => {
166
437
  wasCanceled = true;
167
- if (childProc && !childProc.killed) {
168
- this.logger.info(`[skill-hub] Killing child process for exec ${execId} (user abort)`);
169
- childProc.kill('SIGTERM');
170
- // Force kill after 3 seconds if SIGTERM didn't work
171
- setTimeout(() => {
172
- if (childProc && !childProc.killed) {
173
- childProc.kill('SIGKILL');
174
- }
175
- }, 3000);
176
- }
438
+ terminate('user abort');
177
439
  });
178
440
  }
179
441
  });
@@ -182,10 +444,10 @@ export class SandboxRunner {
182
444
 
183
445
  onProgress?.({ percent: 80, log: wasCanceled ? 'Canceled' : 'Execution completed, collecting files...' });
184
446
 
185
- // 6. Collect output files
447
+ // 8. Collect output files
186
448
  const files = this.fileManager.listOutputFiles(execId);
187
449
 
188
- // 7. Check output size limit
450
+ // 9. Check output size limit
189
451
  const totalSizeBytes = this.fileManager.getTotalOutputSize(execId);
190
452
  const maxBytes = maxOutputSizeMb * 1024 * 1024;
191
453
  if (totalSizeBytes > maxBytes) {
@@ -196,18 +458,23 @@ export class SandboxRunner {
196
458
 
197
459
  onProgress?.({ percent: 100, log: 'Done' });
198
460
 
199
- // Detect timeout
200
- const timedOut = !wasCanceled && processResult.exitCode === -1;
461
+ const timedOut = wasTimedOut && !wasCanceled;
201
462
  if (timedOut) {
202
463
  processResult.stderr = `Execution timed out after ${timeoutSeconds}s\n${processResult.stderr}`;
203
464
  }
204
465
 
466
+ if (outputExceeded) {
467
+ processResult.stderr = `Execution stdout/stderr exceeded ${Math.floor(MAX_STDIO_BYTES / 1024 / 1024)}MB limit\n${
468
+ processResult.stderr
469
+ }`;
470
+ }
471
+
205
472
  if (wasCanceled) {
206
473
  processResult.stderr = `Execution canceled by user\n${processResult.stderr}`;
207
474
  }
208
475
 
209
476
  return {
210
- success: !wasCanceled && !timedOut && processResult.exitCode === 0,
477
+ success: !wasCanceled && !timedOut && !outputExceeded && processResult.exitCode === 0,
211
478
  stdout: processResult.stdout,
212
479
  stderr: processResult.stderr,
213
480
  files,
@@ -206,4 +206,30 @@ export class TokenTracker {
206
206
  return { allowed: true };
207
207
  }
208
208
  }
209
+
210
+ /**
211
+ * Estimate tokens from text length and track on a span.
212
+ * Rough heuristic: ~4 chars per token for English text.
213
+ * Use when actual usage_metadata is not available (e.g. native plugin-ai flow).
214
+ */
215
+ async estimateAndTrack(
216
+ spanId: string | number | undefined,
217
+ input: string,
218
+ output: string,
219
+ runId?: string | number,
220
+ ): Promise<void> {
221
+ if (!spanId) return;
222
+ const inputTokens = Math.ceil((input || '').length / 4);
223
+ const outputTokens = Math.ceil((output || '').length / 4);
224
+ await this.trackSpan(
225
+ spanId,
226
+ {
227
+ inputTokens,
228
+ outputTokens,
229
+ totalTokens: inputTokens + outputTokens,
230
+ cost: estimateCost(inputTokens, outputTokens),
231
+ },
232
+ runId,
233
+ );
234
+ }
209
235
  }