@orcha-ai/runtime-bridge 0.1.20 → 0.1.21

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,22 +1,22 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as hs}from"node:child_process";import{closeSync as ms,existsSync as Ve,mkdirSync as gs,openSync as Ts,readFileSync as Bt,rmSync as _s,statSync as Ge,writeFileSync as Ye}from"node:fs";import{dirname as ys,resolve as qt}from"node:path";import{fileURLToPath as Ss}from"node:url";import{randomUUID as lt}from"node:crypto";var B="0.1.20";function j(){return new Date().toISOString()}function R(e,t=2){return String(e).padStart(t,"0")}function Zt(e){let t=e>=0?"+":"-",n=Math.abs(e);return`${t}${R(Math.floor(n/60))}:${R(n%60)}`}function sn(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${R(e.getMonth()+1)}-${R(e.getDate())}`,`T${R(e.getHours())}:${R(e.getMinutes())}:${R(e.getSeconds())}.${R(e.getMilliseconds(),3)}`,Zt(t)].join("")}function on(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 an(e,t){let n=on(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}-${R(n.month)}-${R(n.day)}`,`T${R(n.hour)}:${R(n.minute)}:${R(n.second)}.${R(e.getMilliseconds(),3)}`,Zt(s)].join("")}function cn(e=new Date){let t=a(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return an(e,t)}catch{return sn(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 w(e){return Array.isArray(e)?e.map(String):[]}var un="[redacted]",ln=/(authorization|api[_-]?key|credential|password|secret|token)/i;function K(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 r={name:e.name,message:e.message};e.stack&&(r.stack=e.stack);for(let s of Object.keys(e))r[s]=K(e[s],t);return t.delete(e),r}if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e)){let r=e.map(s=>K(s,t));return t.delete(e),r}let n={};for(let[r,s]of Object.entries(e))n[r]=ln.test(r)?un:K(s,t);return t.delete(e),n}function Qt(e,t=4e3){let n=JSON.stringify(K(e))??String(e);return!Number.isFinite(t)||n.length<=t?n:`${n.slice(0,t)}...`}function p(e,t,n,r={}){let s={ts:cn(),level:e,module:t,msg:n,...c(r)?K(r):{}};console.error(JSON.stringify(s))}function Z(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 Q=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=Z(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 dn}from"node:child_process";var W="2.0",fn=3e4;function pn(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 hn(e){if(!c(e))return new Error(String(e||"runtime error"));let t=a(e.message)||"runtime error",n="data"in e?Qt(e.data,4e3):"",r=new Error(n?`${t}; data=${n}`:t);return r.rpcCode=e.code,r.data=e.data,r}function mn(e){return c(e)&&"id"in e&&!("method"in e)}function gn(e){return c(e)&&typeof e.method=="string"&&"id"in e}function Tn(e){return c(e)&&typeof e.method=="string"&&!("id"in e)}var tt=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=dn(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 _s}from"node:child_process";import{closeSync as ys,existsSync as Qe,mkdirSync as Ss,openSync as Rs,readFileSync as Gt,rmSync as ws,statSync as je,writeFileSync as tn}from"node:fs";import{dirname as Es,resolve as jt}from"node:path";import{fileURLToPath as xs}from"node:url";import{randomUUID as dt}from"node:crypto";var B="0.1.20";function j(){return new Date().toISOString()}function w(e,t=2){return String(e).padStart(t,"0")}function te(e){let t=e>=0?"+":"-",n=Math.abs(e);return`${t}${w(Math.floor(n/60))}:${w(n%60)}`}function cn(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)}`,te(t)].join("")}function un(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 ln(e,t){let n=un(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)}`,te(s)].join("")}function dn(e=new Date){let t=a(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return ln(e,t)}catch{return cn(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 E(e){return Array.isArray(e)?e.map(String):[]}var fn="[redacted]",pn=/(authorization|api[_-]?key|credential|password|secret|token)/i;function K(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 r={name:e.name,message:e.message};e.stack&&(r.stack=e.stack);for(let s of Object.keys(e))r[s]=K(e[s],t);return t.delete(e),r}if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e)){let r=e.map(s=>K(s,t));return t.delete(e),r}let n={};for(let[r,s]of Object.entries(e))n[r]=pn.test(r)?fn:K(s,t);return t.delete(e),n}function ee(e,t=4e3){let n=JSON.stringify(K(e))??String(e);return!Number.isFinite(t)||n.length<=t?n:`${n.slice(0,t)}...`}function p(e,t,n,r={}){let s={ts:dn(),level:e,module:t,msg:n,...c(r)?K(r):{}};console.error(JSON.stringify(s))}function Q(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 tt=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=Q(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 hn}from"node:child_process";var W="2.0",mn=3e4;function gn(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 Tn(e){if(!c(e))return new Error(String(e||"runtime error"));let t=a(e.message)||"runtime error",n="data"in e?ee(e.data,4e3):"",r=new Error(n?`${t}; data=${n}`:t);return r.rpcCode=e.code,r.data=e.data,r}function _n(e){return c(e)&&"id"in e&&!("method"in e)}function yn(e){return c(e)&&typeof e.method=="string"&&"id"in e}function Sn(e){return c(e)&&typeof e.method=="string"&&!("id"in e)}var et=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=hn(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
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(mn(t)){this.resolveResponse(t);return}if(gn(t)){this.handleRequest(t);return}Tn(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(hn(t.error))):r.resolve(t.result))}async handleRequest(t){let n=this.requestHandlers.get(t.method);if(!n){this.writeFrame({jsonrpc:W,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:W,id:t.id,result:r??{}})}catch(r){this.writeFrame({jsonrpc:W,id:t.id,error:pn(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=fn){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:W,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:W,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){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(_n(t)){this.resolveResponse(t);return}if(yn(t)){this.handleRequest(t);return}Sn(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(Tn(t.error))):r.resolve(t.result))}async handleRequest(t){let n=this.requestHandlers.get(t.method);if(!n){this.writeFrame({jsonrpc:W,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:W,id:t.id,result:r??{}})}catch(r){this.writeFrame({jsonrpc:W,id:t.id,error:gn(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=mn){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:W,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:W,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 ne}from"node:crypto";import{existsSync as _n,readFileSync as yn,realpathSync as te,statSync as Sn}from"node:fs";import{basename as re,extname as se,isAbsolute as xn,relative as Rn}from"node:path";var wn=25*1024*1024;function ie(e,t=""){let n=a(t);if(n)return n;let r=se(a(e)).toLowerCase();return r===".jpg"||r===".jpeg"?"image/jpeg":r===".webp"?"image/webp":r===".gif"?"image/gif":"image/png"}function oe(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 et(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function En(e,t){let n=Rn(t,e);return n===""||!!n&&!n.startsWith("..")&&!xn(n)}function In(e,t){let n=a(e);if(!n||!_n(n))return"";try{let r=te(n);for(let s of t)try{let i=te(s);if(En(r,i))return r}catch{}}catch{return""}return""}function Rt(e,t,n={}){let r=a(e);return!r||r.startsWith("data:")||/^https?:\/\//i.test(r)?r:Cn(r,t,n)}function Cn(e,t,n={}){let r=[...et(n.trustedFileRoots),...et(n.trustedFileRoot),...et(n.artifactRoots),...et(n.artifactRoot)],s=In(e,r);if(!s)return"";try{let i=Sn(s);return!i.isFile()||i.size<=0||i.size>wn?"":`data:${t};base64,${yn(s).toString("base64")}`}catch{return""}}function _(...e){for(let t of e){let n=a(t);if(n)return n}return""}function On(e,t,n,r){let s=n.toLowerCase();if(s==="image"||s==="picture")return!0;let i=_(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=se(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function Et(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=_(r.call_id,r.id),u=_(r.saved_path,r.savedPath),l=_(r.revised_prompt,r.revisedPrompt),d=ie(u,r.mimeType||r.mime_type),f=oe(r.result,d)||Rt(u,d,t);if(!f)return null;let h=f.startsWith("data:")?f:"",m=u?re(u):`${o||ne()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:m||"Generated image",summary:l||"Generated image",content:{prompt:l||void 0,dataUrl:h||void 0,imageUrl:f,previewUrl:f,fileUrl:f,mimeType:d},dataUrl:h||void 0,previewUrl:f,fileUrl:f,metadata:{source:n,eventType:i,callId:o||void 0,savedPath:u||void 0,filename:m,mimeType:d,revisedPrompt:l||void 0}}}function An(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 Mn(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=_(r.saved_path,r.savedPath,s.saved_path,s.savedPath,i.savedPath),u=_(r.mimeType,r.mime_type,s.mimeType,s.mime_type,i.mimeType),l=_(r.artifactType,r.artifact_type,r.type,r.kind,s.type,o?"image":"file"),d=On(r,s,l,o),f=d?ie(o,u):u;if(d){let E=_(r.dataUrl,s.dataUrl),O=E.startsWith("data:")?E:"",N=_(r.imageUrl,r.previewUrl,r.fileUrl,r.downloadUrl,r.url,r.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),g=oe(r.result??s.result,f)||O||Rt(o,f,t)||Rt(N,f,t);g&&(g.startsWith("data:")&&(s.dataUrl||=g),s.imageUrl||=g,s.previewUrl||=g,s.fileUrl||=g,f&&(s.mimeType||=f))}for(let[E,O]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let N=r[E];N!=null&&N!==""&&!(O in s)&&(s[O]=N)}let h=_(r.fileUrl,r.downloadUrl,r.imageUrl,r.dataUrl,r.url,r.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),m=_(r.previewUrl,r.imageUrl,r.dataUrl,r.url,r.fileUrl,r.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),y=_(r.dataUrl,s.dataUrl,h.startsWith("data:")?h:"",m.startsWith("data:")?m:""),S=_(r.filename,i.filename,o?re(o):""),U=_(r.fieldKey,r.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...r,artifactType:l,type:r.type||l,fieldKey:U,title:_(r.title,S,"Runtime artifact"),summary:_(r.summary,s.prompt,r.title,S,"Runtime artifact"),content:s,dataUrl:y||void 0,fileUrl:h||void 0,previewUrl:m||void 0,metadata:{...i,source:_(i.source,n),savedPath:o||i.savedPath,filename:S||i.filename,mimeType:f||i.mimeType}}}function nt(e,t){if(!t||!e)return;let n=c(t.metadata)?t.metadata:{},r=_(n.savedPath,n.callId,t.previewUrl,t.fileUrl)||ne(),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 wt(e,t,n={}){for(let r of An(e))nt(t,Mn(r,n))}function It(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 ee(e,t,n){if(!c(e))return e;let r=c(e.event)?e.event:null;return r?(nt(t,Et(r,n)),{...e,event:It(r)}):e}function ae(e,t,n={}){if(!c(e))return e;wt(e,t,n);let r=ee(e,t,n),s=c(r.update)?ee(r.update,t,n):null;return s&&s!==r.update&&(r={...r,update:s}),r}function ce(e,t,n={}){let r=c(e)?{...e}:{};wt(r,t,n),wt(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 tt({command:t,args:w(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:B},...c(this.target.initializeParams)?this.target.initializeParams:{}}})}async sessionNew(t={}){await this.ensureStarted();let n=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return this.proc.call("session/new",{...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 ce(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),...w(this.target.trustedArtifactRoots),...w(this.target.trustedFileRoots),...w(this.target.artifactRoots),...w(this.target.artifactFileRoots)].filter(Boolean)}}async stop(t){await this.proc?.stop(t)}};function Un(e){let t=c(e.metadata)?e.metadata:{};return a(t.agentCode)}function Nn(e,t){let n=Un(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var rt=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",Nn(t,o)];super(t,{...n,command:u,args:d},s,i)}};import{spawn as bn}from"node:child_process";import{randomUUID as J}from"node:crypto";import{existsSync as pe,mkdirSync as kn,readdirSync as he,readFileSync as me,realpathSync as at,rmSync as Pn,rmdirSync as Ln,statSync as Fn,unlinkSync as Dn}from"node:fs";import{homedir as $n,tmpdir as ge}from"node:os";import{basename as Te,dirname as Hn,join as A,resolve as ue}from"node:path";var vn=36e5,Bn=5e3,zn=2*60*1e3,Gn=2*60*1e3,qn=12,Kn=1e3,jn=1500,st=24*60*60*1e3,le=new Set(["final_answer","final","complete","completed","done"]);function it(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 _e(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 ye(e,t={}){return Et(e,{source:"codex_cli_image_generation",...t})}function Se(e,t){nt(e.artifacts,t)}function xe(e){return It(e)}function Re(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"?le.has(s):!1}function Wn(e,t,n){return n.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:n.captureLastMessage===!0?!0:Te(e)==="codex"}function Jn(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:Te(e)==="codex"}function we(e){return Math.max(20,T(e.codexTranscriptPollMs||e.transcriptPollMs,Kn))}function Xn(e){return Math.max(0,T(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,jn))}function ct(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 Mt(e){let t=c(e?.metadata)?e.metadata:{};return c(t._runtimeBridge)?t._runtimeBridge:{}}function Ct(e){return a(Mt(e).promptKind).toLowerCase()}function Vn(e,t){for(let n of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let r=ct(n);if(r!=null)return r}return Ct(t)==="chat"}function Yn(e,t){let n=Mt(e);for(let s of[n.emitThoughtChunks,n.streamThoughts]){let i=ct(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=ct(s);if(i!=null)return i}return Ct(e)==="chat"}function Zn(e){let t=Mt(e);for(let n of[t.finalTextOnly,t.finalOutputOnly]){let r=ct(n);if(r!=null)return r}return null}function Qn(e,t){let n=Zn(e);return n??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function tr(e,t){return!e.finalTextOnly||t}function er(e,t,n,r=new Set){return{target:e,promptText:t,startedAtMs:n,baselinePaths:r,matchedPath:"",disabled:!1,processedLines:new Map}}function nr(e,t){let n=c(e.env)?e.env:{},r=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||n.ORCHA_RUNTIME_ARTIFACT_DIR)||A(ge(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||J(),i=A(r,s),o=A(i,J());return kn(o,{recursive:!0}),{root:o,realRoot:at(o),sessionRoot:i,realSessionRoot:at(i)}}function Ee(e){return a(c(e)?e.root:e)}function de(e){let t=Ee(e),n=a(c(e)?e.sessionRoot:Hn(t)),r=a(c(e)?e.realSessionRoot:"");if(n)try{if(r&&at(n)!==r)return;Ln(n)}catch{}}function rr(e,t={}){let n=Ee(e),r=a(c(e)?e.realRoot:"");if(n){try{if(r&&at(n)!==r){p("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:n});return}}catch{de(e);return}try{Pn(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}de(e)}}function sr(e,t){return{trustedFileRoots:[t,...w(e.trustedArtifactRoots),...w(e.trustedFileRoots),...w(e.artifactRoots),...w(e.artifactFileRoots)].filter(Boolean)}}function Ie(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)||A($n(),".codex");return A(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 A(e,r,s,i)}function Ce(e,t,n){let r=new Set;for(let s of[t-st,t,t+st,n-st,n,n+st])r.add(ir(e,s));return[...r].filter(s=>pe(s))}function or(e,t,n){let r=Ie(e),s=t-zn,i=n+Gn,o=[];for(let u of Ce(r,t,n)){let l=[];try{l=he(u)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=A(u,d);try{let h=Fn(f);if(!h.isFile()||h.mtimeMs<s||h.mtimeMs>i)continue;o.push({path:f,mtimeMs:h.mtimeMs})}catch{}}}return o.sort((u,l)=>l.mtimeMs-u.mtimeMs).slice(0,qn)}function ar(e,t,n=t){let r=Ie(e),s=new Set;for(let i of Ce(r,t,n)){let o=[];try{o=he(i)}catch{continue}for(let u of o)u.endsWith(".jsonl")&&s.add(A(i,u))}return s}function Ot(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)Ot(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&&Ot(e[r],t,n+1)}}function Oe(e){return a(e).replace(/\s+/g," ")}function cr(e){let t=Oe(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 ur(e,t){let n=cr(t);if(!n.length)return!1;let r=[];for(let i of e)Ot(i,r);let s=Oe(r.join(" "));return n.every(i=>s.includes(i))}function lr(e){return e.find(t=>c(t)&&a(t.type)==="session_meta"&&c(t.payload))||null}function dr(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 fr(e,t,n){if(!ur(e,t.promptText))return!1;let r=lr(e);if(!r)return!1;let s=r.payload,i=a(s.originator),o=a(s.source);if(i!=="codex_exec"&&o!=="exec")return!1;let u=dr(r);if(!Number.isFinite(u)||u<t.startedAtMs-5e3||u>n+5e3)return!1;let l=a(t.target.cwd),d=a(s.cwd);return!(l&&d&&ue(l)!==ue(d))}function fe(e){try{return hr(me(e,"utf8"))}catch{return null}}function pr(e,t,n){if(!e||e.disabled)return null;if(e.matchedPath){let s=fe(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let r=[];for(let s of or(e.target,e.startedAtMs,n)){if(e.baselinePaths.has(s.path))continue;let i=fe(s.path);!i||!fr(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 hr(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 mr(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 gr(e,t,n,r){let s=_e(e),i=Re(e),o=0,u=0,l=0;if(s&&!i&&t.emitThoughtChunks&&!t.emittedThoughtTexts.has(s)&&(t.emittedThoughtTexts.add(s),l=1,r({sessionId:n,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:s}}})),s&&i&&!t.emittedTexts.has(s)){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"&&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 se}from"node:crypto";import{existsSync as Rn,readFileSync as wn,realpathSync as ne,statSync as En}from"node:fs";import{basename as ie,extname as oe,isAbsolute as xn,relative as In}from"node:path";var Cn=25*1024*1024;function ae(e,t=""){let n=a(t);if(n)return n;let r=oe(a(e)).toLowerCase();return r===".jpg"||r===".jpeg"?"image/jpeg":r===".webp"?"image/webp":r===".gif"?"image/gif":"image/png"}function ce(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 nt(e){if(Array.isArray(e))return e.map(a).filter(Boolean);let t=a(e);return t?[t]:[]}function On(e,t){let n=In(t,e);return n===""||!!n&&!n.startsWith("..")&&!xn(n)}function An(e,t){let n=a(e);if(!n||!Rn(n))return"";try{let r=ne(n);for(let s of t)try{let i=ne(s);if(On(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:Mn(r,t,n)}function Mn(e,t,n={}){let r=[...nt(n.trustedFileRoots),...nt(n.trustedFileRoot),...nt(n.artifactRoots),...nt(n.artifactRoot)],s=An(e,r);if(!s)return"";try{let i=En(s);return!i.isFile()||i.size<=0||i.size>Cn?"":`data:${t};base64,${wn(s).toString("base64")}`}catch{return""}}function _(...e){for(let t of e){let n=a(t);if(n)return n}return""}function Un(e,t,n,r){let s=n.toLowerCase();if(s==="image"||s==="picture")return!0;let i=_(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=oe(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function It(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=_(r.call_id,r.id),u=_(r.saved_path,r.savedPath),l=_(r.revised_prompt,r.revisedPrompt),d=ae(u,r.mimeType||r.mime_type),f=ce(r.result,d)||Et(u,d,t);if(!f)return null;let h=f.startsWith("data:")?f:"",m=u?ie(u):`${o||se()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:m||"Generated image",summary:l||"Generated image",content:{prompt:l||void 0,dataUrl:h||void 0,imageUrl:f,previewUrl:f,fileUrl:f,mimeType:d},dataUrl:h||void 0,previewUrl:f,fileUrl:f,metadata:{source:n,eventType:i,callId:o||void 0,savedPath:u||void 0,filename:m,mimeType:d,revisedPrompt:l||void 0}}}function Nn(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 bn(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=_(r.saved_path,r.savedPath,s.saved_path,s.savedPath,i.savedPath),u=_(r.mimeType,r.mime_type,s.mimeType,s.mime_type,i.mimeType),l=_(r.artifactType,r.artifact_type,r.type,r.kind,s.type,o?"image":"file"),d=Un(r,s,l,o),f=d?ae(o,u):u;if(d){let x=_(r.dataUrl,s.dataUrl),O=x.startsWith("data:")?x:"",N=_(r.imageUrl,r.previewUrl,r.fileUrl,r.downloadUrl,r.url,r.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),g=ce(r.result??s.result,f)||O||Et(o,f,t)||Et(N,f,t);g&&(g.startsWith("data:")&&(s.dataUrl||=g),s.imageUrl||=g,s.previewUrl||=g,s.fileUrl||=g,f&&(s.mimeType||=f))}for(let[x,O]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let N=r[x];N!=null&&N!==""&&!(O in s)&&(s[O]=N)}let h=_(r.fileUrl,r.downloadUrl,r.imageUrl,r.dataUrl,r.url,r.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),m=_(r.previewUrl,r.imageUrl,r.dataUrl,r.url,r.fileUrl,r.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),y=_(r.dataUrl,s.dataUrl,h.startsWith("data:")?h:"",m.startsWith("data:")?m:""),S=_(r.filename,i.filename,o?ie(o):""),U=_(r.fieldKey,r.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...r,artifactType:l,type:r.type||l,fieldKey:U,title:_(r.title,S,"Runtime artifact"),summary:_(r.summary,s.prompt,r.title,S,"Runtime artifact"),content:s,dataUrl:y||void 0,fileUrl:h||void 0,previewUrl:m||void 0,metadata:{...i,source:_(i.source,n),savedPath:o||i.savedPath,filename:S||i.filename,mimeType:f||i.mimeType}}}function rt(e,t){if(!t||!e)return;let n=c(t.metadata)?t.metadata:{},r=_(n.savedPath,n.callId,t.previewUrl,t.fileUrl)||se(),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 xt(e,t,n={}){for(let r of Nn(e))rt(t,bn(r,n))}function Ct(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?(rt(t,It(r,n)),{...e,event:Ct(r)}):e}function ue(e,t,n={}){if(!c(e))return e;xt(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 le(e,t,n={}){let r=c(e)?{...e}:{};xt(r,t,n),xt(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 et({command:t,args:E(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:B},...c(this.target.initializeParams)?this.target.initializeParams:{}}})}async sessionNew(t={}){await this.ensureStarted();let n=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return this.proc.call("session/new",{...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(ue(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 le(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),...E(this.target.trustedArtifactRoots),...E(this.target.trustedFileRoots),...E(this.target.artifactRoots),...E(this.target.artifactFileRoots)].filter(Boolean)}}async stop(t){await this.proc?.stop(t)}};function kn(e){let t=c(e.metadata)?e.metadata:{};return a(t.agentCode)}function Pn(e,t){let n=kn(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var st=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",Pn(t,o)];super(t,{...n,command:u,args:d},s,i)}};import{spawn as Ln}from"node:child_process";import{randomUUID as J}from"node:crypto";import{existsSync as me,mkdirSync as Fn,readdirSync as ge,readFileSync as Te,realpathSync as ct,rmSync as Dn,rmdirSync as $n,statSync as Hn,unlinkSync as vn}from"node:fs";import{homedir as Bn,tmpdir as _e}from"node:os";import{basename as ye,dirname as zn,join as A,resolve as de}from"node:path";var Gn=36e5,qn=5e3,Kn=2*60*1e3,jn=2*60*1e3,Wn=12,Jn=1e3,Xn=1500,it=24*60*60*1e3,X=new Set(["final_answer","final","complete","completed","done"]);function ot(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 Se(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 Re(e,t={}){return It(e,{source:"codex_cli_image_generation",...t})}function we(e,t){rt(e.artifacts,t)}function Ee(e){return Ct(e)}function Ut(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"?X.has(s):!1}function fe(e){return c(e)?a(e.phase||e.status||e.stage).toLowerCase():""}function Vn(e){if(!c(e)||Ut(e))return!1;let t=c(e.payload)?e.payload:{},n=a(e.type),r=a(t.type),s=fe(t);if(n==="event_msg"&&r==="agent_message"||n==="response_item"&&r==="message"&&a(t.role)==="assistant")return!!(s&&!X.has(s));let i=c(e.item)?e.item:{},o=fe(i);return a(i.role)==="assistant"||a(i.type)==="message"?!!(o&&!X.has(o)):!1}function Yn(e,t,n){return n.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:n.captureLastMessage===!0?!0:ye(e)==="codex"}function Zn(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:ye(e)==="codex"}function xe(e){return Math.max(20,T(e.codexTranscriptPollMs||e.transcriptPollMs,Jn))}function Qn(e){return Math.max(0,T(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,Xn))}function ut(e){if(typeof e=="boolean")return e;let t=a(e).toLowerCase();return["true","1","yes","y","on"].includes(t)?!0:["false","0","no","n","off"].includes(t)?!1:null}function Nt(e){let t=c(e?.metadata)?e.metadata:{};return c(t._runtimeBridge)?t._runtimeBridge:{}}function Ot(e){return a(Nt(e).promptKind).toLowerCase()}function tr(e,t){for(let n of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let r=ut(n);if(r!=null)return r}return Ot(t)==="chat"}function er(e,t){let n=Nt(e);for(let s of[n.emitThoughtChunks,n.streamThoughts]){let i=ut(s);if(i!=null)return i}let r=Ot(e);if(r&&r!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=ut(s);if(i!=null)return i}return Ot(e)==="chat"}function nr(e){let t=Nt(e);for(let n of[t.finalTextOnly,t.finalOutputOnly]){let r=ut(n);if(r!=null)return r}return null}function rr(e,t){let n=nr(e);return n??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function sr(e,t){return!e.finalTextOnly||t}function Ie(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 Ce(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 ir(e,t,n,r=new Set){return{target:e,promptText:t,startedAtMs:n,baselinePaths:r,matchedPath:"",disabled:!1,processedLines:new Map}}function or(e,t){let n=c(e.env)?e.env:{},r=a(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||n.ORCHA_RUNTIME_ARTIFACT_DIR)||A(_e(),"orcha-runtime-artifacts"),s=a(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||J(),i=A(r,s),o=A(i,J());return Fn(o,{recursive:!0}),{root:o,realRoot:ct(o),sessionRoot:i,realSessionRoot:ct(i)}}function Oe(e){return a(c(e)?e.root:e)}function pe(e){let t=Oe(e),n=a(c(e)?e.sessionRoot:zn(t)),r=a(c(e)?e.realSessionRoot:"");if(n)try{if(r&&ct(n)!==r)return;$n(n)}catch{}}function ar(e,t={}){let n=Oe(e),r=a(c(e)?e.realRoot:"");if(n){try{if(r&&ct(n)!==r){p("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:n});return}}catch{pe(e);return}try{Dn(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}pe(e)}}function cr(e,t){return{trustedFileRoots:[t,...E(e.trustedArtifactRoots),...E(e.trustedFileRoots),...E(e.artifactRoots),...E(e.artifactFileRoots)].filter(Boolean)}}function Ae(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)||A(Bn(),".codex");return A(r,"sessions")}function ur(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 A(e,r,s,i)}function Me(e,t,n){let r=new Set;for(let s of[t-it,t,t+it,n-it,n,n+it])r.add(ur(e,s));return[...r].filter(s=>me(s))}function lr(e,t,n){let r=Ae(e),s=t-Kn,i=n+jn,o=[];for(let u of Me(r,t,n)){let l=[];try{l=ge(u)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=A(u,d);try{let h=Hn(f);if(!h.isFile()||h.mtimeMs<s||h.mtimeMs>i)continue;o.push({path:f,mtimeMs:h.mtimeMs})}catch{}}}return o.sort((u,l)=>l.mtimeMs-u.mtimeMs).slice(0,Wn)}function dr(e,t,n=t){let r=Ae(e),s=new Set;for(let i of Me(r,t,n)){let o=[];try{o=ge(i)}catch{continue}for(let u of o)u.endsWith(".jsonl")&&s.add(A(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 Ue(e){return a(e).replace(/\s+/g," ")}function fr(e){let t=Ue(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 pr(e,t){let n=fr(t);if(!n.length)return!1;let r=[];for(let i of e)At(i,r);let s=Ue(r.join(" "));return n.every(i=>s.includes(i))}function hr(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 gr(e,t,n){if(!pr(e,t.promptText))return!1;let r=hr(e);if(!r)return!1;let s=r.payload,i=a(s.originator),o=a(s.source);if(i!=="codex_exec"&&o!=="exec")return!1;let u=mr(r);if(!Number.isFinite(u)||u<t.startedAtMs-5e3||u>n+5e3)return!1;let l=a(t.target.cwd),d=a(s.cwd);return!(l&&d&&de(l)!==de(d))}function he(e){try{return _r(Te(e,"utf8"))}catch{return null}}function Tr(e,t,n){if(!e||e.disabled)return null;if(e.matchedPath){let s=he(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let r=[];for(let s of lr(e.target,e.startedAtMs,n)){if(e.baselinePaths.has(s.path))continue;let i=he(s.path);!i||!gr(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 _r(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 yr(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 Sr(e,t,n,r){let s=Se(e),i=Ut(e),o=0,u=0,l=0;if(s&&!i&&t.emitThoughtChunks&&Ce(t,n,r,s)&&(l=1),s&&i){let d=t.emittedTexts.size?`
9
9
 
10
- ${s}`:s;t.emittedTexts.add(s),o=1,u=1,r({sessionId:n,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}})}return s&&i&&(t.finalTextSeen=!0),Se(t,ye(e,t.artifactOptions)),(mr(e)||i)&&r({sessionId:n,update:{sessionUpdate:"runtime_event",event:xe(e)}}),{textCount:o,finalTextCount:u,thoughtCount:l}}function At(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=pr(t,n,s);if(f){let h=Math.min(t.processedLines.get(f.path)||0,f.events.length),m=e.artifacts.size;for(let y of f.events.slice(h)){let S=gr(y,e,n,r);u+=S.textCount,l+=S.finalTextCount,d+=S.thoughtCount}t.processedLines.set(f.path,f.events.length),(f.events.length>h||e.artifacts.size>m)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:u,finalTextCount:l,thoughtCount:d}}function Tr(e,{remove:t=!0}={}){if(!e||!pe(e))return"";try{return me(e,"utf8").trim()}catch{return""}finally{t&&ot(e)}}function ot(e){if(e)try{Dn(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 yr(e){return new Promise(t=>setTimeout(t,e))}function Sr(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 xr(e,t,n,r,s,i){let o=At(e,t,n,r,Date.now()),u=()=>Sr(e,n,r,Tr(s,{remove:!1}));if(u()||e.finalTextSeen)return ot(s),o;let l=Xn(i);if(l<=0||!t&&!s)return ot(s),o;let d=Date.now()+l,f=Math.min(we(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await yr(Math.min(f,Math.max(0,d-Date.now()))),o=_r(o,At(e,t,n,r,Date.now())),!u()););return ot(s),o}var ut=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}-${J()}`}}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)||J(),o=Z(t.prompt),u=a(this.target.promptMode||"stdin"),l=this.buildArgs(u,o),d=a(this.target.cwd)||this.agent.workspace||process.cwd(),f=nr(this.target,i),h=f.root,m=sr(this.target,h),y=Jn(s,this.target),S={...this.target,targetCode:this.agent.targetCode,cwd:d},U=y?ar(S,r):new Set,E=Wn(s,l,this.target)?A(ge(),`orcha-runtime-last-message-${J()}.txt`):"";E&&l.push("--output-last-message",E);let O=T(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,T(this.options.sessionPromptTimeoutMs,vn)),N={...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:h},g=bn(s,l,{cwd:d,env:N,stdio:["pipe","pipe","pipe"]});this.active.set(i,g),p("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:i,pid:g.pid,timeoutMs:O});let Wt="",_t=a(this.target.outputMode||"text"),b={artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:m,finalTextSeen:!1,finalTextOnly:Qn(t,this.target),emitThoughtChunks:Yn(t,this.target)},yt=y?er(S,o,r,U):null;return g.stdout.setEncoding("utf8"),g.stdout.on("data",v=>this.handleStdout(v,_t,b,i,n)),g.stderr.setEncoding("utf8"),g.stderr.on("data",v=>{Wt+=v,this.target.emitStderr===!0&&n({sessionId:i,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:v}}})}),u==="stdin"?g.stdin.end(o):g.stdin.end(),await new Promise((v,nn)=>{let V=!1,Jt=!1,F=null,St=yt&&Vn(this.target,t)?setInterval(()=>{try{At(b,yt,i,n)}catch(x){p("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:i,error:String(x?.message||x)})}},we(this.target)):null;St?.unref?.();let Xt=setTimeout(()=>{Jt=!0,p("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:i,pid:g.pid,timeoutMs:O}),it(g,"SIGTERM"),F=setTimeout(()=>{p("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:i,pid:g.pid}),it(g,"SIGKILL")},Bn),F.unref?.(),xt(Object.assign(new Error(`runtime CLI timed out after ${O}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},O);Xt.unref?.();let Vt=()=>{clearTimeout(Xt),St&&clearInterval(St),F&&!Jt&&clearTimeout(F),rr(f,{target:this.agent.targetCode,sessionId:i}),this.active.delete(i)},rn=x=>{V||(V=!0,Vt(),v(x))},xt=x=>{V||(V=!0,Vt(),nn(x))};g.on("error",x=>{p("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:i,pid:g.pid,error:String(x?.message||x)}),xt(x)}),g.on("exit",(x,Yt)=>{(async()=>{F&&(clearTimeout(F),F=null),_t==="json-lines"&&b.value.trim()&&this.handleStdout(`
11
- `,_t,b,i,n);let k=await xr(b,yt,i,n,E,this.target);(k.artifactCount>0||k.textCount>0||k.thoughtCount>0)&&p("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:i,artifactCount:k.artifactCount,textCount:k.textCount,finalTextCount:k.finalTextCount,thoughtCount:k.thoughtCount,transcriptCount:k.transcriptCount});let Y=Wt.trim();Y&&p("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:i,stderr:Y}),p("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:i,pid:g.pid,exitCode:x,signal:Yt,artifactCount:b.artifacts.size,finalTextSeen:b.finalTextSeen}),rn({stopReason:x===0?"end_turn":"error",exitCode:x,signal:Yt,_artifacts:[...b.artifacts.values()],...Y?{stderr:Y}:{}})})().catch(xt)})})}buildArgs(t,n){let r=w(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);Se(r,ye(d,r.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:xe(d)}});let f=_e(d),h=Re(d);f&&tr(r,h)&&!r.emittedTexts.has(f)&&(r.emittedTexts.add(f),i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:f}}})),f&&h&&(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}),it(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}),it(r,"SIGTERM");this.active.clear()}};var Ut=24e3,Nt=8,bt=50,kt=6e3,Rr=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),wr=10*60*1e3,Er=60*1e3,Ir=8,Cr=60*1e3,Or=1,dt="ORCHA_RUNTIME_RESULT_START",Ne="ORCHA_RUNTIME_RESULT_END",Ar=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions","runtimeMaxSessions"]),Mr=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Ur(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:lt()}}}function I(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 be(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return Rr.has(t)}function D(e,t){let n=T(e,t);return Number.isFinite(n)&&n>0?n:t}function Lt(e){let t=T(e,null);return Number.isFinite(t)&&t>0?t:null}function X(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 L(e){return a(e?.type||"echo")}function Nr(e){let t=L(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function Ft(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 br(e){let t=String(e||"");if(Mr.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 Dt(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=kt)return e;let n=e.length-kt;return`${e.slice(0,kt)}... [truncated ${n} characters]`}if(t>=Nt)return Array.isArray(e)?`[array truncated at depth ${Nt}, items=${e.length}]`:c(e)?`[object truncated at depth ${Nt}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let n=e.slice(0,bt).map(r=>Dt(r,t+1));return e.length>bt&&n.push(`[truncated ${e.length-bt} items]`),n}if(c(e)){let n={};for(let[r,s]of Object.entries(e))n[r]=br(r)?"[REDACTED]":Dt(s,t+1);return n}return String(e)}var kr=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 Pr(e){if(!c(e))return e;let t={};for(let n of kr)I(e[n])&&(t[n]=e[n]);return t}function Lr(e){if(!c(e))return e;let t={...e};return c(t.renderedPayload)&&(t.renderedPayload=Pr(t.renderedPayload)),t}function Fr(e){let t=c(e)?e:{},n={};I(t.metadata)&&(n.metadata=Lr(t.metadata));for(let[r,s]of Object.entries(t))Ar.has(r)||r==="metadata"||I(s)&&(n[r]=s);return n}function Dr(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 ke(e){return a(Dr(e).kind).toLowerCase()==="decision"}function Ae(e){let t=c(e)?e:{},n=c(t.metadata)?t.metadata:{};return Lt(t.runtimeMaxSessions??n.runtimeMaxSessions)}function $r(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:L(e)==="cli"}function Me(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return X(t,Nr(e))}function Hr(e,t){let n=c(e?.metadata)?{...e.metadata}:{},r=c(n._runtimeBridge)?{...n._runtimeBridge}:{},s=Ft(r);return n._runtimeBridge={...r,promptKind:"dispatch",finalTextOnly:$r(t),releaseAfterPrompt:s===void 0?Me(t):X(s,Me(t)),requiresRuntimeResult:ke(e)},n}function vr(e){let t=Fr(e);if(!I(t))return"";let n=JSON.stringify(Dt(t),null,2);if(n.length<=Ut)return n;let r=n.length-Ut;return`${n.slice(0,Ut)}
13
- ... [truncated ${r} characters]`}function Pe(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 Br(e){if(!c(e))return"";let t=c(e.update)?e.update:e;return a(t.sessionUpdate)}function zr(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=Br(u),d=Pe(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 $t(s);let o=r[r.length-1]||[];return $t(o)}function Gr(e){return Array.isArray(e)?e.map(Pe).filter(t=>a(t)):[]}function qr(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 Kr(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 jr(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let n=Kr(qr(e[t]));if(n)return n}return""}function $t(e){let t="";for(let n of e){let r=String(n||"");r&&(t?r.startsWith(t)?t=r:t.endsWith(r)||(t+=r):t=r)}return t.trim()}function Wr(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]===`
14
- `?1:0)).trim()}function ft(e){let t=String(e||"").trim();if(!t)return null;try{let n=JSON.parse(t);if(c(n)&&(Le(n)||I(n._artifacts)||I(n.artifacts)||I(n._decision)||I(n._meta)))return n}catch{}return null}function Jr(e){let t=String(e||"");if(!t)return"";let n=t.lastIndexOf(Ne);if(n<0)return"";for(let r=t.lastIndexOf(dt,n);r>=0;r=t.lastIndexOf(dt,r-1)){let s=t.slice(r+dt.length,n).trim();if(ft(s))return s}return""}function pt(e){let t=Jr(e);return t?ft(t):null}function Ue(e){let t=String(e||"").trim();if(!t)return null;let n=pt(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=ft(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=ft(t.slice(s));if(i)return i}return null}function Xr(e){let t=Gr(e);for(let n=t.length-1;n>=0;n-=1){let r=pt(t[n]);if(r)return r}return pt($t(t))}function Le(e){if(!c(e))return!1;if(I(e.output))return!0;for(let t of["content","text","message","summary"])if(a(e[t]))return!0;return!!(be(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 Vr(e){return c(e)?typeof(c(e._decision)?e._decision:c(e.decision)?e.decision:e).passed=="boolean":!1}function Yr(e){return c(e)?c(e._decision)&&typeof e._decision.passed=="boolean"?!0:Vr(e.output):!1}function Pt(e,t,n){let r=c(e)?{...e}:{};if(!I(r.output)){for(let s of["summary","message","content","text"])if(a(r[s])){r.output=a(r[s]);break}}return!I(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)}}}function P(e,t,n){return{...e,...t,_meta:{...c(e._meta)?e._meta:{},...c(t._meta)?t._meta:{},runtimeOutputSource:n}}}function Zr(e,t,n={}){let r=a(n.promptKind),s=n.requiresRuntimeResult===!0,i=s||r==="dispatch",o=M(e),u=typeof o.output=="string"?pt(o.output):null;if(u)return P(o,M(u),"result_block");let l=jr(t),d=l?Ue(l):null,f=i?Xr(t):null;if(Le(o))return be(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||Yr(o)?o:d?P(o,M(d),"final_event"):f?P(o,M(f),"updates"):Pt(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?Pt(o,"final_event",l):{...o,output:l,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let h=Wr(zr(t));if(!h)return o;let m=Ue(h);return m?P(o,M(m),"updates"):s?Pt(o,"updates",h):{...o,output:h,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}var ht=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=j(),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=L(t)==="openclaw"?D(this.config.openClawSessionIdleTtlMs,Cr):D(this.config.sessionIdleTtlMs,wr);return D(t?.sessionIdleTtlMs??t?.idleTtlMs,r)}targetMaxSessions(t,n=null){let s=L(t)==="openclaw"?D(this.config.openClawMaxSessions,Or):D(this.config.maxSessionsPerTarget,Ir),i=D(t?.maxSessions,s),o=Lt(n);return o?Math.max(i,o):i}targetReleaseAfterPrompt(t,n={}){let r=L(t),s=c(n?._runtimeBridge)?n._runtimeBridge:{},i=Ft(s);return i!==void 0?X(i,!1):X(t?.releaseAfterPrompt??t?.disposeAfterPrompt,r==="openclaw")}promptReleaseAfterPrompt(t,n={}){let r=c(n?._runtimeBridge)?n._runtimeBridge:{},s=Ft(r);return s!==void 0?X(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=D(this.config.sessionCleanupIntervalMs,Er);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=Lt(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:j(),runtimeKind:L(s),runtimeMaxSessions:Ae(t)};return this.agents.set(n,i),{agent:i}}runtimeFor(t,n){let{target:r}=this.targetFor(t.targetCode),s=L(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 rt(t,r,n,i,o):s==="cli"?new ut(t,r,o):new Q(t)}async prompt(t,n={}){let r=a(t.agentId),s=a(t.sessionId)||lt();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=Ae(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:m,target:y}=this.targetFor(i.targetCode);await this.reserveTargetSlot(m,y,{agentId:r,runtimeMaxSessions:i.runtimeMaxSessions});let S=this.runtimeFor(i,s),U=await S.sessionNew({cwd:i.workspace||process.cwd(),metadata:c(t.metadata)?t.metadata:{}}),E=Date.now();d={agentId:r,sessionId:s,runtime:S,targetCode:m,runtimeKind:L(y),runtimeSessionId:a(c(U)?U.sessionId:"")||s,idleTtlMs:this.targetIdleTtlMs(y),releaseAfterPrompt:this.targetReleaseAfterPrompt(y,t.metadata),createdAtMs:E,lastUsedAtMs:E,busy:!1,createdAt:j()},this.sessions.set(l,d),this.runtimeSessionIndex.set(`${r}:${d.runtimeSessionId}`,d)}if(d.busy){let m=new Error(`runtime session is already running: ${s}`);throw m.code="RUNTIME_SESSION_BUSY",m}d.busy=!0,d.lastUsedAtMs=Date.now();let f=[],h=m=>{let y=Ur(m,s,d);f.push(y),n.onUpdate?.(y)};try{let m=await d.runtime.sessionPrompt({sessionId:d.runtimeSessionId,prompt:Array.isArray(t.prompt)?t.prompt:[],metadata:c(t.metadata)?t.metadata:{}},h),y=c(t.metadata)?t.metadata:{},S=c(y._runtimeBridge)?y._runtimeBridge:{},U=Zr(m,f,S);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=vr(t),d=ke(t),{target:f}=this.targetFor(t.targetCode||t.framework),h=[{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, wrap the final Orcha Runtime Result JSON between ${dt} and ${Ne}.`:"",d?"The result block must contain exactly one valid JSON object with output and _decision; escape Markdown newlines inside JSON strings as \\n.":"",d?"Do not put process notes inside the result block; text outside the block is ignored by Orcha.":"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
15
- `)}];return this.prompt({...t,agentId:r,sessionId:o,prompt:h,metadata:Hr(t,f)},n)}async requestPermission({agent:t,runtimeSessionId:n,request:r,emitUpdate:s}){let i=lt(),u=this.runtimeSessionIndex.get(`${t.agentId}:${n}`)?.sessionId||n||lt(),l={permissionId:i,agentId:t.agentId,sessionId:u,runtimeSessionId:n,request:c(r)?r:{},status:"pending",createdAt:j()};return s?.({sessionId:n,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=T(r?.timeoutMs,this.config.permissionRequestTimeoutMs),h=setTimeout(()=>{this.pendingPermissions.delete(i),d({permissionId:i,outcome:"denied",response:{reason:"permission request timed out"}})},f);this.pendingPermissions.set(i,{timer:h,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:B,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 Qr from"node:http";import ts from"node:https";import{randomBytes as Fe}from"node:crypto";var G=1,$=3,es=1e4,mt=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=ns(n.connectTimeoutMs,es),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:"?ts:Qr,r=Fe(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===$){o.destroy();return}this.socket=o,this.readyState=G,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==$&&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!==$&&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===G||this.readyState===$)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!==G||this.socket.write(Ht(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==$){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===G&&this.socket.write(Ht(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==$&&(this.clearConnectTimer(),this.readyState=$,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),h=this.buffer.readUInt32BE(u+4);o=f*2**32+h,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((h,m)=>h^f[m%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(Ht(10,d))}}};function ns(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function Ht(e,t){let n=t.length,r=2;n>=126&&n<=65535?r+=2:n>65535&&(r+=8);let s=Fe(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 rs(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 ss(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 gt=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=rs(this.config.orchaUrl),n=new mt(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:B,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,targets:ss(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!==G?!1:(n.send(JSON.stringify(t)),!0)}};import{existsSync as is,readFileSync as os}from"node:fs";import{resolve as De}from"node:path";var as=/^[A-Za-z_][A-Za-z0-9_]*$/;function $e(e=process.env,t=process.cwd()){let n=a(e.ORCHA_RUNTIME_ENV_FILE),r=n?De(t,n):De(t,".env");if(!is(r))return n&&p("warn","config","runtime env file not found",{path:r}),{loaded:!1,path:r,keys:[]};let s=[],i=os(r,"utf8");for(let o of i.split(/\r?\n/)){let u=us(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 He(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:cs(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function cs(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 us(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(!as.test(s))return null;let i=ls(n.slice(r+1).trim());return[s,i]}function ls(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let n=e.slice(1,-1);return t==='"'?ds(n):n}return fs(e).trim()}function ds(e){return e.replaceAll("\\n",`
16
- `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function fs(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 ps}from"node:http";function Tt(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 H(e={}){return{ok:!0,...e}}function vt(e,t,n){return{ok:!1,error:{code:e,message:t,...n===void 0?{}:{detail:n}}}}async function ve(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 Be(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 ze(e,t){let n={"GET /health":async()=>H(t.health()),"POST /agents/create":async r=>H(await t.createAgent(r)),"POST /agents/dispatch":async r=>H(await t.dispatch(r)),"POST /sessions/prompt":async r=>H(await t.prompt(r)),"POST /sessions/cancel":async r=>H(await t.cancel(r)),"POST /permissions/respond":async r=>H(await t.respondPermission(r))};return ps(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){Tt(s,404,vt("NOT_FOUND",`No route for ${o}`));return}try{Be(r,e.token);let l=r.method==="GET"?{}:await ve(r,e.requestLimitBytes);Tt(s,200,await u(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";Tt(s,d,vt(f,l.message||String(l)))}})}var xs=Ss(import.meta.url),Rs=".orcha-runtime-bridge.pid",ws=".orcha-runtime-bridge.log",Es=3,Is=36e5,{command:Cs,options:Ze}=Us(process.argv.slice(2));Ns(Ze);$e();var Os=He();await As(Cs,Os,Ze);async function As(e,t,n){switch(e){case"run":case"foreground":qe(t);return;case"start":if(n.foreground){qe(t);return}je();return;case"reload":case"restart":await We({quiet:!0}),je();return;case"stop":await We();return;case"status":Ms();return;case"help":case"--help":case"-h":Ls();return;default:throw new Error(`Unknown command: ${e}`)}}function qe(e){bs();let t=new ht(e);if(e.mode==="server"){let r=ze(e,t);Ke({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 gt(e,t);Ke({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 Ke({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 je(){let e=Kt(),t=Qe(),n=jt(e);if(n&&q(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:e,logFile:t}));return}n&&Gt(e),Xe(e),Xe(t),zt(t);let r=Ts(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=hs(process.execPath,[xs,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",r,r]});i.unref(),ms(r),Ye(e,`${i.pid}
17
- `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function We({quiet:e=!1}={}){let t=Kt(),n=jt(t);if(!n){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!q(n)){Gt(t),e||console.log(JSON.stringify({status:"not_running",pid:n,pidFile:t}));return}process.kill(n,"SIGTERM"),!await Je(n,1e4)&&q(n)&&(process.kill(n,"SIGKILL"),await Je(n,3e3)),Gt(t),e||console.log(JSON.stringify({status:"stopped",pid:n,pidFile:t}))}function Ms(){let e=Kt(),t=Qe(),n=jt(e),r=!!(n&&q(n));console.log(JSON.stringify({status:r?"running":"not_running",running:r,pid:r?n:null,pidFile:e,logFile:t}))}function Us(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 Ns(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 Kt(){return qt(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Rs)}function Qe(){return qt(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||ws)}function bs(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=tn();if(t<=0)return;let n=qt(process.cwd(),e);zt(n,t);let r=Ps();r<=0||setInterval(()=>zt(n,t),r).unref()}function zt(e,t=tn()){if(t<=0||!Ve(e))return;let n=0,r="";try{if(n=Ge(e).size,n<=0)return;r=Bt(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&&(ks(d,s)?o.push(d):u+=1);if(u===0)return;let l="";try{Ge(e).size>n&&(l=Bt(e,"utf8").slice(r.length));let f=[...o,...l.split(/\r?\n/).filter(Boolean)].join(`
18
- `);Ye(e,f?`${f}
19
- `:""),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 ks(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 en(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,Es)}function Ps(){return en(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Is)}function en(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function jt(e){if(!Ve(e))return null;let t=Number.parseInt(Bt(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function q(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Je(e,t){let n=Date.now();for(;Date.now()-n<t;){if(!q(e))return!0;await new Promise(r=>setTimeout(r,100))}return!q(e)}function Xe(e){gs(ys(e),{recursive:!0})}function Gt(e){try{_s(e,{force:!0})}catch{}}function Ls(){console.log(`Usage: orcha-runtime-bridge [command] [options]
10
+ ${s}`:s;Ie(t,n,r,d,s)&&(o=1,u=1)}return s&&i&&(t.finalTextSeen=!0),we(t,Re(e,t.artifactOptions)),(yr(e)||i)&&r({sessionId:n,update:{sessionUpdate:"runtime_event",event:Ee(e)}}),{textCount:o,finalTextCount:u,thoughtCount:l}}function Mt(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=Tr(t,n,s);if(f){let h=Math.min(t.processedLines.get(f.path)||0,f.events.length),m=e.artifacts.size;for(let y of f.events.slice(h)){let S=Sr(y,e,n,r);u+=S.textCount,l+=S.finalTextCount,d+=S.thoughtCount}t.processedLines.set(f.path,f.events.length),(f.events.length>h||e.artifacts.size>m)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:u,finalTextCount:l,thoughtCount:d}}function Rr(e,{remove:t=!0}={}){if(!e||!me(e))return"";try{return Te(e,"utf8").trim()}catch{return""}finally{t&&at(e)}}function at(e){if(e)try{vn(e)}catch{}}function wr(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 Er(e){return new Promise(t=>setTimeout(t,e))}function xr(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 Ir(e,t,n,r,s,i){let o=Mt(e,t,n,r,Date.now()),u=()=>xr(e,n,r,Rr(s,{remove:!1}));if(u()||e.finalTextSeen)return at(s),o;let l=Qn(i);if(l<=0||!t&&!s)return at(s),o;let d=Date.now()+l,f=Math.min(xe(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await Er(Math.min(f,Math.max(0,d-Date.now()))),o=wr(o,Mt(e,t,n,r,Date.now())),!u()););return at(s),o}var lt=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}-${J()}`}}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)||J(),o=Q(t.prompt),u=a(this.target.promptMode||"stdin"),l=this.buildArgs(u,o),d=a(this.target.cwd)||this.agent.workspace||process.cwd(),f=or(this.target,i),h=f.root,m=cr(this.target,h),y=Zn(s,this.target),S={...this.target,targetCode:this.agent.targetCode,cwd:d},U=y?dr(S,r):new Set,x=Yn(s,l,this.target)?A(_e(),`orcha-runtime-last-message-${J()}.txt`):"";x&&l.push("--output-last-message",x);let O=T(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,T(this.options.sessionPromptTimeoutMs,Gn)),N={...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:h},g=Ln(s,l,{cwd:d,env:N,stdio:["pipe","pipe","pipe"]});this.active.set(i,g),p("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:i,pid:g.pid,timeoutMs:O});let Xt="",yt=a(this.target.outputMode||"text"),b={artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:m,finalTextSeen:!1,finalTextOnly:rr(t,this.target),emitThoughtChunks:er(t,this.target)},St=y?ir(S,o,r,U):null;return g.stdout.setEncoding("utf8"),g.stdout.on("data",v=>this.handleStdout(v,yt,b,i,n)),g.stderr.setEncoding("utf8"),g.stderr.on("data",v=>{Xt+=v,this.target.emitStderr===!0&&n({sessionId:i,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:v}}})}),u==="stdin"?g.stdin.end(o):g.stdin.end(),await new Promise((v,on)=>{let Y=!1,Vt=!1,F=null,Rt=St&&tr(this.target,t)?setInterval(()=>{try{Mt(b,St,i,n)}catch(R){p("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:i,error:String(R?.message||R)})}},xe(this.target)):null;Rt?.unref?.();let Yt=setTimeout(()=>{Vt=!0,p("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:i,pid:g.pid,timeoutMs:O}),ot(g,"SIGTERM"),F=setTimeout(()=>{p("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:i,pid:g.pid}),ot(g,"SIGKILL")},qn),F.unref?.(),wt(Object.assign(new Error(`runtime CLI timed out after ${O}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},O);Yt.unref?.();let Zt=()=>{clearTimeout(Yt),Rt&&clearInterval(Rt),F&&!Vt&&clearTimeout(F),ar(f,{target:this.agent.targetCode,sessionId:i}),this.active.delete(i)},an=R=>{Y||(Y=!0,Zt(),v(R))},wt=R=>{Y||(Y=!0,Zt(),on(R))};g.on("error",R=>{p("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:i,pid:g.pid,error:String(R?.message||R)}),wt(R)}),g.on("exit",(R,Qt)=>{(async()=>{F&&(clearTimeout(F),F=null),yt==="json-lines"&&b.value.trim()&&this.handleStdout(`
11
+ `,yt,b,i,n);let k=await Ir(b,St,i,n,x,this.target);(k.artifactCount>0||k.textCount>0||k.thoughtCount>0)&&p("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:i,artifactCount:k.artifactCount,textCount:k.textCount,finalTextCount:k.finalTextCount,thoughtCount:k.thoughtCount,transcriptCount:k.transcriptCount});let Z=Xt.trim();Z&&p("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:i,stderr:Z}),p("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:i,pid:g.pid,exitCode:R,signal:Qt,artifactCount:b.artifacts.size,finalTextSeen:b.finalTextSeen}),an({stopReason:R===0?"end_turn":"error",exitCode:R,signal:Qt,_artifacts:[...b.artifacts.values()],...Z?{stderr:Z}:{}})})().catch(wt)})})}buildArgs(t,n){let r=E(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);we(r,Re(d,r.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:Ee(d)}});let f=Se(d),h=Ut(d);f&&r.emitThoughtChunks&&!h&&Vn(d)?Ce(r,s,i,f):f&&sr(r,h)&&Ie(r,s,i,f),f&&h&&(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}),ot(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}),ot(r,"SIGTERM");this.active.clear()}};var bt=24e3,kt=8,Pt=50,Lt=6e3,Cr=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),Or=10*60*1e3,Ar=60*1e3,Mr=8,Ur=60*1e3,Nr=1,ft="ORCHA_RUNTIME_RESULT_START",Pe="ORCHA_RUNTIME_RESULT_END",br=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions","runtimeMaxSessions"]),kr=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Pr(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:dt()}}}function I(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 Le(e){let t=a(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return Cr.has(t)}function D(e,t){let n=T(e,t);return Number.isFinite(n)&&n>0?n:t}function Dt(e){let t=T(e,null);return Number.isFinite(t)&&t>0?t:null}function V(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 L(e){return a(e?.type||"echo")}function Lr(e){let t=L(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function $t(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 Fr(e){let t=String(e||"");if(kr.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 Ht(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=Lt)return e;let n=e.length-Lt;return`${e.slice(0,Lt)}... [truncated ${n} characters]`}if(t>=kt)return Array.isArray(e)?`[array truncated at depth ${kt}, items=${e.length}]`:c(e)?`[object truncated at depth ${kt}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let n=e.slice(0,Pt).map(r=>Ht(r,t+1));return e.length>Pt&&n.push(`[truncated ${e.length-Pt} items]`),n}if(c(e)){let n={};for(let[r,s]of Object.entries(e))n[r]=Fr(r)?"[REDACTED]":Ht(s,t+1);return n}return String(e)}var Dr=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 $r(e){if(!c(e))return e;let t={};for(let n of Dr)I(e[n])&&(t[n]=e[n]);return t}function Hr(e){if(!c(e))return e;let t={...e};return c(t.renderedPayload)&&(t.renderedPayload=$r(t.renderedPayload)),t}function vr(e){let t=c(e)?e:{},n={};I(t.metadata)&&(n.metadata=Hr(t.metadata));for(let[r,s]of Object.entries(t))br.has(r)||r==="metadata"||I(s)&&(n[r]=s);return n}function Br(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 Fe(e){return a(Br(e).kind).toLowerCase()==="decision"}function Ne(e){let t=c(e)?e:{},n=c(t.metadata)?t.metadata:{};return Dt(t.runtimeMaxSessions??n.runtimeMaxSessions)}function zr(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:L(e)==="cli"}function be(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return V(t,Lr(e))}function Gr(e,t){let n=c(e?.metadata)?{...e.metadata}:{},r=c(n._runtimeBridge)?{...n._runtimeBridge}:{},s=$t(r);return n._runtimeBridge={...r,promptKind:"dispatch",finalTextOnly:zr(t),releaseAfterPrompt:s===void 0?be(t):V(s,be(t)),requiresRuntimeResult:Fe(e)},n}function qr(e){let t=vr(e);if(!I(t))return"";let n=JSON.stringify(Ht(t),null,2);if(n.length<=bt)return n;let r=n.length-bt;return`${n.slice(0,bt)}
13
+ ... [truncated ${r} characters]`}function De(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 Kr(e){if(!c(e))return"";let t=c(e.update)?e.update:e;return a(t.sessionUpdate)}function jr(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=Kr(u),d=De(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 vt(s);let o=r[r.length-1]||[];return vt(o)}function Wr(e){return Array.isArray(e)?e.map(De).filter(t=>a(t)):[]}function Jr(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 Xr(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 Vr(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let n=Xr(Jr(e[t]));if(n)return n}return""}function vt(e){let t="";for(let n of e){let r=String(n||"");r&&(t?r.startsWith(t)?t=r:t.endsWith(r)||(t+=r):t=r)}return t.trim()}function Yr(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]===`
14
+ `?1:0)).trim()}function pt(e){let t=String(e||"").trim();if(!t)return null;try{let n=JSON.parse(t);if(c(n)&&($e(n)||I(n._artifacts)||I(n.artifacts)||I(n._decision)||I(n._meta)))return n}catch{}return null}function Zr(e){let t=String(e||"");if(!t)return"";let n=t.lastIndexOf(Pe);if(n<0)return"";for(let r=t.lastIndexOf(ft,n);r>=0;r=t.lastIndexOf(ft,r-1)){let s=t.slice(r+ft.length,n).trim();if(pt(s))return s}return""}function ht(e){let t=Zr(e);return t?pt(t):null}function ke(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=pt(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=pt(t.slice(s));if(i)return i}return null}function Qr(e){let t=Wr(e);for(let n=t.length-1;n>=0;n-=1){let r=ht(t[n]);if(r)return r}return ht(vt(t))}function $e(e){if(!c(e))return!1;if(I(e.output))return!0;for(let t of["content","text","message","summary"])if(a(e[t]))return!0;return!!(Le(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 ts(e){return c(e)?typeof(c(e._decision)?e._decision:c(e.decision)?e.decision:e).passed=="boolean":!1}function es(e){return c(e)?c(e._decision)&&typeof e._decision.passed=="boolean"?!0:ts(e.output):!1}function Ft(e,t,n){let r=c(e)?{...e}:{};if(!I(r.output)){for(let s of["summary","message","content","text"])if(a(r[s])){r.output=a(r[s]);break}}return!I(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)}}}function P(e,t,n){return{...e,...t,_meta:{...c(e._meta)?e._meta:{},...c(t._meta)?t._meta:{},runtimeOutputSource:n}}}function ns(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=Vr(t),d=l?ke(l):null,f=i?Qr(t):null;if($e(o))return Le(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||es(o)?o:d?P(o,M(d),"final_event"):f?P(o,M(f),"updates"):Ft(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?Ft(o,"final_event",l):{...o,output:l,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let h=Yr(jr(t));if(!h)return o;let m=ke(h);return m?P(o,M(m),"updates"):s?Ft(o,"updates",h):{...o,output:h,_meta:{...c(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}var mt=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=j(),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=L(t)==="openclaw"?D(this.config.openClawSessionIdleTtlMs,Ur):D(this.config.sessionIdleTtlMs,Or);return D(t?.sessionIdleTtlMs??t?.idleTtlMs,r)}targetMaxSessions(t,n=null){let s=L(t)==="openclaw"?D(this.config.openClawMaxSessions,Nr):D(this.config.maxSessionsPerTarget,Mr),i=D(t?.maxSessions,s),o=Dt(n);return o?Math.max(i,o):i}targetReleaseAfterPrompt(t,n={}){let r=L(t),s=c(n?._runtimeBridge)?n._runtimeBridge:{},i=$t(s);return i!==void 0?V(i,!1):V(t?.releaseAfterPrompt??t?.disposeAfterPrompt,r==="openclaw")}promptReleaseAfterPrompt(t,n={}){let r=c(n?._runtimeBridge)?n._runtimeBridge:{},s=$t(r);return s!==void 0?V(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=D(this.config.sessionCleanupIntervalMs,Ar);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=Dt(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:j(),runtimeKind:L(s),runtimeMaxSessions:Ne(t)};return this.agents.set(n,i),{agent:i}}runtimeFor(t,n){let{target:r}=this.targetFor(t.targetCode),s=L(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 st(t,r,n,i,o):s==="cli"?new lt(t,r,o):new tt(t)}async prompt(t,n={}){let r=a(t.agentId),s=a(t.sessionId)||dt();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=Ne(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:m,target:y}=this.targetFor(i.targetCode);await this.reserveTargetSlot(m,y,{agentId:r,runtimeMaxSessions:i.runtimeMaxSessions});let S=this.runtimeFor(i,s),U=await S.sessionNew({cwd:i.workspace||process.cwd(),metadata:c(t.metadata)?t.metadata:{}}),x=Date.now();d={agentId:r,sessionId:s,runtime:S,targetCode:m,runtimeKind:L(y),runtimeSessionId:a(c(U)?U.sessionId:"")||s,idleTtlMs:this.targetIdleTtlMs(y),releaseAfterPrompt:this.targetReleaseAfterPrompt(y,t.metadata),createdAtMs:x,lastUsedAtMs:x,busy:!1,createdAt:j()},this.sessions.set(l,d),this.runtimeSessionIndex.set(`${r}:${d.runtimeSessionId}`,d)}if(d.busy){let m=new Error(`runtime session is already running: ${s}`);throw m.code="RUNTIME_SESSION_BUSY",m}d.busy=!0,d.lastUsedAtMs=Date.now();let f=[],h=m=>{let y=Pr(m,s,d);f.push(y),n.onUpdate?.(y)};try{let m=await d.runtime.sessionPrompt({sessionId:d.runtimeSessionId,prompt:Array.isArray(t.prompt)?t.prompt:[],metadata:c(t.metadata)?t.metadata:{}},h),y=c(t.metadata)?t.metadata:{},S=c(y._runtimeBridge)?y._runtimeBridge:{},U=ns(m,f,S);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=qr(t),d=Fe(t),{target:f}=this.targetFor(t.targetCode||t.framework),h=[{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, wrap the final Orcha Runtime Result JSON between ${ft} and ${Pe}.`:"",d?"The result block must contain exactly one valid JSON object with output and _decision; escape Markdown newlines inside JSON strings as \\n.":"",d?"Do not put process notes inside the result block; text outside the block is ignored by Orcha.":"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
15
+ `)}];return this.prompt({...t,agentId:r,sessionId:o,prompt:h,metadata:Gr(t,f)},n)}async requestPermission({agent:t,runtimeSessionId:n,request:r,emitUpdate:s}){let i=dt(),u=this.runtimeSessionIndex.get(`${t.agentId}:${n}`)?.sessionId||n||dt(),l={permissionId:i,agentId:t.agentId,sessionId:u,runtimeSessionId:n,request:c(r)?r:{},status:"pending",createdAt:j()};return s?.({sessionId:n,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=T(r?.timeoutMs,this.config.permissionRequestTimeoutMs),h=setTimeout(()=>{this.pendingPermissions.delete(i),d({permissionId:i,outcome:"denied",response:{reason:"permission request timed out"}})},f);this.pendingPermissions.set(i,{timer:h,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:B,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 rs from"node:http";import ss from"node:https";import{randomBytes as He}from"node:crypto";var G=1,$=3,is=1e4,gt=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=os(n.connectTimeoutMs,is),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:"?ss:rs,r=He(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===$){o.destroy();return}this.socket=o,this.readyState=G,o.on("data",l=>this.onData(l)),o.on("close",()=>this.onClose()),o.on("error",l=>{this.readyState!==$&&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!==$&&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===G||this.readyState===$)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!==G||this.socket.write(Bt(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==$){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===G&&this.socket.write(Bt(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==$&&(this.clearConnectTimer(),this.readyState=$,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),h=this.buffer.readUInt32BE(u+4);o=f*2**32+h,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((h,m)=>h^f[m%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(Bt(10,d))}}};function os(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function Bt(e,t){let n=t.length,r=2;n>=126&&n<=65535?r+=2:n>65535&&(r+=8);let s=He(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 as(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 cs(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=as(this.config.orchaUrl),n=new gt(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:B,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,targets:cs(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!==G?!1:(n.send(JSON.stringify(t)),!0)}};import{existsSync as us,readFileSync as ls}from"node:fs";import{resolve as ve}from"node:path";var ds=/^[A-Za-z_][A-Za-z0-9_]*$/;function Be(e=process.env,t=process.cwd()){let n=a(e.ORCHA_RUNTIME_ENV_FILE),r=n?ve(t,n):ve(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=ls(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 ze(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:fs(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function fs(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(!ds.test(s))return null;let i=hs(n.slice(r+1).trim());return[s,i]}function hs(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let n=e.slice(1,-1);return t==='"'?ms(n):n}return gs(e).trim()}function ms(e){return e.replaceAll("\\n",`
16
+ `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function gs(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 Ts}from"node:http";function _t(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 H(e={}){return{ok:!0,...e}}function zt(e,t,n){return{ok:!1,error:{code:e,message:t,...n===void 0?{}:{detail:n}}}}async function Ge(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 qe(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 Ke(e,t){let n={"GET /health":async()=>H(t.health()),"POST /agents/create":async r=>H(await t.createAgent(r)),"POST /agents/dispatch":async r=>H(await t.dispatch(r)),"POST /sessions/prompt":async r=>H(await t.prompt(r)),"POST /sessions/cancel":async r=>H(await t.cancel(r)),"POST /permissions/respond":async r=>H(await t.respondPermission(r))};return Ts(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){_t(s,404,zt("NOT_FOUND",`No route for ${o}`));return}try{qe(r,e.token);let l=r.method==="GET"?{}:await Ge(r,e.requestLimitBytes);_t(s,200,await u(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";_t(s,d,zt(f,l.message||String(l)))}})}var Is=xs(import.meta.url),Cs=".orcha-runtime-bridge.pid",Os=".orcha-runtime-bridge.log",As=3,Ms=36e5,{command:Us,options:en}=Ps(process.argv.slice(2));Ls(en);Be();var Ns=ze();await bs(Us,Ns,en);async function bs(e,t,n){switch(e){case"run":case"foreground":We(t);return;case"start":if(n.foreground){We(t);return}Xe();return;case"reload":case"restart":await Ve({quiet:!0}),Xe();return;case"stop":await Ve();return;case"status":ks();return;case"help":case"--help":case"-h":Hs();return;default:throw new Error(`Unknown command: ${e}`)}}function We(e){Fs();let t=new mt(e);if(e.mode==="server"){let r=Ke(e,t);Je({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);Je({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 Je({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 Xe(){let e=Wt(),t=nn(),n=Jt(e);if(n&&q(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:e,logFile:t}));return}n&&Kt(e),Ze(e),Ze(t),qt(t);let r=Rs(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=_s(process.execPath,[Is,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",r,r]});i.unref(),ys(r),tn(e,`${i.pid}
17
+ `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function Ve({quiet:e=!1}={}){let t=Wt(),n=Jt(t);if(!n){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!q(n)){Kt(t),e||console.log(JSON.stringify({status:"not_running",pid:n,pidFile:t}));return}process.kill(n,"SIGTERM"),!await Ye(n,1e4)&&q(n)&&(process.kill(n,"SIGKILL"),await Ye(n,3e3)),Kt(t),e||console.log(JSON.stringify({status:"stopped",pid:n,pidFile:t}))}function ks(){let e=Wt(),t=nn(),n=Jt(e),r=!!(n&&q(n));console.log(JSON.stringify({status:r?"running":"not_running",running:r,pid:r?n:null,pidFile:e,logFile:t}))}function Ps(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 Ls(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 Wt(){return jt(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Cs)}function nn(){return jt(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||Os)}function Fs(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=rn();if(t<=0)return;let n=jt(process.cwd(),e);qt(n,t);let r=$s();r<=0||setInterval(()=>qt(n,t),r).unref()}function qt(e,t=rn()){if(t<=0||!Qe(e))return;let n=0,r="";try{if(n=je(e).size,n<=0)return;r=Gt(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&&(Ds(d,s)?o.push(d):u+=1);if(u===0)return;let l="";try{je(e).size>n&&(l=Gt(e,"utf8").slice(r.length));let f=[...o,...l.split(/\r?\n/).filter(Boolean)].join(`
18
+ `);tn(e,f?`${f}
19
+ `:""),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 Ds(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 rn(){return sn(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,As)}function $s(){return sn(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Ms)}function sn(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function Jt(e){if(!Qe(e))return null;let t=Number.parseInt(Gt(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function q(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Ye(e,t){let n=Date.now();for(;Date.now()-n<t;){if(!q(e))return!0;await new Promise(r=>setTimeout(r,100))}return!q(e)}function Ze(e){Ss(Es(e),{recursive:!0})}function Kt(e){try{ws(e,{force:!0})}catch{}}function Hs(){console.log(`Usage: orcha-runtime-bridge [command] [options]
20
20
 
21
21
  Commands:
22
22
  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.20",
3
+ "version": "0.1.21",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local Orcha runtime bridge for ACP-compatible agent runtimes.",