dsh-awesome-optimizer 1.8.0 → 2.1.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.
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * node_worker.mjs - Zero-dependency persistent Node.js worker for DSH Agent.
4
+ * Maintains a stateful VM context across execution frames over stdio line-delimited JSON.
5
+ */
6
+
7
+ import readline from 'node:readline';
8
+ import vm from 'node:vm';
9
+ import util from 'node:util';
10
+ import process from 'node:process';
11
+
12
+ function createFreshContext() {
13
+ const sandbox = {
14
+ setTimeout,
15
+ clearTimeout,
16
+ setInterval,
17
+ clearInterval,
18
+ setImmediate,
19
+ clearImmediate,
20
+ Buffer,
21
+ URL,
22
+ URLSearchParams,
23
+ TextEncoder,
24
+ TextDecoder,
25
+ process: {
26
+ env: { ...process.env },
27
+ cwd: () => process.cwd(),
28
+ version: process.version,
29
+ platform: process.platform,
30
+ arch: process.arch
31
+ }
32
+ };
33
+
34
+ const context = vm.createContext(sandbox);
35
+ context.global = context;
36
+ context.globalThis = context;
37
+ return context;
38
+ }
39
+
40
+ let CURRENT_CONTEXT = createFreshContext();
41
+
42
+ function serializeResult(val) {
43
+ if (val === undefined) return { result: null, resultRepr: 'undefined' };
44
+ if (val === null) return { result: null, resultRepr: 'null' };
45
+
46
+ let repr;
47
+ if (typeof val === 'number' && !Number.isInteger(val)) {
48
+ const rounded = Number(val.toFixed(10));
49
+ if (Math.abs(val - rounded) < 1e-12) {
50
+ repr = String(rounded);
51
+ } else {
52
+ repr = String(val);
53
+ }
54
+ } else {
55
+ try {
56
+ repr = util.inspect(val, { depth: 4, maxArrayLength: 100, breakLength: 80 });
57
+ } catch {
58
+ repr = String(val);
59
+ }
60
+ }
61
+
62
+ let serializable;
63
+ try {
64
+ serializable = JSON.parse(JSON.stringify(val));
65
+ } catch {
66
+ serializable = repr;
67
+ }
68
+
69
+ return { result: serializable, resultRepr: repr };
70
+ }
71
+
72
+ function wrapAsyncCode(code) {
73
+ const trimmed = code.trim();
74
+ if (/\breturn\s+/.test(trimmed)) {
75
+ return `(async () => {\n${trimmed}\n})()`;
76
+ }
77
+
78
+ const lines = trimmed.split('\n');
79
+ let lastIndex = -1;
80
+ for (let i = lines.length - 1; i >= 0; i--) {
81
+ if (lines[i].trim().length > 0) {
82
+ lastIndex = i;
83
+ break;
84
+ }
85
+ }
86
+
87
+ if (lastIndex === -1) {
88
+ return `(async () => {})()`;
89
+ }
90
+
91
+ const lastLine = lines[lastIndex].trim();
92
+ const statementKeywords = /^(const|let|var|function|class|import|export|throw|return|if|else|while|for|switch|case|default|try|catch|finally)\b/;
93
+
94
+ if (!statementKeywords.test(lastLine)) {
95
+ const expr = lastLine.endsWith(';') ? lastLine.slice(0, -1) : lastLine;
96
+ lines[lastIndex] = `return (${expr});`;
97
+ return `(async () => {\n${lines.join('\n')}\n})()`;
98
+ }
99
+
100
+ return `(async () => {\n${trimmed}\n})()`;
101
+ }
102
+
103
+ async function executeInContext(code, context) {
104
+ const trimmed = code.trim();
105
+ if (!trimmed) return undefined;
106
+
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 });
119
+ }
120
+ }
121
+
122
+ function sendFrame(payload) {
123
+ let line;
124
+ try {
125
+ line = JSON.stringify(payload) + '\n';
126
+ } catch (err) {
127
+ line = JSON.stringify({
128
+ id: payload.id,
129
+ success: false,
130
+ error: `Failed to serialize response frame: ${err.message}`,
131
+ stdout: payload.stdout || '',
132
+ stderr: payload.stderr || '',
133
+ executionTimeMs: payload.executionTimeMs || 0
134
+ }) + '\n';
135
+ }
136
+ process.stdout.write(line, 'utf-8');
137
+ }
138
+
139
+ function main() {
140
+ // Send ready frame on startup
141
+ sendFrame({ status: 'ready', pid: process.pid });
142
+
143
+ const rl = readline.createInterface({
144
+ input: process.stdin,
145
+ output: process.stdout,
146
+ terminal: false
147
+ });
148
+
149
+ rl.on('line', async rawLine => {
150
+ const line = rawLine.trim();
151
+ if (!line) return;
152
+
153
+ let req;
154
+ try {
155
+ req = JSON.parse(line);
156
+ } catch (e) {
157
+ sendFrame({
158
+ id: null,
159
+ success: false,
160
+ error: `Invalid JSON payload: ${e.message}`,
161
+ stdout: '',
162
+ stderr: '',
163
+ executionTimeMs: 0
164
+ });
165
+ return;
166
+ }
167
+
168
+ const reqId = req.id;
169
+ const action = req.action || 'eval';
170
+ const code = req.code || '';
171
+ const shouldReset = Boolean(req.reset);
172
+
173
+ if (action === 'ping') {
174
+ sendFrame({
175
+ id: reqId,
176
+ success: true,
177
+ status: 'pong',
178
+ pid: process.pid
179
+ });
180
+ return;
181
+ }
182
+
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
+ let stdoutBuf = '';
199
+ let stderrBuf = '';
200
+
201
+ // Intercept console inside context
202
+ const customConsole = {
203
+ log: (...args) => {
204
+ stdoutBuf += util.format(...args) + '\n';
205
+ },
206
+ info: (...args) => {
207
+ stdoutBuf += util.format(...args) + '\n';
208
+ },
209
+ warn: (...args) => {
210
+ stderrBuf += util.format(...args) + '\n';
211
+ },
212
+ error: (...args) => {
213
+ stderrBuf += util.format(...args) + '\n';
214
+ }
215
+ };
216
+ CURRENT_CONTEXT.console = customConsole;
217
+
218
+ const startTime = performance.now();
219
+ let success = true;
220
+ let errorMsg = null;
221
+ let rawResult;
222
+
223
+ try {
224
+ rawResult = await executeInContext(code, CURRENT_CONTEXT);
225
+ } catch (err) {
226
+ success = false;
227
+ errorMsg = err instanceof Error ? err.stack || err.message : String(err);
228
+ stderrBuf += errorMsg + '\n';
229
+ }
230
+
231
+ const elapsedMs = Number((performance.now() - startTime).toFixed(3));
232
+ const { result, resultRepr } = serializeResult(rawResult);
233
+
234
+ sendFrame({
235
+ id: reqId,
236
+ success,
237
+ stdout: stdoutBuf,
238
+ stderr: stderrBuf,
239
+ result: success ? result : null,
240
+ resultRepr: success ? resultRepr : null,
241
+ error: success ? null : errorMsg,
242
+ executionTimeMs: elapsedMs
243
+ });
244
+ });
245
+ }
246
+
247
+ main();
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ py_worker.py - Zero-dependency persistent Python worker for DSH Agent.
5
+ Maintains a stateful global scope across execution frames over stdio line-delimited JSON.
6
+ """
7
+
8
+ import sys
9
+ import io
10
+ import os
11
+ import ast
12
+ import json
13
+ import time
14
+ import traceback
15
+ import math
16
+ import re
17
+ import collections
18
+ import itertools
19
+
20
+ # Ensure strict UTF-8 stdio streams with line buffering
21
+ if hasattr(sys.stdin, "reconfigure"):
22
+ sys.stdin.reconfigure(encoding="utf-8", errors="replace")
23
+ if hasattr(sys.stdout, "reconfigure"):
24
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
25
+ if hasattr(sys.stderr, "reconfigure"):
26
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
27
+
28
+ # Keep handles to original standard streams for JSON protocol frames
29
+ REAL_STDIN = sys.__stdin__
30
+ REAL_STDOUT = sys.__stdout__
31
+
32
+ def create_fresh_scope():
33
+ return {
34
+ "__name__": "__main__",
35
+ "__doc__": "DSH Persistent Python Kernel",
36
+ "__builtins__": __builtins__,
37
+ "math": math,
38
+ "re": re,
39
+ "json": json,
40
+ "time": time,
41
+ "collections": collections,
42
+ "itertools": itertools,
43
+ }
44
+
45
+ GLOBAL_SCOPE = create_fresh_scope()
46
+
47
+ def execute_code(code, scope):
48
+ """
49
+ Execute python code.
50
+ If the last AST node is an expression, evaluate it to capture its return value.
51
+ Otherwise execute as statements.
52
+ """
53
+ code_stripped = code.strip()
54
+ if not code_stripped:
55
+ return None
56
+
57
+ parsed = ast.parse(code, filename="<eval_kernel>", mode="exec")
58
+ if not parsed.body:
59
+ return None
60
+
61
+ # Check if the last statement is an expression
62
+ last_stmt = parsed.body[-1]
63
+ if isinstance(last_stmt, ast.Expr):
64
+ # If there are preceding statements, execute them first
65
+ if len(parsed.body) > 1:
66
+ exec_mod = ast.Module(body=parsed.body[:-1], type_ignores=[])
67
+ exec(compile(exec_mod, filename="<eval_kernel>", mode="exec"), scope)
68
+
69
+ # Evaluate the trailing expression
70
+ eval_expr = ast.Expression(body=last_stmt.value)
71
+ return eval(compile(eval_expr, filename="<eval_kernel>", mode="eval"), scope)
72
+ else:
73
+ # All statements, execute directly
74
+ exec(compile(parsed, filename="<eval_kernel>", mode="exec"), scope)
75
+ return None
76
+
77
+ def serialize_result(result):
78
+ if result is None:
79
+ return None, None
80
+ if isinstance(result, float):
81
+ rounded = round(result, 10)
82
+ if abs(result - rounded) < 1e-12:
83
+ result_repr = str(rounded)
84
+ else:
85
+ result_repr = repr(result)
86
+ else:
87
+ result_repr = repr(result)
88
+ try:
89
+ # Check if directly JSON-serializable
90
+ json.dumps(result)
91
+ return result, result_repr
92
+ except (TypeError, OverflowError):
93
+ # Fall back to string representation
94
+ return result_repr, result_repr
95
+
96
+ def main():
97
+ global GLOBAL_SCOPE
98
+
99
+ # Signal ready frame on startup
100
+ ready_frame = json.dumps({"status": "ready", "pid": os.getpid()}, ensure_ascii=False) + "\n"
101
+ REAL_STDOUT.buffer.write(ready_frame.encode("utf-8"))
102
+ REAL_STDOUT.buffer.flush()
103
+
104
+ for line in REAL_STDIN:
105
+ line_str = line.strip()
106
+ if not line_str:
107
+ continue
108
+
109
+ try:
110
+ req = json.loads(line_str)
111
+ except Exception as e:
112
+ err_frame = json.dumps({
113
+ "id": None,
114
+ "success": False,
115
+ "error": f"Invalid JSON payload: {str(e)}",
116
+ "stdout": "",
117
+ "stderr": "",
118
+ "executionTimeMs": 0
119
+ }, ensure_ascii=False) + "\n"
120
+ REAL_STDOUT.buffer.write(err_frame.encode("utf-8"))
121
+ REAL_STDOUT.buffer.flush()
122
+ continue
123
+
124
+ req_id = req.get("id")
125
+ action = req.get("action", "eval")
126
+ code = req.get("code", "")
127
+ should_reset = bool(req.get("reset", False))
128
+
129
+ if action == "ping":
130
+ resp = {
131
+ "id": req_id,
132
+ "success": True,
133
+ "status": "pong",
134
+ "pid": os.getpid()
135
+ }
136
+ frame = json.dumps(resp, ensure_ascii=False) + "\n"
137
+ REAL_STDOUT.buffer.write(frame.encode("utf-8"))
138
+ REAL_STDOUT.buffer.flush()
139
+ continue
140
+
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
+ captured_stdout = io.StringIO()
158
+ captured_stderr = io.StringIO()
159
+ old_stdout = sys.stdout
160
+ old_stderr = sys.stderr
161
+ sys.stdout = captured_stdout
162
+ sys.stderr = captured_stderr
163
+
164
+ start_time = time.perf_counter()
165
+ success = True
166
+ error_msg = None
167
+ result_val = None
168
+ result_repr = None
169
+
170
+ try:
171
+ raw_result = execute_code(code, GLOBAL_SCOPE)
172
+ result_val, result_repr = serialize_result(raw_result)
173
+ except Exception as ex:
174
+ success = False
175
+ error_msg = str(ex)
176
+ # Write traceback into captured_stderr
177
+ traceback.print_exc(file=captured_stderr)
178
+ finally:
179
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 3)
180
+ sys.stdout = old_stdout
181
+ sys.stderr = old_stderr
182
+
183
+ resp = {
184
+ "id": req_id,
185
+ "success": success,
186
+ "stdout": captured_stdout.getvalue(),
187
+ "stderr": captured_stderr.getvalue(),
188
+ "result": result_val,
189
+ "resultRepr": result_repr,
190
+ "error": error_msg,
191
+ "executionTimeMs": elapsed_ms
192
+ }
193
+
194
+ frame = json.dumps(resp, ensure_ascii=False) + "\n"
195
+ REAL_STDOUT.buffer.write(frame.encode("utf-8"))
196
+ REAL_STDOUT.buffer.flush()
197
+
198
+ if __name__ == "__main__":
199
+ main()