@dudko.dev/agent 0.0.45 → 0.0.47
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/README.md +659 -18
- package/dist/cli.js +154 -95
- package/dist/index.cjs +129 -76
- package/dist/index.d.cts +1099 -22
- package/dist/index.d.ts +1099 -22
- package/dist/index.js +129 -76
- package/dist/sandbox-worker.js +140 -0
- package/dist/subagent-worker.js +105 -69
- package/package.json +8 -2
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import {isMainThread,parentPort}from'worker_threads';var fe=Object.defineProperty;var o=(s,i)=>fe(s,"name",{value:i,configurable:true});var oe="quickjs-emscripten";var pe={memoryLimitBytes:16*1048576};var ge=1e6,Q=500,Z=[".js",".mjs",".json"],ee=1e3,he=256*1024,te=200,P=4e3;var g=o((s,i)=>s.length>i?s.slice(0,i):s,"clip"),z=o(s=>s instanceof Error?`${s.name}: ${s.message}`:typeof s=="string"?s:"unknown error","errorText"),be=o(s=>{let i=s.lastIndexOf("/");return i<=0?"/":s.slice(0,i)},"dirname"),re=o((s,i)=>{let c=String(i);if(!/^(\.{1,2}\/|\/)/.test(c)||/[\\\0]/.test(c))throw new Error(`Cannot load "${g(c,200)}": the sandbox has no packages and no Node or browser modules - only workspace files by path ("./lib.js")`);let a=c.startsWith("/")?[]:be(s).split("/").filter(Boolean);for(let p of c.split("/"))if(!(!p||p===".")){if(p===".."){if(a.length===0)throw new Error(`Cannot load "${g(c,200)}": the path leaves the workspace`);a.pop();continue}a.push(p);}let b=`/${a.join("/")}`;if(!Z.some(p=>b.toLowerCase().endsWith(p)))throw new Error(`Cannot load "${g(b,200)}": only ${Z.join(", ")} files can be imported`);return b},"resolveModulePath");var xe=o(s=>/(^|[\n;])\s*(import\s*[\w$*{'"]|export\s+[\w$*{])/.test(s),"looksLikeModule"),ve=128,ye=`(function (host, cfg) {
|
|
2
|
+
'use strict';
|
|
3
|
+
var g = globalThis, J = JSON, S = String, E = Error, P = Promise, M = Map, R = Reflect;
|
|
4
|
+
var hostLog = host.log, hostTimer = host.timer, hostClear = host.clear;
|
|
5
|
+
var hostCall = host.call, hostResolve = host.resolve, hostCompile = host.compile;
|
|
6
|
+
function inspect(v, depth, seen) {
|
|
7
|
+
var t = typeof v;
|
|
8
|
+
if (t === 'string') return depth ? J.stringify(v) : v;
|
|
9
|
+
if (t === 'bigint') return S(v) + 'n';
|
|
10
|
+
if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';
|
|
11
|
+
if (t !== 'object' || v === null) return S(v);
|
|
12
|
+
if (v instanceof E) return S(v.name) + ': ' + S(v.message) + (v.stack ? '\\n' + S(v.stack).replace(/\\n$/, '') : '');
|
|
13
|
+
if (seen.indexOf(v) >= 0) return '[Circular]';
|
|
14
|
+
if (depth > 4) return Array.isArray(v) ? '[Array]' : '[Object]';
|
|
15
|
+
if (v instanceof Date) return isNaN(v) ? 'Invalid Date' : v.toISOString();
|
|
16
|
+
if (v instanceof RegExp) return S(v);
|
|
17
|
+
seen.push(v);
|
|
18
|
+
var parts = [], out, i, keys;
|
|
19
|
+
if (Array.isArray(v)) {
|
|
20
|
+
for (i = 0; i < v.length && i < 100; i++) parts.push(inspect(v[i], depth + 1, seen));
|
|
21
|
+
if (v.length > 100) parts.push('... ' + (v.length - 100) + ' more');
|
|
22
|
+
out = parts.length ? '[ ' + parts.join(', ') + ' ]' : '[]';
|
|
23
|
+
} else if (v instanceof M) {
|
|
24
|
+
v.forEach(function (val, key) { if (parts.length < 50) parts.push(inspect(key, depth + 1, seen) + ' => ' + inspect(val, depth + 1, seen)); });
|
|
25
|
+
out = 'Map(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';
|
|
26
|
+
} else if (v instanceof Set) {
|
|
27
|
+
v.forEach(function (val) { if (parts.length < 50) parts.push(inspect(val, depth + 1, seen)); });
|
|
28
|
+
out = 'Set(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';
|
|
29
|
+
} else {
|
|
30
|
+
keys = Object.keys(v);
|
|
31
|
+
for (i = 0; i < keys.length && i < 50; i++) parts.push(keys[i] + ': ' + inspect(v[keys[i]], depth + 1, seen));
|
|
32
|
+
if (keys.length > 50) parts.push('... ' + (keys.length - 50) + ' more');
|
|
33
|
+
out = parts.length ? '{ ' + parts.join(', ') + ' }' : '{}';
|
|
34
|
+
}
|
|
35
|
+
seen.pop();
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
function print(level) {
|
|
39
|
+
return function () {
|
|
40
|
+
var s = '', i;
|
|
41
|
+
try {
|
|
42
|
+
for (i = 0; i < arguments.length && s.length <= cfg.max; i++) s += (i ? ' ' : '') + inspect(arguments[i], 0, []);
|
|
43
|
+
} catch (e) { s += '[unprintable]'; }
|
|
44
|
+
hostLog(level, s.length > cfg.max ? s.slice(0, cfg.max + 1) : s);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
g.console = { log: print(''), info: print(''), debug: print(''), trace: print(''), warn: print('warn'), error: print('error') };
|
|
48
|
+
function plain(v, depth, seen, budget) {
|
|
49
|
+
var t = typeof v, out, i, keys;
|
|
50
|
+
if ((budget.n -= 1) < 0) { budget.cut = true; return '[Truncated]'; }
|
|
51
|
+
if (v === null || t === 'boolean' || t === 'undefined') return v;
|
|
52
|
+
if (t === 'string') { if (v.length > cfg.max) { budget.cut = true; return v.slice(0, cfg.max); } return v; }
|
|
53
|
+
if (t === 'number') return isFinite(v) ? v : S(v);
|
|
54
|
+
if (t === 'bigint') return S(v) + 'n';
|
|
55
|
+
if (t === 'symbol') return S(v);
|
|
56
|
+
if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';
|
|
57
|
+
if (v instanceof E) return { name: S(v.name), message: S(v.message) };
|
|
58
|
+
if (seen.indexOf(v) >= 0) return '[Circular]';
|
|
59
|
+
if (depth >= 8) return Array.isArray(v) ? '[Array]' : '[Object]';
|
|
60
|
+
if (v instanceof Date) return isNaN(v) ? null : v.toISOString();
|
|
61
|
+
seen.push(v);
|
|
62
|
+
if (v instanceof M) { out = []; v.forEach(function (val, key) { out.push([plain(key, depth + 1, seen, budget), plain(val, depth + 1, seen, budget)]); }); }
|
|
63
|
+
else if (v instanceof Set) { out = []; v.forEach(function (val) { out.push(plain(val, depth + 1, seen, budget)); }); }
|
|
64
|
+
else if (Array.isArray(v)) { out = []; for (i = 0; i < v.length && budget.n >= 0; i++) out.push(plain(v[i], depth + 1, seen, budget)); }
|
|
65
|
+
else { out = {}; keys = Object.keys(v); for (i = 0; i < keys.length && budget.n >= 0; i++) out[keys[i]] = plain(v[keys[i]], depth + 1, seen, budget); }
|
|
66
|
+
seen.pop();
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
function serialize(v, max) {
|
|
70
|
+
if (v === undefined) return '';
|
|
71
|
+
var budget = { n: 20000, cut: false }, text;
|
|
72
|
+
try { text = J.stringify(plain(v, 0, [], budget)); } catch (e) { text = J.stringify('[unserializable]'); }
|
|
73
|
+
if (text === undefined) return '';
|
|
74
|
+
if (text.length > max) return 'T' + text.slice(0, max);
|
|
75
|
+
return (budget.cut ? 'C' : 'J') + text;
|
|
76
|
+
}
|
|
77
|
+
function describe(e) {
|
|
78
|
+
var name = 'Error', message = '', stack = '';
|
|
79
|
+
try {
|
|
80
|
+
if (e instanceof E || (e && typeof e === 'object' && typeof e.message === 'string')) {
|
|
81
|
+
name = S(e.name || 'Error'); message = S(e.message); stack = typeof e.stack === 'string' ? e.stack : '';
|
|
82
|
+
} else { message = 'thrown: ' + inspect(e, 1, []); }
|
|
83
|
+
} catch (x) { message = '[unprintable error]'; }
|
|
84
|
+
return J.stringify([name.slice(0, cfg.nameMax), message.slice(0, cfg.textMax), stack.slice(0, cfg.textMax)]);
|
|
85
|
+
}
|
|
86
|
+
var timers = new M(), nextTimer = 1;
|
|
87
|
+
function timer(repeat) {
|
|
88
|
+
return function (fn, ms) {
|
|
89
|
+
if (typeof fn !== 'function') throw new TypeError('the first argument must be a function');
|
|
90
|
+
if (timers.size >= cfg.maxTimers) throw new RangeError('too many timers');
|
|
91
|
+
var id = nextTimer++;
|
|
92
|
+
ms = +ms; if (!(ms >= 0)) ms = 0; if (ms > 2147483647) ms = 2147483647;
|
|
93
|
+
if (repeat && ms < 1) ms = 1;
|
|
94
|
+
timers.set(id, { fn: fn, args: Array.prototype.slice.call(arguments, 2), ms: ms, repeat: repeat });
|
|
95
|
+
hostTimer(id, ms);
|
|
96
|
+
return id;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function clear(id) { if (timers.delete(id)) hostClear(id); }
|
|
100
|
+
function fire(id) {
|
|
101
|
+
var t = timers.get(id);
|
|
102
|
+
if (!t) return;
|
|
103
|
+
if (t.repeat) hostTimer(id, t.ms); else timers.delete(id);
|
|
104
|
+
R.apply(t.fn, undefined, t.args);
|
|
105
|
+
}
|
|
106
|
+
g.setTimeout = timer(false); g.setInterval = timer(true);
|
|
107
|
+
g.clearTimeout = clear; g.clearInterval = clear;
|
|
108
|
+
g.queueMicrotask = function (fn) { P.resolve().then(fn); };
|
|
109
|
+
if (cfg.ops.length) {
|
|
110
|
+
var fs = {};
|
|
111
|
+
cfg.ops.forEach(function (op) {
|
|
112
|
+
fs[op] = function () {
|
|
113
|
+
var text;
|
|
114
|
+
try { text = J.stringify(Array.prototype.slice.call(arguments)); } catch (e) { return P.reject(new TypeError('fs.' + op + ': the arguments must be plain data')); }
|
|
115
|
+
if (text.length > cfg.maxCall) return P.reject(new RangeError('fs.' + op + ': the arguments are too large'));
|
|
116
|
+
return hostCall(op, text).then(function (r) { return r === '' ? undefined : J.parse(r); });
|
|
117
|
+
};
|
|
118
|
+
});
|
|
119
|
+
g.fs = fs;
|
|
120
|
+
}
|
|
121
|
+
var loaded = new M();
|
|
122
|
+
function requireFrom(base) {
|
|
123
|
+
return function require(spec) {
|
|
124
|
+
var path = hostResolve(base, S(spec)), mod = loaded.get(path), made;
|
|
125
|
+
if (mod) return mod.exports;
|
|
126
|
+
mod = { exports: {} };
|
|
127
|
+
loaded.set(path, mod);
|
|
128
|
+
made = hostCompile(path);
|
|
129
|
+
if (typeof made === 'string') mod.exports = J.parse(made);
|
|
130
|
+
else made.call(mod.exports, mod, mod.exports, requireFrom(path), path, path.slice(0, Math.max(1, path.lastIndexOf('/'))));
|
|
131
|
+
return mod.exports;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
g.require = requireFrom(cfg.filename);
|
|
135
|
+
return { fire: fire, serialize: serialize, describe: describe };
|
|
136
|
+
})`,W="<sandbox>",X="refused:",ne=65536,Se=o((s,i)=>{let c=globalThis.WebAssembly,a=new c.Memory({initial:pe.memoryLimitBytes/ne,maximum:Math.floor(i/ne)});return s.newQuickJSWASMModuleFromVariant(s.newVariant(s.RELEASE_SYNC,{wasmMemory:a}))},"newBoundedModule"),we=o(async(s,i,c={})=>{let{limits:a}=i,b=i.filename??"/main.js",p=i.modules,M=c.hostCall?i.hostOps??[]:[],d=(await Se(s,a.memoryLimitBytes)).newRuntime();d.setMemoryLimit(a.memoryLimitBytes),d.setMaxStackSize(he);let r=d.newContext();return new Promise(B=>{let j=Date.now(),x=false,h=false,$=0,S=0,q=0,A=0,w=0,ue=0,v,y=new Map,H=[],T=0,I=false,R,D,N="value",le=o(()=>$+(S?Date.now()-S:0),"cpuUsed"),U=o(()=>Date.now()-j-q-(A?Date.now()-A:0),"wallUsed"),G=o(()=>le()>a.timeoutMs||w===0&&U()>a.timeoutMs,"overTime");d.setInterruptHandler(()=>x||G()?(h=true,true):false);let m=o((e,t)=>{if(!x){x=true,v!==void 0&&clearTimeout(v);for(let n of y.values())clearTimeout(n);y.clear(),B({ok:!e,stdout:H.join(""),...t?{result:t.value}:{},...e?{error:e}:{},truncated:I,durationMs:Date.now()-j});}},"finish"),_=o(()=>({name:"TimeoutError",message:`the run was stopped after ${a.timeoutMs} ms (timeoutMs)`}),"timedOut"),L=o(e=>{if(h)return _();try{let t;if(R){let l=r.callFunction(R.describe,r.undefined,e);t=l.error?void 0:JSON.parse(r.getString(l.value));}if(!Array.isArray(t)){let l=r.dump(e);t=[l?.name??"Error",l?.message??String(l),l?.stack??""];}let[n,u,k]=t,E=String(k??"").split(`
|
|
137
|
+
`).filter(l=>l.trim()&&!l.includes(W)).join(`
|
|
138
|
+
`);return {name:g(String(n||"Error"),te),message:g(String(u??""),P),...E?{stack:g(E,P)}:{}}}catch{return h?_():{name:"Error",message:"the program threw an error that could not be read"}}},"describe"),K=o(e=>{h?m(_()):e instanceof RangeError?m({name:"RangeError",message:"Maximum call stack size exceeded"}):m({name:"SandboxError",message:g(z(e),P)});},"engineFailure"),F=o(()=>{v!==void 0&&(clearTimeout(v),v=void 0),!(x||w>0)&&(v=setTimeout(()=>{v=void 0,G()?(h=true,m(_())):F();},Math.max(1,a.timeoutMs-U()+1)));},"armWatchdog"),ce=o(()=>{for(;!x;){if(h){m(_());return}let e=r.getPromiseState(D);if(e.type==="rejected"){m(L(e.error));return}if(e.type==="pending"){y.size===0&&w===0&&m({name:"Error",message:"the program awaits a promise that can never settle (nothing is left to run)"});return}if(N!=="value"){D=r.getProp(e.value,N==="script"?"value":"default"),N="value";continue}if(!e.notAPromise){D=e.value;continue}if(y.size>0||w>0)return;let t=Math.max(200,a.maxOutputChars-T),n=r.callFunction(R.serialize,r.undefined,e.value,r.newNumber(t));if(n.error){m(L(n.error));return}let u=r.getString(n.value);u===""?m():u[0]==="T"?(I=true,m(void 0,{value:g(u.slice(1),t)})):(I||=u[0]==="C",m(void 0,{value:JSON.parse(u.slice(1))}));return}},"settle"),J=o(e=>{if(!x){S=Date.now();try{for(e();!x&&!h;){let t=d.executePendingJobs();if(t.error){let n=L(t.error);$+=Date.now()-S,S=0,m(n);return}if(!d.hasPendingJob())break}$+=Date.now()-S,S=0,ce();}catch(t){$+=Date.now()-S,S=0,K(t);}}},"enter"),C=o((e,t)=>Object.assign(new Error(t),{name:e}),"guestError"),V=r.newObject(),O=o((e,t)=>{r.setProp(V,e,r.newFunction(e,t));},"expose");O("log",(e,t)=>{if(T>=a.maxOutputChars){I=true;return}let n=r.getString(e),u=`${n?`[${n}] `:""}${r.getString(t)}
|
|
139
|
+
`;T+u.length>a.maxOutputChars&&(u=u.slice(0,a.maxOutputChars-T),I=true),H.push(u),T+=u.length;}),O("timer",(e,t)=>{let n=r.getNumber(e),u=r.getNumber(t),k=y.get(n);if(k!==void 0)clearTimeout(k);else if(y.size>=ee)throw C("RangeError","too many timers");y.set(n,setTimeout(()=>{y.delete(n),J(()=>{let E=r.callFunction(R.fire,r.undefined,r.newNumber(n));E.error&&m(L(E.error));});},Math.min(Math.max(0,u),a.timeoutMs+1)));}),O("clear",e=>{let t=r.getNumber(e),n=y.get(t);n!==void 0&&(clearTimeout(n),y.delete(t));}),O("call",(e,t)=>{let n=r.getString(e);if(!M.includes(n)||!c.hostCall)throw C("Error",`fs.${g(n,40)} is not available in this sandbox`);if((ue+=1)>Q)throw C("RangeError",`too many file operations in one run (limit ${Q})`);let u=JSON.parse(r.getString(t)),k=r.newPromise();w===0&&(A=Date.now(),v!==void 0&&(clearTimeout(v),v=void 0)),w+=1;let E=o(l=>{w-=1,w===0&&(q+=Date.now()-A,A=0),!x&&(F(),J(l));},"done");return c.hostCall(n,u).then(l=>E(()=>{let me=l===void 0?"":JSON.stringify(l);k.resolve(r.newString(me??""));}),l=>E(()=>{k.reject(r.newError({name:"Error",message:g(l instanceof Error?l.message:String(l),P)}));})),k.handle});let Y=o(e=>{if(!p)throw C("Error",`Cannot load "${g(e,200)}": this sandbox has no files`);if(!Object.hasOwn(p,e))throw C("Error",`Cannot load "${g(e,200)}": no such file in the workspace (a module must exist before the run and be named by a literal path)`);return p[e]},"load"),de=o((e,t)=>{try{return re(e,t)}catch(n){throw C("Error",n instanceof Error?n.message:String(n))}},"resolvePath");O("resolve",(e,t)=>r.newString(de(r.getString(e),r.getString(t)))),O("compile",e=>{let t=r.getString(e),n=Y(t);if(t.toLowerCase().endsWith(".json"))return r.newString(n);let u=r.evalCode(`(function (module, exports, require, __filename, __dirname) {${n}
|
|
140
|
+
})`,t);return u.error?{error:u.error}:u.value}),d.setModuleLoader(e=>{try{if(e.startsWith(X))throw new Error(e.slice(X.length));let t=Y(e);return e.toLowerCase().endsWith(".json")?`export default JSON.parse(${JSON.stringify(t)})`:t}catch(t){return {error:t}}},(e,t)=>{try{return re(e,t)}catch(n){return `${X}${n instanceof Error?n.message:String(n)}`}});try{let e=r.evalCode(ye,W);if(e.error){m({name:"SandboxError",message:"the sandbox runtime failed to start"});return}let t=r.callFunction(e.value,r.undefined,V,r.evalCode(`(${JSON.stringify({max:a.maxOutputChars,nameMax:te,textMax:P,maxTimers:ee,maxCall:ge+2e3,ops:M,filename:b})})`,W).unwrap());if(t.error){m({name:"SandboxError",message:"the sandbox runtime failed to start"});return}R={fire:r.getProp(t.value,"fire"),serialize:r.getProp(t.value,"serialize"),describe:r.getProp(t.value,"describe")};}catch(e){K(e);return}c.onStart?.(),F(),J(()=>{let e=r.evalCode(i.code,b,ve);if(N="script",e.error&&!h&&xe(i.code)&&(e=r.evalCode(i.code,b,{type:"module"}),N="module"),e.error){m(L(e.error));return}D=e.value;});})},"runGuest");var ie=o((s,i)=>{let c=new Map,a=0,b=false,p=o(async M=>{let f;try{f=await i();}catch(d){s.post({type:"failed",code:"peer-missing",message:z(d)});return}try{let d=await we(f,M,{onStart:o(()=>s.post({type:"started"}),"onStart"),hostCall:o((r,B)=>new Promise((j,x)=>{let h=a+=1;c.set(h,{resolve:j,reject:x}),s.post({type:"host-call",id:h,op:r,args:B});}),"hostCall")});s.post({type:"done",result:d});}catch(d){s.post({type:"failed",code:"engine",message:z(d)});}},"run");s.listen(M=>{let f=M;if(f?.type==="run"&&!b)b=true,p(f.request);else if(f?.type==="host-result"){let d=c.get(f.id);d&&(c.delete(f.id),f.ok?d.resolve(f.value):d.reject(new Error(typeof f.error=="string"?f.error:"the file operation failed")));}});},"serveSandbox");if(!isMainThread&&parentPort){let s=parentPort;ie({post:o(i=>s.postMessage(i),"post"),listen:o(i=>{s.on("message",i);},"listen")},async()=>await import(oe));}
|