@orcha-ai/runtime-bridge 0.1.14 → 0.1.15

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 Kr}from"node:child_process";import{closeSync as qr,existsSync as Fe,mkdirSync as Jr,openSync as Wr,readFileSync as bt,rmSync as Xr,statSync as Me,writeFileSync as $e}from"node:fs";import{dirname as Vr,resolve as Pt}from"node:path";import{fileURLToPath as Yr}from"node:url";import{randomUUID as it}from"node:crypto";var F="0.1.14";function B(){return new Date().toISOString()}function S(e,t=2){return String(e).padStart(t,"0")}function Gt(e){let t=e>=0?"+":"-",n=Math.abs(e);return`${t}${S(Math.floor(n/60))}:${S(n%60)}`}function Ke(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${S(e.getMonth()+1)}-${S(e.getDate())}`,`T${S(e.getHours())}:${S(e.getMinutes())}:${S(e.getSeconds())}.${S(e.getMilliseconds(),3)}`,Gt(t)].join("")}function qe(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 Je(e,t){let n=qe(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}-${S(n.month)}-${S(n.day)}`,`T${S(n.hour)}:${S(n.minute)}:${S(n.second)}.${S(e.getMilliseconds(),3)}`,Gt(s)].join("")}function We(e=new Date){let t=o(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return Je(e,t)}catch{return Ke(e)}}function c(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function o(e){return String(e??"").trim()}function _(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 Xe="[redacted]",Ve=/(authorization|api[_-]?key|credential|password|secret|token)/i;function z(e,t=new WeakSet){if(e==null)return e;if(typeof e=="bigint")return e.toString();if(typeof e!="object")return e;if(e instanceof Date)return e.toISOString();if(e instanceof Error){if(t.has(e))return"[circular]";t.add(e);let r={name:e.name,message:e.message};e.stack&&(r.stack=e.stack);for(let s of Object.keys(e))r[s]=z(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=>z(s,t));return t.delete(e),r}let n={};for(let[r,s]of Object.entries(e))n[r]=Ve.test(r)?Xe:z(s,t);return t.delete(e),n}function jt(e,t=4e3){let n=JSON.stringify(z(e))??String(e);return!Number.isFinite(t)||n.length<=t?n:`${n.slice(0,t)}...`}function p(e,t,n,r={}){let s={ts:We(),level:e,module:t,msg:n,...c(r)?z(r):{}};console.error(JSON.stringify(s))}function J(e){return Array.isArray(e)?e.map(t=>c(t)?t.type==="text"?o(t.text):t.type==="file"?o(t.uri):t.type==="image"?o(t.uri):"":"").filter(Boolean).join(`
3
- `):""}var W=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=J(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 Ye}from"node:child_process";var G="2.0",Ze=3e4;function Qe(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:o(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=o(e.message)||"runtime error",n="data"in e?jt(e.data,4e3):"",r=new Error(n?`${t}; data=${n}`:t);return r.rpcCode=e.code,r.data=e.data,r}function en(e){return c(e)&&"id"in e&&!("method"in e)}function nn(e){return c(e)&&typeof e.method=="string"&&"id"in e}function rn(e){return c(e)&&typeof e.method=="string"&&!("id"in e)}var X=class{constructor({command:t,args:n=[],cwd:r,env:s,label:i,framing:u="line",detached:a=!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=u==="content-length"?"content-length":"line",this.detached=a!==!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=Ye(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 Xr}from"node:child_process";import{closeSync as Vr,existsSync as $e,mkdirSync as Yr,openSync as Zr,readFileSync as kt,rmSync as Qr,statSync as Ne,writeFileSync as He}from"node:fs";import{dirname as ts,resolve as Dt}from"node:path";import{fileURLToPath as es}from"node:url";import{randomUUID as it}from"node:crypto";var F="0.1.15";function B(){return new Date().toISOString()}function S(e,t=2){return String(e).padStart(t,"0")}function jt(e){let t=e>=0?"+":"-",n=Math.abs(e);return`${t}${S(Math.floor(n/60))}:${S(n%60)}`}function qe(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${S(e.getMonth()+1)}-${S(e.getDate())}`,`T${S(e.getHours())}:${S(e.getMinutes())}:${S(e.getSeconds())}.${S(e.getMilliseconds(),3)}`,jt(t)].join("")}function Je(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 We(e,t){let n=Je(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}-${S(n.month)}-${S(n.day)}`,`T${S(n.hour)}:${S(n.minute)}:${S(n.second)}.${S(e.getMilliseconds(),3)}`,jt(s)].join("")}function Xe(e=new Date){let t=o(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return We(e,t)}catch{return qe(e)}}function c(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function o(e){return String(e??"").trim()}function _(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 Ve="[redacted]",Ye=/(authorization|api[_-]?key|credential|password|secret|token)/i;function z(e,t=new WeakSet){if(e==null)return e;if(typeof e=="bigint")return e.toString();if(typeof e!="object")return e;if(e instanceof Date)return e.toISOString();if(e instanceof Error){if(t.has(e))return"[circular]";t.add(e);let r={name:e.name,message:e.message};e.stack&&(r.stack=e.stack);for(let s of Object.keys(e))r[s]=z(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=>z(s,t));return t.delete(e),r}let n={};for(let[r,s]of Object.entries(e))n[r]=Ye.test(r)?Ve:z(s,t);return t.delete(e),n}function Kt(e,t=4e3){let n=JSON.stringify(z(e))??String(e);return!Number.isFinite(t)||n.length<=t?n:`${n.slice(0,t)}...`}function p(e,t,n,r={}){let s={ts:Xe(),level:e,module:t,msg:n,...c(r)?z(r):{}};console.error(JSON.stringify(s))}function J(e){return Array.isArray(e)?e.map(t=>c(t)?t.type==="text"?o(t.text):t.type==="file"?o(t.uri):t.type==="image"?o(t.uri):"":"").filter(Boolean).join(`
3
+ `):""}var W=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=J(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 Ze}from"node:child_process";var G="2.0",Qe=3e4;function tn(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:o(e?.message)||String(e),data:c(e?.data)?e.data:void 0}}function en(e){if(!c(e))return new Error(String(e||"runtime error"));let t=o(e.message)||"runtime error",n="data"in e?Kt(e.data,4e3):"",r=new Error(n?`${t}; data=${n}`:t);return r.rpcCode=e.code,r.data=e.data,r}function nn(e){return c(e)&&"id"in e&&!("method"in e)}function rn(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 X=class{constructor({command:t,args:n=[],cwd:r,env:s,label:i,framing:u="line",detached:a=!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=u==="content-length"?"content-length":"line",this.detached=a!==!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=Ze(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),u=n+4,a=u+i;if(this.headerBuffer.length<a)return;let l=this.headerBuffer.subarray(u,a).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(a),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(en(t)){this.resolveResponse(t);return}if(nn(t)){this.handleRequest(t);return}rn(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:G,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:G,id:t.id,result:r??{}})}catch(r){this.writeFrame({jsonrpc:G,id:t.id,error:Qe(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=Ze){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:G,id:s,method:t,params:n};return new Promise((u,a)=>{let l=setTimeout(()=>{this.pending.delete(s),a(new Error(`${t} timed out after ${r}ms`))},r);this.pending.set(s,{resolve:u,reject:a,timer:l,method:t}),this.writeFrame(i,d=>{d&&(clearTimeout(l),this.pending.delete(s),a(d))})})}notify(t,n={}){this.writeFrame({jsonrpc:G,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),u=n+4,a=u+i;if(this.headerBuffer.length<a)return;let l=this.headerBuffer.subarray(u,a).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(a),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(nn(t)){this.resolveResponse(t);return}if(rn(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(en(t.error))):r.resolve(t.result))}async handleRequest(t){let n=this.requestHandlers.get(t.method);if(!n){this.writeFrame({jsonrpc:G,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:G,id:t.id,result:r??{}})}catch(r){this.writeFrame({jsonrpc:G,id:t.id,error:tn(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=Qe){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:G,id:s,method:t,params:n};return new Promise((u,a)=>{let l=setTimeout(()=>{this.pending.delete(s),a(new Error(`${t} timed out after ${r}ms`))},r);this.pending.set(s,{resolve:u,reject:a,timer:l,method:t}),this.writeFrame(i,d=>{d&&(clearTimeout(l),this.pending.delete(s),a(d))})})}notify(t,n={}){this.writeFrame({jsonrpc:G,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 Jt}from"node:crypto";import{existsSync as sn,readFileSync as on,realpathSync as Kt,statSync as an}from"node:fs";import{basename as Wt,extname as Xt,isAbsolute as cn,relative as un}from"node:path";var ln=25*1024*1024;function Vt(e,t=""){let n=o(t);if(n)return n;let r=Xt(o(e)).toLowerCase();return r===".jpg"||r===".jpeg"?"image/jpeg":r===".webp"?"image/webp":r===".gif"?"image/gif":"image/png"}function Yt(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 V(e){if(Array.isArray(e))return e.map(o).filter(Boolean);let t=o(e);return t?[t]:[]}function dn(e,t){let n=un(t,e);return n===""||!!n&&!n.startsWith("..")&&!cn(n)}function fn(e,t){let n=o(e);if(!n||!sn(n))return"";try{let r=Kt(n);for(let s of t)try{let i=Kt(s);if(dn(r,i))return r}catch{}}catch{return""}return""}function _t(e,t,n={}){let r=o(e);return!r||r.startsWith("data:")||/^https?:\/\//i.test(r)?r:pn(r,t,n)}function pn(e,t,n={}){let r=[...V(n.trustedFileRoots),...V(n.trustedFileRoot),...V(n.artifactRoots),...V(n.artifactRoot)],s=fn(e,r);if(!s)return"";try{let i=an(s);return!i.isFile()||i.size<=0||i.size>ln?"":`data:${t};base64,${on(s).toString("base64")}`}catch{return""}}function y(...e){for(let t of e){let n=o(t);if(n)return n}return""}function mn(e,t,n,r){let s=n.toLowerCase();if(s==="image"||s==="picture")return!0;let i=y(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),u=Xt(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(u)}function Tt(e,t={}){let{source:n="runtime_image_generation_event"}=t;if(!c(e))return null;let r=c(e.payload)?e.payload:{},s=o(e.type),i=o(r.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let u=y(r.call_id,r.id),a=y(r.saved_path,r.savedPath),l=y(r.revised_prompt,r.revisedPrompt),d=Vt(a,r.mimeType||r.mime_type),f=Yt(r.result,d)||_t(a,d,t);if(!f)return null;let m=f.startsWith("data:")?f:"",g=a?Wt(a):`${u||Jt()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:g||"Generated image",summary:l||"Generated image",content:{prompt:l||void 0,dataUrl:m||void 0,imageUrl:f,previewUrl:f,fileUrl:f,mimeType:d},dataUrl:m||void 0,previewUrl:f,fileUrl:f,metadata:{source:n,eventType:i,callId:u||void 0,savedPath:a||void 0,filename:g,mimeType:d,revisedPrompt:l||void 0}}}function hn(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 gn(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}:{},u=y(r.saved_path,r.savedPath,s.saved_path,s.savedPath,i.savedPath),a=y(r.mimeType,r.mime_type,s.mimeType,s.mime_type,i.mimeType),l=y(r.artifactType,r.artifact_type,r.type,r.kind,s.type,u?"image":"file"),d=mn(r,s,l,u),f=d?Vt(u,a):a;if(d){let O=y(r.dataUrl,s.dataUrl),x=O.startsWith("data:")?O:"",U=y(r.imageUrl,r.previewUrl,r.fileUrl,r.downloadUrl,r.url,r.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),h=Yt(r.result??s.result,f)||x||_t(u,f,t)||_t(U,f,t);h&&(h.startsWith("data:")&&(s.dataUrl||=h),s.imageUrl||=h,s.previewUrl||=h,s.fileUrl||=h,f&&(s.mimeType||=f))}for(let[O,x]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let U=r[O];U!=null&&U!==""&&!(x in s)&&(s[x]=U)}let m=y(r.fileUrl,r.downloadUrl,r.imageUrl,r.dataUrl,r.url,r.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),g=y(r.previewUrl,r.imageUrl,r.dataUrl,r.url,r.fileUrl,r.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),E=y(r.dataUrl,s.dataUrl,m.startsWith("data:")?m:"",g.startsWith("data:")?g:""),R=y(r.filename,i.filename,u?Wt(u):""),L=y(r.fieldKey,r.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...r,artifactType:l,type:r.type||l,fieldKey:L,title:y(r.title,R,"Runtime artifact"),summary:y(r.summary,s.prompt,r.title,R,"Runtime artifact"),content:s,dataUrl:E||void 0,fileUrl:m||void 0,previewUrl:g||void 0,metadata:{...i,source:y(i.source,n),savedPath:u||i.savedPath,filename:R||i.filename,mimeType:f||i.mimeType}}}function Y(e,t){if(!t||!e)return;let n=c(t.metadata)?t.metadata:{},r=y(n.savedPath,n.callId,t.previewUrl,t.fileUrl)||Jt(),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 yt(e,t,n={}){for(let r of hn(e))Y(t,gn(r,n))}function St(e){if(!c(e)||!c(e.payload))return c(e)?e:{value:e};let t=o(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 qt(e,t,n){if(!c(e))return e;let r=c(e.event)?e.event:null;return r?(Y(t,Tt(r,n)),{...e,event:St(r)}):e}function Zt(e,t,n={}){if(!c(e))return e;yt(e,t,n);let r=qt(e,t,n),s=c(r.update)?qt(r.update,t,n):null;return s&&s!==r.update&&(r={...r,update:s}),r}function Qt(e,t,n={}){let r=c(e)?{...e}:{};yt(r,t,n),yt(c(r.output)?r.output:{},t,n);let s=[...t?.values?.()||[]];return s.length&&(r._artifacts=s),delete r.artifacts,r}var $=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=o(this.target.command);if(!t)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);this.proc=new X({command:t,args:w(this.target.args),cwd:o(this.target.cwd)||this.agent.workspace||process.cwd(),env:c(this.target.env)?this.target.env:{},label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:o(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:F},...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=o(t.sessionId),s=new Map,i=this.artifactOptions(),u=this.proc.onNotification("session/update",l=>{let d=o(l.sessionId);(!d||d===r)&&n(Zt(l,s,i))}),a=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,a),this.permissionHandlers.set("*",a);try{let l=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return Qt(l,s,i)}finally{u(),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=o(t.sessionId),r=this.permissionHandlers.get(n)||this.permissionHandlers.get("*");return r?r(t):{outcome:"denied",reason:"no active Orcha permission handler"}}artifactSource(){return o(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:[o(this.target.artifactRoot),o(this.target.artifactDir),o(this.target.runtimeArtifactRoot),o(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 _n(e){let t=c(e.metadata)?e.metadata:{};return o(t.agentCode)}function yn(e,t){let n=_n(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var Z=class extends ${constructor(t,n,r,s={},i={}){let u=o(r).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",a=o(n.command)||"openclaw",l=Array.isArray(n.args)?n.args.map(String):[],d=l.length>0?l:["acp","--session",yn(t,u)];super(t,{...n,command:a,args:d},s,i)}};import{spawn as Tn}from"node:child_process";import{randomUUID as j}from"node:crypto";import{existsSync as se,mkdirSync as Sn,readdirSync as ie,readFileSync as oe,realpathSync as nt,rmSync as wn,rmdirSync as En,statSync as In,unlinkSync as Rn}from"node:fs";import{homedir as xn,tmpdir as ae}from"node:os";import{basename as ce,dirname as An,join as A,resolve as te}from"node:path";var Cn=36e5,On=5e3,Un=2*60*1e3,Mn=2*60*1e3,Nn=12,bn=1e3,kn=1500,Q=24*60*60*1e3,ee=new Set(["final_answer","final","complete","completed","done"]);function tt(e,t){try{e.kill(t)}catch{}}function I(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>I(t)).join("");if(!c(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let n=I(e[t]);if(n)return n}return""}function ue(e){if(!c(e))return"";let t=c(e.payload)?e.payload:{};if(o(e.type)==="event_msg"){if(o(t.type)==="agent_message")return o(t.message);if(o(t.type)==="task_complete")return o(t.last_agent_message)}if(o(e.type)==="response_item"&&o(t.type)==="message"&&o(t.role)==="assistant")return I(t.content)||I(t.message);let n=I(e.delta)||I(e.text)||I(e.content);if(n)return n;let r=c(e.item)?e.item:{};return o(r.role)==="assistant"||o(r.type)==="message"?I(r.content)||I(r.text)||I(r.message):""}function le(e,t={}){return Tt(e,{source:"codex_cli_image_generation",...t})}function de(e,t){Y(e.artifacts,t)}function fe(e){return St(e)}function pe(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=o(e.type),r=o(t.type);if(n==="event_msg"&&r==="task_complete")return!0;let s=o(t.phase||t.status||t.stage).toLowerCase();return n==="event_msg"&&r==="agent_message"||n==="response_item"&&r==="message"&&o(t.role)==="assistant"?ee.has(s):!1}function Ln(e,t,n){return n.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:n.captureLastMessage===!0?!0:ce(e)==="codex"}function Pn(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:ce(e)==="codex"}function me(e){return Math.max(20,_(e.codexTranscriptPollMs||e.transcriptPollMs,bn))}function Dn(e){return Math.max(0,_(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,kn))}function Fn(e){return e.codexTranscriptStreaming===!0||e.streamCodexTranscript===!0}function $n(e,t,n,r=new Set){return{target:e,promptText:t,startedAtMs:n,baselinePaths:r,matchedPath:"",disabled:!1,processedLines:new Map}}function Hn(e,t){let n=c(e.env)?e.env:{},r=o(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||n.ORCHA_RUNTIME_ARTIFACT_DIR)||A(ae(),"orcha-runtime-artifacts"),s=o(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||j(),i=A(r,s),u=A(i,j());return Sn(u,{recursive:!0}),{root:u,realRoot:nt(u),sessionRoot:i,realSessionRoot:nt(i)}}function he(e){return o(c(e)?e.root:e)}function ne(e){let t=he(e),n=o(c(e)?e.sessionRoot:An(t)),r=o(c(e)?e.realSessionRoot:"");if(n)try{if(r&&nt(n)!==r)return;En(n)}catch{}}function vn(e,t={}){let n=he(e),r=o(c(e)?e.realRoot:"");if(n){try{if(r&&nt(n)!==r){p("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:n});return}}catch{ne(e);return}try{wn(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}ne(e)}}function zn(e,t){return{trustedFileRoots:[t,...w(e.trustedArtifactRoots),...w(e.trustedFileRoots),...w(e.artifactRoots),...w(e.artifactFileRoots)].filter(Boolean)}}function ge(e){let t=o(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let n=c(e.env)?e.env:{},r=o(e.codexHome||n.CODEX_HOME||process.env.CODEX_HOME)||A(xn(),".codex");return A(r,"sessions")}function Bn(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 _e(e,t,n){let r=new Set;for(let s of[t-Q,t,t+Q,n-Q,n,n+Q])r.add(Bn(e,s));return[...r].filter(s=>se(s))}function Gn(e,t,n){let r=ge(e),s=t-Un,i=n+Mn,u=[];for(let a of _e(r,t,n)){let l=[];try{l=ie(a)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=A(a,d);try{let m=In(f);if(!m.isFile()||m.mtimeMs<s||m.mtimeMs>i)continue;u.push({path:f,mtimeMs:m.mtimeMs})}catch{}}}return u.sort((a,l)=>l.mtimeMs-a.mtimeMs).slice(0,Nn)}function jn(e,t,n=t){let r=ge(e),s=new Set;for(let i of _e(r,t,n)){let u=[];try{u=ie(i)}catch{continue}for(let a of u)a.endsWith(".jsonl")&&s.add(A(i,a))}return s}function wt(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)wt(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&&wt(e[r],t,n+1)}}function ye(e){return o(e).replace(/\s+/g," ")}function Kn(e){let t=ye(e);if(!t)return[];if(t.length<=200)return[t];let n=160,r=[0,Math.floor((t.length-n)/2),t.length-n],s=new Set,i=[];for(let u of r){let a=t.slice(Math.max(0,u),Math.max(0,u)+n).trim();a.length>=40&&!s.has(a)&&(s.add(a),i.push(a))}return i}function qn(e,t){let n=Kn(t);if(!n.length)return!1;let r=[];for(let i of e)wt(i,r);let s=ye(r.join(" "));return n.every(i=>s.includes(i))}function Jn(e){return e.find(t=>c(t)&&o(t.type)==="session_meta"&&c(t.payload))||null}function Wn(e){let t=c(e?.payload)?e.payload:{},n=o(e?.timestamp||t.timestamp),r=Date.parse(n);return Number.isFinite(r)?r:Number.NaN}function Xn(e,t,n){if(!qn(e,t.promptText))return!1;let r=Jn(e);if(!r)return!1;let s=r.payload,i=o(s.originator),u=o(s.source);if(i!=="codex_exec"&&u!=="exec")return!1;let a=Wn(r);if(!Number.isFinite(a)||a<t.startedAtMs-5e3||a>n+5e3)return!1;let l=o(t.target.cwd),d=o(s.cwd);return!(l&&d&&te(l)!==te(d))}function re(e){try{return Yn(oe(e,"utf8"))}catch{return null}}function Vn(e,t,n){if(!e||e.disabled)return null;if(e.matchedPath){let s=re(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let r=[];for(let s of Gn(e.target,e.startedAtMs,n)){if(e.baselinePaths.has(s.path))continue;let i=re(s.path);!i||!Xn(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 Yn(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 Zn(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=o(e.type),r=o(t.type);return n==="event_msg"&&r==="image_generation_end"||n==="response_item"&&r==="image_generation_call"}function Qn(e,t,n,r){let s=ue(e),i=pe(e),u=0,a=0;if(s&&!t.emittedTexts.has(s)){let l=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 Wt}from"node:crypto";import{existsSync as on,readFileSync as an,realpathSync as qt,statSync as cn}from"node:fs";import{basename as Xt,extname as Vt,isAbsolute as un,relative as ln}from"node:path";var dn=25*1024*1024;function Yt(e,t=""){let n=o(t);if(n)return n;let r=Vt(o(e)).toLowerCase();return r===".jpg"||r===".jpeg"?"image/jpeg":r===".webp"?"image/webp":r===".gif"?"image/gif":"image/png"}function Zt(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 V(e){if(Array.isArray(e))return e.map(o).filter(Boolean);let t=o(e);return t?[t]:[]}function fn(e,t){let n=ln(t,e);return n===""||!!n&&!n.startsWith("..")&&!un(n)}function pn(e,t){let n=o(e);if(!n||!on(n))return"";try{let r=qt(n);for(let s of t)try{let i=qt(s);if(fn(r,i))return r}catch{}}catch{return""}return""}function _t(e,t,n={}){let r=o(e);return!r||r.startsWith("data:")||/^https?:\/\//i.test(r)?r:hn(r,t,n)}function hn(e,t,n={}){let r=[...V(n.trustedFileRoots),...V(n.trustedFileRoot),...V(n.artifactRoots),...V(n.artifactRoot)],s=pn(e,r);if(!s)return"";try{let i=cn(s);return!i.isFile()||i.size<=0||i.size>dn?"":`data:${t};base64,${an(s).toString("base64")}`}catch{return""}}function y(...e){for(let t of e){let n=o(t);if(n)return n}return""}function mn(e,t,n,r){let s=n.toLowerCase();if(s==="image"||s==="picture")return!0;let i=y(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),u=Vt(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(u)}function Tt(e,t={}){let{source:n="runtime_image_generation_event"}=t;if(!c(e))return null;let r=c(e.payload)?e.payload:{},s=o(e.type),i=o(r.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let u=y(r.call_id,r.id),a=y(r.saved_path,r.savedPath),l=y(r.revised_prompt,r.revisedPrompt),d=Yt(a,r.mimeType||r.mime_type),f=Zt(r.result,d)||_t(a,d,t);if(!f)return null;let h=f.startsWith("data:")?f:"",g=a?Xt(a):`${u||Wt()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:g||"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:u||void 0,savedPath:a||void 0,filename:g,mimeType:d,revisedPrompt:l||void 0}}}function gn(e){let t=c(e)?e:{},n=[];for(let r of["_artifacts","artifacts"]){let s=t[r];Array.isArray(s)&&n.push(...s)}for(let r of["_artifact","artifact"]){let s=t[r];c(s)&&n.push(s)}return n}function _n(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}:{},u=y(r.saved_path,r.savedPath,s.saved_path,s.savedPath,i.savedPath),a=y(r.mimeType,r.mime_type,s.mimeType,s.mime_type,i.mimeType),l=y(r.artifactType,r.artifact_type,r.type,r.kind,s.type,u?"image":"file"),d=mn(r,s,l,u),f=d?Yt(u,a):a;if(d){let O=y(r.dataUrl,s.dataUrl),R=O.startsWith("data:")?O:"",U=y(r.imageUrl,r.previewUrl,r.fileUrl,r.downloadUrl,r.url,r.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),m=Zt(r.result??s.result,f)||R||_t(u,f,t)||_t(U,f,t);m&&(m.startsWith("data:")&&(s.dataUrl||=m),s.imageUrl||=m,s.previewUrl||=m,s.fileUrl||=m,f&&(s.mimeType||=f))}for(let[O,R]of[["prompt","prompt"],["previewUrl","previewUrl"],["fileUrl","fileUrl"],["downloadUrl","downloadUrl"],["imageUrl","imageUrl"],["dataUrl","dataUrl"],["url","url"],["uri","uri"],["mimeType","mimeType"],["mime_type","mimeType"]]){let U=r[O];U!=null&&U!==""&&!(R in s)&&(s[R]=U)}let h=y(r.fileUrl,r.downloadUrl,r.imageUrl,r.dataUrl,r.url,r.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),g=y(r.previewUrl,r.imageUrl,r.dataUrl,r.url,r.fileUrl,r.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),E=y(r.dataUrl,s.dataUrl,h.startsWith("data:")?h:"",g.startsWith("data:")?g:""),I=y(r.filename,i.filename,u?Xt(u):""),L=y(r.fieldKey,r.field_key,s.fieldKey,i.fieldKey,d?"image":"artifact");return{...r,artifactType:l,type:r.type||l,fieldKey:L,title:y(r.title,I,"Runtime artifact"),summary:y(r.summary,s.prompt,r.title,I,"Runtime artifact"),content:s,dataUrl:E||void 0,fileUrl:h||void 0,previewUrl:g||void 0,metadata:{...i,source:y(i.source,n),savedPath:u||i.savedPath,filename:I||i.filename,mimeType:f||i.mimeType}}}function Y(e,t){if(!t||!e)return;let n=c(t.metadata)?t.metadata:{},r=y(n.savedPath,n.callId,t.previewUrl,t.fileUrl)||Wt(),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 yt(e,t,n={}){for(let r of gn(e))Y(t,_n(r,n))}function St(e){if(!c(e)||!c(e.payload))return c(e)?e:{value:e};let t=o(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 Jt(e,t,n){if(!c(e))return e;let r=c(e.event)?e.event:null;return r?(Y(t,Tt(r,n)),{...e,event:St(r)}):e}function Qt(e,t,n={}){if(!c(e))return e;yt(e,t,n);let r=Jt(e,t,n),s=c(r.update)?Jt(r.update,t,n):null;return s&&s!==r.update&&(r={...r,update:s}),r}function te(e,t,n={}){let r=c(e)?{...e}:{};yt(r,t,n),yt(c(r.output)?r.output:{},t,n);let s=[...t?.values?.()||[]];return s.length&&(r._artifacts=s),delete r.artifacts,r}var $=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=o(this.target.command);if(!t)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);this.proc=new X({command:t,args:w(this.target.args),cwd:o(this.target.cwd)||this.agent.workspace||process.cwd(),env:c(this.target.env)?this.target.env:{},label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:o(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:F},...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=o(t.sessionId),s=new Map,i=this.artifactOptions(),u=this.proc.onNotification("session/update",l=>{let d=o(l.sessionId);(!d||d===r)&&n(Qt(l,s,i))}),a=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,a),this.permissionHandlers.set("*",a);try{let l=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return te(l,s,i)}finally{u(),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=o(t.sessionId),r=this.permissionHandlers.get(n)||this.permissionHandlers.get("*");return r?r(t):{outcome:"denied",reason:"no active Orcha permission handler"}}artifactSource(){return o(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:[o(this.target.artifactRoot),o(this.target.artifactDir),o(this.target.runtimeArtifactRoot),o(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 yn(e){let t=c(e.metadata)?e.metadata:{};return o(t.agentCode)}function Tn(e,t){let n=yn(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var Z=class extends ${constructor(t,n,r,s={},i={}){let u=o(r).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",a=o(n.command)||"openclaw",l=Array.isArray(n.args)?n.args.map(String):[],d=l.length>0?l:["acp","--session",Tn(t,u)];super(t,{...n,command:a,args:d},s,i)}};import{spawn as Sn}from"node:child_process";import{randomUUID as j}from"node:crypto";import{existsSync as ie,mkdirSync as wn,readdirSync as oe,readFileSync as ae,realpathSync as nt,rmSync as En,rmdirSync as xn,statSync as In,unlinkSync as Rn}from"node:fs";import{homedir as Cn,tmpdir as ce}from"node:os";import{basename as xt,dirname as An,join as C,resolve as ee}from"node:path";var On=36e5,Un=5e3,Mn=2*60*1e3,Nn=2*60*1e3,bn=12,kn=1e3,Ln=1500,Q=24*60*60*1e3,ne=new Set(["final_answer","final","complete","completed","done"]);function tt(e,t){try{e.kill(t)}catch{}}function x(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>x(t)).join("");if(!c(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let n=x(e[t]);if(n)return n}return""}function ue(e){if(!c(e))return"";let t=c(e.payload)?e.payload:{};if(o(e.type)==="event_msg"){if(o(t.type)==="agent_message")return o(t.message);if(o(t.type)==="task_complete")return o(t.last_agent_message)}if(o(e.type)==="response_item"&&o(t.type)==="message"&&o(t.role)==="assistant")return x(t.content)||x(t.message);let n=x(e.delta)||x(e.text)||x(e.content);if(n)return n;let r=c(e.item)?e.item:{};return o(r.role)==="assistant"||o(r.type)==="message"?x(r.content)||x(r.text)||x(r.message):""}function le(e,t={}){return Tt(e,{source:"codex_cli_image_generation",...t})}function de(e,t){Y(e.artifacts,t)}function fe(e){return St(e)}function pe(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=o(e.type),r=o(t.type);if(n==="event_msg"&&r==="task_complete")return!0;let s=o(t.phase||t.status||t.stage).toLowerCase();return n==="event_msg"&&r==="agent_message"||n==="response_item"&&r==="message"&&o(t.role)==="assistant"?ne.has(s):!1}function Pn(e,t,n){return n.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:n.captureLastMessage===!0?!0:xt(e)==="codex"}function Dn(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:xt(e)==="codex"}function he(e){return Math.max(20,_(e.codexTranscriptPollMs||e.transcriptPollMs,kn))}function Fn(e){return Math.max(0,_(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,Ln))}function $n(e){return e.codexTranscriptStreaming===!0||e.streamCodexTranscript===!0}function Hn(e,t){return t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:t.finalTextOnly===!1||t.finalOutputOnly===!1?!1:xt(e)==="codex"}function vn(e,t){return!e.finalTextOnly||t}function zn(e,t,n,r=new Set){return{target:e,promptText:t,startedAtMs:n,baselinePaths:r,matchedPath:"",disabled:!1,processedLines:new Map}}function Bn(e,t){let n=c(e.env)?e.env:{},r=o(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||n.ORCHA_RUNTIME_ARTIFACT_DIR)||C(ce(),"orcha-runtime-artifacts"),s=o(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||j(),i=C(r,s),u=C(i,j());return wn(u,{recursive:!0}),{root:u,realRoot:nt(u),sessionRoot:i,realSessionRoot:nt(i)}}function me(e){return o(c(e)?e.root:e)}function re(e){let t=me(e),n=o(c(e)?e.sessionRoot:An(t)),r=o(c(e)?e.realSessionRoot:"");if(n)try{if(r&&nt(n)!==r)return;xn(n)}catch{}}function Gn(e,t={}){let n=me(e),r=o(c(e)?e.realRoot:"");if(n){try{if(r&&nt(n)!==r){p("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:n});return}}catch{re(e);return}try{En(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}re(e)}}function jn(e,t){return{trustedFileRoots:[t,...w(e.trustedArtifactRoots),...w(e.trustedFileRoots),...w(e.artifactRoots),...w(e.artifactFileRoots)].filter(Boolean)}}function ge(e){let t=o(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let n=c(e.env)?e.env:{},r=o(e.codexHome||n.CODEX_HOME||process.env.CODEX_HOME)||C(Cn(),".codex");return C(r,"sessions")}function Kn(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 C(e,r,s,i)}function _e(e,t,n){let r=new Set;for(let s of[t-Q,t,t+Q,n-Q,n,n+Q])r.add(Kn(e,s));return[...r].filter(s=>ie(s))}function qn(e,t,n){let r=ge(e),s=t-Mn,i=n+Nn,u=[];for(let a of _e(r,t,n)){let l=[];try{l=oe(a)}catch{continue}for(let d of l){if(!d.endsWith(".jsonl"))continue;let f=C(a,d);try{let h=In(f);if(!h.isFile()||h.mtimeMs<s||h.mtimeMs>i)continue;u.push({path:f,mtimeMs:h.mtimeMs})}catch{}}}return u.sort((a,l)=>l.mtimeMs-a.mtimeMs).slice(0,bn)}function Jn(e,t,n=t){let r=ge(e),s=new Set;for(let i of _e(r,t,n)){let u=[];try{u=oe(i)}catch{continue}for(let a of u)a.endsWith(".jsonl")&&s.add(C(i,a))}return s}function wt(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)wt(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&&wt(e[r],t,n+1)}}function ye(e){return o(e).replace(/\s+/g," ")}function Wn(e){let t=ye(e);if(!t)return[];if(t.length<=200)return[t];let n=160,r=[0,Math.floor((t.length-n)/2),t.length-n],s=new Set,i=[];for(let u of r){let a=t.slice(Math.max(0,u),Math.max(0,u)+n).trim();a.length>=40&&!s.has(a)&&(s.add(a),i.push(a))}return i}function Xn(e,t){let n=Wn(t);if(!n.length)return!1;let r=[];for(let i of e)wt(i,r);let s=ye(r.join(" "));return n.every(i=>s.includes(i))}function Vn(e){return e.find(t=>c(t)&&o(t.type)==="session_meta"&&c(t.payload))||null}function Yn(e){let t=c(e?.payload)?e.payload:{},n=o(e?.timestamp||t.timestamp),r=Date.parse(n);return Number.isFinite(r)?r:Number.NaN}function Zn(e,t,n){if(!Xn(e,t.promptText))return!1;let r=Vn(e);if(!r)return!1;let s=r.payload,i=o(s.originator),u=o(s.source);if(i!=="codex_exec"&&u!=="exec")return!1;let a=Yn(r);if(!Number.isFinite(a)||a<t.startedAtMs-5e3||a>n+5e3)return!1;let l=o(t.target.cwd),d=o(s.cwd);return!(l&&d&&ee(l)!==ee(d))}function se(e){try{return tr(ae(e,"utf8"))}catch{return null}}function Qn(e,t,n){if(!e||e.disabled)return null;if(e.matchedPath){let s=se(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let r=[];for(let s of qn(e.target,e.startedAtMs,n)){if(e.baselinePaths.has(s.path))continue;let i=se(s.path);!i||!Zn(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 tr(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 er(e){if(!c(e))return!1;let t=c(e.payload)?e.payload:{},n=o(e.type),r=o(t.type);return n==="event_msg"&&r==="image_generation_end"||n==="response_item"&&r==="image_generation_call"}function nr(e,t,n,r){let s=ue(e),i=pe(e),u=0,a=0;if(s&&i&&!t.emittedTexts.has(s)){let l=t.emittedTexts.size?`
9
9
 
10
- ${s}`:s;t.emittedTexts.add(s),u=1,i&&(a=1),r({sessionId:n,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}})}return s&&i&&(t.finalTextSeen=!0),de(t,le(e,t.artifactOptions)),(Zn(e)||i)&&r({sessionId:n,update:{sessionUpdate:"runtime_event",event:fe(e)}}),{textCount:u,finalTextCount:a}}function Et(e,t,n,r,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0};let i=e.artifacts.size,u=0,a=0,l=0,d=Vn(t,n,s);if(d){let f=Math.min(t.processedLines.get(d.path)||0,d.events.length),m=e.artifacts.size;for(let g of d.events.slice(f)){let E=Qn(g,e,n,r);a+=E.textCount,l+=E.finalTextCount}t.processedLines.set(d.path,d.events.length),(d.events.length>f||e.artifacts.size>m)&&(u=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:u,textCount:a,finalTextCount:l}}function tr(e,{remove:t=!0}={}){if(!e||!se(e))return"";try{return oe(e,"utf8").trim()}catch{return""}finally{t&&et(e)}}function et(e){if(e)try{Rn(e)}catch{}}function er(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)}}function nr(e){return new Promise(t=>setTimeout(t,e))}function rr(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 sr(e,t,n,r,s,i){let u=Et(e,t,n,r,Date.now()),a=()=>rr(e,n,r,tr(s,{remove:!1}));if(a()||e.finalTextSeen)return et(s),u;let l=Dn(i);if(l<=0||!t&&!s)return et(s),u;let d=Date.now()+l,f=Math.min(me(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await nr(Math.min(f,Math.max(0,d-Date.now()))),u=er(u,Et(e,t,n,r,Date.now())),!a()););return et(s),u}var rt=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=o(this.target.command);if(!s)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let i=o(t.sessionId)||j(),u=J(t.prompt),a=o(this.target.promptMode||"stdin"),l=this.buildArgs(a,u),d=o(this.target.cwd)||this.agent.workspace||process.cwd(),f=Hn(this.target,i),m=f.root,g=zn(this.target,m),E=Pn(s,this.target),R={...this.target,targetCode:this.agent.targetCode,cwd:d},L=E?jn(R,r):new Set,O=Ln(s,l,this.target)?A(ae(),`orcha-runtime-last-message-${j()}.txt`):"";O&&l.push("--output-last-message",O);let x=_(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,_(this.options.sessionPromptTimeoutMs,Cn)),U={...process.env,...c(this.target.env)?this.target.env:{},...a==="env"?{ORCHA_RUNTIME_PROMPT:u}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:i,ORCHA_RUNTIME_ARTIFACT_DIR:m},h=Tn(s,l,{cwd:d,env:U,stdio:["pipe","pipe","pipe"]});this.active.set(i,h),p("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:i,pid:h.pid,timeoutMs:x});let $t="",pt=o(this.target.outputMode||"text"),M={artifacts:new Map,emittedTexts:new Set,value:"",artifactOptions:g,finalTextSeen:!1},mt=E?$n(R,u,r,L):null;return h.stdout.setEncoding("utf8"),h.stdout.on("data",P=>this.handleStdout(P,pt,M,i,n)),h.stderr.setEncoding("utf8"),h.stderr.on("data",P=>{$t+=P,this.target.emitStderr===!0&&n({sessionId:i,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:P}}})}),a==="stdin"?h.stdin.end(u):h.stdin.end(),await new Promise((P,Ge)=>{let K=!1,Ht=!1,N=null,ht=mt&&Fn(this.target)?setInterval(()=>{try{Et(M,mt,i,n)}catch(T){p("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:i,error:String(T?.message||T)})}},me(this.target)):null;ht?.unref?.();let vt=setTimeout(()=>{Ht=!0,p("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:i,pid:h.pid,timeoutMs:x}),tt(h,"SIGTERM"),N=setTimeout(()=>{p("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:i,pid:h.pid}),tt(h,"SIGKILL")},On),N.unref?.(),gt(Object.assign(new Error(`runtime CLI timed out after ${x}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},x);vt.unref?.();let zt=()=>{clearTimeout(vt),ht&&clearInterval(ht),N&&!Ht&&clearTimeout(N),vn(f,{target:this.agent.targetCode,sessionId:i}),this.active.delete(i)},je=T=>{K||(K=!0,zt(),P(T))},gt=T=>{K||(K=!0,zt(),Ge(T))};h.on("error",T=>{p("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:i,pid:h.pid,error:String(T?.message||T)}),gt(T)}),h.on("exit",(T,Bt)=>{(async()=>{N&&(clearTimeout(N),N=null),pt==="json-lines"&&M.value.trim()&&this.handleStdout(`
11
- `,pt,M,i,n);let D=await sr(M,mt,i,n,O,this.target);(D.artifactCount>0||D.textCount>0)&&p("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:i,artifactCount:D.artifactCount,textCount:D.textCount,finalTextCount:D.finalTextCount,transcriptCount:D.transcriptCount});let q=$t.trim();q&&p("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:i,stderr:q}),p("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:i,pid:h.pid,exitCode:T,signal:Bt,artifactCount:M.artifacts.size,finalTextSeen:M.finalTextSeen}),je({stopReason:T===0?"end_turn":"error",exitCode:T,signal:Bt,_artifacts:[...M.artifacts.values()],...q?{stderr:q}:{}})})().catch(gt)})})}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 u=r.value.split(/\r?\n/);r.value=u.pop()||"";for(let a of u){let l=a.trim();if(l)try{let d=JSON.parse(l);de(r,le(d,r.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:fe(d)}});let f=ue(d);f&&!r.emittedTexts.has(f)&&(r.emittedTexts.add(f),i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:f}}})),f&&pe(d)&&(r.finalTextSeen=!0)}catch{i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a}
12
- `}}})}}}async sessionCancel(t){let n=o(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}),tt(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}),tt(r,"SIGTERM");this.active.clear()}};var It=24e3,Rt=8,xt=50,At=6e3,ir=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),or=10*60*1e3,ar=60*1e3,cr=8,ur=60*1e3,lr=1,ot="ORCHA_RUNTIME_RESULT_START",Se="ORCHA_RUNTIME_RESULT_END",dr=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions"]),fr=/(^|[_-])(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:it()}}}function C(e){return e==null||e===""?!1:typeof e=="string"?o(e)!=="":Array.isArray(e)?e.length>0:c(e)?Object.keys(e).length>0:!0}function mr(e){let t=o(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return ir.has(t)}function b(e,t){let n=_(e,t);return Number.isFinite(n)&&n>0?n:t}function hr(e,t=!1){if(typeof e=="boolean")return e;let n=o(e).toLowerCase();return["true","1","yes","y","on"].includes(n)?!0:["false","0","no","n","off"].includes(n)?!1:t}function H(e){return o(e?.type||"echo")}function gr(e){let t=String(e||"");if(fr.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 Ot(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=At)return e;let n=e.length-At;return`${e.slice(0,At)}... [truncated ${n} characters]`}if(t>=Rt)return Array.isArray(e)?`[array truncated at depth ${Rt}, items=${e.length}]`:c(e)?`[object truncated at depth ${Rt}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let n=e.slice(0,xt).map(r=>Ot(r,t+1));return e.length>xt&&n.push(`[truncated ${e.length-xt} items]`),n}if(c(e)){let n={};for(let[r,s]of Object.entries(e))n[r]=gr(r)?"[REDACTED]":Ot(s,t+1);return n}return String(e)}var _r=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 yr(e){if(!c(e))return e;let t={};for(let n of _r)C(e[n])&&(t[n]=e[n]);return t}function Tr(e){if(!c(e))return e;let t={...e};return c(t.renderedPayload)&&(t.renderedPayload=yr(t.renderedPayload)),t}function Sr(e){let t=c(e)?e:{},n={};C(t.metadata)&&(n.metadata=Tr(t.metadata));for(let[r,s]of Object.entries(t))dr.has(r)||r==="metadata"||C(s)&&(n[r]=s);return n}function wr(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 Er(e){return o(wr(e).kind).toLowerCase()==="decision"}function Ir(e){let t=Sr(e);if(!C(t))return"";let n=JSON.stringify(Ot(t),null,2);if(n.length<=It)return n;let r=n.length-It;return`${n.slice(0,It)}
13
- ... [truncated ${r} characters]`}function Rr(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 xr(e){if(!c(e))return null;let t=c(e.update)?e.update:e;return o(t.sessionUpdate)!=="runtime_event"?null:c(t.event)?t.event:null}function Ar(e){if(!c(e))return"";let t=c(e.payload)?e.payload:{},n=o(e.type),r=o(t.type);if(n==="event_msg"){if(r==="task_complete")return o(t.last_agent_message||t.message||t.output);if(r==="agent_message"){let s=o(t.phase||t.status||t.stage).toLowerCase();if(["final_answer","final","complete","completed","done"].includes(s))return o(t.message||t.text||t.content)}}return""}function Cr(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let n=Ar(xr(e[t]));if(n)return n}return""}function Or(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 Ur(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 at(e){let t=String(e||"").trim();if(!t)return null;try{let n=JSON.parse(t);if(c(n)&&(Ee(n)||C(n._artifacts)||C(n.artifacts)||C(n._decision)||C(n._meta)))return n}catch{}return null}function Mr(e){let t=String(e||"");if(!t)return"";let n=t.lastIndexOf(Se);if(n<0)return"";for(let r=t.lastIndexOf(ot,n);r>=0;r=t.lastIndexOf(ot,r-1)){let s=t.slice(r+ot.length,n).trim();if(at(s))return s}return""}function we(e){let t=Mr(e);return t?at(t):null}function Te(e){let t=String(e||"").trim();if(!t)return null;let n=we(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=at(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=at(t.slice(s));if(i)return i}return null}function Ee(e){if(!c(e))return!1;if(C(e.output))return!0;for(let t of["content","text","message","summary"])if(o(e[t]))return!0;return!!(mr(e.status)||o(e.error)||o(e.errorMessage))}function st(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 Ct(e,t,n){return{...e,...t,_meta:{...c(e._meta)?e._meta:{},...c(t._meta)?t._meta:{},runtimeOutputSource:n}}}function Nr(e,t){let n=st(e),r=typeof n.output=="string"?we(n.output):null;if(r)return Ct(n,st(r),"result_block");if(Ee(n))return n;let s=Cr(t);if(s){let a=Te(s);return a?Ct(n,st(a),"final_event"):{...n,output:s,_meta:{...c(n._meta)?n._meta:{},runtimeOutputSource:"final_event"}}}let i=Ur(Or((Array.isArray(t)?t:[]).map(Rr)));if(!i)return n;let u=Te(i);return u?Ct(n,st(u),"updates"):{...n,output:i,_meta:{...c(n._meta)?n._meta:{},runtimeOutputSource:"updates"}}}var ct=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=B(),this.cleanupTimer=null,this.startSessionCleanup()}targetFor(t){let n=o(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=H(t)==="openclaw"?b(this.config.openClawSessionIdleTtlMs,ur):b(this.config.sessionIdleTtlMs,or);return b(t?.sessionIdleTtlMs??t?.idleTtlMs,r)}targetMaxSessions(t){let r=H(t)==="openclaw"?b(this.config.openClawMaxSessions,lr):b(this.config.maxSessionsPerTarget,cr);return b(t?.maxSessions,r)}targetReleaseAfterPrompt(t){let n=H(t);return hr(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}startSessionCleanup(){let t=b(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}idleTargetSessions(t){return[...this.sessions.entries()].filter(([,n])=>n.targetCode===t&&!n.busy).sort((n,r)=>(n[1].lastUsedAtMs||0)-(r[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){let r=this.targetMaxSessions(n);for(;this.sessionCountForTarget(t)>=r;){let s=this.idleTargetSessions(t);if(!s.length){let i=new Error(`runtime target session limit reached: ${t}`);throw i.code="RUNTIME_TARGET_SESSION_LIMIT",i}await this.closeSession(s[0][0],"target_session_limit")}}async createAgent(t){let n=o(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:o(t.framework||r),workspace:o(t.workspace),metadata:c(t.metadata)?t.metadata:{},createdAt:B(),runtimeKind:H(s)};return this.agents.set(n,i),{agent:i}}runtimeFor(t,n){let{target:r}=this.targetFor(t.targetCode),s=H(r),i={onPermissionRequest:a=>this.requestPermission(a)},u={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs};return s==="stdio-acp"||s==="acp"?new $(t,r,i,u):s==="openclaw"?new Z(t,r,n,i,u):s==="cli"?new rt(t,r,u):new W(t)}async prompt(t,n={}){let r=o(t.agentId),s=o(t.sessionId)||it();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,metadata:t.metadata})).agent,u=o(t.workspace);u&&u!==i.workspace&&(i.workspace=u);let a=`${r}:${s}`;await this.cleanupExpiredSessions();let l=this.sessions.get(a);if(!l){let{code:m,target:g}=this.targetFor(i.targetCode);await this.reserveTargetSlot(m,g);let E=this.runtimeFor(i,s),R=await E.sessionNew({cwd:i.workspace||process.cwd(),metadata:c(t.metadata)?t.metadata:{}}),L=Date.now();l={agentId:r,sessionId:s,runtime:E,targetCode:m,runtimeKind:H(g),runtimeSessionId:o(c(R)?R.sessionId:"")||s,idleTtlMs:this.targetIdleTtlMs(g),releaseAfterPrompt:this.targetReleaseAfterPrompt(g),createdAtMs:L,lastUsedAtMs:L,busy:!1,createdAt:B()},this.sessions.set(a,l),this.runtimeSessionIndex.set(`${r}:${l.runtimeSessionId}`,l)}if(l.busy){let m=new Error(`runtime session is already running: ${s}`);throw m.code="RUNTIME_SESSION_BUSY",m}l.busy=!0,l.lastUsedAtMs=Date.now();let d=[],f=m=>{let g=pr(m,s,l);d.push(g),n.onUpdate?.(g)};try{let m=await l.runtime.sessionPrompt({sessionId:l.runtimeSessionId,prompt:Array.isArray(t.prompt)?t.prompt:[],metadata:c(t.metadata)?t.metadata:{}},f),g=Nr(m,d);return{sessionId:s,runtimeSessionId:l.runtimeSessionId,result:g,updates:d}}finally{l.busy=!1,l.lastUsedAtMs=Date.now(),l.releaseAfterPrompt&&await this.closeSession(a,"release_after_prompt")}}async cancel(t){let n=o(t.agentId),r=o(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=o(t.agentId),s=o(t.taskId),i=o(t.executionId);if(!r||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let u=o(t.sessionId)||`dispatch-${i||s}`,a=o(t.instructions),l=Ir(t),d=Er(t),f=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",a?`instructions: ${a}`:"",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 ${ot} and ${Se}.`:"",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:u,prompt:f},n)}async requestPermission({agent:t,runtimeSessionId:n,request:r,emitUpdate:s}){let i=it(),a=this.runtimeSessionIndex.get(`${t.agentId}:${n}`)?.sessionId||n||it(),l={permissionId:i,agentId:t.agentId,sessionId:a,runtimeSessionId:n,request:c(r)?r:{},status:"pending",createdAt:B()};return s?.({sessionId:n,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=_(r?.timeoutMs,this.config.permissionRequestTimeoutMs),m=setTimeout(()=>{this.pendingPermissions.delete(i),d({permissionId:i,outcome:"denied",response:{reason:"permission request timed out"}})},f);this.pendingPermissions.set(i,{timer:m,resolve:d,permission:l})})}async respondPermission(t){let n=o(t.permissionId),r=this.pendingPermissions.get(n),s=o(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:o(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:F,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 br from"node:http";import kr from"node:https";import{randomBytes as Ie}from"node:crypto";var ut=1,Ut=3,lt=class{constructor(t){this.url=t,this.readyState=0,this.socket=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,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:"?kr:br,r=Ie(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"}});s.on("upgrade",(i,u,a)=>{this.socket=u,this.readyState=ut,u.on("data",l=>this.onData(l)),u.on("close",()=>this.onClose()),u.on("error",l=>{this.emit("error",{error:l,message:l.message,type:"error"}),this.onClose()}),a?.length&&this.onData(a),this.emit("open")}),s.on("response",i=>{this.emit("error",{message:`websocket upgrade failed: HTTP ${i.statusCode}`,type:"error"}),i.resume(),this.onClose()}),s.on("error",i=>{this.emit("error",{error:i,message:i.message,type:"error"}),this.onClose()}),s.end()}send(t){!this.socket||this.readyState!==ut||this.socket.write(Mt(1,Buffer.from(String(t),"utf8")))}close(){!this.socket||this.readyState===Ut||(this.socket.write(Mt(8,Buffer.alloc(0))),this.socket.end(),this.onClose())}onClose(){this.readyState!==Ut&&(this.readyState=Ut,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,u=r&127,a=2;if(u===126){if(this.buffer.length<a+2)return;u=this.buffer.readUInt16BE(a),a+=2}else if(u===127){if(this.buffer.length<a+8)return;let f=this.buffer.readUInt32BE(a),m=this.buffer.readUInt32BE(a+4);u=f*2**32+m,a+=8}let l=a;if(i&&(a+=4),this.buffer.length<a+u)return;let d=this.buffer.subarray(a,a+u);if(i){let f=this.buffer.subarray(l,l+4);d=Buffer.from(d.map((m,g)=>m^f[g%4]))}this.buffer=this.buffer.subarray(a+u),s===1?this.emit("message",{data:d.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write(Mt(10,d))}}};function Mt(e,t){let n=t.length,r=2;n>=126&&n<=65535?r+=2:n>65535&&(r+=8);let s=Ie(4),i=Buffer.alloc(r+4+n);i[0]=128|e;let u=2;n<126?i[1]=128|n:n<=65535?(i[1]=254,i.writeUInt16BE(n,u),u+=2):(i[1]=255,i.writeUInt32BE(Math.floor(n/2**32),u),i.writeUInt32BE(n>>>0,u+4),u+=8),s.copy(i,u),u+=4;for(let a=0;a<n;a+=1)i[u+a]=t[a]^s[a%4];return i}function Lr(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 Pr(e){return Object.entries(e||{}).map(([t,n])=>({targetCode:t,targetName:o(n?.name||n?.targetName||t),targetType:o(n?.type||"echo"),status:"available",metadata:c(n)?n:{}}))}var dt=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(){let t=Lr(this.config.orchaUrl),n=new lt(t);this.ws=n,n.addEventListener("open",()=>this.authenticate()),n.addEventListener("message",r=>this.handleMessage(r.data)),n.addEventListener("close",()=>this.scheduleReconnect("close")),n.addEventListener("error",r=>{p("warn","orcha-client","runtime node websocket error",{error:String(r?.message||r?.type||r)})})}authenticate(){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:F,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,targets:Pr(this.config.targets)})}scheduleReconnect(t){this.connected=!1,!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){let n;try{n=JSON.parse(String(t))}catch(r){p("warn","orcha-client","invalid Orcha websocket frame",{error:String(r)});return}if(c(n)){if(n.type==="runtime_node.authenticated"){this.connected=!0,p("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:n.connectionId});return}if(n.type==="orcha.runtime.request"){await this.handleRequest(n);return}n.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString()})}}async handleRequest(t){let n=o(t.id),r=o(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){return!this.ws||this.ws.readyState!==ut?!1:(this.ws.send(JSON.stringify(t)),!0)}};import{existsSync as Dr,readFileSync as Fr}from"node:fs";import{resolve as Re}from"node:path";var $r=/^[A-Za-z_][A-Za-z0-9_]*$/;function xe(e=process.env,t=process.cwd()){let n=o(e.ORCHA_RUNTIME_ENV_FILE),r=n?Re(t,n):Re(t,".env");if(!Dr(r))return n&&p("warn","config","runtime env file not found",{path:r}),{loaded:!1,path:r,keys:[]};let s=[],i=Fr(r,"utf8");for(let u of i.split(/\r?\n/)){let a=vr(u);if(!a)continue;let[l,d]=a;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 Ae(e=process.env){return{mode:o(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),host:e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1",port:_(e.ORCHA_RUNTIME_BRIDGE_PORT,5588),token:e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",orchaUrl:o(e.ORCHA_RUNTIME_ORCHA_URL),nodeToken:e.ORCHA_RUNTIME_NODE_TOKEN||e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",nodeId:o(e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"local-runtime-node"),nodeName:o(e.ORCHA_RUNTIME_NODE_NAME||e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"Local Runtime Node"),reconnectMs:_(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:_(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),sessionPromptTimeoutMs:_(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,36e5),permissionRequestTimeoutMs:_(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:_(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:_(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:_(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:_(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:_(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),targets:Hr(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function Hr(e){if(!o(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 vr(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(!$r.test(s))return null;let i=zr(n.slice(r+1).trim());return[s,i]}function zr(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let n=e.slice(1,-1);return t==='"'?Br(n):n}return Gr(e).trim()}function Br(e){return e.replaceAll("\\n",`
16
- `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function Gr(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 jr}from"node:http";function ft(e,t,n){let r=JSON.stringify(n);e.writeHead(t,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(r)}),e.end(r)}function k(e={}){return{ok:!0,...e}}function Nt(e,t,n){return{ok:!1,error:{code:e,message:t,...n===void 0?{}:{detail:n}}}}async function Ce(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 Oe(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 Ue(e,t){let n={"GET /health":async()=>k(t.health()),"POST /agents/create":async r=>k(await t.createAgent(r)),"POST /agents/dispatch":async r=>k(await t.dispatch(r)),"POST /sessions/prompt":async r=>k(await t.prompt(r)),"POST /sessions/cancel":async r=>k(await t.cancel(r)),"POST /permissions/respond":async r=>k(await t.respondPermission(r))};return jr(async(r,s)=>{let i=new URL(r.url||"/",`http://${r.headers.host||`${e.host}:${e.port}`}`),u=`${r.method||"GET"} ${i.pathname}`,a=n[u];if(!a){ft(s,404,Nt("NOT_FOUND",`No route for ${u}`));return}try{Oe(r,e.token);let l=r.method==="GET"?{}:await Ce(r,e.requestLimitBytes);ft(s,200,await a(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";ft(s,d,Nt(f,l.message||String(l)))}})}var Zr=Yr(import.meta.url),Qr=".orcha-runtime-bridge.pid",ts=".orcha-runtime-bridge.log",es=3,ns=36e5,{command:rs,options:He}=as(process.argv.slice(2));cs(He);xe();var ss=Ae();await is(rs,ss,He);async function is(e,t,n){switch(e){case"run":case"foreground":Ne(t);return;case"start":if(n.foreground){Ne(t);return}ke();return;case"reload":case"restart":await Le({quiet:!0}),ke();return;case"stop":await Le();return;case"status":os();return;case"help":case"--help":case"-h":fs();return;default:throw new Error(`Unknown command: ${e}`)}}function Ne(e){us();let t=new ct(e);if(e.mode==="server"){let r=Ue(e,t);be({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 dt(e,t);be({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 be({bridge:e,client:t,server:n}){let r=!1,s=i=>{if(r)return;r=!0;let u=Number(e?.sessions?.size||0)>0;p("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(a){p("warn","runtime-bridge","runtime client stop failed",{error:String(a)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(a=>{p("warn","runtime-bridge","runtime bridge stop failed",{error:String(a)})}).finally(()=>{try{n?.close?.()}catch(a){p("warn","runtime-bridge","runtime server close failed",{error:String(a)})}}),setTimeout(()=>process.exit(0),u?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function ke(){let e=Dt(),t=ve(),n=Ft(e);if(n&&v(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:e,logFile:t}));return}n&&Lt(e),De(e),De(t),kt(t);let r=Wr(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=Kr(process.execPath,[Zr,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",r,r]});i.unref(),qr(r),$e(e,`${i.pid}
17
- `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function Le({quiet:e=!1}={}){let t=Dt(),n=Ft(t);if(!n){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!v(n)){Lt(t),e||console.log(JSON.stringify({status:"not_running",pid:n,pidFile:t}));return}process.kill(n,"SIGTERM"),!await Pe(n,1e4)&&v(n)&&(process.kill(n,"SIGKILL"),await Pe(n,3e3)),Lt(t),e||console.log(JSON.stringify({status:"stopped",pid:n,pidFile:t}))}function os(){let e=Dt(),t=ve(),n=Ft(e),r=!!(n&&v(n));console.log(JSON.stringify({status:r?"running":"not_running",running:r,pid:r?n:null,pidFile:e,logFile:t}))}function as(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 cs(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 Dt(){return Pt(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Qr)}function ve(){return Pt(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||ts)}function us(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=ze();if(t<=0)return;let n=Pt(process.cwd(),e);kt(n,t);let r=ds();r<=0||setInterval(()=>kt(n,t),r).unref()}function kt(e,t=ze()){if(t<=0||!Fe(e))return;let n=0,r="";try{if(n=Me(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/),u=[],a=0;for(let d of i)d&&(ls(d,s)?u.push(d):a+=1);if(a===0)return;let l="";try{Me(e).size>n&&(l=bt(e,"utf8").slice(r.length));let f=[...u,...l.split(/\r?\n/).filter(Boolean)].join(`
18
- `);$e(e,f?`${f}
19
- `:""),p("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:a})}catch(d){p("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(d)})}}function ls(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 ze(){return Be(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,es)}function ds(){return Be(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,ns)}function Be(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function Ft(e){if(!Fe(e))return null;let t=Number.parseInt(bt(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function v(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function Pe(e,t){let n=Date.now();for(;Date.now()-n<t;){if(!v(e))return!0;await new Promise(r=>setTimeout(r,100))}return!v(e)}function De(e){Jr(Vr(e),{recursive:!0})}function Lt(e){try{Xr(e,{force:!0})}catch{}}function fs(){console.log(`Usage: orcha-runtime-bridge [command] [options]
10
+ ${s}`:s;t.emittedTexts.add(s),u=1,a=1,r({sessionId:n,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}})}return s&&i&&(t.finalTextSeen=!0),de(t,le(e,t.artifactOptions)),(er(e)||i)&&r({sessionId:n,update:{sessionUpdate:"runtime_event",event:fe(e)}}),{textCount:u,finalTextCount:a}}function Et(e,t,n,r,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0};let i=e.artifacts.size,u=0,a=0,l=0,d=Qn(t,n,s);if(d){let f=Math.min(t.processedLines.get(d.path)||0,d.events.length),h=e.artifacts.size;for(let g of d.events.slice(f)){let E=nr(g,e,n,r);a+=E.textCount,l+=E.finalTextCount}t.processedLines.set(d.path,d.events.length),(d.events.length>f||e.artifacts.size>h)&&(u=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:u,textCount:a,finalTextCount:l}}function rr(e,{remove:t=!0}={}){if(!e||!ie(e))return"";try{return ae(e,"utf8").trim()}catch{return""}finally{t&&et(e)}}function et(e){if(e)try{Rn(e)}catch{}}function sr(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)}}function ir(e){return new Promise(t=>setTimeout(t,e))}function or(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 ar(e,t,n,r,s,i){let u=Et(e,t,n,r,Date.now()),a=()=>or(e,n,r,rr(s,{remove:!1}));if(a()||e.finalTextSeen)return et(s),u;let l=Fn(i);if(l<=0||!t&&!s)return et(s),u;let d=Date.now()+l,f=Math.min(he(i),100);for(;!e.finalTextSeen&&Date.now()<d&&(await ir(Math.min(f,Math.max(0,d-Date.now()))),u=sr(u,Et(e,t,n,r,Date.now())),!a()););return et(s),u}var rt=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=o(this.target.command);if(!s)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let i=o(t.sessionId)||j(),u=J(t.prompt),a=o(this.target.promptMode||"stdin"),l=this.buildArgs(a,u),d=o(this.target.cwd)||this.agent.workspace||process.cwd(),f=Bn(this.target,i),h=f.root,g=jn(this.target,h),E=Dn(s,this.target),I={...this.target,targetCode:this.agent.targetCode,cwd:d},L=E?Jn(I,r):new Set,O=Pn(s,l,this.target)?C(ce(),`orcha-runtime-last-message-${j()}.txt`):"";O&&l.push("--output-last-message",O);let R=_(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,_(this.options.sessionPromptTimeoutMs,On)),U={...process.env,...c(this.target.env)?this.target.env:{},...a==="env"?{ORCHA_RUNTIME_PROMPT:u}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:i,ORCHA_RUNTIME_ARTIFACT_DIR:h},m=Sn(s,l,{cwd:d,env:U,stdio:["pipe","pipe","pipe"]});this.active.set(i,m),p("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:i,pid:m.pid,timeoutMs:R});let Ht="",pt=o(this.target.outputMode||"text"),M={artifacts:new Map,emittedTexts:new Set,value:"",artifactOptions:g,finalTextSeen:!1,finalTextOnly:Hn(s,this.target)},ht=E?zn(I,u,r,L):null;return m.stdout.setEncoding("utf8"),m.stdout.on("data",P=>this.handleStdout(P,pt,M,i,n)),m.stderr.setEncoding("utf8"),m.stderr.on("data",P=>{Ht+=P,this.target.emitStderr===!0&&n({sessionId:i,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:P}}})}),a==="stdin"?m.stdin.end(u):m.stdin.end(),await new Promise((P,je)=>{let K=!1,vt=!1,N=null,mt=ht&&$n(this.target)?setInterval(()=>{try{Et(M,ht,i,n)}catch(T){p("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:i,error:String(T?.message||T)})}},he(this.target)):null;mt?.unref?.();let zt=setTimeout(()=>{vt=!0,p("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:i,pid:m.pid,timeoutMs:R}),tt(m,"SIGTERM"),N=setTimeout(()=>{p("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:i,pid:m.pid}),tt(m,"SIGKILL")},Un),N.unref?.(),gt(Object.assign(new Error(`runtime CLI timed out after ${R}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},R);zt.unref?.();let Bt=()=>{clearTimeout(zt),mt&&clearInterval(mt),N&&!vt&&clearTimeout(N),Gn(f,{target:this.agent.targetCode,sessionId:i}),this.active.delete(i)},Ke=T=>{K||(K=!0,Bt(),P(T))},gt=T=>{K||(K=!0,Bt(),je(T))};m.on("error",T=>{p("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:i,pid:m.pid,error:String(T?.message||T)}),gt(T)}),m.on("exit",(T,Gt)=>{(async()=>{N&&(clearTimeout(N),N=null),pt==="json-lines"&&M.value.trim()&&this.handleStdout(`
11
+ `,pt,M,i,n);let D=await ar(M,ht,i,n,O,this.target);(D.artifactCount>0||D.textCount>0)&&p("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:i,artifactCount:D.artifactCount,textCount:D.textCount,finalTextCount:D.finalTextCount,transcriptCount:D.transcriptCount});let q=Ht.trim();q&&p("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:i,stderr:q}),p("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:i,pid:m.pid,exitCode:T,signal:Gt,artifactCount:M.artifacts.size,finalTextSeen:M.finalTextSeen}),Ke({stopReason:T===0?"end_turn":"error",exitCode:T,signal:Gt,_artifacts:[...M.artifacts.values()],...q?{stderr:q}:{}})})().catch(gt)})})}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 u=r.value.split(/\r?\n/);r.value=u.pop()||"";for(let a of u){let l=a.trim();if(l)try{let d=JSON.parse(l);de(r,le(d,r.artifactOptions)),i({sessionId:s,update:{sessionUpdate:"runtime_event",event:fe(d)}});let f=ue(d),h=pe(d);f&&vn(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:`${a}
12
+ `}}})}}}async sessionCancel(t){let n=o(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}),tt(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}),tt(r,"SIGTERM");this.active.clear()}};var It=24e3,Rt=8,Ct=50,At=6e3,cr=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),ur=10*60*1e3,lr=60*1e3,dr=8,fr=60*1e3,pr=1,ot="ORCHA_RUNTIME_RESULT_START",we="ORCHA_RUNTIME_RESULT_END",hr=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions"]),mr=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function gr(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:it()}}}function A(e){return e==null||e===""?!1:typeof e=="string"?o(e)!=="":Array.isArray(e)?e.length>0:c(e)?Object.keys(e).length>0:!0}function _r(e){let t=o(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return cr.has(t)}function b(e,t){let n=_(e,t);return Number.isFinite(n)&&n>0?n:t}function yr(e,t=!1){if(typeof e=="boolean")return e;let n=o(e).toLowerCase();return["true","1","yes","y","on"].includes(n)?!0:["false","0","no","n","off"].includes(n)?!1:t}function H(e){return o(e?.type||"echo")}function Tr(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 Ut(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=At)return e;let n=e.length-At;return`${e.slice(0,At)}... [truncated ${n} characters]`}if(t>=Rt)return Array.isArray(e)?`[array truncated at depth ${Rt}, items=${e.length}]`:c(e)?`[object truncated at depth ${Rt}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let n=e.slice(0,Ct).map(r=>Ut(r,t+1));return e.length>Ct&&n.push(`[truncated ${e.length-Ct} items]`),n}if(c(e)){let n={};for(let[r,s]of Object.entries(e))n[r]=Tr(r)?"[REDACTED]":Ut(s,t+1);return n}return String(e)}var Sr=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 wr(e){if(!c(e))return e;let t={};for(let n of Sr)A(e[n])&&(t[n]=e[n]);return t}function Er(e){if(!c(e))return e;let t={...e};return c(t.renderedPayload)&&(t.renderedPayload=wr(t.renderedPayload)),t}function xr(e){let t=c(e)?e:{},n={};A(t.metadata)&&(n.metadata=Er(t.metadata));for(let[r,s]of Object.entries(t))hr.has(r)||r==="metadata"||A(s)&&(n[r]=s);return n}function Ir(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 Rr(e){return o(Ir(e).kind).toLowerCase()==="decision"}function Cr(e){let t=xr(e);if(!A(t))return"";let n=JSON.stringify(Ut(t),null,2);if(n.length<=It)return n;let r=n.length-It;return`${n.slice(0,It)}
13
+ ... [truncated ${r} characters]`}function Ar(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 Or(e){if(!c(e))return"";let t=c(e.update)?e.update:e;return o(t.sessionUpdate)}function Ur(e){if(!Array.isArray(e))return"";let t=!1,n=[],r=[],s=[],i=()=>{n.length>0&&(r.push(n),n=[])};for(let a of e){let l=Or(a),d=Ar(a);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 Te(s);let u=r[r.length-1]||[];return Te(u)}function Mr(e){if(!c(e))return null;let t=c(e.update)?e.update:e;return o(t.sessionUpdate)!=="runtime_event"?null:c(t.event)?t.event:null}function Nr(e){if(!c(e))return"";let t=c(e.payload)?e.payload:{},n=o(e.type),r=o(t.type);if(n==="event_msg"){if(r==="task_complete")return o(t.last_agent_message||t.message||t.output);if(r==="agent_message"){let s=o(t.phase||t.status||t.stage).toLowerCase();if(["final_answer","final","complete","completed","done"].includes(s))return o(t.message||t.text||t.content)}}return""}function br(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let n=Nr(Mr(e[t]));if(n)return n}return""}function Te(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 kr(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 at(e){let t=String(e||"").trim();if(!t)return null;try{let n=JSON.parse(t);if(c(n)&&(xe(n)||A(n._artifacts)||A(n.artifacts)||A(n._decision)||A(n._meta)))return n}catch{}return null}function Lr(e){let t=String(e||"");if(!t)return"";let n=t.lastIndexOf(we);if(n<0)return"";for(let r=t.lastIndexOf(ot,n);r>=0;r=t.lastIndexOf(ot,r-1)){let s=t.slice(r+ot.length,n).trim();if(at(s))return s}return""}function Ee(e){let t=Lr(e);return t?at(t):null}function Se(e){let t=String(e||"").trim();if(!t)return null;let n=Ee(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=at(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=at(t.slice(s));if(i)return i}return null}function xe(e){if(!c(e))return!1;if(A(e.output))return!0;for(let t of["content","text","message","summary"])if(o(e[t]))return!0;return!!(_r(e.status)||o(e.error)||o(e.errorMessage))}function st(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 Ot(e,t,n){return{...e,...t,_meta:{...c(e._meta)?e._meta:{},...c(t._meta)?t._meta:{},runtimeOutputSource:n}}}function Pr(e,t){let n=st(e),r=typeof n.output=="string"?Ee(n.output):null;if(r)return Ot(n,st(r),"result_block");if(xe(n))return n;let s=br(t);if(s){let a=Se(s);return a?Ot(n,st(a),"final_event"):{...n,output:s,_meta:{...c(n._meta)?n._meta:{},runtimeOutputSource:"final_event"}}}let i=kr(Ur(t));if(!i)return n;let u=Se(i);return u?Ot(n,st(u),"updates"):{...n,output:i,_meta:{...c(n._meta)?n._meta:{},runtimeOutputSource:"updates"}}}var ct=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=B(),this.cleanupTimer=null,this.startSessionCleanup()}targetFor(t){let n=o(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=H(t)==="openclaw"?b(this.config.openClawSessionIdleTtlMs,fr):b(this.config.sessionIdleTtlMs,ur);return b(t?.sessionIdleTtlMs??t?.idleTtlMs,r)}targetMaxSessions(t){let r=H(t)==="openclaw"?b(this.config.openClawMaxSessions,pr):b(this.config.maxSessionsPerTarget,dr);return b(t?.maxSessions,r)}targetReleaseAfterPrompt(t){let n=H(t);return yr(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}startSessionCleanup(){let t=b(this.config.sessionCleanupIntervalMs,lr);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}idleTargetSessions(t){return[...this.sessions.entries()].filter(([,n])=>n.targetCode===t&&!n.busy).sort((n,r)=>(n[1].lastUsedAtMs||0)-(r[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){let r=this.targetMaxSessions(n);for(;this.sessionCountForTarget(t)>=r;){let s=this.idleTargetSessions(t);if(!s.length){let i=new Error(`runtime target session limit reached: ${t}`);throw i.code="RUNTIME_TARGET_SESSION_LIMIT",i}await this.closeSession(s[0][0],"target_session_limit")}}async createAgent(t){let n=o(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:o(t.framework||r),workspace:o(t.workspace),metadata:c(t.metadata)?t.metadata:{},createdAt:B(),runtimeKind:H(s)};return this.agents.set(n,i),{agent:i}}runtimeFor(t,n){let{target:r}=this.targetFor(t.targetCode),s=H(r),i={onPermissionRequest:a=>this.requestPermission(a)},u={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs};return s==="stdio-acp"||s==="acp"?new $(t,r,i,u):s==="openclaw"?new Z(t,r,n,i,u):s==="cli"?new rt(t,r,u):new W(t)}async prompt(t,n={}){let r=o(t.agentId),s=o(t.sessionId)||it();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,metadata:t.metadata})).agent,u=o(t.workspace);u&&u!==i.workspace&&(i.workspace=u);let a=`${r}:${s}`;await this.cleanupExpiredSessions();let l=this.sessions.get(a);if(!l){let{code:h,target:g}=this.targetFor(i.targetCode);await this.reserveTargetSlot(h,g);let E=this.runtimeFor(i,s),I=await E.sessionNew({cwd:i.workspace||process.cwd(),metadata:c(t.metadata)?t.metadata:{}}),L=Date.now();l={agentId:r,sessionId:s,runtime:E,targetCode:h,runtimeKind:H(g),runtimeSessionId:o(c(I)?I.sessionId:"")||s,idleTtlMs:this.targetIdleTtlMs(g),releaseAfterPrompt:this.targetReleaseAfterPrompt(g),createdAtMs:L,lastUsedAtMs:L,busy:!1,createdAt:B()},this.sessions.set(a,l),this.runtimeSessionIndex.set(`${r}:${l.runtimeSessionId}`,l)}if(l.busy){let h=new Error(`runtime session is already running: ${s}`);throw h.code="RUNTIME_SESSION_BUSY",h}l.busy=!0,l.lastUsedAtMs=Date.now();let d=[],f=h=>{let g=gr(h,s,l);d.push(g),n.onUpdate?.(g)};try{let h=await l.runtime.sessionPrompt({sessionId:l.runtimeSessionId,prompt:Array.isArray(t.prompt)?t.prompt:[],metadata:c(t.metadata)?t.metadata:{}},f),g=Pr(h,d);return{sessionId:s,runtimeSessionId:l.runtimeSessionId,result:g,updates:d}}finally{l.busy=!1,l.lastUsedAtMs=Date.now(),l.releaseAfterPrompt&&await this.closeSession(a,"release_after_prompt")}}async cancel(t){let n=o(t.agentId),r=o(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=o(t.agentId),s=o(t.taskId),i=o(t.executionId);if(!r||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let u=o(t.sessionId)||`dispatch-${i||s}`,a=o(t.instructions),l=Cr(t),d=Rr(t),f=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",a?`instructions: ${a}`:"",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 ${ot} and ${we}.`:"",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:u,prompt:f},n)}async requestPermission({agent:t,runtimeSessionId:n,request:r,emitUpdate:s}){let i=it(),a=this.runtimeSessionIndex.get(`${t.agentId}:${n}`)?.sessionId||n||it(),l={permissionId:i,agentId:t.agentId,sessionId:a,runtimeSessionId:n,request:c(r)?r:{},status:"pending",createdAt:B()};return s?.({sessionId:n,update:{sessionUpdate:"permission_request",permission:l}}),await new Promise(d=>{let f=_(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=o(t.permissionId),r=this.pendingPermissions.get(n),s=o(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:o(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:F,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 Dr from"node:http";import Fr from"node:https";import{randomBytes as Ie}from"node:crypto";var ut=1,Mt=3,lt=class{constructor(t){this.url=t,this.readyState=0,this.socket=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,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:"?Fr:Dr,r=Ie(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"}});s.on("upgrade",(i,u,a)=>{this.socket=u,this.readyState=ut,u.on("data",l=>this.onData(l)),u.on("close",()=>this.onClose()),u.on("error",l=>{this.emit("error",{error:l,message:l.message,type:"error"}),this.onClose()}),a?.length&&this.onData(a),this.emit("open")}),s.on("response",i=>{this.emit("error",{message:`websocket upgrade failed: HTTP ${i.statusCode}`,type:"error"}),i.resume(),this.onClose()}),s.on("error",i=>{this.emit("error",{error:i,message:i.message,type:"error"}),this.onClose()}),s.end()}send(t){!this.socket||this.readyState!==ut||this.socket.write(Nt(1,Buffer.from(String(t),"utf8")))}close(){!this.socket||this.readyState===Mt||(this.socket.write(Nt(8,Buffer.alloc(0))),this.socket.end(),this.onClose())}onClose(){this.readyState!==Mt&&(this.readyState=Mt,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,u=r&127,a=2;if(u===126){if(this.buffer.length<a+2)return;u=this.buffer.readUInt16BE(a),a+=2}else if(u===127){if(this.buffer.length<a+8)return;let f=this.buffer.readUInt32BE(a),h=this.buffer.readUInt32BE(a+4);u=f*2**32+h,a+=8}let l=a;if(i&&(a+=4),this.buffer.length<a+u)return;let d=this.buffer.subarray(a,a+u);if(i){let f=this.buffer.subarray(l,l+4);d=Buffer.from(d.map((h,g)=>h^f[g%4]))}this.buffer=this.buffer.subarray(a+u),s===1?this.emit("message",{data:d.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write(Nt(10,d))}}};function Nt(e,t){let n=t.length,r=2;n>=126&&n<=65535?r+=2:n>65535&&(r+=8);let s=Ie(4),i=Buffer.alloc(r+4+n);i[0]=128|e;let u=2;n<126?i[1]=128|n:n<=65535?(i[1]=254,i.writeUInt16BE(n,u),u+=2):(i[1]=255,i.writeUInt32BE(Math.floor(n/2**32),u),i.writeUInt32BE(n>>>0,u+4),u+=8),s.copy(i,u),u+=4;for(let a=0;a<n;a+=1)i[u+a]=t[a]^s[a%4];return i}function $r(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 Hr(e){return Object.entries(e||{}).map(([t,n])=>({targetCode:t,targetName:o(n?.name||n?.targetName||t),targetType:o(n?.type||"echo"),status:"available",metadata:c(n)?n:{}}))}var dt=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(){let t=$r(this.config.orchaUrl),n=new lt(t);this.ws=n,n.addEventListener("open",()=>this.authenticate()),n.addEventListener("message",r=>this.handleMessage(r.data)),n.addEventListener("close",()=>this.scheduleReconnect("close")),n.addEventListener("error",r=>{p("warn","orcha-client","runtime node websocket error",{error:String(r?.message||r?.type||r)})})}authenticate(){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:F,protocolVersion:"orcha-runtime-node.v1",defaultTargetCode:this.config.defaultTargetCode,targets:Hr(this.config.targets)})}scheduleReconnect(t){this.connected=!1,!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){let n;try{n=JSON.parse(String(t))}catch(r){p("warn","orcha-client","invalid Orcha websocket frame",{error:String(r)});return}if(c(n)){if(n.type==="runtime_node.authenticated"){this.connected=!0,p("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:n.connectionId});return}if(n.type==="orcha.runtime.request"){await this.handleRequest(n);return}n.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString()})}}async handleRequest(t){let n=o(t.id),r=o(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){return!this.ws||this.ws.readyState!==ut?!1:(this.ws.send(JSON.stringify(t)),!0)}};import{existsSync as vr,readFileSync as zr}from"node:fs";import{resolve as Re}from"node:path";var Br=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ce(e=process.env,t=process.cwd()){let n=o(e.ORCHA_RUNTIME_ENV_FILE),r=n?Re(t,n):Re(t,".env");if(!vr(r))return n&&p("warn","config","runtime env file not found",{path:r}),{loaded:!1,path:r,keys:[]};let s=[],i=zr(r,"utf8");for(let u of i.split(/\r?\n/)){let a=jr(u);if(!a)continue;let[l,d]=a;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 Ae(e=process.env){return{mode:o(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),host:e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1",port:_(e.ORCHA_RUNTIME_BRIDGE_PORT,5588),token:e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",orchaUrl:o(e.ORCHA_RUNTIME_ORCHA_URL),nodeToken:e.ORCHA_RUNTIME_NODE_TOKEN||e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",nodeId:o(e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"local-runtime-node"),nodeName:o(e.ORCHA_RUNTIME_NODE_NAME||e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"Local Runtime Node"),reconnectMs:_(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:_(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),sessionPromptTimeoutMs:_(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,36e5),permissionRequestTimeoutMs:_(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:_(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:_(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:_(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:_(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:_(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),targets:Gr(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function Gr(e){if(!o(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 jr(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(!Br.test(s))return null;let i=Kr(n.slice(r+1).trim());return[s,i]}function Kr(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let n=e.slice(1,-1);return t==='"'?qr(n):n}return Jr(e).trim()}function qr(e){return e.replaceAll("\\n",`
16
+ `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function Jr(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 Wr}from"node:http";function ft(e,t,n){let r=JSON.stringify(n);e.writeHead(t,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(r)}),e.end(r)}function k(e={}){return{ok:!0,...e}}function bt(e,t,n){return{ok:!1,error:{code:e,message:t,...n===void 0?{}:{detail:n}}}}async function Oe(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 Ue(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 Me(e,t){let n={"GET /health":async()=>k(t.health()),"POST /agents/create":async r=>k(await t.createAgent(r)),"POST /agents/dispatch":async r=>k(await t.dispatch(r)),"POST /sessions/prompt":async r=>k(await t.prompt(r)),"POST /sessions/cancel":async r=>k(await t.cancel(r)),"POST /permissions/respond":async r=>k(await t.respondPermission(r))};return Wr(async(r,s)=>{let i=new URL(r.url||"/",`http://${r.headers.host||`${e.host}:${e.port}`}`),u=`${r.method||"GET"} ${i.pathname}`,a=n[u];if(!a){ft(s,404,bt("NOT_FOUND",`No route for ${u}`));return}try{Ue(r,e.token);let l=r.method==="GET"?{}:await Oe(r,e.requestLimitBytes);ft(s,200,await a(l))}catch(l){let d=l.status||500,f=l.code||"BRIDGE_INTERNAL";ft(s,d,bt(f,l.message||String(l)))}})}var ns=es(import.meta.url),rs=".orcha-runtime-bridge.pid",ss=".orcha-runtime-bridge.log",is=3,os=36e5,{command:as,options:ve}=ds(process.argv.slice(2));fs(ve);Ce();var cs=Ae();await us(as,cs,ve);async function us(e,t,n){switch(e){case"run":case"foreground":be(t);return;case"start":if(n.foreground){be(t);return}Le();return;case"reload":case"restart":await Pe({quiet:!0}),Le();return;case"stop":await Pe();return;case"status":ls();return;case"help":case"--help":case"-h":gs();return;default:throw new Error(`Unknown command: ${e}`)}}function be(e){ps();let t=new ct(e);if(e.mode==="server"){let r=Me(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 dt(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 u=Number(e?.sessions?.size||0)>0;p("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(a){p("warn","runtime-bridge","runtime client stop failed",{error:String(a)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(a=>{p("warn","runtime-bridge","runtime bridge stop failed",{error:String(a)})}).finally(()=>{try{n?.close?.()}catch(a){p("warn","runtime-bridge","runtime server close failed",{error:String(a)})}}),setTimeout(()=>process.exit(0),u?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function Le(){let e=Ft(),t=ze(),n=$t(e);if(n&&v(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:e,logFile:t}));return}n&&Pt(e),Fe(e),Fe(t),Lt(t);let r=Zr(t,"a"),s={...process.env,ORCHA_RUNTIME_PID_FILE:e,ORCHA_RUNTIME_LOG_FILE:t},i=Xr(process.execPath,[ns,"run"],{cwd:process.cwd(),detached:!0,env:s,stdio:["ignore",r,r]});i.unref(),Vr(r),He(e,`${i.pid}
17
+ `),console.log(JSON.stringify({status:"started",pid:i.pid,pidFile:e,logFile:t}))}async function Pe({quiet:e=!1}={}){let t=Ft(),n=$t(t);if(!n){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!v(n)){Pt(t),e||console.log(JSON.stringify({status:"not_running",pid:n,pidFile:t}));return}process.kill(n,"SIGTERM"),!await De(n,1e4)&&v(n)&&(process.kill(n,"SIGKILL"),await De(n,3e3)),Pt(t),e||console.log(JSON.stringify({status:"stopped",pid:n,pidFile:t}))}function ls(){let e=Ft(),t=ze(),n=$t(e),r=!!(n&&v(n));console.log(JSON.stringify({status:r?"running":"not_running",running:r,pid:r?n:null,pidFile:e,logFile:t}))}function ds(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 fs(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 Ft(){return Dt(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||rs)}function ze(){return Dt(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||ss)}function ps(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=Be();if(t<=0)return;let n=Dt(process.cwd(),e);Lt(n,t);let r=ms();r<=0||setInterval(()=>Lt(n,t),r).unref()}function Lt(e,t=Be()){if(t<=0||!$e(e))return;let n=0,r="";try{if(n=Ne(e).size,n<=0)return;r=kt(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/),u=[],a=0;for(let d of i)d&&(hs(d,s)?u.push(d):a+=1);if(a===0)return;let l="";try{Ne(e).size>n&&(l=kt(e,"utf8").slice(r.length));let f=[...u,...l.split(/\r?\n/).filter(Boolean)].join(`
18
+ `);He(e,f?`${f}
19
+ `:""),p("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:a})}catch(d){p("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(d)})}}function hs(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 Be(){return Ge(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,is)}function ms(){return Ge(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,os)}function Ge(e,t){let n=Number.parseInt(String(e??""),10);return Number.isFinite(n)&&n>=0?n:t}function $t(e){if(!$e(e))return null;let t=Number.parseInt(kt(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function v(e){try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function De(e,t){let n=Date.now();for(;Date.now()-n<t;){if(!v(e))return!0;await new Promise(r=>setTimeout(r,100))}return!v(e)}function Fe(e){Yr(ts(e),{recursive:!0})}function Pt(e){try{Qr(e,{force:!0})}catch{}}function gs(){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.14",
3
+ "version": "0.1.15",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local Orcha runtime bridge for ACP-compatible agent runtimes.",