@orcha-ai/runtime-bridge 0.1.31 → 0.1.33

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/.env.example CHANGED
@@ -10,6 +10,7 @@ ORCHA_RUNTIME_DEFAULT_TARGET=codex
10
10
  ORCHA_RUNTIME_RECONNECT_MS=3000
11
11
  ORCHA_RUNTIME_CONNECT_TIMEOUT_MS=10000
12
12
  ORCHA_RUNTIME_HEARTBEAT_INTERVAL_MS=15000
13
+ ORCHA_RUNTIME_INITIALIZE_TIMEOUT_MS=30000
13
14
  ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS=3600000
14
15
  ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS=300000
15
16
  ORCHA_RUNTIME_SESSION_IDLE_TTL_MS=600000
package/README.md CHANGED
@@ -136,6 +136,12 @@ and receives Orcha RPC frames for:
136
136
 
137
137
  Runtime targets are configured with `ORCHA_RUNTIME_TARGETS_JSON`.
138
138
 
139
+ ACP runtimes complete a JSON-RPC `initialize` handshake before a session is
140
+ created. `ORCHA_RUNTIME_INITIALIZE_TIMEOUT_MS` controls that handshake only
141
+ (30 seconds by default); it is independent from the task/prompt timeout. A
142
+ target can override it with `"initializeTimeoutMs"`. Target processes use
143
+ `cwd`, then `workspace`, then the request workspace as their working directory.
144
+
139
145
  Start the bundled Egress Proxy as a separate supervised process before the
140
146
  Runtime Bridge. In production use separate protected environment files: the
141
147
  proxy file contains only its socket, token, and limits; the bridge file contains
