@hermenics/deepseek-code 0.13.3 → 0.13.5
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/dist/browser-egress-worker.mjs +12 -12
- package/dist/cli.mjs +2588 -1306
- package/dist/runtime.mjs +3 -3
- package/dist/shell-supervisor.mjs +19 -20
- package/package.json +1 -1
package/dist/runtime.mjs
CHANGED
|
@@ -3,15 +3,15 @@
|
|
|
3
3
|
import { dirname, join } from 'node:path'
|
|
4
4
|
import { fileURLToPath } from 'node:url'
|
|
5
5
|
|
|
6
|
-
const MIN_BUN = [1,
|
|
6
|
+
const MIN_BUN = [1, 4]
|
|
7
7
|
const version = typeof Bun !== 'undefined' ? Bun.version : undefined
|
|
8
8
|
if (!version) {
|
|
9
|
-
console.error('DeepSeek Code requires Bun 1.
|
|
9
|
+
console.error('DeepSeek Code requires Bun 1.4+ at runtime. Install Bun: https://bun.sh')
|
|
10
10
|
process.exit(1)
|
|
11
11
|
}
|
|
12
12
|
const [major = 0, minor = 0] = version.split('.').map(Number)
|
|
13
13
|
if (major < MIN_BUN[0] || (major === MIN_BUN[0] && minor < MIN_BUN[1])) {
|
|
14
|
-
console.error(`DeepSeek Code requires Bun 1.
|
|
14
|
+
console.error(`DeepSeek Code requires Bun 1.4+ (found ${version}).`)
|
|
15
15
|
process.exit(1)
|
|
16
16
|
}
|
|
17
17
|
|
|
@@ -1,31 +1,30 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createHash as
|
|
3
|
-
`,"utf8")}finally{await V.close()}}).catch((V)=>{this.writeError=V instanceof Error?V:Error(String(V))});return K}subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}list($){return this.memory.filter((Z)=>!$||Z.taskId===$).map((Z)=>structuredClone(Z))}async flush(){if(await this.writeChain,this.writeError)throw this.writeError}}import{createHash as h2,randomUUID as p0}from"crypto";import{mkdir as y0,readFile as u0,rm as v2,stat as H0,writeFile as y2}from"fs/promises";import{tmpdir as m2}from"os";import{join as t}from"path";import{chmod as $5,readFile as Z5,writeFile as z5,readdir as Q5,rename as g2}from"fs/promises";var f2=new Set(["EPERM","EACCES","EBUSY"]);async function v0($,Z,{platform:Q=process.platform,renameFile:z=g2,attempts:J=10}={}){for(let K=1;;K++)try{return await z($,Z)}catch(V){let Y=V.code??"";if(Q!=="win32"||!f2.has(Y)||K>=J)throw V;await new Promise((U)=>setTimeout(U,K*10))}}var m0=t(m2(),"deepseek-code-leases-v1");function _0($){return $.reason??Error("Lease acquisition cancelled")}async function p2($,Z){if(Z?.aborted)throw _0(Z);await new Promise((Q,z)=>{let J=setTimeout(()=>{V(),Q()},$),K=()=>{clearTimeout(J),V(),z(_0(Z))},V=()=>Z?.removeEventListener("abort",K);Z?.addEventListener("abort",K,{once:!0})})}function u2($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch(Z){return Z.code!=="ESRCH"}}async function X0($,Z){let Q=`${$}.${Z}-${p0()}`;try{await v0($,Q)}catch(z){if(["ENOENT","EEXIST"].includes(z.code??""))return!1;throw z}return await v2(Q,{recursive:!0,force:!0}),!0}async function l2($){try{let Z=JSON.parse(await u0(t($,"owner.json"),"utf8"));if(typeof Z.pid==="number"&&u2(Z.pid))return!1;return X0($,"stale")}catch(Z){let Q=await H0($).catch(()=>{return});if(!Q||Date.now()-Q.mtimeMs<30000)return!1;return X0($,Z.code==="ENOENT"?"incomplete":"invalid")}}async function W0($,Z={},Q){if(Q?.aborted)throw _0(Q);await y0(m0,{recursive:!0,mode:448});let z=h2("sha256").update($).digest("hex"),J=t(m0,z),K=p0(),V={token:K,pid:process.pid,createdAt:new Date().toISOString(),resource:$,metadata:Z};while(!0)try{await y0(J,{mode:448});try{await y2(t(J,"owner.json"),`${JSON.stringify(V)}
|
|
4
|
-
`,{encoding:"utf8",mode:384})}catch(X){throw await X0(J,"incomplete").catch(()=>!1),X}let Y=!1,U,H=async()=>{if(Y)return;let X;try{X=JSON.parse(await u0(t(J,"owner.json"),"utf8"))}catch(W){if(W.code!=="ENOENT")throw W;try{await H0(J)}catch(G){if(G.code!=="ENOENT")throw G;Y=!0;return}throw W}if(X.token!==K){Y=!0;return}try{if(await X0(J,"released")){Y=!0;return}}catch(W){try{await H0(J)}catch(G){if(G.code!=="ENOENT")throw G;Y=!0;return}throw W}try{await H0(J)}catch(W){if(W.code!=="ENOENT")throw W;Y=!0;return}throw Error("Lease directory could not be moved aside")};return{token:K,path:J,release(){if(Y)return Promise.resolve();if(U)return U;let X;return X=H().finally(()=>{if(U===X)U=void 0}),U=X,X}}}catch(Y){if(Y.code!=="EEXIST")throw Y;if(await l2(J))continue;await p2(25,Q)}}var l0=new Intl.Segmenter(void 0,{granularity:"grapheme"});function c0($,Z){return Math.max(0,Math.min($.length,Number.isNaN(Z)?0:Math.trunc(Z)))}function h($,Z){let Q=c0($,Z);if(Q===0||Q===$.length)return Q;let z=0;for(let J of l0.segment($)){let K=J.index+J.segment.length;if(K>Q)return J.index;z=K}return z}function s($,Z){let Q=c0($,Z);if(Q===0||Q===$.length)return Q;for(let z of l0.segment($)){let J=z.index+z.segment.length;if(z.index>=Q)return z.index;if(J>Q)return J}return $.length}var a0=2000000,i=20971520,$0=10,t2=16777216,e2=33554432,$3=256;var Z3=60000,F0=a0,L0=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,v=new Map;function z0($,Z){let Q=Z0("sha256").update($).digest("hex");return A(Z??process.env.HOME??R0(),".deepseek-code","shell-output",Q)}function r0($,Z,Q){let z=Z0("sha256").update($).digest("hex"),J=Q??(Z?A(o0(Z),`${o2(Z)||"shell-output"}-recovery`):A(process.env.HOME??R0(),".deepseek","shell-output-recovery"));return A(J,z)}function z3($){let Z=typeof process.getuid==="function"?String(process.getuid()):Z0("sha256").update(R0()).digest("hex").slice(0,16);return $??A(d2(),`deepseek-code-shell-output-${Z}`)}function t0($,Z){let Q=Z0("sha256").update($).digest("hex");return A(z3(Z),Q)}async function e0($){try{let Z=await e($);if(!Z.isDirectory()||Z.isSymbolicLink()||typeof process.getuid==="function"&&Z.uid!==process.getuid())return;let Q=A($,"supervisors"),z=await e(Q).catch((U)=>{if(U.code==="ENOENT")return;throw U});if(!z)return new Set;if(!z.isDirectory()||z.isSymbolicLink()||typeof process.getuid==="function"&&z.uid!==process.getuid())return;let J=new Set,K=0,V=0,Y=await i2(Q);for await(let U of Y){if(!/^[a-f0-9]{64}\.json$/i.test(U.name))continue;if(++V>$3)return;let H=A(Q,U.name),X=await e(H);if(!X.isFile()||X.isSymbolicLink()||typeof process.getuid==="function"&&X.uid!==process.getuid()||X.size>t2)return;if(K+=X.size,K>e2)return;let W=JSON.parse(await j0(H,"utf8"));if(W.schema!=="shell_supervisor_v1")return;for(let G of[W.outputId,W.reservedOutputId]){if(G===void 0)continue;if(typeof G!=="string"||!L0.test(G))return;J.add(G)}}return J}catch(Z){if(["ENOENT","ENOTDIR"].includes(Z.code??""))return new Set;return}}async function Q3($,Z,Q){let J=(await Promise.all((await n2($)).filter((U)=>L0.test(U)).map(async(U)=>({id:U,path:A($,U),info:await a2(A($,U)).catch(()=>null)})))).filter((U)=>U.info!==null).sort((U,H)=>U.info.mtimeMs-H.info.mtimeMs),K=J.reduce((U,H)=>U+H.info.size,0),V=J.length,Y=[];for(let U of J){if(V<=$0&&K<=i)break;if(U.id===Z||Q===void 0||Q.has(U.id))continue;try{await n0(U.path)}catch(H){if(H.code!=="ENOENT"){Y.push(H);continue}}V--,K-=U.info.size}if(Y.length>0){let U=Error(`Failed to remove ${Y.length} shell output artifact(s) during cleanup`);throw Object.assign(U,{code:Y[0]?.code}),U}return V<=$0&&K<=i}async function B0($,Z,Q,z){try{await J3($,Z,Q)}catch(J){return{stored:!1,error:J}}try{if(await Q3($,Z,z))return{stored:!0};try{await n0(A($,Z))}catch(J){if(J.code!=="ENOENT")return{stored:!0,cleanupWarning:`retention cleanup ${J.code??"failed"}`}}return{stored:!1,error:Object.assign(Error("Shell output retention quota is occupied by referenced artifacts"),{code:"ENOSPC"})}}catch(J){return{stored:!0,cleanupWarning:`cleanup ${J.code??"failed"}`}}}function b0($,Z){return`${$}\x00${Z}`}function M0($){return Z0("sha256").update(JSON.stringify({totalChars:$.totalChars,storedChars:$.storedChars,truncated:$.truncated,redacted:$.redacted===!0,content:$.content,provenance:$.provenance??null})).digest("hex")}function G0($){try{let Z=JSON.parse($);if(typeof Z.content!=="string")return!1;if(Z.contentHash===void 0)return Z.schemaVersion!==2;if(!Number.isSafeInteger(Z.totalChars)||!Number.isSafeInteger(Z.storedChars)||typeof Z.truncated!=="boolean")return!1;return Z.contentHash===M0(Z)}catch{return!1}}async function d0($,Z,Q,z,J,K){let V=JSON.stringify({...Q,schemaVersion:2,storage:"memory",contentHash:M0({...Q,content:z,provenance:J}),content:z,...J?{provenance:J}:{}}),Y=Buffer.byteLength(V,"utf8");if(Y>i)return!1;let U=b0($,Z),H=new Map([[$,K]]);for(let B of v.values())if(!H.has(B.directory))H.set(B.directory,await e0(B.directory));let X=[...v.values()].filter((B)=>{let N=H.get(B.directory);return N===void 0||N.has(B.id)});if(X.length+1>$0||X.reduce((B,N)=>B+N.bytes,Y)>i)return!1;v.set(U,{directory:$,id:Z,raw:V,bytes:Y,createdAt:Date.now()});let W=[...v.entries()].sort((B,N)=>B[1].createdAt-N[1].createdAt),G=W.reduce((B,[,N])=>B+N.bytes,0),k=W.length;for(let[B,N]of W){if(k<=$0&&G<=i)break;let M=H.get(N.directory);if(B===U||M===void 0||M.has(N.id))continue;v.delete(B),k--,G-=N.bytes}if(k>$0||G>i)v.delete(U);return v.has(U)}async function J3($,Z,Q){if(await i0($,{recursive:!0,mode:448}),!(await e($)).isDirectory())throw Error("shell output storage path is not a directory");await s0($,448),await r2(A($,Z),Q,{encoding:"utf8",mode:384,flag:"wx"})}async function K3($){await i0($,{mode:448}).catch((Q)=>{if(Q.code!=="EEXIST")throw Q});let Z=await e($);if(!Z.isDirectory()||Z.isSymbolicLink()||typeof process.getuid==="function"&&Z.uid!==process.getuid())throw Error("Shell emergency output root is not an owned directory");await s0($,448)}async function N0($,Z,Q,z,J,K,V){let Y=M0({...Q,content:z,provenance:J}),U=JSON.stringify({...Q,schemaVersion:2,storage:"emergency-disk",contentHash:Y,retentionWarning:K,content:z,...J?{provenance:J}:{}});try{await K3(o0($))}catch(X){return{retained:!1,warning:`${K}; emergency storage failed (${X.code??"failed"})`}}let H=await B0($,Z,U,V);if(!H.stored)return{retained:!1,warning:`${K}; emergency storage failed (${H.error?.code??"failed"})`};if(H.cleanupWarning)K+=`; emergency ${H.cleanupWarning}`;return{retained:!0,warning:K}}async function V3($,Z,Q,z){let J=v.get(b0($,z));if(J){if(G0(J.raw))return J.raw;v.delete(b0($,z))}let K;try{let V=await j0(A($,z),"utf8");if(G0(V))return V;K=Error("Shell output artifact integrity check failed")}catch(V){K=V}try{let V=await j0(A(Z,z),"utf8");if(G0(V))return V;throw Error("Shell output artifact integrity check failed")}catch{}try{let V=await j0(A(Q,z),"utf8");if(G0(V))return V;throw Error("Shell output artifact integrity check failed")}catch{throw K}}async function $2($,Z,Q){let z=z0($,Z),J=new AbortController,K=setTimeout(()=>J.abort(Error("Timed out waiting for the shell output artifact lease")),Z3),V;try{if(V=await W0(`shell-output-artifacts:${s2(z)}`,{},J.signal),J.signal.aborted)throw await V.release(),J.signal.reason}finally{clearTimeout(K)}try{return await Q((Y,U,H,X,W,G)=>Y3($,Y,U,Z,H,X,W,G))}finally{await V.release()}}async function Y3($,Z,Q=Z.length,z,J,K,V,Y=c2()){if(!L0.test(Y))throw Error("Invalid shell output ID");let U=z0($,z),H=r0($,z,K),X=t0($,V),W=await e0(U),G=Y,k=c(Z),B=h(k,a0),N={totalChars:Q,storedChars:B,truncated:B<Q,redacted:k!==Z},M=k.slice(0,B),D=M0({...N,content:M,provenance:J}),q=JSON.stringify({...N,schemaVersion:2,storage:"disk",contentHash:D,content:M,...J?{provenance:J}:{}}),E=await B0(U,G,q,W);if(!E.stored){let C=E.error,O=`primary storage failed (${C?.code??"failed"})`;if(H!==U){let l=JSON.stringify({...N,schemaVersion:2,storage:"recovery-disk",contentHash:D,retentionWarning:O,content:M,...J?{provenance:J}:{}}),b=await B0(H,G,l,W);if(b.stored){let S=O;if(b.cleanupWarning)S+=`; recovery ${b.cleanupWarning}`;if(X!==U&&X!==H){let f=await N0(X,G,N,M,J,`${O}; emergency mirror`,W);S+=f.retained?"; emergency copy retained":`; ${f.warning}`}return{id:G,metadata:{...N,storage:"recovery-disk",retentionWarning:S}}}let y=`recovery storage failed (${b.error?.code??"failed"})`;if(X!==U&&X!==H){let S=await N0(X,G,N,M,J,`${O}; ${y}`,W);if(S.retained)return{id:G,metadata:{...N,storage:"emergency-disk",retentionWarning:S.warning}};let f={...N,storage:"memory",retentionWarning:S.warning};if(await d0(U,G,N,M,J,W))return{id:G,metadata:f};throw C}}let x=X!==U&&X!==H?await N0(X,G,N,M,J,O,W):null;if(x?.retained)return{id:G,metadata:{...N,storage:"emergency-disk",retentionWarning:x.warning}};let g={...N,storage:"memory",retentionWarning:x?.warning??O};if(await d0(U,G,N,M,J,W))return{id:G,metadata:g};throw C}let w;if(H!==U){let C=JSON.stringify({...N,schemaVersion:2,storage:"recovery-disk",contentHash:D,content:M,...J?{provenance:J}:{}}),O=await B0(H,G,C,W);if(O.stored){if(O.cleanupWarning)w=`recovery ${O.cleanupWarning}`}else{let x=`recovery copy failed (${O.error?.code??"failed"})`;if(X!==U&&X!==H){let g=await N0(X,G,N,M,J,x,W);w=g.retained?`${x}; emergency copy retained`:g.warning}else w=x}}if(E.cleanupWarning)w=[w,`primary ${E.cleanupWarning}`].filter(Boolean).join("; ");return{id:G,metadata:{...N,storage:"disk",...w?{retentionWarning:w}:{}}}}async function Z2($,Z,Q,z,J){if(!L0.test(Z))throw Error("Invalid shell output ID");let K=await V3(z0($,Q),r0($,Q,z),t0($,J),Z),V=JSON.parse(K);if(typeof V.content!=="string"||!Number.isSafeInteger(V.totalChars)||!Number.isSafeInteger(V.storedChars)||typeof V.truncated!=="boolean"||!["disk","recovery-disk","emergency-disk","memory"].includes(V.storage??""))throw Error("Shell output artifact is malformed");let Y={totalChars:V.totalChars,storedChars:V.storedChars,truncated:V.truncated,redacted:V.redacted===!0,storage:V.storage,...typeof V.retentionWarning==="string"?{retentionWarning:V.retentionWarning}:{}};return{content:c(V.content),metadata:Y,...V.provenance?{provenance:V.provenance}:{}}}import{execFileSync as U3}from"child_process";function H3($,Z){if(process.platform==="win32"||!Number.isSafeInteger($)||$<2)return!1;try{return process.kill(-$,Z),!0}catch(Q){if(["ESRCH","EPERM"].includes(Q.code??""))return!1;throw Q}}function z2($,Z){if($.pid&&process.platform!=="win32"){if(H3($.pid,Z))return!0;return $.kill(Z)}else if($.pid&&process.platform==="win32")try{return U3("taskkill",["/PID",String($.pid),"/T","/F"],{stdio:"ignore",timeout:5000}),!0}catch(Q){return $.kill(Z)}return $.kill(Z)}class J2{state="text";push($,Z=!1){let Q="";for(let z of $){let J=z.codePointAt(0);switch(this.state){case"text":if(J===27)this.state="escape";else if(J===155)this.state="csi";else if(J===157)this.state="osc";else if(J===144||J===152||J===158||J===159)this.state="string";else Q+=z;break;case"escape":if(z==="[")this.state="csi";else if(z==="]")this.state="osc";else if(z==="P"||z==="X"||z==="^"||z==="_")this.state="string";else this.state="text";break;case"csi":if(J>=64&&J<=126)this.state="text";break;case"osc":if(J===7)this.state="text";else if(J===156)this.state="text";else if(J===27)this.state="oscEscape";break;case"oscEscape":this.state=z==="\\"?"text":z==="\x1B"?"oscEscape":"osc";break;case"string":if(J===156)this.state="text";else if(J===27)this.state="stringEscape";break;case"stringEscape":this.state=z==="\\"?"text":z==="\x1B"?"stringEscape":"string";break}}if(Z&&this.state!=="text")this.state="text";return Q}}var W3=4096,Q0=8000,D0=8000,G3=/\b(?:error(?:\b|_[A-Z0-9_]+)|fatal|exception|traceback|fail(?:ed|ure)?|panic(?:ked)?|module not found|no module named|modulenotfounderror|cannot find symbol|unresolved (?:reference|import)|undefined reference|caused by)\b|\b[A-Za-z][A-Za-z0-9_.]*(?:Error|Exception)\b|\bundefined:|\b(?:command not found|no such file or directory)\b|\bTS\d{4,5}\b|\bERR_[A-Z0-9_]+\b|\b(?:npm|pnpm|yarn)\s+ERR!|^\s*(?:make(?:\[\d+\])?:\s+\*\*\*|ninja:\s+build stopped)/i;function Q2(){return{schema:"shell_channel_provenance_v1",ordering:"observed-arrival",stdoutChars:0,stderrChars:0,retainedChars:0,segments:[],segmentsOmitted:0,contentOmitted:0,drainTimedOut:!1}}class K2{full="";head="";middle="";tail="";total=0;append($){if(!$)return;if(this.full!==null&&this.total+$.length<=Q0*3){this.full+=$,this.total+=$.length;return}if(this.full!==null){let Z=this.full;this.full=null,this.total=0,this.appendSample(Z)}this.appendSample($)}appendSample($){if(!$)return;if(this.head.length<Q0)this.head+=$.slice(0,h($,Q0-this.head.length));if(!this.middle&&this.total+$.length>1e6){let Q=Math.max(0,1e6-this.total);this.middle=$.slice(s($,Q),h($,Q+Q0))}let Z=this.tail+$;this.tail=Z.slice(s(Z,Z.length-Q0)),this.total+=$.length}render(){if(this.full!==null)return this.full;let $=Math.max(0,this.total-this.head.length-this.middle.length-this.tail.length);return`${this.head}
|
|
5
|
-
\u2026[${$} characters omitted from this stream preview]\u2026${this.middle?`
|
|
2
|
+
import{createHash as wr,randomUUID as br}from"crypto";import{spawn as Er}from"child_process";import{chmod as xr,lstat as ft,mkdir as Or,open as Pr,readdir as Cr,rename as Tr,unlink as ut,writeFile as Ir}from"fs/promises";import{existsSync as kn,lstatSync as Ar,readFileSync as pt}from"fs";import{dirname as Rr,join as Y,resolve as kr}from"path";import{closeSync as wt,openSync as bt,readSync as Et,readlinkSync as xt,readdirSync as Ot}from"fs";function ce(e){let t=bt(e,"r");try{let n=Buffer.alloc(4097),r=0;while(r<n.length){let s=Et(t,n,r,n.length-r,null);if(!s)break;r+=s}if(r>4096)throw Error("Process identity exceeds its byte limit");return n.subarray(0,r).toString("utf8").trim()}finally{wt(t)}}function xe(e,t){let n=e.lastIndexOf(")"),r=e.indexOf("("),s=e.slice(n+1).trim().split(/\s+/);if(!Number.isSafeInteger(t)||t<1||r<1||n<=r||e.slice(0,r).trim()!==String(t)||!/^[A-Za-z]$/.test(s[0]??"")||!/^\d+$/.test(s[2]??"")||!/^\d+$/.test(s[3]??"")||!/^\d+$/.test(s[19]??""))throw Error("Invalid process identity");return{state:s[0],processGroupId:Number(s[2]),sessionId:Number(s[3]),startTimeTicks:s[19]}}function _e(){let e=xt("/proc/self/ns/pid");if(!/^pid:\[[0-9]+\]$/.test(e))throw Error("Invalid PID namespace identity");return e}function Ne(){let e=ce("/proc/sys/kernel/random/boot_id");if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e))throw Error("Invalid boot identity");return e}function Oe(e){let t={...e,observedAt:new Date().toISOString(),status:"unknown",provenance:"unavailable"},n=e.identity;if(!n&&e.provenance==="child-event")return structuredClone(e);if(process.platform!=="linux"||!n||n.platform!=="linux"||!Number.isSafeInteger(n.pid)||n.pid<1)return{...t,reason:"identity-unavailable"};let r=n.processGroupId===n.pid?n.processGroupId:void 0,s={...t,scope:r?"process-group":"leader-only"};try{if(Ne()!==n.bootId){let a=r?{id:r,status:"exited",observedAt:t.observedAt,memberCount:0,reason:"different-boot"}:void 0;return e.provenance==="child-event"?{...e,scope:s.scope,processGroup:a,observedAt:t.observedAt}:{...s,status:"identity-mismatch",provenance:"kernel",reason:"different-boot",processGroup:a}}if(_e()!==n.pidNamespace){let a=r?{id:r,status:"unknown",observedAt:t.observedAt,reason:"different-pid-namespace"}:void 0;return e.provenance==="child-event"?{...e,scope:s.scope,processGroup:a,observedAt:t.observedAt}:{...s,reason:"different-pid-namespace",processGroup:a}}}catch{let a=r?{id:r,status:"unknown",observedAt:t.observedAt,reason:"observation-unavailable"}:void 0;return e.provenance==="child-event"?{...e,scope:s.scope,processGroup:a,observedAt:t.observedAt}:{...s,reason:"observation-unavailable",processGroup:a}}let i=e.provenance==="child-event"?{...e,scope:s.scope,observedAt:t.observedAt}:s,o=!1;if(e.provenance!=="child-event")try{let a=xe(ce(`/proc/${n.pid}/stat`),n.pid);if(a.startTimeTicks!==n.startTimeTicks||n.sessionId!==void 0&&a.sessionId!==n.sessionId)i={...i,status:"identity-mismatch",provenance:"kernel",reason:"different-process"};else i={...i,status:/^[ZXx]$/.test(a.state)?"exited":"alive",provenance:"kernel",reason:void 0},o=!!r&&a.processGroupId===r&&!/^[ZXx]$/.test(a.state)}catch(a){if(a.code==="ENOENT"||a.code==="ESRCH")i={...i,status:"exited",provenance:"kernel",reason:"leader-absent"};else i={...i,reason:"observation-unavailable"}}if(!r)return i;return{...i,processGroup:Pt(r,n.sessionId,o)}}function Pt(e,t,n){let r=new Date().toISOString();if(n)return{id:e,status:"alive",observedAt:r};try{let s=Ot("/proc").filter((o)=>/^\d+$/.test(o));if(s.length>1e5)return{id:e,status:"unknown",observedAt:r,reason:"proc-entry-limit"};let i=0;for(let o of s){let a=Number(o);try{let c=xe(ce(`/proc/${a}/stat`),a);if(c.processGroupId===e&&(t===void 0||c.sessionId===t)&&!/^[ZXx]$/.test(c.state))i++}catch(c){let l=c.code;if(l!=="ENOENT"&&l!=="ESRCH")return{id:e,status:"unknown",observedAt:r,reason:"member-observation-unavailable"}}}return{id:e,status:i?"alive":"exited",observedAt:r,memberCount:i}}catch{return{id:e,status:"unknown",observedAt:r,reason:"proc-scan-unavailable"}}}function Ct(e){let t={status:"unknown",observedAt:new Date().toISOString(),provenance:"unavailable",scope:"leader-only",progress:"not-measured",reason:"identity-unavailable"};if(process.platform!=="linux"||!Number.isSafeInteger(e)||e<1)return t;try{let n=xe(ce(`/proc/${e}/stat`),e),r={platform:"linux",pid:e,bootId:Ne(),pidNamespace:_e(),startTimeTicks:n.startTimeTicks,sessionId:n.sessionId,processGroupId:n.processGroupId};return Oe({...t,scope:r.processGroupId===r.pid?"process-group":"leader-only",identity:r})}catch{return t}}function Le(){return Ct(process.pid)}import{StringDecoder as ir}from"string_decoder";import{createHash as re,randomUUID as Bt}from"crypto";import{homedir as Te,tmpdir as Ft}from"os";import{basename as Gt,dirname as je,join as k,resolve as Ut}from"path";import{chmod as He,lstat as ee,mkdir as We,opendir as jt,readdir as Ht,readFile as he,stat as Wt,unlink as Xe,writeFile as Xt}from"fs/promises";function Tt(e){let t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return/(?:apikey|authorization|cookie|credentials?|password|passwd|privatekey|secret)/.test(t)||/(?:access|auth|refresh|session)?token$/.test(t)}function It(e,t){let n="",r=0,s=0;while(s<e.length){let i=e[s]==='"'||e[s]==="'",o=i?s+1:s;if(!/[A-Za-z_]/.test(e[o]??"")||s>0&&/[A-Za-z0-9_.-]/.test(e[s-1])){s++;continue}let a=o+1;while(a<e.length&&/[A-Za-z0-9_.-]/.test(e[a]))a++;let c=i?e[s]:"";if(c&&e[a]!==c){s++;continue}let l=c?a+1:a;while(/\s/.test(e[l]??""))l++;if(e[l]!==":"&&e[l]!=="="){s=a;continue}l++;while(/\s/.test(e[l]??""))l++;if(!Tt(e.slice(o,a))){s=a;continue}let u=e[l]==='"'||e[l]==="'"?e[l]:"",d=l;if(u){d++;while(d<e.length){if(e[d]==="\\"){d+=2;continue}if(e[d]===u){d++;break}d++}}else while(d<e.length&&!/[\s,;}"']/.test(e[d]))d++;n+=e.slice(r,l),d=Math.min(d,e.length);let f=u&&d>l+1&&e[d-1]===u?u:"";n+=u+t(e.slice(l+(u?1:0),d-(f?1:0)))+f,r=d,s=d}return r?n+e.slice(r):e}function At(e,t){let n=e.replace(/(bearer\s+)[A-Za-z0-9._~+/-]+=*/gi,(r,s)=>s+t(r.slice(s.length))).replace(/-----BEGIN [^-\n]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-\n]*PRIVATE KEY-----|$)/g,(r)=>t(r,"[REDACTED PRIVATE KEY]")).replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[A-Z0-9]{16})\b/g,(r)=>t(r)).replace(/\b(sk-[A-Za-z0-9_-]{12,})\b/g,(r)=>t(r)).replace(/(:\/\/)[^/\s?#@:]*:[^/\s?#]*@/g,(r,s)=>s+t(r.slice(s.length,-1))+"@").replace(/((?:api[_-]?key|password|secret|token|credential)\s*[=:]\s*)[^\s,;"']+/gi,(r,s)=>s+t(r.slice(s.length)));return It(n,t)}function W(e){return At(e,(t)=>t.replace(/[^\r\n]/g,"*"))}import{createHash as _t,randomUUID as De}from"crypto";import{mkdir as Je,readFile as Be,rm as Nt,stat as le,writeFile as Lt}from"fs/promises";import{tmpdir as Mt}from"os";import{join as Q}from"path";import{chmod as Xr,readFile as zr,writeFile as Vr,readdir as qr,rename as Rt}from"fs/promises";var kt=new Set(["EPERM","EACCES","EBUSY"]);async function Me(e,t,{platform:n=process.platform,renameFile:r=Rt,attempts:s=10}={}){for(let i=1;;i++)try{return await r(e,t)}catch(o){let a=o.code??"";if(n!=="win32"||!kt.has(a)||i>=s)throw o;await new Promise((c)=>setTimeout(c,i*10))}}var $e=Q(Mt(),"deepseek-code-leases-v1");function Pe(e){return e.reason??Error("Lease acquisition cancelled")}async function Jt(e,t){if(t?.aborted)throw Pe(t);await new Promise((n,r)=>{let s=setTimeout(()=>{o(),n()},e),i=()=>{clearTimeout(s),o(),r(Pe(t))},o=()=>t?.removeEventListener("abort",i);t?.addEventListener("abort",i,{once:!0})})}function $t(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}async function ue(e,t){let n=`${e}.${t}-${De()}`;try{await Me(e,n)}catch(r){if(["ENOENT","EEXIST"].includes(r.code??""))return!1;throw r}return await Nt(n,{recursive:!0,force:!0}),!0}async function Dt(e){try{let t=JSON.parse(await Be(Q(e,"owner.json"),"utf8"));if(typeof t.pid==="number"&&$t(t.pid))return!1;return ue(e,"stale")}catch(t){let n=await le(e).catch(()=>{return});if(!n||Date.now()-n.mtimeMs<30000)return!1;return ue(e,t.code==="ENOENT"?"incomplete":"invalid")}}async function de(e,t={},n){if(n?.aborted)throw Pe(n);await Je($e,{recursive:!0,mode:448});let r=_t("sha256").update(e).digest("hex"),s=Q($e,r),i=De(),o={token:i,pid:process.pid,createdAt:new Date().toISOString(),resource:e,metadata:t};while(!0)try{await Je(s,{mode:448});try{await Lt(Q(s,"owner.json"),`${JSON.stringify(o)}
|
|
3
|
+
`,{encoding:"utf8",mode:384})}catch(u){throw await ue(s,"incomplete").catch(()=>!1),u}let a=!1,c,l=async()=>{if(a)return;let u;try{u=JSON.parse(await Be(Q(s,"owner.json"),"utf8"))}catch(d){if(d.code!=="ENOENT")throw d;try{await le(s)}catch(f){if(f.code!=="ENOENT")throw f;a=!0;return}throw d}if(u.token!==i){a=!0;return}try{if(await ue(s,"released")){a=!0;return}}catch(d){try{await le(s)}catch(f){if(f.code!=="ENOENT")throw f;a=!0;return}throw d}try{await le(s)}catch(d){if(d.code!=="ENOENT")throw d;a=!0;return}throw Error("Lease directory could not be moved aside")};return{token:i,path:s,release(){if(a)return Promise.resolve();if(c)return c;let u;return u=l().finally(()=>{if(c===u)c=void 0}),c=u,u}}}catch(a){if(a.code!=="EEXIST")throw a;if(await Dt(s))continue;await Jt(25,n)}}var Fe=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Ge(e,t){return Math.max(0,Math.min(e.length,Number.isNaN(t)?0:Math.trunc(t)))}function D(e,t){let n=Ge(e,t);if(n===0||n===e.length)return n;let r=0;for(let s of Fe.segment(e)){let i=s.index+s.segment.length;if(i>n)return s.index;r=i}return r}function V(e,t){let n=Ge(e,t);if(n===0||n===e.length)return n;for(let r of Fe.segment(e)){let s=r.index+r.segment.length;if(r.index>=n)return r.index;if(s>n)return s}return e.length}var ze=2000000,q=20971520,te=10,zt=16777216,Vt=33554432,qt=256;var Yt=60000,ge=ze,Se=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,B=new Map;function ne(e,t){let n=re("sha256").update(e).digest("hex");return k(t??process.env.HOME??Te(),".deepseek-code","shell-output",n)}function Ve(e,t,n){let r=re("sha256").update(e).digest("hex"),s=n??(t?k(je(t),`${Gt(t)||"shell-output"}-recovery`):k(process.env.HOME??Te(),".deepseek","shell-output-recovery"));return k(s,r)}function Zt(e){let t=typeof process.getuid==="function"?String(process.getuid()):re("sha256").update(Te()).digest("hex").slice(0,16);return e??k(Ft(),`deepseek-code-shell-output-${t}`)}function qe(e,t){let n=re("sha256").update(e).digest("hex");return k(Zt(t),n)}async function Ye(e){try{let t=await ee(e);if(!t.isDirectory()||t.isSymbolicLink()||typeof process.getuid==="function"&&t.uid!==process.getuid())return;let n=k(e,"supervisors"),r=await ee(n).catch((c)=>{if(c.code==="ENOENT")return;throw c});if(!r)return new Set;if(!r.isDirectory()||r.isSymbolicLink()||typeof process.getuid==="function"&&r.uid!==process.getuid())return;let s=new Set,i=0,o=0,a=await jt(n);for await(let c of a){if(!/^[a-f0-9]{64}\.json$/i.test(c.name))continue;if(++o>qt)return;let l=k(n,c.name),u=await ee(l);if(!u.isFile()||u.isSymbolicLink()||typeof process.getuid==="function"&&u.uid!==process.getuid()||u.size>zt)return;if(i+=u.size,i>Vt)return;let d=JSON.parse(await he(l,"utf8"));if(d.schema!=="shell_supervisor_v1")return;for(let f of[d.outputId,d.reservedOutputId]){if(f===void 0)continue;if(typeof f!=="string"||!Se.test(f))return;s.add(f)}}return s}catch(t){if(["ENOENT","ENOTDIR"].includes(t.code??""))return new Set;return}}async function Kt(e,t,n){let s=(await Promise.all((await Ht(e)).filter((c)=>Se.test(c)).map(async(c)=>({id:c,path:k(e,c),info:await Wt(k(e,c)).catch(()=>null)})))).filter((c)=>c.info!==null).sort((c,l)=>c.info.mtimeMs-l.info.mtimeMs),i=s.reduce((c,l)=>c+l.info.size,0),o=s.length,a=[];for(let c of s){if(o<=te&&i<=q)break;if(c.id===t||n===void 0||n.has(c.id))continue;try{await Xe(c.path)}catch(l){if(l.code!=="ENOENT"){a.push(l);continue}}o--,i-=c.info.size}if(a.length>0){let c=Error(`Failed to remove ${a.length} shell output artifact(s) during cleanup`);throw Object.assign(c,{code:a[0]?.code}),c}return o<=te&&i<=q}async function me(e,t,n,r){try{await Qt(e,t,n)}catch(s){return{stored:!1,error:s}}try{if(await Kt(e,t,r))return{stored:!0};try{await Xe(k(e,t))}catch(s){if(s.code!=="ENOENT")return{stored:!0,cleanupWarning:`retention cleanup ${s.code??"failed"}`}}return{stored:!1,error:Object.assign(Error("Shell output retention quota is occupied by referenced artifacts"),{code:"ENOSPC"})}}catch(s){return{stored:!0,cleanupWarning:`cleanup ${s.code??"failed"}`}}}function Ce(e,t){return`${e}\x00${t}`}function ye(e){return re("sha256").update(JSON.stringify({totalChars:e.totalChars,storedChars:e.storedChars,truncated:e.truncated,redacted:e.redacted===!0,content:e.content,provenance:e.provenance??null})).digest("hex")}function fe(e){try{let t=JSON.parse(e);if(typeof t.content!=="string")return!1;if(t.contentHash===void 0)return t.schemaVersion!==2;if(!Number.isSafeInteger(t.totalChars)||!Number.isSafeInteger(t.storedChars)||typeof t.truncated!=="boolean")return!1;return t.contentHash===ye(t)}catch{return!1}}async function Ue(e,t,n,r,s,i){let o=JSON.stringify({...n,schemaVersion:2,storage:"memory",contentHash:ye({...n,content:r,provenance:s}),content:r,...s?{provenance:s}:{}}),a=Buffer.byteLength(o,"utf8");if(a>q)return!1;let c=Ce(e,t),l=new Map([[e,i]]);for(let m of B.values())if(!l.has(m.directory))l.set(m.directory,await Ye(m.directory));let u=[...B.values()].filter((m)=>{let p=l.get(m.directory);return p===void 0||p.has(m.id)});if(u.length+1>te||u.reduce((m,p)=>m+p.bytes,a)>q)return!1;B.set(c,{directory:e,id:t,raw:o,bytes:a,createdAt:Date.now()});let d=[...B.entries()].sort((m,p)=>m[1].createdAt-p[1].createdAt),f=d.reduce((m,[,p])=>m+p.bytes,0),b=d.length;for(let[m,p]of d){if(b<=te&&f<=q)break;let y=l.get(p.directory);if(m===c||y===void 0||y.has(p.id))continue;B.delete(m),b--,f-=p.bytes}if(b>te||f>q)B.delete(c);return B.has(c)}async function Qt(e,t,n){if(await We(e,{recursive:!0,mode:448}),!(await ee(e)).isDirectory())throw Error("shell output storage path is not a directory");await He(e,448),await Xt(k(e,t),n,{encoding:"utf8",mode:384,flag:"wx"})}async function er(e){await We(e,{mode:448}).catch((n)=>{if(n.code!=="EEXIST")throw n});let t=await ee(e);if(!t.isDirectory()||t.isSymbolicLink()||typeof process.getuid==="function"&&t.uid!==process.getuid())throw Error("Shell emergency output root is not an owned directory");await He(e,448)}async function pe(e,t,n,r,s,i,o){let a=ye({...n,content:r,provenance:s}),c=JSON.stringify({...n,schemaVersion:2,storage:"emergency-disk",contentHash:a,retentionWarning:i,content:r,...s?{provenance:s}:{}});try{await er(je(e))}catch(u){return{retained:!1,warning:`${i}; emergency storage failed (${u.code??"failed"})`}}let l=await me(e,t,c,o);if(!l.stored)return{retained:!1,warning:`${i}; emergency storage failed (${l.error?.code??"failed"})`};if(l.cleanupWarning)i+=`; emergency ${l.cleanupWarning}`;return{retained:!0,warning:i}}async function tr(e,t,n,r){let s=B.get(Ce(e,r));if(s){if(fe(s.raw))return s.raw;B.delete(Ce(e,r))}let i;try{let o=await he(k(e,r),"utf8");if(fe(o))return o;i=Error("Shell output artifact integrity check failed")}catch(o){i=o}try{let o=await he(k(t,r),"utf8");if(fe(o))return o;throw Error("Shell output artifact integrity check failed")}catch{}try{let o=await he(k(n,r),"utf8");if(fe(o))return o;throw Error("Shell output artifact integrity check failed")}catch{throw i}}async function Ze(e,t,n){let r=ne(e,t),s=new AbortController,i=setTimeout(()=>s.abort(Error("Timed out waiting for the shell output artifact lease")),Yt),o;try{if(o=await de(`shell-output-artifacts:${Ut(r)}`,{},s.signal),s.signal.aborted)throw await o.release(),s.signal.reason}finally{clearTimeout(i)}try{return await n((a,c,l,u,d,f)=>rr(e,a,c,t,l,u,d,f))}finally{await o.release()}}async function rr(e,t,n=t.length,r,s,i,o,a=Bt()){if(!Se.test(a))throw Error("Invalid shell output ID");let c=ne(e,r),l=Ve(e,r,i),u=qe(e,o),d=await Ye(c),f=a,b=W(t),m=D(b,ze),p={totalChars:n,storedChars:m,truncated:m<n,redacted:b!==t},y=b.slice(0,m),v=ye({...p,content:y,provenance:s}),I=JSON.stringify({...p,schemaVersion:2,storage:"disk",contentHash:v,content:y,...s?{provenance:s}:{}}),A=await me(c,f,I,d);if(!A.stored){let R=A.error,O=`primary storage failed (${R?.code??"failed"})`;if(l!==c){let H=JSON.stringify({...p,schemaVersion:2,storage:"recovery-disk",contentHash:v,retentionWarning:O,content:y,...s?{provenance:s}:{}}),C=await me(l,f,H,d);if(C.stored){let L=O;if(C.cleanupWarning)L+=`; recovery ${C.cleanupWarning}`;if(u!==c&&u!==l){let J=await pe(u,f,p,y,s,`${O}; emergency mirror`,d);L+=J.retained?"; emergency copy retained":`; ${J.warning}`}return{id:f,metadata:{...p,storage:"recovery-disk",retentionWarning:L}}}let F=`recovery storage failed (${C.error?.code??"failed"})`;if(u!==c&&u!==l){let L=await pe(u,f,p,y,s,`${O}; ${F}`,d);if(L.retained)return{id:f,metadata:{...p,storage:"emergency-disk",retentionWarning:L.warning}};let J={...p,storage:"memory",retentionWarning:L.warning};if(await Ue(c,f,p,y,s,d))return{id:f,metadata:J};throw R}}let N=u!==c&&u!==l?await pe(u,f,p,y,s,O,d):null;if(N?.retained)return{id:f,metadata:{...p,storage:"emergency-disk",retentionWarning:N.warning}};let M={...p,storage:"memory",retentionWarning:N?.warning??O};if(await Ue(c,f,p,y,s,d))return{id:f,metadata:M};throw R}let w;if(l!==c){let R=JSON.stringify({...p,schemaVersion:2,storage:"recovery-disk",contentHash:v,content:y,...s?{provenance:s}:{}}),O=await me(l,f,R,d);if(O.stored){if(O.cleanupWarning)w=`recovery ${O.cleanupWarning}`}else{let N=`recovery copy failed (${O.error?.code??"failed"})`;if(u!==c&&u!==l){let M=await pe(u,f,p,y,s,N,d);w=M.retained?`${N}; emergency copy retained`:M.warning}else w=N}}if(A.cleanupWarning)w=[w,`primary ${A.cleanupWarning}`].filter(Boolean).join("; ");return{id:f,metadata:{...p,storage:"disk",...w?{retentionWarning:w}:{}}}}async function Ke(e,t,n,r,s){if(!Se.test(t))throw Error("Invalid shell output ID");let i=await tr(ne(e,n),Ve(e,n,r),qe(e,s),t),o=JSON.parse(i);if(typeof o.content!=="string"||!Number.isSafeInteger(o.totalChars)||!Number.isSafeInteger(o.storedChars)||typeof o.truncated!=="boolean"||!["disk","recovery-disk","emergency-disk","memory"].includes(o.storage??""))throw Error("Shell output artifact is malformed");let a={totalChars:o.totalChars,storedChars:o.storedChars,truncated:o.truncated,redacted:o.redacted===!0,storage:o.storage,...typeof o.retentionWarning==="string"?{retentionWarning:o.retentionWarning}:{}};return{content:W(o.content),metadata:a,...o.provenance?{provenance:o.provenance}:{}}}import{execFileSync as nr}from"child_process";function sr(e,t){if(process.platform==="win32"||!Number.isSafeInteger(e)||e<2)return!1;try{return process.kill(-e,t),!0}catch(n){if(["ESRCH","EPERM"].includes(n.code??""))return!1;throw n}}function Qe(e,t){if(e.pid&&process.platform!=="win32"){if(sr(e.pid,t))return!0;return e.kill(t)}else if(e.pid&&process.platform==="win32")try{return nr("taskkill",["/PID",String(e.pid),"/T","/F"],{stdio:"ignore",timeout:5000}),!0}catch(n){return e.kill(t)}return e.kill(t)}class tt{state="text";push(e,t=!1){let n="";for(let r of e){let s=r.codePointAt(0);switch(this.state){case"text":if(s===27)this.state="escape";else if(s===155)this.state="csi";else if(s===157)this.state="osc";else if(s===144||s===152||s===158||s===159)this.state="string";else n+=r;break;case"escape":if(r==="[")this.state="csi";else if(r==="]")this.state="osc";else if(r==="P"||r==="X"||r==="^"||r==="_")this.state="string";else this.state="text";break;case"csi":if(s>=64&&s<=126)this.state="text";break;case"osc":if(s===7)this.state="text";else if(s===156)this.state="text";else if(s===27)this.state="oscEscape";break;case"oscEscape":this.state=r==="\\"?"text":r==="\x1B"?"oscEscape":"osc";break;case"string":if(s===156)this.state="text";else if(s===27)this.state="stringEscape";break;case"stringEscape":this.state=r==="\\"?"text":r==="\x1B"?"stringEscape":"string";break}}if(t&&this.state!=="text")this.state="text";return n}}var or=4096,se=8000,ve=8000,ar=/\b(?:error(?:\b|_[A-Z0-9_]+)|fatal|exception|traceback|fail(?:ed|ure)?|panic(?:ked)?|module not found|no module named|modulenotfounderror|cannot find symbol|unresolved (?:reference|import)|undefined reference|caused by)\b|\b[A-Za-z][A-Za-z0-9_.]*(?:Error|Exception)\b|\bundefined:|\b(?:command not found|no such file or directory)\b|\bTS\d{4,5}\b|\bERR_[A-Z0-9_]+\b|\b(?:npm|pnpm|yarn)\s+ERR!|^\s*(?:make(?:\[\d+\])?:\s+\*\*\*|ninja:\s+build stopped)/i;function et(){return{schema:"shell_channel_provenance_v1",ordering:"observed-arrival",stdoutChars:0,stderrChars:0,retainedChars:0,segments:[],segmentsOmitted:0,contentOmitted:0,drainTimedOut:!1}}class rt{full="";head="";middle="";tail="";total=0;append(e){if(!e)return;if(this.full!==null&&this.total+e.length<=se*3){this.full+=e,this.total+=e.length;return}if(this.full!==null){let t=this.full;this.full=null,this.total=0,this.appendSample(t)}this.appendSample(e)}appendSample(e){if(!e)return;if(this.head.length<se)this.head+=e.slice(0,D(e,se-this.head.length));if(!this.middle&&this.total+e.length>1e6){let n=Math.max(0,1e6-this.total);this.middle=e.slice(V(e,n),D(e,n+se))}let t=this.tail+e;this.tail=t.slice(V(t,t.length-se)),this.total+=e.length}render(){if(this.full!==null)return this.full;let e=Math.max(0,this.total-this.head.length-this.middle.length-this.tail.length);return`${this.head}
|
|
4
|
+
\u2026[${e} characters omitted from this stream preview]\u2026${this.middle?`
|
|
6
5
|
${this.middle}
|
|
7
6
|
\u2026[continued at final stream output]\u2026`:""}
|
|
8
|
-
${this.tail}`}}class
|
|
7
|
+
${this.tail}`}}class Ie{sampler=new rt;previousLine="";diagnosticLines;diagnosticFollow=0;current="";head="";tail="";currentLength=0;currentOverflow=!1;hasCurrent=!1;pendingCR=!1;push(e){let t=0;while(t<e.length){if(this.pendingCR){if(this.pendingCR=!1,e[t]===`
|
|
9
8
|
`){this.commit(`
|
|
10
|
-
`),
|
|
11
|
-
`,
|
|
12
|
-
`);
|
|
13
|
-
`);return
|
|
9
|
+
`),t++;continue}this.resetLine()}let n=e.indexOf("\r",t),r=e.indexOf(`
|
|
10
|
+
`,t),s=n<0?r:r<0?n:Math.min(n,r);if(s<0){this.appendLine(e.slice(t));return}if(s>t)this.appendLine(e.slice(t,s));if(e[s]==="\r")this.pendingCR=!0;else this.commit(`
|
|
11
|
+
`);t=s+1}}finish(){if(this.hasCurrent)this.commit("");this.pendingCR=!1}render(){let e=this.sampler.render();if(!this.diagnosticLines?.length)return e;let t=this.diagnosticLines.join(`
|
|
12
|
+
`);return e.includes(t)?e:`${e}
|
|
14
13
|
[diagnostic excerpt (heuristic)]
|
|
15
|
-
${
|
|
16
|
-
`:""}${
|
|
17
|
-
`);return
|
|
14
|
+
${t}`}renderLive(){let e=this.sampler.render(),t=this.hasCurrent?this.lineText():"",n=t?`${e}${e?`
|
|
15
|
+
`:""}${t}`:e;if(!this.diagnosticLines?.length)return n;let r=this.diagnosticLines.join(`
|
|
16
|
+
`);return n.includes(r)?n:`${n}
|
|
18
17
|
[diagnostic excerpt (heuristic)]
|
|
19
|
-
${
|
|
20
|
-
[preview omitted after an oversized grapheme cluster]`:""}`,
|
|
21
|
-
[preview omitted after an oversized grapheme cluster]`:""}`;return{preview:
|
|
22
|
-
${
|
|
18
|
+
${r}`}appendLine(e){if(!e)return;if(this.hasCurrent=!0,this.currentLength+=e.length,!this.currentOverflow&&this.current.length+e.length<=ve){this.current+=e;return}if(!this.currentOverflow){let r=ve/2;this.head=this.current.slice(0,D(this.current,r)),this.tail=this.current.slice(V(this.current,this.current.length-r)),this.current="",this.currentOverflow=!0}let t=this.tail+e,n=Math.max(0,t.length-ve/2);this.tail=t.slice(V(t,n))}commit(e){let t=this.hasCurrent?this.lineText():"";if(this.hasCurrent||e)this.sampler.append(`${t}${e}`);if(this.diagnosticLines&&this.diagnosticFollow>0){if(t)this.diagnosticLines.push(t);this.diagnosticFollow--}else if(ar.test(t))this.diagnosticLines=[...this.previousLine?[this.previousLine]:[],t],this.diagnosticFollow=1;if(t)this.previousLine=t;this.resetLine()}lineText(){if(!this.currentOverflow)return this.current;let e=Math.max(0,this.currentLength-this.head.length-this.tail.length);return`${this.head}\u2026[${e} characters omitted from progress line]\u2026${this.tail}`}resetLine(){this.current="",this.head="",this.tail="",this.currentLength=0,this.currentOverflow=!1,this.hasCurrent=!1}}function nt(e,t,n){return new Promise((r,s)=>{let i=!1,o=!1,a=!1,c,l=(p)=>Qe(e,p),u=()=>{if(clearTimeout(m),c)clearTimeout(c);n?.removeEventListener("abort",b)},d=(p)=>{if(i)return;i=!0,u(),s(p)},f=(p)=>{if(a||i)return;o=p,a=!0,l("SIGTERM"),c=setTimeout(()=>l("SIGKILL"),1000)},b=()=>f(!1),m=setTimeout(()=>f(!0),t);if(n?.addEventListener("abort",b,{once:!0}),n?.aborted)b();e.once("spawn",()=>{if(a)l("SIGTERM")}),e.once("error",(p)=>d(p)),e.once("close",(p,y)=>{if(i)return;if(i=!0,u(),o)return s(Object.assign(Error(`Command timed out after ${Math.round(t/1000)}s and was killed.`),{timedOut:!0,signal:y}));if(n?.aborted)return s(Object.assign(Error("Command was cancelled."),{cancelled:!0,signal:y}));if(p!==0)return s(Object.assign(Error(`Command exited with code ${p??"unknown"}.`),{exitCode:p??void 0,signal:y}));r({exitCode:0,signal:y})})})}async function st(e,t,n,r,s,i){let o=[{channel:"stdout",stream:e},{channel:"stderr",stream:t}].filter((h)=>Boolean(h.stream));if(!o.length)return{content:"",preview:"",totalChars:0,totalBytes:0,truncated:!1,drainTimedOut:!1,provenance:et()};let a=[],c={stdout:new Ie,stderr:new Ie},l={stdout:"",stderr:""},u={stdout:!1,stderr:!1},d=[],f=0,b=0,m=0,p=0,y=!1,v=[],I=0,A=0,w=et(),R=()=>{let h=`${c.stdout.renderLive()}${u.stdout?`
|
|
19
|
+
[preview omitted after an oversized grapheme cluster]`:""}`,g=`${c.stderr.renderLive()}${u.stderr?`
|
|
20
|
+
[preview omitted after an oversized grapheme cluster]`:""}`;return{preview:h&&g?`[stdout channel preview]
|
|
21
|
+
${h}${h.endsWith(`
|
|
23
22
|
`)?`
|
|
24
23
|
`:`
|
|
25
24
|
|
|
26
25
|
`}[stderr channel preview]
|
|
27
|
-
${
|
|
28
|
-
\u2026[${
|
|
29
|
-
${this.previewTail}`:this.previewHead||this.previewTail}push(
|
|
30
|
-
`,V=Buffer.byteLength(K,"utf8");if(!this.available||this.writerError||!this.accepting||this.committedBytes+this.queuedBytes+this.inFlightBytes+V>(this.options.maxBytes??J0)||this.queuedBytes+V>(this.options.maxQueueBytes??L3)){this.droppedRecords++,this.truncated=!0,this.accepting=!1,this.gapUnknown=!0,this.settleDroppedTail();return}else this.queue.push({value:K,bytes:V}),this.queuedBytes+=V,this.startWriter();Q=z}}startWriter(){if(this.writing||!this.queue.length||!this.file||!this.available)return this.writerPromise??Promise.resolve();return this.writing=!0,this.writerPromise=(async()=>{try{while(this.queue.length){let $=this.queue.shift();this.queuedBytes-=$.bytes,this.inFlightBytes=$.bytes;try{await this.writeRecord(this.file,$.value),this.committedBytes+=$.bytes,this.inFlightBytes=0,this.settledSequence=O3($.value)}catch{this.inFlightBytes=0,this.writerError=!0,this.accepting=!1,this.truncated=!0,this.gapUnknown=!0,this.droppedRecords+=1+this.queue.length,this.queue.length=0,this.queuedBytes=0,this.settleDroppedTail();break}}}finally{this.writing=!1,this.settleDroppedTail()}})(),this.writerPromise}settleDroppedTail(){if(!this.writing&&this.queue.length===0&&(!this.accepting||!this.available||this.writerError))this.settledSequence=this.sequence}writerPromise}function O3($){try{return JSON.parse($).sequence}catch{return 0}}var A0="shell_supervisor_v1",h3=131072,v3=16777216,y3=65536;var m3=500,p3=20971520,u3=10;function L2($){return _3("sha256").update($).digest("hex")}function k0($){let Z=z0($.sessionId,$.storageRoot),Q=n(Z,"supervisors"),z=L2($.taskId);return{outputDirectory:Z,directory:Q,state:n(Q,`${z}.json`),lock:n(Q,`${z}.lock`),journal:n(Q,`${z}.stream.jsonl`)}}function M2($){let Z=Array.isArray($.args)?$.args.reduce((Q,z)=>Q+Buffer.byteLength(z,"utf8"),0):1/0;if(!$.sessionId||$.sessionId.length>256||!$.taskId||$.taskId.length>256||!/^[a-f0-9]{64}$/.test($.fingerprint)||!$.executable||$.executable.includes("/")&&!$.executable.startsWith("/")||!Array.isArray($.args)||$.args.some((Q)=>typeof Q!=="string")||Z>y3||!$.cwd.startsWith("/")||!Number.isSafeInteger($.timeoutMs)||$.timeoutMs<1||$.timeoutMs>86400000)throw Error("Invalid shell supervisor request")}async function C0($){await E3($,{recursive:!0,mode:448});let Z=await B2($);if(!Z.isDirectory()||Z.isSymbolicLink()||typeof process.getuid==="function"&&Z.uid!==process.getuid())throw Error("Shell supervisor state directory is not privately owned");await q3($,448)}async function l3($,Z){let{directory:Q,state:z,journal:J}=k0($),K;try{K=await W0(`shell-stream-journal-retention:${f3(Q)}`);let V=await A3(Q,{withFileTypes:!0}),Y=[];for(let D of V){if(!/^[a-f0-9]{64}\.stream\.jsonl$/i.test(D.name))continue;let q=n(Q,D.name),E=await B2(q);if(!E.isFile()||E.isSymbolicLink()||typeof process.getuid==="function"&&E.uid!==process.getuid())return;let w=n(Q,D.name.replace(/\.stream\.jsonl$/,".json")),C=!1;try{let O=JSON.parse(F2(w,"utf8"));if(O.state==="running")if(!D2(O.identity))C=!0;else C=o3(O0(d3(O.identity)),O.identity)}catch{C=!0}Y.push({name:D.name,path:q,bytes:E.size,modifiedAt:E.mtimeMs,active:C})}let U=`${L2($.taskId)}.stream.jsonl`,H=Y.find((D)=>D.name===U);if(H?.active)return;if(H)await N2(H.path).catch(()=>{}),Y.splice(Y.indexOf(H),1);let X=Y.filter((D)=>D.active).length,W=Y.filter((D)=>!D.active).sort((D,q)=>D.modifiedAt-q.modifiedAt),G=W.reduce((D,q)=>D+q.bytes,0),k=W.length;while(X+k+1>u3||X*J0+G+J0>p3){let D=W.shift();if(!D)return;await N2(D.path).catch(()=>{}),G-=D.bytes,k--}await(await C3(J,"wx",384)).close();let N=new w0(J);await N.open();let M=N.stats();return await a(z,{...Z,streamAvailable:M.available,...!M.available?{streamUnavailableReason:"storage-unavailable"}:{},streamLatestSequence:0,streamDroppedRecords:0,streamTruncated:!1,streamRedactionConservative:!1,streamGapUnknown:!M.available}),M.available?N:void 0}catch{await a(z,{...Z,streamAvailable:!1,streamUnavailableReason:"storage-unavailable",streamLatestSequence:0,streamDroppedRecords:0,streamTruncated:!0,streamRedactionConservative:!1,streamGapUnknown:!0}).catch(()=>{});return}finally{await K?.release().catch(()=>{})}}async function a($,Z){let Q=`${$}.${process.pid}.${Date.now()}.tmp`;await x3(Q,JSON.stringify(Z),{encoding:"utf8",mode:384,flag:"wx"}),await I3(Q,$)}function j2($){let{state:Z}=k0($);try{let Q=S3(Z);if(!Q.isFile()||Q.isSymbolicLink()||Q.size>v3||typeof process.getuid==="function"&&Q.uid!==process.getuid())return;let z=JSON.parse(F2(Z,"utf8"));if(z.schema!==A0||z.sessionId!==$.sessionId||z.taskId!==$.taskId||z.fingerprint!==$.fingerprint||!["running","done","failed","cancelled","timed_out"].includes(z.state??"")||!D2(z.identity)||!["settled","unknown"].includes(z.processGroupSettled??"")||z.outputPreview!==void 0&&(typeof z.outputPreview!=="string"||z.outputPreview.length>1e5)||z.totalChars!==void 0&&(!Number.isSafeInteger(z.totalChars)||z.totalChars<0)||z.outputBytes!==void 0&&(!Number.isSafeInteger(z.outputBytes)||z.outputBytes<0)||z.outputTruncated!==void 0&&typeof z.outputTruncated!=="boolean"||z.streamAvailable!==void 0&&typeof z.streamAvailable!=="boolean"||z.streamLatestSequence!==void 0&&(!Number.isSafeInteger(z.streamLatestSequence)||z.streamLatestSequence<0)||z.streamDroppedRecords!==void 0&&(!Number.isSafeInteger(z.streamDroppedRecords)||z.streamDroppedRecords<0)||z.streamTruncated!==void 0&&typeof z.streamTruncated!=="boolean"||z.streamRedactionConservative!==void 0&&typeof z.streamRedactionConservative!=="boolean"||z.streamGapUnknown!==void 0&&typeof z.streamGapUnknown!=="boolean")return;if(z.memoryContent!==void 0&&(typeof z.memoryContent!=="string"||z.memoryContent.length>2000000))return;return z}catch{return}}function D2($){let Z=$;return!!Z&&Z.platform==="linux"&&Number.isSafeInteger(Z.pid)&&Z.pid>1&&typeof Z.bootId==="string"&&typeof Z.pidNamespace==="string"&&typeof Z.startTimeTicks==="string"&&Number.isSafeInteger(Z.sessionId)&&Number.isSafeInteger(Z.processGroupId)&&Z.sessionId>0&&Z.processGroupId===Z.pid}function c3($,Z){return $.pid===Z.pid&&$.bootId===Z.bootId&&$.pidNamespace===Z.pidNamespace&&$.startTimeTicks===Z.startTimeTicks&&$.sessionId===Z.sessionId&&$.processGroupId===Z.processGroupId}function d3($){return{identity:$,status:"alive",observedAt:new Date().toISOString(),provenance:"kernel",scope:"process-group",progress:"not-measured"}}function o3($,Z){return!!$.identity&&c3($.identity,Z)&&$.scope==="process-group"&&$.status==="alive"&&$.processGroup?.status==="alive"}async function w2($){M2($);let Z=S0();if(!Z.identity||Z.scope!=="process-group")throw Error("Shell supervisor could not capture its Linux process-group identity");let Q=Z.identity,{outputDirectory:z,directory:J,state:K}=k0($);await C0(g3(z)),await C0(z),await C0(J);let V=new Date().toISOString(),Y={schema:A0,sessionId:$.sessionId,taskId:$.taskId,fingerprint:$.fingerprint,state:"running",identity:Q,startedAt:V,processGroupSettled:"unknown"},U=await l3($,Y),H=j2($);if(!H||H.streamAvailable===void 0)await a(K,{...Y,streamAvailable:!1,streamUnavailableReason:"retention-capacity",streamLatestSequence:0,streamDroppedRecords:0,streamTruncated:!0,streamRedactionConservative:!1,streamGapUnknown:!0});if(!U)U=new w0(k0($).journal),U.disable();let X=j2($)??{...Y,streamAvailable:!1,streamTruncated:!0},W=()=>{let L=U?.stats();return{streamAvailable:L?.available??X.streamAvailable??!1,...!L?.available&&X.streamUnavailableReason?{streamUnavailableReason:X.streamUnavailableReason}:{},streamLatestSequence:L?.latestSequence??X.streamLatestSequence??0,streamDroppedRecords:L?.droppedRecords??X.streamDroppedRecords??0,streamTruncated:L?.truncated??X.streamTruncated??!0,streamRedactionConservative:L?.redactionConservative??X.streamRedactionConservative??!1,streamGapUnknown:L?.gapUnknown??X.streamGapUnknown??!1}},G=new AbortController,k=()=>{if(!G.signal.aborted)G.abort(Error("Shell supervisor was asked to stop"))};process.on("SIGTERM",k);let B=R3($.executable,$.args,{cwd:$.cwd,env:H2(),detached:!0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),N=new Promise((L)=>{B.once("exit",()=>L()),B.once("error",()=>L())}),M,D=0,q=0,E=Promise.resolve(),w=()=>{let L=M;if(!L||L.totalChars===D&&L.totalBytes===q)return;D=L.totalChars,q=L.totalBytes,E=E.then(async()=>{await U?.flush(200);let p={...X,totalChars:L.totalChars,outputBytes:L.totalBytes,outputPreview:U.preview(),outputTruncated:L.truncated,...W()};await a(K,p)}).catch(()=>{})},C=setInterval(w,m3);C.unref?.();let O=Y2(B.stdout,B.stderr,N,(L)=>{M=L},(L)=>U?.push(L)),[x,g]=await Promise.allSettled([O,V2(B,$.timeoutMs,G.signal)]);clearInterval(C),w(),await E,await U?.finish(1000);let l=W(),b=x.status==="fulfilled"?x.value:{content:"",preview:"",totalChars:0,totalBytes:0,truncated:!1,drainTimedOut:!0,provenance:{schema:"shell_channel_provenance_v1",ordering:"observed-arrival",stdoutChars:0,stderrChars:0,retainedChars:0,segments:[],segmentsOmitted:0,contentOmitted:0,drainTimedOut:!0}},y="done",S=0,f=null,m=!1,d=!1;if(g.status==="rejected"){let L=g.reason;S=typeof L.exitCode==="number"?L.exitCode:B.exitCode,f=L.signal??B.signalCode,m=L.timedOut===!0,d=L.cancelled===!0||G.signal.aborted,y=m?"timed_out":d?"cancelled":"failed"}if(x.status==="rejected"&&y==="done")y="failed";let o=(B.exitCode!==null||B.signalCode!==null)&&!b.drainTimedOut?"settled":"unknown",K0=b3();await $2($.sessionId,$.storageRoot,async(L)=>{await a(K,{...X,processGroupSettled:o,reservedOutputId:K0,outputPreview:U.preview(),totalChars:b.totalChars,outputBytes:b.totalBytes,outputTruncated:b.truncated,...l});let p=await L(b.content,b.totalChars,b.provenance,$.recoveryRoot,void 0,K0),V0=p.metadata.storage==="memory"?(await Z2($.sessionId,p.id,$.storageRoot,$.recoveryRoot)).content:void 0,j={schema:A0,sessionId:$.sessionId,taskId:$.taskId,fingerprint:$.fingerprint,state:y,identity:Q,startedAt:V,finishedAt:new Date().toISOString(),exitCode:S,signal:f,timedOut:m,cancelled:d,processGroupSettled:o,outputId:p.id,outputMetadata:p.metadata,outputPreview:U.preview(),totalChars:b.totalChars,outputBytes:b.totalBytes,outputTruncated:b.truncated,drainTimedOut:b.drainTimedOut,provenance:b.provenance,...l,...V0!==void 0?{memoryContent:V0}:{}};await a(K,j)}),process.off("SIGTERM",k)}async function k2($){let Z=[],Q=0;for await(let J of $){let K=Buffer.from(J);if(Q+=K.length,Q>h3)throw Error("Shell supervisor configuration exceeds its limit");Z.push(K)}let z=JSON.parse(Buffer.concat(Z).toString("utf8"));return M2(z),z}if(import.meta.main)try{let $=await k2(process.stdin);await w2($),process.exit(0)}catch($){process.stderr.write(`Shell supervisor failed: ${$ instanceof Error?$.message:String($)}
|
|
26
|
+
${g}`:h||g,totalChars:m,totalBytes:p,truncated:m>b+(y?0:I)}},O=(h,g,E,x)=>{if(!x)return;let P=w.segments[w.segments.length-1];if(P&&P.channel===h&&P.offset+P.length===g&&P.channelOffset+P.length===E){P.length+=x,w.retainedChars+=x;return}if(w.segments.length>=or){w.segmentsOmitted++;return}w.segments.push({sequence:w.segments.length+1,channel:h,offset:g,channelOffset:E,length:x}),w.retainedChars+=x},N=()=>{if(!f)return;a.push(d.join("")),d=[],f=0},M=(h,g)=>{if(u[g])return;let E=l[g]+h,x=E.length?D(E,E.length-1):0;if(x)c[g].push(E.slice(0,x));if(l[g]=E.slice(x),l[g].length>ve)l[g]="",u[g]=!0},H=(h)=>{for(let g of h)if(O(g.channel,g.globalOffset,g.channelOffset,g.text.length),d.push(g.text),f+=g.text.length,b+=g.text.length,f>=65536)N()},C=(h,g)=>{let E=[],x=[],P=g;for(let T of h)if(P>=T.text.length)E.push(T),P-=T.text.length;else if(P>0)E.push({...T,text:T.text.slice(0,P)}),x.push({...T,text:T.text.slice(P),globalOffset:T.globalOffset+P,channelOffset:T.channelOffset+P}),P=0;else x.push(T);return[E,x]},F=(h)=>{if(y)return;let g=[...v,h],E=g.map((Ee)=>Ee.text).join(""),x=E.length?D(E,E.length-1):0,P=ge-b,T=D(E,Math.min(x,P)),[j,K]=C(g,T);if(H(j),v=K,I=K.reduce((Ee,vt)=>Ee+vt.text.length,0),T<x||b+I>ge)y=!0,v=[],I=0},L=(h,g)=>{if(!h)return;M(h,g);let E=w[`${g}Chars`],x=m;m+=h.length,w[`${g}Chars`]+=h.length,F({text:h,channel:g,globalOffset:x,channelOffset:E});try{s?.({text:h,channel:g,globalOffset:x,channelOffset:E})}catch{}if(r&&Date.now()-A>=200)A=Date.now(),r(R())},J=o.map(async({stream:h,channel:g})=>{let E=new ir("utf8"),x=new tt;h.on("data",(T)=>{let j=Buffer.isBuffer(T)?T:Buffer.from(T);p+=j.length;try{i?.(j.length)}catch{}L(x.push(E.write(j)),g)}),h.on("end",()=>L(x.push(E.end(),!0),g));let P=new Promise((T,j)=>{let K=()=>{h.removeListener("error",j),T()};h.once("end",K),h.once("close",K),h.once("error",j)});h.resume(),await P}),G=!1,X=Promise.all(J).then(()=>!0,()=>!1),z,oe=async()=>{if(n)await n;return Promise.race([X,new Promise((h)=>{z=setTimeout(()=>h(!1),3000)})])},S=await Promise.race([X,oe()]);if(z)clearTimeout(z);if(!S){G=!0;for(let{stream:h}of o)h.destroy()}if(!y&&v.length)if(b+I<=ge)H(v);else y=!0;v=[],I=0;for(let h of["stdout","stderr"]){if(!u[h]&&l[h])c[h].push(l[h]);l[h]=""}w.contentOmitted=Math.max(0,m-b),w.drainTimedOut=G,N(),c.stdout.finish(),c.stderr.finish();let U=m>b||G,ae=R().preview;return{content:a.join(""),preview:ae,totalChars:m,totalBytes:p,truncated:U,drainTimedOut:G,provenance:w}}var it=process.platform==="win32",wn=process.platform==="darwin",bn=process.platform==="linux";var cr=["PATH","HOME","LANG","LC_ALL","TZ","TERM","TMPDIR","USER","SHELL"],lr=["PATH","SystemRoot","windir","COMSPEC","PATHEXT","TEMP","TMP","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","NUMBER_OF_PROCESSORS","OS","PROCESSOR_ARCHITECTURE"];function ot(){let e=it?lr:cr,t={};for(let n of e){let r=process.env[n]??(it?Object.entries(process.env).find(([s])=>s.toLowerCase()===n.toLowerCase())?.[1]:void 0);if(r!==void 0)t[n]=r}return t}import{open as ur,lstat as dr}from"fs/promises";var ie=2000000,fr=256000;var pr=64000,at=512;function _(e){return e.replace(/[^\r\n]/g,"*")}function ct(e){let t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return/(?:apikey|authorization|cookie|credentials?|password|passwd|privatekey|secret)/.test(t)||/(?:access|auth|refresh|session)?token$/.test(t)}function Ae(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1}function hr(e){let t=/(?:^|[^A-Za-z0-9_.-])(["']?)([A-Za-z_][A-Za-z0-9_.-]{0,127})\1\s*[=:]\s*(["'])/g;for(let n=t.exec(e);n;n=t.exec(e)){if(!ct(n[2]))continue;let r=n[3],i=n.index+n[0].length;while(i<e.length&&(e[i]!==r||Ae(e,i)))i++;if(i===e.length)return r}return null}function mr(e,t){let n=/-----BEGIN ([^-\r\n]*PRIVATE KEY)-----|-----END ([^-\r\n]*PRIVATE KEY)-----/g,r="",s=0;for(let i=n.exec(e);i;i=n.exec(e)){if(r+=t.pem.length?_(e.slice(s,i.index)):e.slice(s,i.index),i[1])t.pem.push(i[1]),r+=_(i[0]);else if(t.pem.at(-1)===i[2])t.pem.pop(),r+=_(i[0]);else if(t.pem.length)r+=_(i[0]);else r+=i[0];s=i.index+i[0].length}return r+(t.pem.length?_(e.slice(s)):e.slice(s))}function gr(e){let t=e.replace(/[\r\n]+$/,""),n=/(?:^|[^A-Za-z0-9_.-])(["']?)([A-Za-z_][A-Za-z0-9_.-]{0,127})\1\s*([=:])?\s*$/.exec(t);if(!n||!ct(n[2]))return null;return n[3]?"value":"delimiter"}function Sr(e,t){let n="",r=0,s=e.search(/[\r\n]/),i=s<0?e.length:s;if(t.assignment==="delimiter"){let o=e.slice(r,i).search(/[=:]/);if(o<0)return e;n+=e.slice(0,o+1),r=o+1,t.assignment="value"}if(t.assignment==="value"){while(r<i&&/\s/.test(e[r]))n+=e[r++];if(r<i&&(e[r]==='"'||e[r]==="'")){let o=e[r];n+=o,r++;let a=r;while(a<i&&(e[a]!==o||Ae(e,a)))a++;if(a===i)return n+=_(e.slice(r)),t.quote=o,t.assignment=null,n+e.slice(i);n+=_(e.slice(r,a))+o,r=a+1,t.assignment=null}else if(r<i){let o=e.slice(r,i).search(/[\s,;}"']/),a=o<0?i:r+o;n+=_(e.slice(r,a)),r=a,t.assignment=null}else return n+e.slice(r)}return n+W(e.slice(r))}function yr(e,t){if(t.maskRest)return _(e);let n=mr(e,t);if(t.quote){let s=0;while(s<n.length&&(n[s]!==t.quote||Ae(n,s)))s++;if(s===n.length)return _(n);return t.quote=null,_(n.slice(0,s))+n[s]+W(n.slice(s+1))}if(t.assignment)return Sr(n,t);let r=W(n);return t.quote=hr(n),t.assignment=gr(n),r}class lt{emit;maxLineChars;channels={stdout:{pending:[],pendingChars:0,state:{pem:[],quote:null,assignment:null,maskRest:!1}},stderr:{pending:[],pendingChars:0,state:{pem:[],quote:null,assignment:null,maskRest:!1}}};ordered=[];orderedChars=0;maskRest=!1;conservative=!1;constructor(e,t=pr){this.emit=e;this.maxLineChars=t}get redactionConservative(){return this.conservative}push(e){if(!e.text)return;let t=0;while(t<e.text.length){let n=e.text.slice(t).search(/[\r\n]/),r=n<0?e.text.length:t+n+1,s=e.text.slice(t,r),i={...e,text:s,globalOffset:e.globalOffset+t,channelOffset:e.channelOffset+t},o=n>=0,a=this.channels[e.channel];if(this.maskRest)this.emitMasked(e,t,r);else if(s.length>this.maxLineChars||a.pendingChars+s.length>this.maxLineChars||a.pending.length>=4096||this.orderedChars+s.length>this.maxLineChars||this.ordered.length>=4096)this.maskPendingRemainder(),this.emitMasked(e,t,r);else{if(this.ordered.push(i),this.orderedChars+=s.length,a.pending.push(i),a.pendingChars+=s.length,o)this.flushChannel(e.channel,!1);this.drainReady()}t=r}}finish(){this.flushChannel("stdout",!1),this.flushChannel("stderr",!1),this.drainReady()}flushChannel(e,t){let n=this.channels[e];if(!n.pendingChars)return;let r=n.pending.map((o)=>o.text).join(""),s=t?_(r):yr(r,n.state),i=0;for(let o of n.pending)o.redactedText=s.slice(i,i+o.text.length),i+=o.text.length;n.pending=[],n.pendingChars=0}appendMasked(e){this.ordered.push({...e,redactedText:_(e.text)}),this.orderedChars+=e.text.length,this.drainReady()}emitMasked(e,t,n){for(let r=t;r<n;){let s=Math.min(n,r+at);if(s<n&&/[\uD800-\uDBFF]/.test(e.text[s-1])&&/[\uDC00-\uDFFF]/.test(e.text[s]))s--;if(s===r)s=Math.min(n,r+2);let i=e.text.slice(r,s);this.appendMasked({...e,text:_(i),globalOffset:e.globalOffset+r,channelOffset:e.channelOffset+r}),r=s}}maskPendingRemainder(){this.conservative=!0,this.maskRest=!0;for(let e of["stdout","stderr"])this.channels[e].state.maskRest=!0,this.flushChannel(e,!0);for(let e of this.ordered)if(e.redactedText===void 0)e.redactedText=_(e.text);this.drainReady()}drainReady(){while(this.ordered.length&&this.ordered[0].redactedText!==void 0){let e=this.ordered.shift();this.orderedChars-=e.text.length,this.emit({...e,text:e.redactedText})}}}class we{path;options;file;queue=[];queuedBytes=0;inFlightBytes=0;committedBytes=0;sequence=0;settledSequence=0;droppedRecords=0;truncated=!1;accepting=!0;available=!1;writing=!1;writerError=!1;gapUnknown=!1;previewFull="";previewHead="";previewTail="";previewChars=0;writeRecord;redactor;constructor(e,t={}){this.path=e;this.options=t;this.writeRecord=t.writeRecord??(async(n,r)=>{await n.write(r,void 0,"utf8")}),this.redactor=new lt((n)=>this.enqueue(n),t.maxLineChars)}async open(){try{try{let t=await dr(this.path);if(!t.isFile()||t.isSymbolicLink()||typeof process.getuid==="function"&&t.uid!==process.getuid())throw Error("Shell stream journal is not a privately owned file")}catch(t){if(t.code!=="ENOENT")throw t}this.file=await ur(this.path,"a",384);let e=await this.file.stat();if(!e.isFile()||typeof process.getuid==="function"&&e.uid!==process.getuid())throw Error("Shell stream journal is not a privately owned file");if(this.committedBytes=e.size,this.committedBytes>(this.options.maxBytes??ie))throw Error("Shell stream journal exceeds its retention limit");this.available=!0}catch{this.available=!1,await this.file?.close().catch(()=>{}),this.file=void 0}}disable(){this.available=!1,this.accepting=!1,this.truncated=!0,this.gapUnknown=!0}preview(){if(this.previewFull!==null)return this.previewFull;let e=Math.max(0,this.previewChars-this.previewHead.length-this.previewTail.length);return e?`${this.previewHead}
|
|
27
|
+
\u2026[${e} characters omitted]\u2026
|
|
28
|
+
${this.previewTail}`:this.previewHead||this.previewTail}push(e){this.redactor.push(e)}async finish(e=1000){if(this.redactor.finish(),!await this.flush(e)){this.accepting=!1,this.truncated=!0,this.gapUnknown=!0,this.droppedRecords+=this.queue.length,this.queue.length=0,this.queuedBytes=0,this.settleDroppedTail();let t=this.file;this.file=void 0,t?.close().catch(()=>{});return}await this.file?.close().catch(()=>{}),this.file=void 0}async flush(e=250){let t=this.startWriter(),n;try{return await Promise.race([t.then(()=>!0),new Promise((r)=>{n=setTimeout(()=>r(!1),e)})])}finally{if(n)clearTimeout(n)}}stats(){return{available:this.available,latestSequence:this.settledSequence,assignedSequence:this.sequence,droppedRecords:this.droppedRecords,bytes:this.committedBytes+this.queuedBytes+this.inFlightBytes,truncated:this.truncated||this.writerError,redactionConservative:this.redactor.redactionConservative,gapUnknown:this.gapUnknown}}enqueue(e){let t=e.text;if(t){if(this.previewFull!==null&&this.previewFull.length+t.length<=60000)this.previewFull+=t;else{if(this.previewFull!==null)this.previewHead=this.previewFull.slice(0,20000),this.previewTail=this.previewFull.slice(-40000),this.previewFull=null;if(this.previewHead.length<20000)this.previewHead+=t.slice(0,20000-this.previewHead.length);this.previewTail=`${this.previewTail}${t}`.slice(-40000)}this.previewChars+=t.length}if(!this.available||this.writerError||!this.accepting){this.truncated=!0,this.gapUnknown=!0,this.settleDroppedTail();return}for(let n=0;n<t.length;){let r=Math.min(t.length,n+at);if(r<t.length&&/[\uD800-\uDBFF]/.test(t[r-1])&&/[\uDC00-\uDFFF]/.test(t[r]))r--;if(r===n)r=Math.min(t.length,n+2);let s={sequence:++this.sequence,channel:e.channel,globalOffset:e.globalOffset+n,channelOffset:e.channelOffset+n,text:t.slice(n,r)},i=`${JSON.stringify(s)}
|
|
29
|
+
`,o=Buffer.byteLength(i,"utf8");if(!this.available||this.writerError||!this.accepting||this.committedBytes+this.queuedBytes+this.inFlightBytes+o>(this.options.maxBytes??ie)||this.queuedBytes+o>(this.options.maxQueueBytes??fr)){this.droppedRecords++,this.truncated=!0,this.accepting=!1,this.gapUnknown=!0,this.settleDroppedTail();return}else this.queue.push({value:i,bytes:o}),this.queuedBytes+=o,this.startWriter();n=r}}startWriter(){if(this.writing||!this.queue.length||!this.file||!this.available)return this.writerPromise??Promise.resolve();return this.writing=!0,this.writerPromise=(async()=>{try{while(this.queue.length){let e=this.queue.shift();this.queuedBytes-=e.bytes,this.inFlightBytes=e.bytes;try{await this.writeRecord(this.file,e.value),this.committedBytes+=e.bytes,this.inFlightBytes=0,this.settledSequence=vr(e.value)}catch{this.inFlightBytes=0,this.writerError=!0,this.accepting=!1,this.truncated=!0,this.gapUnknown=!0,this.droppedRecords+=1+this.queue.length,this.queue.length=0,this.queuedBytes=0,this.settleDroppedTail();break}}}finally{this.writing=!1,this.settleDroppedTail()}})(),this.writerPromise}settleDroppedTail(){if(!this.writing&&this.queue.length===0&&(!this.accepting||!this.available||this.writerError))this.settledSequence=this.sequence}writerPromise}function vr(e){try{return JSON.parse(e).sequence}catch{return 0}}var ke="shell_supervisor_v1",_r=131072,Nr=16777216,Lr=65536;var Mr=500,Jr=20971520,$r=10;function ht(e){return wr("sha256").update(e).digest("hex")}function be(e){let t=ne(e.sessionId,e.storageRoot),n=Y(t,"supervisors"),r=ht(e.taskId);return{outputDirectory:t,directory:n,state:Y(n,`${r}.json`),lock:Y(n,`${r}.lock`),journal:Y(n,`${r}.stream.jsonl`)}}function mt(e){let t=Array.isArray(e.args)?e.args.reduce((n,r)=>n+Buffer.byteLength(r,"utf8"),0):1/0;if(!e.sessionId||e.sessionId.length>256||!e.taskId||e.taskId.length>256||!/^[a-f0-9]{64}$/.test(e.fingerprint)||!e.executable||e.executable.includes("/")&&!e.executable.startsWith("/")||!Array.isArray(e.args)||e.args.some((n)=>typeof n!=="string")||t>Lr||!e.cwd.startsWith("/")||!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>86400000)throw Error("Invalid shell supervisor request")}async function Re(e){await Or(e,{recursive:!0,mode:448});let t=await ft(e);if(!t.isDirectory()||t.isSymbolicLink()||typeof process.getuid==="function"&&t.uid!==process.getuid())throw Error("Shell supervisor state directory is not privately owned");await xr(e,448)}async function Dr(e,t){let{directory:n,state:r,journal:s}=be(e),i;try{i=await de(`shell-stream-journal-retention:${kr(n)}`);let o=await Cr(n,{withFileTypes:!0}),a=[];for(let v of o){if(!/^[a-f0-9]{64}\.stream\.jsonl$/i.test(v.name))continue;let I=Y(n,v.name),A=await ft(I);if(!A.isFile()||A.isSymbolicLink()||typeof process.getuid==="function"&&A.uid!==process.getuid())return;let w=Y(n,v.name.replace(/\.stream\.jsonl$/,".json")),R=!1;try{let O=JSON.parse(pt(w,"utf8"));if(O.state==="running")if(!gt(O.identity))R=!0;else R=Gr(Oe(Fr(O.identity)),O.identity)}catch{R=!0}a.push({name:v.name,path:I,bytes:A.size,modifiedAt:A.mtimeMs,active:R})}let c=`${ht(e.taskId)}.stream.jsonl`,l=a.find((v)=>v.name===c);if(l?.active)return;if(l)await ut(l.path).catch(()=>{}),a.splice(a.indexOf(l),1);let u=a.filter((v)=>v.active).length,d=a.filter((v)=>!v.active).sort((v,I)=>v.modifiedAt-I.modifiedAt),f=d.reduce((v,I)=>v+I.bytes,0),b=d.length;while(u+b+1>$r||u*ie+f+ie>Jr){let v=d.shift();if(!v)return;await ut(v.path).catch(()=>{}),f-=v.bytes,b--}await(await Pr(s,"wx",384)).close();let p=new we(s);await p.open();let y=p.stats();return await Z(r,{...t,streamAvailable:y.available,...!y.available?{streamUnavailableReason:"storage-unavailable"}:{},streamLatestSequence:0,streamDroppedRecords:0,streamTruncated:!1,streamRedactionConservative:!1,streamGapUnknown:!y.available}),y.available?p:void 0}catch{await Z(r,{...t,streamAvailable:!1,streamUnavailableReason:"storage-unavailable",streamLatestSequence:0,streamDroppedRecords:0,streamTruncated:!0,streamRedactionConservative:!1,streamGapUnknown:!0}).catch(()=>{});return}finally{await i?.release().catch(()=>{})}}async function Z(e,t){let n=`${e}.${process.pid}.${Date.now()}.tmp`;await Ir(n,JSON.stringify(t),{encoding:"utf8",mode:384,flag:"wx"}),await Tr(n,e)}function dt(e){let{state:t}=be(e);try{let n=Ar(t);if(!n.isFile()||n.isSymbolicLink()||n.size>Nr||typeof process.getuid==="function"&&n.uid!==process.getuid())return;let r=JSON.parse(pt(t,"utf8"));if(r.schema!==ke||r.sessionId!==e.sessionId||r.taskId!==e.taskId||r.fingerprint!==e.fingerprint||!["running","done","failed","cancelled","timed_out"].includes(r.state??"")||!gt(r.identity)||!["settled","unknown"].includes(r.processGroupSettled??"")||r.outputPreview!==void 0&&(typeof r.outputPreview!=="string"||r.outputPreview.length>1e5)||r.totalChars!==void 0&&(!Number.isSafeInteger(r.totalChars)||r.totalChars<0)||r.outputBytes!==void 0&&(!Number.isSafeInteger(r.outputBytes)||r.outputBytes<0)||r.outputTruncated!==void 0&&typeof r.outputTruncated!=="boolean"||r.streamAvailable!==void 0&&typeof r.streamAvailable!=="boolean"||r.streamLatestSequence!==void 0&&(!Number.isSafeInteger(r.streamLatestSequence)||r.streamLatestSequence<0)||r.streamDroppedRecords!==void 0&&(!Number.isSafeInteger(r.streamDroppedRecords)||r.streamDroppedRecords<0)||r.streamTruncated!==void 0&&typeof r.streamTruncated!=="boolean"||r.streamRedactionConservative!==void 0&&typeof r.streamRedactionConservative!=="boolean"||r.streamGapUnknown!==void 0&&typeof r.streamGapUnknown!=="boolean")return;if(r.memoryContent!==void 0&&(typeof r.memoryContent!=="string"||r.memoryContent.length>2000000))return;return r}catch{return}}function gt(e){let t=e;return!!t&&t.platform==="linux"&&Number.isSafeInteger(t.pid)&&t.pid>1&&typeof t.bootId==="string"&&typeof t.pidNamespace==="string"&&typeof t.startTimeTicks==="string"&&Number.isSafeInteger(t.sessionId)&&Number.isSafeInteger(t.processGroupId)&&t.sessionId>0&&t.processGroupId===t.pid}function Br(e,t){return e.pid===t.pid&&e.bootId===t.bootId&&e.pidNamespace===t.pidNamespace&&e.startTimeTicks===t.startTimeTicks&&e.sessionId===t.sessionId&&e.processGroupId===t.processGroupId}function Fr(e){return{identity:e,status:"alive",observedAt:new Date().toISOString(),provenance:"kernel",scope:"process-group",progress:"not-measured"}}function Gr(e,t){return!!e.identity&&Br(e.identity,t)&&e.scope==="process-group"&&e.status==="alive"&&e.processGroup?.status==="alive"}async function St(e){mt(e);let t=Le();if(!t.identity||t.scope!=="process-group")throw Error("Shell supervisor could not capture its Linux process-group identity");let n=t.identity,{outputDirectory:r,directory:s,state:i}=be(e);await Re(Rr(r)),await Re(r),await Re(s);let o=new Date().toISOString(),a={schema:ke,sessionId:e.sessionId,taskId:e.taskId,fingerprint:e.fingerprint,state:"running",identity:n,startedAt:o,processGroupSettled:"unknown"},c=await Dr(e,a),l=dt(e);if(!l||l.streamAvailable===void 0)await Z(i,{...a,streamAvailable:!1,streamUnavailableReason:"retention-capacity",streamLatestSequence:0,streamDroppedRecords:0,streamTruncated:!0,streamRedactionConservative:!1,streamGapUnknown:!0});if(!c)c=new we(be(e).journal),c.disable();let u=dt(e)??{...a,streamAvailable:!1,streamTruncated:!0},d=()=>{let S=c?.stats();return{streamAvailable:S?.available??u.streamAvailable??!1,...!S?.available&&u.streamUnavailableReason?{streamUnavailableReason:u.streamUnavailableReason}:{},streamLatestSequence:S?.latestSequence??u.streamLatestSequence??0,streamDroppedRecords:S?.droppedRecords??u.streamDroppedRecords??0,streamTruncated:S?.truncated??u.streamTruncated??!0,streamRedactionConservative:S?.redactionConservative??u.streamRedactionConservative??!1,streamGapUnknown:S?.gapUnknown??u.streamGapUnknown??!1}},f=new AbortController,b=()=>{if(!f.signal.aborted)f.abort(Error("Shell supervisor was asked to stop"))};process.on("SIGTERM",b);let m=Er(e.executable,e.args,{cwd:e.cwd,env:ot(),detached:!0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),p=new Promise((S)=>{m.once("exit",()=>S()),m.once("error",()=>S())}),y,v=0,I=0,A=Promise.resolve(),w=()=>{let S=y;if(!S||S.totalChars===v&&S.totalBytes===I)return;v=S.totalChars,I=S.totalBytes,A=A.then(async()=>{await c?.flush(200);let U={...u,totalChars:S.totalChars,outputBytes:S.totalBytes,outputPreview:c.preview(),outputTruncated:S.truncated,...d()};await Z(i,U)}).catch(()=>{})},R=setInterval(w,Mr);R.unref?.();let O=st(m.stdout,m.stderr,p,(S)=>{y=S},(S)=>c?.push(S)),[N,M]=await Promise.allSettled([O,nt(m,e.timeoutMs,f.signal)]);clearInterval(R),w(),await A,await c?.finish(1000);let H=d(),C=N.status==="fulfilled"?N.value:{content:"",preview:"",totalChars:0,totalBytes:0,truncated:!1,drainTimedOut:!0,provenance:{schema:"shell_channel_provenance_v1",ordering:"observed-arrival",stdoutChars:0,stderrChars:0,retainedChars:0,segments:[],segmentsOmitted:0,contentOmitted:0,drainTimedOut:!0}},F="done",L=0,J=null,G=!1,X=!1;if(M.status==="rejected"){let S=M.reason;L=typeof S.exitCode==="number"?S.exitCode:m.exitCode,J=S.signal??m.signalCode,G=S.timedOut===!0,X=S.cancelled===!0||f.signal.aborted,F=G?"timed_out":X?"cancelled":"failed"}if(N.status==="rejected"&&F==="done")F="failed";let z=(m.exitCode!==null||m.signalCode!==null)&&!C.drainTimedOut?"settled":"unknown",oe=br();await Ze(e.sessionId,e.storageRoot,async(S)=>{await Z(i,{...u,processGroupSettled:z,reservedOutputId:oe,outputPreview:c.preview(),totalChars:C.totalChars,outputBytes:C.totalBytes,outputTruncated:C.truncated,...H});let U=await S(C.content,C.totalChars,C.provenance,e.recoveryRoot,void 0,oe),ae=U.metadata.storage==="memory"?(await Ke(e.sessionId,U.id,e.storageRoot,e.recoveryRoot)).content:void 0,h={schema:ke,sessionId:e.sessionId,taskId:e.taskId,fingerprint:e.fingerprint,state:F,identity:n,startedAt:o,finishedAt:new Date().toISOString(),exitCode:L,signal:J,timedOut:G,cancelled:X,processGroupSettled:z,outputId:U.id,outputMetadata:U.metadata,outputPreview:c.preview(),totalChars:C.totalChars,outputBytes:C.totalBytes,outputTruncated:C.truncated,drainTimedOut:C.drainTimedOut,provenance:C.provenance,...H,...ae!==void 0?{memoryContent:ae}:{}};await Z(i,h)}),process.off("SIGTERM",b)}async function yt(e){let t=[],n=0;for await(let s of e){let i=Buffer.from(s);if(n+=i.length,n>_r)throw Error("Shell supervisor configuration exceeds its limit");t.push(i)}let r=JSON.parse(Buffer.concat(t).toString("utf8"));return mt(r),r}if(import.meta.main)try{let e=await yt(process.stdin);await St(e),process.exit(0)}catch(e){process.stderr.write(`Shell supervisor failed: ${e instanceof Error?e.message:String(e)}
|
|
31
30
|
`),process.exit(1)}
|