@orcha-ai/runtime-bridge 0.1.34 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -4
- package/bin/orcha-runtime-bridge.js +17 -17
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -61,6 +61,21 @@ npm tarball under `dist/`. The release package includes the minified `bin/`
|
|
|
61
61
|
runtime, `README.md`, and `.env.example`; it does not publish `src/`, build
|
|
62
62
|
scripts, test scripts, or the local `.env` file.
|
|
63
63
|
|
|
64
|
+
### 0.1.36 Release
|
|
65
|
+
|
|
66
|
+
Packages the goal-verification changes committed on August 25–26, 2026.
|
|
67
|
+
Each verification check requires a positive integer `requiredMatches` and
|
|
68
|
+
counts distinct successful tool call IDs. Results report `requiredMatches`,
|
|
69
|
+
`observedMatches`, and `toolCallIds` instead of the previous single `toolCallId`.
|
|
70
|
+
Callers and result consumers must use these fields when upgrading from 0.1.35.
|
|
71
|
+
|
|
72
|
+
After `npm run check`, `npm test`, and `npm run pack:local` succeed, publish the
|
|
73
|
+
prepared tarball from this directory:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npm publish ./dist/orcha-ai-runtime-bridge-0.1.36.tgz --access public --registry=https://registry.npmjs.org
|
|
77
|
+
```
|
|
78
|
+
|
|
64
79
|
## Configure
|
|
65
80
|
|
|
66
81
|
```bash
|
|
@@ -235,10 +250,11 @@ stricter defaults for this target type:
|
|
|
235
250
|
process after each prompt.
|
|
236
251
|
- `sessionIdleTtlMs`: defaults to `60000` for OpenClaw.
|
|
237
252
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
253
|
+
Session capacity belongs to the Runtime Target, not to an Agent. The bridge
|
|
254
|
+
reports each target's configured capacity, busy sessions, reclaimable idle
|
|
255
|
+
sessions, in-flight reservations, and currently available sessions on every
|
|
256
|
+
heartbeat. Orcha selects a compatible node from that live capacity; the bridge
|
|
257
|
+
still performs the final atomic reservation before starting a runtime.
|
|
242
258
|
|
|
243
259
|
Global lifecycle knobs:
|
|
244
260
|
|
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as
|
|
3
|
-
`):""}var
|
|
2
|
+
import{spawn as Ko}from"node:child_process";import{closeSync as Go,existsSync as On,mkdirSync as Vo,openSync as zo,readFileSync as We,rmSync as Wo,statSync as _n,writeFileSync as In}from"node:fs";import{dirname as Jo,resolve as Ye}from"node:path";import{fileURLToPath as Xo}from"node:url";import{createHash as Bi,randomUUID as qt}from"node:crypto";var Q="0.1.36";function dt(){return new Date().toISOString()}function M(e,t=2){return String(e).padStart(t,"0")}function nr(e){let t=e>=0?"+":"-",r=Math.abs(e);return`${t}${M(Math.floor(r/60))}:${M(r%60)}`}function Un(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)}`,nr(t)].join("")}function Pn(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 kn(e,t){let r=Pn(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)}`,nr(s)].join("")}function Ln(e=new Date){let t=a(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return kn(e,t)}catch{return Un(e)}}function u(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function a(e){return String(e??"").trim()}function _(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 tt(e,t,r=process.cwd()){let n=u(e)?e:{};return a(n.cwd)||a(n.workspace)||a(t)||a(r)||process.cwd()}var Et="[redacted]",Dn=/(authorization|api[_-]?key|credential|password|secret|token)/i;function wt(e){return Dn.test(a(e))}function sr(e,t=[]){let r=String(e??"");for(let n of t){let s=String(n??"");s.length>=4&&(r=r.split(s).join(Et))}return r.replace(/((?:authorization|api[_-]?key|credential|password|secret|token)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,`$1${Et}`).replace(/([?&](?:api[_-]?key|credential|password|secret|token)=)[^&\s]+/gi,`$1${Et}`)}function z(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]=z(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=>z(i,t));return t.delete(e),s}let r={},n=wt(e.name||e.key);for(let[s,i]of Object.entries(e))r[s]=wt(s)||n&&s.toLowerCase()==="value"?Et:z(i,t);return t.delete(e),r}function ir(e,t=4e3){let r=JSON.stringify(z(e))??String(e);return!Number.isFinite(t)||r.length<=t?r:`${r.slice(0,t)}...`}function h(e,t,r,n={}){let s={ts:Ln(),level:e,module:t,msg:r,...u(n)?z(n):{}};console.error(JSON.stringify(s))}function Ot(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 It=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=Ot(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 vn}from"node:child_process";var ft="2.0",Zt=3e4,Hn=4e3;function xt(e,t){let r=Object.entries(u(t)?t:{}).filter(([n])=>wt(n)).map(([,n])=>n);return sr(e,r)}function Fn(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 $n(e){if(!u(e))return new Error(String(e||"runtime error"));let t=a(e.message)||"runtime error",r="data"in e?ir(e.data,4e3):"",n=new Error(r?`${t}; data=${r}`:t);return n.rpcCode=e.code,n.data=e.data,n}function Bn(e){return u(e)&&"id"in e&&!("method"in e)}function qn(e){return u(e)&&typeof e.method=="string"&&"id"in e}function jn(e){return u(e)&&typeof e.method=="string"&&!("id"in e)}var At=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=Zt}={}){if(!(this.child&&!this.exited)&&(this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stderrTail="",this.spawnError=null,this.child=vn(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(-Hn);let i=xt(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,_(n,Zt));try{await this.call("initialize",{protocolVersion:1,clientCapabilities:{},...r},s)}catch(i){let o=this.startupFailureDetail(),c=xt(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:xt(this.spawnError.message,this.env)}:{},...this.stderrTail.trim()?{stderr:xt(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(
|
|
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(Bn(t)){this.resolveResponse(t);return}if(qn(t)){this.handleRequest(t);return}jn(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($n(t.error))):n.resolve(t.result))}async handleRequest(t){let r=this.requestHandlers.get(t.method);if(!r){this.writeFrame({jsonrpc:ft,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:ft,id:t.id,result:n??{}})}catch(n){this.writeFrame({jsonrpc:ft,id:t.id,error:Fn(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=Zt){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:ft,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:ft,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 lr}from"node:crypto";import{existsSync as Vn,readFileSync as zn,realpathSync as ar,statSync as Wn}from"node:fs";import{basename as dr,extname as fr,isAbsolute as mt,join as Jn,relative as mr,resolve as cr}from"node:path";var Xn=25*1024*1024;function pr(e,t=""){let r=a(t);if(r)return r;let n=fr(a(e)).toLowerCase();return n===".jpg"||n===".jpeg"?"image/jpeg":n===".webp"?"image/webp":n===".gif"?"image/gif":"image/png"}function hr(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 Ct(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function Yn(e,t){let r=mr(t,e);return r===""||!!r&&!r.startsWith("..")&&!mt(r)}function Zn(e,t){let r=a(e);if(!r||!Vn(r))return"";try{let n=ar(r);for(let s of t)try{let i=ar(s);if(Yn(n,i))return n}catch{}}catch{return""}return""}function Qn(e,t){let r=a(e);if(!r||!mt(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||!mt(s)||!mt(i))continue;let o=mr(cr(s),cr(r));if(o===""||!o.startsWith("..")&&!mt(o))return o?Jn(i,o):i}return r}function Qt(e,t,r={}){let n=a(e);return!n||n.startsWith("data:")||/^https?:\/\//i.test(n)?n:ts(n,t,r)}function ts(e,t,r={}){let n=[...Ct(r.trustedFileRoots),...Ct(r.trustedFileRoot),...Ct(r.artifactRoots),...Ct(r.artifactRoot)],s=Zn(Qn(e,r.pathMappings),n);if(!s)return"";try{let i=Wn(s);return!i.isFile()||i.size<=0||i.size>Xn?"":`data:${t};base64,${zn(s).toString("base64")}`}catch{return""}}function x(...e){for(let t of e){let r=a(t);if(r)return r}return""}function es(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=fr(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function ee(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=pr(c,n.mimeType||n.mime_type),f=hr(n.result,d)||Qt(c,d,t);if(!f)return null;let p=f.startsWith("data:")?f:"",_=c?dr(c):`${o||lr()}.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 rs(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 ns(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=es(n,s,l,o),f=d?pr(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=hr(n.result??s.result,f)||T||Qt(o,f,t)||Qt(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?dr(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 Nt(e,t){if(!t||!e)return;let r=u(t.metadata)?t.metadata:{},n=x(r.savedPath,r.callId,t.previewUrl,t.fileUrl)||lr(),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 te(e,t,r={}){for(let n of rs(e))Nt(t,ns(n,r))}function re(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 ur(e,t,r){if(!u(e))return e;let n=u(e.event)?e.event:null;return n?(Nt(t,ee(n,r)),{...e,event:re(n)}):e}function gr(e,t,r={}){if(!u(e))return e;te(e,t,r);let n=ur(e,t,r),s=u(n.update)?ur(n.update,t,r):null;return s&&s!==n.update&&(n={...n,update:s}),n}function _r(e,t,r={}){let n=u(e)?{...e}:{};te(n,t,r),te(u(n.output)?n.output:{},t,r);let s=[...t?.values?.()||[]];return s.length&&(n._artifacts=s),delete n.artifacts,n}function Tr(e,t){let r=g(e,t);return r>0?r:t}var et=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:tt(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 At({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:Tr(this.target.initializeTimeoutMs,Tr(this.options.initializeTimeoutMs,3e4)),initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:Q},...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(gr(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 _r(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 ss(e){let t=u(e.metadata)?e.metadata:{};return a(t.agentCode)}function is(e,t){let r=ss(e);return r?`agent:${r}:${t}`:`orcha-${t}`}var bt=class extends et{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",is(t,o)];super(t,{...r,command:c,args:d},s,i)}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as Ir}from"node:child_process";import{randomUUID as rt}from"node:crypto";import{existsSync as Or,mkdirSync as os,readdirSync as xr,readFileSync as Ar,realpathSync as ht,rmSync as as,rmdirSync as cs,statSync as us,unlinkSync as ls}from"node:fs";import{homedir as ds,tmpdir as Cr}from"node:os";import{basename as ae,dirname as fs,join as F,resolve as Rr}from"node:path";var ms=36e5,Nr=5e3,ps=2*60*1e3,hs=2*60*1e3,gs=12,_s=1e3,Ts=1500,Rs=1e3,Mt=24*60*60*1e3,pt=new Set(["final_answer","final","complete","completed","done"]),ys=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"]),Ss=new Set(["context_compacted","context_compaction","context_compressed"]);function Pt(e,t){if(e?.pid){if(process.platform==="win32"){let r=["/PID",String(e.pid),"/T"];t==="SIGKILL"&&r.push("/F");try{Ir("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 ne(e){Pt(e,"SIGTERM");let t=setTimeout(()=>Pt(e,"SIGKILL"),Nr);return t.unref?.(),t}function D(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>D(t)).join("");if(!u(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let r=D(e[t]);if(r)return r}return""}function br(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 D(t.content)||D(t.message);if(a(e.type)==="result")return D(e.result);let r=D(e.delta)||D(e.text)||D(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"?D(n.content)||D(n.text)||D(n.message):""}function Mr(e,t={}){return ee(e,{source:"codex_cli_image_generation",...t})}function Ur(e,t){Nt(e.artifacts,t)}function Pr(e){return z(re(e))}function ce(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 pt.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 Es(e){let t=a(e.terminalProtocol||e.eventProtocol).toLowerCase();if(t)return t;let r=ae(a(e.command)).replace(/\.exe$/i,"").toLowerCase();return r==="codex"||r==="claude"?r:""}function yr(e,t,r){let n=u(t.error)?t.error:{},s=a(n.message)||D(t.error)||a(t.result)||a(t.message)||r;return Object.assign(new Error(s),{code:e})}function ws(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:yr("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:yr("RUNTIME_CLAUDE_RESULT_FAILED",e,"Claude result failed")}:{status:"completed",result:{stopReason:"end_turn",...a(e.result)?{output:a(e.result)}:{}}}}return null}function Sr(e){return u(e)?a(e.phase||e.status||e.stage).toLowerCase():""}function Is(e){if(!u(e)||ce(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type),s=Sr(t);if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&a(t.role)==="assistant")return!!(s&&!pt.has(s));let i=u(e.item)?e.item:{},o=Sr(i);return a(i.role)==="assistant"||a(i.type)==="message"?!!(o&&!pt.has(o)):!1}function Os(e,t,r){return r.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:r.captureLastMessage===!0?!0:ae(e)==="codex"}function xs(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:ae(e)==="codex"}function kr(e){return Math.max(20,g(e.codexTranscriptPollMs||e.transcriptPollMs,_s))}function As(e){return Math.max(0,g(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,Ts))}function kt(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 ue(e){let t=u(e?.metadata)?e.metadata:{};return u(t._runtimeBridge)?t._runtimeBridge:{}}function se(e){return a(ue(e).promptKind).toLowerCase()}function Cs(e,t){for(let r of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let n=kt(r);if(n!=null)return n}return se(t)==="chat"}function Ns(e,t){let r=ue(e);for(let s of[r.emitThoughtChunks,r.streamThoughts]){let i=kt(s);if(i!=null)return i}let n=se(e);if(n&&n!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=kt(s);if(i!=null)return i}return se(e)==="chat"}function bs(e){let t=ue(e);for(let r of[t.finalTextOnly,t.finalOutputOnly]){let n=kt(r);if(n!=null)return n}return null}function Ms(e,t){let r=bs(e);return r??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function Us(e,t){return!e.finalTextOnly||t}function Lr(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 Dr(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 Ps(e,t,r,n=new Set){return{target:e,promptText:t,startedAtMs:r,baselinePaths:n,matchedPath:"",disabled:!1,processedLines:new Map}}function ks(e,t){let r=u(e.env)?e.env:{},n=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||r.ORCHA_RUNTIME_ARTIFACT_DIR)||F(Cr(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||rt(),i=F(n,s),o=F(i,rt());return os(o,{recursive:!0}),{root:o,realRoot:ht(o),sessionRoot:i,realSessionRoot:ht(i)}}function Ls(e){let t=a(e?.artifactDirectory);if(!t)throw new Error("sandbox launch did not provide an artifact directory");return{root:t,realRoot:ht(t),sessionRoot:"",realSessionRoot:""}}function vr(e){return a(u(e)?e.root:e)}function Er(e){let t=vr(e),r=a(u(e)?e.sessionRoot:fs(t)),n=a(u(e)?e.realSessionRoot:"");if(r)try{if(n&&ht(r)!==n)return;cs(r)}catch{}}function Ds(e,t={}){let r=vr(e),n=a(u(e)?e.realRoot:"");if(r){try{if(n&&ht(r)!==n){h("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:r});return}}catch{Er(e);return}try{as(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}Er(e)}}function vs(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 Fr(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)||F(ds(),".codex");return F(n,"sessions")}function Fs(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 F(e,n,s,i)}function Hr(e,t,r){let n=new Set;for(let s of[t-Mt,t,t+Mt,r-Mt,r,r+Mt])n.add(Fs(e,s));return[...n].filter(s=>Or(s))}function Hs(e,t,r){let n=Fr(e),s=t-ps,i=r+hs,o=[];for(let c of Hr(n,t,r)){let l=[];try{l=xr(c)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=F(c,d);try{let p=us(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,gs)}function $s(e,t,r=t){let n=Fr(e),s=new Set;for(let i of Hr(n,t,r)){let o=[];try{o=xr(i)}catch{continue}for(let c of o)c.endsWith(".jsonl")&&s.add(F(i,c))}return s}function ie(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)ie(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&&ie(e[n],t,r+1)}}function $r(e){return a(e).replace(/\s+/g," ")}function Bs(e){let t=$r(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 qs(e,t){let r=Bs(t);if(!r.length)return!1;let n=[];for(let i of e)ie(i,n);let s=$r(n.join(" "));return r.every(i=>s.includes(i))}function js(e){return e.find(t=>u(t)&&a(t.type)==="session_meta"&&u(t.payload))||null}function Ks(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 Gs(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 Vs(e,t,r){if(!qs(e,t.promptText))return!1;let n=js(e);if(!n)return!1;let s=n.payload;if(!Gs(s))return!1;let i=Ks(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&&Rr(o)!==Rr(c))}function wr(e){try{return Ws(Ar(e,"utf8"))}catch{return null}}function zs(e,t,r){if(!e||e.disabled)return null;if(e.matchedPath){let s=wr(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let n=[];for(let s of Hs(e.target,e.startedAtMs,r)){if(e.baselinePaths.has(s.path))continue;let i=wr(s.path);!i||!Vs(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 Ws(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 Js(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 Xs(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return a(e.type)==="response_item"&&ys.has(a(t.type))}function Ys(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return Ss.has(a(t.type))}function Zs(e,t,r,n){let s=br(e),i=ce(e),o=0,c=0,l=0;if(s&&!i&&t.emitThoughtChunks&&Dr(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 ur}from"node:crypto";import{existsSync as Kn,readFileSync as Gn,realpathSync as or,statSync as Vn}from"node:fs";import{basename as lr,extname as dr,isAbsolute as pt,join as zn,relative as fr,resolve as ar}from"node:path";var Wn=25*1024*1024;function pr(e,t=""){let r=a(t);if(r)return r;let n=dr(a(e)).toLowerCase();return n===".jpg"||n===".jpeg"?"image/jpeg":n===".webp"?"image/webp":n===".gif"?"image/gif":"image/png"}function mr(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 Ct(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function Jn(e,t){let r=fr(t,e);return r===""||!!r&&!r.startsWith("..")&&!pt(r)}function Xn(e,t){let r=a(e);if(!r||!Kn(r))return"";try{let n=or(r);for(let s of t)try{let i=or(s);if(Jn(n,i))return n}catch{}}catch{return""}return""}function Yn(e,t){let r=a(e);if(!r||!pt(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||!pt(s)||!pt(i))continue;let o=fr(ar(s),ar(r));if(o===""||!o.startsWith("..")&&!pt(o))return o?zn(i,o):i}return r}function Qt(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=[...Ct(r.trustedFileRoots),...Ct(r.trustedFileRoot),...Ct(r.artifactRoots),...Ct(r.artifactRoot)],s=Xn(Yn(e,r.pathMappings),n);if(!s)return"";try{let i=Vn(s);return!i.isFile()||i.size<=0||i.size>Wn?"":`data:${t};base64,${Gn(s).toString("base64")}`}catch{return""}}function x(...e){for(let t of e){let r=a(t);if(r)return r}return""}function Qn(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=dr(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function ee(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=pr(c,n.mimeType||n.mime_type),f=mr(n.result,d)||Qt(c,d,t);if(!f)return null;let p=f.startsWith("data:")?f:"",m=c?lr(c):`${o||ur()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:m||"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:m,mimeType:d,revisedPrompt:l||void 0}}}function ts(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 es(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=Qn(n,s,l,o),f=d?pr(o,c):c;if(d){let b=x(n.dataUrl,s.dataUrl),T=b.startsWith("data:")?b:"",R=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),S=mr(n.result??s.result,f)||T||Qt(o,f,t)||Qt(R,f,t);S&&(S.startsWith("data:")&&(s.dataUrl||=S),s.imageUrl||=S,s.previewUrl||=S,s.fileUrl||=S,f&&(s.mimeType||=f))}for(let[b,T]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let R=n[b];R!=null&&R!==""&&!(T in s)&&(s[T]=R)}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),m=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),g=x(n.dataUrl,s.dataUrl,p.startsWith("data:")?p:"",m.startsWith("data:")?m:""),y=x(n.filename,i.filename,o?lr(o):""),I=x(n.fieldKey,n.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...n,artifactType:l,type:n.type||l,fieldKey:I,title:x(n.title,y,"Runtime artifact"),summary:x(n.summary,s.prompt,n.title,y,"Runtime artifact"),content:s,dataUrl:g||void 0,fileUrl:p||void 0,previewUrl:m||void 0,metadata:{...i,source:x(i.source,r),savedPath:o||i.savedPath,filename:y||i.filename,mimeType:f||i.mimeType}}}function bt(e,t){if(!t||!e)return;let r=u(t.metadata)?t.metadata:{},n=x(r.savedPath,r.callId,t.previewUrl,t.fileUrl)||ur(),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 te(e,t,r={}){for(let n of ts(e))bt(t,es(n,r))}function re(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 cr(e,t,r){if(!u(e))return e;let n=u(e.event)?e.event:null;return n?(bt(t,ee(n,r)),{...e,event:re(n)}):e}function hr(e,t,r={}){if(!u(e))return e;te(e,t,r);let n=cr(e,t,r),s=u(n.update)?cr(n.update,t,r):null;return s&&s!==n.update&&(n={...n,update:s}),n}function gr(e,t,r={}){let n=u(e)?{...e}:{};te(n,t,r),te(u(n.output)?n.output:{},t,r);let s=[...t?.values?.()||[]];return s.length&&(n._artifacts=s),delete n.artifacts,n}function _r(e,t){let r=_(e,t);return r>0?r:t}var et=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:tt(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 At({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:_r(this.target.initializeTimeoutMs,_r(this.options.initializeTimeoutMs,3e4)),initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:Q},...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(hr(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 gr(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 rs(e){let t=u(e.metadata)?e.metadata:{};return a(t.agentCode)}function ns(e,t){let r=rs(e);return r?`agent:${r}:${t}`:`orcha-${t}`}var Nt=class extends et{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",ns(t,o)];super(t,{...r,command:c,args:d},s,i)}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as wr}from"node:child_process";import{randomUUID as rt}from"node:crypto";import{existsSync as Or,mkdirSync as ss,readdirSync as Ir,readFileSync as xr,realpathSync as ht,rmSync as is,rmdirSync as os,statSync as as,unlinkSync as cs}from"node:fs";import{homedir as us,tmpdir as Ar}from"node:os";import{basename as ae,dirname as ls,join as H,resolve as Tr}from"node:path";var ds=36e5,Cr=5e3,fs=2*60*1e3,ps=2*60*1e3,ms=12,hs=1e3,gs=1500,_s=1e3,Mt=24*60*60*1e3,mt=new Set(["final_answer","final","complete","completed","done"]),Ts=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"]),ys=new Set(["context_compacted","context_compaction","context_compressed"]);function Pt(e,t){if(e?.pid){if(process.platform==="win32"){let r=["/PID",String(e.pid),"/T"];t==="SIGKILL"&&r.push("/F");try{wr("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 ne(e){Pt(e,"SIGTERM");let t=setTimeout(()=>Pt(e,"SIGKILL"),Cr);return t.unref?.(),t}function D(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>D(t)).join("");if(!u(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let r=D(e[t]);if(r)return r}return""}function br(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 D(t.content)||D(t.message);if(a(e.type)==="result")return D(e.result);let r=D(e.delta)||D(e.text)||D(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"?D(n.content)||D(n.text)||D(n.message):""}function Nr(e,t={}){return ee(e,{source:"codex_cli_image_generation",...t})}function Mr(e,t){bt(e.artifacts,t)}function Ur(e){return z(re(e))}function ce(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 mt.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 Rs(e){let t=a(e.terminalProtocol||e.eventProtocol).toLowerCase();if(t)return t;let r=ae(a(e.command)).replace(/\.exe$/i,"").toLowerCase();return r==="codex"||r==="claude"?r:""}function yr(e,t,r){let n=u(t.error)?t.error:{},s=a(n.message)||D(t.error)||a(t.result)||a(t.message)||r;return Object.assign(new Error(s),{code:e})}function Ss(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:yr("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:yr("RUNTIME_CLAUDE_RESULT_FAILED",e,"Claude result failed")}:{status:"completed",result:{stopReason:"end_turn",...a(e.result)?{output:a(e.result)}:{}}}}return null}function Rr(e){return u(e)?a(e.phase||e.status||e.stage).toLowerCase():""}function Es(e){if(!u(e)||ce(e))return!1;let t=u(e.payload)?e.payload:{},r=a(e.type),n=a(t.type),s=Rr(t);if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&a(t.role)==="assistant")return!!(s&&!mt.has(s));let i=u(e.item)?e.item:{},o=Rr(i);return a(i.role)==="assistant"||a(i.type)==="message"?!!(o&&!mt.has(o)):!1}function ws(e,t,r){return r.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:r.captureLastMessage===!0?!0:ae(e)==="codex"}function Os(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:ae(e)==="codex"}function Pr(e){return Math.max(20,_(e.codexTranscriptPollMs||e.transcriptPollMs,hs))}function Is(e){return Math.max(0,_(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,gs))}function kt(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 ue(e){let t=u(e?.metadata)?e.metadata:{};return u(t._runtimeBridge)?t._runtimeBridge:{}}function se(e){return a(ue(e).promptKind).toLowerCase()}function xs(e,t){for(let r of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let n=kt(r);if(n!=null)return n}return se(t)==="chat"}function As(e,t){let r=ue(e);for(let s of[r.emitThoughtChunks,r.streamThoughts]){let i=kt(s);if(i!=null)return i}let n=se(e);if(n&&n!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=kt(s);if(i!=null)return i}return se(e)==="chat"}function Cs(e){let t=ue(e);for(let r of[t.finalTextOnly,t.finalOutputOnly]){let n=kt(r);if(n!=null)return n}return null}function bs(e,t){let r=Cs(e);return r??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function Ns(e,t){return!e.finalTextOnly||t}function kr(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 Lr(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 Ms(e,t,r,n=new Set){return{target:e,promptText:t,startedAtMs:r,baselinePaths:n,matchedPath:"",disabled:!1,processedLines:new Map}}function Us(e,t){let r=u(e.env)?e.env:{},n=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||r.ORCHA_RUNTIME_ARTIFACT_DIR)||H(Ar(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||rt(),i=H(n,s),o=H(i,rt());return ss(o,{recursive:!0}),{root:o,realRoot:ht(o),sessionRoot:i,realSessionRoot:ht(i)}}function Ps(e){let t=a(e?.artifactDirectory);if(!t)throw new Error("sandbox launch did not provide an artifact directory");return{root:t,realRoot:ht(t),sessionRoot:"",realSessionRoot:""}}function Dr(e){return a(u(e)?e.root:e)}function Sr(e){let t=Dr(e),r=a(u(e)?e.sessionRoot:ls(t)),n=a(u(e)?e.realSessionRoot:"");if(r)try{if(n&&ht(r)!==n)return;os(r)}catch{}}function ks(e,t={}){let r=Dr(e),n=a(u(e)?e.realRoot:"");if(r){try{if(n&&ht(r)!==n){h("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:r});return}}catch{Sr(e);return}try{is(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}Sr(e)}}function Ls(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 vr(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)||H(us(),".codex");return H(n,"sessions")}function Ds(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 H(e,n,s,i)}function Hr(e,t,r){let n=new Set;for(let s of[t-Mt,t,t+Mt,r-Mt,r,r+Mt])n.add(Ds(e,s));return[...n].filter(s=>Or(s))}function vs(e,t,r){let n=vr(e),s=t-fs,i=r+ps,o=[];for(let c of Hr(n,t,r)){let l=[];try{l=Ir(c)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=H(c,d);try{let p=as(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,ms)}function Hs(e,t,r=t){let n=vr(e),s=new Set;for(let i of Hr(n,t,r)){let o=[];try{o=Ir(i)}catch{continue}for(let c of o)c.endsWith(".jsonl")&&s.add(H(i,c))}return s}function ie(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)ie(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&&ie(e[n],t,r+1)}}function Fr(e){return a(e).replace(/\s+/g," ")}function Fs(e){let t=Fr(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 $s(e,t){let r=Fs(t);if(!r.length)return!1;let n=[];for(let i of e)ie(i,n);let s=Fr(n.join(" "));return r.every(i=>s.includes(i))}function Bs(e){return e.find(t=>u(t)&&a(t.type)==="session_meta"&&u(t.payload))||null}function qs(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 js(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 Ks(e,t,r){if(!$s(e,t.promptText))return!1;let n=Bs(e);if(!n)return!1;let s=n.payload;if(!js(s))return!1;let i=qs(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&&Tr(o)!==Tr(c))}function Er(e){try{return Vs(xr(e,"utf8"))}catch{return null}}function Gs(e,t,r){if(!e||e.disabled)return null;if(e.matchedPath){let s=Er(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let n=[];for(let s of vs(e.target,e.startedAtMs,r)){if(e.baselinePaths.has(s.path))continue;let i=Er(s.path);!i||!Ks(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 Vs(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 zs(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 Ws(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return a(e.type)==="response_item"&&Ts.has(a(t.type))}function Js(e){if(!u(e))return!1;let t=u(e.payload)?e.payload:{};return ys.has(a(t.type))}function Xs(e,t,r,n){let s=br(e),i=ce(e),o=0,c=0,l=0;if(s&&!i&&t.emitThoughtChunks&&Lr(t,r,n,s)&&(l=1),s&&i){let d=t.emittedTexts.size?`
|
|
9
9
|
|
|
10
|
-
${s}`:s;
|
|
11
|
-
`,at,
|
|
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}),ne(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}),ne(n);this.active.clear()}};var le="ORCHA_RUNTIME_OUTPUT_START",de="ORCHA_RUNTIME_OUTPUT_END",fe="ORCHA_RUNTIME_CONTROL_START",
|
|
13
|
-
`)}function Gr(e,t,r=""){if(!Vr(e))return e==null?null:{required:!0,status:"failed",outcome:a(e?.outcome),goalContractHash:"",checks:[],errorCode:"invalid_goal_contract"};let n=we(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=mi(t),o=e.verificationPlan.checks.map(l=>yi(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 Vr(e){if(!u(e)||e.schemaVersion!==ui||!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 mi(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"){pi(s.event,t,r);continue}if(i==="tool_call"){let o=vt(s)||`tool-${r.length+1}`,c=Dt(t,r,o),l=Se(s,s.name||s.toolName||s.kind);c.toolName=l.toolName,c.arguments=l.arguments,c.status=gt(s.status),c.evidence=Ht(s);continue}if(i==="tool_call_update"){let o=vt(s);if(!o)continue;let c=Dt(t,r,o),l=Se(s,s.name||s.toolName||s.kind);c.toolName||=l.toolName,Object.keys(c.arguments).length===0&&(c.arguments=l.arguments),c.status=gt(s.status),c.evidence.push(...Ht(s))}}return r}function pi(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=vt(n)||`runtime-${r.length+1}`,l=Dt(t,r,c),d=Se(n,n.name||n.tool||s,s);l.toolName=d.toolName,l.arguments=d.arguments,l.status=gt(n.status),l.evidence.push(...Ht(n));return}if(!["function_call_output","custom_tool_call_output","local_shell_call_output","mcp_tool_call_output"].includes(s))return;let i=vt(n);if(!i)return;let o=Dt(t,r,i);o.status=Ti(n,o.toolName),o.evidence.push(...Ht(n))}function Dt(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 hi(e){let t=a(e).toLowerCase();return fi.get(t)||t}function Se(e,t,r=""){let n=gi(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:hi(t),arguments:n}}function vt(e){return u(e)?a(e.call_id||e.callId||e.toolCallId||e.id):""}function gi(e){if(!u(e))return{};for(let r of["arguments","args","rawInput","input","params","parameters"]){let n=_i(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 _i(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 Ti(e,t){if(!u(e))return"unknown";let r=Ft(e,0,{parseCliExitCode:t==="run_command"||t==="apply_patch"});return r.includes("failed")?"failed":r.includes("success")?"success":"unknown"}function Ft(e,t=0,r={}){if(t>8||e===null||e===void 0)return[];if(typeof e=="string")return Ri(e,t,r);if(Array.isArray(e))return e.flatMap(o=>Ft(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=gt(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(...Ft(e[o],t+1,r));return n}function Ri(e,t,r){let n=e.trim();if(!n)return[];try{return Ft(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 gt(e){let t=a(e).toLowerCase();return li.has(t)?"success":di.has(t)?"failed":"unknown"}function Ht(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:gt(i.status??(i.passed===!0?"passed":i.passed===!1?"failed":"")),...a(i.message)?{message:a(i.message)}:{}});return n}function yi(e,t){let r=t.filter(o=>e.toolNames.includes(o.toolName)&&Ee(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 ye(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?ye(e,"failed",i,"Runtime tool evidence failed."):ye(e,"missing",r.at(-1),n?"Required evidence is missing.":"Required tool execution is missing.")}function ye(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 Ee(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>Ee(r,t[n])):u(e)?u(t)?Object.entries(e).every(([r,n])=>Object.hasOwn(t,r)&&Ee(n,t[r])):!1:Object.is(e,t)}function B(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string")return jr(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 B(e[r])}).join(",")}]`;if(u(e))return`{${Object.keys(e).sort().map(t=>`${jr(t)}:${B(e[t])}`).join(",")}}`;throw new Error("invalid_jcs_json_value")}function jr(e){return Si(e),JSON.stringify(e)}function Si(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 Ei}from"node:child_process";import{createHash as wi,randomUUID as Ii}from"node:crypto";import{constants as Oi}from"node:fs";import{access as xi,mkdir as Ie,readdir as Ai,realpath as _t,rm as Ci,stat as Ni}from"node:fs/promises";import bi from"node:http";import{tmpdir as Mi}from"node:os";import{isAbsolute as Tt,join as nt,relative as zr,resolve as xe}from"node:path";var Ae=1,Ui="orcha.process-isolation/v1",Ce="orcha.egress-proxy/v1",Pi="--disable-wasm-trap-handler",$t={read_only:0,workspace_write:1,workspace_network:2},Oe={read_only:["read_only","denied"],workspace_write:["workspace_write","denied"],workspace_network:["workspace_write","restricted"]},ki=new Set([".env",".git-credentials",".netrc",".npmrc",".pypirc","credentials.json","secrets.json","id_rsa","id_ed25519"]);function W(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 Oe)||!(n in Oe))throw S("RUNTIME_SANDBOX_POLICY_INVALID","unsupported runtime access mode");if($t[r]>$t[n])throw S("RUNTIME_SANDBOX_POLICY_INVALID","access mode exceeds its ceiling");let[s,i]=Oe[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)!==Ae||!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 Wr(e,t){let r=W(e),n=W(t);return $t[n.accessMode]<$t[r.accessMode]}async function Jr(e){if(!e.sandboxRequired)return{dispatchable:!0,enforced:!1,backend:"direct",daemonStatus:"not_required",daemonProtocolVersion:"",policySchemaVersions:[Ae],runtimePolicyUpdates:!1,workspaceSync:!1,egressProxy:!1,reason:"external_runtime_sandbox_not_required"};let t=await Yr(e.sandboxBrokerCommand,process.env.PATH||"");if(!t)throw S("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let r=await Hi(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 qi(e),{dispatchable:!0,enforced:!0,backend:a(r.backend),daemonStatus:"ok",daemonProtocolVersion:a(r.protocolVersion||"orcha.runtime-sandbox-broker/v1"),policySchemaVersions:[Ae],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:e.egressProxyRequired}}async function Ne(e,t,r){let n=a(t.workspace||t.cwd),s=a(r),i=n||(t.allowRequestWorkspace===!0?s:"");if(!i||!Tt(i))throw S("RUNTIME_WORKSPACE_NOT_CONFIGURED","runtime target must configure an absolute trusted workspace");let o=await _t(i);if(!(await Ni(o)).isDirectory())throw S("RUNTIME_WORKSPACE_INVALID","runtime workspace is not a directory");if(!(e.trustedWorkspaceRoots.length?await Promise.all(e.trustedWorkspaceRoots.map(d=>_t(d))):[o]).some(d=>Me(d,o)))throw S("RUNTIME_WORKSPACE_OUTSIDE_TRUSTED_ROOT","runtime workspace is outside trusted roots");return o}async function Xr({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=W(d),p=await Ne(e,t,s),_=await _t(s);if(!Me(p,_))throw S("RUNTIME_WORKSPACE_CWD_INVALID","runtime cwd is outside its workspace");let m=await Yr(e.sandboxBrokerCommand,process.env.PATH||"");if(!m)throw S("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let R=`runtime-${wi("sha256").update(String(o)).digest("hex").slice(0,32)}`,O=xe(e.sandboxTempRoot||nt(Mi(),"orcha-runtime-sandboxes"));await Ie(O,{recursive:!0,mode:448});let N=nt(O,`${R}-${Ii()}`),T=nt(N,"home"),y=nt(N,"artifacts");await Ie(T,{recursive:!0,mode:448}),await Ie(y,{recursive:!0,mode:448});let E=f.networkMode==="restricted"?await $i(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",...Di(t,i)};A.HOME="/tmp/home",A.TMPDIR="/tmp",A.ORCHA_RUNTIME_ARTIFACT_DIR="/tmp/artifacts",A.NODE_OPTIONS=Pi;let U={schemaVersion:Ui,runId:String(o),instanceId:R,workspace:p,cwd:_,filesystemMode:f.filesystemMode,networkMode:f.networkMode,environmentMode:"allowlist",deniedRelativePaths:await vi(p),temporaryDirectory:N,egressProxy:E,environment:A,resourceLimits:Fi(f),readOnlyToolchainRoots:await Li(e,t)},K=!1,L=async()=>{if(!K){K=!0;try{E&&await Bi(e,E,{runId:String(o),instanceId:R})}finally{await Ci(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(U)},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:L}}async function Li(e,t){let r=C(t.toolchainRoots||t.sandboxToolchainRoots);if(!r.length)return[];let n=await Promise.all(C(e.trustedToolchainRoots).map(i=>_t(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(!Tt(i))throw S("RUNTIME_TOOLCHAIN_ROOT_INVALID","toolchain roots must be absolute");let o=await _t(i);if(!n.some(c=>Me(c,o)))throw S("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","toolchain root is outside trusted roots");s.push(o)}return[...new Set(s)]}function Di(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 vi(e){let t=[],r=0,n=async s=>{let i;try{i=await Ai(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=nt(s,o.name),l=zr(e,c),d=o.name.toLowerCase();(ki.has(d)||d.startsWith(".env."))&&t.push(l),o.isDirectory()&&!o.isSymbolicLink()&&await n(c)}};return await n(e),t.sort()}function Fi(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 Hi(e,t,r){return await new Promise((n,s)=>{let i=Ei(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 Yr(e,t){let r=a(e);if(!r)return"";let n=Tt(r)?[r]:String(t||"").split(":").filter(Boolean).map(s=>nt(s,r));for(let s of n)try{return await xi(s,Oi.X_OK),s}catch{}return""}async function $i(e,t){if(!e.egressProxyRequired)throw S("RUNTIME_EGRESS_UNAVAILABLE","restricted network requires the Egress Proxy");let r=await be(e,"POST","/v1/grants",{protocolVersion:Ce,...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 Bi(e,t,r){await be(e,"POST",`/v1/grants/${encodeURIComponent(t.grantId)}/revoke`,{protocolVersion:Ce,...r}).catch(()=>{})}async function qi(e){let t=await be(e,"GET","/health");if(t.status!=="ok"||t.proxy!=="orcha-egress-proxy"||t.protocolVersion!==Ce)throw S("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy is unavailable or incompatible")}async function be(e,t,r,n){if(!Tt(e.egressProxySocket)||!e.egressProxyToken)throw S("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy socket and token are required");return await new Promise((s,i)=>{let o=bi.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 Me(e,t){let r=zr(xe(e),xe(t));return r===""||!r.startsWith("..")&&!Tt(r)}function S(e,t){return Object.assign(new Error(t),{code:e})}var Ue=24e3,Pe=8,ke=50,Le=6e3,Ki=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),Gi=10*60*1e3,Vi=60*1e3,zi=8,Wi=30*60*1e3,Ji=60*1e3,Xi=1,rn=2400,Yi=new Set(["max_tokens","max_output_tokens","length"]),Zi=new Set(["agent_message_chunk","tool_call","tool_call_update"]),Qi=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions","runtimeMaxSessions"]),to=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function eo(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 ro(e){return(Array.isArray(e)?e:[]).map(eo).sort((t,r)=>{let n=B(t),s=B(r);return n<s?-1:n>s?1:0})}function no(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 so(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:qt()}}}function k(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 nn(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return Ki.has(t)}function G(e,t){let r=g(e,t);return Number.isFinite(r)&&r>0?r:t}function Fe(e){let t=g(e,null);return Number.isFinite(t)&&t>0?t:null}function Rt(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 j(e){return a(e?.type||"echo")}function sn(e){let t=j(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function He(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 io(e){let t=String(e||"");if(to.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 $e(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=Le)return e;let r=e.length-Le;return`${e.slice(0,Le)}... [truncated ${r} characters]`}if(t>=Pe)return Array.isArray(e)?`[array truncated at depth ${Pe}, items=${e.length}]`:u(e)?`[object truncated at depth ${Pe}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let r=e.slice(0,ke).map(n=>$e(n,t+1));return e.length>ke&&r.push(`[truncated ${e.length-ke} items]`),r}if(u(e)){let r={};for(let[n,s]of Object.entries(e))r[n]=io(n)?"[REDACTED]":$e(s,t+1);return r}return String(e)}var oo=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 ao(e){if(!u(e))return e;let t={};for(let r of oo)k(e[r])&&(t[r]=e[r]);return t}function co(e){if(!u(e))return e;let t={...e};return u(t.renderedPayload)&&(t.renderedPayload=ao(t.renderedPayload)),t}function uo(e){let t=u(e)?e:{},r={};k(t.metadata)&&(r.metadata=co(t.metadata));for(let[n,s]of Object.entries(t))Qi.has(n)||n==="metadata"||k(s)&&(r[n]=s);return r}function lo(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 on(e){return a(lo(e).kind).toLowerCase()==="decision"}function Zr(e){let t=u(e)?e:{},r=u(t.metadata)?t.metadata:{};return Fe(t.runtimeMaxSessions??r.runtimeMaxSessions)}function fo(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:j(e)==="cli"}function Qr(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return Rt(t,sn(e))}function mo(e,t){let r=u(e?.metadata)?{...e.metadata}:{},n=u(r._runtimeBridge)?{...r._runtimeBridge}:{},s=He(n);return r._runtimeBridge={...n,promptKind:"dispatch",finalTextOnly:fo(t),releaseAfterPrompt:s===void 0?Qr(t):Rt(s,Qr(t)),requiresRuntimeResult:on(e)},r}function po(e){let t=uo(e);if(!k(t))return"";let r=JSON.stringify($e(t),null,2);if(r.length<=Ue)return r;let n=r.length-Ue;return`${r.slice(0,Ue)}
|
|
14
|
-
... [truncated ${n} characters]`}function
|
|
15
|
-
`:"";t+=`${s}${n}`}}return t.trim()}function
|
|
16
|
-
`?1:0)).trim()}function
|
|
17
|
-
`)}function xo(e,t){let r=u(t)?{...t}:{},n=un(e?._artifacts,t?._artifacts);return n.length>0&&(r._artifacts=n),r}function Ao(e,t){return{...e,_meta:{...u(e?._meta)?e._meta:{},runtimeProtocolRetry:{attempted:!0,recovered:!0,reason:Ke(t)||"max_tokens"}}}}function Co(e,t){let r=typeof e?.output=="string"?e.output:je(t),n=new P("runtime_output_truncated","Runtime Result \u8FBE\u5230\u6700\u5927\u8F93\u51FA\u957F\u5EA6\uFF0C\u7D27\u51D1\u91CD\u8BD5\u540E\u4ECD\u672A\u5B8C\u6574\u8FD4\u56DE",r);return n.detail={...n.detail,stopReason:Ke(e)||"max_tokens",retryAttempted:!0},n}var Kt=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=dt(),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 Jr(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)?we(t.goalContract):a(t.goalContractHash),i=ji("sha256").update(B({prompt:Array.isArray(t.prompt)?t.prompt:[],mcpServers:ro(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,o=s){let c=u(t.metadata)?t.metadata:{},l=u(c._runtimeBridge)?c._runtimeBridge:{},d=ln(i,o,l),f=Gr(t.goalContract,s,t.goalContractHash);return{sessionId:n,runtimeSessionId:r.runtimeSessionId,result:d,updates:s,...f?{verification:f}:{}}}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=G(this.config.operationTtlMs,Wi);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=j(t)==="openclaw"?G(this.config.openClawSessionIdleTtlMs,Ji):G(this.config.sessionIdleTtlMs,Gi);return G(t?.sessionIdleTtlMs??t?.idleTtlMs,n)}targetMaxSessions(t,r=null){let s=j(t)==="openclaw"?G(this.config.openClawMaxSessions,Xi):G(this.config.maxSessionsPerTarget,zi),i=G(t?.maxSessions,s),o=Fe(r);return o?Math.max(i,o):i}targetReleaseAfterPrompt(t,r={}){let n=j(t),s=u(r?._runtimeBridge)?r._runtimeBridge:{},i=He(s);return i!==void 0?Rt(i,!1):Rt(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}promptReleaseAfterPrompt(t,r={}){if(this.config.sandboxRequired)return!0;let n=u(r?._runtimeBridge)?r._runtimeBridge:{},s=He(n);return s!==void 0?Rt(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=G(this.config.sessionCleanupIntervalMs,Vi);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=Fe(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 Ne(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:dt(),runtimeKind:j(s),runtimeMaxSessions:Zr(t)};return this.agents.set(r,c),{agent:c}}runtimeFor(t,r,n={}){let{target:s}=this.targetFor(t.targetCode),i=j(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=>Xr({config:this.config,target:s,...l,runId:n.runId,agentId:t.agentId,sessionId:r,sandboxPolicy:n.sandboxPolicy})}:{}};return i==="stdio-acp"||i==="acp"?new et(t,s,o,c):i==="openclaw"?new bt(t,s,r,o,c):i==="cli"?new Lt(t,s,c):new Ot(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:W(t.sandboxPolicy)}}let n=a(t.agentId),s=a(t.sessionId)||qt(),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?W(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(j(d.target)==="cli"&&no(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=Zr(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:tt(y,f.workspace),mcpServers:Array.isArray(t.mcpServers)?t.mcpServers:[],metadata:u(t.metadata)?t.metadata:{}}),U=Date.now();m={agentId:s,sessionId:i,runtime:E,targetCode:T,runtimeKind:j(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:U,lastUsedAtMs:U,busy:!1,createdAt:dt()},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=so(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=Kr(t.goalContract),y=Array.isArray(t.prompt)?[...t.prompt]:[];T&&y.unshift({type:"text",text:T,metadata:{source:"orcha_goal_contract"}});let E=u(t.metadata)?t.metadata:{},A=u(E._runtimeBridge)?E._runtimeBridge:{},U=await m.runtime.sessionPrompt({sessionId:m.runtimeSessionId,prompt:y,metadata:E},O,N),K=R,L=null;if(sn({type:m.runtimeKind})&&Io(U,R,A)){L=U;let Y=R.length,at=await m.runtime.sessionPrompt({sessionId:m.runtimeSessionId,prompt:[{type:"text",text:Oo()}],metadata:E,_meta:{thinking:"off"}},O,N);U=xo(L,at),K=R.slice(Y)}let w;try{w=this.promptResponse(t,m,i,R,U,K)}catch(Y){throw L&&dn(U)?Co(U,K):Y}return L&&(w.result=Ao(w.result,L)),n&&this.completeOperation(n,w),w}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=W(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(B(f)!==B(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=Wr(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=po(t),d=on(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  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 ${pe} and ${he}.`:"",d?`Then put a JSON object containing _decision between ${ge} and ${_e}.`:"",d?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"",d?`Keep the report within ${rn} Unicode characters so the CONTROL block fits before the output limit.`:"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
|
|
18
|
-
`)}];return this.prompt({...t,agentId:n,sessionId:o,prompt:p,metadata:mo(t,f)},r)}async requestPermission({agent:t,runtimeSessionId:r,request:n,emitUpdate:s}){let i=qt(),c=this.runtimeSessionIndex.get(`${t.agentId}:${r}`)?.sessionId||r||qt(),l={permissionId:i,agentId:t.agentId,sessionId:c,runtimeSessionId:r,request:u(n)?n:{},status:"pending",createdAt:dt()};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:Q,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 No from"node:http";import bo from"node:https";import{randomBytes as fn}from"node:crypto";var it=1,J=3,Mo=1e4,Gt=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=Uo(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:"?bo:No,n=fn(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===J){o.destroy();return}this.socket=o,this.readyState=it,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==J&&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!==J&&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===it||this.readyState===J)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!==it||this.socket.write(Ge(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==J){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===it&&this.socket.write(Ge(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==J&&(this.clearConnectTimer(),this.readyState=J,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(Ge(10,d))}}};function Uo(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function Ge(e,t){let r=t.length,n=2;r>=126&&r<=65535?n+=2:r>65535&&(n+=8);let s=fn(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 Po(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 Ve(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 Vt=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=Po(this.config.orchaUrl),r=new Gt(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:Q,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,sandboxCapabilities:this.sandboxCapabilities(),targets:Ve(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:Ve(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:Ve(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!==it?!1:(r.send(JSON.stringify(t)),!0)}};import{existsSync as mn,readFileSync as ko}from"node:fs";import{dirname as Lo,resolve as zt}from"node:path";import{fileURLToPath as Do}from"node:url";var vo=/^[A-Za-z_][A-Za-z0-9_]*$/;function pn(e=process.env,t=process.cwd()){let r=a(e.ORCHA_RUNTIME_ENV_FILE),n=r?zt(t,r):zt(t,".env");if(!mn(n))return r&&h("warn","config","runtime env file not found",{path:n}),{loaded:!1,path:n,keys:[]};let s=[],i=ko(n,"utf8");for(let o of i.split(/\r?\n/)){let c=$o(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 hn(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=Lo(Do(import.meta.url)),i=zt(s,"sandbox","broker.js"),o=zt(s,"orcha-runtime-sandbox-broker.js"),c=mn(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:ze(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:ze(e.ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS,"ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS"),trustedToolchainRoots:ze(e.ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS,"ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS"),egressProxyRequired:Ho(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:Fo(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function Fo(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 Ho(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 ze(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 $o(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(!vo.test(s))return null;let i=Bo(r.slice(n+1).trim());return[s,i]}function Bo(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let r=e.slice(1,-1);return t==='"'?qo(r):r}return jo(e).trim()}function qo(e){return e.replaceAll("\\n",`
|
|
19
|
-
`).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function
|
|
20
|
-
`),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function
|
|
21
|
-
`);
|
|
22
|
-
`:""),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
|
|
10
|
+
${s}`:s;kr(t,r,n,d,s)&&(o=1,c=1)}return s&&i&&(t.finalTextSeen=!0),Mr(t,Nr(e,t.artifactOptions)),(zs(e)||Ws(e)||Js(e)||i)&&n({sessionId:r,update:{sessionUpdate:"runtime_event",event:Ur(e)}}),{textCount:o,finalTextCount:c,thoughtCount:l}}function oe(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=Gs(t,r,s);if(f){let p=Math.min(t.processedLines.get(f.path)||0,f.events.length),m=e.artifacts.size;for(let g of f.events.slice(p)){let y=Xs(g,e,r,n);c+=y.textCount,l+=y.finalTextCount,d+=y.thoughtCount}t.processedLines.set(f.path,f.events.length),(f.events.length>p||e.artifacts.size>m)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:c,finalTextCount:l,thoughtCount:d}}function Ys(e,{remove:t=!0}={}){if(!e||!Or(e))return"";try{return xr(e,"utf8").trim()}catch{return""}finally{t&&Ut(e)}}function Ut(e){if(e)try{cs(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 Qs(e){return new Promise(t=>setTimeout(t,e))}function ti(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 ei(e,t,r,n,s,i){let o=oe(e,t,r,n,Date.now()),c=()=>ti(e,r,n,Ys(s,{remove:!1}));if(c()||e.finalTextSeen)return Ut(s),o;let l=Is(i);if(l<=0||!t&&!s)return Ut(s),o;let d=Date.now()+l,f=Math.min(Pr(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await Qs(Math.min(f,Math.max(0,d-Date.now()))),o=Zs(o,oe(e,t,r,n,Date.now())),!c()););return Ut(s),o}var Lt=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}-${rt()}`}}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)||rt(),c=Ot(t.prompt),l=a(this.target.promptMode||"stdin"),d=this.buildArgs(l,c),f=tt(this.target,this.agent.workspace),p=typeof this.options.prepareLaunch=="function",g=ws(i,d,this.target)?p?`/tmp/orcha-runtime-last-message-${rt()}.txt`:H(Ar(),`orcha-runtime-last-message-${rt()}.txt`):"";g&&d.push("--output-last-message",g);let y={...u(this.target.env)?this.target.env:{},...l==="env"?{ORCHA_RUNTIME_PROMPT:c}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:o},I=p?await this.options.prepareLaunch({command:i,args:d,cwd:f,environment:y}):{command:i,args:d,cwd:f,environment:{...process.env,...y},cleanup:async()=>{}},b=p?Ps(I):Us(this.target,o),T=b.root,R=Ls(this.target,T,I),S=Os(i,this.target),A={...this.target,targetCode:this.agent.targetCode,cwd:f,...p?{codexHome:H(I.homeDirectory,".codex")}:{}},U=S?Hs(A,s):new Set,K=p&&g?H(I.tempDirectory,g.slice(5)):g,L=_(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,_(this.options.sessionPromptTimeoutMs,ds));p||(I.environment.ORCHA_RUNTIME_ARTIFACT_DIR=T);let w=wr(I.command,I.args,{cwd:I.cwd,env:I.environment,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(o,w),h("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:o,pid:w.pid,timeoutMs:L,isolation:I.isolation});let Y="",at=a(this.target.outputMode||"text"),N={artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:R,finalTextSeen:!1,finalTextOnly:bs(t,this.target),emitThoughtChunks:As(t,this.target),terminalOutcome:null,terminalProtocol:Rs(this.target),emitTerminal:null},Jt=S?Ms(A,c,s,U):null;return w.stdout.setEncoding("utf8"),w.stdout.on("data",Z=>this.handleStdout(Z,at,N,o,r)),w.stderr.setEncoding("utf8"),w.stderr.on("data",Z=>{Y+=Z,this.target.emitStderr===!0&&r({sessionId:o,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:Z}}})}),l==="stdin"?w.stdin.end(c):w.stdin.end(),await new Promise((Z,Xt)=>{let ct=!1,tr=!1,St=null,ut=null,Yt=Jt&&xs(this.target,t)?setInterval(()=>{try{oe(N,Jt,o,r)}catch(O){h("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:o,error:String(O?.message||O)})}},Pr(this.target)):null;Yt?.unref?.();let er=setTimeout(()=>{tr=!0,h("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:o,pid:w.pid,timeoutMs:L}),Pt(w,"SIGTERM"),St=setTimeout(()=>{h("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:o,pid:w.pid}),Pt(w,"SIGKILL")},Cr),St.unref?.(),lt(Object.assign(new Error(`runtime CLI timed out after ${L}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},L);er.unref?.();let rr=async()=>{clearTimeout(er),ut&&clearTimeout(ut),Yt&&clearInterval(Yt),St&&!tr&&clearTimeout(St),ks(b,{target:this.agent.targetCode,sessionId:o}),this.active.delete(o),N.emitTerminal=null,await I.cleanup?.()},Nn=O=>{ct||(ct=!0,rr().then(()=>Z(O),Xt))},lt=O=>{ct||(ct=!0,rr().then(()=>Xt(O),F=>{h("warn","runtime.cli","sandbox launch cleanup failed",{target:this.agent.targetCode,sessionId:o,error:String(F?.message||F)}),Xt(O)}))};N.emitTerminal=O=>{let F={...u(O.result)?O.result:{},_artifacts:[...N.artifacts.values()]};try{n?.({...O,result:F})}catch(V){h("warn","runtime.cli","runtime terminal listener failed",{target:this.agent.targetCode,sessionId:o,error:String(V?.message||V)})}let v=Math.max(0,_(this.target.terminalExitGraceMs,_s));ut=setTimeout(()=>{ut=null,!(ct||this.active.get(o)!==w)&&(h("warn","runtime.cli","runtime stayed alive after terminal event; terminating child",{target:this.agent.targetCode,sessionId:o,pid:w.pid,terminalProtocol:N.terminalProtocol,graceMs:v}),ne(w))},v),ut.unref?.()},w.on("error",O=>{h("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:o,pid:w.pid,error:String(O?.message||O)}),lt(O)}),w.on("exit",(O,F)=>{(async()=>{at==="json-lines"&&N.value.trim()&&this.handleStdout(`
|
|
11
|
+
`,at,N,o,r);let v=await ei(N,Jt,o,r,K,this.target);(v.artifactCount>0||v.textCount>0||v.thoughtCount>0)&&h("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:o,artifactCount:v.artifactCount,textCount:v.textCount,finalTextCount:v.finalTextCount,thoughtCount:v.thoughtCount,transcriptCount:v.transcriptCount});let V=Y.trim();if(V&&h("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:o,stderr:V}),h("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:o,pid:w.pid,exitCode:O,signal:F,artifactCount:N.artifacts.size,finalTextSeen:N.finalTextSeen}),N.terminalOutcome?.status==="failed"){lt(N.terminalOutcome.error);return}if(O!==0&&N.terminalOutcome?.status!=="completed"){let Mn=Object.assign(new Error(`runtime CLI exited with code ${O??"unknown"}${F?` (${F})`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:O,signal:F});lt(Mn);return}Nn({stopReason:"end_turn",exitCode:O,signal:F,_artifacts:[...N.artifacts.values()],...V?{stderr:V}:{}})})().catch(lt)})})}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);Mr(n,Nr(d,n.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:Ur(d)}});let f=br(d),p=ce(d);f&&n.emitThoughtChunks&&!p&&Es(d)?Lr(n,s,i,f):f&&Ns(n,p)&&kr(n,s,i,f),f&&p&&(n.finalTextSeen=!0);let m=Ss(d,n.terminalProtocol);m&&!n.terminalOutcome&&(m.status==="failed"||n.finalTextSeen||n.artifacts.size>0)&&(n.terminalOutcome=m,n.emitTerminal?.(m))}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}),ne(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}),ne(n);this.active.clear()}};var le="ORCHA_RUNTIME_OUTPUT_START",de="ORCHA_RUNTIME_OUTPUT_END",fe="ORCHA_RUNTIME_CONTROL_START",pe="ORCHA_RUNTIME_CONTROL_END",me=le,he=de,ge=fe,_e=pe,Te=[le,de,fe,pe],ri=new Set(["_artifacts","_decision","_meta"]),ni=new RegExp(`(?:^|(?<=[\\r\\n]))[ \\t]*(?<marker>${Te.join("|")})[ \\t]*(?=\\r\\n?|\\n|$)`,"g"),P=class extends Error{constructor(t,r,n){super(r),this.name="RuntimeResultProtocolError",this.code=t,this.detail={rawOutput:n}}};function Br(e){let t=typeof e=="string"?e.trimStart():"";return Te.some(r=>t.startsWith(r))}function ye(e){if(typeof e!="string")return null;let t=e,r=si(t);if(![...r.values()].some(g=>g.length>0))return null;let n=[],s=[];for(let[g,y]of r)y.length===0?n.push(g):y.length>1&&s.push(g);if(n.length>0||s.length>0){let g=[];throw n.length>0&&g.push(`\u7F3A\u5C11 ${n.join(", ")}`),s.length>0&&g.push(`\u91CD\u590D ${s.join(", ")}`),new P("invalid_markers",`Runtime Result \u534F\u8BAE\u6807\u8BB0\u4E0D\u5B8C\u6574\uFF1A${g.join("\uFF1B")}`,t)}let i=r.get(le)[0],o=r.get(de)[0],c=r.get(fe)[0],l=r.get(pe)[0];if(!(i.end<=o.start&&o.end<=c.start&&c.end<=l.start))throw new P("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=ii(t.slice(i.end,o.start));if(!d.trim())throw new P("empty_output","Runtime Result OUTPUT \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let f=t.slice(c.end,l.start).trim();if(!f)throw new P("empty_control","Runtime Result CONTROL \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let p;try{p=JSON.parse(f)}catch(g){throw new P("invalid_control_json",`Runtime Result CONTROL \u5757\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(g?.message||g)}`,t)}if(!$r(p))throw new P("invalid_control_type","Runtime Result CONTROL \u5757\u5FC5\u987B\u662F JSON \u5BF9\u8C61",t);let m=Object.keys(p).filter(g=>!ri.has(g)).sort();if(m.length>0)throw new P("invalid_control_keys",`Runtime Result CONTROL \u5757\u5305\u542B\u975E\u6807\u51C6\u5B57\u6BB5\uFF1A${m.join(", ")}`,t);if("_artifacts"in p&&!Array.isArray(p._artifacts))throw new P("invalid_control_field_type","Runtime Result CONTROL \u5757\u7684 _artifacts \u5FC5\u987B\u662F JSON \u6570\u7EC4",t);for(let g of["_decision","_meta"])if(g in p&&!$r(p[g]))throw new P("invalid_control_field_type",`Runtime Result CONTROL \u5757\u7684 ${g} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`,t);return{output:d,...p}}function si(e){let t=new Map(Te.map(r=>[r,[]]));for(let r of e.matchAll(ni))t.get(r.groups.marker).push({start:r.index,end:r.index+r[0].length});return t}function ii(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 $r(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{createHash as oi}from"node:crypto";var ai="orcha.goal-contract/v1",ci=new Set(["complete","completed","done","ok","passed","success","succeeded"]),ui=new Set(["aborted","blocked","cancelled","canceled","denied","error","failed","failure","timeout","timed_out"]),li=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 we(e){return oi("sha256").update(B(e)).digest("hex")}function jr(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.","Each check requires requiredMatches distinct successful tool call IDs; repeated updates for one call count once.","A final text claim is not verification; missing or failed tool evidence prevents completion."),t.join(`
|
|
13
|
+
`)}function Kr(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=we(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=di(t),o=e.verificationPlan.checks.map(l=>Ti(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!==ai||!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)))||!Number.isSafeInteger(n.requiredMatches)||n.requiredMatches<1||n.arguments!==void 0&&!u(n.arguments))return!1;return!0}function di(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"){fi(s.event,t,r);continue}if(i==="tool_call"){let o=vt(s)||`tool-${r.length+1}`,c=Dt(t,r,o),l=Se(s,s.name||s.toolName||s.kind);c.toolName=l.toolName,c.arguments=l.arguments,c.status=gt(s.status),c.evidence=Ft(s);continue}if(i==="tool_call_update"){let o=vt(s);if(!o)continue;let c=Dt(t,r,o),l=Se(s,s.name||s.toolName||s.kind);c.toolName||=l.toolName,Object.keys(c.arguments).length===0&&(c.arguments=l.arguments),c.status=gt(s.status),c.evidence.push(...Ft(s))}}return r}function fi(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=vt(n)||`runtime-${r.length+1}`,l=Dt(t,r,c),d=Se(n,n.name||n.tool||s,s);l.toolName=d.toolName,l.arguments=d.arguments,l.status=gt(n.status),l.evidence.push(...Ft(n));return}if(!["function_call_output","custom_tool_call_output","local_shell_call_output","mcp_tool_call_output"].includes(s))return;let i=vt(n);if(!i)return;let o=Dt(t,r,i);o.status=gi(n,o.toolName),o.evidence.push(...Ft(n))}function Dt(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 pi(e){let t=a(e).toLowerCase();return li.get(t)||t}function Se(e,t,r=""){let n=mi(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:pi(t),arguments:n}}function vt(e){return u(e)?a(e.call_id||e.callId||e.toolCallId||e.id):""}function mi(e){if(!u(e))return{};for(let r of["arguments","args","rawInput","input","params","parameters"]){let n=hi(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 hi(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 gi(e,t){if(!u(e))return"unknown";let r=Ht(e,0,{parseCliExitCode:t==="run_command"||t==="apply_patch"});return r.includes("failed")?"failed":r.includes("success")?"success":"unknown"}function Ht(e,t=0,r={}){if(t>8||e===null||e===void 0)return[];if(typeof e=="string")return _i(e,t,r);if(Array.isArray(e))return e.flatMap(o=>Ht(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=gt(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(...Ht(e[o],t+1,r));return n}function _i(e,t,r){let n=e.trim();if(!n)return[];try{return Ht(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 gt(e){let t=a(e).toLowerCase();return ci.has(t)?"success":ui.has(t)?"failed":"unknown"}function Ft(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:gt(i.status??(i.passed===!0?"passed":i.passed===!1?"failed":"")),...a(i.message)?{message:a(i.message)}:{}});return n}function Ti(e,t){let r=t.filter(o=>e.toolNames.includes(o.toolName)&&Ee(e.arguments||{},o.arguments)),n=a(e.evidenceId),s=r.filter(o=>o.status==="success"&&(!n||o.evidence.some(c=>c.id===n&&c.status==="success")));if(s.length>=e.requiredMatches)return Re(e,"passed",s,`Runtime tool evidence passed ${s.length} times.`);let i=r.filter(o=>o.status==="failed"||n&&o.evidence.some(c=>c.id===n&&c.status==="failed"));return s.length===0&&i.length?Re(e,"failed",i,"Runtime tool evidence failed."):Re(e,"missing",s,`Only ${s.length}/${e.requiredMatches} required tool executions passed.`)}function Re(e,t,r,n){let s=r.map(i=>i.toolCallId).filter(Boolean);return{id:e.id,status:t,message:n,...a(e.description)?{description:a(e.description)}:{},toolNames:e.toolNames,requiredMatches:e.requiredMatches,observedMatches:s.length,toolCallIds:s,...u(e.arguments)?{arguments:e.arguments}:{},...a(e.evidenceId)?{evidenceId:a(e.evidenceId)}:{}}}function Ee(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>Ee(r,t[n])):u(e)?u(t)?Object.entries(e).every(([r,n])=>Object.hasOwn(t,r)&&Ee(n,t[r])):!1:Object.is(e,t)}function B(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string")return qr(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 B(e[r])}).join(",")}]`;if(u(e))return`{${Object.keys(e).sort().map(t=>`${qr(t)}:${B(e[t])}`).join(",")}}`;throw new Error("invalid_jcs_json_value")}function qr(e){return yi(e),JSON.stringify(e)}function yi(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 Ri}from"node:child_process";import{createHash as Si,randomUUID as Ei}from"node:crypto";import{constants as wi}from"node:fs";import{access as Oi,mkdir as Oe,readdir as Ii,realpath as _t,rm as xi,stat as Ai}from"node:fs/promises";import Ci from"node:http";import{tmpdir as bi}from"node:os";import{isAbsolute as Tt,join as nt,relative as Vr,resolve as xe}from"node:path";var Ae=1,Ni="orcha.process-isolation/v1",Ce="orcha.egress-proxy/v1",Mi="--disable-wasm-trap-handler",$t={read_only:0,workspace_write:1,workspace_network:2},Ie={read_only:["read_only","denied"],workspace_write:["workspace_write","denied"],workspace_network:["workspace_write","restricted"]},Ui=new Set([".env",".git-credentials",".netrc",".npmrc",".pypirc","credentials.json","secrets.json","id_rsa","id_ed25519"]);function W(e){if(!u(e))throw E("RUNTIME_SANDBOX_POLICY_REQUIRED","sandboxPolicy is required");let t=structuredClone(e),r=a(t.accessMode),n=a(t.accessModeCeiling);if(!(r in Ie)||!(n in Ie))throw E("RUNTIME_SANDBOX_POLICY_INVALID","unsupported runtime access mode");if($t[r]>$t[n])throw E("RUNTIME_SANDBOX_POLICY_INVALID","access mode exceeds its ceiling");let[s,i]=Ie[r];if(t.filesystemMode!==s||t.networkMode!==i)throw E("RUNTIME_SANDBOX_POLICY_INVALID","runtime access profile does not match its mode");if(Number(t.policySchemaVersion)!==Ae||!Number.isInteger(Number(t.policyRevision))||Number(t.policyRevision)<1)throw E("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 E("RUNTIME_SANDBOX_POLICY_INVALID",`${c} cannot be relaxed`);let o=u(t.processIsolation)?t.processIsolation:{};if(o.mode!=="required"||o.backend==="direct")throw E("RUNTIME_SANDBOX_POLICY_INVALID","strong process isolation is required");if(Array.isArray(t.alwaysApprovedApprovalKeys)&&t.alwaysApprovedApprovalKeys.length)throw E("RUNTIME_SANDBOX_POLICY_INVALID","persistent runtime approvals are forbidden");return t}function zr(e,t){let r=W(e),n=W(t);return $t[n.accessMode]<$t[r.accessMode]}async function Wr(e){if(!e.sandboxRequired)return{dispatchable:!0,enforced:!1,backend:"direct",daemonStatus:"not_required",daemonProtocolVersion:"",policySchemaVersions:[Ae],runtimePolicyUpdates:!1,workspaceSync:!1,egressProxy:!1,reason:"external_runtime_sandbox_not_required"};let t=await Xr(e.sandboxBrokerCommand,process.env.PATH||"");if(!t)throw E("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let r=await vi(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 E("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 E("RUNTIME_SANDBOX_UNAVAILABLE",`sandbox broker probe failed: ${s}`);return e.egressProxyRequired&&await $i(e),{dispatchable:!0,enforced:!0,backend:a(r.backend),daemonStatus:"ok",daemonProtocolVersion:a(r.protocolVersion||"orcha.runtime-sandbox-broker/v1"),policySchemaVersions:[Ae],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:e.egressProxyRequired}}async function be(e,t,r){let n=a(t.workspace||t.cwd),s=a(r),i=n||(t.allowRequestWorkspace===!0?s:"");if(!i||!Tt(i))throw E("RUNTIME_WORKSPACE_NOT_CONFIGURED","runtime target must configure an absolute trusted workspace");let o=await _t(i);if(!(await Ai(o)).isDirectory())throw E("RUNTIME_WORKSPACE_INVALID","runtime workspace is not a directory");if(!(e.trustedWorkspaceRoots.length?await Promise.all(e.trustedWorkspaceRoots.map(d=>_t(d))):[o]).some(d=>Me(d,o)))throw E("RUNTIME_WORKSPACE_OUTSIDE_TRUSTED_ROOT","runtime workspace is outside trusted roots");return o}async function Jr({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=W(d),p=await be(e,t,s),m=await _t(s);if(!Me(p,m))throw E("RUNTIME_WORKSPACE_CWD_INVALID","runtime cwd is outside its workspace");let g=await Xr(e.sandboxBrokerCommand,process.env.PATH||"");if(!g)throw E("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let y=`runtime-${Si("sha256").update(String(o)).digest("hex").slice(0,32)}`,I=xe(e.sandboxTempRoot||nt(bi(),"orcha-runtime-sandboxes"));await Oe(I,{recursive:!0,mode:448});let b=nt(I,`${y}-${Ei()}`),T=nt(b,"home"),R=nt(b,"artifacts");await Oe(T,{recursive:!0,mode:448}),await Oe(R,{recursive:!0,mode:448});let S=f.networkMode==="restricted"?await Hi(e,{runId:String(o),instanceId:y,policyRevision:Number(f.policyRevision),ttlMs:Math.min(_(f.maxRuntimeSeconds,900)*1e3,e.egressGrantMaxTtlMs),maxTransferBytes:_(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",...ki(t,i)};A.HOME="/tmp/home",A.TMPDIR="/tmp",A.ORCHA_RUNTIME_ARTIFACT_DIR="/tmp/artifacts",A.NODE_OPTIONS=Mi;let U={schemaVersion:Ni,runId:String(o),instanceId:y,workspace:p,cwd:m,filesystemMode:f.filesystemMode,networkMode:f.networkMode,environmentMode:"allowlist",deniedRelativePaths:await Li(p),temporaryDirectory:b,egressProxy:S,environment:A,resourceLimits:Di(f),readOnlyToolchainRoots:await Pi(e,t)},K=!1,L=async()=>{if(!K){K=!0;try{S&&await Fi(e,S,{runId:String(o),instanceId:y})}finally{await xi(b,{recursive:!0,force:!0})}}};return{command:g,args:[...C(e.sandboxBrokerArguments),"--",r,...n],cwd:m,environment:{PATH:process.env.PATH||"",LANG:process.env.LANG||"C.UTF-8",ORCHA_PROCESS_ISOLATION_REQUEST:JSON.stringify(U)},tempDirectory:b,homeDirectory:T,artifactDirectory:R,pathMappings:[{runtimeRoot:"/tmp/artifacts",hostRoot:R},{runtimeRoot:"/tmp/home",hostRoot:T}],isolation:{enforced:!0,backend:"broker",instanceId:y,policyRevision:f.policyRevision},cleanup:L}}async function Pi(e,t){let r=C(t.toolchainRoots||t.sandboxToolchainRoots);if(!r.length)return[];let n=await Promise.all(C(e.trustedToolchainRoots).map(i=>_t(i)));if(!n.length)throw E("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","target toolchain roots require ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS");let s=[];for(let i of r){if(!Tt(i))throw E("RUNTIME_TOOLCHAIN_ROOT_INVALID","toolchain roots must be absolute");let o=await _t(i);if(!n.some(c=>Me(c,o)))throw E("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","toolchain root is outside trusted roots");s.push(o)}return[...new Set(s)]}function ki(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 Li(e){let t=[],r=0,n=async s=>{let i;try{i=await Ii(s,{withFileTypes:!0})}catch(o){if(s===e)throw o;return}for(let o of i){if(r+=1,r>1e4)throw E("RUNTIME_WORKSPACE_SCAN_LIMIT_EXCEEDED","workspace contains more than 10000 entries");let c=nt(s,o.name),l=Vr(e,c),d=o.name.toLowerCase();(Ui.has(d)||d.startsWith(".env."))&&t.push(l),o.isDirectory()&&!o.isSymbolicLink()&&await n(c)}};return await n(e),t.sort()}function Di(e){return{maxCpuSeconds:Math.max(1,_(e.maxRuntimeSeconds,900)),maxMemoryBytes:_(e.maxMemoryBytes,2*1024*1024*1024),maxProcesses:_(e.maxProcesses,128),maxOpenFiles:_(e.maxOpenFiles,1024),maxFileBytes:_(e.maxFileBytes,64*1024*1024)}}async function vi(e,t,r){return await new Promise((n,s)=>{let i=Ri(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(E("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(E("RUNTIME_SANDBOX_UNAVAILABLE","sandbox probe returned invalid JSON"))}})})}async function Xr(e,t){let r=a(e);if(!r)return"";let n=Tt(r)?[r]:String(t||"").split(":").filter(Boolean).map(s=>nt(s,r));for(let s of n)try{return await Oi(s,wi.X_OK),s}catch{}return""}async function Hi(e,t){if(!e.egressProxyRequired)throw E("RUNTIME_EGRESS_UNAVAILABLE","restricted network requires the Egress Proxy");let r=await Ne(e,"POST","/v1/grants",{protocolVersion:Ce,...t}),n={socketPath:e.egressProxySocket,grantId:a(r.grantId),credential:a(r.credential)};if(!n.grantId||!n.credential)throw E("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy returned an invalid grant");return n}async function Fi(e,t,r){await Ne(e,"POST",`/v1/grants/${encodeURIComponent(t.grantId)}/revoke`,{protocolVersion:Ce,...r}).catch(()=>{})}async function $i(e){let t=await Ne(e,"GET","/health");if(t.status!=="ok"||t.proxy!=="orcha-egress-proxy"||t.protocolVersion!==Ce)throw E("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy is unavailable or incompatible")}async function Ne(e,t,r,n){if(!Tt(e.egressProxySocket)||!e.egressProxyToken)throw E("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy socket and token are required");return await new Promise((s,i)=>{let o=Ci.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(E("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 Me(e,t){let r=Vr(xe(e),xe(t));return r===""||!r.startsWith("..")&&!Tt(r)}function E(e,t){return Object.assign(new Error(t),{code:e})}var Ue=24e3,Pe=8,ke=50,Le=6e3,qi=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),ji=10*60*1e3,Ki=60*1e3,Gi=8,Vi=30*60*1e3,zi=60*1e3,Wi=1,tn=2400,Ji=new Set(["max_tokens","max_output_tokens","length"]),Xi=new Set(["agent_message_chunk","tool_call","tool_call_update"]),Yi=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions"]),Zi=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Qi(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 to(e){return(Array.isArray(e)?e:[]).map(Qi).sort((t,r)=>{let n=B(t),s=B(r);return n<s?-1:n>s?1:0})}function eo(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 ro(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:qt()}}}function k(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 en(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return qi.has(t)}function G(e,t){let r=_(e,t);return Number.isFinite(r)&&r>0?r:t}function yt(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 j(e){return a(e?.type||"echo")}function rn(e){let t=j(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function He(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 no(e){let t=String(e||"");if(Zi.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 Fe(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=Le)return e;let r=e.length-Le;return`${e.slice(0,Le)}... [truncated ${r} characters]`}if(t>=Pe)return Array.isArray(e)?`[array truncated at depth ${Pe}, items=${e.length}]`:u(e)?`[object truncated at depth ${Pe}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let r=e.slice(0,ke).map(n=>Fe(n,t+1));return e.length>ke&&r.push(`[truncated ${e.length-ke} items]`),r}if(u(e)){let r={};for(let[n,s]of Object.entries(e))r[n]=no(n)?"[REDACTED]":Fe(s,t+1);return r}return String(e)}var so=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 io(e){if(!u(e))return e;let t={};for(let r of so)k(e[r])&&(t[r]=e[r]);return t}function oo(e){if(!u(e))return e;let t={...e};return u(t.renderedPayload)&&(t.renderedPayload=io(t.renderedPayload)),t}function ao(e){let t=u(e)?e:{},r={};k(t.metadata)&&(r.metadata=oo(t.metadata));for(let[n,s]of Object.entries(t))Yi.has(n)||n==="metadata"||k(s)&&(r[n]=s);return r}function co(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 nn(e){return a(co(e).kind).toLowerCase()==="decision"}function uo(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:j(e)==="cli"}function Yr(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return yt(t,rn(e))}function lo(e,t){let r=u(e?.metadata)?{...e.metadata}:{},n=u(r._runtimeBridge)?{...r._runtimeBridge}:{},s=He(n);return r._runtimeBridge={...n,promptKind:"dispatch",finalTextOnly:uo(t),releaseAfterPrompt:s===void 0?Yr(t):yt(s,Yr(t)),requiresRuntimeResult:nn(e)},r}function fo(e){let t=ao(e);if(!k(t))return"";let r=JSON.stringify(Fe(t),null,2);if(r.length<=Ue)return r;let n=r.length-Ue;return`${r.slice(0,Ue)}
|
|
14
|
+
... [truncated ${n} characters]`}function Be(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 $e(e){if(!u(e))return"";let t=u(e.update)?e.update:e;return a(t.sessionUpdate)}function qe(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=$e(c),d=Be(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 st(s);let o=n[n.length-1]||[];return st(o)}function po(e){return Array.isArray(e)?e.map(Be).filter(t=>t!==""):[]}function jt(e){return Array.isArray(e)?e.some(r=>$e(r))?e.filter(r=>Xi.has($e(r))).map(Be).filter(r=>r!==""):po(e):[]}function mo(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 ho(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 go(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let r=ho(mo(e[t]));if(r)return r}return""}function st(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=Br(n)&&!/[\r\n]$/.test(t)?`
|
|
15
|
+
`:"";t+=`${s}${n}`}}return t.trim()}function _o(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)&&(sn(r)||k(r._artifacts)||k(r.artifacts)||k(r._decision)||k(r._meta)))return r}catch{}return null}function Rt(e){try{return ye(e)}catch{return null}}function Bt(...e){let t=null;for(let r of e)try{if(ye(r))return}catch(n){t||=n}if(t)throw t}function De(e){let t=String(e||"").trim();if(!t)return null;let r=Rt(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 To(e){let t=Rt(qe(e));if(t)return t;let r=jt(e);for(let n=r.length-1;n>=0;n-=1){let s=Rt(r[n]);if(s)return s}return Rt(st(r))}function sn(e){if(!u(e))return!1;if(k(e.output))return!0;for(let t of["content","text","message","summary"])if(a(e[t]))return!0;return!!(en(e.status)||a(e.error)||a(e.errorMessage))}function $(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 yo(e){return u(e)?typeof(u(e._decision)?e._decision:u(e.decision)?e.decision:e).passed=="boolean":!1}function on(e){return u(e)?u(e._decision)&&typeof e._decision.passed=="boolean"?!0:yo(e.output):!1}function ve(e,t,r){let n=u(e)?{...e}:{};if(!k(n.output)){for(let s of["summary","message","content","text"])if(a(n[s])){n.output=a(n[s]);break}}return!k(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 Ro=["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 So(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 Ro)k(e[i])&&(s[i]=e[i]),k(r[i])&&(s.content[i]=r[i]);return s}function an(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]=So(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=an(e._artifacts,t._artifacts)),n}function cn(e,t,r={}){let n=a(r.promptKind),s=r.requiresRuntimeResult===!0,i=s||n==="dispatch",o=$(e),c=typeof o.output=="string"?Rt(o.output):null;if(c)return q(o,$(c),"result_block");let l=go(t),d=l?De(l):null,f=i?To(t):null;if(sn(o))return en(o.status)||a(o.error)||a(o.errorMessage)?o:n==="dispatch"&&d?q(o,$(d),"final_event"):n==="dispatch"&&f?q(o,$(f),"updates"):!s||on(o)?o:d?q(o,$(d),"final_event"):f?q(o,$(f),"updates"):(Bt(o.output,l,st(jt(t))),ve(o,"result",o.output));if(d)return q(o,$(d),"final_event");if(f)return q(o,$(f),"updates");if(l)return s?(Bt(l,st(jt(t))),ve(o,"final_event",l)):{...o,output:l,_meta:{...u(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let p=qe(t),m=De(p);if(m)return q(o,$(m),"updates");let g=_o(p);if(!g)return s&&Bt(st(jt(t))),o;let y=De(g);return y?q(o,$(y),"updates"):s?(Bt(p,g),ve(o,"updates",g)):{...o,output:g,_meta:{...u(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}function je(e){return u(e)?a(e.stopReason||e.stop_reason).toLowerCase():""}function un(e){return Ji.has(je(e))}function Eo(e,t,r){if(r.promptKind!=="dispatch"||r.requiresRuntimeResult!==!0||!un(e))return!1;try{return!on(cn(e,t,r))}catch{return!0}}function wo(){return["Your previous final response reached the output limit before the Runtime Result protocol was complete.","Re-emit the complete final Runtime Result from scratch using the conclusion you already reached.","Do not repeat analysis, process notes, tool calls, or task work.",`Keep the OUTPUT report within ${tn} Unicode characters.`,`Output ${me}, ${he}, ${ge}, and ${_e} on their own lines.`,"The CONTROL block must be valid JSON containing _decision and must be fully closed.","Return only the two protocol blocks."].join(`
|
|
17
|
+
`)}function Oo(e,t){let r=u(t)?{...t}:{},n=an(e?._artifacts,t?._artifacts);return n.length>0&&(r._artifacts=n),r}function Io(e,t){return{...e,_meta:{...u(e?._meta)?e._meta:{},runtimeProtocolRetry:{attempted:!0,recovered:!0,reason:je(t)||"max_tokens"}}}}function xo(e,t){let r=typeof e?.output=="string"?e.output:qe(t),n=new P("runtime_output_truncated","Runtime Result \u8FBE\u5230\u6700\u5927\u8F93\u51FA\u957F\u5EA6\uFF0C\u7D27\u51D1\u91CD\u8BD5\u540E\u4ECD\u672A\u5B8C\u6574\u8FD4\u56DE",r);return n.detail={...n.detail,stopReason:je(e)||"max_tokens",retryAttempted:!0},n}var Kt=class{constructor(t){this.config=t,this.targets=t.targets||{},this.agents=new Map,this.sessions=new Map,this.startingSessions=new Set,this.targetReservations=new Map,this.runtimeSessionIndex=new Map,this.pendingPermissions=new Map,this.operations=new Map,this.startedAt=dt(),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.onCapacityChanged=null,this.startSessionCleanup()}async start(){try{this.sandboxCapabilities=await Wr(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)?we(t.goalContract):a(t.goalContractHash),i=Bi("sha256").update(B({prompt:Array.isArray(t.prompt)?t.prompt:[],mcpServers:to(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,o=s){let c=u(t.metadata)?t.metadata:{},l=u(c._runtimeBridge)?c._runtimeBridge:{},d=cn(i,o,l),f=Kr(t.goalContract,s,t.goalContractHash);return{sessionId:n,runtimeSessionId:r.runtimeSessionId,result:d,updates:s,...f?{verification:f}:{}}}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=G(this.config.operationTtlMs,Vi);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=j(t)==="openclaw"?G(this.config.openClawSessionIdleTtlMs,zi):G(this.config.sessionIdleTtlMs,ji);return G(t?.sessionIdleTtlMs??t?.idleTtlMs,n)}targetMaxSessions(t){let n=j(t)==="openclaw"?G(this.config.openClawMaxSessions,Wi):G(this.config.maxSessionsPerTarget,Gi);return G(t?.maxSessions,n)}targetReservationCount(t){return Number(this.targetReservations.get(t)||0)}notifyCapacityChanged(){try{this.onCapacityChanged?.()}catch(t){h("warn","runtime-bridge","capacity heartbeat callback failed",{error:String(t)})}}targetCapacitySnapshot(t=!0){return Object.entries(this.targets).map(([r,n])=>{let s=[...this.sessions.values()].filter(f=>f.targetCode===r),i=s.filter(f=>f.busy).length,o=s.length-i,c=this.targetReservationCount(r),l=this.targetMaxSessions(n),d=t?Math.max(0,l-i-c):0;return{targetCode:r,targetName:a(n?.name||n?.targetName||r),targetType:a(n?.type||"echo"),status:t?d>0?"available":"busy":"unavailable",maxSessions:l,busySessions:i,idleSessions:o,reservedSessions:c,availableSessions:d}})}targetReleaseAfterPrompt(t,r={}){let n=j(t),s=u(r?._runtimeBridge)?r._runtimeBridge:{},i=He(s);return i!==void 0?yt(i,!1):yt(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}promptReleaseAfterPrompt(t,r={}){if(this.config.sandboxRequired)return!0;let n=u(r?._runtimeBridge)?r._runtimeBridge:{},s=He(n);return s!==void 0?yt(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=G(this.config.sessionCleanupIntervalMs,Ki);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}idleTargetSessions(t){return[...this.sessions.entries()].filter(([,r])=>r.targetCode===t&&!r.busy).sort((r,n)=>(r[1].lastUsedAtMs||0)-(n[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}`),this.notifyCapacityChanged(),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){let n=this.targetMaxSessions(r);for(;this.sessionCountForTarget(t)+this.targetReservationCount(t)>=n;){let s=this.idleTargetSessions(t);if(!s.length){let i=new Error(`runtime target session limit reached: ${t}`);throw i.code="RUNTIME_TARGET_SESSION_LIMIT",i}await this.closeSession(s[0][0],"target_session_limit")}this.targetReservations.set(t,this.targetReservationCount(t)+1),this.notifyCapacityChanged()}releaseTargetSlot(t){let r=Math.max(0,this.targetReservationCount(t)-1);r>0?this.targetReservations.set(t,r):this.targetReservations.delete(t),this.notifyCapacityChanged()}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 be(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:dt(),runtimeKind:j(s)};return this.agents.set(r,c),{agent:c}}runtimeFor(t,r,n={}){let{target:s}=this.targetFor(t.targetCode),i=j(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=>Jr({config:this.config,target:s,...l,runId:n.runId,agentId:t.agentId,sessionId:r,sandboxPolicy:n.sandboxPolicy})}:{}};return i==="stdio-acp"||i==="acp"?new et(t,s,o,c):i==="openclaw"?new Nt(t,s,r,o,c):i==="cli"?new Lt(t,s,c):new It(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:W(t.sandboxPolicy)}}let n=a(t.agentId),s=a(t.sessionId)||qt(),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?W(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(j(d.target)==="cli"&&eo(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,metadata:t.metadata})).agent;if(!this.config.sandboxRequired){let T=a(t.workspace);T&&T!==f.workspace&&(f.workspace=T)}let p=`${s}:${i}`;await this.cleanupExpiredSessions();let m=this.sessions.get(p),g=null;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){if(this.startingSessions.has(p))throw Object.assign(new Error(`runtime session is already starting: ${i}`),{code:"RUNTIME_SESSION_BUSY"});this.startingSessions.add(p);let{code:T,target:R}=d;try{await this.reserveTargetSlot(T,R),g=T;let S=this.runtimeFor(f,i,{runId:o,sandboxPolicy:c}),A=await S.sessionNew({cwd:tt(R,f.workspace),mcpServers:Array.isArray(t.mcpServers)?t.mcpServers:[],metadata:u(t.metadata)?t.metadata:{}}),U=Date.now();m={agentId:s,sessionId:i,runtime:S,targetCode:T,runtimeKind:j(R),runId:o,sandboxPolicy:c?structuredClone(c):null,runtimeSessionId:a(u(A)?A.sessionId:"")||i,idleTtlMs:this.targetIdleTtlMs(R),releaseAfterPrompt:this.config.sandboxRequired?!0:this.targetReleaseAfterPrompt(R,t.metadata),createdAtMs:U,lastUsedAtMs:U,busy:!1,createdAt:dt()},this.sessions.set(p,m),this.runtimeSessionIndex.set(`${s}:${m.runtimeSessionId}`,m)}catch(S){throw g&&(this.releaseTargetSlot(g),g=null),S}finally{this.startingSessions.delete(p)}}if(m.busy){let T=new Error(`runtime session is already running: ${i}`);throw T.code="RUNTIME_SESSION_BUSY",T}m.busy=!0,g&&this.releaseTargetSlot(g),this.notifyCapacityChanged(),m.operationCorrelationId=n?.correlationId||null,m.lastUsedAtMs=Date.now();let y=n?.updates||[],I=T=>{let R=ro(T,i,m);if(y.push(R),n)for(let S of n.listeners)try{S?.(R)}catch(A){h("warn","runtime-bridge","runtime operation update listener failed",{correlationId:n.correlationId,error:String(A)})}else r.onUpdate?.(R)},b=T=>{if(!(!n||n.status!=="running"||!u(T))){if(T.status==="failed"){let R=T.error;if(R instanceof Error){this.failOperation(n,R);return}let S=u(R)?R:{},A=Object.assign(new Error(a(S.message||T.message)||"runtime terminal failure"),{code:a(S.code||T.code)||"RUNTIME_TERMINAL_FAILED"});this.failOperation(n,A);return}this.completeOperation(n,this.promptResponse(t,m,i,y,u(T.result)?T.result:{stopReason:"end_turn"}))}};try{let T=jr(t.goalContract),R=Array.isArray(t.prompt)?[...t.prompt]:[];T&&R.unshift({type:"text",text:T,metadata:{source:"orcha_goal_contract"}});let S=u(t.metadata)?t.metadata:{},A=u(S._runtimeBridge)?S._runtimeBridge:{},U=await m.runtime.sessionPrompt({sessionId:m.runtimeSessionId,prompt:R,metadata:S},I,b),K=y,L=null;if(rn({type:m.runtimeKind})&&Eo(U,y,A)){L=U;let Y=y.length,at=await m.runtime.sessionPrompt({sessionId:m.runtimeSessionId,prompt:[{type:"text",text:wo()}],metadata:S,_meta:{thinking:"off"}},I,b);U=Oo(L,at),K=y.slice(Y)}let w;try{w=this.promptResponse(t,m,i,y,U,K)}catch(Y){throw L&&un(U)?xo(U,K):Y}return L&&(w.result=Io(w.result,L)),n&&this.completeOperation(n,w),w}finally{m.busy=!1,this.notifyCapacityChanged(),m.operationCorrelationId===n?.correlationId&&(m.operationCorrelationId=null),m.lastUsedAtMs=Date.now(),this.promptReleaseAfterPrompt(m,u(t.metadata)?t.metadata:{})&&await this.closeSession(p,"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=W(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),m=Number(o.policyRevision);if(m<p)throw Object.assign(new Error("runtime sandbox policy revision is stale"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:p});if(m===p){if(B(f)!==B(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 g=zr(f,o);c&&(c.sandboxPolicy=structuredClone(o)),d&&(d.sandboxPolicy=structuredClone(o));let y=!1;return g&&d?.busy===!0&&(await d.runtime.sessionCancel({sessionId:d.runtimeSessionId}),y=await this.closeSession(l,"sandbox_policy_downgrade")),{updated:!0,policyRevision:m,accessMode:o.accessMode,activeCommandCancelled:y,deferredToNextLaunch:!g&&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=fo(t),d=nn(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  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 ${me} and ${he}.`:"",d?`Then put a JSON object containing _decision between ${ge} and ${_e}.`:"",d?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"",d?`Keep the report within ${tn} Unicode characters so the CONTROL block fits before the output limit.`:"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
|
|
18
|
+
`)}];return this.prompt({...t,agentId:n,sessionId:o,prompt:p,metadata:lo(t,f)},r)}async requestPermission({agent:t,runtimeSessionId:r,request:n,emitUpdate:s}){let i=qt(),c=this.runtimeSessionIndex.get(`${t.agentId}:${r}`)?.sessionId||r||qt(),l={permissionId:i,agentId:t.agentId,sessionId:c,runtimeSessionId:r,request:u(n)?n:{},status:"pending",createdAt:dt()};return s?.({sessionId:r,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=_(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:Q,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 Ao from"node:http";import Co from"node:https";import{randomBytes as ln}from"node:crypto";var it=1,J=3,bo=1e4,Gt=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=No(r.connectTimeoutMs,bo),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:"?Co:Ao,n=ln(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===J){o.destroy();return}this.socket=o,this.readyState=it,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==J&&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!==J&&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===it||this.readyState===J)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!==it||this.socket.write(Ke(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==J){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===it&&this.socket.write(Ke(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==J&&(this.clearConnectTimer(),this.readyState=J,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,m)=>p^f[m%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(Ke(10,d))}}};function No(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function Ke(e,t){let r=t.length,n=2;r>=126&&r<=65535?n+=2:r>65535&&(n+=8);let s=ln(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 Mo(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 Uo(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 Ge=Object.freeze(["health","agents/create","agents/dispatch","sessions/prompt","sessions/policy","sessions/cancel","permissions/respond"]),Vt=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,this.capacityHeartbeatTimer=null,this.bridge.onCapacityChanged=()=>this.scheduleCapacityHeartbeat()}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}}runtimeTargets(){let t=this.sandboxCapabilities().dispatchable===!0;return typeof this.bridge.targetCapacitySnapshot=="function"?this.bridge.targetCapacitySnapshot(t):Uo(this.config.targets,t)}start(){this.connect()}stop(){this.stopped=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.capacityHeartbeatTimer&&clearTimeout(this.capacityHeartbeatTimer),this.capacityHeartbeatTimer=null,this.bridge.onCapacityChanged=null,this.ws?.close()}connect(){if(this.stopped)return;let t=Mo(this.config.orchaUrl),r=new Gt(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:Q,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,supportedMethods:Ge,sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()},t)}scheduleReconnect(t,r=this.ws){r&&this.ws!==r||(this.connected=!1,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.capacityHeartbeatTimer&&clearTimeout(this.capacityHeartbeatTimer),this.capacityHeartbeatTimer=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(),supportedMethods:Ge,sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()})}}startHeartbeat(t){this.heartbeatTimer&&clearInterval(this.heartbeatTimer);let r=Math.max(1e3,Number(this.config.heartbeatIntervalMs||15e3)),n=()=>this.sendCapacityHeartbeat(t);n(),this.heartbeatTimer=setInterval(n,r),this.heartbeatTimer.unref?.()}scheduleCapacityHeartbeat(){if(!this.connected||this.capacityHeartbeatTimer)return;let t=Math.max(25,Math.min(1e3,Number(this.config.capacityHeartbeatDebounceMs||100)));this.capacityHeartbeatTimer=setTimeout(()=>{this.capacityHeartbeatTimer=null,this.sendCapacityHeartbeat()},t),this.capacityHeartbeatTimer.unref?.()}sendCapacityHeartbeat(t=this.ws){return this.connected?this.send({type:"runtime_node.heartbeat",ts:new Date().toISOString(),supportedMethods:Ge,sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()},t):!1}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!==it?!1:(r.send(JSON.stringify(t)),!0)}};import{existsSync as dn,readFileSync as Po}from"node:fs";import{dirname as ko,resolve as zt}from"node:path";import{fileURLToPath as Lo}from"node:url";var Do=/^[A-Za-z_][A-Za-z0-9_]*$/;function fn(e=process.env,t=process.cwd()){let r=a(e.ORCHA_RUNTIME_ENV_FILE),n=r?zt(t,r):zt(t,".env");if(!dn(n))return r&&h("warn","config","runtime env file not found",{path:n}),{loaded:!1,path:n,keys:[]};let s=[],i=Po(n,"utf8");for(let o of i.split(/\r?\n/)){let c=Fo(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 pn(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=ko(Lo(import.meta.url)),i=zt(s,"sandbox","broker.js"),o=zt(s,"orcha-runtime-sandbox-broker.js"),c=dn(i)?i:o,l=a(e.ORCHA_RUNTIME_SANDBOX_BROKER_COMMAND);return{mode:t,host:r,port:_(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:_(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),connectTimeoutMs:_(e.ORCHA_RUNTIME_CONNECT_TIMEOUT_MS||e.ORCHA_RUNTIME_WS_CONNECT_TIMEOUT_MS,1e4),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:_(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),initializeTimeoutMs:_(e.ORCHA_RUNTIME_INITIALIZE_TIMEOUT_MS,3e4),sessionPromptTimeoutMs:_(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,36e5),permissionRequestTimeoutMs:_(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:_(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:_(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:_(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:_(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:_(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),heartbeatIntervalMs:_(e.ORCHA_RUNTIME_HEARTBEAT_INTERVAL_MS,15e3),sandboxRequired:n,sandboxBrokerCommand:l||process.execPath,sandboxBrokerArguments:Ve(e.ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS,"ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS",l?[]:[c]),sandboxProbeTimeoutMs:_(e.ORCHA_RUNTIME_SANDBOX_PROBE_TIMEOUT_MS,1e4),sandboxTempRoot:a(e.ORCHA_RUNTIME_SANDBOX_TEMP_ROOT),trustedWorkspaceRoots:Ve(e.ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS,"ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS"),trustedToolchainRoots:Ve(e.ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS,"ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS"),egressProxyRequired:Ho(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:_(e.ORCHA_RUNTIME_EGRESS_GRANT_MAX_TTL_MS,9e5),targets:vo(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function vo(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 Ho(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 Ve(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 Fo(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(!Do.test(s))return null;let i=$o(r.slice(n+1).trim());return[s,i]}function $o(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 qo(e).trim()}function Bo(e){return e.replaceAll("\\n",`
|
|
19
|
+
`).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function qo(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 jo}from"node:http";function Wt(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 X(e={}){return{ok:!0,...e}}function ze(e,t,r){return{ok:!1,error:{code:e,message:t,...r===void 0?{}:{detail:r}}}}async function mn(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 hn(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 gn(e,t){let r={"GET /health":async()=>X(t.health()),"POST /agents/create":async n=>X(await t.createAgent(n)),"POST /agents/dispatch":async n=>X(await t.dispatch(n)),"POST /sessions/prompt":async n=>X(await t.prompt(n)),"POST /sessions/cancel":async n=>X(await t.cancel(n)),"POST /permissions/respond":async n=>X(await t.respondPermission(n))};return jo(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){Wt(s,404,ze("NOT_FOUND",`No route for ${o}`));return}try{hn(n,e.token);let l=n.method==="GET"?{}:await mn(n,e.requestLimitBytes);Wt(s,200,await c(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";Wt(s,d,ze(f,l.message||String(l),l.detail))}})}var Yo=Xo(import.meta.url),Zo=".orcha-runtime-bridge.pid",Qo=".orcha-runtime-bridge.log",ta=3,ea=36e5,{command:ra,options:xn}=oa(process.argv.slice(2));aa(xn);fn();var na=pn();await sa(ra,na,xn);async function sa(e,t,r){switch(e){case"run":case"foreground":await Tn(t);return;case"start":if(r.foreground){await Tn(t);return}Rn();return;case"reload":case"restart":await Sn({quiet:!0}),Rn();return;case"stop":await Sn();return;case"status":ia();return;case"help":case"--help":case"-h":da();return;default:throw new Error(`Unknown command: ${e}`)}}async function Tn(e){ca();let t=new Kt(e);if(await t.start(),e.mode==="server"){let n=gn(e,t);yn({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 Vt(e,t);yn({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 yn({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 Rn(){let e=Ze(),t=An(),r=Qe(e);if(r&&ot(r)){console.log(JSON.stringify({status:"already_running",pid:r,pidFile:e,logFile:t}));return}r&&Xe(e),wn(e),wn(t),Je(t);let n=zo(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=Ko(process.execPath,[Yo,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",n,n]});i.unref(),Go(n),In(e,`${i.pid}
|
|
20
|
+
`),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function Sn({quiet:e=!1}={}){let t=Ze(),r=Qe(t);if(!r){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!ot(r)){Xe(t),e||console.log(JSON.stringify({status:"not_running",pid:r,pidFile:t}));return}process.kill(r,"SIGTERM"),!await En(r,1e4)&&ot(r)&&(process.kill(r,"SIGKILL"),await En(r,3e3)),Xe(t),e||console.log(JSON.stringify({status:"stopped",pid:r,pidFile:t}))}function ia(){let e=Ze(),t=An(),r=Qe(e),n=!!(r&&ot(r));console.log(JSON.stringify({status:n?"running":"not_running",running:n,pid:n?r:null,pidFile:e,logFile:t}))}function oa(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 aa(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 Ze(){return Ye(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Zo)}function An(){return Ye(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||Qo)}function ca(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=Cn();if(t<=0)return;let r=Ye(process.cwd(),e);Je(r,t);let n=la();n<=0||setInterval(()=>Je(r,t),n).unref()}function Je(e,t=Cn()){if(t<=0||!On(e))return;let r=0,n="";try{if(r=_n(e).size,r<=0)return;n=We(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&&(ua(d,s)?o.push(d):c+=1);if(c===0)return;let l="";try{_n(e).size>r&&(l=We(e,"utf8").slice(n.length));let f=[...o,...l.split(/\r?\n/).filter(Boolean)].join(`
|
|
21
|
+
`);In(e,f?`${f}
|
|
22
|
+
`:""),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 ua(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 Cn(){return bn(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,ta)}function la(){return bn(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,ea)}function bn(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function Qe(e){if(!On(e))return null;let t=Number.parseInt(We(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function ot(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function En(e,t){let r=Date.now();for(;Date.now()-r<t;){if(!ot(e))return!0;await new Promise(n=>setTimeout(n,100))}return!ot(e)}function wn(e){Vo(Jo(e),{recursive:!0})}function Xe(e){try{Wo(e,{force:!0})}catch{}}function da(){console.log(`Usage: orcha-runtime-bridge [command] [options]
|
|
23
23
|
|
|
24
24
|
Commands:
|
|
25
25
|
run, foreground Run in the foreground. This is the default.
|