dsh-awesome-optimizer 2.1.0 → 3.3.0

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 (42) hide show
  1. package/README.md +29 -35
  2. package/README.zh.md +29 -35
  3. package/cache-diagnostics.md +19 -0
  4. package/cordis.patch.yml +14 -2
  5. package/outline-benchmark.md +37 -0
  6. package/outline-benchmark.windows.json +184 -0
  7. package/package.json +15 -2
  8. package/scripts/benchmark-outline.mjs +100 -0
  9. package/scripts/benchmark.mjs +33 -26
  10. package/scripts/typecheck.mjs +37 -18
  11. package/src/ast-outline-config.yml +1 -0
  12. package/src/ast-outline.js +143 -0
  13. package/src/cache-diagnostics.js +218 -0
  14. package/src/code-lexical.js +131 -0
  15. package/src/code-outline.js +171 -0
  16. package/src/composite-tools.d.ts +36 -8
  17. package/src/composite-tools.js +538 -194
  18. package/src/convergence.js +3 -3
  19. package/src/custom-prompt.d.ts +7 -1
  20. package/src/custom-prompt.js +53 -18
  21. package/src/edit-recovery.d.ts +59 -0
  22. package/src/edit-recovery.js +524 -0
  23. package/src/failure-recovery.js +1 -1
  24. package/src/file-mutation-policy.js +0 -8
  25. package/src/find-read-output.js +175 -0
  26. package/src/find-read-ranking.js +63 -0
  27. package/src/index.d.ts +34 -2
  28. package/src/index.js +29 -5
  29. package/src/outline-cache.js +36 -0
  30. package/src/persistent-eval/daemon-pool.js +3 -2
  31. package/src/persistent-eval/index.d.ts +35 -8
  32. package/src/persistent-eval/index.js +51 -16
  33. package/src/persistent-eval/stdio-runner.js +209 -30
  34. package/src/persistent-eval/workers/node_worker.mjs +42 -31
  35. package/src/persistent-eval/workers/py_worker.py +47 -24
  36. package/src/prompt-linter.js +43 -26
  37. package/src/read-guard.d.ts +80 -0
  38. package/src/read-guard.js +336 -0
  39. package/src/runtime-policy.d.ts +1 -0
  40. package/src/runtime-policy.js +35 -15
  41. package/src/telemetry.d.ts +4 -0
  42. package/src/telemetry.js +27 -8
@@ -1,10 +1,21 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import readline from 'node:readline';
3
3
  import process from 'node:process';
4
+ /**
5
+ * Convert an aborted signal's reason into an Error suitable for rejection
6
+ * and DSH cancellation classification.
7
+ */
8
+ function toAbortError(signal) {
9
+ const reason = signal?.reason;
10
+ if (reason instanceof Error) return reason;
11
+ const err = new Error(typeof reason === 'string' && reason ? reason : 'The operation was aborted.');
12
+ err.name = 'AbortError';
13
+ return err;
14
+ }
4
15
 
5
16
  /**
6
17
  * Manages a single stateful worker process with stdio line-delimited JSON RPC,
7
- * watchdog timeout self-healing, and output anti-dumping guard.
18
+ * watchdog timeout self-healing, cancellation propagation, and output anti-dumping guard.
8
19
  */
