@orcha-ai/runtime-bridge 0.1.28 → 0.1.29

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.
@@ -1,23 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as vs}from"node:child_process";import{closeSync as Bs,existsSync as mn,mkdirSync as Ks,openSync as zs,readFileSync as Wt,rmSync as js,statSync as an,writeFileSync as hn}from"node:fs";import{dirname as Gs,resolve as Yt}from"node:path";import{fileURLToPath as qs}from"node:url";import{randomUUID as mt}from"node:crypto";var K="0.1.28";function W(){return new Date().toISOString()}function w(e,t=2){return String(e).padStart(t,"0")}function ie(e){let t=e>=0?"+":"-",n=Math.abs(e);return`${t}${w(Math.floor(n/60))}:${w(n%60)}`}function En(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${w(e.getMonth()+1)}-${w(e.getDate())}`,`T${w(e.getHours())}:${w(e.getMinutes())}:${w(e.getSeconds())}.${w(e.getMilliseconds(),3)}`,ie(t)].join("")}function In(e,t){let n=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"}),r={};for(let s of n.formatToParts(e))s.type!=="literal"&&(r[s.type]=Number(s.value));return r}function xn(e,t){let n=In(e,t),r=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,e.getMilliseconds()),s=Math.round((r-e.getTime())/6e4);return[`${n.year}-${w(n.month)}-${w(n.day)}`,`T${w(n.hour)}:${w(n.minute)}:${w(n.second)}.${w(e.getMilliseconds(),3)}`,ie(s)].join("")}function On(e=new Date){let t=a(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return xn(e,t)}catch{return En(e)}}function c(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function a(e){return String(e??"").trim()}function T(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)?n:t}function I(e){return Array.isArray(e)?e.map(String):[]}var Cn="[redacted]",se=/(authorization|api[_-]?key|credential|password|secret|token)/i;function J(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]=J(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=>J(i,t));return t.delete(e),s}let n={},r=se.test(a(e.name||e.key));for(let[s,i]of Object.entries(e))n[s]=se.test(s)||r&&s.toLowerCase()==="value"?Cn:J(i,t);return t.delete(e),n}function oe(e,t=4e3){let n=JSON.stringify(J(e))??String(e);return!Number.isFinite(t)||n.length<=t?n:`${n.slice(0,t)}...`}function p(e,t,n,r={}){let s={ts:On(),level:e,module:t,msg:n,...c(r)?J(r):{}};console.error(JSON.stringify(s))}function nt(e){return Array.isArray(e)?e.map(t=>c(t)?t.type==="text"?a(t.text):t.type==="file"?a(t.uri):t.type==="image"?a(t.uri):"":"").filter(Boolean).join(`
3
- `):""}var rt=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,n){let r=nt(t.prompt);return n({sessionId:t.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r?`Echo runtime received: ${r}`:"Echo runtime received an empty prompt."}}}),{stopReason:"end_turn"}}async sessionCancel(){return{ok:!0}}};import{spawn as An}from"node:child_process";var V="2.0",Nn=3e4;function Mn(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:a(e?.message)||String(e),data:c(e?.data)?e.data:void 0}}function Un(e){if(!c(e))return new Error(String(e||"runtime error"));let t=a(e.message)||"runtime error",n="data"in e?oe(e.data,4e3):"",r=new Error(n?`${t}; data=${n}`:t);return r.rpcCode=e.code,r.data=e.data,r}function bn(e){return c(e)&&"id"in e&&!("method"in e)}function kn(e){return c(e)&&typeof e.method=="string"&&"id"in e}function Ln(e){return c(e)&&typeof e.method=="string"&&!("id"in e)}var st=class{constructor({command:t,args:n=[],cwd:r,env:s,label:i,framing:o="line",detached:u=!0}){this.command=t,this.args=Array.isArray(n)?n.map(String):[],this.cwd=r||process.cwd(),this.env={...process.env,...c(s)?s:{}},this.label=i||t,this.framing=o==="content-length"?"content-length":"line",this.detached=u!==!1,this.child=null,this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stopPromise=null,this.lineBuffer="",this.headerBuffer=Buffer.alloc(0),this.seq=0,this.pending=new Map,this.notificationHandlers=new Map,this.requestHandlers=new Map,this.exitHandlers=new Set}async start({initialize:t=!0,initializeParams:n={}}={}){this.child&&!this.exited||(this.exited=!1,this.exitCode=null,this.exitSignal=null,this.child=An(this.command,this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"],detached:this.detached}),this.child.stdout.on("data",r=>this.onStdout(r)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",r=>{let s=r.trimEnd();s&&p("debug","runtime.stderr","runtime stderr",{target:this.label,text:s})}),this.child.on("exit",(r,s)=>this.handleExit(r,s)),this.child.on("error",r=>this.rejectAll(r)),t&&await this.call("initialize",{protocolVersion:1,clientCapabilities:{},...n}).catch(r=>{throw Object.assign(new Error(`runtime initialize failed: ${r.message}`),{code:"RUNTIME_INITIALIZE_FAILED"})}))}onStdout(t){if(this.framing==="content-length"){this.onContentLengthData(Buffer.isBuffer(t)?t:Buffer.from(t));return}this.onLineData(t.toString("utf8"))}onLineData(t){this.lineBuffer+=t;let n=this.lineBuffer.split(/\r?\n/);this.lineBuffer=n.pop()||"";for(let r of n){let s=r.trim();s&&this.dispatchRaw(s)}}onContentLengthData(t){for(this.headerBuffer=Buffer.concat([this.headerBuffer,t]);this.headerBuffer.length>0;){let n=this.headerBuffer.indexOf(`\r
2
+ import{spawn as Ai}from"node:child_process";import{closeSync as Ni,existsSync as kn,mkdirSync as Mi,openSync as Ui,readFileSync as ce,rmSync as bi,statSync as Cn,writeFileSync as Ln}from"node:fs";import{dirname as ki,resolve as de}from"node:path";import{fileURLToPath as Li}from"node:url";import{createHash as Ns,randomUUID as Rt}from"node:crypto";var z="0.1.29";function Q(){return new Date().toISOString()}function x(e,t=2){return String(e).padStart(t,"0")}function ye(e){let t=e>=0?"+":"-",n=Math.abs(e);return`${t}${x(Math.floor(n/60))}:${x(n%60)}`}function Bn(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${x(e.getMonth()+1)}-${x(e.getDate())}`,`T${x(e.getHours())}:${x(e.getMinutes())}:${x(e.getSeconds())}.${x(e.getMilliseconds(),3)}`,ye(t)].join("")}function Kn(e,t){let n=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"}),r={};for(let s of n.formatToParts(e))s.type!=="literal"&&(r[s.type]=Number(s.value));return r}function qn(e,t){let n=Kn(e,t),r=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,e.getMilliseconds()),s=Math.round((r-e.getTime())/6e4);return[`${n.year}-${x(n.month)}-${x(n.day)}`,`T${x(n.hour)}:${x(n.minute)}:${x(n.second)}.${x(e.getMilliseconds(),3)}`,ye(s)].join("")}function Gn(e=new Date){let t=a(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return qn(e,t)}catch{return Bn(e)}}function c(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function a(e){return String(e??"").trim()}function S(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)?n:t}function N(e){return Array.isArray(e)?e.map(String):[]}var zn="[redacted]",Te=/(authorization|api[_-]?key|credential|password|secret|token)/i;function v(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]=v(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=>v(i,t));return t.delete(e),s}let n={},r=Te.test(a(e.name||e.key));for(let[s,i]of Object.entries(e))n[s]=Te.test(s)||r&&s.toLowerCase()==="value"?zn:v(i,t);return t.delete(e),n}function Se(e,t=4e3){let n=JSON.stringify(v(e))??String(e);return!Number.isFinite(t)||n.length<=t?n:`${n.slice(0,t)}...`}function m(e,t,n,r={}){let s={ts:Gn(),level:e,module:t,msg:n,...c(r)?v(r):{}};console.error(JSON.stringify(s))}function ot(e){return Array.isArray(e)?e.map(t=>c(t)?t.type==="text"?a(t.text):t.type==="file"?a(t.uri):t.type==="image"?a(t.uri):"":"").filter(Boolean).join(`
3
+ `):""}var at=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,n){let r=ot(t.prompt);return n({sessionId:t.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r?`Echo runtime received: ${r}`:"Echo runtime received an empty prompt."}}}),{stopReason:"end_turn"}}async sessionCancel(){return{ok:!0}}};import{spawn as Jn}from"node:child_process";var tt="2.0",Wn=3e4;function Vn(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:a(e?.message)||String(e),data:c(e?.data)?e.data:void 0}}function Xn(e){if(!c(e))return new Error(String(e||"runtime error"));let t=a(e.message)||"runtime error",n="data"in e?Se(e.data,4e3):"",r=new Error(n?`${t}; data=${n}`:t);return r.rpcCode=e.code,r.data=e.data,r}function Yn(e){return c(e)&&"id"in e&&!("method"in e)}function Zn(e){return c(e)&&typeof e.method=="string"&&"id"in e}function Qn(e){return c(e)&&typeof e.method=="string"&&!("id"in e)}var ct=class{constructor({command:t,args:n=[],cwd:r,env:s,label:i,framing:o="line",detached:u=!0}){this.command=t,this.args=Array.isArray(n)?n.map(String):[],this.cwd=r||process.cwd(),this.env={...process.env,...c(s)?s:{}},this.label=i||t,this.framing=o==="content-length"?"content-length":"line",this.detached=u!==!1,this.child=null,this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stopPromise=null,this.lineBuffer="",this.headerBuffer=Buffer.alloc(0),this.seq=0,this.pending=new Map,this.notificationHandlers=new Map,this.requestHandlers=new Map,this.exitHandlers=new Set}async start({initialize:t=!0,initializeParams:n={}}={}){this.child&&!this.exited||(this.exited=!1,this.exitCode=null,this.exitSignal=null,this.child=Jn(this.command,this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"],detached:this.detached}),this.child.stdout.on("data",r=>this.onStdout(r)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",r=>{let s=r.trimEnd();s&&m("debug","runtime.stderr","runtime stderr",{target:this.label,text:s})}),this.child.on("exit",(r,s)=>this.handleExit(r,s)),this.child.on("error",r=>this.rejectAll(r)),t&&await this.call("initialize",{protocolVersion:1,clientCapabilities:{},...n}).catch(r=>{throw Object.assign(new Error(`runtime initialize failed: ${r.message}`),{code:"RUNTIME_INITIALIZE_FAILED"})}))}onStdout(t){if(this.framing==="content-length"){this.onContentLengthData(Buffer.isBuffer(t)?t:Buffer.from(t));return}this.onLineData(t.toString("utf8"))}onLineData(t){this.lineBuffer+=t;let n=this.lineBuffer.split(/\r?\n/);this.lineBuffer=n.pop()||"";for(let r of n){let s=r.trim();s&&this.dispatchRaw(s)}}onContentLengthData(t){for(this.headerBuffer=Buffer.concat([this.headerBuffer,t]);this.headerBuffer.length>0;){let n=this.headerBuffer.indexOf(`\r
4
4
  \r
5
- `);if(n<0)return;let s=this.headerBuffer.subarray(0,n).toString("utf8").match(/content-length:\s*(\d+)/i);if(!s){p("warn","runtime.protocol","missing Content-Length header",{target:this.label}),this.headerBuffer=Buffer.alloc(0);return}let i=Number.parseInt(s[1],10),o=n+4,u=o+i;if(this.headerBuffer.length<u)return;let l=this.headerBuffer.subarray(o,u).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(u),this.dispatchRaw(l)}}dispatchRaw(t){let n;try{n=JSON.parse(t)}catch(r){p("warn","runtime.protocol","invalid JSON frame",{target:this.label,error:String(r)});return}this.dispatch(n)}dispatch(t){if(bn(t)){this.resolveResponse(t);return}if(kn(t)){this.handleRequest(t);return}Ln(t)&&this.handleNotification(t)}resolveResponse(t){let n=String(t.id),r=this.pending.get(n);r&&(clearTimeout(r.timer),this.pending.delete(n),t.error?(p("warn","runtime.protocol","runtime rpc error",{target:this.label,method:r.method,requestId:n,error:t.error}),r.reject(Un(t.error))):r.resolve(t.result))}async handleRequest(t){let n=this.requestHandlers.get(t.method);if(!n){this.writeFrame({jsonrpc:V,id:t.id,error:{code:-32601,message:`method not found: ${t.method}`}});return}try{let r=await n(c(t.params)?t.params:{},t);this.writeFrame({jsonrpc:V,id:t.id,result:r??{}})}catch(r){this.writeFrame({jsonrpc:V,id:t.id,error:Mn(r)})}}handleNotification(t){let n=this.notificationHandlers.get(t.method);if(n)for(let r of n)r(c(t.params)?t.params:{},t)}call(t,n={},r=Nn){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:V,id:s,method:t,params:n};return new Promise((o,u)=>{let l=setTimeout(()=>{this.pending.delete(s),u(new Error(`${t} timed out after ${r}ms`))},r);this.pending.set(s,{resolve:o,reject:u,timer:l,method:t}),this.writeFrame(i,d=>{d&&(clearTimeout(l),this.pending.delete(s),u(d))})})}notify(t,n={}){this.writeFrame({jsonrpc:V,method:t,params:n})}writeFrame(t,n){if(!this.child?.stdin||this.exited){n?.(new Error("runtime process is not running"));return}let r=JSON.stringify(t),s=this.framing==="content-length"?`Content-Length: ${Buffer.byteLength(r,"utf8")}\r
5
+ `);if(n<0)return;let s=this.headerBuffer.subarray(0,n).toString("utf8").match(/content-length:\s*(\d+)/i);if(!s){m("warn","runtime.protocol","missing Content-Length header",{target:this.label}),this.headerBuffer=Buffer.alloc(0);return}let i=Number.parseInt(s[1],10),o=n+4,u=o+i;if(this.headerBuffer.length<u)return;let l=this.headerBuffer.subarray(o,u).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(u),this.dispatchRaw(l)}}dispatchRaw(t){let n;try{n=JSON.parse(t)}catch(r){m("warn","runtime.protocol","invalid JSON frame",{target:this.label,error:String(r)});return}this.dispatch(n)}dispatch(t){if(Yn(t)){this.resolveResponse(t);return}if(Zn(t)){this.handleRequest(t);return}Qn(t)&&this.handleNotification(t)}resolveResponse(t){let n=String(t.id),r=this.pending.get(n);r&&(clearTimeout(r.timer),this.pending.delete(n),t.error?(m("warn","runtime.protocol","runtime rpc error",{target:this.label,method:r.method,requestId:n,error:t.error}),r.reject(Xn(t.error))):r.resolve(t.result))}async handleRequest(t){let n=this.requestHandlers.get(t.method);if(!n){this.writeFrame({jsonrpc:tt,id:t.id,error:{code:-32601,message:`method not found: ${t.method}`}});return}try{let r=await n(c(t.params)?t.params:{},t);this.writeFrame({jsonrpc:tt,id:t.id,result:r??{}})}catch(r){this.writeFrame({jsonrpc:tt,id:t.id,error:Vn(r)})}}handleNotification(t){let n=this.notificationHandlers.get(t.method);if(n)for(let r of n)r(c(t.params)?t.params:{},t)}call(t,n={},r=Wn){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:tt,id:s,method:t,params:n};return new Promise((o,u)=>{let l=setTimeout(()=>{this.pending.delete(s),u(new Error(`${t} timed out after ${r}ms`))},r);this.pending.set(s,{resolve:o,reject:u,timer:l,method:t}),this.writeFrame(i,d=>{d&&(clearTimeout(l),this.pending.delete(s),u(d))})})}notify(t,n={}){this.writeFrame({jsonrpc:tt,method:t,params:n})}writeFrame(t,n){if(!this.child?.stdin||this.exited){n?.(new Error("runtime process is not running"));return}let r=JSON.stringify(t),s=this.framing==="content-length"?`Content-Length: ${Buffer.byteLength(r,"utf8")}\r
6
6
  \r
7
7
  ${r}`:`${r}
8
- `;this.child.stdin.write(s,n)}onNotification(t,n){let r=this.notificationHandlers.get(t)||new Set;return r.add(n),this.notificationHandlers.set(t,r),()=>{r.delete(n),r.size===0&&this.notificationHandlers.delete(t)}}onRequest(t,n){return this.requestHandlers.set(t,n),()=>this.requestHandlers.delete(t)}onExit(t){return this.exitHandlers.add(t),()=>this.exitHandlers.delete(t)}rejectAll(t){for(let n of this.pending.values())clearTimeout(n.timer),n.reject(t);this.pending.clear()}handleExit(t,n){this.exited=!0,this.exitCode=t,this.exitSignal=n,this.rejectAll(new Error(`runtime exited before response (${t}/${n})`));for(let r of this.exitHandlers)r(t,n)}async waitForExit(t=5e3){return!this.child||this.exited?!0:await new Promise(n=>{let r=setTimeout(()=>{s(),n(!1)},t);r.unref?.();let s=()=>{clearTimeout(r),this.exitHandlers.delete(i)},i=()=>{s(),n(!0)};this.exitHandlers.add(i),this.exited&&i()})}signal(t){if(!this.child||this.exited)return!1;let n=this.child.pid;if(!n)return!1;try{return this.detached&&process.platform!=="win32"?process.kill(-n,t):this.child.kill(t),!0}catch(r){if(r?.code==="ESRCH")return this.exited=!0,!1;try{return this.child.kill(t),!0}catch(s){return s?.code!=="ESRCH"&&p("warn","runtime","runtime signal failed",{target:this.label,pid:n,signal:t,error:String(s)}),!1}}}async stop(t="stop",{termTimeoutMs:n=5e3,killTimeoutMs:r=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;p("info","runtime","stopping runtime",{target:this.label,reason:t,pid:s}),this.rejectAll(new Error(`runtime stopped: ${t}`)),this.signal("SIGTERM"),!await this.waitForExit(n)&&this.child&&!this.exited&&(p("warn","runtime","runtime did not exit after SIGTERM; force killing",{target:this.label,reason:t,pid:s}),this.signal("SIGKILL"),await this.waitForExit(r))})();try{await this.stopPromise}finally{this.stopPromise=null}}}};import{randomUUID as ue}from"node:crypto";import{existsSync as Pn,readFileSync as Dn,realpathSync as ae,statSync as Fn}from"node:fs";import{basename as le,extname as de,isAbsolute as $n,relative as Hn}from"node:path";var vn=25*1024*1024;function fe(e,t=""){let n=a(t);if(n)return n;let r=de(a(e)).toLowerCase();return r===".jpg"||r===".jpeg"?"image/jpeg":r===".webp"?"image/webp":r===".gif"?"image/gif":"image/png"}function pe(e,t){let n=typeof e=="string"?e.trim():"";return!n||n==="<omitted>"?"":n.startsWith("data:")?n:`data:${t};base64,${n.replace(/\s+/g,"")}`}function it(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function Bn(e,t){let n=Hn(t,e);return n===""||!!n&&!n.startsWith("..")&&!$n(n)}function Kn(e,t){let n=a(e);if(!n||!Pn(n))return"";try{let r=ae(n);for(let s of t)try{let i=ae(s);if(Bn(r,i))return r}catch{}}catch{return""}return""}function Et(e,t,n={}){let r=a(e);return!r||r.startsWith("data:")||/^https?:\/\//i.test(r)?r:zn(r,t,n)}function zn(e,t,n={}){let r=[...it(n.trustedFileRoots),...it(n.trustedFileRoot),...it(n.artifactRoots),...it(n.artifactRoot)],s=Kn(e,r);if(!s)return"";try{let i=Fn(s);return!i.isFile()||i.size<=0||i.size>vn?"":`data:${t};base64,${Dn(s).toString("base64")}`}catch{return""}}function S(...e){for(let t of e){let n=a(t);if(n)return n}return""}function jn(e,t,n,r){let s=n.toLowerCase();if(s==="image"||s==="picture")return!0;let i=S(r,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=de(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function xt(e,t={}){let{source:n="runtime_image_generation_event"}=t;if(!c(e))return null;let r=c(e.payload)?e.payload:{},s=a(e.type),i=a(r.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let o=S(r.call_id,r.id),u=S(r.saved_path,r.savedPath),l=S(r.revised_prompt,r.revisedPrompt),d=fe(u,r.mimeType||r.mime_type),f=pe(r.result,d)||Et(u,d,t);if(!f)return null;let m=f.startsWith("data:")?f:"",g=u?le(u):`${o||ue()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:g||"Generated image",summary:l||"Generated image",content:{prompt:l||void 0,dataUrl:m||void 0,imageUrl:f,previewUrl:f,fileUrl:f,mimeType:d},dataUrl:m||void 0,previewUrl:f,fileUrl:f,metadata:{source:n,eventType:i,callId:o||void 0,savedPath:u||void 0,filename:g,mimeType:d,revisedPrompt:l||void 0}}}function Gn(e){let t=c(e)?e:{},n=[];for(let r of["_artifacts","artifacts"]){let s=t[r];Array.isArray(s)&&n.push(...s)}for(let r of["_artifact","artifact"]){let s=t[r];c(s)&&n.push(s)}return n}function qn(e,t={}){let{source:n="runtime_artifact"}=t,r=c(e)?e:{};if(!Object.keys(r).length)return null;let s=c(r.content)?{...r.content}:{},i=c(r.metadata)?{...r.metadata}:{},o=S(r.saved_path,r.savedPath,s.saved_path,s.savedPath,i.savedPath),u=S(r.mimeType,r.mime_type,s.mimeType,s.mime_type,i.mimeType),l=S(r.artifactType,r.artifact_type,r.type,r.kind,s.type,o?"image":"file"),d=jn(r,s,l,o),f=d?fe(o,u):u;if(d){let x=S(r.dataUrl,s.dataUrl),A=x.startsWith("data:")?x:"",b=S(r.imageUrl,r.previewUrl,r.fileUrl,r.downloadUrl,r.url,r.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),_=pe(r.result??s.result,f)||A||Et(o,f,t)||Et(b,f,t);_&&(_.startsWith("data:")&&(s.dataUrl||=_),s.imageUrl||=_,s.previewUrl||=_,s.fileUrl||=_,f&&(s.mimeType||=f))}for(let[x,A]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let b=r[x];b!=null&&b!==""&&!(A in s)&&(s[A]=b)}let m=S(r.fileUrl,r.downloadUrl,r.imageUrl,r.dataUrl,r.url,r.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),g=S(r.previewUrl,r.imageUrl,r.dataUrl,r.url,r.fileUrl,r.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),h=S(r.dataUrl,s.dataUrl,m.startsWith("data:")?m:"",g.startsWith("data:")?g:""),y=S(r.filename,i.filename,o?le(o):""),U=S(r.fieldKey,r.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...r,artifactType:l,type:r.type||l,fieldKey:U,title:S(r.title,y,"Runtime artifact"),summary:S(r.summary,s.prompt,r.title,y,"Runtime artifact"),content:s,dataUrl:h||void 0,fileUrl:m||void 0,previewUrl:g||void 0,metadata:{...i,source:S(i.source,n),savedPath:o||i.savedPath,filename:y||i.filename,mimeType:f||i.mimeType}}}function ot(e,t){if(!t||!e)return;let n=c(t.metadata)?t.metadata:{},r=S(n.savedPath,n.callId,t.previewUrl,t.fileUrl)||ue(),s=e.get(r);if(!s){e.set(r,t);return}s.content={...c(s.content)?s.content:{},...c(t.content)?t.content:{}},s.metadata={...c(s.metadata)?s.metadata:{},...n},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 It(e,t,n={}){for(let r of Gn(e))ot(t,qn(r,n))}function Ot(e){if(!c(e)||!c(e.payload))return c(e)?e:{value:e};let t=a(e.payload.type);if(t!=="image_generation_end"&&t!=="image_generation_call")return e;let n={...e.payload};return typeof n.result=="string"&&n.result&&(n.result="<omitted>",n.resultLength=e.payload.result.length),{...e,payload:n}}function ce(e,t,n){if(!c(e))return e;let r=c(e.event)?e.event:null;return r?(ot(t,xt(r,n)),{...e,event:Ot(r)}):e}function me(e,t,n={}){if(!c(e))return e;It(e,t,n);let r=ce(e,t,n),s=c(r.update)?ce(r.update,t,n):null;return s&&s!==r.update&&(r={...r,update:s}),r}function he(e,t,n={}){let r=c(e)?{...e}:{};It(r,t,n),It(c(r.output)?r.output:{},t,n);let s=[...t?.values?.()||[]];return s.length&&(r._artifacts=s),delete r.artifacts,r}var z=class{constructor(t,n,r={},s={}){this.agent=t,this.target=n,this.callbacks=r,this.options=s,this.proc=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`);this.proc=new st({command:t,args:I(this.target.args),cwd:a(this.target.cwd)||this.agent.workspace||process.cwd(),env:c(this.target.env)?this.target.env:{},label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:a(this.target.framing||"line")}),this.proc.onRequest("session/request_permission",n=>this.handlePermissionRequest(n)),this.proc.onRequest("session/requestPermission",n=>this.handlePermissionRequest(n)),await this.proc.start({initialize:this.target.initialize!==!1,initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:K},...c(this.target.initializeParams)?this.target.initializeParams:{}}})}async sessionNew(t={}){return await this.ensureStarted(),this.proc.call("session/new",this.sessionNewParams(t))}sessionNewParams(t={}){let n=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return{...t,mcpServers:n}}async sessionPrompt(t,n){await this.ensureStarted();let r=a(t.sessionId),s=new Map,i=this.artifactOptions(),o=this.proc.onNotification("session/update",l=>{let d=a(l.sessionId);(!d||d===r)&&n(me(l,s,i))}),u=async l=>this.callbacks.onPermissionRequest?.({agent:this.agent,runtimeSessionId:r,request:l,emitUpdate:n})||{outcome:"denied",reason:"permission handler is not configured"};r&&this.permissionHandlers.set(r,u),this.permissionHandlers.set("*",u);try{let l=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return he(l,s,i)}finally{o(),r&&this.permissionHandlers.delete(r),this.permissionHandlers.delete("*")}}async sessionCancel(t){return await this.ensureStarted(),this.proc.call("session/cancel",t,5e3).catch(()=>({ok:!0}))}async handlePermissionRequest(t){let n=a(t.sessionId),r=this.permissionHandlers.get(n)||this.permissionHandlers.get("*");return r?r(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=c(this.target.env)?this.target.env:{};return{source:this.artifactSource(),trustedFileRoots:[a(this.target.artifactRoot),a(this.target.artifactDir),a(this.target.runtimeArtifactRoot),a(t.ORCHA_RUNTIME_ARTIFACT_DIR),...I(this.target.trustedArtifactRoots),...I(this.target.trustedFileRoots),...I(this.target.artifactRoots),...I(this.target.artifactFileRoots)].filter(Boolean)}}async stop(t){await this.proc?.stop(t)}};function Jn(e){let t=c(e.metadata)?e.metadata:{};return a(t.agentCode)}function Wn(e,t){let n=Jn(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var at=class extends z{constructor(t,n,r,s={},i={}){let o=a(r).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",u=a(n.command)||"openclaw",l=Array.isArray(n.args)?n.args.map(String):[],d=l.length>0?l:["acp","--session",Wn(t,o)];super(t,{...n,command:u,args:d},s,i)}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as Vn}from"node:child_process";import{randomUUID as X}from"node:crypto";import{existsSync as Se,mkdirSync as Xn,readdirSync as Re,readFileSync as we,realpathSync as dt,rmSync as Yn,rmdirSync as Zn,statSync as Qn,unlinkSync as tr}from"node:fs";import{homedir as er,tmpdir as Ee}from"node:os";import{basename as Ie,dirname as nr,join as N,resolve as ge}from"node:path";var rr=36e5,sr=5e3,ir=2*60*1e3,or=2*60*1e3,ar=12,cr=1e3,ur=1500,ct=24*60*60*1e3,Y=new Set(["final_answer","final","complete","completed","done"]),lr=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"]);function ut(e,t){try{e.kill(t)}catch{}}function C(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>C(t)).join("");if(!c(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let n=C(e[t]);if(n)return n}return""}function xe(e){if(!c(e))return"";let t=c(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 C(t.content)||C(t.message);let n=C(e.delta)||C(e.text)||C(e.content);if(n)return n;let r=c(e.item)?e.item:{};return a(r.role)==="assistant"||a(r.type)==="message"?C(r.content)||C(r.text)||C(r.message):""}function Oe(e,t={}){return xt(e,{source:"codex_cli_image_generation",...t})}function Ce(e,t){ot(e.artifacts,t)}function Ae(e){let t=Ot(e);if(!De(e))return t;let n=c(e.payload)?e.payload:{};return{type:e.type,...e.timestamp?{timestamp:e.timestamp}:{},payload:Object.fromEntries(["type","name","namespace","title","call_id","callId","id","status","phase","stage"].filter(r=>n[r]!==void 0&&n[r]!==null&&n[r]!=="").map(r=>[r,n[r]]))}}function Mt(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type);if(n==="event_msg"&&r==="task_complete")return!0;let s=a(t.phase||t.status||t.stage).toLowerCase();return n==="event_msg"&&r==="agent_message"||n==="response_item"&&r==="message"&&a(t.role)==="assistant"?Y.has(s):!1}function _e(e){return c(e)?a(e.phase||e.status||e.stage).toLowerCase():""}function dr(e){if(!c(e)||Mt(e))return!1;let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type),s=_e(t);if(n==="event_msg"&&r==="agent_message"||n==="response_item"&&r==="message"&&a(t.role)==="assistant")return!!(s&&!Y.has(s));let i=c(e.item)?e.item:{},o=_e(i);return a(i.role)==="assistant"||a(i.type)==="message"?!!(o&&!Y.has(o)):!1}function fr(e,t,n){return n.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:n.captureLastMessage===!0?!0:Ie(e)==="codex"}function pr(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:Ie(e)==="codex"}function Ne(e){return Math.max(20,T(e.codexTranscriptPollMs||e.transcriptPollMs,cr))}function mr(e){return Math.max(0,T(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,ur))}function ft(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 Ut(e){let t=c(e?.metadata)?e.metadata:{};return c(t._runtimeBridge)?t._runtimeBridge:{}}function Ct(e){return a(Ut(e).promptKind).toLowerCase()}function hr(e,t){for(let n of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let r=ft(n);if(r!=null)return r}return Ct(t)==="chat"}function gr(e,t){let n=Ut(e);for(let s of[n.emitThoughtChunks,n.streamThoughts]){let i=ft(s);if(i!=null)return i}let r=Ct(e);if(r&&r!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=ft(s);if(i!=null)return i}return Ct(e)==="chat"}function _r(e){let t=Ut(e);for(let n of[t.finalTextOnly,t.finalOutputOnly]){let r=ft(n);if(r!=null)return r}return null}function Tr(e,t){let n=_r(e);return n??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function yr(e,t){return!e.finalTextOnly||t}function Me(e,t,n,r,s=r){return!r||e.emittedTexts.has(s)?!1:(e.emittedTexts.add(s),n({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}}}),!0)}function Ue(e,t,n,r){return!r||e.emittedThoughtTexts.has(r)?!1:(e.emittedThoughtTexts.add(r),n({sessionId:t,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:r}}}),!0)}function Sr(e,t,n,r=new Set){return{target:e,promptText:t,startedAtMs:n,baselinePaths:r,matchedPath:"",disabled:!1,processedLines:new Map}}function Rr(e,t){let n=c(e.env)?e.env:{},r=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||n.ORCHA_RUNTIME_ARTIFACT_DIR)||N(Ee(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||X(),i=N(r,s),o=N(i,X());return Xn(o,{recursive:!0}),{root:o,realRoot:dt(o),sessionRoot:i,realSessionRoot:dt(i)}}function be(e){return a(c(e)?e.root:e)}function Te(e){let t=be(e),n=a(c(e)?e.sessionRoot:nr(t)),r=a(c(e)?e.realSessionRoot:"");if(n)try{if(r&&dt(n)!==r)return;Zn(n)}catch{}}function wr(e,t={}){let n=be(e),r=a(c(e)?e.realRoot:"");if(n){try{if(r&&dt(n)!==r){p("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:n});return}}catch{Te(e);return}try{Yn(n,{recursive:!0,force:!0})}catch(s){p("warn","runtime.cli","runtime artifact directory cleanup failed",{...t,artifactRoot:n,error:String(s?.message||s)});return}Te(e)}}function Er(e,t){return{trustedFileRoots:[t,...I(e.trustedArtifactRoots),...I(e.trustedFileRoots),...I(e.artifactRoots),...I(e.artifactFileRoots)].filter(Boolean)}}function ke(e){let t=a(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let n=c(e.env)?e.env:{},r=a(e.codexHome||n.CODEX_HOME||process.env.CODEX_HOME)||N(er(),".codex");return N(r,"sessions")}function Ir(e,t){let n=new Date(t),r=String(n.getFullYear()),s=String(n.getMonth()+1).padStart(2,"0"),i=String(n.getDate()).padStart(2,"0");return N(e,r,s,i)}function Le(e,t,n){let r=new Set;for(let s of[t-ct,t,t+ct,n-ct,n,n+ct])r.add(Ir(e,s));return[...r].filter(s=>Se(s))}function xr(e,t,n){let r=ke(e),s=t-ir,i=n+or,o=[];for(let u of Le(r,t,n)){let l=[];try{l=Re(u)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=N(u,d);try{let m=Qn(f);if(!m.isFile()||m.mtimeMs<s||m.mtimeMs>i)continue;o.push({path:f,mtimeMs:m.mtimeMs})}catch{}}}return o.sort((u,l)=>l.mtimeMs-u.mtimeMs).slice(0,ar)}function Or(e,t,n=t){let r=ke(e),s=new Set;for(let i of Le(r,t,n)){let o=[];try{o=Re(i)}catch{continue}for(let u of o)u.endsWith(".jsonl")&&s.add(N(i,u))}return s}function At(e,t,n=0){if(!(n>8||e===null||e===void 0)){if(typeof e=="string"){e&&t.push(e);return}if(Array.isArray(e)){for(let r of e)At(r,t,n+1);return}if(c(e))for(let r of["payload","item","text","delta","output_text","content","message","output","input","prompt","last_agent_message","revised_prompt"])r in e&&At(e[r],t,n+1)}}function Pe(e){return a(e).replace(/\s+/g," ")}function Cr(e){let t=Pe(e);if(!t)return[];if(t.length<=200)return[t];let n=160,r=[0,Math.floor((t.length-n)/2),t.length-n],s=new Set,i=[];for(let o of r){let u=t.slice(Math.max(0,o),Math.max(0,o)+n).trim();u.length>=40&&!s.has(u)&&(s.add(u),i.push(u))}return i}function Ar(e,t){let n=Cr(t);if(!n.length)return!1;let r=[];for(let i of e)At(i,r);let s=Pe(r.join(" "));return n.every(i=>s.includes(i))}function Nr(e){return e.find(t=>c(t)&&a(t.type)==="session_meta"&&c(t.payload))||null}function Mr(e){let t=c(e?.payload)?e.payload:{},n=a(e?.timestamp||t.timestamp),r=Date.parse(n);return Number.isFinite(r)?r:Number.NaN}function Ur(e){let t=a(e.originator),n=a(e.source);if(t!=="codex_exec"&&n!=="exec"||a(e.parent_thread_id))return!1;let r=a(e.thread_source);if(r&&r!=="user")return!1;let s=a(e.session_id),i=a(e.id);return!(s&&i&&s!==i)}function br(e,t,n){if(!Ar(e,t.promptText))return!1;let r=Nr(e);if(!r)return!1;let s=r.payload;if(!Ur(s))return!1;let i=Mr(r);if(!Number.isFinite(i)||i<t.startedAtMs-5e3||i>n+5e3)return!1;let o=a(t.target.cwd),u=a(s.cwd);return!(o&&u&&ge(o)!==ge(u))}function ye(e){try{return Lr(we(e,"utf8"))}catch{return null}}function kr(e,t,n){if(!e||e.disabled)return null;if(e.matchedPath){let s=ye(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let r=[];for(let s of xr(e.target,e.startedAtMs,n)){if(e.baselinePaths.has(s.path))continue;let i=ye(s.path);!i||!br(i,e,n)||r.push({path:s.path,events:i})}return r.length!==1?(r.length>1&&(e.disabled=!0,p("warn","runtime.cli","codex transcript fallback disabled; multiple matching transcripts",{target:e.target.targetCode,sessionId:t,transcriptCount:r.length})),null):(e.matchedPath=r[0].path,p("info","runtime.cli","codex transcript stream attached",{target:e.target.targetCode,sessionId:t}),r[0])}function Lr(e){let t=[];for(let n of e.split(/\r?\n/)){let r=n.trim();if(r)try{t.push(JSON.parse(r))}catch{}}return t}function Pr(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type);return n==="event_msg"&&r==="image_generation_end"||n==="response_item"&&r==="image_generation_call"}function De(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{};return a(e.type)==="response_item"&&lr.has(a(t.type))}function Dr(e,t,n,r){let s=xe(e),i=Mt(e),o=0,u=0,l=0;if(s&&!i&&t.emitThoughtChunks&&Ue(t,n,r,s)&&(l=1),s&&i){let d=t.emittedTexts.size?`
8
+ `;this.child.stdin.write(s,n)}onNotification(t,n){let r=this.notificationHandlers.get(t)||new Set;return r.add(n),this.notificationHandlers.set(t,r),()=>{r.delete(n),r.size===0&&this.notificationHandlers.delete(t)}}onRequest(t,n){return this.requestHandlers.set(t,n),()=>this.requestHandlers.delete(t)}onExit(t){return this.exitHandlers.add(t),()=>this.exitHandlers.delete(t)}rejectAll(t){for(let n of this.pending.values())clearTimeout(n.timer),n.reject(t);this.pending.clear()}handleExit(t,n){this.exited=!0,this.exitCode=t,this.exitSignal=n,this.rejectAll(new Error(`runtime exited before response (${t}/${n})`));for(let r of this.exitHandlers)r(t,n)}async waitForExit(t=5e3){return!this.child||this.exited?!0:await new Promise(n=>{let r=setTimeout(()=>{s(),n(!1)},t);r.unref?.();let s=()=>{clearTimeout(r),this.exitHandlers.delete(i)},i=()=>{s(),n(!0)};this.exitHandlers.add(i),this.exited&&i()})}signal(t){if(!this.child||this.exited)return!1;let n=this.child.pid;if(!n)return!1;try{return this.detached&&process.platform!=="win32"?process.kill(-n,t):this.child.kill(t),!0}catch(r){if(r?.code==="ESRCH")return this.exited=!0,!1;try{return this.child.kill(t),!0}catch(s){return s?.code!=="ESRCH"&&m("warn","runtime","runtime signal failed",{target:this.label,pid:n,signal:t,error:String(s)}),!1}}}async stop(t="stop",{termTimeoutMs:n=5e3,killTimeoutMs:r=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;m("info","runtime","stopping runtime",{target:this.label,reason:t,pid:s}),this.rejectAll(new Error(`runtime stopped: ${t}`)),this.signal("SIGTERM"),!await this.waitForExit(n)&&this.child&&!this.exited&&(m("warn","runtime","runtime did not exit after SIGTERM; force killing",{target:this.label,reason:t,pid:s}),this.signal("SIGKILL"),await this.waitForExit(r))})();try{await this.stopPromise}finally{this.stopPromise=null}}}};import{randomUUID as Ee}from"node:crypto";import{existsSync as tr,readFileSync as er,realpathSync as we,statSync as nr}from"node:fs";import{basename as Oe,extname as Ie,isAbsolute as rr,relative as sr}from"node:path";var ir=25*1024*1024;function Ce(e,t=""){let n=a(t);if(n)return n;let r=Ie(a(e)).toLowerCase();return r===".jpg"||r===".jpeg"?"image/jpeg":r===".webp"?"image/webp":r===".gif"?"image/gif":"image/png"}function xe(e,t){let n=typeof e=="string"?e.trim():"";return!n||n==="<omitted>"?"":n.startsWith("data:")?n:`data:${t};base64,${n.replace(/\s+/g,"")}`}function ut(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function or(e,t){let n=sr(t,e);return n===""||!!n&&!n.startsWith("..")&&!rr(n)}function ar(e,t){let n=a(e);if(!n||!tr(n))return"";try{let r=we(n);for(let s of t)try{let i=we(s);if(or(r,i))return r}catch{}}catch{return""}return""}function Ut(e,t,n={}){let r=a(e);return!r||r.startsWith("data:")||/^https?:\/\//i.test(r)?r:cr(r,t,n)}function cr(e,t,n={}){let r=[...ut(n.trustedFileRoots),...ut(n.trustedFileRoot),...ut(n.artifactRoots),...ut(n.artifactRoot)],s=ar(e,r);if(!s)return"";try{let i=nr(s);return!i.isFile()||i.size<=0||i.size>ir?"":`data:${t};base64,${er(s).toString("base64")}`}catch{return""}}function O(...e){for(let t of e){let n=a(t);if(n)return n}return""}function ur(e,t,n,r){let s=n.toLowerCase();if(s==="image"||s==="picture")return!0;let i=O(r,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=Ie(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function kt(e,t={}){let{source:n="runtime_image_generation_event"}=t;if(!c(e))return null;let r=c(e.payload)?e.payload:{},s=a(e.type),i=a(r.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let o=O(r.call_id,r.id),u=O(r.saved_path,r.savedPath),l=O(r.revised_prompt,r.revisedPrompt),d=Ce(u,r.mimeType||r.mime_type),f=xe(r.result,d)||Ut(u,d,t);if(!f)return null;let p=f.startsWith("data:")?f:"",h=u?Oe(u):`${o||Ee()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:h||"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:n,eventType:i,callId:o||void 0,savedPath:u||void 0,filename:h,mimeType:d,revisedPrompt:l||void 0}}}function lr(e){let t=c(e)?e:{},n=[];for(let r of["_artifacts","artifacts"]){let s=t[r];Array.isArray(s)&&n.push(...s)}for(let r of["_artifact","artifact"]){let s=t[r];c(s)&&n.push(s)}return n}function dr(e,t={}){let{source:n="runtime_artifact"}=t,r=c(e)?e:{};if(!Object.keys(r).length)return null;let s=c(r.content)?{...r.content}:{},i=c(r.metadata)?{...r.metadata}:{},o=O(r.saved_path,r.savedPath,s.saved_path,s.savedPath,i.savedPath),u=O(r.mimeType,r.mime_type,s.mimeType,s.mime_type,i.mimeType),l=O(r.artifactType,r.artifact_type,r.type,r.kind,s.type,o?"image":"file"),d=ur(r,s,l,o),f=d?Ce(o,u):u;if(d){let _=O(r.dataUrl,s.dataUrl),T=_.startsWith("data:")?_:"",w=O(r.imageUrl,r.previewUrl,r.fileUrl,r.downloadUrl,r.url,r.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),E=xe(r.result??s.result,f)||T||Ut(o,f,t)||Ut(w,f,t);E&&(E.startsWith("data:")&&(s.dataUrl||=E),s.imageUrl||=E,s.previewUrl||=E,s.fileUrl||=E,f&&(s.mimeType||=f))}for(let[_,T]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let w=r[_];w!=null&&w!==""&&!(T in s)&&(s[T]=w)}let p=O(r.fileUrl,r.downloadUrl,r.imageUrl,r.dataUrl,r.url,r.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),h=O(r.previewUrl,r.imageUrl,r.dataUrl,r.url,r.fileUrl,r.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),g=O(r.dataUrl,s.dataUrl,p.startsWith("data:")?p:"",h.startsWith("data:")?h:""),I=O(r.filename,i.filename,o?Oe(o):""),q=O(r.fieldKey,r.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...r,artifactType:l,type:r.type||l,fieldKey:q,title:O(r.title,I,"Runtime artifact"),summary:O(r.summary,s.prompt,r.title,I,"Runtime artifact"),content:s,dataUrl:g||void 0,fileUrl:p||void 0,previewUrl:h||void 0,metadata:{...i,source:O(i.source,n),savedPath:o||i.savedPath,filename:I||i.filename,mimeType:f||i.mimeType}}}function lt(e,t){if(!t||!e)return;let n=c(t.metadata)?t.metadata:{},r=O(n.savedPath,n.callId,t.previewUrl,t.fileUrl)||Ee(),s=e.get(r);if(!s){e.set(r,t);return}s.content={...c(s.content)?s.content:{},...c(t.content)?t.content:{}},s.metadata={...c(s.metadata)?s.metadata:{},...n},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 bt(e,t,n={}){for(let r of lr(e))lt(t,dr(r,n))}function Lt(e){if(!c(e)||!c(e.payload))return c(e)?e:{value:e};let t=a(e.payload.type);if(t!=="image_generation_end"&&t!=="image_generation_call")return e;let n={...e.payload};return typeof n.result=="string"&&n.result&&(n.result="<omitted>",n.resultLength=e.payload.result.length),{...e,payload:n}}function Re(e,t,n){if(!c(e))return e;let r=c(e.event)?e.event:null;return r?(lt(t,kt(r,n)),{...e,event:Lt(r)}):e}function Ae(e,t,n={}){if(!c(e))return e;bt(e,t,n);let r=Re(e,t,n),s=c(r.update)?Re(r.update,t,n):null;return s&&s!==r.update&&(r={...r,update:s}),r}function Ne(e,t,n={}){let r=c(e)?{...e}:{};bt(r,t,n),bt(c(r.output)?r.output:{},t,n);let s=[...t?.values?.()||[]];return s.length&&(r._artifacts=s),delete r.artifacts,r}var J=class{constructor(t,n,r={},s={}){this.agent=t,this.target=n,this.callbacks=r,this.options=s,this.proc=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`);this.proc=new ct({command:t,args:N(this.target.args),cwd:a(this.target.cwd)||this.agent.workspace||process.cwd(),env:c(this.target.env)?this.target.env:{},label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:a(this.target.framing||"line")}),this.proc.onRequest("session/request_permission",n=>this.handlePermissionRequest(n)),this.proc.onRequest("session/requestPermission",n=>this.handlePermissionRequest(n)),await this.proc.start({initialize:this.target.initialize!==!1,initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:z},...c(this.target.initializeParams)?this.target.initializeParams:{}}})}async sessionNew(t={}){return await this.ensureStarted(),this.proc.call("session/new",this.sessionNewParams(t))}sessionNewParams(t={}){let n=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return{...t,mcpServers:n}}async sessionPrompt(t,n){await this.ensureStarted();let r=a(t.sessionId),s=new Map,i=this.artifactOptions(),o=this.proc.onNotification("session/update",l=>{let d=a(l.sessionId);(!d||d===r)&&n(Ae(l,s,i))}),u=async l=>this.callbacks.onPermissionRequest?.({agent:this.agent,runtimeSessionId:r,request:l,emitUpdate:n})||{outcome:"denied",reason:"permission handler is not configured"};r&&this.permissionHandlers.set(r,u),this.permissionHandlers.set("*",u);try{let l=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return Ne(l,s,i)}finally{o(),r&&this.permissionHandlers.delete(r),this.permissionHandlers.delete("*")}}async sessionCancel(t){return await this.ensureStarted(),this.proc.call("session/cancel",t,5e3).catch(()=>({ok:!0}))}async handlePermissionRequest(t){let n=a(t.sessionId),r=this.permissionHandlers.get(n)||this.permissionHandlers.get("*");return r?r(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=c(this.target.env)?this.target.env:{};return{source:this.artifactSource(),trustedFileRoots:[a(this.target.artifactRoot),a(this.target.artifactDir),a(this.target.runtimeArtifactRoot),a(t.ORCHA_RUNTIME_ARTIFACT_DIR),...N(this.target.trustedArtifactRoots),...N(this.target.trustedFileRoots),...N(this.target.artifactRoots),...N(this.target.artifactFileRoots)].filter(Boolean)}}async stop(t){await this.proc?.stop(t)}};function fr(e){let t=c(e.metadata)?e.metadata:{};return a(t.agentCode)}function mr(e,t){let n=fr(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var dt=class extends J{constructor(t,n,r,s={},i={}){let o=a(r).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",u=a(n.command)||"openclaw",l=Array.isArray(n.args)?n.args.map(String):[],d=l.length>0?l:["acp","--session",mr(t,o)];super(t,{...n,command:u,args:d},s,i)}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as Pe}from"node:child_process";import{randomUUID as et}from"node:crypto";import{existsSync as De,mkdirSync as pr,readdirSync as Fe,readFileSync as $e,realpathSync as pt,rmSync as hr,rmdirSync as gr,statSync as _r,unlinkSync as Tr}from"node:fs";import{homedir as yr,tmpdir as He}from"node:os";import{basename as Ht,dirname as Sr,join as k,resolve as Me}from"node:path";var wr=36e5,ve=5e3,Rr=2*60*1e3,Er=2*60*1e3,Or=12,Ir=1e3,Cr=1500,xr=1e3,ft=24*60*60*1e3,nt=new Set(["final_answer","final","complete","completed","done"]),Ar=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"]),Nr=new Set(["context_compacted","context_compaction","context_compressed"]);function ht(e,t){if(e?.pid){if(process.platform==="win32"){let n=["/PID",String(e.pid),"/T"];t==="SIGKILL"&&n.push("/F");try{Pe("taskkill",n,{stdio:"ignore",windowsHide:!0}).unref?.()}catch{try{e.kill(t)}catch{}}return}try{process.kill(-e.pid,t)}catch(n){if(n?.code==="ESRCH")return;try{e.kill(t)}catch{}}}}function Pt(e){ht(e,"SIGTERM");let t=setTimeout(()=>ht(e,"SIGKILL"),ve);return t.unref?.(),t}function M(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>M(t)).join("");if(!c(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let n=M(e[t]);if(n)return n}return""}function je(e){if(!c(e))return"";let t=c(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 M(t.content)||M(t.message);if(a(e.type)==="result")return M(e.result);let n=M(e.delta)||M(e.text)||M(e.content);if(n)return n;let r=c(e.item)?e.item:{};return["message","agent_message"].includes(a(r.type))||a(r.role)==="assistant"?M(r.content)||M(r.text)||M(r.message):""}function Be(e,t={}){return kt(e,{source:"codex_cli_image_generation",...t})}function Ke(e,t){lt(e.artifacts,t)}function qe(e){return v(Lt(e))}function vt(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type);if(n==="event_msg"&&r==="task_complete")return!0;let s=a(t.phase||t.status||t.stage).toLowerCase();if(n==="event_msg"&&r==="agent_message"||n==="response_item"&&r==="message"&&a(t.role)==="assistant")return nt.has(s);let i=c(e.item)?e.item:{};return n==="item.completed"&&a(i.type)==="agent_message"?!0:n==="result"&&e.is_error!==!0?a(e.result).length>0:!1}function Mr(e){let t=a(e.terminalProtocol||e.eventProtocol).toLowerCase();if(t)return t;let n=Ht(a(e.command)).replace(/\.exe$/i,"").toLowerCase();return n==="codex"||n==="claude"?n:""}function Ue(e,t,n){let r=c(t.error)?t.error:{},s=a(r.message)||M(t.error)||a(t.result)||a(t.message)||n;return Object.assign(new Error(s),{code:e})}function Ur(e,t){if(!c(e))return null;let n=a(e.type).toLowerCase();if(t==="codex")return n==="turn.completed"?{status:"completed",result:{stopReason:"end_turn"}}:n==="turn.failed"?{status:"failed",error:Ue("RUNTIME_CODEX_TURN_FAILED",e,"Codex turn failed")}:null;if(t==="claude"&&n==="result"){let r=a(e.subtype).toLowerCase();return e.is_error===!0||r.startsWith("error")||["failed","failure"].includes(r)?{status:"failed",error:Ue("RUNTIME_CLAUDE_RESULT_FAILED",e,"Claude result failed")}:{status:"completed",result:{stopReason:"end_turn",...a(e.result)?{output:a(e.result)}:{}}}}return null}function be(e){return c(e)?a(e.phase||e.status||e.stage).toLowerCase():""}function br(e){if(!c(e)||vt(e))return!1;let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type),s=be(t);if(n==="event_msg"&&r==="agent_message"||n==="response_item"&&r==="message"&&a(t.role)==="assistant")return!!(s&&!nt.has(s));let i=c(e.item)?e.item:{},o=be(i);return a(i.role)==="assistant"||a(i.type)==="message"?!!(o&&!nt.has(o)):!1}function kr(e,t,n){return n.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:n.captureLastMessage===!0?!0:Ht(e)==="codex"}function Lr(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:Ht(e)==="codex"}function Ge(e){return Math.max(20,S(e.codexTranscriptPollMs||e.transcriptPollMs,Ir))}function Pr(e){return Math.max(0,S(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,Cr))}function gt(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 jt(e){let t=c(e?.metadata)?e.metadata:{};return c(t._runtimeBridge)?t._runtimeBridge:{}}function Dt(e){return a(jt(e).promptKind).toLowerCase()}function Dr(e,t){for(let n of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let r=gt(n);if(r!=null)return r}return Dt(t)==="chat"}function Fr(e,t){let n=jt(e);for(let s of[n.emitThoughtChunks,n.streamThoughts]){let i=gt(s);if(i!=null)return i}let r=Dt(e);if(r&&r!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=gt(s);if(i!=null)return i}return Dt(e)==="chat"}function $r(e){let t=jt(e);for(let n of[t.finalTextOnly,t.finalOutputOnly]){let r=gt(n);if(r!=null)return r}return null}function Hr(e,t){let n=$r(e);return n??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function vr(e,t){return!e.finalTextOnly||t}function ze(e,t,n,r,s=r){return!r||e.emittedTexts.has(s)?!1:(e.emittedTexts.add(s),n({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}}}),!0)}function Je(e,t,n,r){return!r||e.emittedThoughtTexts.has(r)?!1:(e.emittedThoughtTexts.add(r),n({sessionId:t,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:r}}}),!0)}function jr(e,t,n,r=new Set){return{target:e,promptText:t,startedAtMs:n,baselinePaths:r,matchedPath:"",disabled:!1,processedLines:new Map}}function Br(e,t){let n=c(e.env)?e.env:{},r=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||n.ORCHA_RUNTIME_ARTIFACT_DIR)||k(He(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||et(),i=k(r,s),o=k(i,et());return pr(o,{recursive:!0}),{root:o,realRoot:pt(o),sessionRoot:i,realSessionRoot:pt(i)}}function We(e){return a(c(e)?e.root:e)}function ke(e){let t=We(e),n=a(c(e)?e.sessionRoot:Sr(t)),r=a(c(e)?e.realSessionRoot:"");if(n)try{if(r&&pt(n)!==r)return;gr(n)}catch{}}function Kr(e,t={}){let n=We(e),r=a(c(e)?e.realRoot:"");if(n){try{if(r&&pt(n)!==r){m("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:n});return}}catch{ke(e);return}try{hr(n,{recursive:!0,force:!0})}catch(s){m("warn","runtime.cli","runtime artifact directory cleanup failed",{...t,artifactRoot:n,error:String(s?.message||s)});return}ke(e)}}function qr(e,t){return{trustedFileRoots:[t,...N(e.trustedArtifactRoots),...N(e.trustedFileRoots),...N(e.artifactRoots),...N(e.artifactFileRoots)].filter(Boolean)}}function Ve(e){let t=a(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let n=c(e.env)?e.env:{},r=a(e.codexHome||n.CODEX_HOME||process.env.CODEX_HOME)||k(yr(),".codex");return k(r,"sessions")}function Gr(e,t){let n=new Date(t),r=String(n.getFullYear()),s=String(n.getMonth()+1).padStart(2,"0"),i=String(n.getDate()).padStart(2,"0");return k(e,r,s,i)}function Xe(e,t,n){let r=new Set;for(let s of[t-ft,t,t+ft,n-ft,n,n+ft])r.add(Gr(e,s));return[...r].filter(s=>De(s))}function zr(e,t,n){let r=Ve(e),s=t-Rr,i=n+Er,o=[];for(let u of Xe(r,t,n)){let l=[];try{l=Fe(u)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=k(u,d);try{let p=_r(f);if(!p.isFile()||p.mtimeMs<s||p.mtimeMs>i)continue;o.push({path:f,mtimeMs:p.mtimeMs})}catch{}}}return o.sort((u,l)=>l.mtimeMs-u.mtimeMs).slice(0,Or)}function Jr(e,t,n=t){let r=Ve(e),s=new Set;for(let i of Xe(r,t,n)){let o=[];try{o=Fe(i)}catch{continue}for(let u of o)u.endsWith(".jsonl")&&s.add(k(i,u))}return s}function Ft(e,t,n=0){if(!(n>8||e===null||e===void 0)){if(typeof e=="string"){e&&t.push(e);return}if(Array.isArray(e)){for(let r of e)Ft(r,t,n+1);return}if(c(e))for(let r of["payload","item","text","delta","output_text","content","message","output","input","prompt","last_agent_message","revised_prompt"])r in e&&Ft(e[r],t,n+1)}}function Ye(e){return a(e).replace(/\s+/g," ")}function Wr(e){let t=Ye(e);if(!t)return[];if(t.length<=200)return[t];let n=160,r=[0,Math.floor((t.length-n)/2),t.length-n],s=new Set,i=[];for(let o of r){let u=t.slice(Math.max(0,o),Math.max(0,o)+n).trim();u.length>=40&&!s.has(u)&&(s.add(u),i.push(u))}return i}function Vr(e,t){let n=Wr(t);if(!n.length)return!1;let r=[];for(let i of e)Ft(i,r);let s=Ye(r.join(" "));return n.every(i=>s.includes(i))}function Xr(e){return e.find(t=>c(t)&&a(t.type)==="session_meta"&&c(t.payload))||null}function Yr(e){let t=c(e?.payload)?e.payload:{},n=a(e?.timestamp||t.timestamp),r=Date.parse(n);return Number.isFinite(r)?r:Number.NaN}function Zr(e){let t=a(e.originator),n=a(e.source);if(t!=="codex_exec"&&n!=="exec"||a(e.parent_thread_id))return!1;let r=a(e.thread_source);if(r&&r!=="user")return!1;let s=a(e.session_id),i=a(e.id);return!(s&&i&&s!==i)}function Qr(e,t,n){if(!Vr(e,t.promptText))return!1;let r=Xr(e);if(!r)return!1;let s=r.payload;if(!Zr(s))return!1;let i=Yr(r);if(!Number.isFinite(i)||i<t.startedAtMs-5e3||i>n+5e3)return!1;let o=a(t.target.cwd),u=a(s.cwd);return!(o&&u&&Me(o)!==Me(u))}function Le(e){try{return es($e(e,"utf8"))}catch{return null}}function ts(e,t,n){if(!e||e.disabled)return null;if(e.matchedPath){let s=Le(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let r=[];for(let s of zr(e.target,e.startedAtMs,n)){if(e.baselinePaths.has(s.path))continue;let i=Le(s.path);!i||!Qr(i,e,n)||r.push({path:s.path,events:i})}return r.length!==1?(r.length>1&&(e.disabled=!0,m("warn","runtime.cli","codex transcript fallback disabled; multiple matching transcripts",{target:e.target.targetCode,sessionId:t,transcriptCount:r.length})),null):(e.matchedPath=r[0].path,m("info","runtime.cli","codex transcript stream attached",{target:e.target.targetCode,sessionId:t}),r[0])}function es(e){let t=[];for(let n of e.split(/\r?\n/)){let r=n.trim();if(r)try{t.push(JSON.parse(r))}catch{}}return t}function ns(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type);return n==="event_msg"&&r==="image_generation_end"||n==="response_item"&&r==="image_generation_call"}function rs(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{};return a(e.type)==="response_item"&&Ar.has(a(t.type))}function ss(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{};return Nr.has(a(t.type))}function is(e,t,n,r){let s=je(e),i=vt(e),o=0,u=0,l=0;if(s&&!i&&t.emitThoughtChunks&&Je(t,n,r,s)&&(l=1),s&&i){let d=t.emittedTexts.size?`
9
9
 
10
- ${s}`:s;Me(t,n,r,d,s)&&(o=1,u=1)}return s&&i&&(t.finalTextSeen=!0),Ce(t,Oe(e,t.artifactOptions)),(Pr(e)||De(e)||i)&&r({sessionId:n,update:{sessionUpdate:"runtime_event",event:Ae(e)}}),{textCount:o,finalTextCount:u,thoughtCount:l}}function Nt(e,t,n,r,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0,thoughtCount:0};let i=e.artifacts.size,o=0,u=0,l=0,d=0,f=kr(t,n,s);if(f){let m=Math.min(t.processedLines.get(f.path)||0,f.events.length),g=e.artifacts.size;for(let h of f.events.slice(m)){let y=Dr(h,e,n,r);u+=y.textCount,l+=y.finalTextCount,d+=y.thoughtCount}t.processedLines.set(f.path,f.events.length),(f.events.length>m||e.artifacts.size>g)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:u,finalTextCount:l,thoughtCount:d}}function Fr(e,{remove:t=!0}={}){if(!e||!Se(e))return"";try{return we(e,"utf8").trim()}catch{return""}finally{t&&lt(e)}}function lt(e){if(e)try{tr(e)}catch{}}function $r(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 Hr(e){return new Promise(t=>setTimeout(t,e))}function vr(e,t,n,r){return r?(e.finalTextSeen=!0,e.emittedTexts.has(r)||(e.emittedTexts.add(r),n({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}}})),!0):!1}async function Br(e,t,n,r,s,i){let o=Nt(e,t,n,r,Date.now()),u=()=>vr(e,n,r,Fr(s,{remove:!1}));if(u()||e.finalTextSeen)return lt(s),o;let l=mr(i);if(l<=0||!t&&!s)return lt(s),o;let d=Date.now()+l,f=Math.min(Ne(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await Hr(Math.min(f,Math.max(0,d-Date.now()))),o=$r(o,Nt(e,t,n,r,Date.now())),!u()););return lt(s),o}var pt=class{constructor(t,n,r={}){this.agent=t,this.target=n,this.options=r,this.active=new Map}async sessionNew(){return{sessionId:`cli-${this.agent.agentId}-${X()}`}}async sessionPrompt(t,n){let r=Date.now(),s=a(this.target.command);if(!s)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let i=a(t.sessionId)||X(),o=nt(t.prompt),u=a(this.target.promptMode||"stdin"),l=this.buildArgs(u,o),d=a(this.target.cwd)||this.agent.workspace||process.cwd(),f=Rr(this.target,i),m=f.root,g=Er(this.target,m),h=pr(s,this.target),y={...this.target,targetCode:this.agent.targetCode,cwd:d},U=h?Or(y,r):new Set,x=fr(s,l,this.target)?N(Ee(),`orcha-runtime-last-message-${X()}.txt`):"";x&&l.push("--output-last-message",x);let A=T(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,T(this.options.sessionPromptTimeoutMs,rr)),b={...process.env,...c(this.target.env)?this.target.env:{},...u==="env"?{ORCHA_RUNTIME_PROMPT:o}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:i,ORCHA_RUNTIME_ARTIFACT_DIR:m},_=Vn(s,l,{cwd:d,env:b,stdio:["pipe","pipe","pipe"]});this.active.set(i,_),p("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:i,pid:_.pid,timeoutMs:A});let te="",St=a(this.target.outputMode||"text"),k={artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:g,finalTextSeen:!1,finalTextOnly:Tr(t,this.target),emitThoughtChunks:gr(t,this.target)},Rt=h?Sr(y,o,r,U):null;return _.stdout.setEncoding("utf8"),_.stdout.on("data",B=>this.handleStdout(B,St,k,i,n)),_.stderr.setEncoding("utf8"),_.stderr.on("data",B=>{te+=B,this.target.emitStderr===!0&&n({sessionId:i,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:B}}})}),u==="stdin"?_.stdin.end(o):_.stdin.end(),await new Promise((B,Sn)=>{let Q=!1,ee=!1,F=null,wt=Rt&&hr(this.target,t)?setInterval(()=>{try{Nt(k,Rt,i,n)}catch(R){p("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:i,error:String(R?.message||R)})}},Ne(this.target)):null;wt?.unref?.();let ne=setTimeout(()=>{ee=!0,p("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:i,pid:_.pid,timeoutMs:A}),ut(_,"SIGTERM"),F=setTimeout(()=>{p("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:i,pid:_.pid}),ut(_,"SIGKILL")},sr),F.unref?.(),tt(Object.assign(new Error(`runtime CLI timed out after ${A}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},A);ne.unref?.();let re=()=>{clearTimeout(ne),wt&&clearInterval(wt),F&&!ee&&clearTimeout(F),wr(f,{target:this.agent.targetCode,sessionId:i}),this.active.delete(i)},Rn=R=>{Q||(Q=!0,re(),B(R))},tt=R=>{Q||(Q=!0,re(),Sn(R))};_.on("error",R=>{p("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:i,pid:_.pid,error:String(R?.message||R)}),tt(R)}),_.on("exit",(R,q)=>{(async()=>{F&&(clearTimeout(F),F=null),St==="json-lines"&&k.value.trim()&&this.handleStdout(`
11
- `,St,k,i,n);let L=await Br(k,Rt,i,n,x,this.target);(L.artifactCount>0||L.textCount>0||L.thoughtCount>0)&&p("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:i,artifactCount:L.artifactCount,textCount:L.textCount,finalTextCount:L.finalTextCount,thoughtCount:L.thoughtCount,transcriptCount:L.transcriptCount});let et=te.trim();if(et&&p("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:i,stderr:et}),p("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:i,pid:_.pid,exitCode:R,signal:q,artifactCount:k.artifacts.size,finalTextSeen:k.finalTextSeen}),R!==0){let wn=Object.assign(new Error(`runtime CLI exited with code ${R??"unknown"}${q?` (${q})`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:R,signal:q});tt(wn);return}Rn({stopReason:"end_turn",exitCode:R,signal:q,_artifacts:[...k.artifacts.values()],...et?{stderr:et}:{}})})().catch(tt)})})}buildArgs(t,n){let r=I(this.target.args);return t==="args"?[...r,n]:r}handleStdout(t,n,r,s,i){if(n!=="json-lines"){i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t}}});return}r.value+=t;let o=r.value.split(/\r?\n/);r.value=o.pop()||"";for(let u of o){let l=u.trim();if(l)try{let d=JSON.parse(l);Ce(r,Oe(d,r.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:Ae(d)}});let f=xe(d),m=Mt(d);f&&r.emitThoughtChunks&&!m&&dr(d)?Ue(r,s,i,f):f&&yr(r,m)&&Me(r,s,i,f),f&&m&&(r.finalTextSeen=!0)}catch{i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${u}
12
- `}}})}}}async sessionCancel(t){let n=a(t.sessionId),r=this.active.get(n);return r?(p("info","runtime.cli","cancelling runtime child",{target:this.agent.targetCode,sessionId:n,pid:r.pid}),ut(r,"SIGTERM"),this.active.delete(n),{ok:!0,cancelled:!0}):{ok:!0,cancelled:!1}}stop(t="stop"){for(let[n,r]of this.active.entries())p("info","runtime.cli","stopping runtime child",{target:this.agent.targetCode,sessionId:n,pid:r.pid,reason:t}),ut(r,"SIGTERM");this.active.clear()}};var bt="ORCHA_RUNTIME_OUTPUT_START",kt="ORCHA_RUNTIME_OUTPUT_END",Lt="ORCHA_RUNTIME_CONTROL_START",Pt="ORCHA_RUNTIME_CONTROL_END",$e=bt,He=kt,ve=Lt,Be=Pt,Dt=[bt,kt,Lt,Pt],Kr=new Set(["_artifacts","_decision","_meta"]),zr=new RegExp(`(?:^|(?<=[\\r\\n]))[ \\t]*(?<marker>${Dt.join("|")})[ \\t]*(?=\\r\\n?|\\n|$)`,"g"),O=class extends Error{constructor(t,n){super(n),this.name="RuntimeResultProtocolError",this.code=t}};function Ke(e){let t=typeof e=="string"?e.trimStart():"";return Dt.some(n=>t.startsWith(n))}function ze(e){if(typeof e!="string")return null;let t=e,n=jr(t);if(![...n.values()].some(h=>h.length>0))return null;let r=[],s=[];for(let[h,y]of n)y.length===0?r.push(h):y.length>1&&s.push(h);if(r.length>0||s.length>0){let h=[];throw r.length>0&&h.push(`\u7F3A\u5C11 ${r.join(", ")}`),s.length>0&&h.push(`\u91CD\u590D ${s.join(", ")}`),new O("invalid_markers",`Runtime Result \u534F\u8BAE\u6807\u8BB0\u4E0D\u5B8C\u6574\uFF1A${h.join("\uFF1B")}`)}let i=n.get(bt)[0],o=n.get(kt)[0],u=n.get(Lt)[0],l=n.get(Pt)[0];if(!(i.end<=o.start&&o.end<=u.start&&u.end<=l.start))throw new O("invalid_marker_order","Runtime Result \u534F\u8BAE\u6807\u8BB0\u987A\u5E8F\u9519\u8BEF\uFF1A\u5FC5\u987B\u5148\u8F93\u51FA OUTPUT \u5757\uFF0C\u518D\u8F93\u51FA CONTROL \u5757");let d=Gr(t.slice(i.end,o.start));if(!d.trim())throw new O("empty_output","Runtime Result OUTPUT \u5757\u4E0D\u80FD\u4E3A\u7A7A");let f=t.slice(u.end,l.start).trim();if(!f)throw new O("empty_control","Runtime Result CONTROL \u5757\u4E0D\u80FD\u4E3A\u7A7A");let m;try{m=JSON.parse(f)}catch(h){throw new O("invalid_control_json",`Runtime Result CONTROL \u5757\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(h?.message||h)}`)}if(!Fe(m))throw new O("invalid_control_type","Runtime Result CONTROL \u5757\u5FC5\u987B\u662F JSON \u5BF9\u8C61");let g=Object.keys(m).filter(h=>!Kr.has(h)).sort();if(g.length>0)throw new O("invalid_control_keys",`Runtime Result CONTROL \u5757\u5305\u542B\u975E\u6807\u51C6\u5B57\u6BB5\uFF1A${g.join(", ")}`);if("_artifacts"in m&&!Array.isArray(m._artifacts))throw new O("invalid_control_field_type","Runtime Result CONTROL \u5757\u7684 _artifacts \u5FC5\u987B\u662F JSON \u6570\u7EC4");for(let h of["_decision","_meta"])if(h in m&&!Fe(m[h]))throw new O("invalid_control_field_type",`Runtime Result CONTROL \u5757\u7684 ${h} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return{output:d,...m}}function jr(e){let t=new Map(Dt.map(n=>[n,[]]));for(let n of e.matchAll(zr))t.get(n.groups.marker).push({start:n.index,end:n.index+n[0].length});return t}function Gr(e){let t=e.match(/^(?:\r\n|\r|\n)/)?.[0]||"",n=t?e.slice(t.length):e;return t&&n.endsWith(t)?n.slice(0,-t.length):n}function Fe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var Ft=24e3,$t=8,Ht=50,vt=6e3,qr=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),Jr=10*60*1e3,Wr=60*1e3,Vr=8,Xr=60*1e3,Yr=1,Zr=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions","runtimeMaxSessions"]),Qr=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function ts(e,t,n){let r=c(e?._meta)?e._meta:{};return{...c(e)?e:{},sessionId:t,update:c(e?.update)?e.update:{},_meta:{...r,orchaAgentId:n.agentId,runtimeSessionId:n.runtimeSessionId,bridgeUpdateId:mt()}}}function E(e){return e==null||e===""?!1:typeof e=="string"?a(e)!=="":Array.isArray(e)?e.length>0:c(e)?Object.keys(e).length>0:!0}function Ve(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return qr.has(t)}function $(e,t){let n=T(e,t);return Number.isFinite(n)&&n>0?n:t}function Kt(e){let t=T(e,null);return Number.isFinite(t)&&t>0?t:null}function Z(e,t=!1){if(typeof e=="boolean")return e;let n=a(e).toLowerCase();return["true","1","yes","y","on"].includes(n)?!0:["false","0","no","n","off"].includes(n)?!1:t}function D(e){return a(e?.type||"echo")}function es(e){let t=D(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function zt(e){if(c(e)){if(Object.prototype.hasOwnProperty.call(e,"releaseAfterPrompt"))return e.releaseAfterPrompt;if(Object.prototype.hasOwnProperty.call(e,"disposeAfterPrompt"))return e.disposeAfterPrompt}}function ns(e){let t=String(e||"");if(Qr.test(t))return!0;let n=t.replace(/[^a-z0-9]/gi,"").toLowerCase();return n.endsWith("token")||n.endsWith("secret")||n.endsWith("password")||n.endsWith("apikey")||n.endsWith("privatekey")||n==="authorization"||n==="cookie"||n==="jwt"||n.includes("credential")}function jt(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=vt)return e;let n=e.length-vt;return`${e.slice(0,vt)}... [truncated ${n} characters]`}if(t>=$t)return Array.isArray(e)?`[array truncated at depth ${$t}, items=${e.length}]`:c(e)?`[object truncated at depth ${$t}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let n=e.slice(0,Ht).map(r=>jt(r,t+1));return e.length>Ht&&n.push(`[truncated ${e.length-Ht} items]`),n}if(c(e)){let n={};for(let[r,s]of Object.entries(e))n[r]=ns(r)?"[REDACTED]":jt(s,t+1);return n}return String(e)}var rs=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 ss(e){if(!c(e))return e;let t={};for(let n of rs)E(e[n])&&(t[n]=e[n]);return t}function is(e){if(!c(e))return e;let t={...e};return c(t.renderedPayload)&&(t.renderedPayload=ss(t.renderedPayload)),t}function os(e){let t=c(e)?e:{},n={};E(t.metadata)&&(n.metadata=is(t.metadata));for(let[r,s]of Object.entries(t))Zr.has(r)||r==="metadata"||E(s)&&(n[r]=s);return n}function as(e){let t=c(e)?e:{},n=c(t.metadata)?t.metadata:{},r=c(n.renderedPayload)?n.renderedPayload:{};return c(t.resultContract)?t.resultContract:c(r.resultContract)?r.resultContract:{}}function Xe(e){return a(as(e).kind).toLowerCase()==="decision"}function je(e){let t=c(e)?e:{},n=c(t.metadata)?t.metadata:{};return Kt(t.runtimeMaxSessions??n.runtimeMaxSessions)}function cs(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:D(e)==="cli"}function Ge(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return Z(t,es(e))}function us(e,t){let n=c(e?.metadata)?{...e.metadata}:{},r=c(n._runtimeBridge)?{...n._runtimeBridge}:{},s=zt(r);return n._runtimeBridge={...r,promptKind:"dispatch",finalTextOnly:cs(t),releaseAfterPrompt:s===void 0?Ge(t):Z(s,Ge(t)),requiresRuntimeResult:Xe(e)},n}function ls(e){let t=os(e);if(!E(t))return"";let n=JSON.stringify(jt(t),null,2);if(n.length<=Ft)return n;let r=n.length-Ft;return`${n.slice(0,Ft)}
13
- ... [truncated ${r} characters]`}function Ye(e){if(!c(e))return"";let t=c(e.update)?e.update:e,r=(c(t.content)?t.content:{}).text??t.text;return r==null?"":String(r)}function ds(e){if(!c(e))return"";let t=c(e.update)?e.update:e;return a(t.sessionUpdate)}function fs(e){if(!Array.isArray(e))return"";let t=!1,n=[],r=[],s=[],i=()=>{n.length>0&&(r.push(n),n=[])};for(let u of e){let l=ds(u),d=Ye(u);if(!l){d&&s.push(d);continue}if(t=!0,l==="agent_message_chunk"){d&&n.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 Gt(s);let o=r[r.length-1]||[];return Gt(o)}function ps(e){return Array.isArray(e)?e.map(Ye).filter(t=>a(t)):[]}function ms(e){if(!c(e))return null;let t=c(e.update)?e.update:e;return a(t.sessionUpdate)!=="runtime_event"?null:c(t.event)?t.event:null}function hs(e){if(!c(e))return"";let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type);if(n==="event_msg"){if(r==="task_complete")return a(t.last_agent_message||t.message||t.output);if(r==="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 gs(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let n=hs(ms(e[t]));if(n)return n}return""}function Gt(e){let t="";for(let n of e){let r=String(n||"");if(r){if(!t)t=r;else if(r.startsWith(t))t=r;else if(!t.endsWith(r)){let s=Ke(r)&&!/[\r\n]$/.test(t)?`
14
- `:"";t+=`${s}${r}`}}}return t.trim()}function _s(e){let t=String(e||"").trim();if(!t)return"";let n=t.match(/(?:^|\n)#{1,3}\s+\S/);return!n||n.index===0?t:t.slice(n.index+(t[n.index]===`
15
- `?1:0)).trim()}function qe(e){let t=String(e||"").trim();if(!t)return null;try{let n=JSON.parse(t);if(c(n)&&(Ze(n)||E(n._artifacts)||E(n.artifacts)||E(n._decision)||E(n._meta)))return n}catch{}return null}function ht(e){try{return ze(e)}catch{return null}}function Je(e){let t=String(e||"").trim();if(!t)return null;let n=ht(t);if(n)return n;let r=[...t.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];for(let s=r.length-1;s>=0;s-=1){let i=qe(r[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=qe(t.slice(s));if(i)return i}return null}function Ts(e){let t=ps(e);for(let n=t.length-1;n>=0;n-=1){let r=ht(t[n]);if(r)return r}return ht(Gt(t))}function Ze(e){if(!c(e))return!1;if(E(e.output))return!0;for(let t of["content","text","message","summary"])if(a(e[t]))return!0;return!!(Ve(e.status)||a(e.error)||a(e.errorMessage))}function M(e){let t=c(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 ys(e){return c(e)?typeof(c(e._decision)?e._decision:c(e.decision)?e.decision:e).passed=="boolean":!1}function Ss(e){return c(e)?c(e._decision)&&typeof e._decision.passed=="boolean"?!0:ys(e.output):!1}function Bt(e,t,n){let r=c(e)?{...e}:{};if(!E(r.output)){for(let s of["summary","message","content","text"])if(a(r[s])){r.output=a(r[s]);break}}return!E(r.output)&&a(n)&&(r.output=a(n)),{...r,_meta:{...c(r._meta)?r._meta:{},runtimeOutputSource:t,requiredRuntimeResult:!0,finalMessagePreview:a(n).slice(0,1e3)}}}var Rs=["dataUrl","dataURL","contentDataUrl","contentDataURL","contentBase64","base64","data"];function We(e){if(!c(e))return"";let t=c(e.content)?e.content:{},n=c(e.metadata)?e.metadata:{};return a(e.fieldKey||e.field_key||t.fieldKey||n.fieldKey)}function ws(e,t){let n=c(e.content)?e.content:{},r=c(t.content)?t.content:{},s={...e,...t,content:{...n,...r},metadata:{...c(e.metadata)?e.metadata:{},...c(t.metadata)?t.metadata:{}}};for(let i of Rs)E(e[i])&&(s[i]=e[i]),E(n[i])&&(s.content[i]=n[i]);return s}function Es(e,t){let n=Array.isArray(e)?e.filter(c):[],r=Array.isArray(t)?t.filter(c):[];if(!n.length)return r;if(!r.length)return n;let s=[...n],i=new Map;for(let u=0;u<n.length;u+=1){let l=We(n[u]),d=i.get(l)||[];d.push(u),i.set(l,d)}let o=new Map;for(let u of r){let l=We(u),d=o.get(l)||0;o.set(l,d+1);let f=i.get(l)?.[d];f===void 0?s.push(u):s[f]=ws(s[f],u)}return s}function P(e,t,n){let r={...e,...t,_meta:{...c(e._meta)?e._meta:{},...c(t._meta)?t._meta:{},runtimeOutputSource:n}};return(Array.isArray(e._artifacts)||Array.isArray(t._artifacts))&&(r._artifacts=Es(e._artifacts,t._artifacts)),r}function Is(e,t,n={}){let r=a(n.promptKind),s=n.requiresRuntimeResult===!0,i=s||r==="dispatch",o=M(e),u=typeof o.output=="string"?ht(o.output):null;if(u)return P(o,M(u),"result_block");let l=gs(t),d=l?Je(l):null,f=i?Ts(t):null;if(Ze(o))return Ve(o.status)||a(o.error)||a(o.errorMessage)?o:r==="dispatch"&&d?P(o,M(d),"final_event"):r==="dispatch"&&f?P(o,M(f),"updates"):!s||Ss(o)?o:d?P(o,M(d),"final_event"):f?P(o,M(f),"updates"):Bt(o,"result",o.output);if(d)return P(o,M(d),"final_event");if(f)return P(o,M(f),"updates");if(l)return s?Bt(o,"final_event",l):{...o,output:l,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let m=_s(fs(t));if(!m)return o;let g=Je(m);return g?P(o,M(g),"updates"):s?Bt(o,"updates",m):{...o,output:m,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}var gt=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.startedAt=W(),this.cleanupTimer=null,this.startSessionCleanup()}targetFor(t){let n=a(t)||this.config.defaultTargetCode,r=this.targets[n];if(!n||!c(r)){let s=new Error(`runtime target is not configured: ${n||"<empty>"}`);throw s.code="RUNTIME_TARGET_NOT_FOUND",s}return{code:n,target:r}}targetIdleTtlMs(t){let r=D(t)==="openclaw"?$(this.config.openClawSessionIdleTtlMs,Xr):$(this.config.sessionIdleTtlMs,Jr);return $(t?.sessionIdleTtlMs??t?.idleTtlMs,r)}targetMaxSessions(t,n=null){let s=D(t)==="openclaw"?$(this.config.openClawMaxSessions,Yr):$(this.config.maxSessionsPerTarget,Vr),i=$(t?.maxSessions,s),o=Kt(n);return o?Math.max(i,o):i}targetReleaseAfterPrompt(t,n={}){let r=D(t),s=c(n?._runtimeBridge)?n._runtimeBridge:{},i=zt(s);return i!==void 0?Z(i,!1):Z(t?.releaseAfterPrompt??t?.disposeAfterPrompt,r==="openclaw")}promptReleaseAfterPrompt(t,n={}){let r=c(n?._runtimeBridge)?n._runtimeBridge:{},s=zt(r);return s!==void 0?Z(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=$(this.config.sessionCleanupIntervalMs,Wr);t<=0||(this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions().catch(n=>{p("warn","runtime-bridge","runtime session cleanup failed",{error:String(n)})})},t),this.cleanupTimer.unref?.())}sessionCountForTarget(t){let n=0;for(let r of this.sessions.values())r.targetCode===t&&(n+=1);return n}sessionCountForAgentTarget(t,n){let r=0;for(let s of this.sessions.values())s.agentId===t&&s.targetCode===n&&(r+=1);return r}idleTargetSessions(t){return[...this.sessions.entries()].filter(([,n])=>n.targetCode===t&&!n.busy).sort((n,r)=>(n[1].lastUsedAtMs||0)-(r[1].lastUsedAtMs||0))}idleAgentTargetSessions(t,n){return[...this.sessions.entries()].filter(([,r])=>r.agentId===t&&r.targetCode===n&&!r.busy).sort((r,s)=>(r[1].lastUsedAtMs||0)-(s[1].lastUsedAtMs||0))}async closeSession(t,n="session_closed"){let r=this.sessions.get(t);if(!r)return!1;try{await r.runtime?.stop?.(n)}catch(s){p("warn","runtime-bridge","runtime session stop failed",{sessionId:r.sessionId,runtimeSessionId:r.runtimeSessionId,targetCode:r.targetCode,runtimeKind:r.runtimeKind,error:String(s)})}return this.sessions.delete(t),this.runtimeSessionIndex.delete(`${r.agentId}:${r.runtimeSessionId}`),p("info","runtime-bridge","runtime session closed",{sessionId:r.sessionId,runtimeSessionId:r.runtimeSessionId,targetCode:r.targetCode,runtimeKind:r.runtimeKind,reason:n}),!0}async closeAllSessions(t="bridge_shutdown"){for(let n of[...this.sessions.keys()])await this.closeSession(n,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[n,r]of[...this.sessions.entries()])r.busy||t-(r.lastUsedAtMs||r.createdAtMs||t)>r.idleTtlMs&&await this.closeSession(n,"idle_timeout")}async reserveTargetSlot(t,n,r={}){let s=a(r.agentId),i=Kt(r.runtimeMaxSessions);if(s&&i)for(;this.sessionCountForAgentTarget(s,t)>=i;){let u=this.idleAgentTargetSessions(s,t);if(!u.length){let l=new Error(`runtime agent session limit reached: ${s}`);throw l.code="RUNTIME_AGENT_SESSION_LIMIT",l}await this.closeSession(u[0][0],"agent_session_limit")}let o=this.targetMaxSessions(n,i);for(;this.sessionCountForTarget(t)>=o;){let u=this.idleTargetSessions(t);if(!u.length){let l=new Error(`runtime target session limit reached: ${t}`);throw l.code="RUNTIME_TARGET_SESSION_LIMIT",l}await this.closeSession(u[0][0],"target_session_limit")}}async createAgent(t){let n=a(t.agentId);if(!n)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});let{code:r,target:s}=this.targetFor(t.targetCode||t.framework),i={agentId:n,targetCode:r,framework:a(t.framework||r),workspace:a(t.workspace),metadata:c(t.metadata)?t.metadata:{},createdAt:W(),runtimeKind:D(s),runtimeMaxSessions:je(t)};return this.agents.set(n,i),{agent:i}}runtimeFor(t,n){let{target:r}=this.targetFor(t.targetCode),s=D(r),i={onPermissionRequest:u=>this.requestPermission(u)},o={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs};return s==="stdio-acp"||s==="acp"?new z(t,r,i,o):s==="openclaw"?new at(t,r,n,i,o):s==="cli"?new pt(t,r,o):new rt(t)}async prompt(t,n={}){let r=a(t.agentId),s=a(t.sessionId)||mt();if(!r)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});let i=this.agents.get(r)||(await this.createAgent({agentId:r,targetCode:t.targetCode,framework:t.framework,workspace:t.workspace,runtimeMaxSessions:t.runtimeMaxSessions,metadata:t.metadata})).agent,o=je(t);o&&(i.runtimeMaxSessions=o);let u=a(t.workspace);u&&u!==i.workspace&&(i.workspace=u);let l=`${r}:${s}`;await this.cleanupExpiredSessions();let d=this.sessions.get(l);if(!d){let{code:g,target:h}=this.targetFor(i.targetCode);await this.reserveTargetSlot(g,h,{agentId:r,runtimeMaxSessions:i.runtimeMaxSessions});let y=this.runtimeFor(i,s),U=await y.sessionNew({cwd:i.workspace||process.cwd(),mcpServers:Array.isArray(t.mcpServers)?t.mcpServers:[],metadata:c(t.metadata)?t.metadata:{}}),x=Date.now();d={agentId:r,sessionId:s,runtime:y,targetCode:g,runtimeKind:D(h),runtimeSessionId:a(c(U)?U.sessionId:"")||s,idleTtlMs:this.targetIdleTtlMs(h),releaseAfterPrompt:this.targetReleaseAfterPrompt(h,t.metadata),createdAtMs:x,lastUsedAtMs:x,busy:!1,createdAt:W()},this.sessions.set(l,d),this.runtimeSessionIndex.set(`${r}:${d.runtimeSessionId}`,d)}if(d.busy){let g=new Error(`runtime session is already running: ${s}`);throw g.code="RUNTIME_SESSION_BUSY",g}d.busy=!0,d.lastUsedAtMs=Date.now();let f=[],m=g=>{let h=ts(g,s,d);f.push(h),n.onUpdate?.(h)};try{let g=await d.runtime.sessionPrompt({sessionId:d.runtimeSessionId,prompt:Array.isArray(t.prompt)?t.prompt:[],metadata:c(t.metadata)?t.metadata:{}},m),h=c(t.metadata)?t.metadata:{},y=c(h._runtimeBridge)?h._runtimeBridge:{},U=Is(g,f,y);return{sessionId:s,runtimeSessionId:d.runtimeSessionId,result:U,updates:f}}finally{d.busy=!1,d.lastUsedAtMs=Date.now(),this.promptReleaseAfterPrompt(d,c(t.metadata)?t.metadata:{})&&await this.closeSession(l,"release_after_prompt")}}async cancel(t){let n=a(t.agentId),r=a(t.sessionId),s=`${n}:${r}`,i=this.sessions.get(s);return i?(await i.runtime.sessionCancel({sessionId:i.runtimeSessionId}),await this.closeSession(s,"cancelled"),{cancelled:!0}):{cancelled:!1}}async dispatch(t,n={}){let r=a(t.agentId),s=a(t.taskId),i=a(t.executionId);if(!r||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let o=a(t.sessionId)||`dispatch-${i||s}`,u=a(t.instructions),l=ls(t),d=Xe(t),{target:f}=this.targetFor(t.targetCode||t.framework),m=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",u?`instructions: ${u}`:"",l?"orchaContext:":"",l,l?"Use orchaContext as the source of truth for upstream outputs, review reports, artifacts, and workflow metadata.":"","Follow the execution protocol in instructions exactly.","When embedding a generated artifact in final Markdown, use the Orcha artifact placeholder as the link target: orcha-artifact://<fieldKey>/<index>.","Example: use ![illustration](orcha-artifact://image/0) for the first generated image artifact.","Do not use local filesystem paths, file:// URLs, or data: URLs in final Markdown; Orcha replaces artifact placeholders after ingestion.",d?`For decision results, put the raw report between ${$e} and ${He}.`:"",d?`Then put a JSON object containing _decision between ${ve} and ${Be}.`:"",d?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
16
- `)}];return this.prompt({...t,agentId:r,sessionId:o,prompt:m,metadata:us(t,f)},n)}async requestPermission({agent:t,runtimeSessionId:n,request:r,emitUpdate:s}){let i=mt(),u=this.runtimeSessionIndex.get(`${t.agentId}:${n}`)?.sessionId||n||mt(),l={permissionId:i,agentId:t.agentId,sessionId:u,runtimeSessionId:n,request:c(r)?r:{},status:"pending",createdAt:W()};return s?.({sessionId:n,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=T(r?.timeoutMs,this.config.permissionRequestTimeoutMs),m=setTimeout(()=>{this.pendingPermissions.delete(i),d({permissionId:i,outcome:"denied",response:{reason:"permission request timed out"}})},f);this.pendingPermissions.set(i,{timer:m,resolve:d,permission:l})})}async respondPermission(t){let n=a(t.permissionId),r=this.pendingPermissions.get(n),s=a(t.outcome||"approved")||"approved";return r?(clearTimeout(r.timer),this.pendingPermissions.delete(n),r.resolve({permissionId:n,outcome:s,response:c(t.response)?t.response:{},userId:a(t.userId),metadata:c(t.metadata)?t.metadata:{}}),{accepted:!0,permissionId:n,outcome:s}):{accepted:!1,permissionId:n,outcome:s}}health(){return{status:"ok",bridgeVersion:K,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)}}};import xs from"node:http";import Os from"node:https";import{randomBytes as Qe}from"node:crypto";var j=1,H=3,Cs=1e4,_t=class{constructor(t,n={}){this.url=t,this.readyState=0,this.socket=null,this.request=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,this.connectTimeoutMs=As(n.connectTimeoutMs,Cs),this.connectTimer=null,this.connect()}addEventListener(t,n){let r=this.listeners.get(t)||new Set;r.add(n),this.listeners.set(t,r)}emit(t,n={}){let r=this.listeners.get(t);if(r)for(let s of r)s(n)}connect(){let t=new URL(this.url),n=t.protocol==="wss:"?Os:xs,r=Qe(16).toString("base64"),s=n.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":r,"Sec-WebSocket-Version":"13"}});this.request=s,this.startConnectTimer(s),s.on("upgrade",(i,o,u)=>{if(this.clearConnectTimer(),this.readyState===H){o.destroy();return}this.socket=o,this.readyState=j,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==H&&this.emit("error",{error:l,message:l.message,type:"error"}),this.onClose()}),u?.length&&this.onData(u),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!==H&&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===j||this.readyState===H)return;let n=`websocket connect timeout after ${this.connectTimeoutMs}ms`;this.emit("error",{message:n,type:"timeout"}),this.onClose(),t.destroy(new Error(n))},this.connectTimeoutMs),this.connectTimer.unref?.())}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}send(t){!this.socket||this.readyState!==j||this.socket.write(qt(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==H){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===j&&this.socket.write(qt(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==H&&(this.clearConnectTimer(),this.readyState=H,this.request=null,this.emit("close"))}onData(t){for(this.buffer=Buffer.concat([this.buffer,t]);this.buffer.length>=2;){let n=this.buffer[0],r=this.buffer[1],s=n&15,i=(r&128)!==0,o=r&127,u=2;if(o===126){if(this.buffer.length<u+2)return;o=this.buffer.readUInt16BE(u),u+=2}else if(o===127){if(this.buffer.length<u+8)return;let f=this.buffer.readUInt32BE(u),m=this.buffer.readUInt32BE(u+4);o=f*2**32+m,u+=8}let l=u;if(i&&(u+=4),this.buffer.length<u+o)return;let d=this.buffer.subarray(u,u+o);if(i){let f=this.buffer.subarray(l,l+4);d=Buffer.from(d.map((m,g)=>m^f[g%4]))}this.buffer=this.buffer.subarray(u+o),s===1?this.emit("message",{data:d.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write(qt(10,d))}}};function As(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function qt(e,t){let n=t.length,r=2;n>=126&&n<=65535?r+=2:n>65535&&(r+=8);let s=Qe(4),i=Buffer.alloc(r+4+n);i[0]=128|e;let o=2;n<126?i[1]=128|n:n<=65535?(i[1]=254,i.writeUInt16BE(n,o),o+=2):(i[1]=255,i.writeUInt32BE(Math.floor(n/2**32),o),i.writeUInt32BE(n>>>0,o+4),o+=8),s.copy(i,o),o+=4;for(let u=0;u<n;u+=1)i[o+u]=t[u]^s[u%4];return i}function Ns(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 Ms(e){return Object.entries(e||{}).map(([t,n])=>({targetCode:t,targetName:a(n?.name||n?.targetName||t),targetType:a(n?.type||"echo"),status:"available",metadata:c(n)?n:{}}))}var Tt=class{constructor(t,n){this.config=t,this.bridge=n,this.ws=null,this.stopped=!1,this.connected=!1,this.reconnectTimer=null}start(){this.connect()}stop(){this.stopped=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.ws?.close()}connect(){if(this.stopped)return;let t=Ns(this.config.orchaUrl),n=new _t(t,{connectTimeoutMs:this.config.connectTimeoutMs});this.ws=n,n.addEventListener("open",()=>{if(this.ws!==n||this.stopped){n.close();return}this.authenticate(n)}),n.addEventListener("message",r=>this.handleMessage(r.data,n)),n.addEventListener("close",()=>this.scheduleReconnect("close",n)),n.addEventListener("error",r=>{p("warn","orcha-client","runtime node websocket error",{error:String(r?.message||r?.type||r)})})}authenticate(t=this.ws){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:K,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,targets:Ms(this.config.targets)},t)}scheduleReconnect(t,n=this.ws){n&&this.ws!==n||(this.connected=!1,n&&this.ws===n&&(this.ws=null),!this.stopped&&(this.reconnectTimer||(p("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,n=this.ws){if(n&&this.ws!==n)return;let r;try{r=JSON.parse(String(t))}catch(s){p("warn","orcha-client","invalid Orcha websocket frame",{error:String(s)});return}if(c(r)){if(r.type==="runtime_node.authenticated"){if(n&&this.ws!==n)return;this.connected=!0,p("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:r.connectionId});return}if(r.type==="orcha.runtime.request"){await this.handleRequest(r);return}r.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString()})}}async handleRequest(t){let n=a(t.id),r=a(t.method),s=c(t.params)?t.params:{};try{let i=await this.invoke(r,s,n);this.send({type:"orcha.runtime.response",id:n,ok:!0,result:i})}catch(i){this.send({type:"orcha.runtime.response",id:n,ok:!1,error:{code:i.code||"RUNTIME_NODE_ERROR",message:i.message||String(i)}})}}async invoke(t,n,r){if(t==="health")return this.bridge.health();if(t==="agents/create")return this.bridge.createAgent(n);if(t==="agents/dispatch")return this.bridge.dispatch(n,{onUpdate:s=>this.sendUpdate(r,s)});if(t==="sessions/prompt")return this.bridge.prompt(n,{onUpdate:s=>this.sendUpdate(r,s)});if(t==="sessions/cancel")return this.bridge.cancel(n);if(t==="permissions/respond")return this.bridge.respondPermission(n);throw Object.assign(new Error(`unsupported Orcha runtime method: ${t}`),{code:"METHOD_NOT_FOUND"})}sendUpdate(t,n){this.send({type:"orcha.runtime.event",requestId:t,eventType:"runtime.update",payload:n})}send(t,n=this.ws){return!n||n!==this.ws||n.readyState!==j?!1:(n.send(JSON.stringify(t)),!0)}};import{existsSync as Us,readFileSync as bs}from"node:fs";import{resolve as tn}from"node:path";var ks=/^[A-Za-z_][A-Za-z0-9_]*$/;function en(e=process.env,t=process.cwd()){let n=a(e.ORCHA_RUNTIME_ENV_FILE),r=n?tn(t,n):tn(t,".env");if(!Us(r))return n&&p("warn","config","runtime env file not found",{path:r}),{loaded:!1,path:r,keys:[]};let s=[],i=bs(r,"utf8");for(let o of i.split(/\r?\n/)){let u=Ps(o);if(!u)continue;let[l,d]=u;Object.prototype.hasOwnProperty.call(e,l)||(e[l]=d,s.push(l))}return p("info","config","runtime env file loaded",{path:r,keyCount:s.length}),{loaded:!0,path:r,keys:s}}function nn(e=process.env){return{mode:a(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),host:e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1",port:T(e.ORCHA_RUNTIME_BRIDGE_PORT,5588),token:e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",orchaUrl:a(e.ORCHA_RUNTIME_ORCHA_URL),nodeToken:e.ORCHA_RUNTIME_NODE_TOKEN||e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",nodeId:a(e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"local-runtime-node"),nodeName:a(e.ORCHA_RUNTIME_NODE_NAME||e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"Local Runtime Node"),reconnectMs:T(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),connectTimeoutMs:T(e.ORCHA_RUNTIME_CONNECT_TIMEOUT_MS||e.ORCHA_RUNTIME_WS_CONNECT_TIMEOUT_MS,1e4),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:T(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),sessionPromptTimeoutMs:T(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,36e5),permissionRequestTimeoutMs:T(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:T(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:T(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:T(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:T(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:T(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),targets:Ls(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function Ls(e){if(!a(e))return{};try{let t=JSON.parse(e);if(c(t))return t}catch(t){p("warn","config","invalid ORCHA_RUNTIME_TARGETS_JSON",{error:String(t)})}return{}}function Ps(e){let t=e.trim();if(!t||t.startsWith("#"))return null;let n=t.startsWith("export ")?t.slice(7).trimStart():t,r=n.indexOf("=");if(r<=0)return null;let s=n.slice(0,r).trim();if(!ks.test(s))return null;let i=Ds(n.slice(r+1).trim());return[s,i]}function Ds(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let n=e.slice(1,-1);return t==='"'?Fs(n):n}return $s(e).trim()}function Fs(e){return e.replaceAll("\\n",`
17
- `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function $s(e){let t=!1,n=!1;for(let r=0;r<e.length;r+=1){let s=e[r],i=e[r-1];if(s==="'"&&!n)t=!t;else if(s==='"'&&!t&&i!=="\\")n=!n;else if(s==="#"&&!t&&!n&&/\s/.test(i||""))return e.slice(0,r)}return e}import{createServer as Hs}from"node:http";function yt(e,t,n){let r=JSON.stringify(n);e.writeHead(t,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(r)}),e.end(r)}function v(e={}){return{ok:!0,...e}}function Jt(e,t,n){return{ok:!1,error:{code:e,message:t,...n===void 0?{}:{detail:n}}}}async function rn(e,t){let n=[],r=0;for await(let i of e){if(r+=i.length,r>t)throw Object.assign(new Error("request body too large"),{status:413,code:"REQUEST_TOO_LARGE"});n.push(i)}if(n.length===0)return{};let s=Buffer.concat(n).toString("utf8");if(!s.trim())return{};try{let i=JSON.parse(s);if(!c(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 sn(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 on(e,t){let n={"GET /health":async()=>v(t.health()),"POST /agents/create":async r=>v(await t.createAgent(r)),"POST /agents/dispatch":async r=>v(await t.dispatch(r)),"POST /sessions/prompt":async r=>v(await t.prompt(r)),"POST /sessions/cancel":async r=>v(await t.cancel(r)),"POST /permissions/respond":async r=>v(await t.respondPermission(r))};return Hs(async(r,s)=>{let i=new URL(r.url||"/",`http://${r.headers.host||`${e.host}:${e.port}`}`),o=`${r.method||"GET"} ${i.pathname}`,u=n[o];if(!u){yt(s,404,Jt("NOT_FOUND",`No route for ${o}`));return}try{sn(r,e.token);let l=r.method==="GET"?{}:await rn(r,e.requestLimitBytes);yt(s,200,await u(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";yt(s,d,Jt(f,l.message||String(l)))}})}var Js=qs(import.meta.url),Ws=".orcha-runtime-bridge.pid",Vs=".orcha-runtime-bridge.log",Xs=3,Ys=36e5,{command:Zs,options:gn}=ni(process.argv.slice(2));ri(gn);en();var Qs=nn();await ti(Zs,Qs,gn);async function ti(e,t,n){switch(e){case"run":case"foreground":cn(t);return;case"start":if(n.foreground){cn(t);return}ln();return;case"reload":case"restart":await dn({quiet:!0}),ln();return;case"stop":await dn();return;case"status":ei();return;case"help":case"--help":case"-h":ai();return;default:throw new Error(`Unknown command: ${e}`)}}function cn(e){si();let t=new gt(e);if(e.mode==="server"){let r=on(e,t);un({bridge:t,server:r}),r.listen(e.port,e.host,()=>{p("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 n=new Tt(e,t);un({bridge:t,client:n}),n.start(),p("info","runtime-bridge","Orcha runtime node started",{nodeId:e.nodeId,nodeName:e.nodeName,orchaUrl:e.orchaUrl,targets:Object.keys(t.targets)})}function un({bridge:e,client:t,server:n}){let r=!1,s=i=>{if(r)return;r=!0;let o=Number(e?.sessions?.size||0)>0;p("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(u){p("warn","runtime-bridge","runtime client stop failed",{error:String(u)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(u=>{p("warn","runtime-bridge","runtime bridge stop failed",{error:String(u)})}).finally(()=>{try{n?.close?.()}catch(u){p("warn","runtime-bridge","runtime server close failed",{error:String(u)})}}),setTimeout(()=>process.exit(0),o?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function ln(){let e=Zt(),t=_n(),n=Qt(e);if(n&&G(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:e,logFile:t}));return}n&&Xt(e),pn(e),pn(t),Vt(t);let r=zs(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=vs(process.execPath,[Js,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",r,r]});i.unref(),Bs(r),hn(e,`${i.pid}
18
- `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function dn({quiet:e=!1}={}){let t=Zt(),n=Qt(t);if(!n){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!G(n)){Xt(t),e||console.log(JSON.stringify({status:"not_running",pid:n,pidFile:t}));return}process.kill(n,"SIGTERM"),!await fn(n,1e4)&&G(n)&&(process.kill(n,"SIGKILL"),await fn(n,3e3)),Xt(t),e||console.log(JSON.stringify({status:"stopped",pid:n,pidFile:t}))}function ei(){let e=Zt(),t=_n(),n=Qt(e),r=!!(n&&G(n));console.log(JSON.stringify({status:r?"running":"not_running",running:r,pid:r?n:null,pidFile:e,logFile:t}))}function ni(e){let t=[],n={};for(let s=0;s<e.length;s+=1){let i=e[s];i==="--daemon"?n.daemon=!0:i==="--foreground"?n.foreground=!0:i==="--env-file"?n.envFile=e[++s]:i==="--pid-file"?n.pidFile=e[++s]:i==="--log-file"?n.logFile=e[++s]:t.push(i)}return{command:t[0]||"run",options:n}}function ri(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 Zt(){return Yt(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Ws)}function _n(){return Yt(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||Vs)}function si(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=Tn();if(t<=0)return;let n=Yt(process.cwd(),e);Vt(n,t);let r=oi();r<=0||setInterval(()=>Vt(n,t),r).unref()}function Vt(e,t=Tn()){if(t<=0||!mn(e))return;let n=0,r="";try{if(n=an(e).size,n<=0)return;r=Wt(e,"utf8")}catch(d){p("warn","runtime-bridge","runtime log cleanup skipped",{logFile:e,error:String(d)});return}let s=Date.now()-t*24*60*60*1e3,i=r.split(/\r?\n/),o=[],u=0;for(let d of i)d&&(ii(d,s)?o.push(d):u+=1);if(u===0)return;let l="";try{an(e).size>n&&(l=Wt(e,"utf8").slice(r.length));let f=[...o,...l.split(/\r?\n/).filter(Boolean)].join(`
19
- `);hn(e,f?`${f}
20
- `:""),p("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:u})}catch(d){p("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(d)})}}function ii(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object")return!0;let r=typeof n.ts=="string"?Date.parse(n.ts):Number.NaN;return!Number.isFinite(r)||r>=t}catch{return!0}}function Tn(){return yn(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,Xs)}function oi(){return yn(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Ys)}function yn(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function Qt(e){if(!mn(e))return null;let t=Number.parseInt(Wt(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function G(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function fn(e,t){let n=Date.now();for(;Date.now()-n<t;){if(!G(e))return!0;await new Promise(r=>setTimeout(r,100))}return!G(e)}function pn(e){Ks(Gs(e),{recursive:!0})}function Xt(e){try{js(e,{force:!0})}catch{}}function ai(){console.log(`Usage: orcha-runtime-bridge [command] [options]
10
+ ${s}`:s;ze(t,n,r,d,s)&&(o=1,u=1)}return s&&i&&(t.finalTextSeen=!0),Ke(t,Be(e,t.artifactOptions)),(ns(e)||rs(e)||ss(e)||i)&&r({sessionId:n,update:{sessionUpdate:"runtime_event",event:qe(e)}}),{textCount:o,finalTextCount:u,thoughtCount:l}}function $t(e,t,n,r,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0,thoughtCount:0};let i=e.artifacts.size,o=0,u=0,l=0,d=0,f=ts(t,n,s);if(f){let p=Math.min(t.processedLines.get(f.path)||0,f.events.length),h=e.artifacts.size;for(let g of f.events.slice(p)){let I=is(g,e,n,r);u+=I.textCount,l+=I.finalTextCount,d+=I.thoughtCount}t.processedLines.set(f.path,f.events.length),(f.events.length>p||e.artifacts.size>h)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:u,finalTextCount:l,thoughtCount:d}}function os(e,{remove:t=!0}={}){if(!e||!De(e))return"";try{return $e(e,"utf8").trim()}catch{return""}finally{t&&mt(e)}}function mt(e){if(e)try{Tr(e)}catch{}}function as(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 cs(e){return new Promise(t=>setTimeout(t,e))}function us(e,t,n,r){return r?(e.finalTextSeen=!0,e.emittedTexts.has(r)||(e.emittedTexts.add(r),n({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}}})),!0):!1}async function ls(e,t,n,r,s,i){let o=$t(e,t,n,r,Date.now()),u=()=>us(e,n,r,os(s,{remove:!1}));if(u()||e.finalTextSeen)return mt(s),o;let l=Pr(i);if(l<=0||!t&&!s)return mt(s),o;let d=Date.now()+l,f=Math.min(Ge(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await cs(Math.min(f,Math.max(0,d-Date.now()))),o=as(o,$t(e,t,n,r,Date.now())),!u()););return mt(s),o}var _t=class{constructor(t,n,r={}){this.agent=t,this.target=n,this.options=r,this.active=new Map}async sessionNew(){return{sessionId:`cli-${this.agent.agentId}-${et()}`}}async sessionPrompt(t,n,r){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)||et(),u=ot(t.prompt),l=a(this.target.promptMode||"stdin"),d=this.buildArgs(l,u),f=a(this.target.cwd)||this.agent.workspace||process.cwd(),p=Br(this.target,o),h=p.root,g=qr(this.target,h),I=Lr(i,this.target),q={...this.target,targetCode:this.agent.targetCode,cwd:f},_=I?Jr(q,s):new Set,T=kr(i,d,this.target)?k(He(),`orcha-runtime-last-message-${et()}.txt`):"";T&&d.push("--output-last-message",T);let w=S(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,S(this.options.sessionPromptTimeoutMs,wr)),E={...process.env,...c(this.target.env)?this.target.env:{},...l==="env"?{ORCHA_RUNTIME_PROMPT:u}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:o,ORCHA_RUNTIME_ARTIFACT_DIR:h},y=Pe(i,d,{cwd:f,env:E,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(o,y),m("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:o,pid:y.pid,timeoutMs:w});let pe="",At=a(this.target.outputMode||"text"),C={artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:g,finalTextSeen:!1,finalTextOnly:Hr(t,this.target),emitThoughtChunks:Fr(t,this.target),terminalOutcome:null,terminalProtocol:Mr(this.target),emitTerminal:null},Nt=I?jr(q,u,s,_):null;return y.stdout.setEncoding("utf8"),y.stdout.on("data",G=>this.handleStdout(G,At,C,o,n)),y.stderr.setEncoding("utf8"),y.stderr.on("data",G=>{pe+=G,this.target.emitStderr===!0&&n({sessionId:o,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:G}}})}),l==="stdin"?y.stdin.end(u):y.stdin.end(),await new Promise((G,Hn)=>{let X=!1,he=!1,it=null,Y=null,Mt=Nt&&Dr(this.target,t)?setInterval(()=>{try{$t(C,Nt,o,n)}catch(R){m("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:o,error:String(R?.message||R)})}},Ge(this.target)):null;Mt?.unref?.();let ge=setTimeout(()=>{he=!0,m("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:o,pid:y.pid,timeoutMs:w}),ht(y,"SIGTERM"),it=setTimeout(()=>{m("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:o,pid:y.pid}),ht(y,"SIGKILL")},ve),it.unref?.(),Z(Object.assign(new Error(`runtime CLI timed out after ${w}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},w);ge.unref?.();let _e=()=>{clearTimeout(ge),Y&&clearTimeout(Y),Mt&&clearInterval(Mt),it&&!he&&clearTimeout(it),Kr(p,{target:this.agent.targetCode,sessionId:o}),this.active.delete(o),C.emitTerminal=null},vn=R=>{X||(X=!0,_e(),G(R))},Z=R=>{X||(X=!0,_e(),Hn(R))};C.emitTerminal=R=>{let $={...c(R.result)?R.result:{},_artifacts:[...C.artifacts.values()]};try{r?.({...R,result:$})}catch(H){m("warn","runtime.cli","runtime terminal listener failed",{target:this.agent.targetCode,sessionId:o,error:String(H?.message||H)})}let U=Math.max(0,S(this.target.terminalExitGraceMs,xr));Y=setTimeout(()=>{Y=null,!(X||this.active.get(o)!==y)&&(m("warn","runtime.cli","runtime stayed alive after terminal event; terminating child",{target:this.agent.targetCode,sessionId:o,pid:y.pid,terminalProtocol:C.terminalProtocol,graceMs:U}),Pt(y))},U),Y.unref?.()},y.on("error",R=>{m("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:o,pid:y.pid,error:String(R?.message||R)}),Z(R)}),y.on("exit",(R,$)=>{(async()=>{At==="json-lines"&&C.value.trim()&&this.handleStdout(`
11
+ `,At,C,o,n);let U=await ls(C,Nt,o,n,T,this.target);(U.artifactCount>0||U.textCount>0||U.thoughtCount>0)&&m("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:o,artifactCount:U.artifactCount,textCount:U.textCount,finalTextCount:U.finalTextCount,thoughtCount:U.thoughtCount,transcriptCount:U.transcriptCount});let H=pe.trim();if(H&&m("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:o,stderr:H}),m("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:o,pid:y.pid,exitCode:R,signal:$,artifactCount:C.artifacts.size,finalTextSeen:C.finalTextSeen}),C.terminalOutcome?.status==="failed"){Z(C.terminalOutcome.error);return}if(R!==0&&C.terminalOutcome?.status!=="completed"){let jn=Object.assign(new Error(`runtime CLI exited with code ${R??"unknown"}${$?` (${$})`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:R,signal:$});Z(jn);return}vn({stopReason:"end_turn",exitCode:R,signal:$,_artifacts:[...C.artifacts.values()],...H?{stderr:H}:{}})})().catch(Z)})})}buildArgs(t,n){let r=N(this.target.args);return t==="args"?[...r,n]:r}handleStdout(t,n,r,s,i){if(n!=="json-lines"){i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t}}});return}r.value+=t;let o=r.value.split(/\r?\n/);r.value=o.pop()||"";for(let u of o){let l=u.trim();if(l)try{let d=JSON.parse(l);Ke(r,Be(d,r.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:qe(d)}});let f=je(d),p=vt(d);f&&r.emitThoughtChunks&&!p&&br(d)?Je(r,s,i,f):f&&vr(r,p)&&ze(r,s,i,f),f&&p&&(r.finalTextSeen=!0);let h=Ur(d,r.terminalProtocol);h&&!r.terminalOutcome&&(h.status==="failed"||r.finalTextSeen||r.artifacts.size>0)&&(r.terminalOutcome=h,r.emitTerminal?.(h))}catch{i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${u}
12
+ `}}})}}}async sessionCancel(t){let n=a(t.sessionId),r=this.active.get(n);return r?(m("info","runtime.cli","cancelling runtime child",{target:this.agent.targetCode,sessionId:n,pid:r.pid}),Pt(r),{ok:!0,cancelled:!0}):{ok:!0,cancelled:!1}}stop(t="stop"){for(let[n,r]of this.active.entries())m("info","runtime.cli","stopping runtime child",{target:this.agent.targetCode,sessionId:n,pid:r.pid,reason:t}),Pt(r);this.active.clear()}};var Bt="ORCHA_RUNTIME_OUTPUT_START",Kt="ORCHA_RUNTIME_OUTPUT_END",qt="ORCHA_RUNTIME_CONTROL_START",Gt="ORCHA_RUNTIME_CONTROL_END",Qe=Bt,tn=Kt,en=qt,nn=Gt,zt=[Bt,Kt,qt,Gt],ds=new Set(["_artifacts","_decision","_meta"]),fs=new RegExp(`(?:^|(?<=[\\r\\n]))[ \\t]*(?<marker>${zt.join("|")})[ \\t]*(?=\\r\\n?|\\n|$)`,"g"),b=class extends Error{constructor(t,n){super(n),this.name="RuntimeResultProtocolError",this.code=t}};function rn(e){let t=typeof e=="string"?e.trimStart():"";return zt.some(n=>t.startsWith(n))}function sn(e){if(typeof e!="string")return null;let t=e,n=ms(t);if(![...n.values()].some(g=>g.length>0))return null;let r=[],s=[];for(let[g,I]of n)I.length===0?r.push(g):I.length>1&&s.push(g);if(r.length>0||s.length>0){let g=[];throw r.length>0&&g.push(`\u7F3A\u5C11 ${r.join(", ")}`),s.length>0&&g.push(`\u91CD\u590D ${s.join(", ")}`),new b("invalid_markers",`Runtime Result \u534F\u8BAE\u6807\u8BB0\u4E0D\u5B8C\u6574\uFF1A${g.join("\uFF1B")}`)}let i=n.get(Bt)[0],o=n.get(Kt)[0],u=n.get(qt)[0],l=n.get(Gt)[0];if(!(i.end<=o.start&&o.end<=u.start&&u.end<=l.start))throw new b("invalid_marker_order","Runtime Result \u534F\u8BAE\u6807\u8BB0\u987A\u5E8F\u9519\u8BEF\uFF1A\u5FC5\u987B\u5148\u8F93\u51FA OUTPUT \u5757\uFF0C\u518D\u8F93\u51FA CONTROL \u5757");let d=ps(t.slice(i.end,o.start));if(!d.trim())throw new b("empty_output","Runtime Result OUTPUT \u5757\u4E0D\u80FD\u4E3A\u7A7A");let f=t.slice(u.end,l.start).trim();if(!f)throw new b("empty_control","Runtime Result CONTROL \u5757\u4E0D\u80FD\u4E3A\u7A7A");let p;try{p=JSON.parse(f)}catch(g){throw new b("invalid_control_json",`Runtime Result CONTROL \u5757\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(g?.message||g)}`)}if(!Ze(p))throw new b("invalid_control_type","Runtime Result CONTROL \u5757\u5FC5\u987B\u662F JSON \u5BF9\u8C61");let h=Object.keys(p).filter(g=>!ds.has(g)).sort();if(h.length>0)throw new b("invalid_control_keys",`Runtime Result CONTROL \u5757\u5305\u542B\u975E\u6807\u51C6\u5B57\u6BB5\uFF1A${h.join(", ")}`);if("_artifacts"in p&&!Array.isArray(p._artifacts))throw new b("invalid_control_field_type","Runtime Result CONTROL \u5757\u7684 _artifacts \u5FC5\u987B\u662F JSON \u6570\u7EC4");for(let g of["_decision","_meta"])if(g in p&&!Ze(p[g]))throw new b("invalid_control_field_type",`Runtime Result CONTROL \u5757\u7684 ${g} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return{output:d,...p}}function ms(e){let t=new Map(zt.map(n=>[n,[]]));for(let n of e.matchAll(fs))t.get(n.groups.marker).push({start:n.index,end:n.index+n[0].length});return t}function ps(e){let t=e.match(/^(?:\r\n|\r|\n)/)?.[0]||"",n=t?e.slice(t.length):e;return t&&n.endsWith(t)?n.slice(0,-t.length):n}function Ze(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{createHash as hs}from"node:crypto";var gs="orcha.goal-contract/v1",_s=new Set(["complete","completed","done","ok","passed","success","succeeded"]),Ts=new Set(["aborted","blocked","cancelled","canceled","denied","error","failed","failure","timeout","timed_out"]),ys=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 Xt(e){return hs("sha256").update(j(e)).digest("hex")}function an(e){if(!un(e))return"";let t=["The following Orcha goal contract is immutable for this turn. Do not narrow its outcome or constraints.",`<goal_contract>${JSON.stringify(e)}</goal_contract>`];return e.verificationPlan?.required===!0&&t.push("Every verification check must be satisfied by a real successful tool call from one of its toolNames.","A final text claim is not verification; missing or failed tool evidence prevents completion."),t.join(`
13
+ `)}function cn(e,t,n=""){if(!un(e))return e==null?null:{required:!0,status:"failed",outcome:a(e?.outcome),goalContractHash:"",checks:[],errorCode:"invalid_goal_contract"};let r=Xt(e),s=e.verificationPlan.required===!0;if(a(n)&&a(n)!==r)return{required:s,status:"failed",outcome:e.outcome,goalContractHash:r,checks:[],errorCode:"goal_contract_hash_mismatch"};if(!s)return{required:!1,status:"not_required",outcome:e.outcome,goalContractHash:r,checks:[]};let i=Ss(t),o=e.verificationPlan.checks.map(l=>xs(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:r,checks:o}}function un(e){if(!c(e)||e.schemaVersion!==gs||!a(e.outcome))return!1;let t=e.verificationPlan;if(!c(t)||typeof t.required!="boolean"||!Array.isArray(t.checks)||t.required&&t.checks.length===0)return!1;let n=new Set;for(let r of t.checks)if(!c(r)||!a(r.id)||n.has(a(r.id))||(n.add(a(r.id)),!Array.isArray(r.toolNames)||r.toolNames.length===0||r.toolNames.some(s=>!a(s)))||r.arguments!==void 0&&!c(r.arguments))return!1;return!0}function Ss(e){let t=new Map,n=[];for(let r of Array.isArray(e)?e:[]){let s=c(r?.update)?r.update:{},i=a(s.sessionUpdate);if(i==="runtime_event"){ws(s.event,t,n);continue}if(i==="tool_call"){let o=yt(s)||`tool-${n.length+1}`,u=Tt(t,n,o),l=Wt(s,s.name||s.toolName||s.kind);u.toolName=l.toolName,u.arguments=l.arguments,u.status=rt(s.status),u.evidence=wt(s);continue}if(i==="tool_call_update"){let o=yt(s);if(!o)continue;let u=Tt(t,n,o),l=Wt(s,s.name||s.toolName||s.kind);u.toolName||=l.toolName,Object.keys(u.arguments).length===0&&(u.arguments=l.arguments),u.status=rt(s.status),u.evidence.push(...wt(s))}}return n}function ws(e,t,n){let r=c(e)&&c(e.payload)?e.payload:c(e)?e:{},s=a(r.type);if(["function_call","custom_tool_call","local_shell_call","mcp_tool_call"].includes(s)){let u=yt(r)||`runtime-${n.length+1}`,l=Tt(t,n,u),d=Wt(r,r.name||r.tool||s,s);l.toolName=d.toolName,l.arguments=d.arguments,l.status=rt(r.status),l.evidence.push(...wt(r));return}if(!["function_call_output","custom_tool_call_output","local_shell_call_output","mcp_tool_call_output"].includes(s))return;let i=yt(r);if(!i)return;let o=Tt(t,n,i);o.status=Is(r,o.toolName),o.evidence.push(...wt(r))}function Tt(e,t,n){let r=e.get(n);return r||(r={toolCallId:n,toolName:"",arguments:{},status:"unknown",evidence:[]},e.set(n,r),t.push(r)),r}function Rs(e){let t=a(e).toLowerCase();return ys.get(t)||t}function Wt(e,t,n=""){let r=Es(e),s=a(n)==="mcp_tool_call"||a(e?.kind).toLowerCase()==="mcp",i=c(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 u=a(e?.tool||e?.toolName||e?.name||t);return{toolName:"plugin_operation",arguments:{...r,...u?{operationCode:u}:{}}}}return{toolName:Rs(t),arguments:r}}function yt(e){return c(e)?a(e.call_id||e.callId||e.toolCallId||e.id):""}function Es(e){if(!c(e))return{};for(let n of["arguments","args","rawInput","input","params","parameters"]){let r=Os(e[n]);if(r)return r}let t={};for(let n of["cmd","command","cwd","operationCode","path","query","url"])e[n]!==void 0&&(t[n]=e[n]);return t}function Os(e){if(c(e))return structuredClone(e);if(typeof e!="string")return null;try{let t=JSON.parse(e);return c(t)?t:null}catch{return null}}function Is(e,t){if(!c(e))return"unknown";let n=St(e,0,{parseCliExitCode:t==="run_command"||t==="apply_patch"});return n.includes("failed")?"failed":n.includes("success")?"success":"unknown"}function St(e,t=0,n={}){if(t>8||e===null||e===void 0)return[];if(typeof e=="string")return Cs(e,t,n);if(Array.isArray(e))return e.flatMap(o=>St(o,t+1,n));if(!c(e))return[];let r=[];typeof e.isError=="boolean"&&r.push(e.isError?"failed":"success"),typeof e.ok=="boolean"&&r.push(e.ok?"success":"failed"),typeof e.success=="boolean"&&r.push(e.success?"success":"failed");let s=rt(e.status);s!=="unknown"&&r.push(s);let i=e.exitCode??e.exit_code;typeof i=="number"&&Number.isFinite(i)&&r.push(i===0?"success":"failed");for(let o of["output","result","structuredContent","content"])e[o]!==void 0&&r.push(...St(e[o],t+1,n));return r}function Cs(e,t,n){let r=e.trim();if(!r)return[];try{return St(JSON.parse(r),t+1,n)}catch{}if(n.parseCliExitCode!==!0)return[];let s=[];for(let i of r.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 rt(e){let t=a(e).toLowerCase();return _s.has(t)?"success":Ts.has(t)?"failed":"unknown"}function wt(e){if(!c(e))return[];let t=c(e.output)?e.output:{},n=[e.verificationEvidence,c(e.verification)?e.verification.evidence:null,t.verificationEvidence,c(t.verification)?t.verification.evidence:null],r=[];for(let s of n)for(let i of Array.isArray(s)?s:s?[s]:[])!c(i)||!a(i.id)||r.push({id:a(i.id),status:rt(i.status??(i.passed===!0?"passed":i.passed===!1?"failed":"")),...a(i.message)?{message:a(i.message)}:{}});return r}function xs(e,t){let n=t.filter(o=>e.toolNames.includes(o.toolName)&&Vt(e.arguments||{},o.arguments)),r=a(e.evidenceId),s=n.find(o=>o.status==="success"&&(!r||o.evidence.some(u=>u.id===r&&u.status==="success")));if(s)return Jt(e,"passed",s,"Runtime tool evidence passed.");let i=n.find(o=>o.status==="failed"||r&&o.evidence.some(u=>u.id===r&&u.status==="failed"));return i?Jt(e,"failed",i,"Runtime tool evidence failed."):Jt(e,"missing",n.at(-1),r?"Required evidence is missing.":"Required tool execution is missing.")}function Jt(e,t,n,r){return{id:e.id,status:t,message:r,...a(e.description)?{description:a(e.description)}:{},toolNames:e.toolNames,...c(e.arguments)?{arguments:e.arguments}:{},...a(e.evidenceId)?{evidenceId:a(e.evidenceId)}:{},...n?.toolCallId?{toolCallId:n.toolCallId}:{}}}function Vt(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>Vt(n,t[r])):c(e)?c(t)?Object.entries(e).every(([n,r])=>Object.hasOwn(t,n)&&Vt(r,t[n])):!1:Object.is(e,t)}function j(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string")return on(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,n)=>{if(!Object.hasOwn(e,n))throw new Error("invalid_jcs_json_value");return j(e[n])}).join(",")}]`;if(c(e))return`{${Object.keys(e).sort().map(t=>`${on(t)}:${j(e[t])}`).join(",")}}`;throw new Error("invalid_jcs_json_value")}function on(e){return As(e),JSON.stringify(e)}function As(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))throw new Error("invalid_jcs_unicode");t+=1}else if(n>=56320&&n<=57343)throw new Error("invalid_jcs_unicode")}}var Yt=24e3,Zt=8,Qt=50,te=6e3,Ms=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),Us=10*60*1e3,bs=60*1e3,ks=8,Ls=30*60*1e3,Ps=60*1e3,Ds=1,Fs=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions","runtimeMaxSessions"]),$s=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Hs(e){if(!c(e))return{};let t={};for(let n of["name","code","serverName","serverCode","type","transport","url","command","protocolVersion"]){let r=a(e[n]);r&&(t[n]=r)}return t}function vs(e){return(Array.isArray(e)?e:[]).map(Hs).sort((t,n)=>{let r=j(t),s=j(n);return r<s?-1:r>s?1:0})}function js(e){return!c(e)||e.verificationPlan?.required!==!0?!1:(Array.isArray(e.verificationPlan.checks)?e.verificationPlan.checks:[]).some(n=>c(n)&&Array.isArray(n.toolNames)&&n.toolNames.some(r=>a(r)==="plugin_operation"))}function Bs(e,t,n){let r=c(e?._meta)?e._meta:{};return{...c(e)?e:{},sessionId:t,update:c(e?.update)?e.update:{},_meta:{...r,orchaAgentId:n.agentId,runtimeSessionId:n.runtimeSessionId,bridgeUpdateId:Rt()}}}function A(e){return e==null||e===""?!1:typeof e=="string"?a(e)!=="":Array.isArray(e)?e.length>0:c(e)?Object.keys(e).length>0:!0}function hn(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return Ms.has(t)}function D(e,t){let n=S(e,t);return Number.isFinite(n)&&n>0?n:t}function ne(e){let t=S(e,null);return Number.isFinite(t)&&t>0?t:null}function st(e,t=!1){if(typeof e=="boolean")return e;let n=a(e).toLowerCase();return["true","1","yes","y","on"].includes(n)?!0:["false","0","no","n","off"].includes(n)?!1:t}function P(e){return a(e?.type||"echo")}function Ks(e){let t=P(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function re(e){if(c(e)){if(Object.prototype.hasOwnProperty.call(e,"releaseAfterPrompt"))return e.releaseAfterPrompt;if(Object.prototype.hasOwnProperty.call(e,"disposeAfterPrompt"))return e.disposeAfterPrompt}}function qs(e){let t=String(e||"");if($s.test(t))return!0;let n=t.replace(/[^a-z0-9]/gi,"").toLowerCase();return n.endsWith("token")||n.endsWith("secret")||n.endsWith("password")||n.endsWith("apikey")||n.endsWith("privatekey")||n==="authorization"||n==="cookie"||n==="jwt"||n.includes("credential")}function se(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=te)return e;let n=e.length-te;return`${e.slice(0,te)}... [truncated ${n} characters]`}if(t>=Zt)return Array.isArray(e)?`[array truncated at depth ${Zt}, items=${e.length}]`:c(e)?`[object truncated at depth ${Zt}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let n=e.slice(0,Qt).map(r=>se(r,t+1));return e.length>Qt&&n.push(`[truncated ${e.length-Qt} items]`),n}if(c(e)){let n={};for(let[r,s]of Object.entries(e))n[r]=qs(r)?"[REDACTED]":se(s,t+1);return n}return String(e)}var Gs=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 zs(e){if(!c(e))return e;let t={};for(let n of Gs)A(e[n])&&(t[n]=e[n]);return t}function Js(e){if(!c(e))return e;let t={...e};return c(t.renderedPayload)&&(t.renderedPayload=zs(t.renderedPayload)),t}function Ws(e){let t=c(e)?e:{},n={};A(t.metadata)&&(n.metadata=Js(t.metadata));for(let[r,s]of Object.entries(t))Fs.has(r)||r==="metadata"||A(s)&&(n[r]=s);return n}function Vs(e){let t=c(e)?e:{},n=c(t.metadata)?t.metadata:{},r=c(n.renderedPayload)?n.renderedPayload:{};return c(t.resultContract)?t.resultContract:c(r.resultContract)?r.resultContract:{}}function gn(e){return a(Vs(e).kind).toLowerCase()==="decision"}function ln(e){let t=c(e)?e:{},n=c(t.metadata)?t.metadata:{};return ne(t.runtimeMaxSessions??n.runtimeMaxSessions)}function Xs(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:P(e)==="cli"}function dn(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return st(t,Ks(e))}function Ys(e,t){let n=c(e?.metadata)?{...e.metadata}:{},r=c(n._runtimeBridge)?{...n._runtimeBridge}:{},s=re(r);return n._runtimeBridge={...r,promptKind:"dispatch",finalTextOnly:Xs(t),releaseAfterPrompt:s===void 0?dn(t):st(s,dn(t)),requiresRuntimeResult:gn(e)},n}function Zs(e){let t=Ws(e);if(!A(t))return"";let n=JSON.stringify(se(t),null,2);if(n.length<=Yt)return n;let r=n.length-Yt;return`${n.slice(0,Yt)}
14
+ ... [truncated ${r} characters]`}function _n(e){if(!c(e))return"";let t=c(e.update)?e.update:e,r=(c(t.content)?t.content:{}).text??t.text;return r==null?"":String(r)}function Qs(e){if(!c(e))return"";let t=c(e.update)?e.update:e;return a(t.sessionUpdate)}function ti(e){if(!Array.isArray(e))return"";let t=!1,n=[],r=[],s=[],i=()=>{n.length>0&&(r.push(n),n=[])};for(let u of e){let l=Qs(u),d=_n(u);if(!l){d&&s.push(d);continue}if(t=!0,l==="agent_message_chunk"){d&&n.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 ie(s);let o=r[r.length-1]||[];return ie(o)}function ei(e){return Array.isArray(e)?e.map(_n).filter(t=>a(t)):[]}function ni(e){if(!c(e))return null;let t=c(e.update)?e.update:e;return a(t.sessionUpdate)!=="runtime_event"?null:c(t.event)?t.event:null}function ri(e){if(!c(e))return"";let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type);if(n==="event_msg"){if(r==="task_complete")return a(t.last_agent_message||t.message||t.output);if(r==="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 si(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let n=ri(ni(e[t]));if(n)return n}return""}function ie(e){let t="";for(let n of e){let r=String(n||"");if(r){if(!t)t=r;else if(r.startsWith(t))t=r;else if(!t.endsWith(r)){let s=rn(r)&&!/[\r\n]$/.test(t)?`
15
+ `:"";t+=`${s}${r}`}}}return t.trim()}function ii(e){let t=String(e||"").trim();if(!t)return"";let n=t.match(/(?:^|\n)#{1,3}\s+\S/);return!n||n.index===0?t:t.slice(n.index+(t[n.index]===`
16
+ `?1:0)).trim()}function fn(e){let t=String(e||"").trim();if(!t)return null;try{let n=JSON.parse(t);if(c(n)&&(Tn(n)||A(n._artifacts)||A(n.artifacts)||A(n._decision)||A(n._meta)))return n}catch{}return null}function Et(e){try{return sn(e)}catch{return null}}function mn(e){let t=String(e||"").trim();if(!t)return null;let n=Et(t);if(n)return n;let r=[...t.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];for(let s=r.length-1;s>=0;s-=1){let i=fn(r[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=fn(t.slice(s));if(i)return i}return null}function oi(e){let t=ei(e);for(let n=t.length-1;n>=0;n-=1){let r=Et(t[n]);if(r)return r}return Et(ie(t))}function Tn(e){if(!c(e))return!1;if(A(e.output))return!0;for(let t of["content","text","message","summary"])if(a(e[t]))return!0;return!!(hn(e.status)||a(e.error)||a(e.errorMessage))}function L(e){let t=c(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 ai(e){return c(e)?typeof(c(e._decision)?e._decision:c(e.decision)?e.decision:e).passed=="boolean":!1}function ci(e){return c(e)?c(e._decision)&&typeof e._decision.passed=="boolean"?!0:ai(e.output):!1}function ee(e,t,n){let r=c(e)?{...e}:{};if(!A(r.output)){for(let s of["summary","message","content","text"])if(a(r[s])){r.output=a(r[s]);break}}return!A(r.output)&&a(n)&&(r.output=a(n)),{...r,_meta:{...c(r._meta)?r._meta:{},runtimeOutputSource:t,requiredRuntimeResult:!0,finalMessagePreview:a(n).slice(0,1e3)}}}var ui=["dataUrl","dataURL","contentDataUrl","contentDataURL","contentBase64","base64","data"];function pn(e){if(!c(e))return"";let t=c(e.content)?e.content:{},n=c(e.metadata)?e.metadata:{};return a(e.fieldKey||e.field_key||t.fieldKey||n.fieldKey)}function li(e,t){let n=c(e.content)?e.content:{},r=c(t.content)?t.content:{},s={...e,...t,content:{...n,...r},metadata:{...c(e.metadata)?e.metadata:{},...c(t.metadata)?t.metadata:{}}};for(let i of ui)A(e[i])&&(s[i]=e[i]),A(n[i])&&(s.content[i]=n[i]);return s}function di(e,t){let n=Array.isArray(e)?e.filter(c):[],r=Array.isArray(t)?t.filter(c):[];if(!n.length)return r;if(!r.length)return n;let s=[...n],i=new Map;for(let u=0;u<n.length;u+=1){let l=pn(n[u]),d=i.get(l)||[];d.push(u),i.set(l,d)}let o=new Map;for(let u of r){let l=pn(u),d=o.get(l)||0;o.set(l,d+1);let f=i.get(l)?.[d];f===void 0?s.push(u):s[f]=li(s[f],u)}return s}function F(e,t,n){let r={...e,...t,_meta:{...c(e._meta)?e._meta:{},...c(t._meta)?t._meta:{},runtimeOutputSource:n}};return(Array.isArray(e._artifacts)||Array.isArray(t._artifacts))&&(r._artifacts=di(e._artifacts,t._artifacts)),r}function fi(e,t,n={}){let r=a(n.promptKind),s=n.requiresRuntimeResult===!0,i=s||r==="dispatch",o=L(e),u=typeof o.output=="string"?Et(o.output):null;if(u)return F(o,L(u),"result_block");let l=si(t),d=l?mn(l):null,f=i?oi(t):null;if(Tn(o))return hn(o.status)||a(o.error)||a(o.errorMessage)?o:r==="dispatch"&&d?F(o,L(d),"final_event"):r==="dispatch"&&f?F(o,L(f),"updates"):!s||ci(o)?o:d?F(o,L(d),"final_event"):f?F(o,L(f),"updates"):ee(o,"result",o.output);if(d)return F(o,L(d),"final_event");if(f)return F(o,L(f),"updates");if(l)return s?ee(o,"final_event",l):{...o,output:l,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let p=ii(ti(t));if(!p)return o;let h=mn(p);return h?F(o,L(h),"updates"):s?ee(o,"updates",p):{...o,output:p,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}var Ot=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=Q(),this.cleanupTimer=null,this.startSessionCleanup()}operationIdentity(t,n,r){let s=c(t.goalContract)?Xt(t.goalContract):a(t.goalContractHash),i=Ns("sha256").update(j({prompt:Array.isArray(t.prompt)?t.prompt:[],mcpServers:vs(t.mcpServers)})).digest("hex");return{agentId:n,sessionId:r,targetCode:a(t.targetCode||t.framework),workspace:a(t.workspace),goalContractHash:s,requestHash:i}}assertOperationIdentity(t,n,r,s){let i=this.operationIdentity(n,r,s),o=Object.keys(t.identity).find(u=>t.identity[u]!==i[u]);if(o)throw Object.assign(new Error(`runtime operation correlation conflict: ${t.correlationId}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT",field:o})}createOperation(t,n,r,s){let i={correlationId:t,agentId:r,sessionId:s,identity:this.operationIdentity(n,r,s),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,n={}){let r=()=>{if(n.onUpdate)for(let s of t.updates)n.onUpdate(s)};if(t.status==="completed")return r(),t.response;if(t.status==="failed")throw r(),t.error;n.onUpdate&&t.listeners.add(n.onUpdate);try{return r(),await new Promise((s,i)=>t.waiters.push({resolve:s,reject:i}))}finally{n.onUpdate&&t.listeners.delete(n.onUpdate)}}completeOperation(t,n){if(t.status==="running"){t.status="completed",t.response=n,t.completedAtMs=Date.now();for(let r of t.waiters.splice(0))r.resolve(n);t.listeners.clear()}}promptResponse(t,n,r,s,i){let o=c(t.metadata)?t.metadata:{},u=c(o._runtimeBridge)?o._runtimeBridge:{},l=fi(i,s,u),d=cn(t.goalContract,s,t.goalContractHash);return{sessionId:r,runtimeSessionId:n.runtimeSessionId,result:l,updates:s,...d?{verification:d}:{}}}failOperation(t,n){if(t.status!=="running")return;let r=n instanceof Error?n:Object.assign(new Error(String(n||"runtime operation failed")),{code:"RUNTIME_NODE_ERROR"});t.status="failed",t.error=r,t.completedAtMs=Date.now();for(let s of t.waiters.splice(0))s.reject(r);t.listeners.clear()}cleanupOperations(t=Date.now()){let n=D(this.config.operationTtlMs,Ls);for(let[r,s]of this.operations)s.status!=="running"&&t-(s.completedAtMs||s.createdAtMs)>n&&this.operations.delete(r)}targetFor(t){let n=a(t)||this.config.defaultTargetCode,r=this.targets[n];if(!n||!c(r)){let s=new Error(`runtime target is not configured: ${n||"<empty>"}`);throw s.code="RUNTIME_TARGET_NOT_FOUND",s}return{code:n,target:r}}targetIdleTtlMs(t){let r=P(t)==="openclaw"?D(this.config.openClawSessionIdleTtlMs,Ps):D(this.config.sessionIdleTtlMs,Us);return D(t?.sessionIdleTtlMs??t?.idleTtlMs,r)}targetMaxSessions(t,n=null){let s=P(t)==="openclaw"?D(this.config.openClawMaxSessions,Ds):D(this.config.maxSessionsPerTarget,ks),i=D(t?.maxSessions,s),o=ne(n);return o?Math.max(i,o):i}targetReleaseAfterPrompt(t,n={}){let r=P(t),s=c(n?._runtimeBridge)?n._runtimeBridge:{},i=re(s);return i!==void 0?st(i,!1):st(t?.releaseAfterPrompt??t?.disposeAfterPrompt,r==="openclaw")}promptReleaseAfterPrompt(t,n={}){let r=c(n?._runtimeBridge)?n._runtimeBridge:{},s=re(r);return s!==void 0?st(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=D(this.config.sessionCleanupIntervalMs,bs);t<=0||(this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions().catch(n=>{m("warn","runtime-bridge","runtime session cleanup failed",{error:String(n)})})},t),this.cleanupTimer.unref?.())}sessionCountForTarget(t){let n=0;for(let r of this.sessions.values())r.targetCode===t&&(n+=1);return n}sessionCountForAgentTarget(t,n){let r=0;for(let s of this.sessions.values())s.agentId===t&&s.targetCode===n&&(r+=1);return r}idleTargetSessions(t){return[...this.sessions.entries()].filter(([,n])=>n.targetCode===t&&!n.busy).sort((n,r)=>(n[1].lastUsedAtMs||0)-(r[1].lastUsedAtMs||0))}idleAgentTargetSessions(t,n){return[...this.sessions.entries()].filter(([,r])=>r.agentId===t&&r.targetCode===n&&!r.busy).sort((r,s)=>(r[1].lastUsedAtMs||0)-(s[1].lastUsedAtMs||0))}async closeSession(t,n="session_closed"){let r=this.sessions.get(t);if(!r)return!1;try{await r.runtime?.stop?.(n)}catch(s){m("warn","runtime-bridge","runtime session stop failed",{sessionId:r.sessionId,runtimeSessionId:r.runtimeSessionId,targetCode:r.targetCode,runtimeKind:r.runtimeKind,error:String(s)})}return this.sessions.delete(t),this.runtimeSessionIndex.delete(`${r.agentId}:${r.runtimeSessionId}`),m("info","runtime-bridge","runtime session closed",{sessionId:r.sessionId,runtimeSessionId:r.runtimeSessionId,targetCode:r.targetCode,runtimeKind:r.runtimeKind,reason:n}),!0}async closeAllSessions(t="bridge_shutdown"){for(let n of[...this.sessions.keys()])await this.closeSession(n,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[n,r]of[...this.sessions.entries()])r.busy||t-(r.lastUsedAtMs||r.createdAtMs||t)>r.idleTtlMs&&await this.closeSession(n,"idle_timeout")}async reserveTargetSlot(t,n,r={}){let s=a(r.agentId),i=ne(r.runtimeMaxSessions);if(s&&i)for(;this.sessionCountForAgentTarget(s,t)>=i;){let u=this.idleAgentTargetSessions(s,t);if(!u.length){let l=new Error(`runtime agent session limit reached: ${s}`);throw l.code="RUNTIME_AGENT_SESSION_LIMIT",l}await this.closeSession(u[0][0],"agent_session_limit")}let o=this.targetMaxSessions(n,i);for(;this.sessionCountForTarget(t)>=o;){let u=this.idleTargetSessions(t);if(!u.length){let l=new Error(`runtime target session limit reached: ${t}`);throw l.code="RUNTIME_TARGET_SESSION_LIMIT",l}await this.closeSession(u[0][0],"target_session_limit")}}async createAgent(t){let n=a(t.agentId);if(!n)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});let{code:r,target:s}=this.targetFor(t.targetCode||t.framework),i=this.agents.get(n);if(i&&i.targetCode!==r)throw Object.assign(new Error(`runtime agent target conflict: ${n}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});let o={agentId:n,targetCode:r,framework:a(t.framework||r),workspace:a(t.workspace),metadata:c(t.metadata)?t.metadata:{},createdAt:Q(),runtimeKind:P(s),runtimeMaxSessions:ln(t)};return this.agents.set(n,o),{agent:o}}runtimeFor(t,n){let{target:r}=this.targetFor(t.targetCode),s=P(r),i={onPermissionRequest:u=>this.requestPermission(u)},o={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs};return s==="stdio-acp"||s==="acp"?new J(t,r,i,o):s==="openclaw"?new dt(t,r,n,i,o):s==="cli"?new _t(t,r,o):new at(t)}async prompt(t,n={}){let r=a(t.agentId),s=a(t.sessionId)||Rt(),i=a(t.correlationId);if(!r)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});if(this.cleanupOperations(),i){let u=this.operations.get(i);if(u)return this.assertOperationIdentity(u,t,r,s),this.attachOperation(u,n);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,r,s):null;if(o){let u=this.attachOperation(o,n);return(async()=>{try{await this._promptOwned(t,{},o,r,s)}catch(l){let d=o.status==="completed";this.failOperation(o,l),d&&m("warn","runtime-bridge","runtime cleanup failed after operation completion",{correlationId:o.correlationId,error:String(l)})}})(),await u}return await this._promptOwned(t,n,o,r,s)}async _promptOwned(t,n,r,s,i){let o=this.agents.get(s),u=this.targetFor(t.targetCode||t.framework||o?.targetCode);if(o&&o.targetCode!==u.code)throw Object.assign(new Error(`runtime agent target conflict: ${s}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});if(P(u.target)==="cli"&&js(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 l=o||(await this.createAgent({agentId:s,targetCode:u.code,framework:t.framework,workspace:t.workspace,runtimeMaxSessions:t.runtimeMaxSessions,metadata:t.metadata})).agent,d=ln(t);d&&(l.runtimeMaxSessions=d);let f=a(t.workspace);f&&f!==l.workspace&&(l.workspace=f);let p=`${s}:${i}`;await this.cleanupExpiredSessions();let h=this.sessions.get(p);if(h&&h.targetCode!==u.code)throw Object.assign(new Error(`runtime session target conflict: ${i}`),{code:"RUNTIME_SESSION_TARGET_CONFLICT"});if(!h){let{code:_,target:T}=u;await this.reserveTargetSlot(_,T,{agentId:s,runtimeMaxSessions:l.runtimeMaxSessions});let w=this.runtimeFor(l,i),E=await w.sessionNew({cwd:l.workspace||process.cwd(),mcpServers:Array.isArray(t.mcpServers)?t.mcpServers:[],metadata:c(t.metadata)?t.metadata:{}}),y=Date.now();h={agentId:s,sessionId:i,runtime:w,targetCode:_,runtimeKind:P(T),runtimeSessionId:a(c(E)?E.sessionId:"")||i,idleTtlMs:this.targetIdleTtlMs(T),releaseAfterPrompt:this.targetReleaseAfterPrompt(T,t.metadata),createdAtMs:y,lastUsedAtMs:y,busy:!1,createdAt:Q()},this.sessions.set(p,h),this.runtimeSessionIndex.set(`${s}:${h.runtimeSessionId}`,h)}if(h.busy){let _=new Error(`runtime session is already running: ${i}`);throw _.code="RUNTIME_SESSION_BUSY",_}h.busy=!0,h.operationCorrelationId=r?.correlationId||null,h.lastUsedAtMs=Date.now();let g=r?.updates||[],I=_=>{let T=Bs(_,i,h);if(g.push(T),r)for(let w of r.listeners)try{w?.(T)}catch(E){m("warn","runtime-bridge","runtime operation update listener failed",{correlationId:r.correlationId,error:String(E)})}else n.onUpdate?.(T)},q=_=>{if(!(!r||r.status!=="running"||!c(_))){if(_.status==="failed"){let T=_.error;if(T instanceof Error){this.failOperation(r,T);return}let w=c(T)?T:{},E=Object.assign(new Error(a(w.message||_.message)||"runtime terminal failure"),{code:a(w.code||_.code)||"RUNTIME_TERMINAL_FAILED"});this.failOperation(r,E);return}this.completeOperation(r,this.promptResponse(t,h,i,g,c(_.result)?_.result:{stopReason:"end_turn"}))}};try{let _=an(t.goalContract),T=Array.isArray(t.prompt)?[...t.prompt]:[];_&&T.unshift({type:"text",text:_,metadata:{source:"orcha_goal_contract"}});let w=await h.runtime.sessionPrompt({sessionId:h.runtimeSessionId,prompt:T,metadata:c(t.metadata)?t.metadata:{}},I,q),E=this.promptResponse(t,h,i,g,w);return r&&this.completeOperation(r,E),E}finally{h.busy=!1,h.operationCorrelationId===r?.correlationId&&(h.operationCorrelationId=null),h.lastUsedAtMs=Date.now(),this.promptReleaseAfterPrompt(h,c(t.metadata)?t.metadata:{})&&await this.closeSession(p,"release_after_prompt")}}async cancel(t){let n=a(t.agentId),r=a(t.sessionId),s=a(t.correlationId);if(s){let u=this.operations.get(s);if(!u||u.status!=="running")return{cancelled:!1,correlationId:s,reason:"operation_not_running"};if(u.agentId!==n||u.sessionId!==r)throw Object.assign(new Error(`runtime operation cancellation identity conflict: ${s}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let l=this.sessions.get(`${n}:${r}`);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(`${n}:${r}`,"cancelled"),{cancelled:!0,correlationId:s})}let i=`${n}:${r}`,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,n={}){let r=a(t.agentId),s=a(t.taskId),i=a(t.executionId);if(!r||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let o=a(t.sessionId)||`dispatch-${i||s}`,u=a(t.instructions),l=Zs(t),d=gn(t),{target:f}=this.targetFor(t.targetCode||t.framework),p=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",u?`instructions: ${u}`:"",l?"orchaContext:":"",l,l?"Use orchaContext as the source of truth for upstream outputs, review reports, artifacts, and workflow metadata.":"","Follow the execution protocol in instructions exactly.","When embedding a generated artifact in final Markdown, use the Orcha artifact placeholder as the link target: orcha-artifact://<fieldKey>/<index>.","Example: use ![illustration](orcha-artifact://image/0) for the first generated image artifact.","Do not use local filesystem paths, file:// URLs, or data: URLs in final Markdown; Orcha replaces artifact placeholders after ingestion.",d?`For decision results, put the raw report between ${Qe} and ${tn}.`:"",d?`Then put a JSON object containing _decision between ${en} and ${nn}.`:"",d?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
17
+ `)}];return this.prompt({...t,agentId:r,sessionId:o,prompt:p,metadata:Ys(t,f)},n)}async requestPermission({agent:t,runtimeSessionId:n,request:r,emitUpdate:s}){let i=Rt(),u=this.runtimeSessionIndex.get(`${t.agentId}:${n}`)?.sessionId||n||Rt(),l={permissionId:i,agentId:t.agentId,sessionId:u,runtimeSessionId:n,request:c(r)?r:{},status:"pending",createdAt:Q()};return s?.({sessionId:n,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=S(r?.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 n=a(t.permissionId),r=this.pendingPermissions.get(n),s=a(t.outcome||"approved")||"approved";return r?(clearTimeout(r.timer),this.pendingPermissions.delete(n),r.resolve({permissionId:n,outcome:s,response:c(t.response)?t.response:{},userId:a(t.userId),metadata:c(t.metadata)?t.metadata:{}}),{accepted:!0,permissionId:n,outcome:s}):{accepted:!1,permissionId:n,outcome:s}}health(){return{status:"ok",bridgeVersion:z,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)}}};import mi from"node:http";import pi from"node:https";import{randomBytes as yn}from"node:crypto";var W=1,B=3,hi=1e4,It=class{constructor(t,n={}){this.url=t,this.readyState=0,this.socket=null,this.request=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,this.connectTimeoutMs=gi(n.connectTimeoutMs,hi),this.connectTimer=null,this.connect()}addEventListener(t,n){let r=this.listeners.get(t)||new Set;r.add(n),this.listeners.set(t,r)}emit(t,n={}){let r=this.listeners.get(t);if(r)for(let s of r)s(n)}connect(){let t=new URL(this.url),n=t.protocol==="wss:"?pi:mi,r=yn(16).toString("base64"),s=n.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":r,"Sec-WebSocket-Version":"13"}});this.request=s,this.startConnectTimer(s),s.on("upgrade",(i,o,u)=>{if(this.clearConnectTimer(),this.readyState===B){o.destroy();return}this.socket=o,this.readyState=W,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==B&&this.emit("error",{error:l,message:l.message,type:"error"}),this.onClose()}),u?.length&&this.onData(u),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!==B&&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===W||this.readyState===B)return;let n=`websocket connect timeout after ${this.connectTimeoutMs}ms`;this.emit("error",{message:n,type:"timeout"}),this.onClose(),t.destroy(new Error(n))},this.connectTimeoutMs),this.connectTimer.unref?.())}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}send(t){!this.socket||this.readyState!==W||this.socket.write(oe(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==B){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===W&&this.socket.write(oe(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==B&&(this.clearConnectTimer(),this.readyState=B,this.request=null,this.emit("close"))}onData(t){for(this.buffer=Buffer.concat([this.buffer,t]);this.buffer.length>=2;){let n=this.buffer[0],r=this.buffer[1],s=n&15,i=(r&128)!==0,o=r&127,u=2;if(o===126){if(this.buffer.length<u+2)return;o=this.buffer.readUInt16BE(u),u+=2}else if(o===127){if(this.buffer.length<u+8)return;let f=this.buffer.readUInt32BE(u),p=this.buffer.readUInt32BE(u+4);o=f*2**32+p,u+=8}let l=u;if(i&&(u+=4),this.buffer.length<u+o)return;let d=this.buffer.subarray(u,u+o);if(i){let f=this.buffer.subarray(l,l+4);d=Buffer.from(d.map((p,h)=>p^f[h%4]))}this.buffer=this.buffer.subarray(u+o),s===1?this.emit("message",{data:d.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write(oe(10,d))}}};function gi(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function oe(e,t){let n=t.length,r=2;n>=126&&n<=65535?r+=2:n>65535&&(r+=8);let s=yn(4),i=Buffer.alloc(r+4+n);i[0]=128|e;let o=2;n<126?i[1]=128|n:n<=65535?(i[1]=254,i.writeUInt16BE(n,o),o+=2):(i[1]=255,i.writeUInt32BE(Math.floor(n/2**32),o),i.writeUInt32BE(n>>>0,o+4),o+=8),s.copy(i,o),o+=4;for(let u=0;u<n;u+=1)i[o+u]=t[u]^s[u%4];return i}function _i(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 Ti(e){return Object.entries(e||{}).map(([t,n])=>({targetCode:t,targetName:a(n?.name||n?.targetName||t),targetType:a(n?.type||"echo"),status:"available"}))}var Ct=class{constructor(t,n){this.config=t,this.bridge=n,this.ws=null,this.stopped=!1,this.connected=!1,this.reconnectTimer=null}start(){this.connect()}stop(){this.stopped=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.ws?.close()}connect(){if(this.stopped)return;let t=_i(this.config.orchaUrl),n=new It(t,{connectTimeoutMs:this.config.connectTimeoutMs});this.ws=n,n.addEventListener("open",()=>{if(this.ws!==n||this.stopped){n.close();return}this.authenticate(n)}),n.addEventListener("message",r=>this.handleMessage(r.data,n)),n.addEventListener("close",()=>this.scheduleReconnect("close",n)),n.addEventListener("error",r=>{m("warn","orcha-client","runtime node websocket error",{error:String(r?.message||r?.type||r)})})}authenticate(t=this.ws){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:z,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,targets:Ti(this.config.targets)},t)}scheduleReconnect(t,n=this.ws){n&&this.ws!==n||(this.connected=!1,n&&this.ws===n&&(this.ws=null),!this.stopped&&(this.reconnectTimer||(m("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,n=this.ws){if(n&&this.ws!==n)return;let r;try{r=JSON.parse(String(t))}catch(s){m("warn","orcha-client","invalid Orcha websocket frame",{error:String(s)});return}if(c(r)){if(r.type==="runtime_node.authenticated"){if(n&&this.ws!==n)return;this.connected=!0,m("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:r.connectionId});return}if(r.type==="orcha.runtime.request"){await this.handleRequest(r);return}r.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString()})}}async handleRequest(t){let n=a(t.id),r=a(t.method),s=c(t.params)?t.params:{};try{let i=await this.invoke(r,s,n);this.send({type:"orcha.runtime.response",id:n,ok:!0,result:i})}catch(i){this.send({type:"orcha.runtime.response",id:n,ok:!1,error:{code:i.code||"RUNTIME_NODE_ERROR",message:i.message||String(i)}})}}async invoke(t,n,r){if(t==="health")return this.bridge.health();if(t==="agents/create")return this.bridge.createAgent(n);if(t==="agents/dispatch")return this.bridge.dispatch(n,{onUpdate:s=>this.sendUpdate(r,s)});if(t==="sessions/prompt")return this.bridge.prompt(n,{onUpdate:s=>this.sendUpdate(r,s)});if(t==="sessions/cancel")return this.bridge.cancel(n);if(t==="permissions/respond")return this.bridge.respondPermission(n);throw Object.assign(new Error(`unsupported Orcha runtime method: ${t}`),{code:"METHOD_NOT_FOUND"})}sendUpdate(t,n){this.send({type:"orcha.runtime.event",requestId:t,eventType:"runtime.update",payload:n})}send(t,n=this.ws){return!n||n!==this.ws||n.readyState!==W?!1:(n.send(JSON.stringify(t)),!0)}};import{existsSync as yi,readFileSync as Si}from"node:fs";import{resolve as Sn}from"node:path";var wi=/^[A-Za-z_][A-Za-z0-9_]*$/;function wn(e=process.env,t=process.cwd()){let n=a(e.ORCHA_RUNTIME_ENV_FILE),r=n?Sn(t,n):Sn(t,".env");if(!yi(r))return n&&m("warn","config","runtime env file not found",{path:r}),{loaded:!1,path:r,keys:[]};let s=[],i=Si(r,"utf8");for(let o of i.split(/\r?\n/)){let u=Ei(o);if(!u)continue;let[l,d]=u;Object.prototype.hasOwnProperty.call(e,l)||(e[l]=d,s.push(l))}return m("info","config","runtime env file loaded",{path:r,keyCount:s.length}),{loaded:!0,path:r,keys:s}}function Rn(e=process.env){return{mode:a(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),host:e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1",port:S(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:S(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),connectTimeoutMs:S(e.ORCHA_RUNTIME_CONNECT_TIMEOUT_MS||e.ORCHA_RUNTIME_WS_CONNECT_TIMEOUT_MS,1e4),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:S(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),sessionPromptTimeoutMs:S(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,36e5),permissionRequestTimeoutMs:S(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:S(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:S(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:S(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:S(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:S(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),targets:Ri(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function Ri(e){if(!a(e))return{};try{let t=JSON.parse(e);if(c(t))return t}catch(t){m("warn","config","invalid ORCHA_RUNTIME_TARGETS_JSON",{error:String(t)})}return{}}function Ei(e){let t=e.trim();if(!t||t.startsWith("#"))return null;let n=t.startsWith("export ")?t.slice(7).trimStart():t,r=n.indexOf("=");if(r<=0)return null;let s=n.slice(0,r).trim();if(!wi.test(s))return null;let i=Oi(n.slice(r+1).trim());return[s,i]}function Oi(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let n=e.slice(1,-1);return t==='"'?Ii(n):n}return Ci(e).trim()}function Ii(e){return e.replaceAll("\\n",`
18
+ `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function Ci(e){let t=!1,n=!1;for(let r=0;r<e.length;r+=1){let s=e[r],i=e[r-1];if(s==="'"&&!n)t=!t;else if(s==='"'&&!t&&i!=="\\")n=!n;else if(s==="#"&&!t&&!n&&/\s/.test(i||""))return e.slice(0,r)}return e}import{createServer as xi}from"node:http";function xt(e,t,n){let r=JSON.stringify(n);e.writeHead(t,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(r)}),e.end(r)}function K(e={}){return{ok:!0,...e}}function ae(e,t,n){return{ok:!1,error:{code:e,message:t,...n===void 0?{}:{detail:n}}}}async function En(e,t){let n=[],r=0;for await(let i of e){if(r+=i.length,r>t)throw Object.assign(new Error("request body too large"),{status:413,code:"REQUEST_TOO_LARGE"});n.push(i)}if(n.length===0)return{};let s=Buffer.concat(n).toString("utf8");if(!s.trim())return{};try{let i=JSON.parse(s);if(!c(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 On(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 In(e,t){let n={"GET /health":async()=>K(t.health()),"POST /agents/create":async r=>K(await t.createAgent(r)),"POST /agents/dispatch":async r=>K(await t.dispatch(r)),"POST /sessions/prompt":async r=>K(await t.prompt(r)),"POST /sessions/cancel":async r=>K(await t.cancel(r)),"POST /permissions/respond":async r=>K(await t.respondPermission(r))};return xi(async(r,s)=>{let i=new URL(r.url||"/",`http://${r.headers.host||`${e.host}:${e.port}`}`),o=`${r.method||"GET"} ${i.pathname}`,u=n[o];if(!u){xt(s,404,ae("NOT_FOUND",`No route for ${o}`));return}try{On(r,e.token);let l=r.method==="GET"?{}:await En(r,e.requestLimitBytes);xt(s,200,await u(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";xt(s,d,ae(f,l.message||String(l)))}})}var Pi=Li(import.meta.url),Di=".orcha-runtime-bridge.pid",Fi=".orcha-runtime-bridge.log",$i=3,Hi=36e5,{command:vi,options:Pn}=qi(process.argv.slice(2));Gi(Pn);wn();var ji=Rn();await Bi(vi,ji,Pn);async function Bi(e,t,n){switch(e){case"run":case"foreground":xn(t);return;case"start":if(n.foreground){xn(t);return}Nn();return;case"reload":case"restart":await Mn({quiet:!0}),Nn();return;case"stop":await Mn();return;case"status":Ki();return;case"help":case"--help":case"-h":Vi();return;default:throw new Error(`Unknown command: ${e}`)}}function xn(e){zi();let t=new Ot(e);if(e.mode==="server"){let r=In(e,t);An({bridge:t,server:r}),r.listen(e.port,e.host,()=>{m("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 n=new Ct(e,t);An({bridge:t,client:n}),n.start(),m("info","runtime-bridge","Orcha runtime node started",{nodeId:e.nodeId,nodeName:e.nodeName,orchaUrl:e.orchaUrl,targets:Object.keys(t.targets)})}function An({bridge:e,client:t,server:n}){let r=!1,s=i=>{if(r)return;r=!0;let o=Number(e?.sessions?.size||0)>0;m("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(u){m("warn","runtime-bridge","runtime client stop failed",{error:String(u)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(u=>{m("warn","runtime-bridge","runtime bridge stop failed",{error:String(u)})}).finally(()=>{try{n?.close?.()}catch(u){m("warn","runtime-bridge","runtime server close failed",{error:String(u)})}}),setTimeout(()=>process.exit(0),o?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function Nn(){let e=fe(),t=Dn(),n=me(e);if(n&&V(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:e,logFile:t}));return}n&&le(e),bn(e),bn(t),ue(t);let r=Ui(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=Ai(process.execPath,[Pi,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",r,r]});i.unref(),Ni(r),Ln(e,`${i.pid}
19
+ `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function Mn({quiet:e=!1}={}){let t=fe(),n=me(t);if(!n){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!V(n)){le(t),e||console.log(JSON.stringify({status:"not_running",pid:n,pidFile:t}));return}process.kill(n,"SIGTERM"),!await Un(n,1e4)&&V(n)&&(process.kill(n,"SIGKILL"),await Un(n,3e3)),le(t),e||console.log(JSON.stringify({status:"stopped",pid:n,pidFile:t}))}function Ki(){let e=fe(),t=Dn(),n=me(e),r=!!(n&&V(n));console.log(JSON.stringify({status:r?"running":"not_running",running:r,pid:r?n:null,pidFile:e,logFile:t}))}function qi(e){let t=[],n={};for(let s=0;s<e.length;s+=1){let i=e[s];i==="--daemon"?n.daemon=!0:i==="--foreground"?n.foreground=!0:i==="--env-file"?n.envFile=e[++s]:i==="--pid-file"?n.pidFile=e[++s]:i==="--log-file"?n.logFile=e[++s]:t.push(i)}return{command:t[0]||"run",options:n}}function Gi(e){e.envFile&&(process.env.ORCHA_RUNTIME_ENV_FILE=e.envFile),e.pidFile&&(process.env.ORCHA_RUNTIME_PID_FILE=e.pidFile),e.logFile&&(process.env.ORCHA_RUNTIME_LOG_FILE=e.logFile)}function fe(){return de(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Di)}function Dn(){return de(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||Fi)}function zi(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=Fn();if(t<=0)return;let n=de(process.cwd(),e);ue(n,t);let r=Wi();r<=0||setInterval(()=>ue(n,t),r).unref()}function ue(e,t=Fn()){if(t<=0||!kn(e))return;let n=0,r="";try{if(n=Cn(e).size,n<=0)return;r=ce(e,"utf8")}catch(d){m("warn","runtime-bridge","runtime log cleanup skipped",{logFile:e,error:String(d)});return}let s=Date.now()-t*24*60*60*1e3,i=r.split(/\r?\n/),o=[],u=0;for(let d of i)d&&(Ji(d,s)?o.push(d):u+=1);if(u===0)return;let l="";try{Cn(e).size>n&&(l=ce(e,"utf8").slice(r.length));let f=[...o,...l.split(/\r?\n/).filter(Boolean)].join(`
20
+ `);Ln(e,f?`${f}
21
+ `:""),m("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:u})}catch(d){m("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(d)})}}function Ji(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object")return!0;let r=typeof n.ts=="string"?Date.parse(n.ts):Number.NaN;return!Number.isFinite(r)||r>=t}catch{return!0}}function Fn(){return $n(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,$i)}function Wi(){return $n(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Hi)}function $n(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function me(e){if(!kn(e))return null;let t=Number.parseInt(ce(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function V(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Un(e,t){let n=Date.now();for(;Date.now()-n<t;){if(!V(e))return!0;await new Promise(r=>setTimeout(r,100))}return!V(e)}function bn(e){Mi(ki(e),{recursive:!0})}function le(e){try{bi(e,{force:!0})}catch{}}function Vi(){console.log(`Usage: orcha-runtime-bridge [command] [options]
21
22
 
22
23
  Commands:
23
24
  run, foreground Run in the foreground. This is the default.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orcha-ai/runtime-bridge",
3
- "version": "0.1.28",
3
+ "version": "0.1.29",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local Orcha runtime bridge for ACP-compatible agent runtimes.",