@orcha-ai/runtime-bridge 0.1.11 → 0.1.13

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