1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
|
// module-sandbox.js — Sandboxed execution pool using WebWorkers
// Commands: sandbox-status, sandbox-config, sandbox-run
class SandboxModule {
constructor() {
this.commands = {};
this.terminal = null;
this.workers = [];
this.MAX_WORKERS = 4;
this.MIN_WORKERS = 1;
this.queue = [];
this.activeTasks = {};
this._nextTaskId = 0;
this._totalRuns = 0;
this._totalErrors = 0;
this._totalDuration = 0;
this._fallbackMode = false; // true if WebWorkers unavailable
this._workerReady = {};
}
getHelpInfo() {
return {
'sandbox-status': 'sandbox-status — Show sandbox pool health and task metrics',
'sandbox-config': 'sandbox-config <key> <value> — Tune: max-workers, min-workers, pool-timeout',
'sandbox-run': 'sandbox-run <task> — Run a task in the sandbox (automatic routing)',
};
}
registerCommands() {
this.commands['sandbox-status'] = () => this.showStatus();
this.commands['sandbox-config'] = (args) => this.setConfig(args);
this.commands['sandbox-run'] = (args) => this.runInSandbox(args.join(' '));
}
init(terminal) {
this.terminal = terminal;
this.workerUrl = '/spaces/newos4/modules/core/sandbox-worker.js?v=2026-06-05-v4.4.0';
// Detect Worker availability
if (typeof Worker === 'undefined') {
this._fallbackMode = true;
this.terminal.print('⚠️ WebWorkers not available — sandbox using inline fallback', 'warning');
} else {
this._initPool();
// Deferred check: workers may fail asynchronously (headless browsers)
// If no worker proves alive within 1.5s, switch to inline fallback
this._workerCheckTimer = setTimeout(() => {
if (!this._fallbackMode && this.workers.length > 0) {
const alive = this.workers.some(w => !w._failed && this._workerReady[w._sandboxId]);
if (!alive) {
this._fallbackMode = true;
this.workers.forEach(w => w.terminate());
this.workers = [];
this.terminal.print('⚠️ WebWorkers unavailable — switching to inline fallback', 'warning');
}
}
}, 1500);
}
this.terminal.print('🧪 Sandbox module loaded', 'info');
}
_initPool() {
// Start with MIN_WORKERS, grow on demand up to MAX_WORKERS
for (let i = 0; i < this.MIN_WORKERS; i++) {
const w = this._spawnWorker();
if (!w) break; // first failure kills the pool
}
}
_spawnWorker() {
if (this.workers.length >= this.MAX_WORKERS) return null;
if (this._fallbackMode) return null;
try {
const worker = new Worker(this.workerUrl);
const id = `w${this.workers.length + 1}`;
worker._sandboxId = id;
worker._busy = false;
worker._failed = false;
// Detect immediate worker failure (headless browsers, restricted contexts)
const failTimer = setTimeout(() => {
if (!worker._failed) {
// Worker survived 2 seconds - likely functional
}
}, 2000);
worker.onmessage = (e) => {
clearTimeout(failTimer);
if (e.data && e.data.type === 'ready') {
this._workerReady[id] = true;
} else {
this._handleResult(e.data, id);
}
};
worker.onerror = (e) => {
clearTimeout(failTimer);
worker._failed = true;
worker.terminate();
console.warn(`[Sandbox] Worker ${id} failed (headless env) — switching to inline`);
this._fallbackMode = true;
this.workers.forEach(w => w.terminate());
this.workers = [];
this.terminal.print('⚠️ WebWorkers unavailable in this environment — using inline fallback', 'warning');
};
this.workers.push(worker);
return worker;
} catch (e) {
console.warn('[Sandbox] Failed to spawn worker:', e);
this._fallbackMode = true;
return null;
}
}
_replaceWorker(id) {
// In headless environments, workers don't work — don't retry
if (this._fallbackMode) return;
const idx = this.workers.findIndex(w => w._sandboxId === id);
if (idx !== -1) {
this.workers[idx].terminate();
this.workers.splice(idx, 1);
delete this._workerReady[id];
}
}
_getIdleWorker() {
for (const w of this.workers) {
if (!w._busy) return w;
}
// Grow pool if under max
if (this.workers.length < this.MAX_WORKERS) {
const w = this._spawnWorker();
if (w) return w;
}
return null;
}
async runInSandbox(task, capabilities) {
if (!task) return this.terminal.print('Usage: sandbox-run <task>', 'error');
// Check if any worker is actually alive and ready
const hasAliveWorker = this.workers.some(w =>
!w._failed && this._workerReady[w._sandboxId]
);
const useInline = this._fallbackMode || this.workers.length === 0 || !hasAliveWorker;
if (useInline) {
return this._runInline(task, capabilities);
}
const worker = this._getIdleWorker();
if (!worker) {
// Queue it
return new Promise((resolve) => {
this.queue.push({ task, capabilities, resolve });
this.terminal.print(`⏳ Task queued (${this.queue.length} waiting)`, 'info');
this._drainQueue();
});
}
return this._executeOnWorker(worker, task, capabilities);
}
async _executeOnWorker(worker, task, capabilities) {
const taskId = `task-${++this._nextTaskId}`;
worker._busy = true;
const startTime = performance.now();
return new Promise((resolve) => {
const handler = (e) => {
if (e.data && e.data.taskId === taskId) {
worker.removeEventListener('message', handler);
worker._busy = false;
const duration = ((performance.now() - startTime) / 1000).toFixed(2);
this._totalRuns++;
this._totalDuration += parseFloat(duration);
if (e.data.error) {
this._totalErrors++;
this.terminal.print(`❌ Sandbox task failed: ${e.data.error}`, 'error');
resolve({ error: e.data.error, duration });
} else {
this.terminal.print(`✅ Sandbox task complete (${duration}s, ${e.data.toolCalls || 0} tools)`, 'success');
resolve({ result: e.data.result, duration, toolCalls: e.data.toolCalls || 0 });
}
this._drainQueue();
}
};
worker.addEventListener('message', handler);
// Get VFS snapshot from terminal
let vfsSnapshot = null;
try {
if (this.terminal && this.terminal.fs && this.terminal.fs.root) {
vfsSnapshot = JSON.stringify({
root: this.terminal.fs.root,
currentPath: this.terminal.fs.currentPath || []
});
}
} catch (e) {
console.warn('[Sandbox] Could not serialize VFS:', e.message);
}
const caps = capabilities || ['list_files', 'read_file'];
const allowedCommands = ['ls', 'cat', 'echo', 'find', 'grep', 'help', 'status',
'touch', 'mkdir', 'rm', 'cp', 'mv'];
worker.postMessage({
taskId,
task,
capabilities: caps,
vfsSnapshot,
allowedCommands,
apiProxy: window.location.origin + '/api'
});
// Timeout after 30 seconds
setTimeout(() => {
if (worker._busy) {
worker._busy = false;
this._totalErrors++;
this.terminal.print(`⏰ Sandbox task ${taskId} timed out after 30s`, 'error');
resolve({ error: 'Timeout (30s)', duration: 30 });
this._drainQueue();
}
}, 30000);
});
}
_handleResult(data, workerId) {
// Handled via promise in _executeOnWorker
// This is the fallback handler for tasks not tracked by promise
if (data.error) {
this.terminal.print(`[Sandbox ${workerId}] Error: ${data.error}`, 'error');
}
}
_drainQueue() {
if (this.queue.length === 0) return;
const next = this.queue.shift();
this.runInSandbox(next.task, next.capabilities).then(result => {
next.resolve(result);
});
}
_runInline(task, capabilities) {
// Fallback when WebWorkers unavailable — runs in main thread
const startTime = performance.now();
const parts = task.trim().split(/\s+/);
const cmd = parts[0].toLowerCase();
let result = '';
let toolCalls = 0;
const fs = this.terminal ? this.terminal.fs : null;
if (cmd === 'ls' && fs) {
const path = parts[1] || '/';
const entries = fs.ls(path);
if (!entries) return this.terminal.print(`ls: ${path}: No such directory`, 'error');
result = entries.map(e => `${e.type === 'dir' ? '[dir]' : '[file]'} ${e.name}`).join('\\n');
toolCalls++;
} else if ((cmd === 'cat' || cmd === 'read') && fs) {
const path = parts[1] || '';
const content = fs.readFile(path);
if (content === null) return this.terminal.print(`cat: ${path}: No such file`, 'error');
result = typeof content === 'string' ? content.substring(0, 8000) : String(content);
toolCalls++;
} else if (cmd === 'find' && fs) {
const q = parts.slice(1).join(' ') || '';
// Walk VFS
const results = [];
const walk = (p) => {
const entries = fs.ls(p);
if (!entries) return;
for (const e of entries) {
const full = p === '/' ? '/' + e.name : p + '/' + e.name;
if (e.type === 'file' && (!q || full.toLowerCase().includes(q.toLowerCase()))) {
results.push(full);
}
if (e.type === 'dir') walk(full);
}
};
walk('/');
result = results.join('\\n') || '(empty)';
toolCalls++;
} else if (cmd === 'status') {
let f = 0, d = 0;
const walk = (p) => {
const entries = fs ? fs.ls(p) : [];
if (!entries) return;
for (const e of entries) {
if (e.type === 'file') f++;
else { d++; walk(p === '/' ? '/' + e.name : p + '/' + e.name); }
}
};
walk('/');
result = `Files: ${f}, Dirs: ${d}`;
toolCalls++;
} else {
result = `Task: "${task}" (inline fallback)`;
}
const duration = ((performance.now() - startTime) / 1000).toFixed(2);
this._totalRuns++;
this._totalDuration += parseFloat(duration);
this.terminal.print(result, 'info');
return { result, duration, toolCalls };
}
// ─── Config ───
setConfig(args) {
if (args.length < 2) return this.terminal.print('Usage: sandbox-config <key> <value>', 'error');
const key = args[0];
const val = args[1];
const configMap = {
'max-workers': () => {
const n = parseInt(val);
if (isNaN(n) || n < 1 || n > 8) return 'Must be 1-8';
this.MAX_WORKERS = n;
// Scale down if needed
while (this.workers.length > n) {
const w = this.workers.pop();
w.terminate();
}
// Scale up
for (let i = this.workers.length; i < Math.min(n, this.MIN_WORKERS); i++) {
this._spawnWorker();
}
return `max-workers set to ${n}`;
},
'min-workers': () => {
const n = parseInt(val);
if (isNaN(n) || n < 0 || n > this.MAX_WORKERS) return `Must be 0-${this.MAX_WORKERS}`;
this.MIN_WORKERS = n;
while (this.workers.length < n) this._spawnWorker();
return `min-workers set to ${n}`;
},
};
if (!configMap[key]) {
return this.terminal.print(`Unknown: ${key}. Valid: ${Object.keys(configMap).join(', ')}`, 'error');
}
const msg = configMap[key]();
this.terminal.print(`✅ ${msg}`, 'success');
}
// ─── Status ───
showStatus() {
const busy = this.workers.filter(w => w._busy).length;
const idle = this.workers.length - busy;
const avgDuration = this._totalRuns > 0 ? (this._totalDuration / this._totalRuns).toFixed(2) : 'N/A';
this.terminal.print('🧪 Sandbox Pool', 'header');
this.terminal.print(` Workers: ${this.workers.length}/${this.MAX_WORKERS} (${busy} busy, ${idle} idle)`, 'info');
this.terminal.print(` Mode: ${this._fallbackMode ? '⚠️ Inline fallback' : '✅ WebWorker'}`, 'info');
this.terminal.print(` Queue: ${this.queue.length} pending`, 'info');
this.terminal.print(` Total runs: ${this._totalRuns} (errors: ${this._totalErrors})`, 'info');
this.terminal.print(` Avg duration: ${avgDuration}s`, 'info');
}
}
// Required for module system
if (typeof window !== 'undefined') {
window.SandboxModule = SandboxModule;
}
|