@@ -168,6 +174,7 @@ receive work.
168
174
  "openclaw": {
169
175
  "type": "openclaw",
170
176
  "command": "openclaw",
177
+ "workspace": "/workspaces/project-a",
171
178
  "maxSessions": 1,
172
179
  "releaseAfterPrompt": true,
173
180
  "sessionIdleTtlMs": 60000,
@@ -1,24 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as Co}from"node:child_process";import{closeSync as No,existsSync as fn,mkdirSync as bo,openSync as Mo,readFileSync as ke,rmSync as Uo,statSync as sn,writeFileSync as pn}from"node:fs";import{dirname as Po,resolve as ve}from"node:path";import{fileURLToPath as ko}from"node:url";import{createHash as Ci,randomUUID as kt}from"node:crypto";var Y="0.1.31";function ot(){return new Date().toISOString()}function M(e,t=2){return String(e).padStart(t,"0")}function Ke(e){let t=e>=0?"+":"-",r=Math.abs(e);return`${t}${M(Math.floor(r/60))}:${M(r%60)}`}function Rn(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${M(e.getMonth()+1)}-${M(e.getDate())}`,`T${M(e.getHours())}:${M(e.getMinutes())}:${M(e.getSeconds())}.${M(e.getMilliseconds(),3)}`,Ke(t)].join("")}function Sn(e,t){let r=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),n={};for(let s of r.formatToParts(e))s.type!=="literal"&&(n[s.type]=Number(s.value));return n}function En(e,t){let r=Sn(e,t),n=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,e.getMilliseconds()),s=Math.round((n-e.getTime())/6e4);return[`${r.year}-${M(r.month)}-${M(r.day)}`,`T${M(r.hour)}:${M(r.minute)}:${M(r.second)}.${M(e.getMilliseconds(),3)}`,Ke(s)].join("")}function wn(e=new Date){let t=a(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return En(e,t)}catch{return Rn(e)}}function u(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function a(e){return String(e??"").trim()}function T(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)?r:t}function C(e){return Array.isArray(e)?e.map(String):[]}var In="[redacted]",Ge=/(authorization|api[_-]?key|credential|password|secret|token)/i;function G(e,t=new WeakSet){if(e==null)return e;if(typeof e=="bigint")return e.toString();if(typeof e!="object")return e;if(e instanceof Date)return e.toISOString();if(e instanceof Error){if(t.has(e))return"[circular]";t.add(e);let s={name:e.name,message:e.message};e.stack&&(s.stack=e.stack);for(let i of Object.keys(e))s[i]=G(e[i],t);return t.delete(e),s}if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e)){let s=e.map(i=>G(i,t));return t.delete(e),s}let r={},n=Ge.test(a(e.name||e.key));for(let[s,i]of Object.entries(e))r[s]=Ge.test(s)||n&&s.toLowerCase()==="value"?In:G(i,t);return t.delete(e),r}function Ve(e,t=4e3){let r=JSON.stringify(G(e))??String(e);return!Number.isFinite(t)||r.length<=t?r:`${r.slice(0,t)}...`}function h(e,t,r,n={}){let s={ts:wn(),level:e,module:t,msg:r,...u(n)?G(n):{}};console.error(JSON.stringify(s))}function Tt(e){return Array.isArray(e)?e.map(t=>u(t)?t.type==="text"?a(t.text):t.type==="file"?a(t.uri):t.type==="image"?a(t.uri):"":"").filter(Boolean).join(`
3
- `):""}var yt=class{constructor(t){this.agent=t,this.sessionCounter=0}async sessionNew(){return this.sessionCounter+=1,{sessionId:`echo-${this.agent.agentId}-${this.sessionCounter}`}}async sessionPrompt(t,r){let n=Tt(t.prompt);return r({sessionId:t.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n?`Echo runtime received: ${n}`:"Echo runtime received an empty prompt."}}}),{stopReason:"end_turn"}}async sessionCancel(){return{ok:!0}}};import{spawn as On}from"node:child_process";var at="2.0",xn=3e4;function An(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:a(e?.message)||String(e),data:u(e?.data)?e.data:void 0}}function Cn(e){if(!u(e))return new Error(String(e||"runtime error"));let t=a(e.message)||"runtime error",r="data"in e?Ve(e.data,4e3):"",n=new Error(r?`${t}; data=${r}`:t);return n.rpcCode=e.code,n.data=e.data,n}function Nn(e){return u(e)&&"id"in e&&!("method"in e)}function bn(e){return u(e)&&typeof e.method=="string"&&"id"in e}function Mn(e){return u(e)&&typeof e.method=="string"&&!("id"in e)}var Rt=class{constructor({command:t,args:r=[],cwd:n,env:s,label:i,framing:o="line",detached:c=!0}){this.command=t,this.args=Array.isArray(r)?r.map(String):[],this.cwd=n||process.cwd(),this.env=u(s)?{...s}:{...process.env},this.label=i||t,this.framing=o==="content-length"?"content-length":"line",this.detached=c!==!1,this.child=null,this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stopPromise=null,this.lineBuffer="",this.headerBuffer=Buffer.alloc(0),this.seq=0,this.pending=new Map,this.notificationHandlers=new Map,this.requestHandlers=new Map,this.exitHandlers=new Set}async start({initialize:t=!0,initializeParams:r={}}={}){this.child&&!this.exited||(this.exited=!1,this.exitCode=null,this.exitSignal=null,this.child=On(this.command,this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"],detached:this.detached}),this.child.stdout.on("data",n=>this.onStdout(n)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",n=>{let s=n.trimEnd();s&&h("debug","runtime.stderr","runtime stderr",{target:this.label,text:s})}),this.child.on("exit",(n,s)=>this.handleExit(n,s)),this.child.on("error",n=>this.rejectAll(n)),t&&await this.call("initialize",{protocolVersion:1,clientCapabilities:{},...r}).catch(n=>{throw Object.assign(new Error(`runtime initialize failed: ${n.message}`),{code:"RUNTIME_INITIALIZE_FAILED"})}))}onStdout(t){if(this.framing==="content-length"){this.onContentLengthData(Buffer.isBuffer(t)?t:Buffer.from(t));return}this.onLineData(t.toString("utf8"))}onLineData(t){this.lineBuffer+=t;let r=this.lineBuffer.split(/\r?\n/);this.lineBuffer=r.pop()||"";for(let n of r){let s=n.trim();s&&this.dispatchRaw(s)}}onContentLengthData(t){for(this.headerBuffer=Buffer.concat([this.headerBuffer,t]);this.headerBuffer.length>0;){let r=this.headerBuffer.indexOf(`\r
2
+ import{spawn as Po}from"node:child_process";import{closeSync as ko,existsSync as yn,mkdirSync as Lo,openSync as Do,readFileSync as qe,rmSync as vo,statSync as fn,writeFileSync as Rn}from"node:fs";import{dirname as Fo,resolve as Ke}from"node:path";import{fileURLToPath as Ho}from"node:url";import{createHash as Li,randomUUID as Ht}from"node:crypto";var Y="0.1.33";function at(){return new Date().toISOString()}function M(e,t=2){return String(e).padStart(t,"0")}function Ze(e){let t=e>=0?"+":"-",r=Math.abs(e);return`${t}${M(Math.floor(r/60))}:${M(r%60)}`}function An(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${M(e.getMonth()+1)}-${M(e.getDate())}`,`T${M(e.getHours())}:${M(e.getMinutes())}:${M(e.getSeconds())}.${M(e.getMilliseconds(),3)}`,Ze(t)].join("")}function Cn(e,t){let r=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),n={};for(let s of r.formatToParts(e))s.type!=="literal"&&(n[s.type]=Number(s.value));return n}function Nn(e,t){let r=Cn(e,t),n=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,e.getMilliseconds()),s=Math.round((n-e.getTime())/6e4);return[`${r.year}-${M(r.month)}-${M(r.day)}`,`T${M(r.hour)}:${M(r.minute)}:${M(r.second)}.${M(e.getMilliseconds(),3)}`,Ze(s)].join("")}function bn(e=new Date){let t=a(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return Nn(e,t)}catch{return An(e)}}function u(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function a(e){return String(e??"").trim()}function g(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)?r:t}function C(e){return Array.isArray(e)?e.map(String):[]}function Z(e,t,r=process.cwd()){let n=u(e)?e:{};return a(n.cwd)||a(n.workspace)||a(t)||a(r)||process.cwd()}var Rt="[redacted]",Mn=/(authorization|api[_-]?key|credential|password|secret|token)/i;function St(e){return Mn.test(a(e))}function Qe(e,t=[]){let r=String(e??"");for(let n of t){let s=String(n??"");s.length>=4&&(r=r.split(s).join(Rt))}return r.replace(/((?:authorization|api[_-]?key|credential|password|secret|token)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,`$1${Rt}`).replace(/([?&](?:api[_-]?key|credential|password|secret|token)=)[^&\s]+/gi,`$1${Rt}`)}function G(e,t=new WeakSet){if(e==null)return e;if(typeof e=="bigint")return e.toString();if(typeof e!="object")return e;if(e instanceof Date)return e.toISOString();if(e instanceof Error){if(t.has(e))return"[circular]";t.add(e);let s={name:e.name,message:e.message};e.stack&&(s.stack=e.stack);for(let i of Object.keys(e))s[i]=G(e[i],t);return t.delete(e),s}if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e)){let s=e.map(i=>G(i,t));return t.delete(e),s}let r={},n=St(e.name||e.key);for(let[s,i]of Object.entries(e))r[s]=St(s)||n&&s.toLowerCase()==="value"?Rt:G(i,t);return t.delete(e),r}function tr(e,t=4e3){let r=JSON.stringify(G(e))??String(e);return!Number.isFinite(t)||r.length<=t?r:`${r.slice(0,t)}...`}function h(e,t,r,n={}){let s={ts:bn(),level:e,module:t,msg:r,...u(n)?G(n):{}};console.error(JSON.stringify(s))}function Et(e){return Array.isArray(e)?e.map(t=>u(t)?t.type==="text"?a(t.text):t.type==="file"?a(t.uri):t.type==="image"?a(t.uri):"":"").filter(Boolean).join(`
3
+ `):""}var wt=class{constructor(t){this.agent=t,this.sessionCounter=0}async sessionNew(){return this.sessionCounter+=1,{sessionId:`echo-${this.agent.agentId}-${this.sessionCounter}`}}async sessionPrompt(t,r){let n=Et(t.prompt);return r({sessionId:t.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n?`Echo runtime received: ${n}`:"Echo runtime received an empty prompt."}}}),{stopReason:"end_turn"}}async sessionCancel(){return{ok:!0}}};import{spawn as Un}from"node:child_process";var ct="2.0",Jt=3e4,Pn=4e3;function It(e,t){let r=Object.entries(u(t)?t:{}).filter(([n])=>St(n)).map(([,n])=>n);return Qe(e,r)}function kn(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:a(e?.message)||String(e),data:u(e?.data)?e.data:void 0}}function Ln(e){if(!u(e))return new Error(String(e||"runtime error"));let t=a(e.message)||"runtime error",r="data"in e?tr(e.data,4e3):"",n=new Error(r?`${t}; data=${r}`:t);return n.rpcCode=e.code,n.data=e.data,n}function Dn(e){return u(e)&&"id"in e&&!("method"in e)}function vn(e){return u(e)&&typeof e.method=="string"&&"id"in e}function Fn(e){return u(e)&&typeof e.method=="string"&&!("id"in e)}var Ot=class{constructor({command:t,args:r=[],cwd:n,env:s,label:i,framing:o="line",detached:c=!0}){this.command=t,this.args=Array.isArray(r)?r.map(String):[],this.cwd=n||process.cwd(),this.env=u(s)?{...s}:{...process.env},this.label=i||t,this.framing=o==="content-length"?"content-length":"line",this.detached=c!==!1,this.child=null,this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stopPromise=null,this.stderrTail="",this.spawnError=null,this.lineBuffer="",this.headerBuffer=Buffer.alloc(0),this.seq=0,this.pending=new Map,this.notificationHandlers=new Map,this.requestHandlers=new Map,this.exitHandlers=new Set}async start({initialize:t=!0,initializeParams:r={},initializeTimeoutMs:n=Jt}={}){if(!(this.child&&!this.exited)&&(this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stderrTail="",this.spawnError=null,this.child=Un(this.command,this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"],detached:this.detached}),this.child.stdout.on("data",s=>this.onStdout(s)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",s=>{this.stderrTail=`${this.stderrTail}${s}`.slice(-Pn);let i=It(s.trimEnd(),this.env);i&&h("debug","runtime.stderr","runtime stderr",{target:this.label,text:i})}),this.child.on("exit",(s,i)=>this.handleExit(s,i)),this.child.on("error",s=>{this.spawnError=s,this.rejectAll(s)}),t)){let s=Math.max(1,g(n,Jt));try{await this.call("initialize",{protocolVersion:1,clientCapabilities:{},...r},s)}catch(i){let o=this.startupFailureDetail(),c=It(i?.message||i,this.env);h("warn","runtime.initialize","runtime initialize failed",{target:this.label,timeoutMs:s,cause:c,...o}),await this.stop("initialize failed",{termTimeoutMs:1e3,killTimeoutMs:1e3});let l=o.stderr?`; stderr: ${o.stderr}`:`; command=${o.command}; cwd=${o.cwd}`;throw Object.assign(new Error(`runtime initialize failed: ${c}${l}`,{cause:i}),{code:"RUNTIME_INITIALIZE_FAILED",detail:o})}}}startupFailureDetail(){return{command:this.command,cwd:this.cwd,exited:this.exited,exitCode:this.exitCode,exitSignal:this.exitSignal,...this.spawnError?{spawnError:It(this.spawnError.message,this.env)}:{},...this.stderrTail.trim()?{stderr:It(this.stderrTail.trim(),this.env)}:{}}}onStdout(t){if(this.framing==="content-length"){this.onContentLengthData(Buffer.isBuffer(t)?t:Buffer.from(t));return}this.onLineData(t.toString("utf8"))}onLineData(t){this.lineBuffer+=t;let r=this.lineBuffer.split(/\r?\n/);this.lineBuffer=r.pop()||"";for(let n of r){let s=n.trim();s&&this.dispatchRaw(s)}}onContentLengthData(t){for(this.headerBuffer=Buffer.concat([this.headerBuffer,t]);this.headerBuffer.length>0;){let r=this.headerBuffer.indexOf(`\r
4
4
  \r
5
- `);if(r<0)return;let s=this.headerBuffer.subarray(0,r).toString("utf8").match(/content-length:\s*(\d+)/i);if(!s){h("warn","runtime.protocol","missing Content-Length header",{target:this.label}),this.headerBuffer=Buffer.alloc(0);return}let i=Number.parseInt(s[1],10),o=r+4,c=o+i;if(this.headerBuffer.length<c)return;let l=this.headerBuffer.subarray(o,c).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(c),this.dispatchRaw(l)}}dispatchRaw(t){let r;try{r=JSON.parse(t)}catch(n){h("warn","runtime.protocol","invalid JSON frame",{target:this.label,error:String(n)});return}this.dispatch(r)}dispatch(t){if(Nn(t)){this.resolveResponse(t);return}if(bn(t)){this.handleRequest(t);return}Mn(t)&&this.handleNotification(t)}resolveResponse(t){let r=String(t.id),n=this.pending.get(r);n&&(clearTimeout(n.timer),this.pending.delete(r),t.error?(h("warn","runtime.protocol","runtime rpc error",{target:this.label,method:n.method,requestId:r,error:t.error}),n.reject(Cn(t.error))):n.resolve(t.result))}async handleRequest(t){let r=this.requestHandlers.get(t.method);if(!r){this.writeFrame({jsonrpc:at,id:t.id,error:{code:-32601,message:`method not found: ${t.method}`}});return}try{let n=await r(u(t.params)?t.params:{},t);this.writeFrame({jsonrpc:at,id:t.id,result:n??{}})}catch(n){this.writeFrame({jsonrpc:at,id:t.id,error:An(n)})}}handleNotification(t){let r=this.notificationHandlers.get(t.method);if(r)for(let n of r)n(u(t.params)?t.params:{},t)}call(t,r={},n=xn){if(!this.child||!this.child.stdin||this.exited)return Promise.reject(new Error("runtime process is not running"));let s=`${t}_${++this.seq}`,i={jsonrpc:at,id:s,method:t,params:r};return new Promise((o,c)=>{let l=setTimeout(()=>{this.pending.delete(s),c(new Error(`${t} timed out after ${n}ms`))},n);this.pending.set(s,{resolve:o,reject:c,timer:l,method:t}),this.writeFrame(i,d=>{d&&(clearTimeout(l),this.pending.delete(s),c(d))})})}notify(t,r={}){this.writeFrame({jsonrpc:at,method:t,params:r})}writeFrame(t,r){if(!this.child?.stdin||this.exited){r?.(new Error("runtime process is not running"));return}let n=JSON.stringify(t),s=this.framing==="content-length"?`Content-Length: ${Buffer.byteLength(n,"utf8")}\r
5
+ `);if(r<0)return;let s=this.headerBuffer.subarray(0,r).toString("utf8").match(/content-length:\s*(\d+)/i);if(!s){h("warn","runtime.protocol","missing Content-Length header",{target:this.label}),this.headerBuffer=Buffer.alloc(0);return}let i=Number.parseInt(s[1],10),o=r+4,c=o+i;if(this.headerBuffer.length<c)return;let l=this.headerBuffer.subarray(o,c).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(c),this.dispatchRaw(l)}}dispatchRaw(t){let r;try{r=JSON.parse(t)}catch(n){h("warn","runtime.protocol","invalid JSON frame",{target:this.label,error:String(n)});return}this.dispatch(r)}dispatch(t){if(Dn(t)){this.resolveResponse(t);return}if(vn(t)){this.handleRequest(t);return}Fn(t)&&this.handleNotification(t)}resolveResponse(t){let r=String(t.id),n=this.pending.get(r);n&&(clearTimeout(n.timer),this.pending.delete(r),t.error?(h("warn","runtime.protocol","runtime rpc error",{target:this.label,method:n.method,requestId:r,error:t.error}),n.reject(Ln(t.error))):n.resolve(t.result))}async handleRequest(t){let r=this.requestHandlers.get(t.method);if(!r){this.writeFrame({jsonrpc:ct,id:t.id,error:{code:-32601,message:`method not found: ${t.method}`}});return}try{let n=await r(u(t.params)?t.params:{},t);this.writeFrame({jsonrpc:ct,id:t.id,result:n??{}})}catch(n){this.writeFrame({jsonrpc:ct,id:t.id,error:kn(n)})}}handleNotification(t){let r=this.notificationHandlers.get(t.method);if(r)for(let n of r)n(u(t.params)?t.params:{},t)}call(t,r={},n=Jt){if(!this.child||!this.child.stdin||this.exited)return Promise.reject(new Error("runtime process is not running"));let s=`${t}_${++this.seq}`,i={jsonrpc:ct,id:s,method:t,params:r};return new Promise((o,c)=>{let l=setTimeout(()=>{this.pending.delete(s),c(new Error(`${t} timed out after ${n}ms`))},n);this.pending.set(s,{resolve:o,reject:c,timer:l,method:t}),this.writeFrame(i,d=>{d&&(clearTimeout(l),this.pending.delete(s),c(d))})})}notify(t,r={}){this.writeFrame({jsonrpc:ct,method:t,params:r})}writeFrame(t,r){if(!this.child?.stdin||this.exited){r?.(new Error("runtime process is not running"));return}let n=JSON.stringify(t),s=this.framing==="content-length"?`Content-Length: ${Buffer.byteLength(n,"utf8")}\r
6
6
  \r
7
7
  ${n}`:`${n}
8
- `;this.child.stdin.write(s,r)}onNotification(t,r){let n=this.notificationHandlers.get(t)||new Set;return n.add(r),this.notificationHandlers.set(t,n),()=>{n.delete(r),n.size===0&&this.notificationHandlers.delete(t)}}onRequest(t,r){return this.requestHandlers.set(t,r),()=>this.requestHandlers.delete(t)}onExit(t){return this.exitHandlers.add(t),()=>this.exitHandlers.delete(t)}rejectAll(t){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(t);this.pending.clear()}handleExit(t,r){this.exited=!0,this.exitCode=t,this.exitSignal=r,this.rejectAll(new Error(`runtime exited before response (${t}/${r})`));for(let n of this.exitHandlers)n(t,r)}async waitForExit(t=5e3){return!this.child||this.exited?!0:await new Promise(r=>{let n=setTimeout(()=>{s(),r(!1)},t);n.unref?.();let s=()=>{clearTimeout(n),this.exitHandlers.delete(i)},i=()=>{s(),r(!0)};this.exitHandlers.add(i),this.exited&&i()})}signal(t){if(!this.child||this.exited)return!1;let r=this.child.pid;if(!r)return!1;try{return this.detached&&process.platform!=="win32"?process.kill(-r,t):this.child.kill(t),!0}catch(n){if(n?.code==="ESRCH")return this.exited=!0,!1;try{return this.child.kill(t),!0}catch(s){return s?.code!=="ESRCH"&&h("warn","runtime","runtime signal failed",{target:this.label,pid:r,signal:t,error:String(s)}),!1}}}async stop(t="stop",{termTimeoutMs:r=5e3,killTimeoutMs:n=2e3}={}){if(!(!this.child||this.exited)){if(this.stopPromise)return await this.stopPromise;this.stopPromise=(async()=>{if(!this.child||this.exited)return;let s=this.child.pid;h("info","runtime","stopping runtime",{target:this.label,reason:t,pid:s}),this.rejectAll(new Error(`runtime stopped: ${t}`)),this.signal("SIGTERM"),!await this.waitForExit(r)&&this.child&&!this.exited&&(h("warn","runtime","runtime did not exit after SIGTERM; force killing",{target:this.label,reason:t,pid:s}),this.signal("SIGKILL"),await this.waitForExit(n))})();try{await this.stopPromise}finally{this.stopPromise=null}}}};import{randomUUID as Xe}from"node:crypto";import{existsSync as Un,readFileSync as Pn,realpathSync as ze,statSync as kn}from"node:fs";import{basename as Ye,extname as Qe,isAbsolute as ct,join as Ln,relative as Ze,resolve as We}from"node:path";var Dn=25*1024*1024;function tr(e,t=""){let r=a(t);if(r)return r;let n=Qe(a(e)).toLowerCase();return n===".jpg"||n===".jpeg"?"image/jpeg":n===".webp"?"image/webp":n===".gif"?"image/gif":"image/png"}function er(e,t){let r=typeof e=="string"?e.trim():"";return!r||r==="<omitted>"?"":r.startsWith("data:")?r:`data:${t};base64,${r.replace(/\s+/g,"")}`}function St(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function vn(e,t){let r=Ze(t,e);return r===""||!!r&&!r.startsWith("..")&&!ct(r)}function Fn(e,t){let r=a(e);if(!r||!Un(r))return"";try{let n=ze(r);for(let s of t)try{let i=ze(s);if(vn(n,i))return n}catch{}}catch{return""}return""}function Hn(e,t){let r=a(e);if(!r||!ct(r))return r;for(let n of Array.isArray(t)?t:[]){if(!u(n))continue;let s=a(n.runtimeRoot),i=a(n.hostRoot);if(!s||!i||!ct(s)||!ct(i))continue;let o=Ze(We(s),We(r));if(o===""||!o.startsWith("..")&&!ct(o))return o?Ln(i,o):i}return r}function Kt(e,t,r={}){let n=a(e);return!n||n.startsWith("data:")||/^https?:\/\//i.test(n)?n:$n(n,t,r)}function $n(e,t,r={}){let n=[...St(r.trustedFileRoots),...St(r.trustedFileRoot),...St(r.artifactRoots),...St(r.artifactRoot)],s=Fn(Hn(e,r.pathMappings),n);if(!s)return"";try{let i=kn(s);return!i.isFile()||i.size<=0||i.size>Dn?"":`data:${t};base64,${Pn(s).toString("base64")}`}catch{return""}}function x(...e){for(let t of e){let r=a(t);if(r)return r}return""}function Bn(e,t,r,n){let s=r.toLowerCase();if(s==="image"||s==="picture")return!0;let i=x(n,e.previewUrl,e.fileUrl,e.imageUrl,e.dataUrl,e.url,e.uri,t.previewUrl,t.fileUrl,t.imageUrl,t.dataUrl,t.url,t.uri),o=Qe(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function zt(e,t={}){let{source:r="runtime_image_generation_event"}=t;if(!u(e))return null;let n=u(e.payload)?e.payload:{},s=a(e.type),i=a(n.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let o=x(n.call_id,n.id),c=x(n.saved_path,n.savedPath),l=x(n.revised_prompt,n.revisedPrompt),d=tr(c,n.mimeType||n.mime_type),f=er(n.result,d)||Kt(c,d,t);if(!f)return null;let p=f.startsWith("data:")?f:"",g=c?Ye(c):`${o||Xe()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:g||"Generated image",summary:l||"Generated image",content:{prompt:l||void 0,dataUrl:p||void 0,imageUrl:f,previewUrl:f,fileUrl:f,mimeType:d},dataUrl:p||void 0,previewUrl:f,fileUrl:f,metadata:{source:r,eventType:i,callId:o||void 0,savedPath:c||void 0,filename:g,mimeType:d,revisedPrompt:l||void 0}}}function qn(e){let t=u(e)?e:{},r=[];for(let n of["_artifacts","artifacts"]){let s=t[n];Array.isArray(s)&&r.push(...s)}for(let n of["_artifact","artifact"]){let s=t[n];u(s)&&r.push(s)}return r}function jn(e,t={}){let{source:r="runtime_artifact"}=t,n=u(e)?e:{};if(!Object.keys(n).length)return null;let s=u(n.content)?{...n.content}:{},i=u(n.metadata)?{...n.metadata}:{},o=x(n.saved_path,n.savedPath,s.saved_path,s.savedPath,i.savedPath),c=x(n.mimeType,n.mime_type,s.mimeType,s.mime_type,i.mimeType),l=x(n.artifactType,n.artifact_type,n.type,n.kind,s.type,o?"image":"file"),d=Bn(n,s,l,o),f=d?tr(o,c):c;if(d){let N=x(n.dataUrl,s.dataUrl),_=N.startsWith("data:")?N:"",y=x(n.imageUrl,n.previewUrl,n.fileUrl,n.downloadUrl,n.url,n.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),E=er(n.result??s.result,f)||_||Kt(o,f,t)||Kt(y,f,t);E&&(E.startsWith("data:")&&(s.dataUrl||=E),s.imageUrl||=E,s.previewUrl||=E,s.fileUrl||=E,f&&(s.mimeType||=f))}for(let[N,_]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let y=n[N];y!=null&&y!==""&&!(_ in s)&&(s[_]=y)}let p=x(n.fileUrl,n.downloadUrl,n.imageUrl,n.dataUrl,n.url,n.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),g=x(n.previewUrl,n.imageUrl,n.dataUrl,n.url,n.fileUrl,n.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),m=x(n.dataUrl,s.dataUrl,p.startsWith("data:")?p:"",g.startsWith("data:")?g:""),S=x(n.filename,i.filename,o?Ye(o):""),O=x(n.fieldKey,n.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...n,artifactType:l,type:n.type||l,fieldKey:O,title:x(n.title,S,"Runtime artifact"),summary:x(n.summary,s.prompt,n.title,S,"Runtime artifact"),content:s,dataUrl:m||void 0,fileUrl:p||void 0,previewUrl:g||void 0,metadata:{...i,source:x(i.source,r),savedPath:o||i.savedPath,filename:S||i.filename,mimeType:f||i.mimeType}}}function Et(e,t){if(!t||!e)return;let r=u(t.metadata)?t.metadata:{},n=x(r.savedPath,r.callId,t.previewUrl,t.fileUrl)||Xe(),s=e.get(n);if(!s){e.set(n,t);return}s.content={...u(s.content)?s.content:{},...u(t.content)?t.content:{}},s.metadata={...u(s.metadata)?s.metadata:{},...r},s.previewUrl=t.previewUrl||s.previewUrl,s.fileUrl=t.fileUrl||s.fileUrl,s.summary=t.summary||s.summary,s.title=t.title||s.title}function Vt(e,t,r={}){for(let n of qn(e))Et(t,jn(n,r))}function Wt(e){if(!u(e)||!u(e.payload))return u(e)?e:{value:e};let t=a(e.payload.type);if(t!=="image_generation_end"&&t!=="image_generation_call")return e;let r={...e.payload};return typeof r.result=="string"&&r.result&&(r.result="<omitted>",r.resultLength=e.payload.result.length),{...e,payload:r}}function Je(e,t,r){if(!u(e))return e;let n=u(e.event)?e.event:null;return n?(Et(t,zt(n,r)),{...e,event:Wt(n)}):e}function rr(e,t,r={}){if(!u(e))return e;Vt(e,t,r);let n=Je(e,t,r),s=u(n.update)?Je(n.update,t,r):null;return s&&s!==n.update&&(n={...n,update:s}),n}function nr(e,t,r={}){let n=u(e)?{...e}:{};Vt(n,t,r),Vt(u(n.output)?n.output:{},t,r);let s=[...t?.values?.()||[]];return s.length&&(n._artifacts=s),delete n.artifacts,n}var Q=class{constructor(t,r,n={},s={}){this.agent=t,this.target=r,this.callbacks=n,this.options=s,this.proc=null,this.launch=null,this.launchCleanup=null,this.permissionHandlers=new Map}async ensureStarted(){if(this.proc)return;let t=a(this.target.command);if(!t)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let r={command:t,args:C(this.target.args),cwd:a(this.target.cwd)||this.agent.workspace||process.cwd(),environment:u(this.target.env)?this.target.env:{}},n=this.options.prepareLaunch?await this.options.prepareLaunch(r):{...r,environment:{...process.env,...r.environment},cleanup:async()=>{}};this.launch=n,this.launchCleanup=n.cleanup,this.proc=new Rt({command:n.command,args:n.args,cwd:n.cwd,env:n.environment,label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:a(this.target.framing||"line")}),this.proc.onRequest("session/request_permission",s=>this.handlePermissionRequest(s)),this.proc.onRequest("session/requestPermission",s=>this.handlePermissionRequest(s));try{await this.proc.start({initialize:this.target.initialize!==!1,initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:Y},...u(this.target.initializeParams)?this.target.initializeParams:{}}})}catch(s){throw this.proc=null,await this.cleanupLaunch(),s}}async sessionNew(t={}){return await this.ensureStarted(),this.proc.call("session/new",this.sessionNewParams(t))}sessionNewParams(t={}){let r=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return{...t,mcpServers:r}}async sessionPrompt(t,r){await this.ensureStarted();let n=a(t.sessionId),s=new Map,i=this.artifactOptions(),o=this.proc.onNotification("session/update",l=>{let d=a(l.sessionId);(!d||d===n)&&r(rr(l,s,i))}),c=async l=>this.callbacks.onPermissionRequest?.({agent:this.agent,runtimeSessionId:n,request:l,emitUpdate:r})||{outcome:"denied",reason:"permission handler is not configured"};n&&this.permissionHandlers.set(n,c),this.permissionHandlers.set("*",c);try{let l=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return nr(l,s,i)}finally{o(),n&&this.permissionHandlers.delete(n),this.permissionHandlers.delete("*")}}async sessionCancel(t){return await this.ensureStarted(),this.proc.call("session/cancel",t,5e3).catch(()=>({ok:!0}))}async handlePermissionRequest(t){let r=a(t.sessionId),n=this.permissionHandlers.get(r)||this.permissionHandlers.get("*");return n?n(t):{outcome:"denied",reason:"no active Orcha permission handler"}}artifactSource(){return a(this.target.type||"acp")==="openclaw"?"openclaw_image_generation":"acp_runtime_image_generation"}artifactOptions(){let t=u(this.target.env)?this.target.env:{};return{source:this.artifactSource(),trustedFileRoots:[a(this.launch?.artifactDirectory),a(this.launch?.homeDirectory),a(this.target.artifactRoot),a(this.target.artifactDir),a(this.target.runtimeArtifactRoot),a(t.ORCHA_RUNTIME_ARTIFACT_DIR),...C(this.target.trustedArtifactRoots),...C(this.target.trustedFileRoots),...C(this.target.artifactRoots),...C(this.target.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(this.launch?.pathMappings)?this.launch.pathMappings:[]}}async stop(t){try{await this.proc?.stop(t)}finally{this.proc=null,await this.cleanupLaunch()}}async cleanupLaunch(){let t=this.launchCleanup;this.launchCleanup=null,this.launch=null,await t?.()}};function Gn(e){let t=u(e.metadata)?e.metadata:{};return a(t.agentCode)}function Kn(e,t){let r=Gn(e);return r?`agent:${r}:${t}`:`orcha-${t}`}var wt=class extends Q{constructor(t,r,n,s={},i={}){let o=a(n).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",c=a(r.command)||"openclaw",l=Array.isArray(r.args)?r.args.map(String):[],d=l.length>0?l:["acp","--session",Kn(t,o)];super(t,{...r,command:c,args:d},s,i)}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as ur}from"node:child_process";import{randomUUID as Z}from"node:crypto";import{existsSync as lr,mkdirSync as Vn,readdirSync as dr,readFileSync as fr,realpathSync as lt,rmSync as zn,rmdirSync as Wn,statSync as Jn,unlinkSync as Xn}from"node:fs";import{homedir as Yn,tmpdir as pr}from"node:os";import{basename as Zt,dirname as Qn,join as L,resolve as sr}from"node:path";var Zn=36e5,mr=5e3,ts=2*60*1e3,es=2*60*1e3,rs=12,ns=1e3,ss=1500,is=1e3,It=24*60*60*1e3,ut=new Set(["final_answer","final","complete","completed","done"]),os=new Set(["function_call","function_call_output","custom_tool_call","custom_tool_call_output","local_shell_call","local_shell_call_output","mcp_tool_call","mcp_tool_call_output","web_search_call","image_generation_call","image_generation_end"]),as=new Set(["context_compacted","context_compaction","context_compressed"]);function xt(e,t){if(e?.pid){if(process.platform==="win32"){let r=["/PID",String(e.pid),"/T"];t==="SIGKILL"&&r.push("/F");try{ur("taskkill",r,{stdio:"ignore",windowsHide:!0}).unref?.()}catch{try{e.kill(t)}catch{}}return}try{process.kill(-e.pid,t)}catch(r){if(r?.code==="ESRCH")return;try{e.kill(t)}catch{}}}}function Jt(e){xt(e,"SIGTERM");let t=setTimeout(()=>xt(e,"SIGKILL"),mr);return t.unref?.(),t}function P(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>P(t)).join("");if(!u(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let r=P(e[t]);if(r)return r}return""}function hr(e){if(!u(e))return"";let t=u(e.payload)?e.payload:{};if(a(e.type)==="event_msg"){if(a(t.type)==="agent_message")return a(t.message);if(a(t.type)==="task_complete")return a(t.last_agent_message)}if(a(e.type)==="response_item"&&a(t.type)==="message"&&a(t.role)==="assistant")return P(t.content)||P(t.message);if(a(e.type)==="result")return P(e.result);let r=P(e.delta)||P(e.text)||P(e.content);if(r)return r;let n=u(e.item)?e.item:{};return["message","agent_message"].includes(a(n.type))||a(n.role)==="assistant"?P(n.content)||P(n.text)||P(n.message):""}function gr(e,t={}){return zt(e,{source:"codex_cli_image_generation",...t})}function _r(e,t){Et(e.artifacts,t)}function Tr(e){return G(Wt(e))}function te(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type);if(r==="event_msg"&&n==="task_complete")return!0;let s=a(t.phase||t.status||t.stage).toLowerCase();if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&a(t.role)==="assistant")return ut.has(s);let i=u(e.item)?e.item:{};return r==="item.completed"&&a(i.type)==="agent_message"?!0:r==="result"&&e.is_error!==!0?a(e.result).length>0:!1}function cs(e){let t=a(e.terminalProtocol||e.eventProtocol).toLowerCase();if(t)return t;let r=Zt(a(e.command)).replace(/\.exe$/i,"").toLowerCase();return r==="codex"||r==="claude"?r:""}function ir(e,t,r){let n=u(t.error)?t.error:{},s=a(n.message)||P(t.error)||a(t.result)||a(t.message)||r;return Object.assign(new Error(s),{code:e})}function us(e,t){if(!u(e))return null;let r=a(e.type).toLowerCase();if(t==="codex")return r==="turn.completed"?{status:"completed",result:{stopReason:"end_turn"}}:r==="turn.failed"?{status:"failed",error:ir("RUNTIME_CODEX_TURN_FAILED",e,"Codex turn failed")}:null;if(t==="claude"&&r==="result"){let n=a(e.subtype).toLowerCase();return e.is_error===!0||n.startsWith("error")||["failed","failure"].includes(n)?{status:"failed",error:ir("RUNTIME_CLAUDE_RESULT_FAILED",e,"Claude result failed")}:{status:"completed",result:{stopReason:"end_turn",...a(e.result)?{output:a(e.result)}:{}}}}return null}function or(e){return u(e)?a(e.phase||e.status||e.stage).toLowerCase():""}function ls(e){if(!u(e)||te(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type),s=or(t);if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&a(t.role)==="assistant")return!!(s&&!ut.has(s));let i=u(e.item)?e.item:{},o=or(i);return a(i.role)==="assistant"||a(i.type)==="message"?!!(o&&!ut.has(o)):!1}function ds(e,t,r){return r.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:r.captureLastMessage===!0?!0:Zt(e)==="codex"}function fs(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:Zt(e)==="codex"}function yr(e){return Math.max(20,T(e.codexTranscriptPollMs||e.transcriptPollMs,ns))}function ps(e){return Math.max(0,T(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,ss))}function At(e){if(typeof e=="boolean")return e;let t=a(e).toLowerCase();return["true","1","yes","y","on"].includes(t)?!0:["false","0","no","n","off"].includes(t)?!1:null}function ee(e){let t=u(e?.metadata)?e.metadata:{};return u(t._runtimeBridge)?t._runtimeBridge:{}}function Xt(e){return a(ee(e).promptKind).toLowerCase()}function ms(e,t){for(let r of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let n=At(r);if(n!=null)return n}return Xt(t)==="chat"}function hs(e,t){let r=ee(e);for(let s of[r.emitThoughtChunks,r.streamThoughts]){let i=At(s);if(i!=null)return i}let n=Xt(e);if(n&&n!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=At(s);if(i!=null)return i}return Xt(e)==="chat"}function gs(e){let t=ee(e);for(let r of[t.finalTextOnly,t.finalOutputOnly]){let n=At(r);if(n!=null)return n}return null}function _s(e,t){let r=gs(e);return r??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function Ts(e,t){return!e.finalTextOnly||t}function Rr(e,t,r,n,s=n){return!n||e.emittedTexts.has(s)?!1:(e.emittedTexts.add(s),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}}),!0)}function Sr(e,t,r,n){return!n||e.emittedThoughtTexts.has(n)?!1:(e.emittedThoughtTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}}}),!0)}function ys(e,t,r,n=new Set){return{target:e,promptText:t,startedAtMs:r,baselinePaths:n,matchedPath:"",disabled:!1,processedLines:new Map}}function Rs(e,t){let r=u(e.env)?e.env:{},n=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||r.ORCHA_RUNTIME_ARTIFACT_DIR)||L(pr(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||Z(),i=L(n,s),o=L(i,Z());return Vn(o,{recursive:!0}),{root:o,realRoot:lt(o),sessionRoot:i,realSessionRoot:lt(i)}}function Ss(e){let t=a(e?.artifactDirectory);if(!t)throw new Error("sandbox launch did not provide an artifact directory");return{root:t,realRoot:lt(t),sessionRoot:"",realSessionRoot:""}}function Er(e){return a(u(e)?e.root:e)}function ar(e){let t=Er(e),r=a(u(e)?e.sessionRoot:Qn(t)),n=a(u(e)?e.realSessionRoot:"");if(r)try{if(n&&lt(r)!==n)return;Wn(r)}catch{}}function Es(e,t={}){let r=Er(e),n=a(u(e)?e.realRoot:"");if(r){try{if(n&&lt(r)!==n){h("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:r});return}}catch{ar(e);return}try{zn(r,{recursive:!0,force:!0})}catch(s){h("warn","runtime.cli","runtime artifact directory cleanup failed",{...t,artifactRoot:r,error:String(s?.message||s)});return}ar(e)}}function ws(e,t,r=null){return{trustedFileRoots:[t,a(r?.artifactDirectory),a(r?.homeDirectory),...C(e.trustedArtifactRoots),...C(e.trustedFileRoots),...C(e.artifactRoots),...C(e.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(r?.pathMappings)?r.pathMappings:[]}}function wr(e){let t=a(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let r=u(e.env)?e.env:{},n=a(e.codexHome||r.CODEX_HOME||process.env.CODEX_HOME)||L(Yn(),".codex");return L(n,"sessions")}function Is(e,t){let r=new Date(t),n=String(r.getFullYear()),s=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");return L(e,n,s,i)}function Ir(e,t,r){let n=new Set;for(let s of[t-It,t,t+It,r-It,r,r+It])n.add(Is(e,s));return[...n].filter(s=>lr(s))}function Os(e,t,r){let n=wr(e),s=t-ts,i=r+es,o=[];for(let c of Ir(n,t,r)){let l=[];try{l=dr(c)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=L(c,d);try{let p=Jn(f);if(!p.isFile()||p.mtimeMs<s||p.mtimeMs>i)continue;o.push({path:f,mtimeMs:p.mtimeMs})}catch{}}}return o.sort((c,l)=>l.mtimeMs-c.mtimeMs).slice(0,rs)}function xs(e,t,r=t){let n=wr(e),s=new Set;for(let i of Ir(n,t,r)){let o=[];try{o=dr(i)}catch{continue}for(let c of o)c.endsWith(".jsonl")&&s.add(L(i,c))}return s}function Yt(e,t,r=0){if(!(r>8||e===null||e===void 0)){if(typeof e=="string"){e&&t.push(e);return}if(Array.isArray(e)){for(let n of e)Yt(n,t,r+1);return}if(u(e))for(let n of["payload","item","text","delta","output_text","content","message","output","input","prompt","last_agent_message","revised_prompt"])n in e&&Yt(e[n],t,r+1)}}function Or(e){return a(e).replace(/\s+/g," ")}function As(e){let t=Or(e);if(!t)return[];if(t.length<=200)return[t];let r=160,n=[0,Math.floor((t.length-r)/2),t.length-r],s=new Set,i=[];for(let o of n){let c=t.slice(Math.max(0,o),Math.max(0,o)+r).trim();c.length>=40&&!s.has(c)&&(s.add(c),i.push(c))}return i}function Cs(e,t){let r=As(t);if(!r.length)return!1;let n=[];for(let i of e)Yt(i,n);let s=Or(n.join(" "));return r.every(i=>s.includes(i))}function Ns(e){return e.find(t=>u(t)&&a(t.type)==="session_meta"&&u(t.payload))||null}function bs(e){let t=u(e?.payload)?e.payload:{},r=a(e?.timestamp||t.timestamp),n=Date.parse(r);return Number.isFinite(n)?n:Number.NaN}function Ms(e){let t=a(e.originator),r=a(e.source);if(t!=="codex_exec"&&r!=="exec"||a(e.parent_thread_id))return!1;let n=a(e.thread_source);if(n&&n!=="user")return!1;let s=a(e.session_id),i=a(e.id);return!(s&&i&&s!==i)}function Us(e,t,r){if(!Cs(e,t.promptText))return!1;let n=Ns(e);if(!n)return!1;let s=n.payload;if(!Ms(s))return!1;let i=bs(n);if(!Number.isFinite(i)||i<t.startedAtMs-5e3||i>r+5e3)return!1;let o=a(t.target.cwd),c=a(s.cwd);return!(o&&c&&sr(o)!==sr(c))}function cr(e){try{return ks(fr(e,"utf8"))}catch{return null}}function Ps(e,t,r){if(!e||e.disabled)return null;if(e.matchedPath){let s=cr(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let n=[];for(let s of Os(e.target,e.startedAtMs,r)){if(e.baselinePaths.has(s.path))continue;let i=cr(s.path);!i||!Us(i,e,r)||n.push({path:s.path,events:i})}return n.length!==1?(n.length>1&&(e.disabled=!0,h("warn","runtime.cli","codex transcript fallback disabled; multiple matching transcripts",{target:e.target.targetCode,sessionId:t,transcriptCount:n.length})),null):(e.matchedPath=n[0].path,h("info","runtime.cli","codex transcript stream attached",{target:e.target.targetCode,sessionId:t}),n[0])}function ks(e){let t=[];for(let r of e.split(/\r?\n/)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}function Ls(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type);return r==="event_msg"&&n==="image_generation_end"||r==="response_item"&&n==="image_generation_call"}function Ds(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return a(e.type)==="response_item"&&os.has(a(t.type))}function vs(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return as.has(a(t.type))}function Fs(e,t,r,n){let s=hr(e),i=te(e),o=0,c=0,l=0;if(s&&!i&&t.emitThoughtChunks&&Sr(t,r,n,s)&&(l=1),s&&i){let d=t.emittedTexts.size?`
8
+ `;this.child.stdin.write(s,r)}onNotification(t,r){let n=this.notificationHandlers.get(t)||new Set;return n.add(r),this.notificationHandlers.set(t,n),()=>{n.delete(r),n.size===0&&this.notificationHandlers.delete(t)}}onRequest(t,r){return this.requestHandlers.set(t,r),()=>this.requestHandlers.delete(t)}onExit(t){return this.exitHandlers.add(t),()=>this.exitHandlers.delete(t)}rejectAll(t){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(t);this.pending.clear()}handleExit(t,r){this.exited=!0,this.exitCode=t,this.exitSignal=r,this.rejectAll(new Error(`runtime exited before response (${t}/${r})`));for(let n of this.exitHandlers)n(t,r)}async waitForExit(t=5e3){return!this.child||this.exited?!0:await new Promise(r=>{let n=setTimeout(()=>{s(),r(!1)},t);n.unref?.();let s=()=>{clearTimeout(n),this.exitHandlers.delete(i)},i=()=>{s(),r(!0)};this.exitHandlers.add(i),this.exited&&i()})}signal(t){if(!this.child||this.exited)return!1;let r=this.child.pid;if(!r)return!1;try{return this.detached&&process.platform!=="win32"?process.kill(-r,t):this.child.kill(t),!0}catch(n){if(n?.code==="ESRCH")return this.exited=!0,!1;try{return this.child.kill(t),!0}catch(s){return s?.code!=="ESRCH"&&h("warn","runtime","runtime signal failed",{target:this.label,pid:r,signal:t,error:String(s)}),!1}}}async stop(t="stop",{termTimeoutMs:r=5e3,killTimeoutMs:n=2e3}={}){if(!(!this.child||this.exited)){if(this.stopPromise)return await this.stopPromise;this.stopPromise=(async()=>{if(!this.child||this.exited)return;let s=this.child.pid;h("info","runtime","stopping runtime",{target:this.label,reason:t,pid:s}),this.rejectAll(new Error(`runtime stopped: ${t}`)),this.signal("SIGTERM"),!await this.waitForExit(r)&&this.child&&!this.exited&&(h("warn","runtime","runtime did not exit after SIGTERM; force killing",{target:this.label,reason:t,pid:s}),this.signal("SIGKILL"),await this.waitForExit(n))})();try{await this.stopPromise}finally{this.stopPromise=null}}}};import{randomUUID as sr}from"node:crypto";import{existsSync as Hn,readFileSync as $n,realpathSync as er,statSync as Bn}from"node:fs";import{basename as ir,extname as or,isAbsolute as ut,join as qn,relative as ar,resolve as rr}from"node:path";var jn=25*1024*1024;function cr(e,t=""){let r=a(t);if(r)return r;let n=or(a(e)).toLowerCase();return n===".jpg"||n===".jpeg"?"image/jpeg":n===".webp"?"image/webp":n===".gif"?"image/gif":"image/png"}function ur(e,t){let r=typeof e=="string"?e.trim():"";return!r||r==="<omitted>"?"":r.startsWith("data:")?r:`data:${t};base64,${r.replace(/\s+/g,"")}`}function xt(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function Gn(e,t){let r=ar(t,e);return r===""||!!r&&!r.startsWith("..")&&!ut(r)}function Kn(e,t){let r=a(e);if(!r||!Hn(r))return"";try{let n=er(r);for(let s of t)try{let i=er(s);if(Gn(n,i))return n}catch{}}catch{return""}return""}function Vn(e,t){let r=a(e);if(!r||!ut(r))return r;for(let n of Array.isArray(t)?t:[]){if(!u(n))continue;let s=a(n.runtimeRoot),i=a(n.hostRoot);if(!s||!i||!ut(s)||!ut(i))continue;let o=ar(rr(s),rr(r));if(o===""||!o.startsWith("..")&&!ut(o))return o?qn(i,o):i}return r}function Xt(e,t,r={}){let n=a(e);return!n||n.startsWith("data:")||/^https?:\/\//i.test(n)?n:zn(n,t,r)}function zn(e,t,r={}){let n=[...xt(r.trustedFileRoots),...xt(r.trustedFileRoot),...xt(r.artifactRoots),...xt(r.artifactRoot)],s=Kn(Vn(e,r.pathMappings),n);if(!s)return"";try{let i=Bn(s);return!i.isFile()||i.size<=0||i.size>jn?"":`data:${t};base64,${$n(s).toString("base64")}`}catch{return""}}function x(...e){for(let t of e){let r=a(t);if(r)return r}return""}function Wn(e,t,r,n){let s=r.toLowerCase();if(s==="image"||s==="picture")return!0;let i=x(n,e.previewUrl,e.fileUrl,e.imageUrl,e.dataUrl,e.url,e.uri,t.previewUrl,t.fileUrl,t.imageUrl,t.dataUrl,t.url,t.uri),o=or(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function Zt(e,t={}){let{source:r="runtime_image_generation_event"}=t;if(!u(e))return null;let n=u(e.payload)?e.payload:{},s=a(e.type),i=a(n.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let o=x(n.call_id,n.id),c=x(n.saved_path,n.savedPath),l=x(n.revised_prompt,n.revisedPrompt),d=cr(c,n.mimeType||n.mime_type),f=ur(n.result,d)||Xt(c,d,t);if(!f)return null;let p=f.startsWith("data:")?f:"",_=c?ir(c):`${o||sr()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:_||"Generated image",summary:l||"Generated image",content:{prompt:l||void 0,dataUrl:p||void 0,imageUrl:f,previewUrl:f,fileUrl:f,mimeType:d},dataUrl:p||void 0,previewUrl:f,fileUrl:f,metadata:{source:r,eventType:i,callId:o||void 0,savedPath:c||void 0,filename:_,mimeType:d,revisedPrompt:l||void 0}}}function Jn(e){let t=u(e)?e:{},r=[];for(let n of["_artifacts","artifacts"]){let s=t[n];Array.isArray(s)&&r.push(...s)}for(let n of["_artifact","artifact"]){let s=t[n];u(s)&&r.push(s)}return r}function Xn(e,t={}){let{source:r="runtime_artifact"}=t,n=u(e)?e:{};if(!Object.keys(n).length)return null;let s=u(n.content)?{...n.content}:{},i=u(n.metadata)?{...n.metadata}:{},o=x(n.saved_path,n.savedPath,s.saved_path,s.savedPath,i.savedPath),c=x(n.mimeType,n.mime_type,s.mimeType,s.mime_type,i.mimeType),l=x(n.artifactType,n.artifact_type,n.type,n.kind,s.type,o?"image":"file"),d=Wn(n,s,l,o),f=d?cr(o,c):c;if(d){let N=x(n.dataUrl,s.dataUrl),T=N.startsWith("data:")?N:"",y=x(n.imageUrl,n.previewUrl,n.fileUrl,n.downloadUrl,n.url,n.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),E=ur(n.result??s.result,f)||T||Xt(o,f,t)||Xt(y,f,t);E&&(E.startsWith("data:")&&(s.dataUrl||=E),s.imageUrl||=E,s.previewUrl||=E,s.fileUrl||=E,f&&(s.mimeType||=f))}for(let[N,T]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let y=n[N];y!=null&&y!==""&&!(T in s)&&(s[T]=y)}let p=x(n.fileUrl,n.downloadUrl,n.imageUrl,n.dataUrl,n.url,n.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),_=x(n.previewUrl,n.imageUrl,n.dataUrl,n.url,n.fileUrl,n.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),m=x(n.dataUrl,s.dataUrl,p.startsWith("data:")?p:"",_.startsWith("data:")?_:""),R=x(n.filename,i.filename,o?ir(o):""),O=x(n.fieldKey,n.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...n,artifactType:l,type:n.type||l,fieldKey:O,title:x(n.title,R,"Runtime artifact"),summary:x(n.summary,s.prompt,n.title,R,"Runtime artifact"),content:s,dataUrl:m||void 0,fileUrl:p||void 0,previewUrl:_||void 0,metadata:{...i,source:x(i.source,r),savedPath:o||i.savedPath,filename:R||i.filename,mimeType:f||i.mimeType}}}function At(e,t){if(!t||!e)return;let r=u(t.metadata)?t.metadata:{},n=x(r.savedPath,r.callId,t.previewUrl,t.fileUrl)||sr(),s=e.get(n);if(!s){e.set(n,t);return}s.content={...u(s.content)?s.content:{},...u(t.content)?t.content:{}},s.metadata={...u(s.metadata)?s.metadata:{},...r},s.previewUrl=t.previewUrl||s.previewUrl,s.fileUrl=t.fileUrl||s.fileUrl,s.summary=t.summary||s.summary,s.title=t.title||s.title}function Yt(e,t,r={}){for(let n of Jn(e))At(t,Xn(n,r))}function Qt(e){if(!u(e)||!u(e.payload))return u(e)?e:{value:e};let t=a(e.payload.type);if(t!=="image_generation_end"&&t!=="image_generation_call")return e;let r={...e.payload};return typeof r.result=="string"&&r.result&&(r.result="<omitted>",r.resultLength=e.payload.result.length),{...e,payload:r}}function nr(e,t,r){if(!u(e))return e;let n=u(e.event)?e.event:null;return n?(At(t,Zt(n,r)),{...e,event:Qt(n)}):e}function lr(e,t,r={}){if(!u(e))return e;Yt(e,t,r);let n=nr(e,t,r),s=u(n.update)?nr(n.update,t,r):null;return s&&s!==n.update&&(n={...n,update:s}),n}function dr(e,t,r={}){let n=u(e)?{...e}:{};Yt(n,t,r),Yt(u(n.output)?n.output:{},t,r);let s=[...t?.values?.()||[]];return s.length&&(n._artifacts=s),delete n.artifacts,n}function fr(e,t){let r=g(e,t);return r>0?r:t}var Q=class{constructor(t,r,n={},s={}){this.agent=t,this.target=r,this.callbacks=n,this.options=s,this.proc=null,this.launch=null,this.launchCleanup=null,this.permissionHandlers=new Map}async ensureStarted(){if(this.proc)return;let t=a(this.target.command);if(!t)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let r={command:t,args:C(this.target.args),cwd:Z(this.target,this.agent.workspace),environment:u(this.target.env)?this.target.env:{}},n=this.options.prepareLaunch?await this.options.prepareLaunch(r):{...r,environment:{...process.env,...r.environment},cleanup:async()=>{}};this.launch=n,this.launchCleanup=n.cleanup,this.proc=new Ot({command:n.command,args:n.args,cwd:n.cwd,env:n.environment,label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:a(this.target.framing||"line")}),this.proc.onRequest("session/request_permission",s=>this.handlePermissionRequest(s)),this.proc.onRequest("session/requestPermission",s=>this.handlePermissionRequest(s));try{await this.proc.start({initialize:this.target.initialize!==!1,initializeTimeoutMs:fr(this.target.initializeTimeoutMs,fr(this.options.initializeTimeoutMs,3e4)),initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:Y},...u(this.target.initializeParams)?this.target.initializeParams:{}}})}catch(s){throw await this.proc?.stop("runtime startup failed"),this.proc=null,await this.cleanupLaunch(),s}}async sessionNew(t={}){return await this.ensureStarted(),this.proc.call("session/new",this.sessionNewParams(t))}sessionNewParams(t={}){let r=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return{...t,mcpServers:r}}async sessionPrompt(t,r){await this.ensureStarted();let n=a(t.sessionId),s=new Map,i=this.artifactOptions(),o=this.proc.onNotification("session/update",l=>{let d=a(l.sessionId);(!d||d===n)&&r(lr(l,s,i))}),c=async l=>this.callbacks.onPermissionRequest?.({agent:this.agent,runtimeSessionId:n,request:l,emitUpdate:r})||{outcome:"denied",reason:"permission handler is not configured"};n&&this.permissionHandlers.set(n,c),this.permissionHandlers.set("*",c);try{let l=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return dr(l,s,i)}finally{o(),n&&this.permissionHandlers.delete(n),this.permissionHandlers.delete("*")}}async sessionCancel(t){return await this.ensureStarted(),this.proc.call("session/cancel",t,5e3).catch(()=>({ok:!0}))}async handlePermissionRequest(t){let r=a(t.sessionId),n=this.permissionHandlers.get(r)||this.permissionHandlers.get("*");return n?n(t):{outcome:"denied",reason:"no active Orcha permission handler"}}artifactSource(){return a(this.target.type||"acp")==="openclaw"?"openclaw_image_generation":"acp_runtime_image_generation"}artifactOptions(){let t=u(this.target.env)?this.target.env:{};return{source:this.artifactSource(),trustedFileRoots:[a(this.launch?.artifactDirectory),a(this.launch?.homeDirectory),a(this.target.artifactRoot),a(this.target.artifactDir),a(this.target.runtimeArtifactRoot),a(t.ORCHA_RUNTIME_ARTIFACT_DIR),...C(this.target.trustedArtifactRoots),...C(this.target.trustedFileRoots),...C(this.target.artifactRoots),...C(this.target.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(this.launch?.pathMappings)?this.launch.pathMappings:[]}}async stop(t){try{await this.proc?.stop(t)}finally{this.proc=null,await this.cleanupLaunch()}}async cleanupLaunch(){let t=this.launchCleanup;this.launchCleanup=null,this.launch=null,await t?.()}};function Yn(e){let t=u(e.metadata)?e.metadata:{};return a(t.agentCode)}function Zn(e,t){let r=Yn(e);return r?`agent:${r}:${t}`:`orcha-${t}`}var Ct=class extends Q{constructor(t,r,n,s={},i={}){let o=a(n).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",c=a(r.command)||"openclaw",l=Array.isArray(r.args)?r.args.map(String):[],d=l.length>0?l:["acp","--session",Zn(t,o)];super(t,{...r,command:c,args:d},s,i)}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as Tr}from"node:child_process";import{randomUUID as tt}from"node:crypto";import{existsSync as yr,mkdirSync as Qn,readdirSync as Rr,readFileSync as Sr,realpathSync as dt,rmSync as ts,rmdirSync as es,statSync as rs,unlinkSync as ns}from"node:fs";import{homedir as ss,tmpdir as Er}from"node:os";import{basename as se,dirname as is,join as L,resolve as mr}from"node:path";var os=36e5,wr=5e3,as=2*60*1e3,cs=2*60*1e3,us=12,ls=1e3,ds=1500,fs=1e3,Nt=24*60*60*1e3,lt=new Set(["final_answer","final","complete","completed","done"]),ms=new Set(["function_call","function_call_output","custom_tool_call","custom_tool_call_output","local_shell_call","local_shell_call_output","mcp_tool_call","mcp_tool_call_output","web_search_call","image_generation_call","image_generation_end"]),ps=new Set(["context_compacted","context_compaction","context_compressed"]);function Mt(e,t){if(e?.pid){if(process.platform==="win32"){let r=["/PID",String(e.pid),"/T"];t==="SIGKILL"&&r.push("/F");try{Tr("taskkill",r,{stdio:"ignore",windowsHide:!0}).unref?.()}catch{try{e.kill(t)}catch{}}return}try{process.kill(-e.pid,t)}catch(r){if(r?.code==="ESRCH")return;try{e.kill(t)}catch{}}}}function te(e){Mt(e,"SIGTERM");let t=setTimeout(()=>Mt(e,"SIGKILL"),wr);return t.unref?.(),t}function P(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>P(t)).join("");if(!u(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let r=P(e[t]);if(r)return r}return""}function Ir(e){if(!u(e))return"";let t=u(e.payload)?e.payload:{};if(a(e.type)==="event_msg"){if(a(t.type)==="agent_message")return a(t.message);if(a(t.type)==="task_complete")return a(t.last_agent_message)}if(a(e.type)==="response_item"&&a(t.type)==="message"&&a(t.role)==="assistant")return P(t.content)||P(t.message);if(a(e.type)==="result")return P(e.result);let r=P(e.delta)||P(e.text)||P(e.content);if(r)return r;let n=u(e.item)?e.item:{};return["message","agent_message"].includes(a(n.type))||a(n.role)==="assistant"?P(n.content)||P(n.text)||P(n.message):""}function Or(e,t={}){return Zt(e,{source:"codex_cli_image_generation",...t})}function xr(e,t){At(e.artifacts,t)}function Ar(e){return G(Qt(e))}function ie(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type);if(r==="event_msg"&&n==="task_complete")return!0;let s=a(t.phase||t.status||t.stage).toLowerCase();if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&a(t.role)==="assistant")return lt.has(s);let i=u(e.item)?e.item:{};return r==="item.completed"&&a(i.type)==="agent_message"?!0:r==="result"&&e.is_error!==!0?a(e.result).length>0:!1}function hs(e){let t=a(e.terminalProtocol||e.eventProtocol).toLowerCase();if(t)return t;let r=se(a(e.command)).replace(/\.exe$/i,"").toLowerCase();return r==="codex"||r==="claude"?r:""}function pr(e,t,r){let n=u(t.error)?t.error:{},s=a(n.message)||P(t.error)||a(t.result)||a(t.message)||r;return Object.assign(new Error(s),{code:e})}function gs(e,t){if(!u(e))return null;let r=a(e.type).toLowerCase();if(t==="codex")return r==="turn.completed"?{status:"completed",result:{stopReason:"end_turn"}}:r==="turn.failed"?{status:"failed",error:pr("RUNTIME_CODEX_TURN_FAILED",e,"Codex turn failed")}:null;if(t==="claude"&&r==="result"){let n=a(e.subtype).toLowerCase();return e.is_error===!0||n.startsWith("error")||["failed","failure"].includes(n)?{status:"failed",error:pr("RUNTIME_CLAUDE_RESULT_FAILED",e,"Claude result failed")}:{status:"completed",result:{stopReason:"end_turn",...a(e.result)?{output:a(e.result)}:{}}}}return null}function hr(e){return u(e)?a(e.phase||e.status||e.stage).toLowerCase():""}function _s(e){if(!u(e)||ie(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type),s=hr(t);if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&a(t.role)==="assistant")return!!(s&&!lt.has(s));let i=u(e.item)?e.item:{},o=hr(i);return a(i.role)==="assistant"||a(i.type)==="message"?!!(o&&!lt.has(o)):!1}function Ts(e,t,r){return r.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:r.captureLastMessage===!0?!0:se(e)==="codex"}function ys(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:se(e)==="codex"}function Cr(e){return Math.max(20,g(e.codexTranscriptPollMs||e.transcriptPollMs,ls))}function Rs(e){return Math.max(0,g(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,ds))}function Ut(e){if(typeof e=="boolean")return e;let t=a(e).toLowerCase();return["true","1","yes","y","on"].includes(t)?!0:["false","0","no","n","off"].includes(t)?!1:null}function oe(e){let t=u(e?.metadata)?e.metadata:{};return u(t._runtimeBridge)?t._runtimeBridge:{}}function ee(e){return a(oe(e).promptKind).toLowerCase()}function Ss(e,t){for(let r of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let n=Ut(r);if(n!=null)return n}return ee(t)==="chat"}function Es(e,t){let r=oe(e);for(let s of[r.emitThoughtChunks,r.streamThoughts]){let i=Ut(s);if(i!=null)return i}let n=ee(e);if(n&&n!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=Ut(s);if(i!=null)return i}return ee(e)==="chat"}function ws(e){let t=oe(e);for(let r of[t.finalTextOnly,t.finalOutputOnly]){let n=Ut(r);if(n!=null)return n}return null}function Is(e,t){let r=ws(e);return r??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function Os(e,t){return!e.finalTextOnly||t}function Nr(e,t,r,n,s=n){return!n||e.emittedTexts.has(s)?!1:(e.emittedTexts.add(s),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}}),!0)}function br(e,t,r,n){return!n||e.emittedThoughtTexts.has(n)?!1:(e.emittedThoughtTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}}}),!0)}function xs(e,t,r,n=new Set){return{target:e,promptText:t,startedAtMs:r,baselinePaths:n,matchedPath:"",disabled:!1,processedLines:new Map}}function As(e,t){let r=u(e.env)?e.env:{},n=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||r.ORCHA_RUNTIME_ARTIFACT_DIR)||L(Er(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||tt(),i=L(n,s),o=L(i,tt());return Qn(o,{recursive:!0}),{root:o,realRoot:dt(o),sessionRoot:i,realSessionRoot:dt(i)}}function Cs(e){let t=a(e?.artifactDirectory);if(!t)throw new Error("sandbox launch did not provide an artifact directory");return{root:t,realRoot:dt(t),sessionRoot:"",realSessionRoot:""}}function Mr(e){return a(u(e)?e.root:e)}function gr(e){let t=Mr(e),r=a(u(e)?e.sessionRoot:is(t)),n=a(u(e)?e.realSessionRoot:"");if(r)try{if(n&&dt(r)!==n)return;es(r)}catch{}}function Ns(e,t={}){let r=Mr(e),n=a(u(e)?e.realRoot:"");if(r){try{if(n&&dt(r)!==n){h("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:r});return}}catch{gr(e);return}try{ts(r,{recursive:!0,force:!0})}catch(s){h("warn","runtime.cli","runtime artifact directory cleanup failed",{...t,artifactRoot:r,error:String(s?.message||s)});return}gr(e)}}function bs(e,t,r=null){return{trustedFileRoots:[t,a(r?.artifactDirectory),a(r?.homeDirectory),...C(e.trustedArtifactRoots),...C(e.trustedFileRoots),...C(e.artifactRoots),...C(e.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(r?.pathMappings)?r.pathMappings:[]}}function Ur(e){let t=a(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let r=u(e.env)?e.env:{},n=a(e.codexHome||r.CODEX_HOME||process.env.CODEX_HOME)||L(ss(),".codex");return L(n,"sessions")}function Ms(e,t){let r=new Date(t),n=String(r.getFullYear()),s=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");return L(e,n,s,i)}function Pr(e,t,r){let n=new Set;for(let s of[t-Nt,t,t+Nt,r-Nt,r,r+Nt])n.add(Ms(e,s));return[...n].filter(s=>yr(s))}function Us(e,t,r){let n=Ur(e),s=t-as,i=r+cs,o=[];for(let c of Pr(n,t,r)){let l=[];try{l=Rr(c)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=L(c,d);try{let p=rs(f);if(!p.isFile()||p.mtimeMs<s||p.mtimeMs>i)continue;o.push({path:f,mtimeMs:p.mtimeMs})}catch{}}}return o.sort((c,l)=>l.mtimeMs-c.mtimeMs).slice(0,us)}function Ps(e,t,r=t){let n=Ur(e),s=new Set;for(let i of Pr(n,t,r)){let o=[];try{o=Rr(i)}catch{continue}for(let c of o)c.endsWith(".jsonl")&&s.add(L(i,c))}return s}function re(e,t,r=0){if(!(r>8||e===null||e===void 0)){if(typeof e=="string"){e&&t.push(e);return}if(Array.isArray(e)){for(let n of e)re(n,t,r+1);return}if(u(e))for(let n of["payload","item","text","delta","output_text","content","message","output","input","prompt","last_agent_message","revised_prompt"])n in e&&re(e[n],t,r+1)}}function kr(e){return a(e).replace(/\s+/g," ")}function ks(e){let t=kr(e);if(!t)return[];if(t.length<=200)return[t];let r=160,n=[0,Math.floor((t.length-r)/2),t.length-r],s=new Set,i=[];for(let o of n){let c=t.slice(Math.max(0,o),Math.max(0,o)+r).trim();c.length>=40&&!s.has(c)&&(s.add(c),i.push(c))}return i}function Ls(e,t){let r=ks(t);if(!r.length)return!1;let n=[];for(let i of e)re(i,n);let s=kr(n.join(" "));return r.every(i=>s.includes(i))}function Ds(e){return e.find(t=>u(t)&&a(t.type)==="session_meta"&&u(t.payload))||null}function vs(e){let t=u(e?.payload)?e.payload:{},r=a(e?.timestamp||t.timestamp),n=Date.parse(r);return Number.isFinite(n)?n:Number.NaN}function Fs(e){let t=a(e.originator),r=a(e.source);if(t!=="codex_exec"&&r!=="exec"||a(e.parent_thread_id))return!1;let n=a(e.thread_source);if(n&&n!=="user")return!1;let s=a(e.session_id),i=a(e.id);return!(s&&i&&s!==i)}function Hs(e,t,r){if(!Ls(e,t.promptText))return!1;let n=Ds(e);if(!n)return!1;let s=n.payload;if(!Fs(s))return!1;let i=vs(n);if(!Number.isFinite(i)||i<t.startedAtMs-5e3||i>r+5e3)return!1;let o=a(t.target.cwd),c=a(s.cwd);return!(o&&c&&mr(o)!==mr(c))}function _r(e){try{return Bs(Sr(e,"utf8"))}catch{return null}}function $s(e,t,r){if(!e||e.disabled)return null;if(e.matchedPath){let s=_r(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let n=[];for(let s of Us(e.target,e.startedAtMs,r)){if(e.baselinePaths.has(s.path))continue;let i=_r(s.path);!i||!Hs(i,e,r)||n.push({path:s.path,events:i})}return n.length!==1?(n.length>1&&(e.disabled=!0,h("warn","runtime.cli","codex transcript fallback disabled; multiple matching transcripts",{target:e.target.targetCode,sessionId:t,transcriptCount:n.length})),null):(e.matchedPath=n[0].path,h("info","runtime.cli","codex transcript stream attached",{target:e.target.targetCode,sessionId:t}),n[0])}function Bs(e){let t=[];for(let r of e.split(/\r?\n/)){let n=r.trim();if(n)try{t.push(JSON.parse(n))}catch{}}return t}function qs(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type);return r==="event_msg"&&n==="image_generation_end"||r==="response_item"&&n==="image_generation_call"}function js(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return a(e.type)==="response_item"&&ms.has(a(t.type))}function Gs(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return ps.has(a(t.type))}function Ks(e,t,r,n){let s=Ir(e),i=ie(e),o=0,c=0,l=0;if(s&&!i&&t.emitThoughtChunks&&br(t,r,n,s)&&(l=1),s&&i){let d=t.emittedTexts.size?`
9
9
 
10
- ${s}`:s;Rr(t,r,n,d,s)&&(o=1,c=1)}return s&&i&&(t.finalTextSeen=!0),_r(t,gr(e,t.artifactOptions)),(Ls(e)||Ds(e)||vs(e)||i)&&n({sessionId:r,update:{sessionUpdate:"runtime_event",event:Tr(e)}}),{textCount:o,finalTextCount:c,thoughtCount:l}}function Qt(e,t,r,n,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0,thoughtCount:0};let i=e.artifacts.size,o=0,c=0,l=0,d=0,f=Ps(t,r,s);if(f){let p=Math.min(t.processedLines.get(f.path)||0,f.events.length),g=e.artifacts.size;for(let m of f.events.slice(p)){let S=Fs(m,e,r,n);c+=S.textCount,l+=S.finalTextCount,d+=S.thoughtCount}t.processedLines.set(f.path,f.events.length),(f.events.length>p||e.artifacts.size>g)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:c,finalTextCount:l,thoughtCount:d}}function Hs(e,{remove:t=!0}={}){if(!e||!lr(e))return"";try{return fr(e,"utf8").trim()}catch{return""}finally{t&&Ot(e)}}function Ot(e){if(e)try{Xn(e)}catch{}}function $s(e,t){return{artifactCount:(e?.artifactCount||0)+(t?.artifactCount||0),transcriptCount:(e?.transcriptCount||0)+(t?.transcriptCount||0),textCount:(e?.textCount||0)+(t?.textCount||0),finalTextCount:(e?.finalTextCount||0)+(t?.finalTextCount||0),thoughtCount:(e?.thoughtCount||0)+(t?.thoughtCount||0)}}function Bs(e){return new Promise(t=>setTimeout(t,e))}function qs(e,t,r,n){return n?(e.finalTextSeen=!0,e.emittedTexts.has(n)||(e.emittedTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}})),!0):!1}async function js(e,t,r,n,s,i){let o=Qt(e,t,r,n,Date.now()),c=()=>qs(e,r,n,Hs(s,{remove:!1}));if(c()||e.finalTextSeen)return Ot(s),o;let l=ps(i);if(l<=0||!t&&!s)return Ot(s),o;let d=Date.now()+l,f=Math.min(yr(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await Bs(Math.min(f,Math.max(0,d-Date.now()))),o=$s(o,Qt(e,t,r,n,Date.now())),!c()););return Ot(s),o}var Ct=class{constructor(t,r,n={}){this.agent=t,this.target=r,this.options=n,this.active=new Map}async sessionNew(){return{sessionId:`cli-${this.agent.agentId}-${Z()}`}}async sessionPrompt(t,r,n){let s=Date.now(),i=a(this.target.command);if(!i)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let o=a(t.sessionId)||Z(),c=Tt(t.prompt),l=a(this.target.promptMode||"stdin"),d=this.buildArgs(l,c),f=a(this.target.cwd)||this.agent.workspace||process.cwd(),p=typeof this.options.prepareLaunch=="function",m=ds(i,d,this.target)?p?`/tmp/orcha-runtime-last-message-${Z()}.txt`:L(pr(),`orcha-runtime-last-message-${Z()}.txt`):"";m&&d.push("--output-last-message",m);let S={...u(this.target.env)?this.target.env:{},...l==="env"?{ORCHA_RUNTIME_PROMPT:c}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:o},O=p?await this.options.prepareLaunch({command:i,args:d,cwd:f,environment:S}):{command:i,args:d,cwd:f,environment:{...process.env,...S},cleanup:async()=>{}},N=p?Ss(O):Rs(this.target,o),_=N.root,y=ws(this.target,_,O),E=fs(i,this.target),A={...this.target,targetCode:this.agent.targetCode,cwd:f,...p?{codexHome:L(O.homeDirectory,".codex")}:{}},W=E?xs(A,s):new Set,gt=p&&m?L(O.tempDirectory,m.slice(5)):m,J=T(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,T(this.options.sessionPromptTimeoutMs,Zn));p||(O.environment.ORCHA_RUNTIME_ARTIFACT_DIR=_);let I=ur(O.command,O.args,{cwd:O.cwd,env:O.environment,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(o,I),h("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:o,pid:I.pid,timeoutMs:J,isolation:O.isolation});let $e="",Bt=a(this.target.outputMode||"text"),b={artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:y,finalTextSeen:!1,finalTextOnly:_s(t,this.target),emitThoughtChunks:hs(t,this.target),terminalOutcome:null,terminalProtocol:cs(this.target),emitTerminal:null},qt=E?ys(A,c,s,W):null;return I.stdout.setEncoding("utf8"),I.stdout.on("data",X=>this.handleStdout(X,Bt,b,o,r)),I.stderr.setEncoding("utf8"),I.stderr.on("data",X=>{$e+=X,this.target.emitStderr===!0&&r({sessionId:o,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:X}}})}),l==="stdin"?I.stdin.end(c):I.stdin.end(),await new Promise((X,jt)=>{let nt=!1,Be=!1,_t=null,st=null,Gt=qt&&ms(this.target,t)?setInterval(()=>{try{Qt(b,qt,o,r)}catch(w){h("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:o,error:String(w?.message||w)})}},yr(this.target)):null;Gt?.unref?.();let qe=setTimeout(()=>{Be=!0,h("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:o,pid:I.pid,timeoutMs:J}),xt(I,"SIGTERM"),_t=setTimeout(()=>{h("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:o,pid:I.pid}),xt(I,"SIGKILL")},mr),_t.unref?.(),it(Object.assign(new Error(`runtime CLI timed out after ${J}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},J);qe.unref?.();let je=async()=>{clearTimeout(qe),st&&clearTimeout(st),Gt&&clearInterval(Gt),_t&&!Be&&clearTimeout(_t),Es(N,{target:this.agent.targetCode,sessionId:o}),this.active.delete(o),b.emitTerminal=null,await O.cleanup?.()},Tn=w=>{nt||(nt=!0,je().then(()=>X(w),jt))},it=w=>{nt||(nt=!0,je().then(()=>jt(w),v=>{h("warn","runtime.cli","sandbox launch cleanup failed",{target:this.agent.targetCode,sessionId:o,error:String(v?.message||v)}),jt(w)}))};b.emitTerminal=w=>{let v={...u(w.result)?w.result:{},_artifacts:[...b.artifacts.values()]};try{n?.({...w,result:v})}catch(j){h("warn","runtime.cli","runtime terminal listener failed",{target:this.agent.targetCode,sessionId:o,error:String(j?.message||j)})}let k=Math.max(0,T(this.target.terminalExitGraceMs,is));st=setTimeout(()=>{st=null,!(nt||this.active.get(o)!==I)&&(h("warn","runtime.cli","runtime stayed alive after terminal event; terminating child",{target:this.agent.targetCode,sessionId:o,pid:I.pid,terminalProtocol:b.terminalProtocol,graceMs:k}),Jt(I))},k),st.unref?.()},I.on("error",w=>{h("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:o,pid:I.pid,error:String(w?.message||w)}),it(w)}),I.on("exit",(w,v)=>{(async()=>{Bt==="json-lines"&&b.value.trim()&&this.handleStdout(`
11
- `,Bt,b,o,r);let k=await js(b,qt,o,r,gt,this.target);(k.artifactCount>0||k.textCount>0||k.thoughtCount>0)&&h("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:o,artifactCount:k.artifactCount,textCount:k.textCount,finalTextCount:k.finalTextCount,thoughtCount:k.thoughtCount,transcriptCount:k.transcriptCount});let j=$e.trim();if(j&&h("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:o,stderr:j}),h("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:o,pid:I.pid,exitCode:w,signal:v,artifactCount:b.artifacts.size,finalTextSeen:b.finalTextSeen}),b.terminalOutcome?.status==="failed"){it(b.terminalOutcome.error);return}if(w!==0&&b.terminalOutcome?.status!=="completed"){let yn=Object.assign(new Error(`runtime CLI exited with code ${w??"unknown"}${v?` (${v})`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:w,signal:v});it(yn);return}Tn({stopReason:"end_turn",exitCode:w,signal:v,_artifacts:[...b.artifacts.values()],...j?{stderr:j}:{}})})().catch(it)})})}buildArgs(t,r){let n=C(this.target.args);return t==="args"?[...n,r]:n}handleStdout(t,r,n,s,i){if(r!=="json-lines"){i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t}}});return}n.value+=t;let o=n.value.split(/\r?\n/);n.value=o.pop()||"";for(let c of o){let l=c.trim();if(l)try{let d=JSON.parse(l);_r(n,gr(d,n.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:Tr(d)}});let f=hr(d),p=te(d);f&&n.emitThoughtChunks&&!p&&ls(d)?Sr(n,s,i,f):f&&Ts(n,p)&&Rr(n,s,i,f),f&&p&&(n.finalTextSeen=!0);let g=us(d,n.terminalProtocol);g&&!n.terminalOutcome&&(g.status==="failed"||n.finalTextSeen||n.artifacts.size>0)&&(n.terminalOutcome=g,n.emitTerminal?.(g))}catch{i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${c}
12
- `}}})}}}async sessionCancel(t){let r=a(t.sessionId),n=this.active.get(r);return n?(h("info","runtime.cli","cancelling runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid}),Jt(n),{ok:!0,cancelled:!0}):{ok:!0,cancelled:!1}}stop(t="stop"){for(let[r,n]of this.active.entries())h("info","runtime.cli","stopping runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid,reason:t}),Jt(n);this.active.clear()}};var re="ORCHA_RUNTIME_OUTPUT_START",ne="ORCHA_RUNTIME_OUTPUT_END",se="ORCHA_RUNTIME_CONTROL_START",ie="ORCHA_RUNTIME_CONTROL_END",Ar=re,Cr=ne,Nr=se,br=ie,oe=[re,ne,se,ie],Gs=new Set(["_artifacts","_decision","_meta"]),Ks=new RegExp(`(?:^|(?<=[\\r\\n]))[ \\t]*(?<marker>${oe.join("|")})[ \\t]*(?=\\r\\n?|\\n|$)`,"g"),D=class extends Error{constructor(t,r){super(r),this.name="RuntimeResultProtocolError",this.code=t}};function Mr(e){let t=typeof e=="string"?e.trimStart():"";return oe.some(r=>t.startsWith(r))}function ae(e){if(typeof e!="string")return null;let t=e,r=Vs(t);if(![...r.values()].some(m=>m.length>0))return null;let n=[],s=[];for(let[m,S]of r)S.length===0?n.push(m):S.length>1&&s.push(m);if(n.length>0||s.length>0){let m=[];throw n.length>0&&m.push(`\u7F3A\u5C11 ${n.join(", ")}`),s.length>0&&m.push(`\u91CD\u590D ${s.join(", ")}`),new D("invalid_markers",`Runtime Result \u534F\u8BAE\u6807\u8BB0\u4E0D\u5B8C\u6574\uFF1A${m.join("\uFF1B")}`)}let i=r.get(re)[0],o=r.get(ne)[0],c=r.get(se)[0],l=r.get(ie)[0];if(!(i.end<=o.start&&o.end<=c.start&&c.end<=l.start))throw new D("invalid_marker_order","Runtime Result \u534F\u8BAE\u6807\u8BB0\u987A\u5E8F\u9519\u8BEF\uFF1A\u5FC5\u987B\u5148\u8F93\u51FA OUTPUT \u5757\uFF0C\u518D\u8F93\u51FA CONTROL \u5757");let d=zs(t.slice(i.end,o.start));if(!d.trim())throw new D("empty_output","Runtime Result OUTPUT \u5757\u4E0D\u80FD\u4E3A\u7A7A");let f=t.slice(c.end,l.start).trim();if(!f)throw new D("empty_control","Runtime Result CONTROL \u5757\u4E0D\u80FD\u4E3A\u7A7A");let p;try{p=JSON.parse(f)}catch(m){throw new D("invalid_control_json",`Runtime Result CONTROL \u5757\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(m?.message||m)}`)}if(!xr(p))throw new D("invalid_control_type","Runtime Result CONTROL \u5757\u5FC5\u987B\u662F JSON \u5BF9\u8C61");let g=Object.keys(p).filter(m=>!Gs.has(m)).sort();if(g.length>0)throw new D("invalid_control_keys",`Runtime Result CONTROL \u5757\u5305\u542B\u975E\u6807\u51C6\u5B57\u6BB5\uFF1A${g.join(", ")}`);if("_artifacts"in p&&!Array.isArray(p._artifacts))throw new D("invalid_control_field_type","Runtime Result CONTROL \u5757\u7684 _artifacts \u5FC5\u987B\u662F JSON \u6570\u7EC4");for(let m of["_decision","_meta"])if(m in p&&!xr(p[m]))throw new D("invalid_control_field_type",`Runtime Result CONTROL \u5757\u7684 ${m} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return{output:d,...p}}function Vs(e){let t=new Map(oe.map(r=>[r,[]]));for(let r of e.matchAll(Ks))t.get(r.groups.marker).push({start:r.index,end:r.index+r[0].length});return t}function zs(e){let t=e.match(/^(?:\r\n|\r|\n)/)?.[0]||"",r=t?e.slice(t.length):e;return t&&r.endsWith(t)?r.slice(0,-t.length):r}function xr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{createHash as Ws}from"node:crypto";var Js="orcha.goal-contract/v1",Xs=new Set(["complete","completed","done","ok","passed","success","succeeded"]),Ys=new Set(["aborted","blocked","cancelled","canceled","denied","error","failed","failure","timeout","timed_out"]),Qs=new Map([["exec_command","run_command"],["local_shell_call","run_command"],["run_command","run_command"],["apply_patch","apply_patch"],["read_file","read_file"],["list_files","list_files"],["plugin_operation","plugin_operation"]]);function de(e){return Ws("sha256").update(F(e)).digest("hex")}function Pr(e){if(!Lr(e))return"";let t=["The following Orcha goal contract is immutable for this turn. Do not narrow its outcome or constraints.",`<goal_contract>${JSON.stringify(e)}</goal_contract>`];return e.verificationPlan?.required===!0&&t.push("Every verification check must be satisfied by a real successful tool call from one of its toolNames.","A final text claim is not verification; missing or failed tool evidence prevents completion."),t.join(`
13
- `)}function kr(e,t,r=""){if(!Lr(e))return e==null?null:{required:!0,status:"failed",outcome:a(e?.outcome),goalContractHash:"",checks:[],errorCode:"invalid_goal_contract"};let n=de(e),s=e.verificationPlan.required===!0;if(a(r)&&a(r)!==n)return{required:s,status:"failed",outcome:e.outcome,goalContractHash:n,checks:[],errorCode:"goal_contract_hash_mismatch"};if(!s)return{required:!1,status:"not_required",outcome:e.outcome,goalContractHash:n,checks:[]};let i=Zs(t),o=e.verificationPlan.checks.map(l=>oi(l,i));return{required:!0,status:o.some(l=>l.status==="failed")?"failed":o.some(l=>l.status==="missing")?"missing":"passed",outcome:e.outcome,goalContractHash:n,checks:o}}function Lr(e){if(!u(e)||e.schemaVersion!==Js||!a(e.outcome))return!1;let t=e.verificationPlan;if(!u(t)||typeof t.required!="boolean"||!Array.isArray(t.checks)||t.required&&t.checks.length===0)return!1;let r=new Set;for(let n of t.checks)if(!u(n)||!a(n.id)||r.has(a(n.id))||(r.add(a(n.id)),!Array.isArray(n.toolNames)||n.toolNames.length===0||n.toolNames.some(s=>!a(s)))||n.arguments!==void 0&&!u(n.arguments))return!1;return!0}function Zs(e){let t=new Map,r=[];for(let n of Array.isArray(e)?e:[]){let s=u(n?.update)?n.update:{},i=a(s.sessionUpdate);if(i==="runtime_event"){ti(s.event,t,r);continue}if(i==="tool_call"){let o=bt(s)||`tool-${r.length+1}`,c=Nt(t,r,o),l=ue(s,s.name||s.toolName||s.kind);c.toolName=l.toolName,c.arguments=l.arguments,c.status=dt(s.status),c.evidence=Ut(s);continue}if(i==="tool_call_update"){let o=bt(s);if(!o)continue;let c=Nt(t,r,o),l=ue(s,s.name||s.toolName||s.kind);c.toolName||=l.toolName,Object.keys(c.arguments).length===0&&(c.arguments=l.arguments),c.status=dt(s.status),c.evidence.push(...Ut(s))}}return r}function ti(e,t,r){let n=u(e)&&u(e.payload)?e.payload:u(e)?e:{},s=a(n.type);if(["function_call","custom_tool_call","local_shell_call","mcp_tool_call"].includes(s)){let c=bt(n)||`runtime-${r.length+1}`,l=Nt(t,r,c),d=ue(n,n.name||n.tool||s,s);l.toolName=d.toolName,l.arguments=d.arguments,l.status=dt(n.status),l.evidence.push(...Ut(n));return}if(!["function_call_output","custom_tool_call_output","local_shell_call_output","mcp_tool_call_output"].includes(s))return;let i=bt(n);if(!i)return;let o=Nt(t,r,i);o.status=si(n,o.toolName),o.evidence.push(...Ut(n))}function Nt(e,t,r){let n=e.get(r);return n||(n={toolCallId:r,toolName:"",arguments:{},status:"unknown",evidence:[]},e.set(r,n),t.push(n)),n}function ei(e){let t=a(e).toLowerCase();return Qs.get(t)||t}function ue(e,t,r=""){let n=ri(e),s=a(r)==="mcp_tool_call"||a(e?.kind).toLowerCase()==="mcp",i=u(e?._meta)?e._meta:{},o=a(e?.server||e?.serverName||e?.server_name||e?.mcpServer||i.server||i.serverName).toLowerCase();if(s&&o==="orcha"){let c=a(e?.tool||e?.toolName||e?.name||t);return{toolName:"plugin_operation",arguments:{...n,...c?{operationCode:c}:{}}}}return{toolName:ei(t),arguments:n}}function bt(e){return u(e)?a(e.call_id||e.callId||e.toolCallId||e.id):""}function ri(e){if(!u(e))return{};for(let r of["arguments","args","rawInput","input","params","parameters"]){let n=ni(e[r]);if(n)return n}let t={};for(let r of["cmd","command","cwd","operationCode","path","query","url"])e[r]!==void 0&&(t[r]=e[r]);return t}function ni(e){if(u(e))return structuredClone(e);if(typeof e!="string")return null;try{let t=JSON.parse(e);return u(t)?t:null}catch{return null}}function si(e,t){if(!u(e))return"unknown";let r=Mt(e,0,{parseCliExitCode:t==="run_command"||t==="apply_patch"});return r.includes("failed")?"failed":r.includes("success")?"success":"unknown"}function Mt(e,t=0,r={}){if(t>8||e===null||e===void 0)return[];if(typeof e=="string")return ii(e,t,r);if(Array.isArray(e))return e.flatMap(o=>Mt(o,t+1,r));if(!u(e))return[];let n=[];typeof e.isError=="boolean"&&n.push(e.isError?"failed":"success"),typeof e.ok=="boolean"&&n.push(e.ok?"success":"failed"),typeof e.success=="boolean"&&n.push(e.success?"success":"failed");let s=dt(e.status);s!=="unknown"&&n.push(s);let i=e.exitCode??e.exit_code;typeof i=="number"&&Number.isFinite(i)&&n.push(i===0?"success":"failed");for(let o of["output","result","structuredContent","content"])e[o]!==void 0&&n.push(...Mt(e[o],t+1,r));return n}function ii(e,t,r){let n=e.trim();if(!n)return[];try{return Mt(JSON.parse(n),t+1,r)}catch{}if(r.parseCliExitCode!==!0)return[];let s=[];for(let i of n.matchAll(/(?:process\s+exited\s+with\s+code|exit\s+code\s*:?)\s*(-?\d+)/gi))s.push(Number(i[1])===0?"success":"failed");return s}function dt(e){let t=a(e).toLowerCase();return Xs.has(t)?"success":Ys.has(t)?"failed":"unknown"}function Ut(e){if(!u(e))return[];let t=u(e.output)?e.output:{},r=[e.verificationEvidence,u(e.verification)?e.verification.evidence:null,t.verificationEvidence,u(t.verification)?t.verification.evidence:null],n=[];for(let s of r)for(let i of Array.isArray(s)?s:s?[s]:[])!u(i)||!a(i.id)||n.push({id:a(i.id),status:dt(i.status??(i.passed===!0?"passed":i.passed===!1?"failed":"")),...a(i.message)?{message:a(i.message)}:{}});return n}function oi(e,t){let r=t.filter(o=>e.toolNames.includes(o.toolName)&&le(e.arguments||{},o.arguments)),n=a(e.evidenceId),s=r.find(o=>o.status==="success"&&(!n||o.evidence.some(c=>c.id===n&&c.status==="success")));if(s)return ce(e,"passed",s,"Runtime tool evidence passed.");let i=r.find(o=>o.status==="failed"||n&&o.evidence.some(c=>c.id===n&&c.status==="failed"));return i?ce(e,"failed",i,"Runtime tool evidence failed."):ce(e,"missing",r.at(-1),n?"Required evidence is missing.":"Required tool execution is missing.")}function ce(e,t,r,n){return{id:e.id,status:t,message:n,...a(e.description)?{description:a(e.description)}:{},toolNames:e.toolNames,...u(e.arguments)?{arguments:e.arguments}:{},...a(e.evidenceId)?{evidenceId:a(e.evidenceId)}:{},...r?.toolCallId?{toolCallId:r.toolCallId}:{}}}function le(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>le(r,t[n])):u(e)?u(t)?Object.entries(e).every(([r,n])=>Object.hasOwn(t,r)&&le(n,t[r])):!1:Object.is(e,t)}function F(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string")return Ur(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("invalid_jcs_number");return JSON.stringify(Object.is(e,-0)?0:e)}if(Array.isArray(e))return`[${Array.from({length:e.length},(t,r)=>{if(!Object.hasOwn(e,r))throw new Error("invalid_jcs_json_value");return F(e[r])}).join(",")}]`;if(u(e))return`{${Object.keys(e).sort().map(t=>`${Ur(t)}:${F(e[t])}`).join(",")}}`;throw new Error("invalid_jcs_json_value")}function Ur(e){return ai(e),JSON.stringify(e)}function ai(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw new Error("invalid_jcs_unicode");t+=1}else if(r>=56320&&r<=57343)throw new Error("invalid_jcs_unicode")}}import{spawn as ci}from"node:child_process";import{createHash as ui,randomUUID as li}from"node:crypto";import{constants as di}from"node:fs";import{access as fi,mkdir as fe,readdir as pi,realpath as ft,rm as mi,stat as hi}from"node:fs/promises";import gi from"node:http";import{tmpdir as _i}from"node:os";import{isAbsolute as pt,join as tt,relative as Dr,resolve as me}from"node:path";var he=1,Ti="orcha.process-isolation/v1",ge="orcha.egress-proxy/v1",Pt={read_only:0,workspace_write:1,workspace_network:2},pe={read_only:["read_only","denied"],workspace_write:["workspace_write","denied"],workspace_network:["workspace_write","restricted"]},yi=new Set([".env",".git-credentials",".netrc",".npmrc",".pypirc","credentials.json","secrets.json","id_rsa","id_ed25519"]);function K(e){if(!u(e))throw R("RUNTIME_SANDBOX_POLICY_REQUIRED","sandboxPolicy is required");let t=structuredClone(e),r=a(t.accessMode),n=a(t.accessModeCeiling);if(!(r in pe)||!(n in pe))throw R("RUNTIME_SANDBOX_POLICY_INVALID","unsupported runtime access mode");if(Pt[r]>Pt[n])throw R("RUNTIME_SANDBOX_POLICY_INVALID","access mode exceeds its ceiling");let[s,i]=pe[r];if(t.filesystemMode!==s||t.networkMode!==i)throw R("RUNTIME_SANDBOX_POLICY_INVALID","runtime access profile does not match its mode");if(Number(t.policySchemaVersion)!==he||!Number.isInteger(Number(t.policyRevision))||Number(t.policyRevision)<1)throw R("RUNTIME_SANDBOX_POLICY_INVALID","unsupported sandbox policy schema or revision");for(let[c,l]of Object.entries({outsideWorkspaceAccess:"denied",hostAccess:"denied",hostEnvironmentAccess:"denied",dockerSocketAccess:"denied",environmentMode:"allowlist"}))if(t[c]!==l)throw R("RUNTIME_SANDBOX_POLICY_INVALID",`${c} cannot be relaxed`);let o=u(t.processIsolation)?t.processIsolation:{};if(o.mode!=="required"||o.backend==="direct")throw R("RUNTIME_SANDBOX_POLICY_INVALID","strong process isolation is required");if(Array.isArray(t.alwaysApprovedApprovalKeys)&&t.alwaysApprovedApprovalKeys.length)throw R("RUNTIME_SANDBOX_POLICY_INVALID","persistent runtime approvals are forbidden");return t}function vr(e,t){let r=K(e),n=K(t);return Pt[n.accessMode]<Pt[r.accessMode]}async function Fr(e){if(!e.sandboxRequired)return{dispatchable:!0,enforced:!1,backend:"direct",daemonStatus:"not_required",daemonProtocolVersion:"",policySchemaVersions:[he],runtimePolicyUpdates:!1,workspaceSync:!1,egressProxy:!1,reason:"external_runtime_sandbox_not_required"};let t=await $r(e.sandboxBrokerCommand,process.env.PATH||"");if(!t)throw R("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let r=await Ii(t,C(e.sandboxBrokerArguments),e.sandboxProbeTimeoutMs);if(r.enforced!==!0||a(r.protocolVersion)!=="orcha.runtime-sandbox-broker/v1"||!["bubblewrap","broker"].includes(a(r.backend)))throw R("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker did not report enforced isolation");let n=u(r.probes)?r.probes:{};for(let s of["emptyRoot","outsideWorkspaceDenied","hostFilesystemDenied","sensitiveFilesDenied","environmentAllowlist","dockerSocketDenied","networkNamespace","workspaceReadOnly","workspaceWrite","resourceLimits"])if(n[s]!==!0)throw R("RUNTIME_SANDBOX_UNAVAILABLE",`sandbox broker probe failed: ${s}`);return e.egressProxyRequired&&await Ai(e),{dispatchable:!0,enforced:!0,backend:a(r.backend),daemonStatus:"ok",daemonProtocolVersion:a(r.protocolVersion||"orcha.runtime-sandbox-broker/v1"),policySchemaVersions:[he],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:e.egressProxyRequired}}async function _e(e,t,r){let n=a(t.workspace||t.cwd),s=a(r),i=n||(t.allowRequestWorkspace===!0?s:"");if(!i||!pt(i))throw R("RUNTIME_WORKSPACE_NOT_CONFIGURED","runtime target must configure an absolute trusted workspace");let o=await ft(i);if(!(await hi(o)).isDirectory())throw R("RUNTIME_WORKSPACE_INVALID","runtime workspace is not a directory");if(!(e.trustedWorkspaceRoots.length?await Promise.all(e.trustedWorkspaceRoots.map(d=>ft(d))):[o]).some(d=>ye(d,o)))throw R("RUNTIME_WORKSPACE_OUTSIDE_TRUSTED_ROOT","runtime workspace is outside trusted roots");return o}async function Hr({config:e,target:t,command:r,args:n,cwd:s,environment:i,runId:o,agentId:c,sessionId:l,sandboxPolicy:d}){if(!e.sandboxRequired)return{command:r,args:[...n],cwd:s,environment:{...process.env,...i},tempDirectory:"",isolation:{enforced:!1,backend:"development_direct"},cleanup:async()=>{}};let f=K(d),p=await _e(e,t,s),g=await ft(s);if(!ye(p,g))throw R("RUNTIME_WORKSPACE_CWD_INVALID","runtime cwd is outside its workspace");let m=await $r(e.sandboxBrokerCommand,process.env.PATH||"");if(!m)throw R("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let S=`runtime-${ui("sha256").update(String(o)).digest("hex").slice(0,32)}`,O=me(e.sandboxTempRoot||tt(_i(),"orcha-runtime-sandboxes"));await fe(O,{recursive:!0,mode:448});let N=tt(O,`${S}-${li()}`),_=tt(N,"home"),y=tt(N,"artifacts");await fe(_,{recursive:!0,mode:448}),await fe(y,{recursive:!0,mode:448});let E=f.networkMode==="restricted"?await Oi(e,{runId:String(o),instanceId:S,policyRevision:Number(f.policyRevision),ttlMs:Math.min(T(f.maxRuntimeSeconds,900)*1e3,e.egressGrantMaxTtlMs),maxTransferBytes:T(f.maxNetworkBytes,64*1024*1024)}):null,A={PATH:a(i.PATH||process.env.PATH),LANG:a(i.LANG||process.env.LANG||"C.UTF-8"),HOME:"/tmp/home",TMPDIR:"/tmp",USER:"orcha",LOGNAME:"orcha",SHELL:"/bin/sh",ORCHA_AGENT_ID:String(c),ORCHA_SESSION_ID:String(l),ORCHA_RUN_ID:String(o),ORCHA_RUNTIME_ARTIFACT_DIR:"/tmp/artifacts",...Si(t,i)};A.HOME="/tmp/home",A.TMPDIR="/tmp",A.ORCHA_RUNTIME_ARTIFACT_DIR="/tmp/artifacts";let W={schemaVersion:Ti,runId:String(o),instanceId:S,workspace:p,cwd:g,filesystemMode:f.filesystemMode,networkMode:f.networkMode,environmentMode:"allowlist",deniedRelativePaths:await Ei(p),temporaryDirectory:N,egressProxy:E,environment:A,resourceLimits:wi(f),readOnlyToolchainRoots:await Ri(e,t)},gt=!1,J=async()=>{if(!gt){gt=!0;try{E&&await xi(e,E,{runId:String(o),instanceId:S})}finally{await mi(N,{recursive:!0,force:!0})}}};return{command:m,args:[...C(e.sandboxBrokerArguments),"--",r,...n],cwd:g,environment:{PATH:process.env.PATH||"",LANG:process.env.LANG||"C.UTF-8",ORCHA_PROCESS_ISOLATION_REQUEST:JSON.stringify(W)},tempDirectory:N,homeDirectory:_,artifactDirectory:y,pathMappings:[{runtimeRoot:"/tmp/artifacts",hostRoot:y},{runtimeRoot:"/tmp/home",hostRoot:_}],isolation:{enforced:!0,backend:"broker",instanceId:S,policyRevision:f.policyRevision},cleanup:J}}async function Ri(e,t){let r=C(t.toolchainRoots||t.sandboxToolchainRoots);if(!r.length)return[];let n=await Promise.all(C(e.trustedToolchainRoots).map(i=>ft(i)));if(!n.length)throw R("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","target toolchain roots require ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS");let s=[];for(let i of r){if(!pt(i))throw R("RUNTIME_TOOLCHAIN_ROOT_INVALID","toolchain roots must be absolute");let o=await ft(i);if(!n.some(c=>ye(c,o)))throw R("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","toolchain root is outside trusted roots");s.push(o)}return[...new Set(s)]}function Si(e,t){let r=u(e.env)?e.env:{},n={};for(let[s,i]of Object.entries(r))/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&i!=null&&(n[s]=String(i));for(let s of["ORCHA_RUNTIME_PROMPT","ORCHA_RUNTIME_ARTIFACT_DIR"])t[s]!=null&&(n[s]=String(t[s]));return n}async function Ei(e){let t=[],r=0,n=async s=>{let i;try{i=await pi(s,{withFileTypes:!0})}catch(o){if(s===e)throw o;return}for(let o of i){if(r+=1,r>1e4)throw R("RUNTIME_WORKSPACE_SCAN_LIMIT_EXCEEDED","workspace contains more than 10000 entries");let c=tt(s,o.name),l=Dr(e,c),d=o.name.toLowerCase();(yi.has(d)||d.startsWith(".env."))&&t.push(l),o.isDirectory()&&!o.isSymbolicLink()&&await n(c)}};return await n(e),t.sort()}function wi(e){return{maxCpuSeconds:Math.max(1,T(e.maxRuntimeSeconds,900)),maxMemoryBytes:T(e.maxMemoryBytes,2*1024*1024*1024),maxProcesses:T(e.maxProcesses,128),maxOpenFiles:T(e.maxOpenFiles,1024),maxFileBytes:T(e.maxFileBytes,64*1024*1024)}}async function Ii(e,t,r){return await new Promise((n,s)=>{let i=ci(e,[...t,"--probe"],{env:{PATH:process.env.PATH||"",LANG:"C.UTF-8"},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=[],c=[];i.stdout.on("data",d=>o.push(Buffer.from(d))),i.stderr.on("data",d=>c.push(Buffer.from(d)));let l=setTimeout(()=>i.kill("SIGKILL"),Math.max(1e3,r));i.once("error",s),i.once("close",d=>{if(clearTimeout(l),d!==0){s(R("RUNTIME_SANDBOX_UNAVAILABLE",Buffer.concat(c).toString("utf8").trim()||`sandbox probe exited with ${d}`));return}try{n(JSON.parse(Buffer.concat(o).toString("utf8")))}catch{s(R("RUNTIME_SANDBOX_UNAVAILABLE","sandbox probe returned invalid JSON"))}})})}async function $r(e,t){let r=a(e);if(!r)return"";let n=pt(r)?[r]:String(t||"").split(":").filter(Boolean).map(s=>tt(s,r));for(let s of n)try{return await fi(s,di.X_OK),s}catch{}return""}async function Oi(e,t){if(!e.egressProxyRequired)throw R("RUNTIME_EGRESS_UNAVAILABLE","restricted network requires the Egress Proxy");let r=await Te(e,"POST","/v1/grants",{protocolVersion:ge,...t}),n={socketPath:e.egressProxySocket,grantId:a(r.grantId),credential:a(r.credential)};if(!n.grantId||!n.credential)throw R("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy returned an invalid grant");return n}async function xi(e,t,r){await Te(e,"POST",`/v1/grants/${encodeURIComponent(t.grantId)}/revoke`,{protocolVersion:ge,...r}).catch(()=>{})}async function Ai(e){let t=await Te(e,"GET","/health");if(t.status!=="ok"||t.proxy!=="orcha-egress-proxy"||t.protocolVersion!==ge)throw R("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy is unavailable or incompatible")}async function Te(e,t,r,n){if(!pt(e.egressProxySocket)||!e.egressProxyToken)throw R("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy socket and token are required");return await new Promise((s,i)=>{let o=gi.request({socketPath:e.egressProxySocket,path:r,method:t,headers:{Authorization:`Bearer ${e.egressProxyToken}`,Accept:"application/json",...n?{"Content-Type":"application/json"}:{}}},c=>{let l=[],d=0;c.on("data",f=>{d+=f.length,d>1048576?o.destroy(new Error("egress response is too large")):l.push(Buffer.from(f))}),c.once("end",()=>{try{let f=JSON.parse(Buffer.concat(l).toString("utf8")||"{}");(c.statusCode||500)>=400?i(R("RUNTIME_EGRESS_UNAVAILABLE",a(f.error)||"Egress Proxy rejected the request")):s(f)}catch(f){i(f)}})});o.once("error",i),o.setTimeout(3e3,()=>o.destroy(new Error("Egress Proxy request timed out"))),n?o.end(JSON.stringify(n)):o.end()})}function ye(e,t){let r=Dr(me(e),me(t));return r===""||!r.startsWith("..")&&!pt(r)}function R(e,t){return Object.assign(new Error(t),{code:e})}var Re=24e3,Se=8,Ee=50,we=6e3,Ni=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),bi=10*60*1e3,Mi=60*1e3,Ui=8,Pi=30*60*1e3,ki=60*1e3,Li=1,Di=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions","runtimeMaxSessions"]),vi=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Fi(e){if(!u(e))return{};let t={};for(let r of["name","code","serverName","serverCode","type","transport","url","command","protocolVersion"]){let n=a(e[r]);n&&(t[r]=n)}return t}function Hi(e){return(Array.isArray(e)?e:[]).map(Fi).sort((t,r)=>{let n=F(t),s=F(r);return n<s?-1:n>s?1:0})}function $i(e){return!u(e)||e.verificationPlan?.required!==!0?!1:(Array.isArray(e.verificationPlan.checks)?e.verificationPlan.checks:[]).some(r=>u(r)&&Array.isArray(r.toolNames)&&r.toolNames.some(n=>a(n)==="plugin_operation"))}function Bi(e,t,r){let n=u(e?._meta)?e._meta:{};return{...u(e)?e:{},sessionId:t,update:u(e?.update)?e.update:{},_meta:{...n,orchaAgentId:r.agentId,runtimeSessionId:r.runtimeSessionId,bridgeUpdateId:kt()}}}function U(e){return e==null||e===""?!1:typeof e=="string"?a(e)!=="":Array.isArray(e)?e.length>0:u(e)?Object.keys(e).length>0:!0}function zr(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return Ni.has(t)}function B(e,t){let r=T(e,t);return Number.isFinite(r)&&r>0?r:t}function xe(e){let t=T(e,null);return Number.isFinite(t)&&t>0?t:null}function mt(e,t=!1){if(typeof e=="boolean")return e;let r=a(e).toLowerCase();return["true","1","yes","y","on"].includes(r)?!0:["false","0","no","n","off"].includes(r)?!1:t}function $(e){return a(e?.type||"echo")}function qi(e){let t=$(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function Ae(e){if(u(e)){if(Object.prototype.hasOwnProperty.call(e,"releaseAfterPrompt"))return e.releaseAfterPrompt;if(Object.prototype.hasOwnProperty.call(e,"disposeAfterPrompt"))return e.disposeAfterPrompt}}function ji(e){let t=String(e||"");if(vi.test(t))return!0;let r=t.replace(/[^a-z0-9]/gi,"").toLowerCase();return r.endsWith("token")||r.endsWith("secret")||r.endsWith("password")||r.endsWith("apikey")||r.endsWith("privatekey")||r==="authorization"||r==="cookie"||r==="jwt"||r.includes("credential")}function Ce(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=we)return e;let r=e.length-we;return`${e.slice(0,we)}... [truncated ${r} characters]`}if(t>=Se)return Array.isArray(e)?`[array truncated at depth ${Se}, items=${e.length}]`:u(e)?`[object truncated at depth ${Se}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let r=e.slice(0,Ee).map(n=>Ce(n,t+1));return e.length>Ee&&r.push(`[truncated ${e.length-Ee} items]`),r}if(u(e)){let r={};for(let[n,s]of Object.entries(e))r[n]=ji(n)?"[REDACTED]":Ce(s,t+1);return r}return String(e)}var Gi=new Set(["type","executionId","taskId","task","traceId","requestId","agentCode","stage","phase","nodeId","nodeType","capabilityCode","operationCode","outputType","artifactType","input","inputs","rejection","previous","artifactRefs","outputSchema","executionPolicy","resultContract"]);function Ki(e){if(!u(e))return e;let t={};for(let r of Gi)U(e[r])&&(t[r]=e[r]);return t}function Vi(e){if(!u(e))return e;let t={...e};return u(t.renderedPayload)&&(t.renderedPayload=Ki(t.renderedPayload)),t}function zi(e){let t=u(e)?e:{},r={};U(t.metadata)&&(r.metadata=Vi(t.metadata));for(let[n,s]of Object.entries(t))Di.has(n)||n==="metadata"||U(s)&&(r[n]=s);return r}function Wi(e){let t=u(e)?e:{},r=u(t.metadata)?t.metadata:{},n=u(r.renderedPayload)?r.renderedPayload:{};return u(t.resultContract)?t.resultContract:u(n.resultContract)?n.resultContract:{}}function Wr(e){return a(Wi(e).kind).toLowerCase()==="decision"}function Br(e){let t=u(e)?e:{},r=u(t.metadata)?t.metadata:{};return xe(t.runtimeMaxSessions??r.runtimeMaxSessions)}function Ji(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:$(e)==="cli"}function qr(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return mt(t,qi(e))}function Xi(e,t){let r=u(e?.metadata)?{...e.metadata}:{},n=u(r._runtimeBridge)?{...r._runtimeBridge}:{},s=Ae(n);return r._runtimeBridge={...n,promptKind:"dispatch",finalTextOnly:Ji(t),releaseAfterPrompt:s===void 0?qr(t):mt(s,qr(t)),requiresRuntimeResult:Wr(e)},r}function Yi(e){let t=zi(e);if(!U(t))return"";let r=JSON.stringify(Ce(t),null,2);if(r.length<=Re)return r;let n=r.length-Re;return`${r.slice(0,Re)}
14
- ... [truncated ${n} characters]`}function Jr(e){if(!u(e))return"";let t=u(e.update)?e.update:e,n=(u(t.content)?t.content:{}).text??t.text;return n==null?"":String(n)}function Qi(e){if(!u(e))return"";let t=u(e.update)?e.update:e;return a(t.sessionUpdate)}function jr(e){if(!Array.isArray(e))return"";let t=!1,r=[],n=[],s=[],i=()=>{r.length>0&&(n.push(r),r=[])};for(let c of e){let l=Qi(c),d=Jr(c);if(!l){d&&s.push(d);continue}if(t=!0,l==="agent_message_chunk"){d&&r.push(d);continue}(l==="agent_thought_chunk"||l==="user_message_chunk"||l==="tool_call"||l==="tool_call_update"||l==="plan")&&i()}if(i(),!t)return ht(s);let o=n[n.length-1]||[];return ht(o)}function Ne(e){return Array.isArray(e)?e.map(Jr).filter(t=>t!==""):[]}function Zi(e){if(!u(e))return null;let t=u(e.update)?e.update:e;return a(t.sessionUpdate)!=="runtime_event"?null:u(t.event)?t.event:null}function to(e){if(!u(e))return"";let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type);if(r==="event_msg"){if(n==="task_complete")return a(t.last_agent_message||t.message||t.output);if(n==="agent_message"){let s=a(t.phase||t.status||t.stage).toLowerCase();if(["final_answer","final","complete","completed","done"].includes(s))return a(t.message||t.text||t.content)}}return""}function eo(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let r=to(Zi(e[t]));if(r)return r}return""}function ht(e){let t="";for(let r of e){let n=String(r||"");if(n)if(!t)t=n;else if(n.length>t.length&&n.startsWith(t))t=n;else{let s=Mr(n)&&!/[\r\n]$/.test(t)?`
15
- `:"";t+=`${s}${n}`}}return t.trim()}function ro(e){let t=String(e||"").trim();if(!t)return"";let r=t.match(/(?:^|\n)#{1,3}\s+\S/);return!r||r.index===0?t:t.slice(r.index+(t[r.index]===`
16
- `?1:0)).trim()}function Gr(e){let t=String(e||"").trim();if(!t)return null;try{let r=JSON.parse(t);if(u(r)&&(Xr(r)||U(r._artifacts)||U(r.artifacts)||U(r._decision)||U(r._meta)))return r}catch{}return null}function Lt(e){try{return ae(e)}catch{return null}}function no(e){try{return ae(e),null}catch(t){return t}}function Ie(...e){for(let t of e){let r=no(t);if(r)throw r}}function Kr(e){let t=String(e||"").trim();if(!t)return null;let r=Lt(t);if(r)return r;let n=[...t.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];for(let s=n.length-1;s>=0;s-=1){let i=Gr(n[s][1]);if(i)return i}if(!t.endsWith("}"))return null;for(let s=t.lastIndexOf("{");s>=0;s=t.lastIndexOf("{",s-1)){let i=Gr(t.slice(s));if(i)return i}return null}function so(e){let t=Ne(e);for(let r=t.length-1;r>=0;r-=1){let n=Lt(t[r]);if(n)return n}return Lt(ht(t))}function Xr(e){if(!u(e))return!1;if(U(e.output))return!0;for(let t of["content","text","message","summary"])if(a(e[t]))return!0;return!!(zr(e.status)||a(e.error)||a(e.errorMessage))}function H(e){let t=u(e)?{...e}:{};return(!Array.isArray(t._artifacts)||t._artifacts.length===0)&&Array.isArray(t.artifacts)&&t.artifacts.length>0&&(t._artifacts=t.artifacts),delete t.artifacts,t}function io(e){return u(e)?typeof(u(e._decision)?e._decision:u(e.decision)?e.decision:e).passed=="boolean":!1}function oo(e){return u(e)?u(e._decision)&&typeof e._decision.passed=="boolean"?!0:io(e.output):!1}function Oe(e,t,r){let n=u(e)?{...e}:{};if(!U(n.output)){for(let s of["summary","message","content","text"])if(a(n[s])){n.output=a(n[s]);break}}return!U(n.output)&&a(r)&&(n.output=a(r)),{...n,_meta:{...u(n._meta)?n._meta:{},runtimeOutputSource:t,requiredRuntimeResult:!0,finalMessagePreview:a(r).slice(0,1e3)}}}var ao=["dataUrl","dataURL","contentDataUrl","contentDataURL","contentBase64","base64","data"];function Vr(e){if(!u(e))return"";let t=u(e.content)?e.content:{},r=u(e.metadata)?e.metadata:{};return a(e.fieldKey||e.field_key||t.fieldKey||r.fieldKey)}function co(e,t){let r=u(e.content)?e.content:{},n=u(t.content)?t.content:{},s={...e,...t,content:{...r,...n},metadata:{...u(e.metadata)?e.metadata:{},...u(t.metadata)?t.metadata:{}}};for(let i of ao)U(e[i])&&(s[i]=e[i]),U(r[i])&&(s.content[i]=r[i]);return s}function uo(e,t){let r=Array.isArray(e)?e.filter(u):[],n=Array.isArray(t)?t.filter(u):[];if(!r.length)return n;if(!n.length)return r;let s=[...r],i=new Map;for(let c=0;c<r.length;c+=1){let l=Vr(r[c]),d=i.get(l)||[];d.push(c),i.set(l,d)}let o=new Map;for(let c of n){let l=Vr(c),d=o.get(l)||0;o.set(l,d+1);let f=i.get(l)?.[d];f===void 0?s.push(c):s[f]=co(s[f],c)}return s}function q(e,t,r){let n={...e,...t,_meta:{...u(e._meta)?e._meta:{},...u(t._meta)?t._meta:{},runtimeOutputSource:r}};return(Array.isArray(e._artifacts)||Array.isArray(t._artifacts))&&(n._artifacts=uo(e._artifacts,t._artifacts)),n}function lo(e,t,r={}){let n=a(r.promptKind),s=r.requiresRuntimeResult===!0,i=s||n==="dispatch",o=H(e),c=typeof o.output=="string"?Lt(o.output):null;if(c)return q(o,H(c),"result_block");let l=eo(t),d=l?Kr(l):null,f=i?so(t):null;if(Xr(o))return zr(o.status)||a(o.error)||a(o.errorMessage)?o:n==="dispatch"&&d?q(o,H(d),"final_event"):n==="dispatch"&&f?q(o,H(f),"updates"):!s||oo(o)?o:d?q(o,H(d),"final_event"):f?q(o,H(f),"updates"):(Ie(o.output,l,ht(Ne(t))),Oe(o,"result",o.output));if(d)return q(o,H(d),"final_event");if(f)return q(o,H(f),"updates");if(l)return s?(Ie(l,ht(Ne(t))),Oe(o,"final_event",l)):{...o,output:l,_meta:{...u(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let p=ro(jr(t));if(!p)return o;let g=Kr(p);return g?q(o,H(g),"updates"):s?(Ie(jr(t),p),Oe(o,"updates",p)):{...o,output:p,_meta:{...u(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}var Dt=class{constructor(t){this.config=t,this.targets=t.targets||{},this.agents=new Map,this.sessions=new Map,this.runtimeSessionIndex=new Map,this.pendingPermissions=new Map,this.operations=new Map,this.startedAt=ot(),this.sandboxCapabilities={dispatchable:t.sandboxRequired!==!0,enforced:!1,backend:t.sandboxRequired?"unavailable":"direct",daemonStatus:t.sandboxRequired?"pending":"not_required",policySchemaVersions:[1],runtimePolicyUpdates:t.sandboxRequired===!0,workspaceSync:!1,egressProxy:!1},this.cleanupTimer=null,this.startSessionCleanup()}async start(){try{this.sandboxCapabilities=await Fr(this.config)}catch(t){this.sandboxCapabilities={...this.sandboxCapabilities,dispatchable:!1,enforced:!1,backend:"unavailable",daemonStatus:"unavailable",reason:a(t?.code||t?.message||t)||"sandbox_probe_failed"},h("error","runtime-bridge","runtime node sandbox probe failed; node will not accept work",{reason:this.sandboxCapabilities.reason})}return this.sandboxCapabilities}assertDispatchable(){if(this.config.sandboxRequired&&!(this.sandboxCapabilities.dispatchable===!0&&this.sandboxCapabilities.enforced===!0))throw Object.assign(new Error("runtime node strong sandbox is unavailable"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"})}operationIdentity(t,r,n){let s=u(t.goalContract)?de(t.goalContract):a(t.goalContractHash),i=Ci("sha256").update(F({prompt:Array.isArray(t.prompt)?t.prompt:[],mcpServers:Hi(t.mcpServers)})).digest("hex");return{agentId:r,runId:a(t.runId),sessionId:n,targetCode:a(t.targetCode||t.framework),workspace:a(t.workspace),goalContractHash:s,requestHash:i}}assertOperationIdentity(t,r,n,s){let i=this.operationIdentity(r,n,s),o=Object.keys(t.identity).find(c=>t.identity[c]!==i[c]);if(o)throw Object.assign(new Error(`runtime operation correlation conflict: ${t.correlationId}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT",field:o})}createOperation(t,r,n,s){let i={correlationId:t,agentId:n,sessionId:s,identity:this.operationIdentity(r,n,s),sandboxPolicy:u(r.sandboxPolicy)?structuredClone(r.sandboxPolicy):null,status:"running",updates:[],listeners:new Set,waiters:[],response:null,error:null,createdAtMs:Date.now(),completedAtMs:null};return this.operations.set(t,i),i}async attachOperation(t,r={}){let n=()=>{if(r.onUpdate)for(let s of t.updates)r.onUpdate(s)};if(t.status==="completed")return n(),t.response;if(t.status==="failed")throw n(),t.error;r.onUpdate&&t.listeners.add(r.onUpdate);try{return n(),await new Promise((s,i)=>t.waiters.push({resolve:s,reject:i}))}finally{r.onUpdate&&t.listeners.delete(r.onUpdate)}}completeOperation(t,r){if(t.status==="running"){t.status="completed",t.response=r,t.completedAtMs=Date.now();for(let n of t.waiters.splice(0))n.resolve(r);t.listeners.clear()}}promptResponse(t,r,n,s,i){let o=u(t.metadata)?t.metadata:{},c=u(o._runtimeBridge)?o._runtimeBridge:{},l=lo(i,s,c),d=kr(t.goalContract,s,t.goalContractHash);return{sessionId:n,runtimeSessionId:r.runtimeSessionId,result:l,updates:s,...d?{verification:d}:{}}}failOperation(t,r){if(t.status!=="running")return;let n=r instanceof Error?r:Object.assign(new Error(String(r||"runtime operation failed")),{code:"RUNTIME_NODE_ERROR"});t.status="failed",t.error=n,t.completedAtMs=Date.now();for(let s of t.waiters.splice(0))s.reject(n);t.listeners.clear()}cleanupOperations(t=Date.now()){let r=B(this.config.operationTtlMs,Pi);for(let[n,s]of this.operations)s.status!=="running"&&t-(s.completedAtMs||s.createdAtMs)>r&&this.operations.delete(n)}targetFor(t){let r=a(t)||this.config.defaultTargetCode,n=this.targets[r];if(!r||!u(n)){let s=new Error(`runtime target is not configured: ${r||"<empty>"}`);throw s.code="RUNTIME_TARGET_NOT_FOUND",s}return{code:r,target:n}}targetIdleTtlMs(t){let n=$(t)==="openclaw"?B(this.config.openClawSessionIdleTtlMs,ki):B(this.config.sessionIdleTtlMs,bi);return B(t?.sessionIdleTtlMs??t?.idleTtlMs,n)}targetMaxSessions(t,r=null){let s=$(t)==="openclaw"?B(this.config.openClawMaxSessions,Li):B(this.config.maxSessionsPerTarget,Ui),i=B(t?.maxSessions,s),o=xe(r);return o?Math.max(i,o):i}targetReleaseAfterPrompt(t,r={}){let n=$(t),s=u(r?._runtimeBridge)?r._runtimeBridge:{},i=Ae(s);return i!==void 0?mt(i,!1):mt(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}promptReleaseAfterPrompt(t,r={}){if(this.config.sandboxRequired)return!0;let n=u(r?._runtimeBridge)?r._runtimeBridge:{},s=Ae(n);return s!==void 0?mt(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=B(this.config.sessionCleanupIntervalMs,Mi);t<=0||(this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions().catch(r=>{h("warn","runtime-bridge","runtime session cleanup failed",{error:String(r)})})},t),this.cleanupTimer.unref?.())}sessionCountForTarget(t){let r=0;for(let n of this.sessions.values())n.targetCode===t&&(r+=1);return r}sessionCountForAgentTarget(t,r){let n=0;for(let s of this.sessions.values())s.agentId===t&&s.targetCode===r&&(n+=1);return n}idleTargetSessions(t){return[...this.sessions.entries()].filter(([,r])=>r.targetCode===t&&!r.busy).sort((r,n)=>(r[1].lastUsedAtMs||0)-(n[1].lastUsedAtMs||0))}idleAgentTargetSessions(t,r){return[...this.sessions.entries()].filter(([,n])=>n.agentId===t&&n.targetCode===r&&!n.busy).sort((n,s)=>(n[1].lastUsedAtMs||0)-(s[1].lastUsedAtMs||0))}async closeSession(t,r="session_closed"){let n=this.sessions.get(t);if(!n)return!1;try{await n.runtime?.stop?.(r)}catch(s){h("warn","runtime-bridge","runtime session stop failed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,error:String(s)})}return this.sessions.delete(t),this.runtimeSessionIndex.delete(`${n.agentId}:${n.runtimeSessionId}`),h("info","runtime-bridge","runtime session closed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,reason:r}),!0}async closeAllSessions(t="bridge_shutdown"){for(let r of[...this.sessions.keys()])await this.closeSession(r,t)}async stop(t="bridge_stop"){this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=null,await this.closeAllSessions(t)}async cleanupExpiredSessions(t=Date.now()){for(let[r,n]of[...this.sessions.entries()])n.busy||t-(n.lastUsedAtMs||n.createdAtMs||t)>n.idleTtlMs&&await this.closeSession(r,"idle_timeout")}async reserveTargetSlot(t,r,n={}){let s=a(n.agentId),i=xe(n.runtimeMaxSessions);if(s&&i)for(;this.sessionCountForAgentTarget(s,t)>=i;){let c=this.idleAgentTargetSessions(s,t);if(!c.length){let l=new Error(`runtime agent session limit reached: ${s}`);throw l.code="RUNTIME_AGENT_SESSION_LIMIT",l}await this.closeSession(c[0][0],"agent_session_limit")}let o=this.targetMaxSessions(r,i);for(;this.sessionCountForTarget(t)>=o;){let c=this.idleTargetSessions(t);if(!c.length){let l=new Error(`runtime target session limit reached: ${t}`);throw l.code="RUNTIME_TARGET_SESSION_LIMIT",l}await this.closeSession(c[0][0],"target_session_limit")}}async createAgent(t){let r=a(t.agentId);if(!r)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});let{code:n,target:s}=this.targetFor(t.targetCode||t.framework),i=this.agents.get(r);if(i&&i.targetCode!==n)throw Object.assign(new Error(`runtime agent target conflict: ${r}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});let o=this.config.sandboxRequired?await _e(this.config,s,t.workspace):a(t.workspace),c={agentId:r,targetCode:n,framework:a(t.framework||n),workspace:o,metadata:u(t.metadata)?t.metadata:{},createdAt:ot(),runtimeKind:$(s),runtimeMaxSessions:Br(t)};return this.agents.set(r,c),{agent:c}}runtimeFor(t,r,n={}){let{target:s}=this.targetFor(t.targetCode),i=$(s),o={onPermissionRequest:l=>this.requestPermission(l)},c={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs,sandboxRequired:this.config.sandboxRequired,...this.config.sandboxRequired?{prepareLaunch:l=>Hr({config:this.config,target:s,...l,runId:n.runId,agentId:t.agentId,sessionId:r,sandboxPolicy:n.sandboxPolicy})}:{}};return i==="stdio-acp"||i==="acp"?new Q(t,s,o,c):i==="openclaw"?new wt(t,s,r,o,c):i==="cli"?new Ct(t,s,c):new yt(t)}async prompt(t,r={}){if(this.assertDispatchable(),this.config.sandboxRequired){let c=a(t.runId);if(!c)throw Object.assign(new Error("runId is required"),{code:"BAD_REQUEST"});t={...t,runId:c,sandboxPolicy:K(t.sandboxPolicy)}}let n=a(t.agentId),s=a(t.sessionId)||kt(),i=a(t.correlationId);if(!n)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});if(this.cleanupOperations(),i){let c=this.operations.get(i);if(c)return this.assertOperationIdentity(c,t,n,s),this.attachOperation(c,r);if(t.attachOnly===!0)throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"})}else if(t.attachOnly===!0)throw Object.assign(new Error("correlationId is required for attachOnly"),{code:"BAD_REQUEST"});let o=i?this.createOperation(i,t,n,s):null;if(o){let c=this.attachOperation(o,r);return(async()=>{try{await this._promptOwned(t,{},o,n,s)}catch(l){let d=o.status==="completed";this.failOperation(o,l),d&&h("warn","runtime-bridge","runtime cleanup failed after operation completion",{correlationId:o.correlationId,error:String(l)})}})(),await c}return await this._promptOwned(t,r,o,n,s)}async _promptOwned(t,r,n,s,i){let o=a(t.runId),c=this.config.sandboxRequired?K(n?.sandboxPolicy||t.sandboxPolicy):null,l=this.agents.get(s),d=this.targetFor(t.targetCode||t.framework||l?.targetCode);if(l&&l.targetCode!==d.code)throw Object.assign(new Error(`runtime agent target conflict: ${s}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});if($(d.target)==="cli"&&$i(t.goalContract))throw Object.assign(new Error("CLI runtimes do not support per-run dynamic MCP required by plugin_operation"),{code:"unsupported_dynamic_mcp"});let f=l||(await this.createAgent({agentId:s,targetCode:d.code,framework:t.framework,workspace:t.workspace,runtimeMaxSessions:t.runtimeMaxSessions,metadata:t.metadata})).agent,p=Br(t);if(p&&(f.runtimeMaxSessions=p),!this.config.sandboxRequired){let _=a(t.workspace);_&&_!==f.workspace&&(f.workspace=_)}let g=`${s}:${i}`;await this.cleanupExpiredSessions();let m=this.sessions.get(g);if(m&&m.targetCode!==d.code)throw Object.assign(new Error(`runtime session target conflict: ${i}`),{code:"RUNTIME_SESSION_TARGET_CONFLICT"});if(m&&this.config.sandboxRequired&&m.runId!==o)throw Object.assign(new Error(`runtime session cannot be shared across runs: ${i}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});if(!m){let{code:_,target:y}=d;await this.reserveTargetSlot(_,y,{agentId:s,runtimeMaxSessions:f.runtimeMaxSessions});let E=this.runtimeFor(f,i,{runId:o,sandboxPolicy:c}),A=await E.sessionNew({cwd:f.workspace||process.cwd(),mcpServers:Array.isArray(t.mcpServers)?t.mcpServers:[],metadata:u(t.metadata)?t.metadata:{}}),W=Date.now();m={agentId:s,sessionId:i,runtime:E,targetCode:_,runtimeKind:$(y),runId:o,sandboxPolicy:c?structuredClone(c):null,runtimeSessionId:a(u(A)?A.sessionId:"")||i,idleTtlMs:this.targetIdleTtlMs(y),releaseAfterPrompt:this.config.sandboxRequired?!0:this.targetReleaseAfterPrompt(y,t.metadata),createdAtMs:W,lastUsedAtMs:W,busy:!1,createdAt:ot()},this.sessions.set(g,m),this.runtimeSessionIndex.set(`${s}:${m.runtimeSessionId}`,m)}if(m.busy){let _=new Error(`runtime session is already running: ${i}`);throw _.code="RUNTIME_SESSION_BUSY",_}m.busy=!0,m.operationCorrelationId=n?.correlationId||null,m.lastUsedAtMs=Date.now();let S=n?.updates||[],O=_=>{let y=Bi(_,i,m);if(S.push(y),n)for(let E of n.listeners)try{E?.(y)}catch(A){h("warn","runtime-bridge","runtime operation update listener failed",{correlationId:n.correlationId,error:String(A)})}else r.onUpdate?.(y)},N=_=>{if(!(!n||n.status!=="running"||!u(_))){if(_.status==="failed"){let y=_.error;if(y instanceof Error){this.failOperation(n,y);return}let E=u(y)?y:{},A=Object.assign(new Error(a(E.message||_.message)||"runtime terminal failure"),{code:a(E.code||_.code)||"RUNTIME_TERMINAL_FAILED"});this.failOperation(n,A);return}this.completeOperation(n,this.promptResponse(t,m,i,S,u(_.result)?_.result:{stopReason:"end_turn"}))}};try{let _=Pr(t.goalContract),y=Array.isArray(t.prompt)?[...t.prompt]:[];_&&y.unshift({type:"text",text:_,metadata:{source:"orcha_goal_contract"}});let E=await m.runtime.sessionPrompt({sessionId:m.runtimeSessionId,prompt:y,metadata:u(t.metadata)?t.metadata:{}},O,N),A=this.promptResponse(t,m,i,S,E);return n&&this.completeOperation(n,A),A}finally{m.busy=!1,m.operationCorrelationId===n?.correlationId&&(m.operationCorrelationId=null),m.lastUsedAtMs=Date.now(),this.promptReleaseAfterPrompt(m,u(t.metadata)?t.metadata:{})&&await this.closeSession(g,"release_after_prompt")}}async updatePolicy(t){if(this.assertDispatchable(),!this.config.sandboxRequired)throw Object.assign(new Error("runtime sandbox policy updates require an enforced sandbox"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"});let r=a(t.agentId),n=a(t.runId),s=a(t.sessionId),i=a(t.correlationId);if(!r||!n||!s||!i)throw Object.assign(new Error("agentId, runId, sessionId and correlationId are required"),{code:"BAD_REQUEST"});let o=K(t.sandboxPolicy),c=this.operations.get(i);if(c&&(c.agentId!==r||c.sessionId!==s||c.identity.runId!==n))throw Object.assign(new Error(`runtime operation policy identity conflict: ${i}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let l=`${r}:${s}`,d=this.sessions.get(l);if(d&&d.runId!==n)throw Object.assign(new Error(`runtime session policy identity conflict: ${s}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});let f=d?.sandboxPolicy||c?.sandboxPolicy;if(!f)throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"});let p=Number(f.policyRevision),g=Number(o.policyRevision);if(g<p)throw Object.assign(new Error("runtime sandbox policy revision is stale"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:p});if(g===p){if(F(f)!==F(o))throw Object.assign(new Error("runtime sandbox policy revision payload conflicts"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:p});return{updated:!1,idempotent:!0,policyRevision:p,accessMode:f.accessMode}}let m=vr(f,o);c&&(c.sandboxPolicy=structuredClone(o)),d&&(d.sandboxPolicy=structuredClone(o));let S=!1;return m&&d?.busy===!0&&(await d.runtime.sessionCancel({sessionId:d.runtimeSessionId}),S=await this.closeSession(l,"sandbox_policy_downgrade")),{updated:!0,policyRevision:g,accessMode:o.accessMode,activeCommandCancelled:S,deferredToNextLaunch:!m&&d?.busy===!0}}async cancel(t){let r=a(t.agentId),n=a(t.sessionId),s=a(t.correlationId);if(s){let c=this.operations.get(s);if(!c||c.status!=="running")return{cancelled:!1,correlationId:s,reason:"operation_not_running"};if(c.agentId!==r||c.sessionId!==n)throw Object.assign(new Error(`runtime operation cancellation identity conflict: ${s}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let l=this.sessions.get(`${r}:${n}`);return!l||l.busy!==!0||l.operationCorrelationId!==s?{cancelled:!1,correlationId:s,reason:"operation_not_running"}:(await l.runtime.sessionCancel({sessionId:l.runtimeSessionId}),await this.closeSession(`${r}:${n}`,"cancelled"),{cancelled:!0,correlationId:s})}let i=`${r}:${n}`,o=this.sessions.get(i);return o?(await o.runtime.sessionCancel({sessionId:o.runtimeSessionId}),await this.closeSession(i,"cancelled"),{cancelled:!0}):{cancelled:!1}}async dispatch(t,r={}){let n=a(t.agentId),s=a(t.taskId),i=a(t.executionId);if(!n||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let o=a(t.sessionId)||`dispatch-${i||s}`,c=a(t.instructions),l=Yi(t),d=Wr(t),{target:f}=this.targetFor(t.targetCode||t.framework),p=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",c?`instructions: ${c}`:"",l?"orchaContext:":"",l,l?"Use orchaContext as the source of truth for upstream outputs, review reports, artifacts, and workflow metadata.":"","Follow the execution protocol in instructions exactly.","When embedding a generated artifact in final Markdown, use the Orcha artifact placeholder as the link target: orcha-artifact://<fieldKey>/<index>.","Example: use ![illustration](orcha-artifact://image/0) for the first generated image artifact.","Do not use local filesystem paths, file:// URLs, or data: URLs in final Markdown; Orcha replaces artifact placeholders after ingestion.",d?`For decision results, put the raw report between ${Ar} and ${Cr}.`:"",d?`Then put a JSON object containing _decision between ${Nr} and ${br}.`:"",d?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
17
- `)}];return this.prompt({...t,agentId:n,sessionId:o,prompt:p,metadata:Xi(t,f)},r)}async requestPermission({agent:t,runtimeSessionId:r,request:n,emitUpdate:s}){let i=kt(),c=this.runtimeSessionIndex.get(`${t.agentId}:${r}`)?.sessionId||r||kt(),l={permissionId:i,agentId:t.agentId,sessionId:c,runtimeSessionId:r,request:u(n)?n:{},status:"pending",createdAt:ot()};return s?.({sessionId:r,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=T(n?.timeoutMs,this.config.permissionRequestTimeoutMs),p=setTimeout(()=>{this.pendingPermissions.delete(i),d({permissionId:i,outcome:"denied",response:{reason:"permission request timed out"}})},f);this.pendingPermissions.set(i,{timer:p,resolve:d,permission:l})})}async respondPermission(t){let r=a(t.permissionId),n=this.pendingPermissions.get(r),s=a(t.outcome||"approved")||"approved";return n?(clearTimeout(n.timer),this.pendingPermissions.delete(r),n.resolve({permissionId:r,outcome:s,response:u(t.response)?t.response:{},userId:a(t.userId),metadata:u(t.metadata)?t.metadata:{}}),{accepted:!0,permissionId:r,outcome:s}):{accepted:!1,permissionId:r,outcome:s}}health(){return{status:this.config.sandboxRequired&&!this.sandboxCapabilities.dispatchable?"unavailable":"ok",bridgeVersion:Y,startedAt:this.startedAt,agents:[...this.agents.values()].map(t=>({agentId:t.agentId,targetCode:t.targetCode,framework:t.framework,runtimeKind:t.runtimeKind})),sessions:this.sessions.size,pendingPermissions:this.pendingPermissions.size,targets:Object.keys(this.targets),sandboxCapabilities:this.sandboxCapabilities}}};import fo from"node:http";import po from"node:https";import{randomBytes as Yr}from"node:crypto";var et=1,V=3,mo=1e4,vt=class{constructor(t,r={}){this.url=t,this.readyState=0,this.socket=null,this.request=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,this.connectTimeoutMs=ho(r.connectTimeoutMs,mo),this.connectTimer=null,this.connect()}addEventListener(t,r){let n=this.listeners.get(t)||new Set;n.add(r),this.listeners.set(t,n)}emit(t,r={}){let n=this.listeners.get(t);if(n)for(let s of n)s(r)}connect(){let t=new URL(this.url),r=t.protocol==="wss:"?po:fo,n=Yr(16).toString("base64"),s=r.request({protocol:t.protocol==="wss:"?"https:":"http:",hostname:t.hostname,port:t.port||(t.protocol==="wss:"?443:80),path:`${t.pathname}${t.search}`,method:"GET",headers:{Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Key":n,"Sec-WebSocket-Version":"13"}});this.request=s,this.startConnectTimer(s),s.on("upgrade",(i,o,c)=>{if(this.clearConnectTimer(),this.readyState===V){o.destroy();return}this.socket=o,this.readyState=et,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==V&&this.emit("error",{error:l,message:l.message,type:"error"}),this.onClose()}),c?.length&&this.onData(c),this.emit("open")}),s.on("response",i=>{this.clearConnectTimer(),this.emit("error",{message:`websocket upgrade failed: HTTP ${i.statusCode}`,type:"error"}),i.resume(),this.onClose()}),s.on("error",i=>{this.clearConnectTimer(),this.readyState!==V&&this.emit("error",{error:i,message:i.message,type:"error"}),this.onClose()}),s.end()}startConnectTimer(t){this.connectTimeoutMs<=0||(this.connectTimer=setTimeout(()=>{if(this.readyState===et||this.readyState===V)return;let r=`websocket connect timeout after ${this.connectTimeoutMs}ms`;this.emit("error",{message:r,type:"timeout"}),this.onClose(),t.destroy(new Error(r))},this.connectTimeoutMs),this.connectTimer.unref?.())}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}send(t){!this.socket||this.readyState!==et||this.socket.write(be(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==V){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===et&&this.socket.write(be(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==V&&(this.clearConnectTimer(),this.readyState=V,this.request=null,this.emit("close"))}onData(t){for(this.buffer=Buffer.concat([this.buffer,t]);this.buffer.length>=2;){let r=this.buffer[0],n=this.buffer[1],s=r&15,i=(n&128)!==0,o=n&127,c=2;if(o===126){if(this.buffer.length<c+2)return;o=this.buffer.readUInt16BE(c),c+=2}else if(o===127){if(this.buffer.length<c+8)return;let f=this.buffer.readUInt32BE(c),p=this.buffer.readUInt32BE(c+4);o=f*2**32+p,c+=8}let l=c;if(i&&(c+=4),this.buffer.length<c+o)return;let d=this.buffer.subarray(c,c+o);if(i){let f=this.buffer.subarray(l,l+4);d=Buffer.from(d.map((p,g)=>p^f[g%4]))}this.buffer=this.buffer.subarray(c+o),s===1?this.emit("message",{data:d.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write(be(10,d))}}};function ho(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function be(e,t){let r=t.length,n=2;r>=126&&r<=65535?n+=2:r>65535&&(n+=8);let s=Yr(4),i=Buffer.alloc(n+4+r);i[0]=128|e;let o=2;r<126?i[1]=128|r:r<=65535?(i[1]=254,i.writeUInt16BE(r,o),o+=2):(i[1]=255,i.writeUInt32BE(Math.floor(r/2**32),o),i.writeUInt32BE(r>>>0,o+4),o+=8),s.copy(i,o),o+=4;for(let c=0;c<r;c+=1)i[o+c]=t[c]^s[c%4];return i}function go(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol!=="ws:"&&t.protocol!=="wss:")throw new Error(`unsupported ORCHA_RUNTIME_ORCHA_URL protocol: ${t.protocol}`);return t.pathname=`${t.pathname.replace(/\/+$/,"")}/api/agent-runtime-bridge/ws`,t.search="",t.toString()}function Me(e,t=!0){return Object.entries(e||{}).map(([r,n])=>({targetCode:r,targetName:a(n?.name||n?.targetName||r),targetType:a(n?.type||"echo"),status:t?"available":"unavailable"}))}var Ft=class{constructor(t,r){this.config=t,this.bridge=r,this.ws=null,this.stopped=!1,this.connected=!1,this.reconnectTimer=null,this.heartbeatTimer=null}sandboxCapabilities(){return this.bridge.sandboxCapabilities||{dispatchable:this.config.sandboxRequired!==!0,enforced:!1,backend:"development_direct",daemonStatus:"development_only",policySchemaVersions:[1],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:!1}}start(){this.connect()}stop(){this.stopped=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.ws?.close()}connect(){if(this.stopped)return;let t=go(this.config.orchaUrl),r=new vt(t,{connectTimeoutMs:this.config.connectTimeoutMs});this.ws=r,r.addEventListener("open",()=>{if(this.ws!==r||this.stopped){r.close();return}this.authenticate(r)}),r.addEventListener("message",n=>this.handleMessage(n.data,r)),r.addEventListener("close",()=>this.scheduleReconnect("close",r)),r.addEventListener("error",n=>{h("warn","orcha-client","runtime node websocket error",{error:String(n?.message||n?.type||n)})})}authenticate(t=this.ws){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:Y,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,sandboxCapabilities:this.sandboxCapabilities(),targets:Me(this.config.targets,this.sandboxCapabilities().dispatchable===!0)},t)}scheduleReconnect(t,r=this.ws){r&&this.ws!==r||(this.connected=!1,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,r&&this.ws===r&&(this.ws=null),!this.stopped&&(this.reconnectTimer||(h("info","orcha-client","runtime node disconnected; reconnect scheduled",{reason:t,reconnectMs:this.config.reconnectMs}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},this.config.reconnectMs))))}async handleMessage(t,r=this.ws){if(r&&this.ws!==r)return;let n;try{n=JSON.parse(String(t))}catch(s){h("warn","orcha-client","invalid Orcha websocket frame",{error:String(s)});return}if(u(n)){if(n.type==="runtime_node.authenticated"){if(r&&this.ws!==r)return;this.connected=!0,this.startHeartbeat(r),h("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:n.connectionId});return}if(n.type==="orcha.runtime.request"){await this.handleRequest(n);return}n.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString(),sandboxCapabilities:this.sandboxCapabilities(),targets:Me(this.config.targets,this.sandboxCapabilities().dispatchable===!0)})}}startHeartbeat(t){this.heartbeatTimer&&clearInterval(this.heartbeatTimer);let r=Math.max(1e3,Number(this.config.heartbeatIntervalMs||15e3)),n=()=>this.send({type:"runtime_node.heartbeat",ts:new Date().toISOString(),sandboxCapabilities:this.sandboxCapabilities(),targets:Me(this.config.targets,this.sandboxCapabilities().dispatchable===!0)},t);n(),this.heartbeatTimer=setInterval(n,r),this.heartbeatTimer.unref?.()}async handleRequest(t){let r=a(t.id),n=a(t.method),s=u(t.params)?t.params:{};try{let i=await this.invoke(n,s,r);this.send({type:"orcha.runtime.response",id:r,ok:!0,result:i})}catch(i){this.send({type:"orcha.runtime.response",id:r,ok:!1,error:{code:i.code||"RUNTIME_NODE_ERROR",message:i.message||String(i)}})}}async invoke(t,r,n){if(t==="health")return this.bridge.health();if(t==="agents/create")return this.bridge.createAgent(r);if(t==="agents/dispatch")return this.bridge.dispatch(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/prompt")return this.bridge.prompt(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/policy")return this.bridge.updatePolicy(r);if(t==="sessions/cancel")return this.bridge.cancel(r);if(t==="permissions/respond")return this.bridge.respondPermission(r);throw Object.assign(new Error(`unsupported Orcha runtime method: ${t}`),{code:"METHOD_NOT_FOUND"})}sendUpdate(t,r){this.send({type:"orcha.runtime.event",requestId:t,eventType:"runtime.update",payload:r})}send(t,r=this.ws){return!r||r!==this.ws||r.readyState!==et?!1:(r.send(JSON.stringify(t)),!0)}};import{existsSync as Qr,readFileSync as _o}from"node:fs";import{dirname as To,resolve as Ht}from"node:path";import{fileURLToPath as yo}from"node:url";var Ro=/^[A-Za-z_][A-Za-z0-9_]*$/;function Zr(e=process.env,t=process.cwd()){let r=a(e.ORCHA_RUNTIME_ENV_FILE),n=r?Ht(t,r):Ht(t,".env");if(!Qr(n))return r&&h("warn","config","runtime env file not found",{path:n}),{loaded:!1,path:n,keys:[]};let s=[],i=_o(n,"utf8");for(let o of i.split(/\r?\n/)){let c=wo(o);if(!c)continue;let[l,d]=c;Object.prototype.hasOwnProperty.call(e,l)||(e[l]=d,s.push(l))}return h("info","config","runtime env file loaded",{path:n,keyCount:s.length}),{loaded:!0,path:n,keys:s}}function tn(e=process.env){let t=a(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),r=a(e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1"),n=!1,s=To(yo(import.meta.url)),i=Ht(s,"sandbox","broker.js"),o=Ht(s,"orcha-runtime-sandbox-broker.js"),c=Qr(i)?i:o,l=a(e.ORCHA_RUNTIME_SANDBOX_BROKER_COMMAND);return{mode:t,host:r,port:T(e.ORCHA_RUNTIME_BRIDGE_PORT,5588),token:e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",orchaUrl:a(e.ORCHA_RUNTIME_ORCHA_URL),nodeToken:e.ORCHA_RUNTIME_NODE_TOKEN||e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",nodeId:a(e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"local-runtime-node"),nodeName:a(e.ORCHA_RUNTIME_NODE_NAME||e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"Local Runtime Node"),reconnectMs:T(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),connectTimeoutMs:T(e.ORCHA_RUNTIME_CONNECT_TIMEOUT_MS||e.ORCHA_RUNTIME_WS_CONNECT_TIMEOUT_MS,1e4),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:T(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),sessionPromptTimeoutMs:T(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,36e5),permissionRequestTimeoutMs:T(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:T(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:T(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:T(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:T(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:T(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),heartbeatIntervalMs:T(e.ORCHA_RUNTIME_HEARTBEAT_INTERVAL_MS,15e3),sandboxRequired:n,sandboxBrokerCommand:l||process.execPath,sandboxBrokerArguments:Ue(e.ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS,"ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS",l?[]:[c]),sandboxProbeTimeoutMs:T(e.ORCHA_RUNTIME_SANDBOX_PROBE_TIMEOUT_MS,1e4),sandboxTempRoot:a(e.ORCHA_RUNTIME_SANDBOX_TEMP_ROOT),trustedWorkspaceRoots:Ue(e.ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS,"ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS"),trustedToolchainRoots:Ue(e.ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS,"ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS"),egressProxyRequired:Eo(e.ORCHA_RUNTIME_EGRESS_PROXY_REQUIRED,t==="node"),egressProxySocket:a(e.ORCHA_RUNTIME_EGRESS_PROXY_SOCKET),egressProxyToken:a(e.ORCHA_RUNTIME_EGRESS_PROXY_TOKEN),egressGrantMaxTtlMs:T(e.ORCHA_RUNTIME_EGRESS_GRANT_MAX_TTL_MS,9e5),targets:So(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function So(e){if(!a(e))return{};try{let t=JSON.parse(e);if(u(t))return t}catch(t){h("warn","config","invalid ORCHA_RUNTIME_TARGETS_JSON",{error:String(t)})}return{}}function Eo(e,t){let r=a(e).toLowerCase();if(!r)return t;if(["true","1","yes","on"].includes(r))return!0;if(["false","0","no","off"].includes(r))return!1;throw new Error(`invalid boolean configuration value: ${r}`)}function Ue(e,t,r=[]){let n=a(e);if(!n)return[...r];let s;try{s=JSON.parse(n)}catch{throw new Error(`${t} must be a JSON string array`)}if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw new Error(`${t} must be a JSON string array`);return s.map(i=>i.trim()).filter(Boolean)}function wo(e){let t=e.trim();if(!t||t.startsWith("#"))return null;let r=t.startsWith("export ")?t.slice(7).trimStart():t,n=r.indexOf("=");if(n<=0)return null;let s=r.slice(0,n).trim();if(!Ro.test(s))return null;let i=Io(r.slice(n+1).trim());return[s,i]}function Io(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let r=e.slice(1,-1);return t==='"'?Oo(r):r}return xo(e).trim()}function Oo(e){return e.replaceAll("\\n",`
18
- `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function xo(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n],i=e[n-1];if(s==="'"&&!r)t=!t;else if(s==='"'&&!t&&i!=="\\")r=!r;else if(s==="#"&&!t&&!r&&/\s/.test(i||""))return e.slice(0,n)}return e}import{createServer as Ao}from"node:http";function $t(e,t,r){let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(n)}),e.end(n)}function z(e={}){return{ok:!0,...e}}function Pe(e,t,r){return{ok:!1,error:{code:e,message:t,...r===void 0?{}:{detail:r}}}}async function en(e,t){let r=[],n=0;for await(let i of e){if(n+=i.length,n>t)throw Object.assign(new Error("request body too large"),{status:413,code:"REQUEST_TOO_LARGE"});r.push(i)}if(r.length===0)return{};let s=Buffer.concat(r).toString("utf8");if(!s.trim())return{};try{let i=JSON.parse(s);if(!u(i))throw Object.assign(new Error("JSON body must be an object"),{status:400,code:"BAD_JSON"});return i}catch(i){throw i.status?i:Object.assign(new Error(`invalid JSON body: ${i.message}`),{status:400,code:"BAD_JSON"})}}function rn(e,t){if(!t)return;if((e.headers.authorization||"")!==`Bearer ${t}`)throw Object.assign(new Error("runtime bridge token is invalid"),{status:401,code:"UNAUTHORIZED"})}function nn(e,t){let r={"GET /health":async()=>z(t.health()),"POST /agents/create":async n=>z(await t.createAgent(n)),"POST /agents/dispatch":async n=>z(await t.dispatch(n)),"POST /sessions/prompt":async n=>z(await t.prompt(n)),"POST /sessions/cancel":async n=>z(await t.cancel(n)),"POST /permissions/respond":async n=>z(await t.respondPermission(n))};return Ao(async(n,s)=>{let i=new URL(n.url||"/",`http://${n.headers.host||`${e.host}:${e.port}`}`),o=`${n.method||"GET"} ${i.pathname}`,c=r[o];if(!c){$t(s,404,Pe("NOT_FOUND",`No route for ${o}`));return}try{rn(n,e.token);let l=n.method==="GET"?{}:await en(n,e.requestLimitBytes);$t(s,200,await c(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";$t(s,d,Pe(f,l.message||String(l)))}})}var Lo=ko(import.meta.url),Do=".orcha-runtime-bridge.pid",vo=".orcha-runtime-bridge.log",Fo=3,Ho=36e5,{command:$o,options:mn}=Go(process.argv.slice(2));Ko(mn);Zr();var Bo=tn();await qo($o,Bo,mn);async function qo(e,t,r){switch(e){case"run":case"foreground":await on(t);return;case"start":if(r.foreground){await on(t);return}cn();return;case"reload":case"restart":await un({quiet:!0}),cn();return;case"stop":await un();return;case"status":jo();return;case"help":case"--help":case"-h":Jo();return;default:throw new Error(`Unknown command: ${e}`)}}async function on(e){Vo();let t=new Dt(e);if(await t.start(),e.mode==="server"){let n=nn(e,t);an({bridge:t,server:n}),n.listen(e.port,e.host,()=>{h("info","runtime-bridge","Orcha runtime bridge HTTP server started",{host:e.host,port:e.port,targets:Object.keys(t.targets)})});return}if(!e.orchaUrl)throw new Error("ORCHA_RUNTIME_ORCHA_URL is required in runtime node mode");let r=new Ft(e,t);an({bridge:t,client:r}),r.start(),h("info","runtime-bridge","Orcha runtime node started",{nodeId:e.nodeId,nodeName:e.nodeName,orchaUrl:e.orchaUrl,targets:Object.keys(t.targets)})}function an({bridge:e,client:t,server:r}){let n=!1,s=i=>{if(n)return;n=!0;let o=Number(e?.sessions?.size||0)>0;h("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(c){h("warn","runtime-bridge","runtime client stop failed",{error:String(c)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(c=>{h("warn","runtime-bridge","runtime bridge stop failed",{error:String(c)})}).finally(()=>{try{r?.close?.()}catch(c){h("warn","runtime-bridge","runtime server close failed",{error:String(c)})}}),setTimeout(()=>process.exit(0),o?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function cn(){let e=Fe(),t=hn(),r=He(e);if(r&&rt(r)){console.log(JSON.stringify({status:"already_running",pid:r,pidFile:e,logFile:t}));return}r&&De(e),dn(e),dn(t),Le(t);let n=Mo(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=Co(process.execPath,[Lo,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",n,n]});i.unref(),No(n),pn(e,`${i.pid}
19
- `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function un({quiet:e=!1}={}){let t=Fe(),r=He(t);if(!r){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!rt(r)){De(t),e||console.log(JSON.stringify({status:"not_running",pid:r,pidFile:t}));return}process.kill(r,"SIGTERM"),!await ln(r,1e4)&&rt(r)&&(process.kill(r,"SIGKILL"),await ln(r,3e3)),De(t),e||console.log(JSON.stringify({status:"stopped",pid:r,pidFile:t}))}function jo(){let e=Fe(),t=hn(),r=He(e),n=!!(r&&rt(r));console.log(JSON.stringify({status:n?"running":"not_running",running:n,pid:n?r:null,pidFile:e,logFile:t}))}function Go(e){let t=[],r={};for(let s=0;s<e.length;s+=1){let i=e[s];i==="--daemon"?r.daemon=!0:i==="--foreground"?r.foreground=!0:i==="--env-file"?r.envFile=e[++s]:i==="--pid-file"?r.pidFile=e[++s]:i==="--log-file"?r.logFile=e[++s]:t.push(i)}return{command:t[0]||"run",options:r}}function Ko(e){e.envFile&&(process.env.ORCHA_RUNTIME_ENV_FILE=e.envFile),e.pidFile&&(process.env.ORCHA_RUNTIME_PID_FILE=e.pidFile),e.logFile&&(process.env.ORCHA_RUNTIME_LOG_FILE=e.logFile)}function Fe(){return ve(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Do)}function hn(){return ve(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||vo)}function Vo(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=gn();if(t<=0)return;let r=ve(process.cwd(),e);Le(r,t);let n=Wo();n<=0||setInterval(()=>Le(r,t),n).unref()}function Le(e,t=gn()){if(t<=0||!fn(e))return;let r=0,n="";try{if(r=sn(e).size,r<=0)return;n=ke(e,"utf8")}catch(d){h("warn","runtime-bridge","runtime log cleanup skipped",{logFile:e,error:String(d)});return}let s=Date.now()-t*24*60*60*1e3,i=n.split(/\r?\n/),o=[],c=0;for(let d of i)d&&(zo(d,s)?o.push(d):c+=1);if(c===0)return;let l="";try{sn(e).size>r&&(l=ke(e,"utf8").slice(n.length));let f=[...o,...l.split(/\r?\n/).filter(Boolean)].join(`
20
- `);pn(e,f?`${f}
21
- `:""),h("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:c})}catch(d){h("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(d)})}}function zo(e,t){try{let r=JSON.parse(e);if(!r||typeof r!="object")return!0;let n=typeof r.ts=="string"?Date.parse(r.ts):Number.NaN;return!Number.isFinite(n)||n>=t}catch{return!0}}function gn(){return _n(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,Fo)}function Wo(){return _n(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Ho)}function _n(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function He(e){if(!fn(e))return null;let t=Number.parseInt(ke(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function rt(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function ln(e,t){let r=Date.now();for(;Date.now()-r<t;){if(!rt(e))return!0;await new Promise(n=>setTimeout(n,100))}return!rt(e)}function dn(e){bo(Po(e),{recursive:!0})}function De(e){try{Uo(e,{force:!0})}catch{}}function Jo(){console.log(`Usage: orcha-runtime-bridge [command] [options]
10
+ ${s}`:s;Nr(t,r,n,d,s)&&(o=1,c=1)}return s&&i&&(t.finalTextSeen=!0),xr(t,Or(e,t.artifactOptions)),(qs(e)||js(e)||Gs(e)||i)&&n({sessionId:r,update:{sessionUpdate:"runtime_event",event:Ar(e)}}),{textCount:o,finalTextCount:c,thoughtCount:l}}function ne(e,t,r,n,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0,thoughtCount:0};let i=e.artifacts.size,o=0,c=0,l=0,d=0,f=$s(t,r,s);if(f){let p=Math.min(t.processedLines.get(f.path)||0,f.events.length),_=e.artifacts.size;for(let m of f.events.slice(p)){let R=Ks(m,e,r,n);c+=R.textCount,l+=R.finalTextCount,d+=R.thoughtCount}t.processedLines.set(f.path,f.events.length),(f.events.length>p||e.artifacts.size>_)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:c,finalTextCount:l,thoughtCount:d}}function Vs(e,{remove:t=!0}={}){if(!e||!yr(e))return"";try{return Sr(e,"utf8").trim()}catch{return""}finally{t&&bt(e)}}function bt(e){if(e)try{ns(e)}catch{}}function zs(e,t){return{artifactCount:(e?.artifactCount||0)+(t?.artifactCount||0),transcriptCount:(e?.transcriptCount||0)+(t?.transcriptCount||0),textCount:(e?.textCount||0)+(t?.textCount||0),finalTextCount:(e?.finalTextCount||0)+(t?.finalTextCount||0),thoughtCount:(e?.thoughtCount||0)+(t?.thoughtCount||0)}}function Ws(e){return new Promise(t=>setTimeout(t,e))}function Js(e,t,r,n){return n?(e.finalTextSeen=!0,e.emittedTexts.has(n)||(e.emittedTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}})),!0):!1}async function Xs(e,t,r,n,s,i){let o=ne(e,t,r,n,Date.now()),c=()=>Js(e,r,n,Vs(s,{remove:!1}));if(c()||e.finalTextSeen)return bt(s),o;let l=Rs(i);if(l<=0||!t&&!s)return bt(s),o;let d=Date.now()+l,f=Math.min(Cr(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await Ws(Math.min(f,Math.max(0,d-Date.now()))),o=zs(o,ne(e,t,r,n,Date.now())),!c()););return bt(s),o}var Pt=class{constructor(t,r,n={}){this.agent=t,this.target=r,this.options=n,this.active=new Map}async sessionNew(){return{sessionId:`cli-${this.agent.agentId}-${tt()}`}}async sessionPrompt(t,r,n){let s=Date.now(),i=a(this.target.command);if(!i)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let o=a(t.sessionId)||tt(),c=Et(t.prompt),l=a(this.target.promptMode||"stdin"),d=this.buildArgs(l,c),f=Z(this.target,this.agent.workspace),p=typeof this.options.prepareLaunch=="function",m=Ts(i,d,this.target)?p?`/tmp/orcha-runtime-last-message-${tt()}.txt`:L(Er(),`orcha-runtime-last-message-${tt()}.txt`):"";m&&d.push("--output-last-message",m);let R={...u(this.target.env)?this.target.env:{},...l==="env"?{ORCHA_RUNTIME_PROMPT:c}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:o},O=p?await this.options.prepareLaunch({command:i,args:d,cwd:f,environment:R}):{command:i,args:d,cwd:f,environment:{...process.env,...R},cleanup:async()=>{}},N=p?Cs(O):As(this.target,o),T=N.root,y=bs(this.target,T,O),E=ys(i,this.target),A={...this.target,targetCode:this.agent.targetCode,cwd:f,...p?{codexHome:L(O.homeDirectory,".codex")}:{}},W=E?Ps(A,s):new Set,Tt=p&&m?L(O.tempDirectory,m.slice(5)):m,J=g(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,g(this.options.sessionPromptTimeoutMs,os));p||(O.environment.ORCHA_RUNTIME_ARTIFACT_DIR=T);let I=Tr(O.command,O.args,{cwd:O.cwd,env:O.environment,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(o,I),h("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:o,pid:I.pid,timeoutMs:J,isolation:O.isolation});let We="",Kt=a(this.target.outputMode||"text"),b={artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:y,finalTextSeen:!1,finalTextOnly:Is(t,this.target),emitThoughtChunks:Es(t,this.target),terminalOutcome:null,terminalProtocol:hs(this.target),emitTerminal:null},Vt=E?xs(A,c,s,W):null;return I.stdout.setEncoding("utf8"),I.stdout.on("data",X=>this.handleStdout(X,Kt,b,o,r)),I.stderr.setEncoding("utf8"),I.stderr.on("data",X=>{We+=X,this.target.emitStderr===!0&&r({sessionId:o,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:X}}})}),l==="stdin"?I.stdin.end(c):I.stdin.end(),await new Promise((X,zt)=>{let st=!1,Je=!1,yt=null,it=null,Wt=Vt&&Ss(this.target,t)?setInterval(()=>{try{ne(b,Vt,o,r)}catch(w){h("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:o,error:String(w?.message||w)})}},Cr(this.target)):null;Wt?.unref?.();let Xe=setTimeout(()=>{Je=!0,h("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:o,pid:I.pid,timeoutMs:J}),Mt(I,"SIGTERM"),yt=setTimeout(()=>{h("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:o,pid:I.pid}),Mt(I,"SIGKILL")},wr),yt.unref?.(),ot(Object.assign(new Error(`runtime CLI timed out after ${J}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},J);Xe.unref?.();let Ye=async()=>{clearTimeout(Xe),it&&clearTimeout(it),Wt&&clearInterval(Wt),yt&&!Je&&clearTimeout(yt),Ns(N,{target:this.agent.targetCode,sessionId:o}),this.active.delete(o),b.emitTerminal=null,await O.cleanup?.()},On=w=>{st||(st=!0,Ye().then(()=>X(w),zt))},ot=w=>{st||(st=!0,Ye().then(()=>zt(w),v=>{h("warn","runtime.cli","sandbox launch cleanup failed",{target:this.agent.targetCode,sessionId:o,error:String(v?.message||v)}),zt(w)}))};b.emitTerminal=w=>{let v={...u(w.result)?w.result:{},_artifacts:[...b.artifacts.values()]};try{n?.({...w,result:v})}catch(j){h("warn","runtime.cli","runtime terminal listener failed",{target:this.agent.targetCode,sessionId:o,error:String(j?.message||j)})}let k=Math.max(0,g(this.target.terminalExitGraceMs,fs));it=setTimeout(()=>{it=null,!(st||this.active.get(o)!==I)&&(h("warn","runtime.cli","runtime stayed alive after terminal event; terminating child",{target:this.agent.targetCode,sessionId:o,pid:I.pid,terminalProtocol:b.terminalProtocol,graceMs:k}),te(I))},k),it.unref?.()},I.on("error",w=>{h("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:o,pid:I.pid,error:String(w?.message||w)}),ot(w)}),I.on("exit",(w,v)=>{(async()=>{Kt==="json-lines"&&b.value.trim()&&this.handleStdout(`
11
+ `,Kt,b,o,r);let k=await Xs(b,Vt,o,r,Tt,this.target);(k.artifactCount>0||k.textCount>0||k.thoughtCount>0)&&h("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:o,artifactCount:k.artifactCount,textCount:k.textCount,finalTextCount:k.finalTextCount,thoughtCount:k.thoughtCount,transcriptCount:k.transcriptCount});let j=We.trim();if(j&&h("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:o,stderr:j}),h("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:o,pid:I.pid,exitCode:w,signal:v,artifactCount:b.artifacts.size,finalTextSeen:b.finalTextSeen}),b.terminalOutcome?.status==="failed"){ot(b.terminalOutcome.error);return}if(w!==0&&b.terminalOutcome?.status!=="completed"){let xn=Object.assign(new Error(`runtime CLI exited with code ${w??"unknown"}${v?` (${v})`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:w,signal:v});ot(xn);return}On({stopReason:"end_turn",exitCode:w,signal:v,_artifacts:[...b.artifacts.values()],...j?{stderr:j}:{}})})().catch(ot)})})}buildArgs(t,r){let n=C(this.target.args);return t==="args"?[...n,r]:n}handleStdout(t,r,n,s,i){if(r!=="json-lines"){i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t}}});return}n.value+=t;let o=n.value.split(/\r?\n/);n.value=o.pop()||"";for(let c of o){let l=c.trim();if(l)try{let d=JSON.parse(l);xr(n,Or(d,n.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:Ar(d)}});let f=Ir(d),p=ie(d);f&&n.emitThoughtChunks&&!p&&_s(d)?br(n,s,i,f):f&&Os(n,p)&&Nr(n,s,i,f),f&&p&&(n.finalTextSeen=!0);let _=gs(d,n.terminalProtocol);_&&!n.terminalOutcome&&(_.status==="failed"||n.finalTextSeen||n.artifacts.size>0)&&(n.terminalOutcome=_,n.emitTerminal?.(_))}catch{i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${c}
12
+ `}}})}}}async sessionCancel(t){let r=a(t.sessionId),n=this.active.get(r);return n?(h("info","runtime.cli","cancelling runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid}),te(n),{ok:!0,cancelled:!0}):{ok:!0,cancelled:!1}}stop(t="stop"){for(let[r,n]of this.active.entries())h("info","runtime.cli","stopping runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid,reason:t}),te(n);this.active.clear()}};var ae="ORCHA_RUNTIME_OUTPUT_START",ce="ORCHA_RUNTIME_OUTPUT_END",ue="ORCHA_RUNTIME_CONTROL_START",le="ORCHA_RUNTIME_CONTROL_END",Dr=ae,vr=ce,Fr=ue,Hr=le,de=[ae,ce,ue,le],Ys=new Set(["_artifacts","_decision","_meta"]),Zs=new RegExp(`(?:^|(?<=[\\r\\n]))[ \\t]*(?<marker>${de.join("|")})[ \\t]*(?=\\r\\n?|\\n|$)`,"g"),D=class extends Error{constructor(t,r,n){super(r),this.name="RuntimeResultProtocolError",this.code=t,this.detail={rawOutput:n}}};function $r(e){let t=typeof e=="string"?e.trimStart():"";return de.some(r=>t.startsWith(r))}function fe(e){if(typeof e!="string")return null;let t=e,r=Qs(t);if(![...r.values()].some(m=>m.length>0))return null;let n=[],s=[];for(let[m,R]of r)R.length===0?n.push(m):R.length>1&&s.push(m);if(n.length>0||s.length>0){let m=[];throw n.length>0&&m.push(`\u7F3A\u5C11 ${n.join(", ")}`),s.length>0&&m.push(`\u91CD\u590D ${s.join(", ")}`),new D("invalid_markers",`Runtime Result \u534F\u8BAE\u6807\u8BB0\u4E0D\u5B8C\u6574\uFF1A${m.join("\uFF1B")}`,t)}let i=r.get(ae)[0],o=r.get(ce)[0],c=r.get(ue)[0],l=r.get(le)[0];if(!(i.end<=o.start&&o.end<=c.start&&c.end<=l.start))throw new D("invalid_marker_order","Runtime Result \u534F\u8BAE\u6807\u8BB0\u987A\u5E8F\u9519\u8BEF\uFF1A\u5FC5\u987B\u5148\u8F93\u51FA OUTPUT \u5757\uFF0C\u518D\u8F93\u51FA CONTROL \u5757",t);let d=ti(t.slice(i.end,o.start));if(!d.trim())throw new D("empty_output","Runtime Result OUTPUT \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let f=t.slice(c.end,l.start).trim();if(!f)throw new D("empty_control","Runtime Result CONTROL \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let p;try{p=JSON.parse(f)}catch(m){throw new D("invalid_control_json",`Runtime Result CONTROL \u5757\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(m?.message||m)}`,t)}if(!Lr(p))throw new D("invalid_control_type","Runtime Result CONTROL \u5757\u5FC5\u987B\u662F JSON \u5BF9\u8C61",t);let _=Object.keys(p).filter(m=>!Ys.has(m)).sort();if(_.length>0)throw new D("invalid_control_keys",`Runtime Result CONTROL \u5757\u5305\u542B\u975E\u6807\u51C6\u5B57\u6BB5\uFF1A${_.join(", ")}`,t);if("_artifacts"in p&&!Array.isArray(p._artifacts))throw new D("invalid_control_field_type","Runtime Result CONTROL \u5757\u7684 _artifacts \u5FC5\u987B\u662F JSON \u6570\u7EC4",t);for(let m of["_decision","_meta"])if(m in p&&!Lr(p[m]))throw new D("invalid_control_field_type",`Runtime Result CONTROL \u5757\u7684 ${m} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`,t);return{output:d,...p}}function Qs(e){let t=new Map(de.map(r=>[r,[]]));for(let r of e.matchAll(Zs))t.get(r.groups.marker).push({start:r.index,end:r.index+r[0].length});return t}function ti(e){let t=e.match(/^(?:\r\n|\r|\n)/)?.[0]||"",r=t?e.slice(t.length):e;return t&&r.endsWith(t)?r.slice(0,-t.length):r}function Lr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{createHash as ei}from"node:crypto";var ri="orcha.goal-contract/v1",ni=new Set(["complete","completed","done","ok","passed","success","succeeded"]),si=new Set(["aborted","blocked","cancelled","canceled","denied","error","failed","failure","timeout","timed_out"]),ii=new Map([["exec_command","run_command"],["local_shell_call","run_command"],["run_command","run_command"],["apply_patch","apply_patch"],["read_file","read_file"],["list_files","list_files"],["plugin_operation","plugin_operation"]]);function ge(e){return ei("sha256").update(H(e)).digest("hex")}function qr(e){if(!Gr(e))return"";let t=["The following Orcha goal contract is immutable for this turn. Do not narrow its outcome or constraints.",`<goal_contract>${JSON.stringify(e)}</goal_contract>`];return e.verificationPlan?.required===!0&&t.push("Every verification check must be satisfied by a real successful tool call from one of its toolNames.","A final text claim is not verification; missing or failed tool evidence prevents completion."),t.join(`
13
+ `)}function jr(e,t,r=""){if(!Gr(e))return e==null?null:{required:!0,status:"failed",outcome:a(e?.outcome),goalContractHash:"",checks:[],errorCode:"invalid_goal_contract"};let n=ge(e),s=e.verificationPlan.required===!0;if(a(r)&&a(r)!==n)return{required:s,status:"failed",outcome:e.outcome,goalContractHash:n,checks:[],errorCode:"goal_contract_hash_mismatch"};if(!s)return{required:!1,status:"not_required",outcome:e.outcome,goalContractHash:n,checks:[]};let i=oi(t),o=e.verificationPlan.checks.map(l=>mi(l,i));return{required:!0,status:o.some(l=>l.status==="failed")?"failed":o.some(l=>l.status==="missing")?"missing":"passed",outcome:e.outcome,goalContractHash:n,checks:o}}function Gr(e){if(!u(e)||e.schemaVersion!==ri||!a(e.outcome))return!1;let t=e.verificationPlan;if(!u(t)||typeof t.required!="boolean"||!Array.isArray(t.checks)||t.required&&t.checks.length===0)return!1;let r=new Set;for(let n of t.checks)if(!u(n)||!a(n.id)||r.has(a(n.id))||(r.add(a(n.id)),!Array.isArray(n.toolNames)||n.toolNames.length===0||n.toolNames.some(s=>!a(s)))||n.arguments!==void 0&&!u(n.arguments))return!1;return!0}function oi(e){let t=new Map,r=[];for(let n of Array.isArray(e)?e:[]){let s=u(n?.update)?n.update:{},i=a(s.sessionUpdate);if(i==="runtime_event"){ai(s.event,t,r);continue}if(i==="tool_call"){let o=Lt(s)||`tool-${r.length+1}`,c=kt(t,r,o),l=pe(s,s.name||s.toolName||s.kind);c.toolName=l.toolName,c.arguments=l.arguments,c.status=ft(s.status),c.evidence=vt(s);continue}if(i==="tool_call_update"){let o=Lt(s);if(!o)continue;let c=kt(t,r,o),l=pe(s,s.name||s.toolName||s.kind);c.toolName||=l.toolName,Object.keys(c.arguments).length===0&&(c.arguments=l.arguments),c.status=ft(s.status),c.evidence.push(...vt(s))}}return r}function ai(e,t,r){let n=u(e)&&u(e.payload)?e.payload:u(e)?e:{},s=a(n.type);if(["function_call","custom_tool_call","local_shell_call","mcp_tool_call"].includes(s)){let c=Lt(n)||`runtime-${r.length+1}`,l=kt(t,r,c),d=pe(n,n.name||n.tool||s,s);l.toolName=d.toolName,l.arguments=d.arguments,l.status=ft(n.status),l.evidence.push(...vt(n));return}if(!["function_call_output","custom_tool_call_output","local_shell_call_output","mcp_tool_call_output"].includes(s))return;let i=Lt(n);if(!i)return;let o=kt(t,r,i);o.status=di(n,o.toolName),o.evidence.push(...vt(n))}function kt(e,t,r){let n=e.get(r);return n||(n={toolCallId:r,toolName:"",arguments:{},status:"unknown",evidence:[]},e.set(r,n),t.push(n)),n}function ci(e){let t=a(e).toLowerCase();return ii.get(t)||t}function pe(e,t,r=""){let n=ui(e),s=a(r)==="mcp_tool_call"||a(e?.kind).toLowerCase()==="mcp",i=u(e?._meta)?e._meta:{},o=a(e?.server||e?.serverName||e?.server_name||e?.mcpServer||i.server||i.serverName).toLowerCase();if(s&&o==="orcha"){let c=a(e?.tool||e?.toolName||e?.name||t);return{toolName:"plugin_operation",arguments:{...n,...c?{operationCode:c}:{}}}}return{toolName:ci(t),arguments:n}}function Lt(e){return u(e)?a(e.call_id||e.callId||e.toolCallId||e.id):""}function ui(e){if(!u(e))return{};for(let r of["arguments","args","rawInput","input","params","parameters"]){let n=li(e[r]);if(n)return n}let t={};for(let r of["cmd","command","cwd","operationCode","path","query","url"])e[r]!==void 0&&(t[r]=e[r]);return t}function li(e){if(u(e))return structuredClone(e);if(typeof e!="string")return null;try{let t=JSON.parse(e);return u(t)?t:null}catch{return null}}function di(e,t){if(!u(e))return"unknown";let r=Dt(e,0,{parseCliExitCode:t==="run_command"||t==="apply_patch"});return r.includes("failed")?"failed":r.includes("success")?"success":"unknown"}function Dt(e,t=0,r={}){if(t>8||e===null||e===void 0)return[];if(typeof e=="string")return fi(e,t,r);if(Array.isArray(e))return e.flatMap(o=>Dt(o,t+1,r));if(!u(e))return[];let n=[];typeof e.isError=="boolean"&&n.push(e.isError?"failed":"success"),typeof e.ok=="boolean"&&n.push(e.ok?"success":"failed"),typeof e.success=="boolean"&&n.push(e.success?"success":"failed");let s=ft(e.status);s!=="unknown"&&n.push(s);let i=e.exitCode??e.exit_code;typeof i=="number"&&Number.isFinite(i)&&n.push(i===0?"success":"failed");for(let o of["output","result","structuredContent","content"])e[o]!==void 0&&n.push(...Dt(e[o],t+1,r));return n}function fi(e,t,r){let n=e.trim();if(!n)return[];try{return Dt(JSON.parse(n),t+1,r)}catch{}if(r.parseCliExitCode!==!0)return[];let s=[];for(let i of n.matchAll(/(?:process\s+exited\s+with\s+code|exit\s+code\s*:?)\s*(-?\d+)/gi))s.push(Number(i[1])===0?"success":"failed");return s}function ft(e){let t=a(e).toLowerCase();return ni.has(t)?"success":si.has(t)?"failed":"unknown"}function vt(e){if(!u(e))return[];let t=u(e.output)?e.output:{},r=[e.verificationEvidence,u(e.verification)?e.verification.evidence:null,t.verificationEvidence,u(t.verification)?t.verification.evidence:null],n=[];for(let s of r)for(let i of Array.isArray(s)?s:s?[s]:[])!u(i)||!a(i.id)||n.push({id:a(i.id),status:ft(i.status??(i.passed===!0?"passed":i.passed===!1?"failed":"")),...a(i.message)?{message:a(i.message)}:{}});return n}function mi(e,t){let r=t.filter(o=>e.toolNames.includes(o.toolName)&&he(e.arguments||{},o.arguments)),n=a(e.evidenceId),s=r.find(o=>o.status==="success"&&(!n||o.evidence.some(c=>c.id===n&&c.status==="success")));if(s)return me(e,"passed",s,"Runtime tool evidence passed.");let i=r.find(o=>o.status==="failed"||n&&o.evidence.some(c=>c.id===n&&c.status==="failed"));return i?me(e,"failed",i,"Runtime tool evidence failed."):me(e,"missing",r.at(-1),n?"Required evidence is missing.":"Required tool execution is missing.")}function me(e,t,r,n){return{id:e.id,status:t,message:n,...a(e.description)?{description:a(e.description)}:{},toolNames:e.toolNames,...u(e.arguments)?{arguments:e.arguments}:{},...a(e.evidenceId)?{evidenceId:a(e.evidenceId)}:{},...r?.toolCallId?{toolCallId:r.toolCallId}:{}}}function he(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>he(r,t[n])):u(e)?u(t)?Object.entries(e).every(([r,n])=>Object.hasOwn(t,r)&&he(n,t[r])):!1:Object.is(e,t)}function H(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string")return Br(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("invalid_jcs_number");return JSON.stringify(Object.is(e,-0)?0:e)}if(Array.isArray(e))return`[${Array.from({length:e.length},(t,r)=>{if(!Object.hasOwn(e,r))throw new Error("invalid_jcs_json_value");return H(e[r])}).join(",")}]`;if(u(e))return`{${Object.keys(e).sort().map(t=>`${Br(t)}:${H(e[t])}`).join(",")}}`;throw new Error("invalid_jcs_json_value")}function Br(e){return pi(e),JSON.stringify(e)}function pi(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw new Error("invalid_jcs_unicode");t+=1}else if(r>=56320&&r<=57343)throw new Error("invalid_jcs_unicode")}}import{spawn as hi}from"node:child_process";import{createHash as gi,randomUUID as _i}from"node:crypto";import{constants as Ti}from"node:fs";import{access as yi,mkdir as _e,readdir as Ri,realpath as mt,rm as Si,stat as Ei}from"node:fs/promises";import wi from"node:http";import{tmpdir as Ii}from"node:os";import{isAbsolute as pt,join as et,relative as Kr,resolve as ye}from"node:path";var Re=1,Oi="orcha.process-isolation/v1",Se="orcha.egress-proxy/v1",Ft={read_only:0,workspace_write:1,workspace_network:2},Te={read_only:["read_only","denied"],workspace_write:["workspace_write","denied"],workspace_network:["workspace_write","restricted"]},xi=new Set([".env",".git-credentials",".netrc",".npmrc",".pypirc","credentials.json","secrets.json","id_rsa","id_ed25519"]);function K(e){if(!u(e))throw S("RUNTIME_SANDBOX_POLICY_REQUIRED","sandboxPolicy is required");let t=structuredClone(e),r=a(t.accessMode),n=a(t.accessModeCeiling);if(!(r in Te)||!(n in Te))throw S("RUNTIME_SANDBOX_POLICY_INVALID","unsupported runtime access mode");if(Ft[r]>Ft[n])throw S("RUNTIME_SANDBOX_POLICY_INVALID","access mode exceeds its ceiling");let[s,i]=Te[r];if(t.filesystemMode!==s||t.networkMode!==i)throw S("RUNTIME_SANDBOX_POLICY_INVALID","runtime access profile does not match its mode");if(Number(t.policySchemaVersion)!==Re||!Number.isInteger(Number(t.policyRevision))||Number(t.policyRevision)<1)throw S("RUNTIME_SANDBOX_POLICY_INVALID","unsupported sandbox policy schema or revision");for(let[c,l]of Object.entries({outsideWorkspaceAccess:"denied",hostAccess:"denied",hostEnvironmentAccess:"denied",dockerSocketAccess:"denied",environmentMode:"allowlist"}))if(t[c]!==l)throw S("RUNTIME_SANDBOX_POLICY_INVALID",`${c} cannot be relaxed`);let o=u(t.processIsolation)?t.processIsolation:{};if(o.mode!=="required"||o.backend==="direct")throw S("RUNTIME_SANDBOX_POLICY_INVALID","strong process isolation is required");if(Array.isArray(t.alwaysApprovedApprovalKeys)&&t.alwaysApprovedApprovalKeys.length)throw S("RUNTIME_SANDBOX_POLICY_INVALID","persistent runtime approvals are forbidden");return t}function Vr(e,t){let r=K(e),n=K(t);return Ft[n.accessMode]<Ft[r.accessMode]}async function zr(e){if(!e.sandboxRequired)return{dispatchable:!0,enforced:!1,backend:"direct",daemonStatus:"not_required",daemonProtocolVersion:"",policySchemaVersions:[Re],runtimePolicyUpdates:!1,workspaceSync:!1,egressProxy:!1,reason:"external_runtime_sandbox_not_required"};let t=await Jr(e.sandboxBrokerCommand,process.env.PATH||"");if(!t)throw S("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let r=await Mi(t,C(e.sandboxBrokerArguments),e.sandboxProbeTimeoutMs);if(r.enforced!==!0||a(r.protocolVersion)!=="orcha.runtime-sandbox-broker/v1"||!["bubblewrap","broker"].includes(a(r.backend)))throw S("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker did not report enforced isolation");let n=u(r.probes)?r.probes:{};for(let s of["emptyRoot","outsideWorkspaceDenied","hostFilesystemDenied","sensitiveFilesDenied","environmentAllowlist","dockerSocketDenied","networkNamespace","workspaceReadOnly","workspaceWrite","resourceLimits"])if(n[s]!==!0)throw S("RUNTIME_SANDBOX_UNAVAILABLE",`sandbox broker probe failed: ${s}`);return e.egressProxyRequired&&await ki(e),{dispatchable:!0,enforced:!0,backend:a(r.backend),daemonStatus:"ok",daemonProtocolVersion:a(r.protocolVersion||"orcha.runtime-sandbox-broker/v1"),policySchemaVersions:[Re],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:e.egressProxyRequired}}async function Ee(e,t,r){let n=a(t.workspace||t.cwd),s=a(r),i=n||(t.allowRequestWorkspace===!0?s:"");if(!i||!pt(i))throw S("RUNTIME_WORKSPACE_NOT_CONFIGURED","runtime target must configure an absolute trusted workspace");let o=await mt(i);if(!(await Ei(o)).isDirectory())throw S("RUNTIME_WORKSPACE_INVALID","runtime workspace is not a directory");if(!(e.trustedWorkspaceRoots.length?await Promise.all(e.trustedWorkspaceRoots.map(d=>mt(d))):[o]).some(d=>Ie(d,o)))throw S("RUNTIME_WORKSPACE_OUTSIDE_TRUSTED_ROOT","runtime workspace is outside trusted roots");return o}async function Wr({config:e,target:t,command:r,args:n,cwd:s,environment:i,runId:o,agentId:c,sessionId:l,sandboxPolicy:d}){if(!e.sandboxRequired)return{command:r,args:[...n],cwd:s,environment:{...process.env,...i},tempDirectory:"",isolation:{enforced:!1,backend:"development_direct"},cleanup:async()=>{}};let f=K(d),p=await Ee(e,t,s),_=await mt(s);if(!Ie(p,_))throw S("RUNTIME_WORKSPACE_CWD_INVALID","runtime cwd is outside its workspace");let m=await Jr(e.sandboxBrokerCommand,process.env.PATH||"");if(!m)throw S("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let R=`runtime-${gi("sha256").update(String(o)).digest("hex").slice(0,32)}`,O=ye(e.sandboxTempRoot||et(Ii(),"orcha-runtime-sandboxes"));await _e(O,{recursive:!0,mode:448});let N=et(O,`${R}-${_i()}`),T=et(N,"home"),y=et(N,"artifacts");await _e(T,{recursive:!0,mode:448}),await _e(y,{recursive:!0,mode:448});let E=f.networkMode==="restricted"?await Ui(e,{runId:String(o),instanceId:R,policyRevision:Number(f.policyRevision),ttlMs:Math.min(g(f.maxRuntimeSeconds,900)*1e3,e.egressGrantMaxTtlMs),maxTransferBytes:g(f.maxNetworkBytes,64*1024*1024)}):null,A={PATH:a(i.PATH||process.env.PATH),LANG:a(i.LANG||process.env.LANG||"C.UTF-8"),HOME:"/tmp/home",TMPDIR:"/tmp",USER:"orcha",LOGNAME:"orcha",SHELL:"/bin/sh",ORCHA_AGENT_ID:String(c),ORCHA_SESSION_ID:String(l),ORCHA_RUN_ID:String(o),ORCHA_RUNTIME_ARTIFACT_DIR:"/tmp/artifacts",...Ci(t,i)};A.HOME="/tmp/home",A.TMPDIR="/tmp",A.ORCHA_RUNTIME_ARTIFACT_DIR="/tmp/artifacts";let W={schemaVersion:Oi,runId:String(o),instanceId:R,workspace:p,cwd:_,filesystemMode:f.filesystemMode,networkMode:f.networkMode,environmentMode:"allowlist",deniedRelativePaths:await Ni(p),temporaryDirectory:N,egressProxy:E,environment:A,resourceLimits:bi(f),readOnlyToolchainRoots:await Ai(e,t)},Tt=!1,J=async()=>{if(!Tt){Tt=!0;try{E&&await Pi(e,E,{runId:String(o),instanceId:R})}finally{await Si(N,{recursive:!0,force:!0})}}};return{command:m,args:[...C(e.sandboxBrokerArguments),"--",r,...n],cwd:_,environment:{PATH:process.env.PATH||"",LANG:process.env.LANG||"C.UTF-8",ORCHA_PROCESS_ISOLATION_REQUEST:JSON.stringify(W)},tempDirectory:N,homeDirectory:T,artifactDirectory:y,pathMappings:[{runtimeRoot:"/tmp/artifacts",hostRoot:y},{runtimeRoot:"/tmp/home",hostRoot:T}],isolation:{enforced:!0,backend:"broker",instanceId:R,policyRevision:f.policyRevision},cleanup:J}}async function Ai(e,t){let r=C(t.toolchainRoots||t.sandboxToolchainRoots);if(!r.length)return[];let n=await Promise.all(C(e.trustedToolchainRoots).map(i=>mt(i)));if(!n.length)throw S("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","target toolchain roots require ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS");let s=[];for(let i of r){if(!pt(i))throw S("RUNTIME_TOOLCHAIN_ROOT_INVALID","toolchain roots must be absolute");let o=await mt(i);if(!n.some(c=>Ie(c,o)))throw S("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","toolchain root is outside trusted roots");s.push(o)}return[...new Set(s)]}function Ci(e,t){let r=u(e.env)?e.env:{},n={};for(let[s,i]of Object.entries(r))/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&i!=null&&(n[s]=String(i));for(let s of["ORCHA_RUNTIME_PROMPT","ORCHA_RUNTIME_ARTIFACT_DIR"])t[s]!=null&&(n[s]=String(t[s]));return n}async function Ni(e){let t=[],r=0,n=async s=>{let i;try{i=await Ri(s,{withFileTypes:!0})}catch(o){if(s===e)throw o;return}for(let o of i){if(r+=1,r>1e4)throw S("RUNTIME_WORKSPACE_SCAN_LIMIT_EXCEEDED","workspace contains more than 10000 entries");let c=et(s,o.name),l=Kr(e,c),d=o.name.toLowerCase();(xi.has(d)||d.startsWith(".env."))&&t.push(l),o.isDirectory()&&!o.isSymbolicLink()&&await n(c)}};return await n(e),t.sort()}function bi(e){return{maxCpuSeconds:Math.max(1,g(e.maxRuntimeSeconds,900)),maxMemoryBytes:g(e.maxMemoryBytes,2*1024*1024*1024),maxProcesses:g(e.maxProcesses,128),maxOpenFiles:g(e.maxOpenFiles,1024),maxFileBytes:g(e.maxFileBytes,64*1024*1024)}}async function Mi(e,t,r){return await new Promise((n,s)=>{let i=hi(e,[...t,"--probe"],{env:{PATH:process.env.PATH||"",LANG:"C.UTF-8"},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=[],c=[];i.stdout.on("data",d=>o.push(Buffer.from(d))),i.stderr.on("data",d=>c.push(Buffer.from(d)));let l=setTimeout(()=>i.kill("SIGKILL"),Math.max(1e3,r));i.once("error",s),i.once("close",d=>{if(clearTimeout(l),d!==0){s(S("RUNTIME_SANDBOX_UNAVAILABLE",Buffer.concat(c).toString("utf8").trim()||`sandbox probe exited with ${d}`));return}try{n(JSON.parse(Buffer.concat(o).toString("utf8")))}catch{s(S("RUNTIME_SANDBOX_UNAVAILABLE","sandbox probe returned invalid JSON"))}})})}async function Jr(e,t){let r=a(e);if(!r)return"";let n=pt(r)?[r]:String(t||"").split(":").filter(Boolean).map(s=>et(s,r));for(let s of n)try{return await yi(s,Ti.X_OK),s}catch{}return""}async function Ui(e,t){if(!e.egressProxyRequired)throw S("RUNTIME_EGRESS_UNAVAILABLE","restricted network requires the Egress Proxy");let r=await we(e,"POST","/v1/grants",{protocolVersion:Se,...t}),n={socketPath:e.egressProxySocket,grantId:a(r.grantId),credential:a(r.credential)};if(!n.grantId||!n.credential)throw S("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy returned an invalid grant");return n}async function Pi(e,t,r){await we(e,"POST",`/v1/grants/${encodeURIComponent(t.grantId)}/revoke`,{protocolVersion:Se,...r}).catch(()=>{})}async function ki(e){let t=await we(e,"GET","/health");if(t.status!=="ok"||t.proxy!=="orcha-egress-proxy"||t.protocolVersion!==Se)throw S("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy is unavailable or incompatible")}async function we(e,t,r,n){if(!pt(e.egressProxySocket)||!e.egressProxyToken)throw S("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy socket and token are required");return await new Promise((s,i)=>{let o=wi.request({socketPath:e.egressProxySocket,path:r,method:t,headers:{Authorization:`Bearer ${e.egressProxyToken}`,Accept:"application/json",...n?{"Content-Type":"application/json"}:{}}},c=>{let l=[],d=0;c.on("data",f=>{d+=f.length,d>1048576?o.destroy(new Error("egress response is too large")):l.push(Buffer.from(f))}),c.once("end",()=>{try{let f=JSON.parse(Buffer.concat(l).toString("utf8")||"{}");(c.statusCode||500)>=400?i(S("RUNTIME_EGRESS_UNAVAILABLE",a(f.error)||"Egress Proxy rejected the request")):s(f)}catch(f){i(f)}})});o.once("error",i),o.setTimeout(3e3,()=>o.destroy(new Error("Egress Proxy request timed out"))),n?o.end(JSON.stringify(n)):o.end()})}function Ie(e,t){let r=Kr(ye(e),ye(t));return r===""||!r.startsWith("..")&&!pt(r)}function S(e,t){return Object.assign(new Error(t),{code:e})}var Oe=24e3,xe=8,Ae=50,Ce=6e3,Di=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),vi=10*60*1e3,Fi=60*1e3,Hi=8,$i=30*60*1e3,Bi=60*1e3,qi=1,ji=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions","runtimeMaxSessions"]),Gi=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Ki(e){if(!u(e))return{};let t={};for(let r of["name","code","serverName","serverCode","type","transport","url","command","protocolVersion"]){let n=a(e[r]);n&&(t[r]=n)}return t}function Vi(e){return(Array.isArray(e)?e:[]).map(Ki).sort((t,r)=>{let n=H(t),s=H(r);return n<s?-1:n>s?1:0})}function zi(e){return!u(e)||e.verificationPlan?.required!==!0?!1:(Array.isArray(e.verificationPlan.checks)?e.verificationPlan.checks:[]).some(r=>u(r)&&Array.isArray(r.toolNames)&&r.toolNames.some(n=>a(n)==="plugin_operation"))}function Wi(e,t,r){let n=u(e?._meta)?e._meta:{};return{...u(e)?e:{},sessionId:t,update:u(e?.update)?e.update:{},_meta:{...n,orchaAgentId:r.agentId,runtimeSessionId:r.runtimeSessionId,bridgeUpdateId:Ht()}}}function U(e){return e==null||e===""?!1:typeof e=="string"?a(e)!=="":Array.isArray(e)?e.length>0:u(e)?Object.keys(e).length>0:!0}function tn(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return Di.has(t)}function q(e,t){let r=g(e,t);return Number.isFinite(r)&&r>0?r:t}function Ue(e){let t=g(e,null);return Number.isFinite(t)&&t>0?t:null}function ht(e,t=!1){if(typeof e=="boolean")return e;let r=a(e).toLowerCase();return["true","1","yes","y","on"].includes(r)?!0:["false","0","no","n","off"].includes(r)?!1:t}function B(e){return a(e?.type||"echo")}function Ji(e){let t=B(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function Pe(e){if(u(e)){if(Object.prototype.hasOwnProperty.call(e,"releaseAfterPrompt"))return e.releaseAfterPrompt;if(Object.prototype.hasOwnProperty.call(e,"disposeAfterPrompt"))return e.disposeAfterPrompt}}function Xi(e){let t=String(e||"");if(Gi.test(t))return!0;let r=t.replace(/[^a-z0-9]/gi,"").toLowerCase();return r.endsWith("token")||r.endsWith("secret")||r.endsWith("password")||r.endsWith("apikey")||r.endsWith("privatekey")||r==="authorization"||r==="cookie"||r==="jwt"||r.includes("credential")}function ke(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=Ce)return e;let r=e.length-Ce;return`${e.slice(0,Ce)}... [truncated ${r} characters]`}if(t>=xe)return Array.isArray(e)?`[array truncated at depth ${xe}, items=${e.length}]`:u(e)?`[object truncated at depth ${xe}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let r=e.slice(0,Ae).map(n=>ke(n,t+1));return e.length>Ae&&r.push(`[truncated ${e.length-Ae} items]`),r}if(u(e)){let r={};for(let[n,s]of Object.entries(e))r[n]=Xi(n)?"[REDACTED]":ke(s,t+1);return r}return String(e)}var Yi=new Set(["type","executionId","taskId","task","traceId","requestId","agentCode","stage","phase","nodeId","nodeType","capabilityCode","operationCode","outputType","artifactType","input","inputs","rejection","previous","artifactRefs","outputSchema","executionPolicy","resultContract"]);function Zi(e){if(!u(e))return e;let t={};for(let r of Yi)U(e[r])&&(t[r]=e[r]);return t}function Qi(e){if(!u(e))return e;let t={...e};return u(t.renderedPayload)&&(t.renderedPayload=Zi(t.renderedPayload)),t}function to(e){let t=u(e)?e:{},r={};U(t.metadata)&&(r.metadata=Qi(t.metadata));for(let[n,s]of Object.entries(t))ji.has(n)||n==="metadata"||U(s)&&(r[n]=s);return r}function eo(e){let t=u(e)?e:{},r=u(t.metadata)?t.metadata:{},n=u(r.renderedPayload)?r.renderedPayload:{};return u(t.resultContract)?t.resultContract:u(n.resultContract)?n.resultContract:{}}function en(e){return a(eo(e).kind).toLowerCase()==="decision"}function Xr(e){let t=u(e)?e:{},r=u(t.metadata)?t.metadata:{};return Ue(t.runtimeMaxSessions??r.runtimeMaxSessions)}function ro(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:B(e)==="cli"}function Yr(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return ht(t,Ji(e))}function no(e,t){let r=u(e?.metadata)?{...e.metadata}:{},n=u(r._runtimeBridge)?{...r._runtimeBridge}:{},s=Pe(n);return r._runtimeBridge={...n,promptKind:"dispatch",finalTextOnly:ro(t),releaseAfterPrompt:s===void 0?Yr(t):ht(s,Yr(t)),requiresRuntimeResult:en(e)},r}function so(e){let t=to(e);if(!U(t))return"";let r=JSON.stringify(ke(t),null,2);if(r.length<=Oe)return r;let n=r.length-Oe;return`${r.slice(0,Oe)}
14
+ ... [truncated ${n} characters]`}function ve(e){if(!u(e))return"";let t=u(e.update)?e.update:e,n=(u(t.content)?t.content:{}).text??t.text;return n==null?"":String(n)}function Le(e){if(!u(e))return"";let t=u(e.update)?e.update:e;return a(t.sessionUpdate)}function rn(e){if(!Array.isArray(e))return"";let t=!1,r=[],n=[],s=[],i=()=>{r.length>0&&(n.push(r),r=[])};for(let c of e){let l=Le(c),d=ve(c);if(!l){d&&s.push(d);continue}if(t=!0,l==="agent_message_chunk"){d&&r.push(d);continue}(l==="agent_thought_chunk"||l==="user_message_chunk"||l==="tool_call"||l==="tool_call_update"||l==="plan")&&i()}if(i(),!t)return _t(s);let o=n[n.length-1]||[];return _t(o)}function De(e){return Array.isArray(e)?e.map(ve).filter(t=>t!==""):[]}function io(e){if(!u(e))return null;let t=u(e.update)?e.update:e;return a(t.sessionUpdate)!=="runtime_event"?null:u(t.event)?t.event:null}function oo(e){if(!u(e))return"";let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type);if(r==="event_msg"){if(n==="task_complete")return a(t.last_agent_message||t.message||t.output);if(n==="agent_message"){let s=a(t.phase||t.status||t.stage).toLowerCase();if(["final_answer","final","complete","completed","done"].includes(s))return a(t.message||t.text||t.content)}}return""}function ao(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let r=oo(io(e[t]));if(r)return r}return""}function _t(e){let t="";for(let r of e){let n=String(r||"");if(n)if(!t)t=n;else if(n.length>t.length&&n.startsWith(t))t=n;else{let s=$r(n)&&!/[\r\n]$/.test(t)?`
15
+ `:"";t+=`${s}${n}`}}return t.trim()}function co(e){let t=String(e||"").trim();if(!t)return"";let r=t.match(/(?:^|\n)#{1,3}\s+\S/);return!r||r.index===0?t:t.slice(r.index+(t[r.index]===`
16
+ `?1:0)).trim()}function Zr(e){let t=String(e||"").trim();if(!t)return null;try{let r=JSON.parse(t);if(u(r)&&(nn(r)||U(r._artifacts)||U(r.artifacts)||U(r._decision)||U(r._meta)))return r}catch{}return null}function gt(e){try{return fe(e)}catch{return null}}function Ne(...e){let t=null;for(let r of e)try{if(fe(r))return}catch(n){t||=n}if(t)throw t}function be(e){let t=String(e||"").trim();if(!t)return null;let r=gt(t);if(r)return r;let n=[...t.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];for(let s=n.length-1;s>=0;s-=1){let i=Zr(n[s][1]);if(i)return i}if(!t.endsWith("}"))return null;for(let s=t.lastIndexOf("{");s>=0;s=t.lastIndexOf("{",s-1)){let i=Zr(t.slice(s));if(i)return i}return null}function uo(e){let t=gt(rn(e));if(t)return t;let n=Array.isArray(e)&&e.some(s=>Le(s))?e.filter(s=>Le(s)!=="user_message_chunk").map(ve).filter(s=>s!==""):De(e);for(let s=n.length-1;s>=0;s-=1){let i=gt(n[s]);if(i)return i}return gt(_t(n))}function nn(e){if(!u(e))return!1;if(U(e.output))return!0;for(let t of["content","text","message","summary"])if(a(e[t]))return!0;return!!(tn(e.status)||a(e.error)||a(e.errorMessage))}function F(e){let t=u(e)?{...e}:{};return(!Array.isArray(t._artifacts)||t._artifacts.length===0)&&Array.isArray(t.artifacts)&&t.artifacts.length>0&&(t._artifacts=t.artifacts),delete t.artifacts,t}function lo(e){return u(e)?typeof(u(e._decision)?e._decision:u(e.decision)?e.decision:e).passed=="boolean":!1}function fo(e){return u(e)?u(e._decision)&&typeof e._decision.passed=="boolean"?!0:lo(e.output):!1}function Me(e,t,r){let n=u(e)?{...e}:{};if(!U(n.output)){for(let s of["summary","message","content","text"])if(a(n[s])){n.output=a(n[s]);break}}return!U(n.output)&&a(r)&&(n.output=a(r)),{...n,_meta:{...u(n._meta)?n._meta:{},runtimeOutputSource:t,requiredRuntimeResult:!0,finalMessagePreview:a(r).slice(0,1e3)}}}var mo=["dataUrl","dataURL","contentDataUrl","contentDataURL","contentBase64","base64","data"];function Qr(e){if(!u(e))return"";let t=u(e.content)?e.content:{},r=u(e.metadata)?e.metadata:{};return a(e.fieldKey||e.field_key||t.fieldKey||r.fieldKey)}function po(e,t){let r=u(e.content)?e.content:{},n=u(t.content)?t.content:{},s={...e,...t,content:{...r,...n},metadata:{...u(e.metadata)?e.metadata:{},...u(t.metadata)?t.metadata:{}}};for(let i of mo)U(e[i])&&(s[i]=e[i]),U(r[i])&&(s.content[i]=r[i]);return s}function ho(e,t){let r=Array.isArray(e)?e.filter(u):[],n=Array.isArray(t)?t.filter(u):[];if(!r.length)return n;if(!n.length)return r;let s=[...r],i=new Map;for(let c=0;c<r.length;c+=1){let l=Qr(r[c]),d=i.get(l)||[];d.push(c),i.set(l,d)}let o=new Map;for(let c of n){let l=Qr(c),d=o.get(l)||0;o.set(l,d+1);let f=i.get(l)?.[d];f===void 0?s.push(c):s[f]=po(s[f],c)}return s}function $(e,t,r){let n={...e,...t,_meta:{...u(e._meta)?e._meta:{},...u(t._meta)?t._meta:{},runtimeOutputSource:r}};return(Array.isArray(e._artifacts)||Array.isArray(t._artifacts))&&(n._artifacts=ho(e._artifacts,t._artifacts)),n}function go(e,t,r={}){let n=a(r.promptKind),s=r.requiresRuntimeResult===!0,i=s||n==="dispatch",o=F(e),c=typeof o.output=="string"?gt(o.output):null;if(c)return $(o,F(c),"result_block");let l=ao(t),d=l?be(l):null,f=i?uo(t):null;if(nn(o))return tn(o.status)||a(o.error)||a(o.errorMessage)?o:n==="dispatch"&&d?$(o,F(d),"final_event"):n==="dispatch"&&f?$(o,F(f),"updates"):!s||fo(o)?o:d?$(o,F(d),"final_event"):f?$(o,F(f),"updates"):(Ne(o.output,l,_t(De(t))),Me(o,"result",o.output));if(d)return $(o,F(d),"final_event");if(f)return $(o,F(f),"updates");if(l)return s?(Ne(l,_t(De(t))),Me(o,"final_event",l)):{...o,output:l,_meta:{...u(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let p=rn(t),_=be(p);if(_)return $(o,F(_),"updates");let m=co(p);if(!m)return o;let R=be(m);return R?$(o,F(R),"updates"):s?(Ne(p,m),Me(o,"updates",m)):{...o,output:m,_meta:{...u(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}var $t=class{constructor(t){this.config=t,this.targets=t.targets||{},this.agents=new Map,this.sessions=new Map,this.runtimeSessionIndex=new Map,this.pendingPermissions=new Map,this.operations=new Map,this.startedAt=at(),this.sandboxCapabilities={dispatchable:t.sandboxRequired!==!0,enforced:!1,backend:t.sandboxRequired?"unavailable":"direct",daemonStatus:t.sandboxRequired?"pending":"not_required",policySchemaVersions:[1],runtimePolicyUpdates:t.sandboxRequired===!0,workspaceSync:!1,egressProxy:!1},this.cleanupTimer=null,this.startSessionCleanup()}async start(){try{this.sandboxCapabilities=await zr(this.config)}catch(t){this.sandboxCapabilities={...this.sandboxCapabilities,dispatchable:!1,enforced:!1,backend:"unavailable",daemonStatus:"unavailable",reason:a(t?.code||t?.message||t)||"sandbox_probe_failed"},h("error","runtime-bridge","runtime node sandbox probe failed; node will not accept work",{reason:this.sandboxCapabilities.reason})}return this.sandboxCapabilities}assertDispatchable(){if(this.config.sandboxRequired&&!(this.sandboxCapabilities.dispatchable===!0&&this.sandboxCapabilities.enforced===!0))throw Object.assign(new Error("runtime node strong sandbox is unavailable"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"})}operationIdentity(t,r,n){let s=u(t.goalContract)?ge(t.goalContract):a(t.goalContractHash),i=Li("sha256").update(H({prompt:Array.isArray(t.prompt)?t.prompt:[],mcpServers:Vi(t.mcpServers)})).digest("hex");return{agentId:r,runId:a(t.runId),sessionId:n,targetCode:a(t.targetCode||t.framework),workspace:a(t.workspace),goalContractHash:s,requestHash:i}}assertOperationIdentity(t,r,n,s){let i=this.operationIdentity(r,n,s),o=Object.keys(t.identity).find(c=>t.identity[c]!==i[c]);if(o)throw Object.assign(new Error(`runtime operation correlation conflict: ${t.correlationId}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT",field:o})}createOperation(t,r,n,s){let i={correlationId:t,agentId:n,sessionId:s,identity:this.operationIdentity(r,n,s),sandboxPolicy:u(r.sandboxPolicy)?structuredClone(r.sandboxPolicy):null,status:"running",updates:[],listeners:new Set,waiters:[],response:null,error:null,createdAtMs:Date.now(),completedAtMs:null};return this.operations.set(t,i),i}async attachOperation(t,r={}){let n=()=>{if(r.onUpdate)for(let s of t.updates)r.onUpdate(s)};if(t.status==="completed")return n(),t.response;if(t.status==="failed")throw n(),t.error;r.onUpdate&&t.listeners.add(r.onUpdate);try{return n(),await new Promise((s,i)=>t.waiters.push({resolve:s,reject:i}))}finally{r.onUpdate&&t.listeners.delete(r.onUpdate)}}completeOperation(t,r){if(t.status==="running"){t.status="completed",t.response=r,t.completedAtMs=Date.now();for(let n of t.waiters.splice(0))n.resolve(r);t.listeners.clear()}}promptResponse(t,r,n,s,i){let o=u(t.metadata)?t.metadata:{},c=u(o._runtimeBridge)?o._runtimeBridge:{},l=go(i,s,c),d=jr(t.goalContract,s,t.goalContractHash);return{sessionId:n,runtimeSessionId:r.runtimeSessionId,result:l,updates:s,...d?{verification:d}:{}}}failOperation(t,r){if(t.status!=="running")return;let n=r instanceof Error?r:Object.assign(new Error(String(r||"runtime operation failed")),{code:"RUNTIME_NODE_ERROR"});t.status="failed",t.error=n,t.completedAtMs=Date.now();for(let s of t.waiters.splice(0))s.reject(n);t.listeners.clear()}cleanupOperations(t=Date.now()){let r=q(this.config.operationTtlMs,$i);for(let[n,s]of this.operations)s.status!=="running"&&t-(s.completedAtMs||s.createdAtMs)>r&&this.operations.delete(n)}targetFor(t){let r=a(t)||this.config.defaultTargetCode,n=this.targets[r];if(!r||!u(n)){let s=new Error(`runtime target is not configured: ${r||"<empty>"}`);throw s.code="RUNTIME_TARGET_NOT_FOUND",s}return{code:r,target:n}}targetIdleTtlMs(t){let n=B(t)==="openclaw"?q(this.config.openClawSessionIdleTtlMs,Bi):q(this.config.sessionIdleTtlMs,vi);return q(t?.sessionIdleTtlMs??t?.idleTtlMs,n)}targetMaxSessions(t,r=null){let s=B(t)==="openclaw"?q(this.config.openClawMaxSessions,qi):q(this.config.maxSessionsPerTarget,Hi),i=q(t?.maxSessions,s),o=Ue(r);return o?Math.max(i,o):i}targetReleaseAfterPrompt(t,r={}){let n=B(t),s=u(r?._runtimeBridge)?r._runtimeBridge:{},i=Pe(s);return i!==void 0?ht(i,!1):ht(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}promptReleaseAfterPrompt(t,r={}){if(this.config.sandboxRequired)return!0;let n=u(r?._runtimeBridge)?r._runtimeBridge:{},s=Pe(n);return s!==void 0?ht(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=q(this.config.sessionCleanupIntervalMs,Fi);t<=0||(this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions().catch(r=>{h("warn","runtime-bridge","runtime session cleanup failed",{error:String(r)})})},t),this.cleanupTimer.unref?.())}sessionCountForTarget(t){let r=0;for(let n of this.sessions.values())n.targetCode===t&&(r+=1);return r}sessionCountForAgentTarget(t,r){let n=0;for(let s of this.sessions.values())s.agentId===t&&s.targetCode===r&&(n+=1);return n}idleTargetSessions(t){return[...this.sessions.entries()].filter(([,r])=>r.targetCode===t&&!r.busy).sort((r,n)=>(r[1].lastUsedAtMs||0)-(n[1].lastUsedAtMs||0))}idleAgentTargetSessions(t,r){return[...this.sessions.entries()].filter(([,n])=>n.agentId===t&&n.targetCode===r&&!n.busy).sort((n,s)=>(n[1].lastUsedAtMs||0)-(s[1].lastUsedAtMs||0))}async closeSession(t,r="session_closed"){let n=this.sessions.get(t);if(!n)return!1;try{await n.runtime?.stop?.(r)}catch(s){h("warn","runtime-bridge","runtime session stop failed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,error:String(s)})}return this.sessions.delete(t),this.runtimeSessionIndex.delete(`${n.agentId}:${n.runtimeSessionId}`),h("info","runtime-bridge","runtime session closed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,reason:r}),!0}async closeAllSessions(t="bridge_shutdown"){for(let r of[...this.sessions.keys()])await this.closeSession(r,t)}async stop(t="bridge_stop"){this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=null,await this.closeAllSessions(t)}async cleanupExpiredSessions(t=Date.now()){for(let[r,n]of[...this.sessions.entries()])n.busy||t-(n.lastUsedAtMs||n.createdAtMs||t)>n.idleTtlMs&&await this.closeSession(r,"idle_timeout")}async reserveTargetSlot(t,r,n={}){let s=a(n.agentId),i=Ue(n.runtimeMaxSessions);if(s&&i)for(;this.sessionCountForAgentTarget(s,t)>=i;){let c=this.idleAgentTargetSessions(s,t);if(!c.length){let l=new Error(`runtime agent session limit reached: ${s}`);throw l.code="RUNTIME_AGENT_SESSION_LIMIT",l}await this.closeSession(c[0][0],"agent_session_limit")}let o=this.targetMaxSessions(r,i);for(;this.sessionCountForTarget(t)>=o;){let c=this.idleTargetSessions(t);if(!c.length){let l=new Error(`runtime target session limit reached: ${t}`);throw l.code="RUNTIME_TARGET_SESSION_LIMIT",l}await this.closeSession(c[0][0],"target_session_limit")}}async createAgent(t){let r=a(t.agentId);if(!r)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});let{code:n,target:s}=this.targetFor(t.targetCode||t.framework),i=this.agents.get(r);if(i&&i.targetCode!==n)throw Object.assign(new Error(`runtime agent target conflict: ${r}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});let o=this.config.sandboxRequired?await Ee(this.config,s,t.workspace):a(t.workspace),c={agentId:r,targetCode:n,framework:a(t.framework||n),workspace:o,metadata:u(t.metadata)?t.metadata:{},createdAt:at(),runtimeKind:B(s),runtimeMaxSessions:Xr(t)};return this.agents.set(r,c),{agent:c}}runtimeFor(t,r,n={}){let{target:s}=this.targetFor(t.targetCode),i=B(s),o={onPermissionRequest:l=>this.requestPermission(l)},c={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs,initializeTimeoutMs:this.config.initializeTimeoutMs,sandboxRequired:this.config.sandboxRequired,...this.config.sandboxRequired?{prepareLaunch:l=>Wr({config:this.config,target:s,...l,runId:n.runId,agentId:t.agentId,sessionId:r,sandboxPolicy:n.sandboxPolicy})}:{}};return i==="stdio-acp"||i==="acp"?new Q(t,s,o,c):i==="openclaw"?new Ct(t,s,r,o,c):i==="cli"?new Pt(t,s,c):new wt(t)}async prompt(t,r={}){if(this.assertDispatchable(),this.config.sandboxRequired){let c=a(t.runId);if(!c)throw Object.assign(new Error("runId is required"),{code:"BAD_REQUEST"});t={...t,runId:c,sandboxPolicy:K(t.sandboxPolicy)}}let n=a(t.agentId),s=a(t.sessionId)||Ht(),i=a(t.correlationId);if(!n)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});if(this.cleanupOperations(),i){let c=this.operations.get(i);if(c)return this.assertOperationIdentity(c,t,n,s),this.attachOperation(c,r);if(t.attachOnly===!0)throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"})}else if(t.attachOnly===!0)throw Object.assign(new Error("correlationId is required for attachOnly"),{code:"BAD_REQUEST"});let o=i?this.createOperation(i,t,n,s):null;if(o){let c=this.attachOperation(o,r);return(async()=>{try{await this._promptOwned(t,{},o,n,s)}catch(l){let d=o.status==="completed";this.failOperation(o,l),d&&h("warn","runtime-bridge","runtime cleanup failed after operation completion",{correlationId:o.correlationId,error:String(l)})}})(),await c}return await this._promptOwned(t,r,o,n,s)}async _promptOwned(t,r,n,s,i){let o=a(t.runId),c=this.config.sandboxRequired?K(n?.sandboxPolicy||t.sandboxPolicy):null,l=this.agents.get(s),d=this.targetFor(t.targetCode||t.framework||l?.targetCode);if(l&&l.targetCode!==d.code)throw Object.assign(new Error(`runtime agent target conflict: ${s}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});if(B(d.target)==="cli"&&zi(t.goalContract))throw Object.assign(new Error("CLI runtimes do not support per-run dynamic MCP required by plugin_operation"),{code:"unsupported_dynamic_mcp"});let f=l||(await this.createAgent({agentId:s,targetCode:d.code,framework:t.framework,workspace:t.workspace,runtimeMaxSessions:t.runtimeMaxSessions,metadata:t.metadata})).agent,p=Xr(t);if(p&&(f.runtimeMaxSessions=p),!this.config.sandboxRequired){let T=a(t.workspace);T&&T!==f.workspace&&(f.workspace=T)}let _=`${s}:${i}`;await this.cleanupExpiredSessions();let m=this.sessions.get(_);if(m&&m.targetCode!==d.code)throw Object.assign(new Error(`runtime session target conflict: ${i}`),{code:"RUNTIME_SESSION_TARGET_CONFLICT"});if(m&&this.config.sandboxRequired&&m.runId!==o)throw Object.assign(new Error(`runtime session cannot be shared across runs: ${i}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});if(!m){let{code:T,target:y}=d;await this.reserveTargetSlot(T,y,{agentId:s,runtimeMaxSessions:f.runtimeMaxSessions});let E=this.runtimeFor(f,i,{runId:o,sandboxPolicy:c}),A=await E.sessionNew({cwd:Z(y,f.workspace),mcpServers:Array.isArray(t.mcpServers)?t.mcpServers:[],metadata:u(t.metadata)?t.metadata:{}}),W=Date.now();m={agentId:s,sessionId:i,runtime:E,targetCode:T,runtimeKind:B(y),runId:o,sandboxPolicy:c?structuredClone(c):null,runtimeSessionId:a(u(A)?A.sessionId:"")||i,idleTtlMs:this.targetIdleTtlMs(y),releaseAfterPrompt:this.config.sandboxRequired?!0:this.targetReleaseAfterPrompt(y,t.metadata),createdAtMs:W,lastUsedAtMs:W,busy:!1,createdAt:at()},this.sessions.set(_,m),this.runtimeSessionIndex.set(`${s}:${m.runtimeSessionId}`,m)}if(m.busy){let T=new Error(`runtime session is already running: ${i}`);throw T.code="RUNTIME_SESSION_BUSY",T}m.busy=!0,m.operationCorrelationId=n?.correlationId||null,m.lastUsedAtMs=Date.now();let R=n?.updates||[],O=T=>{let y=Wi(T,i,m);if(R.push(y),n)for(let E of n.listeners)try{E?.(y)}catch(A){h("warn","runtime-bridge","runtime operation update listener failed",{correlationId:n.correlationId,error:String(A)})}else r.onUpdate?.(y)},N=T=>{if(!(!n||n.status!=="running"||!u(T))){if(T.status==="failed"){let y=T.error;if(y instanceof Error){this.failOperation(n,y);return}let E=u(y)?y:{},A=Object.assign(new Error(a(E.message||T.message)||"runtime terminal failure"),{code:a(E.code||T.code)||"RUNTIME_TERMINAL_FAILED"});this.failOperation(n,A);return}this.completeOperation(n,this.promptResponse(t,m,i,R,u(T.result)?T.result:{stopReason:"end_turn"}))}};try{let T=qr(t.goalContract),y=Array.isArray(t.prompt)?[...t.prompt]:[];T&&y.unshift({type:"text",text:T,metadata:{source:"orcha_goal_contract"}});let E=await m.runtime.sessionPrompt({sessionId:m.runtimeSessionId,prompt:y,metadata:u(t.metadata)?t.metadata:{}},O,N),A=this.promptResponse(t,m,i,R,E);return n&&this.completeOperation(n,A),A}finally{m.busy=!1,m.operationCorrelationId===n?.correlationId&&(m.operationCorrelationId=null),m.lastUsedAtMs=Date.now(),this.promptReleaseAfterPrompt(m,u(t.metadata)?t.metadata:{})&&await this.closeSession(_,"release_after_prompt")}}async updatePolicy(t){if(this.assertDispatchable(),!this.config.sandboxRequired)throw Object.assign(new Error("runtime sandbox policy updates require an enforced sandbox"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"});let r=a(t.agentId),n=a(t.runId),s=a(t.sessionId),i=a(t.correlationId);if(!r||!n||!s||!i)throw Object.assign(new Error("agentId, runId, sessionId and correlationId are required"),{code:"BAD_REQUEST"});let o=K(t.sandboxPolicy),c=this.operations.get(i);if(c&&(c.agentId!==r||c.sessionId!==s||c.identity.runId!==n))throw Object.assign(new Error(`runtime operation policy identity conflict: ${i}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let l=`${r}:${s}`,d=this.sessions.get(l);if(d&&d.runId!==n)throw Object.assign(new Error(`runtime session policy identity conflict: ${s}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});let f=d?.sandboxPolicy||c?.sandboxPolicy;if(!f)throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"});let p=Number(f.policyRevision),_=Number(o.policyRevision);if(_<p)throw Object.assign(new Error("runtime sandbox policy revision is stale"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:p});if(_===p){if(H(f)!==H(o))throw Object.assign(new Error("runtime sandbox policy revision payload conflicts"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:p});return{updated:!1,idempotent:!0,policyRevision:p,accessMode:f.accessMode}}let m=Vr(f,o);c&&(c.sandboxPolicy=structuredClone(o)),d&&(d.sandboxPolicy=structuredClone(o));let R=!1;return m&&d?.busy===!0&&(await d.runtime.sessionCancel({sessionId:d.runtimeSessionId}),R=await this.closeSession(l,"sandbox_policy_downgrade")),{updated:!0,policyRevision:_,accessMode:o.accessMode,activeCommandCancelled:R,deferredToNextLaunch:!m&&d?.busy===!0}}async cancel(t){let r=a(t.agentId),n=a(t.sessionId),s=a(t.correlationId);if(s){let c=this.operations.get(s);if(!c||c.status!=="running")return{cancelled:!1,correlationId:s,reason:"operation_not_running"};if(c.agentId!==r||c.sessionId!==n)throw Object.assign(new Error(`runtime operation cancellation identity conflict: ${s}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let l=this.sessions.get(`${r}:${n}`);return!l||l.busy!==!0||l.operationCorrelationId!==s?{cancelled:!1,correlationId:s,reason:"operation_not_running"}:(await l.runtime.sessionCancel({sessionId:l.runtimeSessionId}),await this.closeSession(`${r}:${n}`,"cancelled"),{cancelled:!0,correlationId:s})}let i=`${r}:${n}`,o=this.sessions.get(i);return o?(await o.runtime.sessionCancel({sessionId:o.runtimeSessionId}),await this.closeSession(i,"cancelled"),{cancelled:!0}):{cancelled:!1}}async dispatch(t,r={}){let n=a(t.agentId),s=a(t.taskId),i=a(t.executionId);if(!n||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let o=a(t.sessionId)||`dispatch-${i||s}`,c=a(t.instructions),l=so(t),d=en(t),{target:f}=this.targetFor(t.targetCode||t.framework),p=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",c?`instructions: ${c}`:"",l?"orchaContext:":"",l,l?"Use orchaContext as the source of truth for upstream outputs, review reports, artifacts, and workflow metadata.":"","Follow the execution protocol in instructions exactly.","When embedding a generated artifact in final Markdown, use the Orcha artifact placeholder as the link target: orcha-artifact://<fieldKey>/<index>.","Example: use ![illustration](orcha-artifact://image/0) for the first generated image artifact.","Do not use local filesystem paths, file:// URLs, or data: URLs in final Markdown; Orcha replaces artifact placeholders after ingestion.",d?`For decision results, put the raw report between ${Dr} and ${vr}.`:"",d?`Then put a JSON object containing _decision between ${Fr} and ${Hr}.`:"",d?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
17
+ `)}];return this.prompt({...t,agentId:n,sessionId:o,prompt:p,metadata:no(t,f)},r)}async requestPermission({agent:t,runtimeSessionId:r,request:n,emitUpdate:s}){let i=Ht(),c=this.runtimeSessionIndex.get(`${t.agentId}:${r}`)?.sessionId||r||Ht(),l={permissionId:i,agentId:t.agentId,sessionId:c,runtimeSessionId:r,request:u(n)?n:{},status:"pending",createdAt:at()};return s?.({sessionId:r,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=g(n?.timeoutMs,this.config.permissionRequestTimeoutMs),p=setTimeout(()=>{this.pendingPermissions.delete(i),d({permissionId:i,outcome:"denied",response:{reason:"permission request timed out"}})},f);this.pendingPermissions.set(i,{timer:p,resolve:d,permission:l})})}async respondPermission(t){let r=a(t.permissionId),n=this.pendingPermissions.get(r),s=a(t.outcome||"approved")||"approved";return n?(clearTimeout(n.timer),this.pendingPermissions.delete(r),n.resolve({permissionId:r,outcome:s,response:u(t.response)?t.response:{},userId:a(t.userId),metadata:u(t.metadata)?t.metadata:{}}),{accepted:!0,permissionId:r,outcome:s}):{accepted:!1,permissionId:r,outcome:s}}health(){return{status:this.config.sandboxRequired&&!this.sandboxCapabilities.dispatchable?"unavailable":"ok",bridgeVersion:Y,startedAt:this.startedAt,agents:[...this.agents.values()].map(t=>({agentId:t.agentId,targetCode:t.targetCode,framework:t.framework,runtimeKind:t.runtimeKind})),sessions:this.sessions.size,pendingPermissions:this.pendingPermissions.size,targets:Object.keys(this.targets),sandboxCapabilities:this.sandboxCapabilities}}};import _o from"node:http";import To from"node:https";import{randomBytes as sn}from"node:crypto";var rt=1,V=3,yo=1e4,Bt=class{constructor(t,r={}){this.url=t,this.readyState=0,this.socket=null,this.request=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,this.connectTimeoutMs=Ro(r.connectTimeoutMs,yo),this.connectTimer=null,this.connect()}addEventListener(t,r){let n=this.listeners.get(t)||new Set;n.add(r),this.listeners.set(t,n)}emit(t,r={}){let n=this.listeners.get(t);if(n)for(let s of n)s(r)}connect(){let t=new URL(this.url),r=t.protocol==="wss:"?To:_o,n=sn(16).toString("base64"),s=r.request({protocol:t.protocol==="wss:"?"https:":"http:",hostname:t.hostname,port:t.port||(t.protocol==="wss:"?443:80),path:`${t.pathname}${t.search}`,method:"GET",headers:{Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Key":n,"Sec-WebSocket-Version":"13"}});this.request=s,this.startConnectTimer(s),s.on("upgrade",(i,o,c)=>{if(this.clearConnectTimer(),this.readyState===V){o.destroy();return}this.socket=o,this.readyState=rt,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==V&&this.emit("error",{error:l,message:l.message,type:"error"}),this.onClose()}),c?.length&&this.onData(c),this.emit("open")}),s.on("response",i=>{this.clearConnectTimer(),this.emit("error",{message:`websocket upgrade failed: HTTP ${i.statusCode}`,type:"error"}),i.resume(),this.onClose()}),s.on("error",i=>{this.clearConnectTimer(),this.readyState!==V&&this.emit("error",{error:i,message:i.message,type:"error"}),this.onClose()}),s.end()}startConnectTimer(t){this.connectTimeoutMs<=0||(this.connectTimer=setTimeout(()=>{if(this.readyState===rt||this.readyState===V)return;let r=`websocket connect timeout after ${this.connectTimeoutMs}ms`;this.emit("error",{message:r,type:"timeout"}),this.onClose(),t.destroy(new Error(r))},this.connectTimeoutMs),this.connectTimer.unref?.())}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}send(t){!this.socket||this.readyState!==rt||this.socket.write(Fe(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==V){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===rt&&this.socket.write(Fe(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==V&&(this.clearConnectTimer(),this.readyState=V,this.request=null,this.emit("close"))}onData(t){for(this.buffer=Buffer.concat([this.buffer,t]);this.buffer.length>=2;){let r=this.buffer[0],n=this.buffer[1],s=r&15,i=(n&128)!==0,o=n&127,c=2;if(o===126){if(this.buffer.length<c+2)return;o=this.buffer.readUInt16BE(c),c+=2}else if(o===127){if(this.buffer.length<c+8)return;let f=this.buffer.readUInt32BE(c),p=this.buffer.readUInt32BE(c+4);o=f*2**32+p,c+=8}let l=c;if(i&&(c+=4),this.buffer.length<c+o)return;let d=this.buffer.subarray(c,c+o);if(i){let f=this.buffer.subarray(l,l+4);d=Buffer.from(d.map((p,_)=>p^f[_%4]))}this.buffer=this.buffer.subarray(c+o),s===1?this.emit("message",{data:d.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write(Fe(10,d))}}};function Ro(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function Fe(e,t){let r=t.length,n=2;r>=126&&r<=65535?n+=2:r>65535&&(n+=8);let s=sn(4),i=Buffer.alloc(n+4+r);i[0]=128|e;let o=2;r<126?i[1]=128|r:r<=65535?(i[1]=254,i.writeUInt16BE(r,o),o+=2):(i[1]=255,i.writeUInt32BE(Math.floor(r/2**32),o),i.writeUInt32BE(r>>>0,o+4),o+=8),s.copy(i,o),o+=4;for(let c=0;c<r;c+=1)i[o+c]=t[c]^s[c%4];return i}function So(e){let t=new URL(e);if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol!=="ws:"&&t.protocol!=="wss:")throw new Error(`unsupported ORCHA_RUNTIME_ORCHA_URL protocol: ${t.protocol}`);return t.pathname=`${t.pathname.replace(/\/+$/,"")}/api/agent-runtime-bridge/ws`,t.search="",t.toString()}function He(e,t=!0){return Object.entries(e||{}).map(([r,n])=>({targetCode:r,targetName:a(n?.name||n?.targetName||r),targetType:a(n?.type||"echo"),status:t?"available":"unavailable"}))}var qt=class{constructor(t,r){this.config=t,this.bridge=r,this.ws=null,this.stopped=!1,this.connected=!1,this.reconnectTimer=null,this.heartbeatTimer=null}sandboxCapabilities(){return this.bridge.sandboxCapabilities||{dispatchable:this.config.sandboxRequired!==!0,enforced:!1,backend:"development_direct",daemonStatus:"development_only",policySchemaVersions:[1],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:!1}}start(){this.connect()}stop(){this.stopped=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.ws?.close()}connect(){if(this.stopped)return;let t=So(this.config.orchaUrl),r=new Bt(t,{connectTimeoutMs:this.config.connectTimeoutMs});this.ws=r,r.addEventListener("open",()=>{if(this.ws!==r||this.stopped){r.close();return}this.authenticate(r)}),r.addEventListener("message",n=>this.handleMessage(n.data,r)),r.addEventListener("close",()=>this.scheduleReconnect("close",r)),r.addEventListener("error",n=>{h("warn","orcha-client","runtime node websocket error",{error:String(n?.message||n?.type||n)})})}authenticate(t=this.ws){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:Y,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,sandboxCapabilities:this.sandboxCapabilities(),targets:He(this.config.targets,this.sandboxCapabilities().dispatchable===!0)},t)}scheduleReconnect(t,r=this.ws){r&&this.ws!==r||(this.connected=!1,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,r&&this.ws===r&&(this.ws=null),!this.stopped&&(this.reconnectTimer||(h("info","orcha-client","runtime node disconnected; reconnect scheduled",{reason:t,reconnectMs:this.config.reconnectMs}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},this.config.reconnectMs))))}async handleMessage(t,r=this.ws){if(r&&this.ws!==r)return;let n;try{n=JSON.parse(String(t))}catch(s){h("warn","orcha-client","invalid Orcha websocket frame",{error:String(s)});return}if(u(n)){if(n.type==="runtime_node.authenticated"){if(r&&this.ws!==r)return;this.connected=!0,this.startHeartbeat(r),h("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:n.connectionId});return}if(n.type==="orcha.runtime.request"){await this.handleRequest(n);return}n.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString(),sandboxCapabilities:this.sandboxCapabilities(),targets:He(this.config.targets,this.sandboxCapabilities().dispatchable===!0)})}}startHeartbeat(t){this.heartbeatTimer&&clearInterval(this.heartbeatTimer);let r=Math.max(1e3,Number(this.config.heartbeatIntervalMs||15e3)),n=()=>this.send({type:"runtime_node.heartbeat",ts:new Date().toISOString(),sandboxCapabilities:this.sandboxCapabilities(),targets:He(this.config.targets,this.sandboxCapabilities().dispatchable===!0)},t);n(),this.heartbeatTimer=setInterval(n,r),this.heartbeatTimer.unref?.()}async handleRequest(t){let r=a(t.id),n=a(t.method),s=u(t.params)?t.params:{};try{let i=await this.invoke(n,s,r);this.send({type:"orcha.runtime.response",id:r,ok:!0,result:i})}catch(i){this.send({type:"orcha.runtime.response",id:r,ok:!1,error:{code:i.code||"RUNTIME_NODE_ERROR",message:i.message||String(i),...i.detail===void 0?{}:{detail:i.detail}}})}}async invoke(t,r,n){if(t==="health")return this.bridge.health();if(t==="agents/create")return this.bridge.createAgent(r);if(t==="agents/dispatch")return this.bridge.dispatch(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/prompt")return this.bridge.prompt(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/policy")return this.bridge.updatePolicy(r);if(t==="sessions/cancel")return this.bridge.cancel(r);if(t==="permissions/respond")return this.bridge.respondPermission(r);throw Object.assign(new Error(`unsupported Orcha runtime method: ${t}`),{code:"METHOD_NOT_FOUND"})}sendUpdate(t,r){this.send({type:"orcha.runtime.event",requestId:t,eventType:"runtime.update",payload:r})}send(t,r=this.ws){return!r||r!==this.ws||r.readyState!==rt?!1:(r.send(JSON.stringify(t)),!0)}};import{existsSync as on,readFileSync as Eo}from"node:fs";import{dirname as wo,resolve as jt}from"node:path";import{fileURLToPath as Io}from"node:url";var Oo=/^[A-Za-z_][A-Za-z0-9_]*$/;function an(e=process.env,t=process.cwd()){let r=a(e.ORCHA_RUNTIME_ENV_FILE),n=r?jt(t,r):jt(t,".env");if(!on(n))return r&&h("warn","config","runtime env file not found",{path:n}),{loaded:!1,path:n,keys:[]};let s=[],i=Eo(n,"utf8");for(let o of i.split(/\r?\n/)){let c=Co(o);if(!c)continue;let[l,d]=c;Object.prototype.hasOwnProperty.call(e,l)||(e[l]=d,s.push(l))}return h("info","config","runtime env file loaded",{path:n,keyCount:s.length}),{loaded:!0,path:n,keys:s}}function cn(e=process.env){let t=a(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),r=a(e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1"),n=!1,s=wo(Io(import.meta.url)),i=jt(s,"sandbox","broker.js"),o=jt(s,"orcha-runtime-sandbox-broker.js"),c=on(i)?i:o,l=a(e.ORCHA_RUNTIME_SANDBOX_BROKER_COMMAND);return{mode:t,host:r,port:g(e.ORCHA_RUNTIME_BRIDGE_PORT,5588),token:e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",orchaUrl:a(e.ORCHA_RUNTIME_ORCHA_URL),nodeToken:e.ORCHA_RUNTIME_NODE_TOKEN||e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",nodeId:a(e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"local-runtime-node"),nodeName:a(e.ORCHA_RUNTIME_NODE_NAME||e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"Local Runtime Node"),reconnectMs:g(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),connectTimeoutMs:g(e.ORCHA_RUNTIME_CONNECT_TIMEOUT_MS||e.ORCHA_RUNTIME_WS_CONNECT_TIMEOUT_MS,1e4),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:g(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),initializeTimeoutMs:g(e.ORCHA_RUNTIME_INITIALIZE_TIMEOUT_MS,3e4),sessionPromptTimeoutMs:g(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,36e5),permissionRequestTimeoutMs:g(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:g(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:g(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:g(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:g(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:g(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),heartbeatIntervalMs:g(e.ORCHA_RUNTIME_HEARTBEAT_INTERVAL_MS,15e3),sandboxRequired:n,sandboxBrokerCommand:l||process.execPath,sandboxBrokerArguments:$e(e.ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS,"ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS",l?[]:[c]),sandboxProbeTimeoutMs:g(e.ORCHA_RUNTIME_SANDBOX_PROBE_TIMEOUT_MS,1e4),sandboxTempRoot:a(e.ORCHA_RUNTIME_SANDBOX_TEMP_ROOT),trustedWorkspaceRoots:$e(e.ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS,"ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS"),trustedToolchainRoots:$e(e.ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS,"ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS"),egressProxyRequired:Ao(e.ORCHA_RUNTIME_EGRESS_PROXY_REQUIRED,t==="node"),egressProxySocket:a(e.ORCHA_RUNTIME_EGRESS_PROXY_SOCKET),egressProxyToken:a(e.ORCHA_RUNTIME_EGRESS_PROXY_TOKEN),egressGrantMaxTtlMs:g(e.ORCHA_RUNTIME_EGRESS_GRANT_MAX_TTL_MS,9e5),targets:xo(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function xo(e){if(!a(e))return{};try{let t=JSON.parse(e);if(u(t))return t}catch(t){h("warn","config","invalid ORCHA_RUNTIME_TARGETS_JSON",{error:String(t)})}return{}}function Ao(e,t){let r=a(e).toLowerCase();if(!r)return t;if(["true","1","yes","on"].includes(r))return!0;if(["false","0","no","off"].includes(r))return!1;throw new Error(`invalid boolean configuration value: ${r}`)}function $e(e,t,r=[]){let n=a(e);if(!n)return[...r];let s;try{s=JSON.parse(n)}catch{throw new Error(`${t} must be a JSON string array`)}if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw new Error(`${t} must be a JSON string array`);return s.map(i=>i.trim()).filter(Boolean)}function Co(e){let t=e.trim();if(!t||t.startsWith("#"))return null;let r=t.startsWith("export ")?t.slice(7).trimStart():t,n=r.indexOf("=");if(n<=0)return null;let s=r.slice(0,n).trim();if(!Oo.test(s))return null;let i=No(r.slice(n+1).trim());return[s,i]}function No(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let r=e.slice(1,-1);return t==='"'?bo(r):r}return Mo(e).trim()}function bo(e){return e.replaceAll("\\n",`
18
+ `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function Mo(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n],i=e[n-1];if(s==="'"&&!r)t=!t;else if(s==='"'&&!t&&i!=="\\")r=!r;else if(s==="#"&&!t&&!r&&/\s/.test(i||""))return e.slice(0,n)}return e}import{createServer as Uo}from"node:http";function Gt(e,t,r){let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(n)}),e.end(n)}function z(e={}){return{ok:!0,...e}}function Be(e,t,r){return{ok:!1,error:{code:e,message:t,...r===void 0?{}:{detail:r}}}}async function un(e,t){let r=[],n=0;for await(let i of e){if(n+=i.length,n>t)throw Object.assign(new Error("request body too large"),{status:413,code:"REQUEST_TOO_LARGE"});r.push(i)}if(r.length===0)return{};let s=Buffer.concat(r).toString("utf8");if(!s.trim())return{};try{let i=JSON.parse(s);if(!u(i))throw Object.assign(new Error("JSON body must be an object"),{status:400,code:"BAD_JSON"});return i}catch(i){throw i.status?i:Object.assign(new Error(`invalid JSON body: ${i.message}`),{status:400,code:"BAD_JSON"})}}function ln(e,t){if(!t)return;if((e.headers.authorization||"")!==`Bearer ${t}`)throw Object.assign(new Error("runtime bridge token is invalid"),{status:401,code:"UNAUTHORIZED"})}function dn(e,t){let r={"GET /health":async()=>z(t.health()),"POST /agents/create":async n=>z(await t.createAgent(n)),"POST /agents/dispatch":async n=>z(await t.dispatch(n)),"POST /sessions/prompt":async n=>z(await t.prompt(n)),"POST /sessions/cancel":async n=>z(await t.cancel(n)),"POST /permissions/respond":async n=>z(await t.respondPermission(n))};return Uo(async(n,s)=>{let i=new URL(n.url||"/",`http://${n.headers.host||`${e.host}:${e.port}`}`),o=`${n.method||"GET"} ${i.pathname}`,c=r[o];if(!c){Gt(s,404,Be("NOT_FOUND",`No route for ${o}`));return}try{ln(n,e.token);let l=n.method==="GET"?{}:await un(n,e.requestLimitBytes);Gt(s,200,await c(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";Gt(s,d,Be(f,l.message||String(l),l.detail))}})}var $o=Ho(import.meta.url),Bo=".orcha-runtime-bridge.pid",qo=".orcha-runtime-bridge.log",jo=3,Go=36e5,{command:Ko,options:Sn}=Jo(process.argv.slice(2));Xo(Sn);an();var Vo=cn();await zo(Ko,Vo,Sn);async function zo(e,t,r){switch(e){case"run":case"foreground":await mn(t);return;case"start":if(r.foreground){await mn(t);return}hn();return;case"reload":case"restart":await gn({quiet:!0}),hn();return;case"stop":await gn();return;case"status":Wo();return;case"help":case"--help":case"-h":ta();return;default:throw new Error(`Unknown command: ${e}`)}}async function mn(e){Yo();let t=new $t(e);if(await t.start(),e.mode==="server"){let n=dn(e,t);pn({bridge:t,server:n}),n.listen(e.port,e.host,()=>{h("info","runtime-bridge","Orcha runtime bridge HTTP server started",{host:e.host,port:e.port,targets:Object.keys(t.targets)})});return}if(!e.orchaUrl)throw new Error("ORCHA_RUNTIME_ORCHA_URL is required in runtime node mode");let r=new qt(e,t);pn({bridge:t,client:r}),r.start(),h("info","runtime-bridge","Orcha runtime node started",{nodeId:e.nodeId,nodeName:e.nodeName,orchaUrl:e.orchaUrl,targets:Object.keys(t.targets)})}function pn({bridge:e,client:t,server:r}){let n=!1,s=i=>{if(n)return;n=!0;let o=Number(e?.sessions?.size||0)>0;h("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(c){h("warn","runtime-bridge","runtime client stop failed",{error:String(c)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(c=>{h("warn","runtime-bridge","runtime bridge stop failed",{error:String(c)})}).finally(()=>{try{r?.close?.()}catch(c){h("warn","runtime-bridge","runtime server close failed",{error:String(c)})}}),setTimeout(()=>process.exit(0),o?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function hn(){let e=Ve(),t=En(),r=ze(e);if(r&&nt(r)){console.log(JSON.stringify({status:"already_running",pid:r,pidFile:e,logFile:t}));return}r&&Ge(e),Tn(e),Tn(t),je(t);let n=Do(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=Po(process.execPath,[$o,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",n,n]});i.unref(),ko(n),Rn(e,`${i.pid}
19
+ `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function gn({quiet:e=!1}={}){let t=Ve(),r=ze(t);if(!r){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!nt(r)){Ge(t),e||console.log(JSON.stringify({status:"not_running",pid:r,pidFile:t}));return}process.kill(r,"SIGTERM"),!await _n(r,1e4)&&nt(r)&&(process.kill(r,"SIGKILL"),await _n(r,3e3)),Ge(t),e||console.log(JSON.stringify({status:"stopped",pid:r,pidFile:t}))}function Wo(){let e=Ve(),t=En(),r=ze(e),n=!!(r&&nt(r));console.log(JSON.stringify({status:n?"running":"not_running",running:n,pid:n?r:null,pidFile:e,logFile:t}))}function Jo(e){let t=[],r={};for(let s=0;s<e.length;s+=1){let i=e[s];i==="--daemon"?r.daemon=!0:i==="--foreground"?r.foreground=!0:i==="--env-file"?r.envFile=e[++s]:i==="--pid-file"?r.pidFile=e[++s]:i==="--log-file"?r.logFile=e[++s]:t.push(i)}return{command:t[0]||"run",options:r}}function Xo(e){e.envFile&&(process.env.ORCHA_RUNTIME_ENV_FILE=e.envFile),e.pidFile&&(process.env.ORCHA_RUNTIME_PID_FILE=e.pidFile),e.logFile&&(process.env.ORCHA_RUNTIME_LOG_FILE=e.logFile)}function Ve(){return Ke(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Bo)}function En(){return Ke(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||qo)}function Yo(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=wn();if(t<=0)return;let r=Ke(process.cwd(),e);je(r,t);let n=Qo();n<=0||setInterval(()=>je(r,t),n).unref()}function je(e,t=wn()){if(t<=0||!yn(e))return;let r=0,n="";try{if(r=fn(e).size,r<=0)return;n=qe(e,"utf8")}catch(d){h("warn","runtime-bridge","runtime log cleanup skipped",{logFile:e,error:String(d)});return}let s=Date.now()-t*24*60*60*1e3,i=n.split(/\r?\n/),o=[],c=0;for(let d of i)d&&(Zo(d,s)?o.push(d):c+=1);if(c===0)return;let l="";try{fn(e).size>r&&(l=qe(e,"utf8").slice(n.length));let f=[...o,...l.split(/\r?\n/).filter(Boolean)].join(`
20
+ `);Rn(e,f?`${f}
21
+ `:""),h("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:c})}catch(d){h("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(d)})}}function Zo(e,t){try{let r=JSON.parse(e);if(!r||typeof r!="object")return!0;let n=typeof r.ts=="string"?Date.parse(r.ts):Number.NaN;return!Number.isFinite(n)||n>=t}catch{return!0}}function wn(){return In(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,jo)}function Qo(){return In(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Go)}function In(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function ze(e){if(!yn(e))return null;let t=Number.parseInt(qe(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function nt(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function _n(e,t){let r=Date.now();for(;Date.now()-r<t;){if(!nt(e))return!0;await new Promise(n=>setTimeout(n,100))}return!nt(e)}function Tn(e){Lo(Fo(e),{recursive:!0})}function Ge(e){try{vo(e,{force:!0})}catch{}}function ta(){console.log(`Usage: orcha-runtime-bridge [command] [options]
22
22
 
23
23
  Commands:
24
24
  run, foreground Run in the foreground. This is the default.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orcha-ai/runtime-bridge",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local Orcha runtime bridge for ACP-compatible agent runtimes.",