9
20
  export class StdioWorkerRunner {
10
21
  /**
@@ -51,21 +62,34 @@ export class StdioWorkerRunner {
51
62
  }
52
63
 
53
64
  ensureStarted() {
65
+ if (this.isDestroyed) {
66
+ return Promise.reject(new Error('Worker runner has been destroyed.'));
67
+ }
54
68
  if (this.child && !this.child.killed && this.isReady) {
55
69
  return Promise.resolve();
56
70
  }
57
71
  if (this.child && !this.child.killed && !this.isReady) {
58
- return new Promise(resolve => this.readyWaiters.push(resolve));
72
+ return new Promise((resolve, reject) => this.readyWaiters.push({ resolve, reject }));
59
73
  }
60
74
  return this._spawnProcess();
61
75
  }
62
76
 
77
+ _resolveReadyWaiters() {
78
+ const waiters = this.readyWaiters.splice(0, this.readyWaiters.length);
79
+ for (const w of waiters) w.resolve();
80
+ }
81
+
82
+ _rejectReadyWaiters(err) {
83
+ const waiters = this.readyWaiters.splice(0, this.readyWaiters.length);
84
+ for (const w of waiters) w.reject(err);
85
+ }
86
+
63
87
  _spawnProcess() {
64
88
  this.launchCount++;
65
89
  this.isReady = false;
66
90
 
67
91
  return new Promise((resolve, reject) => {
68
- this.readyWaiters.push(resolve);
92
+ this.readyWaiters.push({ resolve, reject });
69
93
 
70
94
  try {
71
95
  const mergedEnv = {
@@ -75,37 +99,48 @@ export class StdioWorkerRunner {
75
99
  ...this.env
76
100
  };
77
101
 
78
- this.child = spawn(this.command, this.args, {
102
+ const child = spawn(this.command, this.args, {
79
103
  stdio: ['pipe', 'pipe', 'pipe'],
80
104
  env: mergedEnv,
81
105
  windowsHide: true
82
106
  });
107
+ this.child = child;
83
108
 
84
109
  this._ref();
85
110
 
86
- this.rl = readline.createInterface({
87
- input: this.child.stdout,
111
+ const rl = readline.createInterface({
112
+ input: child.stdout,
88
113
  terminal: false
89
114
  });
115
+ this.rl = rl;
90
116
 
91
- this.rl.on('line', line => this._handleStdoutLine(line));
117
+ rl.on('line', line => {
118
+ if (this.child !== child) return;
119
+ this._handleStdoutLine(line);
120
+ });
92
121
 
93
- this.child.stderr.on('data', chunk => {
122
+ child.stderr.on('data', chunk => {
123
+ if (this.child !== child) return;
94
124
  // Worker-level unhandled stderr logging (not during task execution)
95
125
  if (this.currentTask) {
96
126
  this.currentTask.stderrChunk = (this.currentTask.stderrChunk || '') + chunk.toString('utf-8');
97
127
  }
98
128
  });
99
129
 
100
- this.child.on('error', err => {
130
+ child.on('error', err => {
131
+ if (this.child !== child) return;
101
132
  this._handleProcessFailure(err);
102
133
  });
103
134
 
104
- this.child.on('exit', (code, signal) => {
135
+ child.on('exit', (code, signal) => {
136
+ if (this.child !== child) return;
105
137
  this._handleProcessExit(code, signal);
106
138
  });
107
139
  } catch (err) {
108
- reject(err);
140
+ this.isReady = false;
141
+ this.child = null;
142
+ this.rl = null;
143
+ this._rejectReadyWaiters(err);
109
144
  }
110
145
  });
111
146
  }
@@ -123,8 +158,7 @@ export class StdioWorkerRunner {
123
158
 
124
159
  if (parsed.status === 'ready' && !this.isReady) {
125
160
  this.isReady = true;
126
- const waiters = this.readyWaiters.splice(0, this.readyWaiters.length);
127
- for (const w of waiters) w();
161
+ this._resolveReadyWaiters();
128
162
  if (!this.currentTask && this.pendingQueue.length === 0) {
129
163
  this._unref();
130
164
  }
@@ -134,13 +168,24 @@ export class StdioWorkerRunner {
134
168
  if (this.currentTask && parsed.id === this.currentTask.id) {
135
169
  const task = this.currentTask;
136
170
  this.currentTask = null;
137
- if (task.timeoutTimer) clearTimeout(task.timeoutTimer);
171
+ this._cleanupTask(task);
138
172
 
139
173
  this._truncateAndResolve(task, parsed);
140
174
  this._drainQueue();
141
175
  }
142
176
  }
143
177
 
178
+ _cleanupTask(task) {
179
+ if (task.timeoutTimer) {
180
+ clearTimeout(task.timeoutTimer);
181
+ task.timeoutTimer = null;
182
+ }
183
+ if (task.abortCleanup) {
184
+ task.abortCleanup();
185
+ task.abortCleanup = null;
186
+ }
187
+ }
188
+
144
189
  _truncateAndResolve(task, response) {
145
190
  let stdout = response.stdout || '';
146
191
  let stderr = (response.stderr || '') + (task.stderrChunk || '');
@@ -159,24 +204,41 @@ export class StdioWorkerRunner {
159
204
  }
160
205
 
161
206
  _handleProcessFailure(err) {
207
+ this.isReady = false;
208
+ if (this.rl) {
209
+ try { this.rl.close(); } catch {}
210
+ this.rl = null;
211
+ }
212
+ this.child = null;
213
+ this._rejectReadyWaiters(err);
162
214
  if (this.currentTask) {
163
215
  const task = this.currentTask;
164
216
  this.currentTask = null;
165
- if (task.timeoutTimer) clearTimeout(task.timeoutTimer);
217
+ this._cleanupTask(task);
166
218
  task.reject(err);
167
219
  }
168
220
  this._drainQueue();
169
221
  }
170
222
 
171
223
  _handleProcessExit(code, signal) {
224
+ const wasReady = this.isReady;
172
225
  this.isReady = false;
226
+ if (this.rl) {
227
+ try { this.rl.close(); } catch {}
228
+ this.rl = null;
229
+ }
173
230
  this.child = null;
174
- this.rl = null;
231
+
232
+ if (!wasReady && this.readyWaiters.length > 0) {
233
+ this._rejectReadyWaiters(
234
+ new Error(`Worker process exited before ready (code: ${code}, signal: ${signal}).`)
235
+ );
236
+ }
175
237
 
176
238
  if (this.currentTask) {
177
239
  const task = this.currentTask;
178
240
  this.currentTask = null;
179
- if (task.timeoutTimer) clearTimeout(task.timeoutTimer);
241
+ this._cleanupTask(task);
180
242
 
181
243
  task.resolve({
182
244
  id: task.id,
@@ -193,23 +255,125 @@ export class StdioWorkerRunner {
193
255
  this._drainQueue();
194
256
  }
195
257
 
258
+ _ensureStartedWithSignal(signal) {
259
+ if (signal?.aborted) {
260
+ return Promise.reject(toAbortError(signal));
261
+ }
262
+ const startPromise = this.ensureStarted();
263
+ if (!signal) return startPromise;
264
+
265
+ return new Promise((resolve, reject) => {
266
+ let settled = false;
267
+ const onAbort = () => {
268
+ if (settled) return;
269
+ settled = true;
270
+ signal.removeEventListener('abort', onAbort);
271
+ reject(toAbortError(signal));
272
+ };
273
+ signal.addEventListener('abort', onAbort, { once: true });
274
+ startPromise.then(
275
+ () => {
276
+ if (settled) return;
277
+ settled = true;
278
+ signal.removeEventListener('abort', onAbort);
279
+ resolve();
280
+ },
281
+ err => {
282
+ if (settled) return;
283
+ settled = true;
284
+ signal.removeEventListener('abort', onAbort);
285
+ reject(err);
286
+ }
287
+ );
288
+ });
289
+ }
290
+
291
+ _abortTask(task, signal) {
292
+ if (task.settled) return;
293
+ const abortErr = toAbortError(signal);
294
+ this._cleanupTask(task);
295
+
296
+ if (this.currentTask === task) {
297
+ this.currentTask = null;
298
+ // Detach and terminate the active child process immediately so subsequent tasks get a clean worker
299
+ const dyingChild = this.child;
300
+ this.isReady = false;
301
+ this.child = null;
302
+ if (this.rl) {
303
+ try { this.rl.close(); } catch {}
304
+ this.rl = null;
305
+ }
306
+ this._forceKill(dyingChild);
307
+ task.reject(abortErr);
308
+ this._drainQueue();
309
+ return;
310
+ }
311
+
312
+ const queueIdx = this.pendingQueue.indexOf(task);
313
+ if (queueIdx >= 0) {
314
+ this.pendingQueue.splice(queueIdx, 1);
315
+ task.reject(abortErr);
316
+ if (!this.currentTask && this.pendingQueue.length === 0) {
317
+ this._unref();
318
+ }
319
+ }
320
+ }
321
+
196
322
  async execute(code, options = {}) {
197
323
  if (this.isDestroyed) {
198
324
  throw new Error('Worker runner has been destroyed.');
199
325
  }
326
+ const signal = options.signal;
327
+ if (signal?.aborted) {
328
+ throw toAbortError(signal);
329
+ }
200
330
 
201
- await this.ensureStarted();
331
+ await this._ensureStartedWithSignal(signal);
332
+ if (this.isDestroyed) {
333
+ throw new Error('Worker runner has been destroyed.');
334
+ }
335
+ if (signal?.aborted) {
336
+ throw toAbortError(signal);
337
+ }
202
338
 
203
339
  const id = `req-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
204
340
  const payload = {
205
341
  id,
206
342
  action: options.action || 'eval',
343
+ cwd: options.cwd,
207
344
  code: code || '',
208
345
  reset: Boolean(options.reset)
209
346
  };
210
347
 
211
348
  return new Promise((resolve, reject) => {
212
- this.pendingQueue.push({ id, payload, resolve, reject, options });
349
+ const task = {
350
+ id,
351
+ payload,
352
+ resolve: val => {
353
+ if (task.settled) return;
354
+ task.settled = true;
355
+ this._cleanupTask(task);
356
+ resolve(val);
357
+ },
358
+ reject: err => {
359
+ if (task.settled) return;
360
+ task.settled = true;
361
+ this._cleanupTask(task);
362
+ reject(err);
363
+ },
364
+ options,
365
+ settled: false,
366
+ timeoutTimer: null,
367
+ abortCleanup: null
368
+ };
369
+
370
+ if (signal) {
371
+ const onAbort = () => this._abortTask(task, signal);
372
+ signal.addEventListener('abort', onAbort, { once: true });
373
+ task.abortCleanup = () => signal.removeEventListener('abort', onAbort);
374
+ }
375
+
376
+ this.pendingQueue.push(task);
213
377
  if (!this.currentTask) {
214
378
  this._drainQueue();
215
379
  }
@@ -248,6 +412,11 @@ export class StdioWorkerRunner {
248
412
  }
249
413
 
250
414
  const task = this.pendingQueue.shift();
415
+ if (task.options?.signal?.aborted) {
416
+ task.reject(toAbortError(task.options.signal));
417
+ this._drainQueue();
418
+ return;
419
+ }
251
420
  this.currentTask = task;
252
421
 
253
422
  // Armed watchdog timer
@@ -261,26 +430,26 @@ export class StdioWorkerRunner {
261
430
  const line = JSON.stringify(task.payload) + '\n';
262
431
  this.child.stdin.write(line, 'utf-8');
263
432
  } catch (err) {
264
- if (task.timeoutTimer) clearTimeout(task.timeoutTimer);
265
433
  this.currentTask = null;
434
+ this._cleanupTask(task);
266
435
  task.reject(err);
267
436
  this._drainQueue();
268
437
  }
269
438
  }
270
439
 
271
- _forceKill() {
272
- if (!this.child) return;
273
- const pid = this.child.pid;
440
+ _forceKill(targetChild = this.child) {
441
+ if (!targetChild) return;
442
+ const pid = targetChild.pid;
274
443
  try {
275
444
  if (process.platform === 'win32' && pid) {
276
445
  // Force terminate process tree on Windows to prevent orphan python processes
277
446
  spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true });
278
447
  } else {
279
- this.child.kill('SIGKILL');
448
+ targetChild.kill('SIGKILL');
280
449
  }
281
450
  } catch {
282
451
  try {
283
- this.child.kill('SIGKILL');
452
+ targetChild.kill('SIGKILL');
284
453
  } catch {
285
454
  // Ignored
286
455
  }
@@ -289,16 +458,26 @@ export class StdioWorkerRunner {
289
458
 
290
459
  destroy() {
291
460
  this.isDestroyed = true;
292
- if (this.currentTask && this.currentTask.timeoutTimer) {
293
- clearTimeout(this.currentTask.timeoutTimer);
461
+ this.isReady = false;
462
+ const destroyErr = new Error('Worker runner has been destroyed.');
463
+ if (this.currentTask) {
464
+ const task = this.currentTask;
465
+ this.currentTask = null;
466
+ this._cleanupTask(task);
467
+ task.reject(destroyErr);
468
+ }
469
+ this._rejectReadyWaiters(destroyErr);
470
+ const pending = this.pendingQueue.splice(0, this.pendingQueue.length);
471
+ for (const task of pending) {
472
+ this._cleanupTask(task);
473
+ task.reject(destroyErr);
294
474
  }
295
475
  if (this.rl) {
296
476
  try { this.rl.close(); } catch {}
297
477
  this.rl = null;
298
478
  }
299
- this._forceKill();
479
+ const activeChild = this.child;
300
480
  this.child = null;
301
- this.pendingQueue = [];
302
- this.currentTask = null;
481
+ this._forceKill(activeChild);
303
482
  }
304
483
  }
@@ -8,9 +8,11 @@ import readline from 'node:readline';
8
8
  import vm from 'node:vm';
9
9
  import util from 'node:util';
10
10
  import process from 'node:process';
11
+ import path from 'node:path';
11
12
 
12
13
  function createFreshContext() {
13
14
  const sandbox = {
15
+ CWD: process.cwd(),
14
16
  setTimeout,
15
17
  clearTimeout,
16
18
  setInterval,
@@ -78,7 +80,8 @@ function wrapAsyncCode(code) {
78
80
  const lines = trimmed.split('\n');
79
81
  let lastIndex = -1;
80
82
  for (let i = lines.length - 1; i >= 0; i--) {
81
- if (lines[i].trim().length > 0) {
83
+ const lineTrimmed = lines[i].trim();
84
+ if (lineTrimmed.length > 0 && !lineTrimmed.startsWith('//') && !/^\/\*.*\*\/$/.test(lineTrimmed)) {
82
85
  lastIndex = i;
83
86
  break;
84
87
  }
@@ -93,8 +96,15 @@ function wrapAsyncCode(code) {
93
96
 
94
97
  if (!statementKeywords.test(lastLine)) {
95
98
  const expr = lastLine.endsWith(';') ? lastLine.slice(0, -1) : lastLine;
96
- lines[lastIndex] = `return (${expr});`;
97
- return `(async () => {\n${lines.join('\n')}\n})()`;
99
+ const candidateLines = [...lines];
100
+ candidateLines[lastIndex] = `return (\n${expr}\n);`;
101
+ const candidate = `(async () => {\n${candidateLines.join('\n')}\n})()`;
102
+ try {
103
+ new vm.Script(candidate, { filename: '<eval_kernel>' });
104
+ return candidate;
105
+ } catch {
106
+ // Fall back to executing unmodified statements if wrapping last line fails syntax check
107
+ }
98
108
  }
99
109
 
100
110
  return `(async () => {\n${trimmed}\n})()`;
@@ -104,19 +114,22 @@ async function executeInContext(code, context) {
104
114
  const trimmed = code.trim();
105
115
  if (!trimmed) return undefined;
106
116
 
107
- // If code appears to use top-level await, wrap in async IIFE
108
- const hasTopLevelAwait = /\bawait\s+/.test(trimmed);
109
-
110
- if (hasTopLevelAwait) {
111
- const wrappedCode = wrapAsyncCode(trimmed);
112
- const script = new vm.Script(wrappedCode, { filename: '<eval_kernel>' });
113
- const promise = script.runInContext(context, { breakOnSigint: true });
114
- return await promise;
115
- } else {
116
- // Standard execution: natively returns the value of the last evaluated expression
117
- const script = new vm.Script(trimmed, { filename: '<eval_kernel>' });
118
- return script.runInContext(context, { breakOnSigint: true });
117
+ // Compile synchronously first so await inside strings, comments, or async functions
118
+ // never triggers unnecessary IIFE wrapping that would shadow top-level declarations.
119
+ let syncScript;
120
+ try {
121
+ syncScript = new vm.Script(trimmed, { filename: '<eval_kernel>' });
122
+ } catch (err) {
123
+ if (err instanceof SyntaxError && /\bawait\b/i.test(err.message)) {
124
+ const wrappedCode = wrapAsyncCode(trimmed);
125
+ const asyncScript = new vm.Script(wrappedCode, { filename: '<eval_kernel>' });
126
+ const promise = asyncScript.runInContext(context, { breakOnSigint: true });
127
+ return await promise;
128
+ }
129
+ throw err;
119
130
  }
131
+
132
+ return syncScript.runInContext(context, { breakOnSigint: true });
120
133
  }
121
134
 
122
135
  function sendFrame(payload) {
@@ -180,21 +193,6 @@ function main() {
180
193
  return;
181
194
  }
182
195
 
183
- if (action === 'reset' || shouldReset) {
184
- CURRENT_CONTEXT = createFreshContext();
185
- if (action === 'reset') {
186
- sendFrame({
187
- id: reqId,
188
- success: true,
189
- stdout: '',
190
- stderr: '',
191
- result: 'Node VM context reset successfully.',
192
- executionTimeMs: 0
193
- });
194
- return;
195
- }
196
- }
197
-
198
196
  let stdoutBuf = '';
199
197
  let stderrBuf = '';
200
198
 
@@ -221,7 +219,20 @@ function main() {
221
219
  let rawResult;
222
220
 
223
221
  try {
224
- rawResult = await executeInContext(code, CURRENT_CONTEXT);
222
+ if (Object.hasOwn(req, 'cwd')) {
223
+ if (typeof req.cwd !== 'string' || !path.isAbsolute(req.cwd)) {
224
+ throw new TypeError('cwd must be an absolute directory path');
225
+ }
226
+ process.chdir(req.cwd);
227
+ }
228
+ if (action === 'reset' || shouldReset) {
229
+ CURRENT_CONTEXT = createFreshContext();
230
+ CURRENT_CONTEXT.console = customConsole;
231
+ }
232
+ CURRENT_CONTEXT.CWD = process.cwd();
233
+ rawResult = action === 'reset'
234
+ ? 'Node VM context reset successfully.'
235
+ : await executeInContext(code, CURRENT_CONTEXT);
225
236
  } catch (err) {
226
237
  success = false;
227
238
  errorMsg = err instanceof Error ? err.stack || err.message : String(err);
@@ -16,13 +16,16 @@ import math
16
16
  import re
17
17
  import collections
18
18
  import itertools
19
+ import pathlib
20
+ import difflib
21
+ import csv
19
22
 
20
23
  # Ensure strict UTF-8 stdio streams with line buffering
21
- if hasattr(sys.stdin, "reconfigure"):
24
+ if isinstance(sys.stdin, io.TextIOWrapper):
22
25
  sys.stdin.reconfigure(encoding="utf-8", errors="replace")
23
- if hasattr(sys.stdout, "reconfigure"):
26
+ if isinstance(sys.stdout, io.TextIOWrapper):
24
27
  sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
25
- if hasattr(sys.stderr, "reconfigure"):
28
+ if isinstance(sys.stderr, io.TextIOWrapper):
26
29
  sys.stderr.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
27
30
 
28
31
  # Keep handles to original standard streams for JSON protocol frames
@@ -40,6 +43,10 @@ def create_fresh_scope():
40
43
  "time": time,
41
44
  "collections": collections,
42
45
  "itertools": itertools,
46
+ "pathlib": pathlib,
47
+ "difflib": difflib,
48
+ "csv": csv,
49
+ "CWD": os.getcwd(),
43
50
  }
44
51
 
45
52
  GLOBAL_SCOPE = create_fresh_scope()
@@ -54,7 +61,8 @@ def execute_code(code, scope):
54
61
  if not code_stripped:
55
62
  return None
56
63
 
57
- parsed = ast.parse(code, filename="<eval_kernel>", mode="exec")
64
+ parsed = compile(code, filename="<eval_kernel>", mode="exec", flags=ast.PyCF_ONLY_AST)
65
+ assert isinstance(parsed, ast.Module)
58
66
  if not parsed.body:
59
67
  return None
60
68
 
@@ -93,8 +101,29 @@ def serialize_result(result):
93
101
  # Fall back to string representation
94
102
  return result_repr, result_repr
95
103
 
104
+ def print_user_traceback(ex, stream):
105
+ """Hide worker frames without discarding user frames or exception metadata."""
106
+ diagnostic = traceback.TracebackException.from_exception(ex)
107
+ pending = [diagnostic]
108
+ seen = set()
109
+ while pending:
110
+ current = pending.pop()
111
+ if id(current) in seen:
112
+ continue
113
+ seen.add(id(current))
114
+ current.stack = traceback.StackSummary.from_list(
115
+ frame for frame in current.stack if frame.filename != __file__
116
+ )
117
+ for linked in (current.__cause__, current.__context__):
118
+ if linked is not None:
119
+ pending.append(linked)
120
+ pending.extend(getattr(current, "exceptions", None) or [])
121
+ diagnostic.print(file=stream)
122
+
123
+
96
124
  def main():
97
125
  global GLOBAL_SCOPE
126
+ assert REAL_STDIN is not None and REAL_STDOUT is not None, "Worker requires stdio pipes"
98
127
 
99
128
  # Signal ready frame on startup
100
129
  ready_frame = json.dumps({"status": "ready", "pid": os.getpid()}, ensure_ascii=False) + "\n"
@@ -138,22 +167,6 @@ def main():
138
167
  REAL_STDOUT.buffer.flush()
139
168
  continue
140
169
 
141
- if action == "reset" or should_reset:
142
- GLOBAL_SCOPE = create_fresh_scope()
143
- if action == "reset":
144
- resp = {
145
- "id": req_id,
146
- "success": True,
147
- "stdout": "",
148
- "stderr": "",
149
- "result": "Kernel namespace reset successfully.",
150
- "executionTimeMs": 0
151
- }
152
- frame = json.dumps(resp, ensure_ascii=False) + "\n"
153
- REAL_STDOUT.buffer.write(frame.encode("utf-8"))
154
- REAL_STDOUT.buffer.flush()
155
- continue
156
-
157
170
  captured_stdout = io.StringIO()
158
171
  captured_stderr = io.StringIO()
159
172
  old_stdout = sys.stdout
@@ -168,13 +181,23 @@ def main():
168
181
  result_repr = None
169
182
 
170
183
  try:
171
- raw_result = execute_code(code, GLOBAL_SCOPE)
172
- result_val, result_repr = serialize_result(raw_result)
184
+ if "cwd" in req:
185
+ cwd = req["cwd"]
186
+ if not isinstance(cwd, str) or not os.path.isabs(cwd):
187
+ raise ValueError("cwd must be an absolute directory path")
188
+ os.chdir(cwd)
189
+ if action == "reset" or should_reset:
190
+ GLOBAL_SCOPE = create_fresh_scope()
191
+ GLOBAL_SCOPE["CWD"] = os.getcwd()
192
+ if action == "reset":
193
+ result_val = "Kernel namespace reset successfully."
194
+ else:
195
+ raw_result = execute_code(code, GLOBAL_SCOPE)
196
+ result_val, result_repr = serialize_result(raw_result)
173
197
  except Exception as ex:
174
198
  success = False
175
199
  error_msg = str(ex)
176
- # Write traceback into captured_stderr
177
- traceback.print_exc(file=captured_stderr)
200
+ print_user_traceback(ex, captured_stderr)
178
201
  finally:
179
202
  elapsed_ms = round((time.perf_counter() - start_time) * 1000, 3)
180
203
  sys.stdout = old_stdout