@orcha-ai/runtime-bridge 0.1.57 → 0.1.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,8 @@ orcha-runtime-bridge connect --url https://orcha.example.com
24
24
 
25
25
  `connect` exchanges the one-time code in the foreground, then starts the existing daemon manager with the saved profile. The code and device credential are not passed to the background command. Reconnecting an already running device returns its existing process; stop it first before replacing its pairing.
26
26
 
27
+ Since 0.1.58, network failures reconnect with exponential backoff and jitter, capped at 60 seconds; successful authentication resets the delay. An HTTP or `runtime_node.error` 401/403 stops reconnecting. Update the device credentials and restart Bridge to connect again; rejected credentials are never retried indefinitely.
28
+
27
29
  Manage the device from any terminal directory with the same server address:
28
30
 
29
31
  ```bash
@@ -45,9 +47,9 @@ Device Bridge advertises `agents/models` through `supportedMethods` on the exist
45
47
 
46
48
  Per-conversation selections reach Codex `turn/start` as `model` / `effort`, or Claude Code as `--model` / `--effort`. Clearing a Codex selection resolves the workspace's native defaults before resuming; Claude uses its native `default` alias. Native session identity, approvals and task MCP bindings remain in place. A running operation's identity includes these controls, so reconnect cannot substitute another selection. The actual model is recorded only when reported by the native runtime.
47
49
 
48
- The platform stores selections on the agent's conversation member and freezes them when a message is accepted, including settings used by later group delegations. Only that agent's owner can edit its settings in a group. Group ownership and administrator roles do not grant this permission. Authorized shared users can choose settings for their own direct conversations.
50
+ The platform stores selections on the agent's conversation member and freezes them when a message is accepted, including settings used by later group delegations. Only the current group owner can edit member model and reasoning settings, and they must have permission to use that agent. Agent ownership and administrator roles alone do not grant permission to change group settings. Group settings do not change the agent's global configuration or sharing rules. Authorized shared users can choose settings for their own direct conversations.
49
51
 
50
- Rollout requires the approved member-column migration on Core, then Bridge 0.1.57 or later installed and reloaded on the device. Existing Bridges retain device-default execution and reject explicit selections until upgraded. OpenClaw currently reports model controls as unsupported and keeps its native defaults; it never receives fabricated catalog choices. The source package has not been published to npm. Native catalog discovery has been checked locally; model execution through an upgraded real device remains an acceptance step.
52
+ Rollout requires the approved member-column migration on Core, then Bridge 0.1.57 or later installed and reloaded on the device. Existing Bridges retain device-default execution and reject explicit selections until upgraded. OpenClaw currently reports model controls as unsupported and keeps its native defaults; it never receives fabricated catalog choices. Version 0.1.57 was published to npm on 2026-10-16. Native catalog discovery has been checked locally; model execution through an upgraded real device remains an acceptance step.
51
53
 
52
54
  ## Discovery and execution
53
55
 
@@ -91,8 +93,8 @@ Build produces `bin/orcha-runtime-bridge.js` and the clean npm package in `dist/
91
93
  Version 0.1.44 routes replies, native `message` tool sends, and background notifications through the same Orcha IM sender, and streams native Channel tools and host-visible reasoning/process updates through the existing Orcha progress UI. The plugin sends response headers immediately and heartbeats every 15 seconds; task deadlines and transport timeouts remain explicit failures. Bridge and the bundled plugin must upgrade together: native delivery preflight and content negotiation reject the old JSON-only contract before starting a host turn. `orcha-runtime-node.v2` is unchanged. Deploying Orcha does not publish npm or upgrade connected devices automatically. Build and validate the release tarball before publishing:
92
94
 
93
95
  ```bash
94
- npm run release:check
95
- npm publish ./dist/orcha-ai-runtime-bridge-0.1.57.tgz --access public --registry=https://registry.npmjs.org
96
+ npm run release:check &&
97
+ npm publish ./dist/orcha-ai-runtime-bridge-0.1.59.tgz --access public --registry=https://registry.npmjs.org
96
98
  ```
97
99
 
98
100
  After updating the npm package on a device, run `orcha-runtime-bridge reload --url ...` to switch the existing background process to the installed version. `reload` and `restart` also install/update the bundled plugin for OpenClaw targets saved on that device, using the target's executable and environment. Bridge stops before `openclaw plugins install <bundled-path> --force` and `openclaw gateway restart`; it starts again only after Gateway health succeeds and any configured MCP binding endpoint passes native Channel protocol preflight. Targets sharing an executable and environment update together. Installation/restart/health failures stop the command with an error and leave Bridge stopped; fix the reported problem and rerun `reload`. Package/executable preflight failures leave the existing Bridge running. The earlier manually downloaded foreground process must be stopped before connecting with npm to avoid duplicate connections.
@@ -103,7 +105,11 @@ Native delivery uses `application/x-orcha-channel-events-v2+ndjson` with `heartb
103
105
 
104
106
  Tests cover discovery errors, paths, public-field filtering, immutable commands, exact OpenClaw IDs, atomic configuration, capacity, reconnect, MCP lifecycle and cancellation. The live Codex model test is opt-in (`ORCHA_TEST_REAL_CODEX` set to the installed CLI path) and spends one short turn of the local account; fixtures do not certify a real vendor account or OpenClaw Gateway version.
105
107
 
106
- To check reply classification against the real SDK without installing or starting a Gateway, extract the official `openclaw@2026.7.1` npm tarball and run `npm run test:openclaw-sdk -- /absolute/path/to/extracted/package`. This check imports the actual SDK functions, covering final text/media, reasoning, commentary, status/progress notices and TTS supplements; it does not replace a live host/model acceptance test.
108
+ To check reply classification against the real SDK without starting another Gateway, use an existing official `openclaw@2026.10.6` installation on its host and run `npm run test:openclaw-sdk -- /absolute/path/to/openclaw/package`. This check imports the actual SDK functions, covering final text/media, reasoning, commentary, status/progress notices and TTS supplements. `node scripts/check-openclaw-native-sdk.js /absolute/path/to/openclaw/package` also checks native target resolution, message actions and receipt reconciliation; neither replaces a live host/model acceptance test. Run these checks with the Node.js version required by the selected OpenClaw release.
109
+
110
+ Version 0.1.59 adapts the plugin to OpenClaw 2026.10.6. Each enabled account owns a Gateway lifecycle task that admits HTTP deliveries until stopped; stopping the account rejects new work and cancels and drains its active host turns. Readiness describes this local HTTP runtime, not a persistent connection to Core. Config and workspace resolution use the host's current runtime config and agent resolver rather than the retired `agents.list` layout. Ordinary queued sends opt into automatic unknown-send reconciliation so the host supplies durable delivery identities, and the sender checks the host's direct-handoff fence immediately before platform I/O. Existing account credentials, saved send identities, session boundaries and the native Channel stream protocol remain unchanged. Install the updated bundle on the OpenClaw host and restart that Gateway; deploying Core alone does not update the plugin.
111
+
112
+ Acceptance for 0.1.59: Bridge checks, fixture tests and build pass, as do both SDK checks against the host's installed OpenClaw 2026.10.6. The updated plugin was installed through the official plugin installer; Gateway health passed and Bridge restarted. A user-triggered live OrchaAI reply was confirmed. This bundle was installed directly on the existing device and has not been published to npm.
107
113
 
108
114
  ## Tool error warnings (0.1.46)
109
115
 
@@ -129,7 +135,7 @@ Device Codex accepts Core's existing `session-<id>:<human-member>:<agent-member>
129
135
 
130
136
  OpenClaw native Channel, device Codex and device Claude Code conversations send only the current message and attachments. Orcha conversation IDs and optional historical task IDs define conversation boundaries; native runtimes own history and compaction. OpenClaw session keys include the Core endpoint, binding revision, chat/task/member and history/policy scope. Device Codex saves the thread ID returned by app-server `thread/start` under `~/.orcha/codex-sessions/` and resumes it with `thread/resume`; env-configured `codex exec` targets save `thread.started.thread_id` and use `codex exec resume <thread-id>`. The identity also includes the endpoint, Agent, target, workspace and Codex home. It never uses `--last`. Claude Code saves the `session_id` from its `system/init` event under `~/.orcha/claude-sessions/` and uses `claude -p --resume <session-id>`; the identity includes the endpoint, Agent, target, workspace and Claude config directory, and never uses `--continue`. Each turn still has a separate run ID, tool credential and retry fence. Device Codex and Claude Code close their temporary MCP proxy after each turn and open a fresh one for the next.
131
137
 
132
- Send exactly `/new` to an Agent to reset context while staying in the current conversation. It creates no model run and is not forwarded to OpenClaw, Codex or Claude Code. Core records a centered “已开始新对话” system notice; existing messages remain visible, while subsequent model context starts after this boundary. The receipt retains the same `sessionId` and task scope with `runId:null`. In a group, select an Agent explicitly; send the command without a quoted message, attachments, plugins or skills. Complete or stop unfinished work in that context before resetting. The existing history boundary in native session keys makes the next OpenClaw/Codex/Claude Code turn start a fresh native conversation. Other raw commands, such as `/status`, reach OpenClaw and remain subject to its own command permissions.
138
+ Send exactly `/new` to an Agent to reset context while staying in the current conversation. It creates no model run and is not forwarded to OpenClaw, Codex or Claude Code. The receipt retains the same `sessionId` and task scope with `runId:null`. In a group, select exactly one Agent explicitly; send the command without a quoted message, attachments, plugins or skills. Selecting an external member records an `external_session_reset` notice bound to that member through the existing message mention relation. Only that member's next native conversation changes; other members and the group's shared history, memory and checkpoints retain their boundaries. Only unfinished work belonging to the selected member blocks this reset, including delegated and background runs. Existing `context_reset` notices retain their shared-boundary meaning. Core supplies the resulting member-specific history floor through the existing native session scope or Channel delivery, so this change requires no Bridge update, schema migration or protocol version. See the authoritative [context reset rules](../docs/新文档/02-AI对话/36-默认长聊与独立话题列表交互建议.md#4-new-原地重置上下文). Other raw commands, such as `/status`, reach OpenClaw and remain subject to its own command permissions.
133
139
 
134
140
  Old Orcha history and per-run native sessions are not migrated or injected. Upgrade Core, Bridge and the bundled plugin together. A normal Bridge restart preserves completed Codex and Claude Code conversations. If a process crashes during a native turn, its durable lock remains and the affected conversation requires `/new`: automatically replaying a detached process could repeat side effects. Missing/mismatched native IDs and repeated run IDs fail explicitly. Keep the local Codex home or Claude config directory and the Orcha session mapping together; clearing either does not authorize silently starting over in the same conversation.
135
141
 
@@ -1,39 +1,39 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as mu}from"node:child_process";import{closeSync as hu,existsSync as Kr,mkdirSync as gu,openSync as _u,readFileSync as jr,rmSync as yu,statSync as Hs,writeFileSync as Gs}from"node:fs";import{dirname as Ks,resolve as Ct}from"node:path";import{fileURLToPath as wu}from"node:url";import{createHash as es}from"node:crypto";import{mkdir as ia,readFile as oa,writeFile as aa,rename as ca}from"node:fs/promises";import{join as ts}from"node:path";import{homedir as ua,hostname as la}from"node:os";import{execFile as ti}from"node:child_process";import{access as ei,realpath as ri}from"node:fs/promises";import{constants as ni}from"node:fs";import{delimiter as si,join as Xr,isAbsolute as Yr}from"node:path";import{homedir as Wr}from"node:os";async function xe(e,t=process.env){let r=process.platform==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of(t.PATH||"").split(si).filter(Yr))for(let s of r){let i=Xr(n,`${e}${s}`);try{return await ei(i,ni.X_OK),i}catch{}}return null}function ii(e,t){return new Promise(r=>ti(e,t,{timeout:8e3,maxBuffer:1024*1024,windowsHide:!0},(n,s)=>r({code:n?n.code:0,stdout:String(s||"")})))}async function Ae(e){let t=e==="~"?Wr():e.startsWith("~/")?Xr(Wr(),e.slice(2)):e;if(!Yr(t))throw new Error("\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u8BBE\u5907\u4E0A\u7684\u7EDD\u5BF9\u8DEF\u5F84\u6216 ~/ \u5F00\u5934\u7684\u8DEF\u5F84");let r=await ri(t),{stat:n}=await import("node:fs/promises");if(!(await n(r)).isDirectory())throw new Error("\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6\u5939");return r}async function Qr({find:e=xe,run:t=ii,cwd:r=process.cwd()}={}){return(await Promise.all(["codex","claude","openclaw"].map(async s=>{let i=await e(s);if(!i)return[];let o={codex:"Codex",claude:"Claude Code",openclaw:"OpenClaw"}[s],a=await t(i,["--version"]),c=a.code===0&&a.stdout.match(/\d+\.\d+\.\d+[^\s]*/)?.[0]||"",l={id:s,name:o,framework:s,version:c,workspace:r,managed:!1};if(a.code!==0)return[{...l,status:"error",message:"\u7A0B\u5E8F\u65E0\u6CD5\u542F\u52A8\uFF0C\u8BF7\u5728\u672C\u673A\u68C0\u67E5\u5B89\u88C5"}];if(s==="openclaw"){let f=await t(i,["agents","list","--json"]),h;try{h=JSON.parse(f.stdout)}catch{}if(f.code!==0||!Array.isArray(h))return[{...l,status:"error",message:"\u65E0\u6CD5\u8BFB\u53D6 OpenClaw \u667A\u80FD\u4F53\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u914D\u7F6E"}];let g=await t(i,["health","--json"]);return h.filter(w=>typeof w.id=="string"&&typeof w.workspace=="string").slice(0,32).map(w=>({...l,id:`openclaw:${w.id}`,name:w.name||w.identityName||w.id,workspace:w.workspace,managed:!0,localAgentId:w.id,command:i,status:g.code===0?"ready":"needs_setup",message:g.code===0?"":"\u8BF7\u5148\u5728\u672C\u673A\u542F\u52A8\u5E76\u914D\u7F6E OpenClaw Gateway"}))}let p=await t(i,s==="codex"?["login","status"]:["auth","status"]),m=p.code===0?"ready":p.code===1?"needs_login":"error";return[{...l,command:i,status:m,message:m==="needs_login"?`\u8BF7\u5728\u672C\u673A\u8FD0\u884C ${s} ${s==="codex"?"login":"auth login"}`:m==="error"?"\u767B\u5F55\u72B6\u6001\u68C0\u6D4B\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 CLI \u7248\u672C":""}]}))).flat()}import{spawn as ra}from"node:child_process";import{createInterface as na}from"node:readline";import{randomUUID as sa}from"node:crypto";import{createInterface as di}from"node:readline";var B="0.1.57";function Mt(){return new Date().toISOString()}function $(e,t=2){return String(e).padStart(t,"0")}function Zr(e){let t=e>=0?"+":"-",r=Math.abs(e);return`${t}${$(Math.floor(r/60))}:${$(r%60)}`}function oi(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${$(e.getMonth()+1)}-${$(e.getDate())}`,`T${$(e.getHours())}:${$(e.getMinutes())}:${$(e.getSeconds())}.${$(e.getMilliseconds(),3)}`,Zr(t)].join("")}function ai(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 ci(e,t){let r=ai(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}-${$(r.month)}-${$(r.day)}`,`T${$(r.hour)}:${$(r.minute)}:${$(r.second)}.${$(e.getMilliseconds(),3)}`,Zr(s)].join("")}function ui(e=new Date){let t=u(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return ci(e,t)}catch{return oi(e)}}function d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function u(e){return String(e??"").trim()}function R(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)?r:t}function k(e){return Array.isArray(e)?e.map(String):[]}function K(e,t,r=process.cwd()){let n=d(e)?e:{};return u(n.cwd)||u(n.workspace)||u(t)||u(r)||process.cwd()}var qt="[redacted]",li=/(authorization|api[_-]?key|credential|password|secret|token)/i;function rt(e){return li.test(u(e))}function ct(e,t=[]){let r=String(e??"");for(let n of t){let s=String(n??"");s.length>=4&&(r=r.split(s).join(qt))}return r.replace(/((?:authorization|api[_-]?key|credential|password|secret|token)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,`$1${qt}`).replace(/([?&](?:api[_-]?key|credential|password|secret|token)=)[^&\s]+/gi,`$1${qt}`)}function at(e,t=new WeakSet){if(e==null)return e;if(typeof e=="bigint")return e.toString();if(typeof e!="object")return e;if(e instanceof Date)return e.toISOString();if(e instanceof Error){if(t.has(e))return"[circular]";t.add(e);let s={name:e.name,message:e.message};e.stack&&(s.stack=e.stack);for(let i of Object.keys(e))s[i]=at(e[i],t);return t.delete(e),s}if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e)){let s=e.map(i=>at(i,t));return t.delete(e),s}let r={},n=rt(e.name||e.key);for(let[s,i]of Object.entries(e))r[s]=rt(s)||n&&s.toLowerCase()==="value"?qt:at(i,t);return t.delete(e),r}function tn(e,t=4e3){let r=JSON.stringify(at(e))??String(e);return!Number.isFinite(t)||r.length<=t?r:`${r.slice(0,t)}...`}function _(e,t,r,n={}){let s={ts:ui(),level:e,module:t,msg:r,...d(n)?at(n):{}};console.error(JSON.stringify(s))}function Gt(e,{onNotification:t=()=>{},onRequest:r=()=>{throw new Error("Unsupported request")}}={}){let n=1,s=new Map,i=o=>e.stdin.write(`${JSON.stringify(o)}
3
- `);return di({input:e.stdout}).on("line",o=>{if(!o.trim())return;let a;try{a=JSON.parse(o)}catch{_("warn","runtime.codex","ignored non-JSON app-server output");return}if(typeof a.method=="string"&&a.id!==void 0){Promise.resolve().then(()=>r(a.method,d(a.params)?a.params:{})).then(l=>i({id:a.id,result:l}),l=>i({id:a.id,error:{code:-32603,message:String(l?.message||l)}}));return}if(typeof a.method=="string"){t(a.method,d(a.params)?a.params:{});return}let c=s.get(a.id);c&&(s.delete(a.id),a.error?c.reject(Object.assign(new Error(u(a.error.message)||"Codex app-server request failed"),{code:"RUNTIME_CODEX_APP_SERVER_ERROR"})):c.resolve(a.result))}),e.once("exit",()=>{for(let o of s.values())o.reject(new Error("Codex app-server closed"));s.clear()}),{request:(o,a)=>new Promise((c,l)=>{let p=n++;s.set(p,{resolve:c,reject:l}),i({id:p,method:o,params:a})}),notify:o=>i({method:o})}}import{spawn as $n}from"node:child_process";import{randomUUID as wt}from"node:crypto";import{existsSync as Hn,mkdirSync as co,readdirSync as Fn,readFileSync as Bn,realpathSync as kt,rmSync as uo,rmdirSync as lo,statSync as po,unlinkSync as fo}from"node:fs";import{homedir as mo,tmpdir as jn}from"node:os";import{basename as Fe,dirname as ho,join as q,resolve as Pn}from"node:path";import{randomUUID as sn}from"node:crypto";import{existsSync as pi,readFileSync as fi,realpathSync as en,statSync as mi}from"node:fs";import{basename as on,extname as an,isAbsolute as Ut,join as hi,relative as cn,resolve as rn}from"node:path";var gi=25*1024*1024;function un(e,t=""){let r=u(t);if(r)return r;let n=an(u(e)).toLowerCase();return n===".jpg"||n===".jpeg"?"image/jpeg":n===".webp"?"image/webp":n===".gif"?"image/gif":"image/png"}function ln(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 Kt(e){if(Array.isArray(e))return e.map(u).filter(Boolean);let t=u(e);return t?[t]:[]}function _i(e,t){let r=cn(t,e);return r===""||!!r&&!r.startsWith("..")&&!Ut(r)}function yi(e,t){let r=u(e);if(!r||!pi(r))return"";try{let n=en(r);for(let s of t)try{let i=en(s);if(_i(n,i))return n}catch{}}catch{return""}return""}function wi(e,t){let r=u(e);if(!r||!Ut(r))return r;for(let n of Array.isArray(t)?t:[]){if(!d(n))continue;let s=u(n.runtimeRoot),i=u(n.hostRoot);if(!s||!i||!Ut(s)||!Ut(i))continue;let o=cn(rn(s),rn(r));if(o===""||!o.startsWith("..")&&!Ut(o))return o?hi(i,o):i}return r}function be(e,t,r={}){let n=u(e);return!n||n.startsWith("data:")||/^https?:\/\//i.test(n)?n:Ti(n,t,r)}function Ti(e,t,r={}){let n=[...Kt(r.trustedFileRoots),...Kt(r.trustedFileRoot),...Kt(r.artifactRoots),...Kt(r.artifactRoot)],s=yi(wi(e,r.pathMappings),n);if(!s)return"";try{let i=mi(s);return!i.isFile()||i.size<=0||i.size>gi?"":`data:${t};base64,${fi(s).toString("base64")}`}catch{return""}}function v(...e){for(let t of e){let r=u(t);if(r)return r}return""}function Ei(e,t,r,n){let s=r.toLowerCase();if(s==="image"||s==="picture")return!0;let i=v(n,e.previewUrl,e.fileUrl,e.imageUrl,e.dataUrl,e.url,e.uri,t.previewUrl,t.fileUrl,t.imageUrl,t.dataUrl,t.url,t.uri),o=an(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function Me(e,t={}){let{source:r="runtime_image_generation_event"}=t;if(!d(e))return null;let n=d(e.payload)?e.payload:{},s=u(e.type),i=u(n.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let o=v(n.call_id,n.id),a=v(n.saved_path,n.savedPath),c=v(n.revised_prompt,n.revisedPrompt),l=un(a,n.mimeType||n.mime_type),p=ln(n.result,l)||be(a,l,t);if(!p)return null;let m=p.startsWith("data:")?p:"",f=a?on(a):`${o||sn()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:f||"Generated image",summary:c||"Generated image",content:{prompt:c||void 0,dataUrl:m||void 0,imageUrl:p,previewUrl:p,fileUrl:p,mimeType:l},dataUrl:m||void 0,previewUrl:p,fileUrl:p,metadata:{source:r,eventType:i,callId:o||void 0,savedPath:a||void 0,filename:f,mimeType:l,revisedPrompt:c||void 0}}}function Oi(e){let t=d(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];d(s)&&r.push(s)}return r}function Si(e,t={}){let{source:r="runtime_artifact"}=t,n=d(e)?e:{};if(!Object.keys(n).length)return null;let s=d(n.content)?{...n.content}:{},i=d(n.metadata)?{...n.metadata}:{},o=v(n.saved_path,n.savedPath,s.saved_path,s.savedPath,i.savedPath),a=v(n.mimeType,n.mime_type,s.mimeType,s.mime_type,i.mimeType),c=v(n.artifactType,n.artifact_type,n.type,n.kind,s.type,o?"image":"file"),l=Ei(n,s,c,o),p=l?un(o,a):a;if(l){let I=v(n.dataUrl,s.dataUrl),E=I.startsWith("data:")?I:"",C=v(n.imageUrl,n.previewUrl,n.fileUrl,n.downloadUrl,n.url,n.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),y=ln(n.result??s.result,p)||E||be(o,p,t)||be(C,p,t);y&&(y.startsWith("data:")&&(s.dataUrl||=y),s.imageUrl||=y,s.previewUrl||=y,s.fileUrl||=y,p&&(s.mimeType||=p))}for(let[I,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[I];C!=null&&C!==""&&!(E in s)&&(s[E]=C)}let m=v(n.fileUrl,n.downloadUrl,n.imageUrl,n.dataUrl,n.url,n.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),f=v(n.previewUrl,n.imageUrl,n.dataUrl,n.url,n.fileUrl,n.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),h=v(n.dataUrl,s.dataUrl,m.startsWith("data:")?m:"",f.startsWith("data:")?f:""),g=v(n.filename,i.filename,o?on(o):""),w=v(n.fieldKey,n.field_key,s.fieldKey,i.fieldKey,l?"image":"artifact");return{...n,artifactType:c,type:n.type||c,fieldKey:w,title:v(n.title,g,"Runtime artifact"),summary:v(n.summary,s.prompt,n.title,g,"Runtime artifact"),content:s,dataUrl:h||void 0,fileUrl:m||void 0,previewUrl:f||void 0,metadata:{...i,source:v(i.source,r),savedPath:o||i.savedPath,filename:g||i.filename,mimeType:p||i.mimeType}}}function zt(e,t){if(!t||!e)return;let r=d(t.metadata)?t.metadata:{},n=v(r.savedPath,r.callId,t.previewUrl,t.fileUrl)||sn(),s=e.get(n);if(!s){e.set(n,t);return}s.content={...d(s.content)?s.content:{},...d(t.content)?t.content:{}},s.metadata={...d(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 Ne(e,t,r={}){for(let n of Oi(e))zt(t,Si(n,r))}function Ue(e){if(!d(e)||!d(e.payload))return d(e)?e:{value:e};let t=u(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 nn(e,t,r){if(!d(e))return e;let n=d(e.event)?e.event:null;return n?(zt(t,Me(n,r)),{...e,event:Ue(n)}):e}function dn(e,t,r={}){if(!d(e))return e;Ne(e,t,r);let n=nn(e,t,r),s=d(n.update)?nn(n.update,t,r):null;return s&&s!==n.update&&(n={...n,update:s}),n}function pn(e,t,r={}){let n=d(e)?{...e}:{};Ne(n,t,r),Ne(d(n.output)?n.output:{},t,r);let s=[...t?.values?.()||[]];return s.length&&(n._artifacts=s),delete n.artifacts,n}function yt(e){return Array.isArray(e)?e.map(t=>d(t)?t.type==="text"?u(t.text):t.type==="file"?u(t.uri):t.type==="image"?u(t.uri):"":"").filter(Boolean).join(`
4
- `):""}import{createHash as Gi,randomUUID as Ki}from"node:crypto";import{mkdirSync as In,readFileSync as zi,renameSync as Vi,rmSync as Ji,writeFileSync as Cn}from"node:fs";import{homedir as Le}from"node:os";import{join as lt}from"node:path";import{createServer as Ii}from"node:http";import{randomBytes as Ci}from"node:crypto";var Vt={controlTools:["find_capabilities_and_skills","describe_capability","inspect_result","execute_capability"],residentTools:["search_orcha_docs","knowledge_search"]};var xi=Object.freeze([...Vt.controlTools,...Vt.residentTools]),Ai=new Set(xi),bi=8*1024*1024;function Jt(e,t){if(!Array.isArray(e)||e.length!==1)throw new Error("one task-scoped Orcha MCP server is required");let r=e[0],n=new URL(r.url);if(r.name!=="orcha"||r.type!=="http"||!["http:","https:"].includes(n.protocol)||n.username||n.password||n.hash||t&&n.href!==new URL(t).href)throw new Error("Orcha MCP server does not match the trusted binding");let s=Object.fromEntries((r.headers||[]).map(({name:i,value:o})=>[i.toLowerCase(),o]));if(!String(s.authorization||"").startsWith("Bearer "))throw new Error("Orcha MCP task credentials are missing");return{url:n.href,headers:{...s,"content-type":"application/json",accept:"application/json"}}}async function mn(e){let t=0,r=[];for await(let n of e){if(t+=n.length,t>bi)throw new Error("MCP payload exceeds the size limit");r.push(Buffer.from(n))}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function hn(e,t,r){let n=await fetch(e.url,{method:"POST",headers:e.headers,body:JSON.stringify(t),redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(36e5),...r?[r]:[]])});if(!n.ok)throw new Error(`Orcha MCP request failed (${n.status})`);if(n.status===202||n.status===204)return null;let s=await mn(n.body);if(!s||s.jsonrpc!=="2.0"||s.id!==t.id)throw new Error("Orcha MCP response identity mismatch");return s}async function fn(e,t){let r=await hn(e,{jsonrpc:"2.0",id:"orcha-bind-tools",method:"tools/list"},t),n=r?.result?.tools;if(r?.error){let s=Object.entries(e.headers).filter(([a])=>rt(a)).flatMap(([,a])=>[a,String(a).replace(/^Bearer\s+/i,"")]),i=typeof r.error.message=="string"?ct(r.error.message,s).slice(0,512):"",o=Number.isInteger(r.error.code)?` (${r.error.code})`:"";throw new Error(`Orcha MCP tool discovery failed${o}${i?`: ${i}`:""}`)}return Ni(n)}function Ni(e){if(!Array.isArray(e)||e.some(t=>!t||!Ai.has(t.name)||t.inputSchema?.type!=="object"||typeof t.description!="string")||new Set(e.map(t=>t.name)).size!==e.length||e.length&&Vt.controlTools.some(t=>!e.some(r=>r.name===t)))throw new Error("Orcha MCP returned an unsupported or invalid authorized tool catalog");return e}function Mi(e,t){let r=s=>Array.isArray(s)?s.map(r):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(i=>[i,r(s[i])])):s,n=s=>s.map(({name:i,inputSchema:o})=>({name:i,inputSchema:o})).sort((i,o)=>i.name.localeCompare(o.name));return JSON.stringify(r(n(e)))===JSON.stringify(r(n(t)))}async function gn(e,t=[]){let r=Jt(e),n=new AbortController,s=await fn(r,n.signal);if(t.some(a=>s.some(c=>c.name===a.name)))throw new Error("Local and remote MCP tools conflict");let i=Ci(32).toString("hex"),o=Ii(async(a,c)=>{if(a.url!=="/mcp"||a.headers.authorization!==`Bearer ${i}`){c.writeHead(403).end();return}if(a.method!=="POST"){c.writeHead(405).end();return}try{let l=await mn(a);if(!l||l.jsonrpc!=="2.0"||typeof l.method!="string")throw new Error("Invalid MCP request");let p=l.method==="tools/call"&&t.find(f=>f.name===l.params?.name);if(l.method==="tools/call"&&!p&&!s.some(f=>f.name===l.params?.name))throw new Error("Tool is not authorized in this task binding");let m;if(p)try{m={jsonrpc:"2.0",id:l.id,result:await p.call(l.params.arguments,{upstream:r,signal:n.signal})}}catch(f){m={jsonrpc:"2.0",id:l.id,result:{isError:!0,content:[{type:"text",text:ct(String(f.message),[r.headers.authorization,i])}]}}}else m=await hn(r,l,n.signal),l.method==="tools/list"&&m?.result?.tools&&m.result.tools.push(...t.map(({call:f,...h})=>h));c.writeHead(m===null?202:200,{"content-type":"application/json"}),c.end(m===null?"":JSON.stringify(m))}catch{c.writeHead(502,{"content-type":"application/json"}).end(JSON.stringify({error:"The task-scoped Orcha MCP connection failed"}))}});return await new Promise((a,c)=>{o.once("error",c),o.listen(0,"127.0.0.1",a)}),{url:`http://127.0.0.1:${o.address().port}/mcp`,token:i,async refresh(a){let c=Jt(a,r.url);if(!Mi(s,await fn(c,n.signal)))throw new Error("The frozen MCP tool catalog changed; start a new task");r=c},async close(){n.abort(),o.closeAllConnections(),await new Promise(a=>o.close(a))}}}import{createHash as _n}from"node:crypto";import{constants as Pe}from"node:fs";import{open as Ui,realpath as yn}from"node:fs/promises";import{basename as Pi,isAbsolute as Li,relative as ki,resolve as vi}from"node:path";var Di=32*1024*1024,$i={name:"send_file",description:"Send one explicitly selected local file to the current OrchaAI conversation. Use this to deliver images, PDFs, documents, spreadsheets or other files to the user; viewing an image or writing a local Markdown link does not send it. path must be in the current workspace, a configured artifact root, or (Codex only) the current thread's generated_images directory. Copy other intended deliverables into the workspace first. Success means the attachment message is saved; do not send it again or embed the local path. Internal previews and intermediate files need not be sent.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string",minLength:1,description:"Absolute file path, or a path relative to the current workspace."},message:{type:"string",maxLength:1e4,description:"Optional short caption for the attachment message, such as what the file is. The attachment is saved as its own message and your final reply is still posted separately, so do not repeat the final reply's summary, findings or conclusions here; omit it when the final reply already explains the file."}}}};function wn(e){return{...$i,async call(t,{upstream:r,signal:n}){if(!t||typeof t.path!="string"||!t.path.trim()||Object.keys(t).some(y=>!["path","message"].includes(y))||t.message!==void 0&&(typeof t.message!="string"||t.message.length>1e4))throw new Error("send_file requires a file path and an optional caption of at most 10000 characters");let{cwd:s,roots:i}=e();if(!s)throw new Error("The current file delivery workspace is unavailable");let o=await yn(vi(s,t.path)),a=!1;for(let y of i)try{let O=ki(await yn(y),o);(!O||O!==".."&&!O.startsWith("../")&&!O.startsWith("..\\")&&!Li(O))&&(a=!0)}catch{}if(!a)throw new Error("File is outside the current workspace and authorized artifact roots");let c=await Ui(o,Pe.O_RDONLY|Pe.O_NOFOLLOW|Pe.O_NONBLOCK),l;try{let y=await c.stat();if(!y.isFile()||y.size<=0||y.size>Di)throw new Error("Select a non-empty regular file of at most 32 MiB");l=Buffer.alloc(y.size);let O=0;for(;O<l.length;){let{bytesRead:A}=await c.read(l,O,l.length-O,O);if(!A)throw new Error("File changed while preparing delivery; retry after it is saved");O+=A}let M=await c.stat();if(M.size!==y.size||M.mtimeMs!==y.mtimeMs)throw new Error("File changed while preparing delivery; retry after it is saved")}finally{await c.close()}let p=t.message||"",m=Pi(o),f=_n("sha256").update(l).digest("hex"),h=_n("sha256").update(JSON.stringify([o,f,p])).digest("hex"),g=new FormData;g.set("deliveryId",h),g.set("message",p),g.set("file",new Blob([l]),m);let w=new URL(r.url);w.pathname=`${w.pathname.replace(/\/$/,"")}/files`;let I=await fetch(w,{method:"POST",headers:{authorization:r.headers.authorization},body:g,redirect:"error",signal:AbortSignal.any([n,AbortSignal.timeout(12e4)])});if(!I.ok)throw new Error(`File delivery failed (HTTP ${I.status}); no successful receipt was received`);let E=await I.json();if(!E.success)throw new Error(`File delivery failed: ${String(E.message||E.code||"request rejected").slice(0,512)}`);let C=E.data;if(!C?.accepted||typeof C.messageId!="string"||!C.messageId||typeof C.fileId!="string"||!C.fileId)throw new Error("File delivery did not return a saved message and file receipt");return{content:[{type:"text",text:JSON.stringify(C)}],structuredContent:C,isError:!1}}}}var Hi=new Set(["Bash","PowerShell"]),Fi=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Bi="SandboxNetworkAccess",Tn=2e3,En=50;function ut(e,t=0){return typeof e=="string"?e.length>Tn?`${e.slice(0,Tn)}\u2026`:e:t>=4&&(Array.isArray(e)||d(e))?"\u2026":Array.isArray(e)?e.slice(0,En).map(r=>ut(r,t+1)):d(e)?Object.fromEntries(Object.entries(e).slice(0,En).map(([r,n])=>[r,ut(n,t+1)])):e}function ji(e){let t=e.tool_name,r=e.input,n=Hi.has(t)?"command":Fi.has(t)?"file_change":t===Bi?"permission":"other",s=r.file_path||r.notebook_path;return{runtime:"claude",kind:n,toolName:t,title:typeof e.description=="string"?e.description:"",...n==="command"&&typeof r.command=="string"?{command:r.command}:{},...n==="file_change"&&typeof s=="string"?{paths:[s]}:{},input:ut(r)}}async function On(e,t,r){if(e?.subtype!=="can_use_tool"||typeof e.tool_name!="string"||!d(e.input))return{subtype:"error",error:`OrchaAI does not handle Claude control request ${e?.subtype}`};let n=await t(ji(e),{signal:r}),s=n?.response?.reason||n?.reason||n?.outcome||"not approved";return{subtype:"success",response:n?.outcome==="approved"?{behavior:"allow",updatedInput:e.input}:{behavior:"deny",message:`OrchaAI did not approve this action (${s}). Do not retry the same action unless the user asks.`}}}var qi=new Set(["threadId","turnId","itemId","approvalId","startedAtMs","environmentId","command","cwd","reason"]);function Sn(e,t,r){let n=Object.fromEntries(Object.entries(t).filter(([i,o])=>!qi.has(i)&&o!=null)),s={runtime:"codex",title:typeof t.reason=="string"?t.reason:"",input:ut(n)};if(e==="item/commandExecution/requestApproval")return{...s,kind:"command",toolName:"shell",...typeof t.command=="string"?{command:t.command}:{},...typeof t.cwd=="string"?{cwd:t.cwd}:{}};if(e==="item/fileChange/requestApproval"){let i=Array.isArray(r?.changes)?r.changes.map(o=>o?.path).filter(o=>typeof o=="string"):[];return{...s,kind:"file_change",toolName:"apply_patch",...i.length?{paths:i}:{}}}return{...s,kind:"permission",...typeof t.cwd=="string"?{cwd:t.cwd}:{}}}function Rn(e,t,r){return e==="item/permissions/requestApproval"?{permissions:Object.fromEntries(Object.entries(d(t.permissions)?t.permissions:{}).filter(([,s])=>r&&s!=null)),scope:"turn"}:{decision:r?"accept":"decline"}}var xn=e=>Gi("sha256").update(JSON.stringify(e)).digest("hex"),Q=(e,t)=>Object.assign(new Error(t),{code:e}),An=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ke="ORCHA_TASK_MCP_TOKEN",Wi=new Set(["--no-session-persistence","--resume","-r","--continue","-c","--session-id","--fork-session"]);function Xi(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t?.type==="text").map(t=>t.text).join(`
2
+ import{spawn as hu}from"node:child_process";import{closeSync as gu,existsSync as Kr,mkdirSync as _u,openSync as yu,readFileSync as jr,rmSync as wu,statSync as Hs,writeFileSync as Gs}from"node:fs";import{dirname as Ks,resolve as Ct}from"node:path";import{fileURLToPath as Tu}from"node:url";import{createHash as es}from"node:crypto";import{mkdir as ia,readFile as oa,writeFile as aa,rename as ca}from"node:fs/promises";import{join as ts}from"node:path";import{homedir as ua,hostname as la}from"node:os";import{execFile as ti}from"node:child_process";import{access as ei,realpath as ri}from"node:fs/promises";import{constants as ni}from"node:fs";import{delimiter as si,join as Xr,isAbsolute as Yr}from"node:path";import{homedir as Wr}from"node:os";async function xe(e,t=process.env){let r=process.platform==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of(t.PATH||"").split(si).filter(Yr))for(let s of r){let i=Xr(n,`${e}${s}`);try{return await ei(i,ni.X_OK),i}catch{}}return null}function ii(e,t){return new Promise(r=>ti(e,t,{timeout:8e3,maxBuffer:1024*1024,windowsHide:!0},(n,s)=>r({code:n?n.code:0,stdout:String(s||"")})))}async function Ae(e){let t=e==="~"?Wr():e.startsWith("~/")?Xr(Wr(),e.slice(2)):e;if(!Yr(t))throw new Error("\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u8BBE\u5907\u4E0A\u7684\u7EDD\u5BF9\u8DEF\u5F84\u6216 ~/ \u5F00\u5934\u7684\u8DEF\u5F84");let r=await ri(t),{stat:n}=await import("node:fs/promises");if(!(await n(r)).isDirectory())throw new Error("\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6\u5939");return r}async function Qr({find:e=xe,run:t=ii,cwd:r=process.cwd()}={}){return(await Promise.all(["codex","claude","openclaw"].map(async s=>{let i=await e(s);if(!i)return[];let o={codex:"Codex",claude:"Claude Code",openclaw:"OpenClaw"}[s],a=await t(i,["--version"]),c=a.code===0&&a.stdout.match(/\d+\.\d+\.\d+[^\s]*/)?.[0]||"",l={id:s,name:o,framework:s,version:c,workspace:r,managed:!1};if(a.code!==0)return[{...l,status:"error",message:"\u7A0B\u5E8F\u65E0\u6CD5\u542F\u52A8\uFF0C\u8BF7\u5728\u672C\u673A\u68C0\u67E5\u5B89\u88C5"}];if(s==="openclaw"){let f=await t(i,["agents","list","--json"]),h;try{h=JSON.parse(f.stdout)}catch{}if(f.code!==0||!Array.isArray(h))return[{...l,status:"error",message:"\u65E0\u6CD5\u8BFB\u53D6 OpenClaw \u667A\u80FD\u4F53\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u914D\u7F6E"}];let _=await t(i,["health","--json"]);return h.filter(w=>typeof w.id=="string"&&typeof w.workspace=="string").slice(0,32).map(w=>({...l,id:`openclaw:${w.id}`,name:w.name||w.identityName||w.id,workspace:w.workspace,managed:!0,localAgentId:w.id,command:i,status:_.code===0?"ready":"needs_setup",message:_.code===0?"":"\u8BF7\u5148\u5728\u672C\u673A\u542F\u52A8\u5E76\u914D\u7F6E OpenClaw Gateway"}))}let p=await t(i,s==="codex"?["login","status"]:["auth","status"]),m=p.code===0?"ready":p.code===1?"needs_login":"error";return[{...l,command:i,status:m,message:m==="needs_login"?`\u8BF7\u5728\u672C\u673A\u8FD0\u884C ${s} ${s==="codex"?"login":"auth login"}`:m==="error"?"\u767B\u5F55\u72B6\u6001\u68C0\u6D4B\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 CLI \u7248\u672C":""}]}))).flat()}import{spawn as ra}from"node:child_process";import{createInterface as na}from"node:readline";import{randomUUID as sa}from"node:crypto";import{createInterface as di}from"node:readline";var B="0.1.59";function Mt(){return new Date().toISOString()}function $(e,t=2){return String(e).padStart(t,"0")}function Zr(e){let t=e>=0?"+":"-",r=Math.abs(e);return`${t}${$(Math.floor(r/60))}:${$(r%60)}`}function oi(e){let t=-e.getTimezoneOffset();return[`${e.getFullYear()}-${$(e.getMonth()+1)}-${$(e.getDate())}`,`T${$(e.getHours())}:${$(e.getMinutes())}:${$(e.getSeconds())}.${$(e.getMilliseconds(),3)}`,Zr(t)].join("")}function ai(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 ci(e,t){let r=ai(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}-${$(r.month)}-${$(r.day)}`,`T${$(r.hour)}:${$(r.minute)}:${$(r.second)}.${$(e.getMilliseconds(),3)}`,Zr(s)].join("")}function ui(e=new Date){let t=u(process.env.ORCHA_RUNTIME_LOG_TIMEZONE||process.env.TZ||"Asia/Shanghai");try{return ci(e,t)}catch{return oi(e)}}function d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function u(e){return String(e??"").trim()}function R(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)?r:t}function k(e){return Array.isArray(e)?e.map(String):[]}function K(e,t,r=process.cwd()){let n=d(e)?e:{};return u(n.cwd)||u(n.workspace)||u(t)||u(r)||process.cwd()}var qt="[redacted]",li=/(authorization|api[_-]?key|credential|password|secret|token)/i;function rt(e){return li.test(u(e))}function ct(e,t=[]){let r=String(e??"");for(let n of t){let s=String(n??"");s.length>=4&&(r=r.split(s).join(qt))}return r.replace(/((?:authorization|api[_-]?key|credential|password|secret|token)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,`$1${qt}`).replace(/([?&](?:api[_-]?key|credential|password|secret|token)=)[^&\s]+/gi,`$1${qt}`)}function at(e,t=new WeakSet){if(e==null)return e;if(typeof e=="bigint")return e.toString();if(typeof e!="object")return e;if(e instanceof Date)return e.toISOString();if(e instanceof Error){if(t.has(e))return"[circular]";t.add(e);let s={name:e.name,message:e.message};e.stack&&(s.stack=e.stack);for(let i of Object.keys(e))s[i]=at(e[i],t);return t.delete(e),s}if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e)){let s=e.map(i=>at(i,t));return t.delete(e),s}let r={},n=rt(e.name||e.key);for(let[s,i]of Object.entries(e))r[s]=rt(s)||n&&s.toLowerCase()==="value"?qt:at(i,t);return t.delete(e),r}function tn(e,t=4e3){let r=JSON.stringify(at(e))??String(e);return!Number.isFinite(t)||r.length<=t?r:`${r.slice(0,t)}...`}function g(e,t,r,n={}){let s={ts:ui(),level:e,module:t,msg:r,...d(n)?at(n):{}};console.error(JSON.stringify(s))}function Gt(e,{onNotification:t=()=>{},onRequest:r=()=>{throw new Error("Unsupported request")}}={}){let n=1,s=new Map,i=o=>e.stdin.write(`${JSON.stringify(o)}
3
+ `);return di({input:e.stdout}).on("line",o=>{if(!o.trim())return;let a;try{a=JSON.parse(o)}catch{g("warn","runtime.codex","ignored non-JSON app-server output");return}if(typeof a.method=="string"&&a.id!==void 0){Promise.resolve().then(()=>r(a.method,d(a.params)?a.params:{})).then(l=>i({id:a.id,result:l}),l=>i({id:a.id,error:{code:-32603,message:String(l?.message||l)}}));return}if(typeof a.method=="string"){t(a.method,d(a.params)?a.params:{});return}let c=s.get(a.id);c&&(s.delete(a.id),a.error?c.reject(Object.assign(new Error(u(a.error.message)||"Codex app-server request failed"),{code:"RUNTIME_CODEX_APP_SERVER_ERROR"})):c.resolve(a.result))}),e.once("exit",()=>{for(let o of s.values())o.reject(new Error("Codex app-server closed"));s.clear()}),{request:(o,a)=>new Promise((c,l)=>{let p=n++;s.set(p,{resolve:c,reject:l}),i({id:p,method:o,params:a})}),notify:o=>i({method:o})}}import{spawn as $n}from"node:child_process";import{randomUUID as wt}from"node:crypto";import{existsSync as Hn,mkdirSync as co,readdirSync as Fn,readFileSync as Bn,realpathSync as kt,rmSync as uo,rmdirSync as lo,statSync as po,unlinkSync as fo}from"node:fs";import{homedir as mo,tmpdir as jn}from"node:os";import{basename as Fe,dirname as ho,join as q,resolve as Pn}from"node:path";import{randomUUID as sn}from"node:crypto";import{existsSync as pi,readFileSync as fi,realpathSync as en,statSync as mi}from"node:fs";import{basename as on,extname as an,isAbsolute as Ut,join as hi,relative as cn,resolve as rn}from"node:path";var gi=25*1024*1024;function un(e,t=""){let r=u(t);if(r)return r;let n=an(u(e)).toLowerCase();return n===".jpg"||n===".jpeg"?"image/jpeg":n===".webp"?"image/webp":n===".gif"?"image/gif":"image/png"}function ln(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 Kt(e){if(Array.isArray(e))return e.map(u).filter(Boolean);let t=u(e);return t?[t]:[]}function _i(e,t){let r=cn(t,e);return r===""||!!r&&!r.startsWith("..")&&!Ut(r)}function yi(e,t){let r=u(e);if(!r||!pi(r))return"";try{let n=en(r);for(let s of t)try{let i=en(s);if(_i(n,i))return n}catch{}}catch{return""}return""}function wi(e,t){let r=u(e);if(!r||!Ut(r))return r;for(let n of Array.isArray(t)?t:[]){if(!d(n))continue;let s=u(n.runtimeRoot),i=u(n.hostRoot);if(!s||!i||!Ut(s)||!Ut(i))continue;let o=cn(rn(s),rn(r));if(o===""||!o.startsWith("..")&&!Ut(o))return o?hi(i,o):i}return r}function be(e,t,r={}){let n=u(e);return!n||n.startsWith("data:")||/^https?:\/\//i.test(n)?n:Ti(n,t,r)}function Ti(e,t,r={}){let n=[...Kt(r.trustedFileRoots),...Kt(r.trustedFileRoot),...Kt(r.artifactRoots),...Kt(r.artifactRoot)],s=yi(wi(e,r.pathMappings),n);if(!s)return"";try{let i=mi(s);return!i.isFile()||i.size<=0||i.size>gi?"":`data:${t};base64,${fi(s).toString("base64")}`}catch{return""}}function v(...e){for(let t of e){let r=u(t);if(r)return r}return""}function Ei(e,t,r,n){let s=r.toLowerCase();if(s==="image"||s==="picture")return!0;let i=v(n,e.previewUrl,e.fileUrl,e.imageUrl,e.dataUrl,e.url,e.uri,t.previewUrl,t.fileUrl,t.imageUrl,t.dataUrl,t.url,t.uri),o=an(i.split("?",1)[0].split("#",1)[0]).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(o)}function Me(e,t={}){let{source:r="runtime_image_generation_event"}=t;if(!d(e))return null;let n=d(e.payload)?e.payload:{},s=u(e.type),i=u(n.type);if(!(s==="event_msg"&&i==="image_generation_end"||s==="response_item"&&i==="image_generation_call"))return null;let o=v(n.call_id,n.id),a=v(n.saved_path,n.savedPath),c=v(n.revised_prompt,n.revisedPrompt),l=un(a,n.mimeType||n.mime_type),p=ln(n.result,l)||be(a,l,t);if(!p)return null;let m=p.startsWith("data:")?p:"",f=a?on(a):`${o||sn()}.png`;return{artifactType:"image",type:"image",fieldKey:"image",title:f||"Generated image",summary:c||"Generated image",content:{prompt:c||void 0,dataUrl:m||void 0,imageUrl:p,previewUrl:p,fileUrl:p,mimeType:l},dataUrl:m||void 0,previewUrl:p,fileUrl:p,metadata:{source:r,eventType:i,callId:o||void 0,savedPath:a||void 0,filename:f,mimeType:l,revisedPrompt:c||void 0}}}function Oi(e){let t=d(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];d(s)&&r.push(s)}return r}function Si(e,t={}){let{source:r="runtime_artifact"}=t,n=d(e)?e:{};if(!Object.keys(n).length)return null;let s=d(n.content)?{...n.content}:{},i=d(n.metadata)?{...n.metadata}:{},o=v(n.saved_path,n.savedPath,s.saved_path,s.savedPath,i.savedPath),a=v(n.mimeType,n.mime_type,s.mimeType,s.mime_type,i.mimeType),c=v(n.artifactType,n.artifact_type,n.type,n.kind,s.type,o?"image":"file"),l=Ei(n,s,c,o),p=l?un(o,a):a;if(l){let I=v(n.dataUrl,s.dataUrl),E=I.startsWith("data:")?I:"",C=v(n.imageUrl,n.previewUrl,n.fileUrl,n.downloadUrl,n.url,n.uri,s.imageUrl,s.previewUrl,s.fileUrl,s.downloadUrl,s.url,s.uri),y=ln(n.result??s.result,p)||E||be(o,p,t)||be(C,p,t);y&&(y.startsWith("data:")&&(s.dataUrl||=y),s.imageUrl||=y,s.previewUrl||=y,s.fileUrl||=y,p&&(s.mimeType||=p))}for(let[I,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[I];C!=null&&C!==""&&!(E in s)&&(s[E]=C)}let m=v(n.fileUrl,n.downloadUrl,n.imageUrl,n.dataUrl,n.url,n.uri,s.fileUrl,s.downloadUrl,s.imageUrl,s.dataUrl,s.url,s.uri),f=v(n.previewUrl,n.imageUrl,n.dataUrl,n.url,n.fileUrl,n.uri,s.previewUrl,s.imageUrl,s.dataUrl,s.url,s.fileUrl,s.uri),h=v(n.dataUrl,s.dataUrl,m.startsWith("data:")?m:"",f.startsWith("data:")?f:""),_=v(n.filename,i.filename,o?on(o):""),w=v(n.fieldKey,n.field_key,s.fieldKey,i.fieldKey,l?"image":"artifact");return{...n,artifactType:c,type:n.type||c,fieldKey:w,title:v(n.title,_,"Runtime artifact"),summary:v(n.summary,s.prompt,n.title,_,"Runtime artifact"),content:s,dataUrl:h||void 0,fileUrl:m||void 0,previewUrl:f||void 0,metadata:{...i,source:v(i.source,r),savedPath:o||i.savedPath,filename:_||i.filename,mimeType:p||i.mimeType}}}function zt(e,t){if(!t||!e)return;let r=d(t.metadata)?t.metadata:{},n=v(r.savedPath,r.callId,t.previewUrl,t.fileUrl)||sn(),s=e.get(n);if(!s){e.set(n,t);return}s.content={...d(s.content)?s.content:{},...d(t.content)?t.content:{}},s.metadata={...d(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 Ne(e,t,r={}){for(let n of Oi(e))zt(t,Si(n,r))}function Ue(e){if(!d(e)||!d(e.payload))return d(e)?e:{value:e};let t=u(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 nn(e,t,r){if(!d(e))return e;let n=d(e.event)?e.event:null;return n?(zt(t,Me(n,r)),{...e,event:Ue(n)}):e}function dn(e,t,r={}){if(!d(e))return e;Ne(e,t,r);let n=nn(e,t,r),s=d(n.update)?nn(n.update,t,r):null;return s&&s!==n.update&&(n={...n,update:s}),n}function pn(e,t,r={}){let n=d(e)?{...e}:{};Ne(n,t,r),Ne(d(n.output)?n.output:{},t,r);let s=[...t?.values?.()||[]];return s.length&&(n._artifacts=s),delete n.artifacts,n}function yt(e){return Array.isArray(e)?e.map(t=>d(t)?t.type==="text"?u(t.text):t.type==="file"?u(t.uri):t.type==="image"?u(t.uri):"":"").filter(Boolean).join(`
4
+ `):""}import{createHash as Gi,randomUUID as Ki}from"node:crypto";import{mkdirSync as In,readFileSync as zi,renameSync as Vi,rmSync as Ji,writeFileSync as Cn}from"node:fs";import{homedir as Le}from"node:os";import{join as lt}from"node:path";import{createServer as Ii}from"node:http";import{randomBytes as Ci}from"node:crypto";var Vt={controlTools:["find_capabilities_and_skills","describe_capability","inspect_result","execute_capability"],residentTools:["search_orcha_docs","knowledge_search"]};var xi=Object.freeze([...Vt.controlTools,...Vt.residentTools]),Ai=new Set(xi),bi=8*1024*1024;function Jt(e,t){if(!Array.isArray(e)||e.length!==1)throw new Error("one task-scoped Orcha MCP server is required");let r=e[0],n=new URL(r.url);if(r.name!=="orcha"||r.type!=="http"||!["http:","https:"].includes(n.protocol)||n.username||n.password||n.hash||t&&n.href!==new URL(t).href)throw new Error("Orcha MCP server does not match the trusted binding");let s=Object.fromEntries((r.headers||[]).map(({name:i,value:o})=>[i.toLowerCase(),o]));if(!String(s.authorization||"").startsWith("Bearer "))throw new Error("Orcha MCP task credentials are missing");return{url:n.href,headers:{...s,"content-type":"application/json",accept:"application/json"}}}async function mn(e){let t=0,r=[];for await(let n of e){if(t+=n.length,t>bi)throw new Error("MCP payload exceeds the size limit");r.push(Buffer.from(n))}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function hn(e,t,r){let n=await fetch(e.url,{method:"POST",headers:e.headers,body:JSON.stringify(t),redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(36e5),...r?[r]:[]])});if(!n.ok)throw new Error(`Orcha MCP request failed (${n.status})`);if(n.status===202||n.status===204)return null;let s=await mn(n.body);if(!s||s.jsonrpc!=="2.0"||s.id!==t.id)throw new Error("Orcha MCP response identity mismatch");return s}async function fn(e,t){let r=await hn(e,{jsonrpc:"2.0",id:"orcha-bind-tools",method:"tools/list"},t),n=r?.result?.tools;if(r?.error){let s=Object.entries(e.headers).filter(([a])=>rt(a)).flatMap(([,a])=>[a,String(a).replace(/^Bearer\s+/i,"")]),i=typeof r.error.message=="string"?ct(r.error.message,s).slice(0,512):"",o=Number.isInteger(r.error.code)?` (${r.error.code})`:"";throw new Error(`Orcha MCP tool discovery failed${o}${i?`: ${i}`:""}`)}return Ni(n)}function Ni(e){if(!Array.isArray(e)||e.some(t=>!t||!Ai.has(t.name)||t.inputSchema?.type!=="object"||typeof t.description!="string")||new Set(e.map(t=>t.name)).size!==e.length||e.length&&Vt.controlTools.some(t=>!e.some(r=>r.name===t)))throw new Error("Orcha MCP returned an unsupported or invalid authorized tool catalog");return e}function Mi(e,t){let r=s=>Array.isArray(s)?s.map(r):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(i=>[i,r(s[i])])):s,n=s=>s.map(({name:i,inputSchema:o})=>({name:i,inputSchema:o})).sort((i,o)=>i.name.localeCompare(o.name));return JSON.stringify(r(n(e)))===JSON.stringify(r(n(t)))}async function gn(e,t=[]){let r=Jt(e),n=new AbortController,s=await fn(r,n.signal);if(t.some(a=>s.some(c=>c.name===a.name)))throw new Error("Local and remote MCP tools conflict");let i=Ci(32).toString("hex"),o=Ii(async(a,c)=>{if(a.url!=="/mcp"||a.headers.authorization!==`Bearer ${i}`){c.writeHead(403).end();return}if(a.method!=="POST"){c.writeHead(405).end();return}try{let l=await mn(a);if(!l||l.jsonrpc!=="2.0"||typeof l.method!="string")throw new Error("Invalid MCP request");let p=l.method==="tools/call"&&t.find(f=>f.name===l.params?.name);if(l.method==="tools/call"&&!p&&!s.some(f=>f.name===l.params?.name))throw new Error("Tool is not authorized in this task binding");let m;if(p)try{m={jsonrpc:"2.0",id:l.id,result:await p.call(l.params.arguments,{upstream:r,signal:n.signal})}}catch(f){m={jsonrpc:"2.0",id:l.id,result:{isError:!0,content:[{type:"text",text:ct(String(f.message),[r.headers.authorization,i])}]}}}else m=await hn(r,l,n.signal),l.method==="tools/list"&&m?.result?.tools&&m.result.tools.push(...t.map(({call:f,...h})=>h));c.writeHead(m===null?202:200,{"content-type":"application/json"}),c.end(m===null?"":JSON.stringify(m))}catch{c.writeHead(502,{"content-type":"application/json"}).end(JSON.stringify({error:"The task-scoped Orcha MCP connection failed"}))}});return await new Promise((a,c)=>{o.once("error",c),o.listen(0,"127.0.0.1",a)}),{url:`http://127.0.0.1:${o.address().port}/mcp`,token:i,async refresh(a){let c=Jt(a,r.url);if(!Mi(s,await fn(c,n.signal)))throw new Error("The frozen MCP tool catalog changed; start a new task");r=c},async close(){n.abort(),o.closeAllConnections(),await new Promise(a=>o.close(a))}}}import{createHash as _n}from"node:crypto";import{constants as Pe}from"node:fs";import{open as Ui,realpath as yn}from"node:fs/promises";import{basename as Pi,isAbsolute as Li,relative as ki,resolve as vi}from"node:path";var Di=32*1024*1024,$i={name:"send_file",description:"Send one explicitly selected local file to the current OrchaAI conversation. Use this to deliver images, PDFs, documents, spreadsheets or other files to the user; viewing an image or writing a local Markdown link does not send it. path must be in the current workspace, a configured artifact root, or (Codex only) the current thread's generated_images directory. Copy other intended deliverables into the workspace first. Success means the attachment message is saved; do not send it again or embed the local path. Internal previews and intermediate files need not be sent.",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string",minLength:1,description:"Absolute file path, or a path relative to the current workspace."},message:{type:"string",maxLength:1e4,description:"Optional short caption for the attachment message, such as what the file is. The attachment is saved as its own message and your final reply is still posted separately, so do not repeat the final reply's summary, findings or conclusions here; omit it when the final reply already explains the file."}}}};function wn(e){return{...$i,async call(t,{upstream:r,signal:n}){if(!t||typeof t.path!="string"||!t.path.trim()||Object.keys(t).some(y=>!["path","message"].includes(y))||t.message!==void 0&&(typeof t.message!="string"||t.message.length>1e4))throw new Error("send_file requires a file path and an optional caption of at most 10000 characters");let{cwd:s,roots:i}=e();if(!s)throw new Error("The current file delivery workspace is unavailable");let o=await yn(vi(s,t.path)),a=!1;for(let y of i)try{let O=ki(await yn(y),o);(!O||O!==".."&&!O.startsWith("../")&&!O.startsWith("..\\")&&!Li(O))&&(a=!0)}catch{}if(!a)throw new Error("File is outside the current workspace and authorized artifact roots");let c=await Ui(o,Pe.O_RDONLY|Pe.O_NOFOLLOW|Pe.O_NONBLOCK),l;try{let y=await c.stat();if(!y.isFile()||y.size<=0||y.size>Di)throw new Error("Select a non-empty regular file of at most 32 MiB");l=Buffer.alloc(y.size);let O=0;for(;O<l.length;){let{bytesRead:A}=await c.read(l,O,l.length-O,O);if(!A)throw new Error("File changed while preparing delivery; retry after it is saved");O+=A}let M=await c.stat();if(M.size!==y.size||M.mtimeMs!==y.mtimeMs)throw new Error("File changed while preparing delivery; retry after it is saved")}finally{await c.close()}let p=t.message||"",m=Pi(o),f=_n("sha256").update(l).digest("hex"),h=_n("sha256").update(JSON.stringify([o,f,p])).digest("hex"),_=new FormData;_.set("deliveryId",h),_.set("message",p),_.set("file",new Blob([l]),m);let w=new URL(r.url);w.pathname=`${w.pathname.replace(/\/$/,"")}/files`;let I=await fetch(w,{method:"POST",headers:{authorization:r.headers.authorization},body:_,redirect:"error",signal:AbortSignal.any([n,AbortSignal.timeout(12e4)])});if(!I.ok)throw new Error(`File delivery failed (HTTP ${I.status}); no successful receipt was received`);let E=await I.json();if(!E.success)throw new Error(`File delivery failed: ${String(E.message||E.code||"request rejected").slice(0,512)}`);let C=E.data;if(!C?.accepted||typeof C.messageId!="string"||!C.messageId||typeof C.fileId!="string"||!C.fileId)throw new Error("File delivery did not return a saved message and file receipt");return{content:[{type:"text",text:JSON.stringify(C)}],structuredContent:C,isError:!1}}}}var Hi=new Set(["Bash","PowerShell"]),Fi=new Set(["Edit","Write","MultiEdit","NotebookEdit"]),Bi="SandboxNetworkAccess",Tn=2e3,En=50;function ut(e,t=0){return typeof e=="string"?e.length>Tn?`${e.slice(0,Tn)}\u2026`:e:t>=4&&(Array.isArray(e)||d(e))?"\u2026":Array.isArray(e)?e.slice(0,En).map(r=>ut(r,t+1)):d(e)?Object.fromEntries(Object.entries(e).slice(0,En).map(([r,n])=>[r,ut(n,t+1)])):e}function ji(e){let t=e.tool_name,r=e.input,n=Hi.has(t)?"command":Fi.has(t)?"file_change":t===Bi?"permission":"other",s=r.file_path||r.notebook_path;return{runtime:"claude",kind:n,toolName:t,title:typeof e.description=="string"?e.description:"",...n==="command"&&typeof r.command=="string"?{command:r.command}:{},...n==="file_change"&&typeof s=="string"?{paths:[s]}:{},input:ut(r)}}async function On(e,t,r){if(e?.subtype!=="can_use_tool"||typeof e.tool_name!="string"||!d(e.input))return{subtype:"error",error:`OrchaAI does not handle Claude control request ${e?.subtype}`};let n=await t(ji(e),{signal:r}),s=n?.response?.reason||n?.reason||n?.outcome||"not approved";return{subtype:"success",response:n?.outcome==="approved"?{behavior:"allow",updatedInput:e.input}:{behavior:"deny",message:`OrchaAI did not approve this action (${s}). Do not retry the same action unless the user asks.`}}}var qi=new Set(["threadId","turnId","itemId","approvalId","startedAtMs","environmentId","command","cwd","reason"]);function Sn(e,t,r){let n=Object.fromEntries(Object.entries(t).filter(([i,o])=>!qi.has(i)&&o!=null)),s={runtime:"codex",title:typeof t.reason=="string"?t.reason:"",input:ut(n)};if(e==="item/commandExecution/requestApproval")return{...s,kind:"command",toolName:"shell",...typeof t.command=="string"?{command:t.command}:{},...typeof t.cwd=="string"?{cwd:t.cwd}:{}};if(e==="item/fileChange/requestApproval"){let i=Array.isArray(r?.changes)?r.changes.map(o=>o?.path).filter(o=>typeof o=="string"):[];return{...s,kind:"file_change",toolName:"apply_patch",...i.length?{paths:i}:{}}}return{...s,kind:"permission",...typeof t.cwd=="string"?{cwd:t.cwd}:{}}}function Rn(e,t,r){return e==="item/permissions/requestApproval"?{permissions:Object.fromEntries(Object.entries(d(t.permissions)?t.permissions:{}).filter(([,s])=>r&&s!=null)),scope:"turn"}:{decision:r?"accept":"decline"}}var xn=e=>Gi("sha256").update(JSON.stringify(e)).digest("hex"),Q=(e,t)=>Object.assign(new Error(t),{code:e}),An=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ke="ORCHA_TASK_MCP_TOKEN",Wi=new Set(["--no-session-persistence","--resume","-r","--continue","-c","--session-id","--fork-session"]);function Xi(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t?.type==="text").map(t=>t.text).join(`
5
5
  `):""}var Pt=(e,t)=>({sessionUpdate:e,content:{type:"text",text:t}});function Yi(e,t,{emitThoughts:r,streamText:n}){let s=e?.type;if(s==="result"&&e.is_error!==!0){let c=typeof e.result=="string"?e.result:"",l=t.streamed;return t.text=t.streamed="",c?l?l.trim()===c.trim()?[]:[Pt("agent_message_snapshot",c)]:[Pt("agent_message_chunk",c)]:[]}if(!["assistant","user","stream_event"].includes(s))return null;let i=[];if(e.parent_tool_use_id)return i;let o=()=>{let c=t.streamed||t.text;t.streamed&&i.push(Pt("agent_message_snapshot","")),c&&r&&i.push(Pt("agent_thought_chunk",c)),t.text=t.streamed=""},a=c=>{t.streamed=(t.streamed||"")+c,i.push(Pt("agent_message_chunk",c))};if(s==="stream_event"){if(!n)return i;t.streaming=!0;let c=e.event,l=c?.content_block?.type;return c?.type==="content_block_start"&&l==="tool_use"?o():c?.type==="content_block_start"&&l==="text"&&t.streamed?a(`
6
6
 
7
7
  `):c?.type==="content_block_delta"&&c.delta?.type==="text_delta"&&c.delta.text&&a(c.delta.text),i}for(let c of Array.isArray(e.message?.content)?e.message.content:[])s==="user"?c?.type==="tool_result"&&c.tool_use_id&&i.push({sessionUpdate:"tool_call_update",toolCallId:c.tool_use_id,status:c.is_error?"failed":"completed",rawOutput:Xi(c.content)}):c?.type==="text"&&c.text?t.streaming||(t.text=t.text?`${t.text}
8
8
 
9
- ${c.text}`:c.text):c?.type==="tool_use"&&c.id&&(o(),i.push({sessionUpdate:"tool_call",toolCallId:c.id,title:c.name,status:"in_progress",rawInput:c.input}));return i}var dt=Object.freeze({codex:{label:"Codex",code:"CODEX",sessionDirectory:"codex-sessions",home:e=>e.env?.CODEX_HOME||process.env.CODEX_HOME||lt(Le(),".codex"),threadId:e=>e?.type==="thread.started"?e.thread_id:void 0,resumeArgs(e,t){let r=e.indexOf("exec");if(r<0||e.includes("resume")||e.includes("--ephemeral"))throw Q("BAD_REQUEST","Codex \u539F\u751F\u4F1A\u8BDD\u9700\u8981\u6807\u51C6 codex exec \u914D\u7F6E");return t?[...e.slice(0,r+1),"resume",t,...e.slice(r+1)]:e},mcpArgs:e=>["-c",`mcp_servers.orcha={url=${JSON.stringify(e)},bearer_token_env_var=${JSON.stringify(ke)},required=true}`]},claude:{label:"Claude Code",code:"CLAUDE",sessionDirectory:"claude-sessions",modelArgs:e=>["--model",e.model||"default",...e.effort?["--effort",e.effort]:[]],home:e=>e.env?.CLAUDE_CONFIG_DIR||process.env.CLAUDE_CONFIG_DIR||lt(Le(),".claude"),threadId:e=>e?.type==="system"&&e.subtype==="init"?e.session_id:void 0,resumeArgs(e,t){let r=e.indexOf("--output-format");if(!e.includes("-p")&&!e.includes("--print")||r<0||e[r+1]!=="stream-json"||!e.includes("--verbose")||e.some(n=>Wi.has(n)))throw Q("BAD_REQUEST","Claude Code \u539F\u751F\u4F1A\u8BDD\u9700\u8981\u6807\u51C6 claude -p --output-format stream-json --verbose \u914D\u7F6E");return t?[...e,"--resume",t]:e},mcpArgs:e=>["--mcp-config",JSON.stringify({mcpServers:{orcha:{type:"http",url:e,headers:{Authorization:`Bearer \${${ke}}`}}}}),"--allowedTools","mcp__orcha"],control:{args:["--input-format","stream-json","--permission-prompt-tool","stdio"],prompt:e=>JSON.stringify({type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}),respond:On},taskMcpError(e){if(e?.type!=="system"||e.subtype!=="init")return null;let t=e.mcp_servers?.find(r=>r?.name==="orcha")?.status||"missing";return t==="connected"?null:Q("RUNTIME_CLAUDE_MCP_UNAVAILABLE",`Claude Code \u672A\u80FD\u8FDE\u63A5 OrchaAI \u4EFB\u52A1\u5DE5\u5177\uFF08${t}\uFF09\uFF0C\u672C\u8F6E\u672A\u6267\u884C`)},progress:Yi}});async function bn(e,t,r){let n=await gn(t,r?[wn(r)]:[]);return{args:e.mcpArgs(n.url),environment:{[ke]:n.token},refresh:s=>n.refresh(s),close:()=>n.close()}}var Wt=class{constructor(t,r,n=lt(Le(),".orcha",dt[t].sessionDirectory)){this.adapter=dt[t],this.directory=lt(n,xn(r))}async turn(t,r,n,s,i){let{label:o,code:a}=this.adapter;if(!t)throw Q("BAD_REQUEST",`${o} native turn requires a run ID`);In(this.directory,{recursive:!0,mode:448});let c=lt(this.directory,"active");try{In(c,{mode:448})}catch(f){throw f.code==="EEXIST"?Q("RUNTIME_SESSION_BUSY",`${o} \u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\u6216\u4E0A\u8F6E\u5F02\u5E38\u4E2D\u65AD\uFF1B\u8BF7\u7B49\u5F85\u5B8C\u6210\uFF0C\u6216\u53D1\u9001 /new \u5F00\u59CB\u65B0\u4EFB\u52A1`):f}let l=lt(this.directory,"session.json"),p,m=()=>{let f=`${l}.${Ki()}.pending`;Cn(f,JSON.stringify(p),{mode:384}),Vi(f,l)};try{try{p=JSON.parse(zi(l,"utf8"))}catch(w){if(w.code!=="ENOENT")throw w}if(p&&!An.test(p.threadId||""))throw Q("RUNTIME_OPERATION_NOT_FOUND",`${o} \u4E0A\u8F6E\u672A\u80FD\u4FDD\u5B58\u539F\u751F\u4F1A\u8BDD\u6807\u8BC6\uFF0C\u8BF7\u53D1\u9001 /new`);try{Cn(lt(this.directory,`${xn(t)}.run`),"",{flag:"wx",mode:384})}catch(w){throw w.code==="EEXIST"?Q("RUNTIME_OPERATION_NOT_FOUND",`\u6B64\u8F6E ${o} \u5DF2\u6267\u884C\u6216\u6267\u884C\u7ED3\u679C\u4E0D\u786E\u5B9A\uFF0C\u4E0D\u80FD\u91CD\u590D\u53D1\u9001`):w}p||={threadId:null},m();let f,h=w=>{if(f)return;let I=w.update?.sessionUpdate==="runtime_event"?this.adapter.threadId(w.update.event):void 0;if(I!==void 0)try{if(!An.test(I||"")||p.threadId&&p.threadId!==I)throw Q(`${a}_SESSION_MISMATCH`,`${o} \u8FD4\u56DE\u4E86\u4E0D\u540C\u7684\u539F\u751F\u4F1A\u8BDD\uFF0C\u8BF7\u53D1\u9001 /new`);p.threadId=I,m()}catch(E){f=E,i();return}n(w)},g=await r(p.threadId,h,w=>{!f&&p.threadId&&s?.(w)});if(f)throw f;if(!p.threadId)throw Q(`${a}_SESSION_MISSING`,`${o} \u6CA1\u6709\u8FD4\u56DE\u539F\u751F\u4F1A\u8BDD\u6807\u8BC6\uFF0C\u8BF7\u68C0\u67E5 CLI \u7248\u672C\u5E76\u53D1\u9001 /new`);return g}finally{Ji(c,{recursive:!0})}}};import{existsSync as Nn,readFileSync as Qi}from"node:fs";import{dirname as Zi,resolve as Xt}from"node:path";import{fileURLToPath as to}from"node:url";var eo=/^[A-Za-z_][A-Za-z0-9_]*$/,J=24*60*60*1e3;function Mn(e=process.env,t=process.cwd()){let r=u(e.ORCHA_RUNTIME_ENV_FILE),n=r?Xt(t,r):Xt(t,".env");if(!Nn(n))return r&&_("warn","config","runtime env file not found",{path:n}),{loaded:!1,path:n,keys:[]};let s=[],i=Qi(n,"utf8");for(let o of i.split(/\r?\n/)){let a=so(o);if(!a)continue;let[c,l]=a;Object.prototype.hasOwnProperty.call(e,c)||(e[c]=l,s.push(c))}return _("info","config","runtime env file loaded",{path:n,keyCount:s.length}),{loaded:!0,path:n,keys:s}}function Un(e=process.env){let t=u(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),r=u(e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1"),n=!1,s=Zi(to(import.meta.url)),i=Xt(s,"sandbox","broker.js"),o=Xt(s,"orcha-runtime-sandbox-broker.js"),a=Nn(i)?i:o,c=u(e.ORCHA_RUNTIME_SANDBOX_BROKER_COMMAND);return{mode:t,host:r,port:R(e.ORCHA_RUNTIME_BRIDGE_PORT,5588),token:e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",orchaUrl:u(e.ORCHA_RUNTIME_ORCHA_URL),nodeToken:e.ORCHA_RUNTIME_NODE_TOKEN||e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",nodeId:u(e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"local-runtime-node"),nodeName:u(e.ORCHA_RUNTIME_NODE_NAME||e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"Local Runtime Node"),reconnectMs:R(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),connectTimeoutMs:R(e.ORCHA_RUNTIME_CONNECT_TIMEOUT_MS||e.ORCHA_RUNTIME_WS_CONNECT_TIMEOUT_MS,1e4),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:R(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),initializeTimeoutMs:R(e.ORCHA_RUNTIME_INITIALIZE_TIMEOUT_MS,3e4),sessionPromptTimeoutMs:R(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,J),permissionRequestTimeoutMs:R(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:R(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:R(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:R(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:R(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:R(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),heartbeatIntervalMs:R(e.ORCHA_RUNTIME_HEARTBEAT_INTERVAL_MS,15e3),sandboxRequired:n,sandboxBrokerCommand:c||process.execPath,sandboxBrokerArguments:ve(e.ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS,"ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS",c?[]:[a]),sandboxProbeTimeoutMs:R(e.ORCHA_RUNTIME_SANDBOX_PROBE_TIMEOUT_MS,1e4),sandboxTempRoot:u(e.ORCHA_RUNTIME_SANDBOX_TEMP_ROOT),trustedWorkspaceRoots:ve(e.ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS,"ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS"),trustedToolchainRoots:ve(e.ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS,"ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS"),egressProxyRequired:no(e.ORCHA_RUNTIME_EGRESS_PROXY_REQUIRED,t==="node"),egressProxySocket:u(e.ORCHA_RUNTIME_EGRESS_PROXY_SOCKET),egressProxyToken:u(e.ORCHA_RUNTIME_EGRESS_PROXY_TOKEN),egressGrantMaxTtlMs:R(e.ORCHA_RUNTIME_EGRESS_GRANT_MAX_TTL_MS,9e5),targets:ro(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function ro(e){if(!u(e))return{};try{let t=JSON.parse(e);if(d(t))return t}catch(t){_("warn","config","invalid ORCHA_RUNTIME_TARGETS_JSON",{error:String(t)})}return{}}function no(e,t){let r=u(e).toLowerCase();if(!r)return t;if(["true","1","yes","on"].includes(r))return!0;if(["false","0","no","off"].includes(r))return!1;throw new Error(`invalid boolean configuration value: ${r}`)}function ve(e,t,r=[]){let n=u(e);if(!n)return[...r];let s;try{s=JSON.parse(n)}catch{throw new Error(`${t} must be a JSON string array`)}if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw new Error(`${t} must be a JSON string array`);return s.map(i=>i.trim()).filter(Boolean)}function so(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(!eo.test(s))return null;let i=io(r.slice(n+1).trim());return[s,i]}function io(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let r=e.slice(1,-1);return t==='"'?oo(r):r}return ao(e).trim()}function oo(e){return e.replaceAll("\\n",`
10
- `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function ao(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}var qn=5e3,go=2*60*1e3,_o=2*60*1e3,yo=12,wo=1e3,To=1500,Eo=1e3,Oo=/^(?:task|session)-[1-9]\d*(?::[1-9]\d*){4}(?![\s\S])/,Yt=24*60*60*1e3,Lt=new Set(["final_answer","final","complete","completed","done"]),So=new Set(["function_call","function_call_output","custom_tool_call","custom_tool_call_output","local_shell_call","local_shell_call_output","mcp_tool_call","mcp_tool_call_output","web_search_call","image_generation_call","image_generation_end"]),Ro=new Set(["context_compacted","context_compaction","context_compressed"]);function Zt(e,t){if(e?.pid){if(process.platform==="win32"){let r=["/PID",String(e.pid),"/T"];t==="SIGKILL"&&r.push("/F");try{$n("taskkill",r,{stdio:"ignore",windowsHide:!0}).unref?.()}catch{try{e.kill(t)}catch{}}return}try{process.kill(-e.pid,t)}catch(r){if(r?.code==="ESRCH")return;try{e.kill(t)}catch{}}}}function nt(e){Zt(e,"SIGTERM");let t=setTimeout(()=>Zt(e,"SIGKILL"),qn);return t.unref?.(),t}function j(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>j(t)).join("");if(!d(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let r=j(e[t]);if(r)return r}return""}function Gn(e){if(!d(e))return"";let t=d(e.payload)?e.payload:{};if(u(e.type)==="event_msg"){if(u(t.type)==="agent_message")return u(t.message);if(u(t.type)==="task_complete")return u(t.last_agent_message)}if(u(e.type)==="response_item"&&u(t.type)==="message"&&u(t.role)==="assistant")return j(t.content)||j(t.message);if(u(e.type)==="result")return j(e.result);let r=j(e.delta)||j(e.text)||j(e.content);if(r)return r;let n=d(e.item)?e.item:{};return["message","agent_message"].includes(u(n.type))||u(n.role)==="assistant"?j(n.content)||j(n.text)||j(n.message):""}function Kn(e,t){e.explicitFileDelivery||zt(e.artifacts,Me(t,{source:"codex_cli_image_generation",...e.artifactOptions}))}function zn(e){return at(Ue(e))}function Be(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{},r=u(e.type),n=u(t.type);if(r==="event_msg"&&n==="task_complete")return!0;let s=u(t.phase||t.status||t.stage).toLowerCase();if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&u(t.role)==="assistant")return Lt.has(s);let i=d(e.item)?e.item:{};return r==="item.completed"&&u(i.type)==="agent_message"?!0:r==="result"&&e.is_error!==!0?u(e.result).length>0:!1}function te(e){let t=u(e.terminalProtocol||e.eventProtocol).toLowerCase();if(t)return t;let r=Fe(u(e.command)).replace(/\.exe$/i,"").toLowerCase();return r==="codex"||r==="claude"?r:""}function Ln(e,t,r){let n=d(t.error)?t.error:{},s=u(n.message)||j(t.error)||u(t.result)||u(t.message)||r;return Object.assign(new Error(s),{code:e})}function Io(e,t){if(!d(e))return null;let r=u(e.type).toLowerCase();if(t==="codex")return r==="turn.completed"?{status:"completed",result:{stopReason:"end_turn"}}:r==="turn.failed"?{status:"failed",error:Ln("RUNTIME_CODEX_TURN_FAILED",e,"Codex turn failed")}:null;if(t==="claude"&&r==="result"){let n=u(e.subtype).toLowerCase();return e.is_error===!0||n.startsWith("error")||["failed","failure"].includes(n)?{status:"failed",error:Ln("RUNTIME_CLAUDE_RESULT_FAILED",e,"Claude result failed")}:{status:"completed",result:{stopReason:"end_turn",...u(e.result)?{output:u(e.result)}:{}}}}return null}function kn(e){return d(e)?u(e.phase||e.status||e.stage).toLowerCase():""}function Co(e){if(!d(e)||Be(e))return!1;let t=d(e.payload)?e.payload:{},r=u(e.type),n=u(t.type),s=kn(t);if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&u(t.role)==="assistant")return!!(s&&!Lt.has(s));let i=d(e.item)?e.item:{},o=kn(i);return u(i.role)==="assistant"||u(i.type)==="message"?!!(o&&!Lt.has(o)):!1}function xo(e,t,r){return r.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:r.captureLastMessage===!0?!0:Fe(e)==="codex"}function Ao(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:Fe(e)==="codex"}function Vn(e){return Math.max(20,R(e.codexTranscriptPollMs||e.transcriptPollMs,wo))}function bo(e){return Math.max(0,R(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,To))}function ee(e){if(typeof e=="boolean")return e;let t=u(e).toLowerCase();return["true","1","yes","y","on"].includes(t)?!0:["false","0","no","n","off"].includes(t)?!1:null}function je(e){let t=d(e?.metadata)?e.metadata:{};return d(t._runtimeBridge)?t._runtimeBridge:{}}function De(e){return u(je(e).promptKind).toLowerCase()}function No(e,t){for(let r of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let n=ee(r);if(n!=null)return n}return De(t)==="chat"}function qe(e,t){let r=je(e);for(let s of[r.emitThoughtChunks,r.streamThoughts]){let i=ee(s);if(i!=null)return i}let n=De(e);if(n&&n!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=ee(s);if(i!=null)return i}return De(e)==="chat"}function Mo(e){let t=je(e);for(let r of[t.finalTextOnly,t.finalOutputOnly]){let n=ee(r);if(n!=null)return n}return null}function Uo(e,t){let r=Mo(e);return r??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function Po(e,t){return!e.finalTextOnly||t}function Jn(e,t,r,n,s=n){return!n||e.emittedTexts.has(s)?!1:(e.emittedTexts.add(s),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}}),!0)}function Wn(e,t,r,n){return!n||e.emittedThoughtTexts.has(n)?!1:(e.emittedThoughtTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}}}),!0)}function Lo(e,t,r,n=new Set){return{target:e,promptText:t,startedAtMs:r,baselinePaths:n,matchedPath:"",disabled:!1,processedLines:new Map}}function Ge(e,t){let r=d(e.env)?e.env:{},n=u(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||r.ORCHA_RUNTIME_ARTIFACT_DIR)||q(jn(),"orcha-runtime-artifacts"),s=u(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||wt(),i=q(n,s),o=q(i,wt());return co(o,{recursive:!0}),{root:o,realRoot:kt(o),sessionRoot:i,realSessionRoot:kt(i)}}function ko(e){let t=u(e?.artifactDirectory);if(!t)throw new Error("sandbox launch did not provide an artifact directory");return{root:t,realRoot:kt(t),sessionRoot:"",realSessionRoot:""}}function Xn(e){return u(d(e)?e.root:e)}function vn(e){let t=Xn(e),r=u(d(e)?e.sessionRoot:ho(t)),n=u(d(e)?e.realSessionRoot:"");if(r)try{if(n&&kt(r)!==n)return;lo(r)}catch{}}function Ke(e,t={}){let r=Xn(e),n=u(d(e)?e.realRoot:"");if(r){try{if(n&&kt(r)!==n){_("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:r});return}}catch{vn(e);return}try{uo(r,{recursive:!0,force:!0})}catch(s){_("warn","runtime.cli","runtime artifact directory cleanup failed",{...t,artifactRoot:r,error:String(s?.message||s)});return}vn(e)}}function ze(e,t,r=null){return{trustedFileRoots:[t,u(r?.artifactDirectory),u(r?.homeDirectory),...k(e.trustedArtifactRoots),...k(e.trustedFileRoots),...k(e.artifactRoots),...k(e.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(r?.pathMappings)?r.pathMappings:[]}}function Ve(e){let t=u(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let r=d(e.env)?e.env:{},n=u(e.codexHome||r.CODEX_HOME||process.env.CODEX_HOME)||q(mo(),".codex");return q(n,"sessions")}function vo(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 q(e,n,s,i)}function Yn(e,t,r){let n=new Set;for(let s of[t-Yt,t,t+Yt,r-Yt,r,r+Yt])n.add(vo(e,s));return[...n].filter(s=>Hn(s))}function Do(e,t,r){let n=Ve(e),s=t-go,i=r+_o,o=[];for(let a of Yn(n,t,r)){let c=[];try{c=Fn(a)}catch{continue}for(let l of c){if(!l.endsWith(".jsonl"))continue;let p=q(a,l);try{let m=po(p);if(!m.isFile()||m.mtimeMs<s||m.mtimeMs>i)continue;o.push({path:p,mtimeMs:m.mtimeMs})}catch{}}}return o.sort((a,c)=>c.mtimeMs-a.mtimeMs).slice(0,yo)}function $o(e,t,r=t){let n=Ve(e),s=new Set;for(let i of Yn(n,t,r)){let o=[];try{o=Fn(i)}catch{continue}for(let a of o)a.endsWith(".jsonl")&&s.add(q(i,a))}return s}function $e(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)$e(n,t,r+1);return}if(d(e))for(let n of["payload","item","text","delta","output_text","content","message","output","input","prompt","last_agent_message","revised_prompt"])n in e&&$e(e[n],t,r+1)}}function Qn(e){return u(e).replace(/\s+/g," ")}function Ho(e){let t=Qn(e);if(!t)return[];if(t.length<=200)return[t];let r=160,n=[0,Math.floor((t.length-r)/2),t.length-r],s=new Set,i=[];for(let o of n){let a=t.slice(Math.max(0,o),Math.max(0,o)+r).trim();a.length>=40&&!s.has(a)&&(s.add(a),i.push(a))}return i}function Fo(e,t){let r=Ho(t);if(!r.length)return!1;let n=[];for(let i of e)$e(i,n);let s=Qn(n.join(" "));return r.every(i=>s.includes(i))}function Bo(e){return e.find(t=>d(t)&&u(t.type)==="session_meta"&&d(t.payload))||null}function jo(e){let t=d(e?.payload)?e.payload:{},r=u(e?.timestamp||t.timestamp),n=Date.parse(r);return Number.isFinite(n)?n:Number.NaN}function qo(e){let t=u(e.originator),r=u(e.source);if(t!=="codex_exec"&&r!=="exec"||u(e.parent_thread_id))return!1;let n=u(e.thread_source);if(n&&n!=="user")return!1;let s=u(e.session_id),i=u(e.id);return!(s&&i&&s!==i)}function Go(e,t,r){if(!Fo(e,t.promptText))return!1;let n=Bo(e);if(!n)return!1;let s=n.payload;if(!qo(s))return!1;let i=jo(n);if(!Number.isFinite(i)||i<t.startedAtMs-5e3||i>r+5e3)return!1;let o=u(t.target.cwd),a=u(s.cwd);return!(o&&a&&Pn(o)!==Pn(a))}function Dn(e){try{return zo(Bn(e,"utf8"))}catch{return null}}function Ko(e,t,r){if(!e||e.disabled)return null;if(e.matchedPath){let s=Dn(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let n=[];for(let s of Do(e.target,e.startedAtMs,r)){if(e.baselinePaths.has(s.path))continue;let i=Dn(s.path);!i||!Go(i,e,r)||n.push({path:s.path,events:i})}return n.length!==1?(n.length>1&&(e.disabled=!0,_("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,_("info","runtime.cli","codex transcript stream attached",{target:e.target.targetCode,sessionId:t}),n[0])}function zo(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 Vo(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{},r=u(e.type),n=u(t.type);return r==="event_msg"&&n==="image_generation_end"||r==="response_item"&&n==="image_generation_call"}function Jo(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{};return u(e.type)==="response_item"&&So.has(u(t.type))}function Wo(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{};return Ro.has(u(t.type))}function Xo(e,t,r,n){let s=Gn(e),i=Be(e),o=0,a=0,c=0;if(s&&!i&&t.emitThoughtChunks&&Wn(t,r,n,s)&&(c=1),s&&i){let l=t.emittedTexts.size?`
9
+ ${c.text}`:c.text):c?.type==="tool_use"&&c.id&&(o(),i.push({sessionUpdate:"tool_call",toolCallId:c.id,title:c.name,status:"in_progress",rawInput:c.input}));return i}var dt=Object.freeze({codex:{label:"Codex",code:"CODEX",sessionDirectory:"codex-sessions",home:e=>e.env?.CODEX_HOME||process.env.CODEX_HOME||lt(Le(),".codex"),threadId:e=>e?.type==="thread.started"?e.thread_id:void 0,resumeArgs(e,t){let r=e.indexOf("exec");if(r<0||e.includes("resume")||e.includes("--ephemeral"))throw Q("BAD_REQUEST","Codex \u539F\u751F\u4F1A\u8BDD\u9700\u8981\u6807\u51C6 codex exec \u914D\u7F6E");return t?[...e.slice(0,r+1),"resume",t,...e.slice(r+1)]:e},mcpArgs:e=>["-c",`mcp_servers.orcha={url=${JSON.stringify(e)},bearer_token_env_var=${JSON.stringify(ke)},required=true}`]},claude:{label:"Claude Code",code:"CLAUDE",sessionDirectory:"claude-sessions",modelArgs:e=>["--model",e.model||"default",...e.effort?["--effort",e.effort]:[]],home:e=>e.env?.CLAUDE_CONFIG_DIR||process.env.CLAUDE_CONFIG_DIR||lt(Le(),".claude"),threadId:e=>e?.type==="system"&&e.subtype==="init"?e.session_id:void 0,resumeArgs(e,t){let r=e.indexOf("--output-format");if(!e.includes("-p")&&!e.includes("--print")||r<0||e[r+1]!=="stream-json"||!e.includes("--verbose")||e.some(n=>Wi.has(n)))throw Q("BAD_REQUEST","Claude Code \u539F\u751F\u4F1A\u8BDD\u9700\u8981\u6807\u51C6 claude -p --output-format stream-json --verbose \u914D\u7F6E");return t?[...e,"--resume",t]:e},mcpArgs:e=>["--mcp-config",JSON.stringify({mcpServers:{orcha:{type:"http",url:e,headers:{Authorization:`Bearer \${${ke}}`}}}}),"--allowedTools","mcp__orcha"],control:{args:["--input-format","stream-json","--permission-prompt-tool","stdio"],prompt:e=>JSON.stringify({type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}),respond:On},taskMcpError(e){if(e?.type!=="system"||e.subtype!=="init")return null;let t=e.mcp_servers?.find(r=>r?.name==="orcha")?.status||"missing";return t==="connected"?null:Q("RUNTIME_CLAUDE_MCP_UNAVAILABLE",`Claude Code \u672A\u80FD\u8FDE\u63A5 OrchaAI \u4EFB\u52A1\u5DE5\u5177\uFF08${t}\uFF09\uFF0C\u672C\u8F6E\u672A\u6267\u884C`)},progress:Yi}});async function bn(e,t,r){let n=await gn(t,r?[wn(r)]:[]);return{args:e.mcpArgs(n.url),environment:{[ke]:n.token},refresh:s=>n.refresh(s),close:()=>n.close()}}var Wt=class{constructor(t,r,n=lt(Le(),".orcha",dt[t].sessionDirectory)){this.adapter=dt[t],this.directory=lt(n,xn(r))}async turn(t,r,n,s,i){let{label:o,code:a}=this.adapter;if(!t)throw Q("BAD_REQUEST",`${o} native turn requires a run ID`);In(this.directory,{recursive:!0,mode:448});let c=lt(this.directory,"active");try{In(c,{mode:448})}catch(f){throw f.code==="EEXIST"?Q("RUNTIME_SESSION_BUSY",`${o} \u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\u6216\u4E0A\u8F6E\u5F02\u5E38\u4E2D\u65AD\uFF1B\u8BF7\u7B49\u5F85\u5B8C\u6210\uFF0C\u6216\u53D1\u9001 /new \u5F00\u59CB\u65B0\u4EFB\u52A1`):f}let l=lt(this.directory,"session.json"),p,m=()=>{let f=`${l}.${Ki()}.pending`;Cn(f,JSON.stringify(p),{mode:384}),Vi(f,l)};try{try{p=JSON.parse(zi(l,"utf8"))}catch(w){if(w.code!=="ENOENT")throw w}if(p&&!An.test(p.threadId||""))throw Q("RUNTIME_OPERATION_NOT_FOUND",`${o} \u4E0A\u8F6E\u672A\u80FD\u4FDD\u5B58\u539F\u751F\u4F1A\u8BDD\u6807\u8BC6\uFF0C\u8BF7\u53D1\u9001 /new`);try{Cn(lt(this.directory,`${xn(t)}.run`),"",{flag:"wx",mode:384})}catch(w){throw w.code==="EEXIST"?Q("RUNTIME_OPERATION_NOT_FOUND",`\u6B64\u8F6E ${o} \u5DF2\u6267\u884C\u6216\u6267\u884C\u7ED3\u679C\u4E0D\u786E\u5B9A\uFF0C\u4E0D\u80FD\u91CD\u590D\u53D1\u9001`):w}p||={threadId:null},m();let f,h=w=>{if(f)return;let I=w.update?.sessionUpdate==="runtime_event"?this.adapter.threadId(w.update.event):void 0;if(I!==void 0)try{if(!An.test(I||"")||p.threadId&&p.threadId!==I)throw Q(`${a}_SESSION_MISMATCH`,`${o} \u8FD4\u56DE\u4E86\u4E0D\u540C\u7684\u539F\u751F\u4F1A\u8BDD\uFF0C\u8BF7\u53D1\u9001 /new`);p.threadId=I,m()}catch(E){f=E,i();return}n(w)},_=await r(p.threadId,h,w=>{!f&&p.threadId&&s?.(w)});if(f)throw f;if(!p.threadId)throw Q(`${a}_SESSION_MISSING`,`${o} \u6CA1\u6709\u8FD4\u56DE\u539F\u751F\u4F1A\u8BDD\u6807\u8BC6\uFF0C\u8BF7\u68C0\u67E5 CLI \u7248\u672C\u5E76\u53D1\u9001 /new`);return _}finally{Ji(c,{recursive:!0})}}};import{existsSync as Nn,readFileSync as Qi}from"node:fs";import{dirname as Zi,resolve as Xt}from"node:path";import{fileURLToPath as to}from"node:url";var eo=/^[A-Za-z_][A-Za-z0-9_]*$/,J=24*60*60*1e3;function Mn(e=process.env,t=process.cwd()){let r=u(e.ORCHA_RUNTIME_ENV_FILE),n=r?Xt(t,r):Xt(t,".env");if(!Nn(n))return r&&g("warn","config","runtime env file not found",{path:n}),{loaded:!1,path:n,keys:[]};let s=[],i=Qi(n,"utf8");for(let o of i.split(/\r?\n/)){let a=so(o);if(!a)continue;let[c,l]=a;Object.prototype.hasOwnProperty.call(e,c)||(e[c]=l,s.push(c))}return g("info","config","runtime env file loaded",{path:n,keyCount:s.length}),{loaded:!0,path:n,keys:s}}function Un(e=process.env){let t=u(e.ORCHA_RUNTIME_MODE||(e.ORCHA_RUNTIME_ORCHA_URL?"node":"server")),r=u(e.ORCHA_RUNTIME_BRIDGE_HOST||"127.0.0.1"),n=!1,s=Zi(to(import.meta.url)),i=Xt(s,"sandbox","broker.js"),o=Xt(s,"orcha-runtime-sandbox-broker.js"),a=Nn(i)?i:o,c=u(e.ORCHA_RUNTIME_SANDBOX_BROKER_COMMAND);return{mode:t,host:r,port:R(e.ORCHA_RUNTIME_BRIDGE_PORT,5588),token:e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",orchaUrl:u(e.ORCHA_RUNTIME_ORCHA_URL),nodeToken:e.ORCHA_RUNTIME_NODE_TOKEN||e.ORCHA_RUNTIME_BRIDGE_TOKEN||"",nodeId:u(e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"local-runtime-node"),nodeName:u(e.ORCHA_RUNTIME_NODE_NAME||e.ORCHA_RUNTIME_NODE_ID||e.HOSTNAME||"Local Runtime Node"),reconnectMs:R(e.ORCHA_RUNTIME_RECONNECT_MS,3e3),connectTimeoutMs:R(e.ORCHA_RUNTIME_CONNECT_TIMEOUT_MS||e.ORCHA_RUNTIME_WS_CONNECT_TIMEOUT_MS,1e4),defaultTargetCode:e.ORCHA_RUNTIME_DEFAULT_TARGET||"echo",requestLimitBytes:R(e.ORCHA_RUNTIME_REQUEST_LIMIT_BYTES,1048576),initializeTimeoutMs:R(e.ORCHA_RUNTIME_INITIALIZE_TIMEOUT_MS,3e4),sessionPromptTimeoutMs:R(e.ORCHA_RUNTIME_SESSION_PROMPT_TIMEOUT_MS,J),permissionRequestTimeoutMs:R(e.ORCHA_RUNTIME_PERMISSION_TIMEOUT_MS,3e5),sessionIdleTtlMs:R(e.ORCHA_RUNTIME_SESSION_IDLE_TTL_MS,6e5),sessionCleanupIntervalMs:R(e.ORCHA_RUNTIME_SESSION_CLEANUP_INTERVAL_MS,6e4),maxSessionsPerTarget:R(e.ORCHA_RUNTIME_MAX_SESSIONS_PER_TARGET,8),openClawSessionIdleTtlMs:R(e.ORCHA_RUNTIME_OPENCLAW_SESSION_IDLE_TTL_MS,6e4),openClawMaxSessions:R(e.ORCHA_RUNTIME_OPENCLAW_MAX_SESSIONS,1),heartbeatIntervalMs:R(e.ORCHA_RUNTIME_HEARTBEAT_INTERVAL_MS,15e3),sandboxRequired:n,sandboxBrokerCommand:c||process.execPath,sandboxBrokerArguments:ve(e.ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS,"ORCHA_RUNTIME_SANDBOX_BROKER_ARGUMENTS",c?[]:[a]),sandboxProbeTimeoutMs:R(e.ORCHA_RUNTIME_SANDBOX_PROBE_TIMEOUT_MS,1e4),sandboxTempRoot:u(e.ORCHA_RUNTIME_SANDBOX_TEMP_ROOT),trustedWorkspaceRoots:ve(e.ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS,"ORCHA_RUNTIME_TRUSTED_WORKSPACE_ROOTS"),trustedToolchainRoots:ve(e.ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS,"ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS"),egressProxyRequired:no(e.ORCHA_RUNTIME_EGRESS_PROXY_REQUIRED,t==="node"),egressProxySocket:u(e.ORCHA_RUNTIME_EGRESS_PROXY_SOCKET),egressProxyToken:u(e.ORCHA_RUNTIME_EGRESS_PROXY_TOKEN),egressGrantMaxTtlMs:R(e.ORCHA_RUNTIME_EGRESS_GRANT_MAX_TTL_MS,9e5),targets:ro(e.ORCHA_RUNTIME_TARGETS_JSON||"")}}function ro(e){if(!u(e))return{};try{let t=JSON.parse(e);if(d(t))return t}catch(t){g("warn","config","invalid ORCHA_RUNTIME_TARGETS_JSON",{error:String(t)})}return{}}function no(e,t){let r=u(e).toLowerCase();if(!r)return t;if(["true","1","yes","on"].includes(r))return!0;if(["false","0","no","off"].includes(r))return!1;throw new Error(`invalid boolean configuration value: ${r}`)}function ve(e,t,r=[]){let n=u(e);if(!n)return[...r];let s;try{s=JSON.parse(n)}catch{throw new Error(`${t} must be a JSON string array`)}if(!Array.isArray(s)||s.some(i=>typeof i!="string"))throw new Error(`${t} must be a JSON string array`);return s.map(i=>i.trim()).filter(Boolean)}function so(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(!eo.test(s))return null;let i=io(r.slice(n+1).trim());return[s,i]}function io(e){if(!e)return"";let t=e[0];if((t==='"'||t==="'")&&e.endsWith(t)){let r=e.slice(1,-1);return t==='"'?oo(r):r}return ao(e).trim()}function oo(e){return e.replaceAll("\\n",`
10
+ `).replaceAll("\\r","\r").replaceAll("\\t"," ").replaceAll('\\"','"').replaceAll("\\\\","\\")}function ao(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}var qn=5e3,go=2*60*1e3,_o=2*60*1e3,yo=12,wo=1e3,To=1500,Eo=1e3,Oo=/^(?:task|session)-[1-9]\d*(?::[1-9]\d*){4}(?![\s\S])/,Yt=24*60*60*1e3,Lt=new Set(["final_answer","final","complete","completed","done"]),So=new Set(["function_call","function_call_output","custom_tool_call","custom_tool_call_output","local_shell_call","local_shell_call_output","mcp_tool_call","mcp_tool_call_output","web_search_call","image_generation_call","image_generation_end"]),Ro=new Set(["context_compacted","context_compaction","context_compressed"]);function Zt(e,t){if(e?.pid){if(process.platform==="win32"){let r=["/PID",String(e.pid),"/T"];t==="SIGKILL"&&r.push("/F");try{$n("taskkill",r,{stdio:"ignore",windowsHide:!0}).unref?.()}catch{try{e.kill(t)}catch{}}return}try{process.kill(-e.pid,t)}catch(r){if(r?.code==="ESRCH")return;try{e.kill(t)}catch{}}}}function nt(e){Zt(e,"SIGTERM");let t=setTimeout(()=>Zt(e,"SIGKILL"),qn);return t.unref?.(),t}function j(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>j(t)).join("");if(!d(e))return"";for(let t of["text","delta","output_text","content","message","output"]){let r=j(e[t]);if(r)return r}return""}function Gn(e){if(!d(e))return"";let t=d(e.payload)?e.payload:{};if(u(e.type)==="event_msg"){if(u(t.type)==="agent_message")return u(t.message);if(u(t.type)==="task_complete")return u(t.last_agent_message)}if(u(e.type)==="response_item"&&u(t.type)==="message"&&u(t.role)==="assistant")return j(t.content)||j(t.message);if(u(e.type)==="result")return j(e.result);let r=j(e.delta)||j(e.text)||j(e.content);if(r)return r;let n=d(e.item)?e.item:{};return["message","agent_message"].includes(u(n.type))||u(n.role)==="assistant"?j(n.content)||j(n.text)||j(n.message):""}function Kn(e,t){e.explicitFileDelivery||zt(e.artifacts,Me(t,{source:"codex_cli_image_generation",...e.artifactOptions}))}function zn(e){return at(Ue(e))}function Be(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{},r=u(e.type),n=u(t.type);if(r==="event_msg"&&n==="task_complete")return!0;let s=u(t.phase||t.status||t.stage).toLowerCase();if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&u(t.role)==="assistant")return Lt.has(s);let i=d(e.item)?e.item:{};return r==="item.completed"&&u(i.type)==="agent_message"?!0:r==="result"&&e.is_error!==!0?u(e.result).length>0:!1}function te(e){let t=u(e.terminalProtocol||e.eventProtocol).toLowerCase();if(t)return t;let r=Fe(u(e.command)).replace(/\.exe$/i,"").toLowerCase();return r==="codex"||r==="claude"?r:""}function Ln(e,t,r){let n=d(t.error)?t.error:{},s=u(n.message)||j(t.error)||u(t.result)||u(t.message)||r;return Object.assign(new Error(s),{code:e})}function Io(e,t){if(!d(e))return null;let r=u(e.type).toLowerCase();if(t==="codex")return r==="turn.completed"?{status:"completed",result:{stopReason:"end_turn"}}:r==="turn.failed"?{status:"failed",error:Ln("RUNTIME_CODEX_TURN_FAILED",e,"Codex turn failed")}:null;if(t==="claude"&&r==="result"){let n=u(e.subtype).toLowerCase();return e.is_error===!0||n.startsWith("error")||["failed","failure"].includes(n)?{status:"failed",error:Ln("RUNTIME_CLAUDE_RESULT_FAILED",e,"Claude result failed")}:{status:"completed",result:{stopReason:"end_turn",...u(e.result)?{output:u(e.result)}:{}}}}return null}function kn(e){return d(e)?u(e.phase||e.status||e.stage).toLowerCase():""}function Co(e){if(!d(e)||Be(e))return!1;let t=d(e.payload)?e.payload:{},r=u(e.type),n=u(t.type),s=kn(t);if(r==="event_msg"&&n==="agent_message"||r==="response_item"&&n==="message"&&u(t.role)==="assistant")return!!(s&&!Lt.has(s));let i=d(e.item)?e.item:{},o=kn(i);return u(i.role)==="assistant"||u(i.type)==="message"?!!(o&&!Lt.has(o)):!1}function xo(e,t,r){return r.captureLastMessage===!1||t.includes("--output-last-message")||t.includes("-o")?!1:r.captureLastMessage===!0?!0:Fe(e)==="codex"}function Ao(e,t){return t.collectCodexTranscriptArtifacts===!1?!1:t.collectCodexTranscriptArtifacts===!0?!0:Fe(e)==="codex"}function Vn(e){return Math.max(20,R(e.codexTranscriptPollMs||e.transcriptPollMs,wo))}function bo(e){return Math.max(0,R(e.codexFinalOutputWaitMs||e.finalOutputWaitMs,To))}function ee(e){if(typeof e=="boolean")return e;let t=u(e).toLowerCase();return["true","1","yes","y","on"].includes(t)?!0:["false","0","no","n","off"].includes(t)?!1:null}function je(e){let t=d(e?.metadata)?e.metadata:{};return d(t._runtimeBridge)?t._runtimeBridge:{}}function De(e){return u(je(e).promptKind).toLowerCase()}function No(e,t){for(let r of[e.codexTranscriptStreaming,e.streamCodexTranscript]){let n=ee(r);if(n!=null)return n}return De(t)==="chat"}function qe(e,t){let r=je(e);for(let s of[r.emitThoughtChunks,r.streamThoughts]){let i=ee(s);if(i!=null)return i}let n=De(e);if(n&&n!=="chat")return!1;for(let s of[t.emitThoughtChunks,t.streamThoughts]){let i=ee(s);if(i!=null)return i}return De(e)==="chat"}function Mo(e){let t=je(e);for(let r of[t.finalTextOnly,t.finalOutputOnly]){let n=ee(r);if(n!=null)return n}return null}function Uo(e,t){let r=Mo(e);return r??(t.finalTextOnly===!0||t.finalOutputOnly===!0?!0:(t.finalTextOnly===!1||t.finalOutputOnly===!1,!1))}function Po(e,t){return!e.finalTextOnly||t}function Jn(e,t,r,n,s=n){return!n||e.emittedTexts.has(s)?!1:(e.emittedTexts.add(s),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}}),!0)}function Wn(e,t,r,n){return!n||e.emittedThoughtTexts.has(n)?!1:(e.emittedThoughtTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n}}}),!0)}function Lo(e,t,r,n=new Set){return{target:e,promptText:t,startedAtMs:r,baselinePaths:n,matchedPath:"",disabled:!1,processedLines:new Map}}function Ge(e,t){let r=d(e.env)?e.env:{},n=u(e.artifactRoot||e.artifactDir||e.runtimeArtifactRoot||r.ORCHA_RUNTIME_ARTIFACT_DIR)||q(jn(),"orcha-runtime-artifacts"),s=u(t).replace(/[^A-Za-z0-9._-]+/g,"-").slice(0,80)||wt(),i=q(n,s),o=q(i,wt());return co(o,{recursive:!0}),{root:o,realRoot:kt(o),sessionRoot:i,realSessionRoot:kt(i)}}function ko(e){let t=u(e?.artifactDirectory);if(!t)throw new Error("sandbox launch did not provide an artifact directory");return{root:t,realRoot:kt(t),sessionRoot:"",realSessionRoot:""}}function Xn(e){return u(d(e)?e.root:e)}function vn(e){let t=Xn(e),r=u(d(e)?e.sessionRoot:ho(t)),n=u(d(e)?e.realSessionRoot:"");if(r)try{if(n&&kt(r)!==n)return;lo(r)}catch{}}function Ke(e,t={}){let r=Xn(e),n=u(d(e)?e.realRoot:"");if(r){try{if(n&&kt(r)!==n){g("warn","runtime.cli","runtime artifact directory cleanup skipped; path changed",{...t,artifactRoot:r});return}}catch{vn(e);return}try{uo(r,{recursive:!0,force:!0})}catch(s){g("warn","runtime.cli","runtime artifact directory cleanup failed",{...t,artifactRoot:r,error:String(s?.message||s)});return}vn(e)}}function ze(e,t,r=null){return{trustedFileRoots:[t,u(r?.artifactDirectory),u(r?.homeDirectory),...k(e.trustedArtifactRoots),...k(e.trustedFileRoots),...k(e.artifactRoots),...k(e.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(r?.pathMappings)?r.pathMappings:[]}}function Ve(e){let t=u(e.codexSessionsRoot||e.codexSessionRoot);if(t)return t;let r=d(e.env)?e.env:{},n=u(e.codexHome||r.CODEX_HOME||process.env.CODEX_HOME)||q(mo(),".codex");return q(n,"sessions")}function vo(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 q(e,n,s,i)}function Yn(e,t,r){let n=new Set;for(let s of[t-Yt,t,t+Yt,r-Yt,r,r+Yt])n.add(vo(e,s));return[...n].filter(s=>Hn(s))}function Do(e,t,r){let n=Ve(e),s=t-go,i=r+_o,o=[];for(let a of Yn(n,t,r)){let c=[];try{c=Fn(a)}catch{continue}for(let l of c){if(!l.endsWith(".jsonl"))continue;let p=q(a,l);try{let m=po(p);if(!m.isFile()||m.mtimeMs<s||m.mtimeMs>i)continue;o.push({path:p,mtimeMs:m.mtimeMs})}catch{}}}return o.sort((a,c)=>c.mtimeMs-a.mtimeMs).slice(0,yo)}function $o(e,t,r=t){let n=Ve(e),s=new Set;for(let i of Yn(n,t,r)){let o=[];try{o=Fn(i)}catch{continue}for(let a of o)a.endsWith(".jsonl")&&s.add(q(i,a))}return s}function $e(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)$e(n,t,r+1);return}if(d(e))for(let n of["payload","item","text","delta","output_text","content","message","output","input","prompt","last_agent_message","revised_prompt"])n in e&&$e(e[n],t,r+1)}}function Qn(e){return u(e).replace(/\s+/g," ")}function Ho(e){let t=Qn(e);if(!t)return[];if(t.length<=200)return[t];let r=160,n=[0,Math.floor((t.length-r)/2),t.length-r],s=new Set,i=[];for(let o of n){let a=t.slice(Math.max(0,o),Math.max(0,o)+r).trim();a.length>=40&&!s.has(a)&&(s.add(a),i.push(a))}return i}function Fo(e,t){let r=Ho(t);if(!r.length)return!1;let n=[];for(let i of e)$e(i,n);let s=Qn(n.join(" "));return r.every(i=>s.includes(i))}function Bo(e){return e.find(t=>d(t)&&u(t.type)==="session_meta"&&d(t.payload))||null}function jo(e){let t=d(e?.payload)?e.payload:{},r=u(e?.timestamp||t.timestamp),n=Date.parse(r);return Number.isFinite(n)?n:Number.NaN}function qo(e){let t=u(e.originator),r=u(e.source);if(t!=="codex_exec"&&r!=="exec"||u(e.parent_thread_id))return!1;let n=u(e.thread_source);if(n&&n!=="user")return!1;let s=u(e.session_id),i=u(e.id);return!(s&&i&&s!==i)}function Go(e,t,r){if(!Fo(e,t.promptText))return!1;let n=Bo(e);if(!n)return!1;let s=n.payload;if(!qo(s))return!1;let i=jo(n);if(!Number.isFinite(i)||i<t.startedAtMs-5e3||i>r+5e3)return!1;let o=u(t.target.cwd),a=u(s.cwd);return!(o&&a&&Pn(o)!==Pn(a))}function Dn(e){try{return zo(Bn(e,"utf8"))}catch{return null}}function Ko(e,t,r){if(!e||e.disabled)return null;if(e.matchedPath){let s=Dn(e.matchedPath);return s?{path:e.matchedPath,events:s}:null}let n=[];for(let s of Do(e.target,e.startedAtMs,r)){if(e.baselinePaths.has(s.path))continue;let i=Dn(s.path);!i||!Go(i,e,r)||n.push({path:s.path,events:i})}return n.length!==1?(n.length>1&&(e.disabled=!0,g("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,g("info","runtime.cli","codex transcript stream attached",{target:e.target.targetCode,sessionId:t}),n[0])}function zo(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 Vo(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{},r=u(e.type),n=u(t.type);return r==="event_msg"&&n==="image_generation_end"||r==="response_item"&&n==="image_generation_call"}function Jo(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{};return u(e.type)==="response_item"&&So.has(u(t.type))}function Wo(e){if(!d(e))return!1;let t=d(e.payload)?e.payload:{};return Ro.has(u(t.type))}function Xo(e,t,r,n){let s=Gn(e),i=Be(e),o=0,a=0,c=0;if(s&&!i&&t.emitThoughtChunks&&Wn(t,r,n,s)&&(c=1),s&&i){let l=t.emittedTexts.size?`
11
11
 
12
- ${s}`:s;Jn(t,r,n,l,s)&&(o=1,a=1)}return s&&i&&(t.finalTextSeen=!0),Kn(t,e),(Vo(e)||Jo(e)||Wo(e)||i)&&n({sessionId:r,update:{sessionUpdate:"runtime_event",event:zn(e)}}),{textCount:o,finalTextCount:a,thoughtCount:c}}function He(e,t,r,n,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0,thoughtCount:0};let i=e.artifacts.size,o=0,a=0,c=0,l=0,p=Ko(t,r,s);if(p){let m=Math.min(t.processedLines.get(p.path)||0,p.events.length),f=e.artifacts.size;for(let h of p.events.slice(m)){let g=Xo(h,e,r,n);a+=g.textCount,c+=g.finalTextCount,l+=g.thoughtCount}t.processedLines.set(p.path,p.events.length),(p.events.length>m||e.artifacts.size>f)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:a,finalTextCount:c,thoughtCount:l}}function Yo(e,{remove:t=!0}={}){if(!e||!Hn(e))return"";try{return Bn(e,"utf8").trim()}catch{return""}finally{t&&Qt(e)}}function Qt(e){if(e)try{fo(e)}catch{}}function Qo(e,t){return{artifactCount:(e?.artifactCount||0)+(t?.artifactCount||0),transcriptCount:(e?.transcriptCount||0)+(t?.transcriptCount||0),textCount:(e?.textCount||0)+(t?.textCount||0),finalTextCount:(e?.finalTextCount||0)+(t?.finalTextCount||0),thoughtCount:(e?.thoughtCount||0)+(t?.thoughtCount||0)}}function Zo(e){return new Promise(t=>setTimeout(t,e))}function ta(e,t,r,n){return n?(e.finalTextSeen=!0,e.emittedTexts.has(n)||(e.emittedTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}})),!0):!1}async function ea(e,t,r,n,s,i){let o=He(e,t,r,n,Date.now()),a=()=>ta(e,r,n,Yo(s,{remove:!1}));if(a()||e.finalTextSeen)return Qt(s),o;let c=bo(i);if(c<=0||!t&&!s)return Qt(s),o;let l=Date.now()+c,p=Math.min(Vn(i),100);for(;!e.finalTextSeen&&Date.now()<l&&(await Zo(Math.min(p,Math.max(0,l-Date.now()))),o=Qo(o,He(e,t,r,n,Date.now())),!a()););return Qt(s),o}var Tt=class{constructor(t,r,n={},s={}){this.agent=t,this.target=r,this.options=n,this.callbacks=s,this.active=new Map;let i=te(r);if(this.adapter=Object.hasOwn(dt,i)?dt[i]:null,n.source==="ai_chat_runtime_node"&&this.adapter){let{label:o}=this.adapter;if(typeof n.cloudSessionId!="string"||!Oo.test(n.cloudSessionId))throw Object.assign(new Error(`${o} \u539F\u751F\u4F1A\u8BDD\u6807\u8BC6\u65E0\u6548\uFF1A\u9700\u8981\u5B8C\u6574\u7684\u4EFB\u52A1\u6216\u4F1A\u8BDD\u9694\u79BB\u6807\u8BC6`),{code:"BAD_REQUEST"});if(!n.orchaUrl)throw Object.assign(new Error(`${o} \u539F\u751F\u4F1A\u8BDD\u7F3A\u5C11 OrchaAI \u670D\u52A1\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u8BBE\u5907`),{code:"BAD_REQUEST"});if(n.prepareLaunch)throw Object.assign(new Error(`${o} \u539F\u751F\u4F1A\u8BDD\u4E0D\u652F\u6301\u6C99\u7BB1\u542F\u52A8\uFF0C\u8BF7\u4F7F\u7528\u5DF2\u63A5\u5165\u7684\u672C\u673A\u8BBE\u5907`),{code:"BAD_REQUEST"});this.nativeSession=new Wt(i,[n.orchaUrl,t.agentId,t.targetCode,n.cloudSessionId,K(r,t.workspace),r.command,this.adapter.home(r)])}}async sessionNew(t={}){let r=t.mcpServers||[];if(r.length&&(t.metadata?.source==="conversation_delegation"||this.nativeSession)&&this.adapter){if(this.options.prepareLaunch)throw Object.assign(new Error(`${this.adapter.label} task MCP requires a reachable node-local transport; this sandbox launcher does not provide one`),{code:"unsupported_dynamic_mcp"});this.explicitFileDelivery=!0,this.taskMcp=await bn(this.adapter,r,()=>({cwd:this.deliveryCwd,roots:[...this.deliveryRoots||[],...this.deliveryThreadId?[q(Ve(this.target),"..","generated_images",this.deliveryThreadId)]:[]]}))}else if(r.length&&t.metadata?.source==="conversation_delegation")throw Object.assign(new Error("This CLI adapter does not support task-scoped MCP"),{code:"unsupported_dynamic_mcp"});return{sessionId:`cli-${this.agent.agentId}-${wt()}`}}async requestApproval(t,{signal:r}={}){let n=this.approvalTurn;return!n||!this.callbacks.onPermissionRequest?{outcome:"denied",reason:"no active OrchaAI turn"}:this.callbacks.onPermissionRequest({agent:this.agent,runtimeSessionId:n.sessionId,request:t,emitUpdate:n.emitUpdate,signal:r?AbortSignal.any([n.ended.signal,r]):n.ended.signal})}async refreshMcpServers(t){if(!this.taskMcp)throw Object.assign(new Error("The original Codex MCP binding is unavailable"),{code:"RUNTIME_OPERATION_NOT_FOUND"});await this.taskMcp.refresh(t)}async sessionPrompt(t,r,n){return this.nativeSession?this.nativeSession.turn(this.options.runId,(s,i,o)=>this.runPrompt(t,i,o,s),s=>{let i=s.update?.event;i?.type==="thread.started"&&(this.deliveryThreadId=i.thread_id),r(s)},n,()=>this.sessionCancel(t)):this.runPrompt(t,r,n)}async runPrompt(t,r,n,s){let i=Date.now(),o=u(this.target.command);if(!o)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let a=u(t.sessionId)||wt(),c=yt(t.prompt),l=this.nativeSession&&this.adapter.control,p=l?"stdin":u(this.target.promptMode||"stdin"),m=this.buildArgs(p,c);if(t.modelOptions&&!this.adapter?.modelArgs)throw Object.assign(new Error("This native CLI cannot select models"),{code:"RUNTIME_MODEL_OPTIONS_UNSUPPORTED"});let f=[...this.taskMcp?.args||[],...l?.args||[],...t.modelOptions?this.adapter.modelArgs(t.modelOptions):[],...this.nativeSession?this.adapter.resumeArgs(m,s):m],h=K(this.target,this.agent.workspace),g=typeof this.options.prepareLaunch=="function",I=xo(o,f,this.target)?g?`/tmp/orcha-runtime-last-message-${wt()}.txt`:q(jn(),`orcha-runtime-last-message-${wt()}.txt`):"";I&&f.push("--output-last-message",I);let E={...d(this.target.env)?this.target.env:{},...this.taskMcp?.environment||{},...p==="env"?{ORCHA_RUNTIME_PROMPT:c}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:a},C=g?await this.options.prepareLaunch({command:o,args:f,cwd:h,environment:E}):{command:o,args:f,cwd:h,environment:{...process.env,...E},cleanup:async()=>{}},y=g?ko(C):Ge(this.target,a),O=y.root,M=ze(this.target,O,C);this.deliveryCwd=h,this.deliveryRoots=[h,...M.trustedFileRoots].filter(Boolean),this.deliveryThreadId=s||null;let A=Ao(o,this.target),T={...this.target,targetCode:this.agent.targetCode,cwd:h,...g?{codexHome:q(C.homeDirectory,".codex")}:{}},x=A?$o(T,i):new Set,S=g&&I?q(C.tempDirectory,I.slice(5)):I,U=R(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,R(this.options.sessionPromptTimeoutMs,J));g||(C.environment.ORCHA_RUNTIME_ARTIFACT_DIR=O);let z={sessionId:a,emitUpdate:r,ended:new AbortController};this.approvalTurn=z;let b=$n(C.command,C.args,{cwd:C.cwd,env:C.environment,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(a,b),_("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:a,pid:b.pid,timeoutMs:U,isolation:C.isolation});let _t="",X=u(this.target.outputMode||"text"),P={control:l?{respond:l.respond,stdin:b.stdin,pending:new Map}:null,explicitFileDelivery:this.explicitFileDelivery,artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:M,finalTextSeen:!1,finalTextOnly:Uo(t,this.target),emitThoughtChunks:qe(t,this.target),terminalOutcome:null,terminalProtocol:te(this.target),emitTerminal:null,progress:{}},xt=A?Lo(T,c,i,x):null;return b.stdout.setEncoding("utf8"),b.stdout.on("data",Y=>this.handleStdout(Y,X,P,a,r)),b.stderr.setEncoding("utf8"),b.stderr.on("data",Y=>{_t+=Y,this.target.emitStderr===!0&&r({sessionId:a,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:Y}}})}),b.stdin.on("error",Y=>_("debug","runtime.cli","runtime stdin closed",{target:this.agent.targetCode,sessionId:a,error:String(Y?.message||Y)})),l?b.stdin.write(`${l.prompt(c)}
13
- `):p==="stdin"?b.stdin.end(c):b.stdin.end(),await new Promise((Y,Ie)=>{let At=!1,zr=!1,jt=null,bt=null,Ce=xt&&No(this.target,t)?setInterval(()=>{try{He(P,xt,a,r)}catch(L){_("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:a,error:String(L?.message||L)})}},Vn(this.target)):null;Ce?.unref?.();let Vr=setTimeout(()=>{zr=!0,_("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:a,pid:b.pid,timeoutMs:U}),Zt(b,"SIGTERM"),jt=setTimeout(()=>{_("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:a,pid:b.pid}),Zt(b,"SIGKILL")},qn),jt.unref?.(),Nt(Object.assign(new Error(`runtime CLI timed out after ${U}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},U);Vr.unref?.();let Jr=async()=>{clearTimeout(Vr),bt&&clearTimeout(bt),Ce&&clearInterval(Ce),jt&&!zr&&clearTimeout(jt),z.ended.abort(),this.approvalTurn===z&&(this.approvalTurn=null),Ke(y,{target:this.agent.targetCode,sessionId:a}),this.active.delete(a),P.emitTerminal=null,await C.cleanup?.()},Qs=L=>{At||(At=!0,Jr().then(()=>Y(L),Ie))},Nt=L=>{At||(At=!0,Jr().then(()=>Ie(L),V=>{_("warn","runtime.cli","sandbox launch cleanup failed",{target:this.agent.targetCode,sessionId:a,error:String(V?.message||V)}),Ie(L)}))};P.emitTerminal=L=>{let V={...d(L.result)?L.result:{},_artifacts:[...P.artifacts.values()],...P.nativeModel?{nativeModel:P.nativeModel}:{}};try{n?.({...L,result:V})}catch(ot){_("warn","runtime.cli","runtime terminal listener failed",{target:this.agent.targetCode,sessionId:a,error:String(ot?.message||ot)})}let G=Math.max(0,R(this.target.terminalExitGraceMs,Eo));bt=setTimeout(()=>{bt=null,!(At||this.active.get(a)!==b)&&(_("warn","runtime.cli","runtime stayed alive after terminal event; terminating child",{target:this.agent.targetCode,sessionId:a,pid:b.pid,terminalProtocol:P.terminalProtocol,graceMs:G}),nt(b))},G),bt.unref?.()},b.on("error",L=>{_("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:a,pid:b.pid,error:String(L?.message||L)}),Nt(L)}),b.on("exit",(L,V)=>{(async()=>{X==="json-lines"&&P.value.trim()&&this.handleStdout(`
14
- `,X,P,a,r);let G=await ea(P,xt,a,r,S,this.target);(G.artifactCount>0||G.textCount>0||G.thoughtCount>0)&&_("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:a,artifactCount:G.artifactCount,textCount:G.textCount,finalTextCount:G.finalTextCount,thoughtCount:G.thoughtCount,transcriptCount:G.transcriptCount});let ot=_t.trim();if(ot&&_("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:a,stderr:ot}),_("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:a,pid:b.pid,exitCode:L,signal:V,artifactCount:P.artifacts.size,finalTextSeen:P.finalTextSeen}),P.terminalOutcome?.status==="failed"){Nt(P.terminalOutcome.error);return}if(L!==0&&P.terminalOutcome?.status!=="completed"){let Zs=Object.assign(new Error(`runtime CLI exited with code ${L??"unknown"}${V?` (${V})`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:L,signal:V});Nt(Zs);return}Qs({stopReason:"end_turn",exitCode:L,signal:V,_artifacts:[...P.artifacts.values()],...P.nativeModel?{nativeModel:P.nativeModel}:{},...ot?{stderr:ot}:{}})})().catch(Nt)})})}buildArgs(t,r){let n=k(this.target.args);return t==="args"?[...n,r]:n}handleStdout(t,r,n,s,i){if(r!=="json-lines"){i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t}}});return}n.value+=t;let o=n.value.split(/\r?\n/);n.value=o.pop()||"";for(let a of o){let c=a.trim();if(c)try{let l=JSON.parse(c);if(n.terminalProtocol==="claude"){let I=l.type==="system"&&l.subtype==="init"?l.model:l.type==="assistant"&&l.parent_tool_use_id==null?l.message?.model:null;typeof I=="string"&&I&&(n.nativeModel=I)}if(n.control&&this.hostControl(n.control,l))continue;!this.nativeSession&&l.type==="thread.started"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l.thread_id||"")&&(this.deliveryThreadId=l.thread_id);let p=this.taskMcp&&this.adapter?.taskMcpError?.(l);if(p){n.terminalOutcome||(n.terminalOutcome={status:"failed",error:p},n.emitTerminal?.(n.terminalOutcome)),nt(this.active.get(s));continue}Kn(n,l);let m=this.adapter?.progress?.(l,n.progress,{emitThoughts:n.emitThoughtChunks,streamText:!n.finalTextOnly});for(let I of m||[{sessionUpdate:"runtime_event",event:zn(l)}])i({sessionId:s,update:I});let f=Gn(l),h=Be(l),g=m?"":f;g&&n.emitThoughtChunks&&!h&&Co(l)?Wn(n,s,i,g):g&&Po(n,h)&&Jn(n,s,i,g),f&&h&&(n.finalTextSeen=!0);let w=Io(l,n.terminalProtocol);w&&!n.terminalOutcome&&(w.status==="failed"||n.finalTextSeen||n.artifacts.size>0)&&(n.terminalOutcome=w,n.emitTerminal?.(w))}catch{i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a}
12
+ ${s}`:s;Jn(t,r,n,l,s)&&(o=1,a=1)}return s&&i&&(t.finalTextSeen=!0),Kn(t,e),(Vo(e)||Jo(e)||Wo(e)||i)&&n({sessionId:r,update:{sessionUpdate:"runtime_event",event:zn(e)}}),{textCount:o,finalTextCount:a,thoughtCount:c}}function He(e,t,r,n,s=Date.now()){if(!t)return{artifactCount:0,transcriptCount:0,textCount:0,finalTextCount:0,thoughtCount:0};let i=e.artifacts.size,o=0,a=0,c=0,l=0,p=Ko(t,r,s);if(p){let m=Math.min(t.processedLines.get(p.path)||0,p.events.length),f=e.artifacts.size;for(let h of p.events.slice(m)){let _=Xo(h,e,r,n);a+=_.textCount,c+=_.finalTextCount,l+=_.thoughtCount}t.processedLines.set(p.path,p.events.length),(p.events.length>m||e.artifacts.size>f)&&(o=1)}return{artifactCount:e.artifacts.size-i,transcriptCount:o,textCount:a,finalTextCount:c,thoughtCount:l}}function Yo(e,{remove:t=!0}={}){if(!e||!Hn(e))return"";try{return Bn(e,"utf8").trim()}catch{return""}finally{t&&Qt(e)}}function Qt(e){if(e)try{fo(e)}catch{}}function Qo(e,t){return{artifactCount:(e?.artifactCount||0)+(t?.artifactCount||0),transcriptCount:(e?.transcriptCount||0)+(t?.transcriptCount||0),textCount:(e?.textCount||0)+(t?.textCount||0),finalTextCount:(e?.finalTextCount||0)+(t?.finalTextCount||0),thoughtCount:(e?.thoughtCount||0)+(t?.thoughtCount||0)}}function Zo(e){return new Promise(t=>setTimeout(t,e))}function ta(e,t,r,n){return n?(e.finalTextSeen=!0,e.emittedTexts.has(n)||(e.emittedTexts.add(n),r({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}})),!0):!1}async function ea(e,t,r,n,s,i){let o=He(e,t,r,n,Date.now()),a=()=>ta(e,r,n,Yo(s,{remove:!1}));if(a()||e.finalTextSeen)return Qt(s),o;let c=bo(i);if(c<=0||!t&&!s)return Qt(s),o;let l=Date.now()+c,p=Math.min(Vn(i),100);for(;!e.finalTextSeen&&Date.now()<l&&(await Zo(Math.min(p,Math.max(0,l-Date.now()))),o=Qo(o,He(e,t,r,n,Date.now())),!a()););return Qt(s),o}var Tt=class{constructor(t,r,n={},s={}){this.agent=t,this.target=r,this.options=n,this.callbacks=s,this.active=new Map;let i=te(r);if(this.adapter=Object.hasOwn(dt,i)?dt[i]:null,n.source==="ai_chat_runtime_node"&&this.adapter){let{label:o}=this.adapter;if(typeof n.cloudSessionId!="string"||!Oo.test(n.cloudSessionId))throw Object.assign(new Error(`${o} \u539F\u751F\u4F1A\u8BDD\u6807\u8BC6\u65E0\u6548\uFF1A\u9700\u8981\u5B8C\u6574\u7684\u4EFB\u52A1\u6216\u4F1A\u8BDD\u9694\u79BB\u6807\u8BC6`),{code:"BAD_REQUEST"});if(!n.orchaUrl)throw Object.assign(new Error(`${o} \u539F\u751F\u4F1A\u8BDD\u7F3A\u5C11 OrchaAI \u670D\u52A1\u5730\u5740\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u8BBE\u5907`),{code:"BAD_REQUEST"});if(n.prepareLaunch)throw Object.assign(new Error(`${o} \u539F\u751F\u4F1A\u8BDD\u4E0D\u652F\u6301\u6C99\u7BB1\u542F\u52A8\uFF0C\u8BF7\u4F7F\u7528\u5DF2\u63A5\u5165\u7684\u672C\u673A\u8BBE\u5907`),{code:"BAD_REQUEST"});this.nativeSession=new Wt(i,[n.orchaUrl,t.agentId,t.targetCode,n.cloudSessionId,K(r,t.workspace),r.command,this.adapter.home(r)])}}async sessionNew(t={}){let r=t.mcpServers||[];if(r.length&&(t.metadata?.source==="conversation_delegation"||this.nativeSession)&&this.adapter){if(this.options.prepareLaunch)throw Object.assign(new Error(`${this.adapter.label} task MCP requires a reachable node-local transport; this sandbox launcher does not provide one`),{code:"unsupported_dynamic_mcp"});this.explicitFileDelivery=!0,this.taskMcp=await bn(this.adapter,r,()=>({cwd:this.deliveryCwd,roots:[...this.deliveryRoots||[],...this.deliveryThreadId?[q(Ve(this.target),"..","generated_images",this.deliveryThreadId)]:[]]}))}else if(r.length&&t.metadata?.source==="conversation_delegation")throw Object.assign(new Error("This CLI adapter does not support task-scoped MCP"),{code:"unsupported_dynamic_mcp"});return{sessionId:`cli-${this.agent.agentId}-${wt()}`}}async requestApproval(t,{signal:r}={}){let n=this.approvalTurn;return!n||!this.callbacks.onPermissionRequest?{outcome:"denied",reason:"no active OrchaAI turn"}:this.callbacks.onPermissionRequest({agent:this.agent,runtimeSessionId:n.sessionId,request:t,emitUpdate:n.emitUpdate,signal:r?AbortSignal.any([n.ended.signal,r]):n.ended.signal})}async refreshMcpServers(t){if(!this.taskMcp)throw Object.assign(new Error("The original Codex MCP binding is unavailable"),{code:"RUNTIME_OPERATION_NOT_FOUND"});await this.taskMcp.refresh(t)}async sessionPrompt(t,r,n){return this.nativeSession?this.nativeSession.turn(this.options.runId,(s,i,o)=>this.runPrompt(t,i,o,s),s=>{let i=s.update?.event;i?.type==="thread.started"&&(this.deliveryThreadId=i.thread_id),r(s)},n,()=>this.sessionCancel(t)):this.runPrompt(t,r,n)}async runPrompt(t,r,n,s){let i=Date.now(),o=u(this.target.command);if(!o)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let a=u(t.sessionId)||wt(),c=yt(t.prompt),l=this.nativeSession&&this.adapter.control,p=l?"stdin":u(this.target.promptMode||"stdin"),m=this.buildArgs(p,c);if(t.modelOptions&&!this.adapter?.modelArgs)throw Object.assign(new Error("This native CLI cannot select models"),{code:"RUNTIME_MODEL_OPTIONS_UNSUPPORTED"});let f=[...this.taskMcp?.args||[],...l?.args||[],...t.modelOptions?this.adapter.modelArgs(t.modelOptions):[],...this.nativeSession?this.adapter.resumeArgs(m,s):m],h=K(this.target,this.agent.workspace),_=typeof this.options.prepareLaunch=="function",I=xo(o,f,this.target)?_?`/tmp/orcha-runtime-last-message-${wt()}.txt`:q(jn(),`orcha-runtime-last-message-${wt()}.txt`):"";I&&f.push("--output-last-message",I);let E={...d(this.target.env)?this.target.env:{},...this.taskMcp?.environment||{},...p==="env"?{ORCHA_RUNTIME_PROMPT:c}:{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:a},C=_?await this.options.prepareLaunch({command:o,args:f,cwd:h,environment:E}):{command:o,args:f,cwd:h,environment:{...process.env,...E},cleanup:async()=>{}},y=_?ko(C):Ge(this.target,a),O=y.root,M=ze(this.target,O,C);this.deliveryCwd=h,this.deliveryRoots=[h,...M.trustedFileRoots].filter(Boolean),this.deliveryThreadId=s||null;let A=Ao(o,this.target),T={...this.target,targetCode:this.agent.targetCode,cwd:h,..._?{codexHome:q(C.homeDirectory,".codex")}:{}},x=A?$o(T,i):new Set,S=_&&I?q(C.tempDirectory,I.slice(5)):I,U=R(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,R(this.options.sessionPromptTimeoutMs,J));_||(C.environment.ORCHA_RUNTIME_ARTIFACT_DIR=O);let z={sessionId:a,emitUpdate:r,ended:new AbortController};this.approvalTurn=z;let b=$n(C.command,C.args,{cwd:C.cwd,env:C.environment,stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(a,b),g("info","runtime.cli","runtime prompt started",{target:this.agent.targetCode,sessionId:a,pid:b.pid,timeoutMs:U,isolation:C.isolation});let _t="",X=u(this.target.outputMode||"text"),P={control:l?{respond:l.respond,stdin:b.stdin,pending:new Map}:null,explicitFileDelivery:this.explicitFileDelivery,artifacts:new Map,emittedTexts:new Set,emittedThoughtTexts:new Set,value:"",artifactOptions:M,finalTextSeen:!1,finalTextOnly:Uo(t,this.target),emitThoughtChunks:qe(t,this.target),terminalOutcome:null,terminalProtocol:te(this.target),emitTerminal:null,progress:{}},xt=A?Lo(T,c,i,x):null;return b.stdout.setEncoding("utf8"),b.stdout.on("data",Y=>this.handleStdout(Y,X,P,a,r)),b.stderr.setEncoding("utf8"),b.stderr.on("data",Y=>{_t+=Y,this.target.emitStderr===!0&&r({sessionId:a,update:{sessionUpdate:"runtime_stderr_chunk",content:{type:"text",text:Y}}})}),b.stdin.on("error",Y=>g("debug","runtime.cli","runtime stdin closed",{target:this.agent.targetCode,sessionId:a,error:String(Y?.message||Y)})),l?b.stdin.write(`${l.prompt(c)}
13
+ `):p==="stdin"?b.stdin.end(c):b.stdin.end(),await new Promise((Y,Ie)=>{let At=!1,zr=!1,jt=null,bt=null,Ce=xt&&No(this.target,t)?setInterval(()=>{try{He(P,xt,a,r)}catch(L){g("warn","runtime.cli","codex transcript stream poll failed",{target:this.agent.targetCode,sessionId:a,error:String(L?.message||L)})}},Vn(this.target)):null;Ce?.unref?.();let Vr=setTimeout(()=>{zr=!0,g("warn","runtime.cli","runtime prompt timed out; terminating child",{target:this.agent.targetCode,sessionId:a,pid:b.pid,timeoutMs:U}),Zt(b,"SIGTERM"),jt=setTimeout(()=>{g("warn","runtime.cli","runtime prompt force killing child",{target:this.agent.targetCode,sessionId:a,pid:b.pid}),Zt(b,"SIGKILL")},qn),jt.unref?.(),Nt(Object.assign(new Error(`runtime CLI timed out after ${U}ms`),{code:"RUNTIME_CLI_TIMEOUT"}))},U);Vr.unref?.();let Jr=async()=>{clearTimeout(Vr),bt&&clearTimeout(bt),Ce&&clearInterval(Ce),jt&&!zr&&clearTimeout(jt),z.ended.abort(),this.approvalTurn===z&&(this.approvalTurn=null),Ke(y,{target:this.agent.targetCode,sessionId:a}),this.active.delete(a),P.emitTerminal=null,await C.cleanup?.()},Qs=L=>{At||(At=!0,Jr().then(()=>Y(L),Ie))},Nt=L=>{At||(At=!0,Jr().then(()=>Ie(L),V=>{g("warn","runtime.cli","sandbox launch cleanup failed",{target:this.agent.targetCode,sessionId:a,error:String(V?.message||V)}),Ie(L)}))};P.emitTerminal=L=>{let V={...d(L.result)?L.result:{},_artifacts:[...P.artifacts.values()],...P.nativeModel?{nativeModel:P.nativeModel}:{}};try{n?.({...L,result:V})}catch(ot){g("warn","runtime.cli","runtime terminal listener failed",{target:this.agent.targetCode,sessionId:a,error:String(ot?.message||ot)})}let G=Math.max(0,R(this.target.terminalExitGraceMs,Eo));bt=setTimeout(()=>{bt=null,!(At||this.active.get(a)!==b)&&(g("warn","runtime.cli","runtime stayed alive after terminal event; terminating child",{target:this.agent.targetCode,sessionId:a,pid:b.pid,terminalProtocol:P.terminalProtocol,graceMs:G}),nt(b))},G),bt.unref?.()},b.on("error",L=>{g("warn","runtime.cli","runtime child error",{target:this.agent.targetCode,sessionId:a,pid:b.pid,error:String(L?.message||L)}),Nt(L)}),b.on("exit",(L,V)=>{(async()=>{X==="json-lines"&&P.value.trim()&&this.handleStdout(`
14
+ `,X,P,a,r);let G=await ea(P,xt,a,r,S,this.target);(G.artifactCount>0||G.textCount>0||G.thoughtCount>0)&&g("info","runtime.cli","codex transcript updates collected",{target:this.agent.targetCode,sessionId:a,artifactCount:G.artifactCount,textCount:G.textCount,finalTextCount:G.finalTextCount,thoughtCount:G.thoughtCount,transcriptCount:G.transcriptCount});let ot=_t.trim();if(ot&&g("debug","runtime.cli","runtime stderr",{target:this.agent.targetCode,sessionId:a,stderr:ot}),g("info","runtime.cli","runtime prompt finished",{target:this.agent.targetCode,sessionId:a,pid:b.pid,exitCode:L,signal:V,artifactCount:P.artifacts.size,finalTextSeen:P.finalTextSeen}),P.terminalOutcome?.status==="failed"){Nt(P.terminalOutcome.error);return}if(L!==0&&P.terminalOutcome?.status!=="completed"){let Zs=Object.assign(new Error(`runtime CLI exited with code ${L??"unknown"}${V?` (${V})`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:L,signal:V});Nt(Zs);return}Qs({stopReason:"end_turn",exitCode:L,signal:V,_artifacts:[...P.artifacts.values()],...P.nativeModel?{nativeModel:P.nativeModel}:{},...ot?{stderr:ot}:{}})})().catch(Nt)})})}buildArgs(t,r){let n=k(this.target.args);return t==="args"?[...n,r]:n}handleStdout(t,r,n,s,i){if(r!=="json-lines"){i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t}}});return}n.value+=t;let o=n.value.split(/\r?\n/);n.value=o.pop()||"";for(let a of o){let c=a.trim();if(c)try{let l=JSON.parse(c);if(n.terminalProtocol==="claude"){let I=l.type==="system"&&l.subtype==="init"?l.model:l.type==="assistant"&&l.parent_tool_use_id==null?l.message?.model:null;typeof I=="string"&&I&&(n.nativeModel=I)}if(n.control&&this.hostControl(n.control,l))continue;!this.nativeSession&&l.type==="thread.started"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l.thread_id||"")&&(this.deliveryThreadId=l.thread_id);let p=this.taskMcp&&this.adapter?.taskMcpError?.(l);if(p){n.terminalOutcome||(n.terminalOutcome={status:"failed",error:p},n.emitTerminal?.(n.terminalOutcome)),nt(this.active.get(s));continue}Kn(n,l);let m=this.adapter?.progress?.(l,n.progress,{emitThoughts:n.emitThoughtChunks,streamText:!n.finalTextOnly});for(let I of m||[{sessionUpdate:"runtime_event",event:zn(l)}])i({sessionId:s,update:I});let f=Gn(l),h=Be(l),_=m?"":f;_&&n.emitThoughtChunks&&!h&&Co(l)?Wn(n,s,i,_):_&&Po(n,h)&&Jn(n,s,i,_),f&&h&&(n.finalTextSeen=!0);let w=Io(l,n.terminalProtocol);w&&!n.terminalOutcome&&(w.status==="failed"||n.finalTextSeen||n.artifacts.size>0)&&(n.terminalOutcome=w,n.emitTerminal?.(w))}catch{i({sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a}
15
15
  `}}})}}}hostControl(t,r){if(r.type==="control_cancel_request")return t.pending.get(r.request_id)?.abort(),!0;if(r.type==="result"&&t.stdin.end(),r.type!=="control_request")return!1;let n=new AbortController;return t.pending.set(r.request_id,n),t.respond(r.request,(s,i)=>this.requestApproval(s,i),n.signal).catch(s=>({subtype:"error",error:String(s?.message||s)})).then(s=>{t.pending.delete(r.request_id),!(n.signal.aborted||!t.stdin.writable)&&t.stdin.write(`${JSON.stringify({type:"control_response",response:{...s,request_id:r.request_id}})}
16
- `)}),!0}async sessionCancel(t){let r=u(t.sessionId),n=this.active.get(r);return n?(_("info","runtime.cli","cancelling runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid}),nt(n),{ok:!0,cancelled:!0}):{ok:!0,cancelled:!1}}async stop(t="stop"){for(let[r,n]of this.active.entries())_("info","runtime.cli","stopping runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid,reason:t}),nt(n);this.active.clear(),await this.taskMcp?.close(),this.taskMcp=null}};var re=e=>Object.assign(new Error(e),{code:"RUNTIME_MODEL_DISCOVERY_FAILED"});async function Zn(e,t,r,n=3e4){let s=ra(e.command,t,{cwd:K(e,e.workspace),env:{...process.env,...e.env},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});s.stderr.resume();let i;try{return await Promise.race([r(s),new Promise((o,a)=>{i=setTimeout(()=>a(re("Native model discovery timed out")),n),s.once("error",a),s.once("exit",()=>a(re("Native process exited before returning its model catalog")))})])}finally{clearTimeout(i),nt(s)}}async function ne(e){return e.terminalProtocol==="codex"?Zn(e,e.args,async t=>{let r=Gt(t);return await r.request("initialize",{clientInfo:{name:"orcha_runtime_bridge",version:B},capabilities:null}),r.notify("initialized"),Je(r,e.workspace)}):e.terminalProtocol==="claude"?Zn(e,["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--no-session-persistence","--permission-prompt-tool","stdio"],t=>new Promise((r,n)=>{let s=sa();na({input:t.stdout}).on("line",i=>{let o;try{o=JSON.parse(i)}catch{return}if(o.type!=="control_response"||o.response?.request_id!==s)return;let a=o.response.response;if(o.response.subtype==="error"||!Array.isArray(a?.models)){n(re("Claude Code did not return its model catalog; update the native CLI"));return}r({supported:!0,models:a.models.map(c=>({id:c.value,name:c.displayName,efforts:c.supportsEffort===!0?c.supportedEffortLevels||[]:[],isDefault:c.value==="default"})),defaultModel:a.models.find(c=>c.value==="default")?.value||null})}),t.stdin.write(`${JSON.stringify({type:"control_request",request_id:s,request:{subtype:"initialize"}})}
17
- `)})):{supported:!1,models:[]}}async function Je(e,t){let r=(await e.request("config/read",{cwd:t})).config,n=[],s;do{let i=await e.request("model/list",{limit:100,...s?{cursor:s}:{}});for(let o of i.data||[])n.push({id:o.model,name:o.displayName,efforts:(o.supportedReasoningEfforts||[]).map(a=>a.reasoningEffort),defaultEffort:o.defaultReasoningEffort||null,isDefault:o.isDefault===!0});s=i.nextCursor}while(s&&n.length<1e3);if(s)throw re("Codex returned an invalid model catalog");return{supported:!0,models:n,defaultModel:r.model||n.find(i=>i.isDefault)?.id||null,defaultEffort:r.model_reasoning_effort||null}}var Xe={terminalProtocol:"claude",args:["-p","--output-format","stream-json","--verbose","--include-partial-messages"],promptMode:"stdin",outputMode:"json-lines"},rs={terminalProtocol:"codex",args:["app-server"]},da=[{protocol:"claude",promptMode:"args",args:JSON.stringify(["-p","--output-format","json","--no-session-persistence"]),launch:Xe},{protocol:"claude",promptMode:"stdin",args:JSON.stringify(["-p","--output-format","stream-json","--verbose"]),launch:Xe},{protocol:"codex",promptMode:"stdin",args:JSON.stringify(["exec","--skip-git-repo-check","--json"]),launch:rs}];async function We(e,t){let r=`${e}.${process.pid}.tmp`;await aa(r,JSON.stringify(t),{mode:384}),await ca(r,e)}function Qe(e){let t=new URL(e);if(t.username||t.password||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("\u8FDE\u63A5\u5730\u5740\u5FC5\u987B\u4F7F\u7528 HTTPS\uFF1B\u4EC5\u672C\u673A\u5F00\u53D1\u5141\u8BB8 HTTP");let r=ts(ua(),".orcha","devices"),n=ts(r,es("sha256").update(t.toString()).digest("hex").slice(0,20));return{address:t,root:r,profile:`${n}.json`,pidFile:`${n}.pid`,logFile:`${n}.log`}}async function se(e,{url:t,pairCode:r}){let{address:n,root:s,profile:i}=Qe(t||e.orchaUrl);await ia(s,{recursive:!0,mode:448});let o;if(r){let a=await fetch(new URL("api/agent-devices/pairings/exchange",`${n.toString().replace(/\/+$/,"")}/`),{method:"POST",redirect:"error",headers:{"content-type":"application/json"},signal:AbortSignal.timeout(15e3),body:JSON.stringify({code:r,name:la()})}),c=await a.json();if(!a.ok||!c.success)throw new Error(c.message||c.detail||"\u8BBE\u5907\u8FDE\u63A5\u5931\u8D25");o={...c.data,targets:{}},await We(i,o)}else{try{o=JSON.parse(await oa(i,"utf8"))}catch{throw new Error("\u6CA1\u6709\u5DF2\u8FDE\u63A5\u8BBE\u5907\uFF0C\u8BF7\u4ECE\u667A\u80FD\u4F53\u9875\u9762\u751F\u6210\u8FDE\u63A5\u7801")}let a=!1;for(let[c,l]of Object.entries(o.targets||{})){let p=da.find(E=>E.protocol===l.terminalProtocol&&E.promptMode===l.promptMode&&E.args===JSON.stringify(l.args));if(!p)continue;let{terminalProtocol:m,args:f,promptMode:h,outputMode:g,captureLastMessage:w,...I}=l;o.targets[c]={...I,...structuredClone(p.launch)},a=!0}a&&await We(i,o)}e.orchaUrl=n.toString().replace(/\/+$/,""),e.mode="node",e.nodeId=o.nodeCode,e.nodeName=o.nodeName,e.nodeToken=o.token,e.targets=o.targets,e.defaultTargetCode="",e.deviceConnection=new Ye(e,o,async()=>We(i,o))}var Ye=class{constructor(t,r,n,s=Qr,i=ne){this.config=t,this.profile=r,this.persist=n,this.discover=s,this.models=i}async candidates(){return{candidates:(await this.discover()).map(({command:r,localAgentId:n,...s})=>s)}}async configure(t,r){if(!Array.isArray(t.selections)||!t.selections.length||t.selections.length>32)throw new Error("\u6DFB\u52A0\u9879\u65E0\u6548");let n=new Map((await this.discover()).map(c=>[c.id,c])),s={...r.targets},i=[],o=new Set;for(let c of t.selections){let l=n.get(c.candidateId);if(!l||l.status!=="ready"||o.has(l.id))throw new Error("\u53D1\u73B0\u7ED3\u679C\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u6D4B");o.add(l.id);let p=String(c.name||"").trim();if(!p||p.length>128)throw new Error("\u667A\u80FD\u4F53\u540D\u79F0\u65E0\u6548");let m=await Ae(String(c.workspace||""));if(l.managed&&m!==await Ae(l.workspace))throw new Error("\u5DF2\u6709\u667A\u80FD\u4F53\u5FC5\u987B\u6CBF\u7528\u672C\u673A\u5DE5\u4F5C\u76EE\u5F55");let f=`${this.config.nodeId}:${es("sha256").update(l.id).digest("hex").slice(0,20)}`;if([...r.sessions.values()].some(h=>h.targetCode===f))throw new Error("\u6B64\u667A\u80FD\u4F53\u4ECD\u6709\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u7ED3\u675F\u4F1A\u8BDD\u518D\u4FEE\u6539\u63A5\u5165");s[f]={name:p,workspace:m,command:l.command,type:l.managed?"openclaw":"cli",...l.managed?{openclawAgentId:l.localAgentId}:structuredClone(l.framework==="codex"?rs:Xe)},i.push({candidateId:l.id,name:p,workspace:m,targetCode:f,framework:l.framework,modelCatalog:await this.models(s[f])})}let a=this.profile.targets;this.profile.targets=s;try{await this.persist()}catch(c){throw this.profile.targets=a,c}return r.targets=s,this.config.targets=s,r.notifyCapacityChanged(),{agents:i}}};import{execFile as pa}from"node:child_process";import{constants as fa}from"node:fs";import{access as is,readFile as os,realpath as ma}from"node:fs/promises";import{join as Ze}from"node:path";import{promisify as ha}from"node:util";var pt="application/x-orcha-channel-events-v2+ndjson";function D(e,t){return Object.assign(new Error(t||(["run_timeout","RUNTIME_NODE_TIMEOUT"].includes(e)?"OpenClaw \u539F\u751F IM \u6267\u884C\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002":e==="OPENCLAW_CHANNEL_PROTOCOL_MISMATCH"?"OpenClaw \u63D2\u4EF6\u4E0E Bridge \u7684\u539F\u751F IM \u534F\u8BAE\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u914D\u5957\u5347\u7EA7\u3002":`OpenClaw \u539F\u751F IM \u6267\u884C\u5931\u8D25\uFF08${e}\uFF09`)),{code:e})}function ns(e,t){let r=e.cause?.code||e.code;return t?.reason?.name==="TimeoutError"||e.name==="TimeoutError"||["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","ETIMEDOUT"].includes(r)?Object.assign(D("RUNTIME_NODE_TIMEOUT","OpenClaw \u8FDE\u63A5\u6216\u7B49\u5F85\u54CD\u5E94\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002"),{detail:{causeCode:r||"REQUEST_TIMEOUT"}}):e}async function ss(e,t){if(e.headers.get("content-type")!==pt)throw await e.body?.cancel(),D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH");let r=Buffer.alloc(0);for await(let n of e.body){r=Buffer.concat([r,n]);let s;for(;(s=r.indexOf(10))>=0;){if(s>2097152)throw D("OPENCLAW_CHANNEL_FRAME_TOO_LARGE");let i=r.subarray(0,s).toString("utf8");r=r.subarray(s+1);let o;try{o=JSON.parse(i)}catch{throw D("OPENCLAW_CHANNEL_INVALID_FRAME")}if(o.type!=="heartbeat")if(o.type==="update"&&o.payload?.update&&o.payload?._meta?.channelUpdateId)await t(o.payload);else{if(o.type==="result"&&o.result?.stopReason)return o.result;throw o.type==="error"&&typeof o.code=="string"?D(o.code):D("OPENCLAW_CHANNEL_INVALID_FRAME")}}if(r.length>2097152)throw D("OPENCLAW_CHANNEL_FRAME_TOO_LARGE")}throw D("OPENCLAW_CHANNEL_STREAM_INTERRUPTED","OpenClaw \u8FC7\u7A0B\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u4EFB\u52A1\u7EC8\u6001\uFF0C\u8BF7\u68C0\u67E5\u8282\u70B9\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}var st=class{constructor(t,r){this.target=t,this.identity=r,this.bound=!1}async request(t,r,n=!1,s="mcp-bindings",i=3e4,o=null){let a=u(this.target.mcpBridgeUrl),c=u(this.target.mcpBridgeTokenEnv),l=this.target.env?.[c]||process.env[c];if(!a||!c||!l)throw Object.assign(new Error("OpenClaw requires the Orcha tool plugin, mcpBridgeUrl and mcpBridgeTokenEnv"),{code:"OPENCLAW_MCP_NOT_CONFIGURED"});let p=new URL(a);if(!["http:","https:"].includes(p.protocol)||p.username||p.password||p.pathname!=="/plugins/orcha-runtime/mcp-bindings"||p.search||p.hash)throw new Error("OpenClaw MCP binding URL must be the trusted Gateway plugin route");if(!["mcp-bindings","deliveries","background"].includes(s))throw new Error("Unsupported Orcha plugin route");p.pathname=`/plugins/orcha-runtime/${s}`;let m=AbortSignal.timeout(i);try{let f=await fetch(p,{method:t,redirect:"error",signal:m,headers:{authorization:`Bearer ${l}`,"content-type":"application/json",...o?{accept:pt}:{},...n?{"if-match":this.identity.runId}:{}},...r!==void 0?{body:JSON.stringify(r)}:{}});if(t==="GET"&&s==="deliveries"&&[404,405].includes(f.status))throw await f.body?.cancel(),D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH");if(f.ok&&o)return await ss(f,o);let h=await f.json();if(!f.ok)throw D(h.error||"OPENCLAW_MCP_BINDING_FAILED");return h}catch(f){throw ns(f,m)}}async bind(t,r=!1){Jt(t),await this.request("PUT",{...this.identity,mcpServer:t[0]},r),this.bound=!0}async close(){this.bound&&(await this.request("DELETE",{runId:this.identity.runId,sessionKey:this.identity.sessionKey}),this.bound=!1)}};var ga=ha(pa),_a=12e4;async function as(e,t){let r=new Map,n=[];for(let s of Object.values(e)){if(s.type!=="openclaw")continue;if(s.mcpBridgeUrl&&(n.push(s),!["localhost","127.0.0.1","[::1]"].includes(new URL(s.mcpBridgeUrl).hostname))){process.stderr.write(`\u8FDC\u7A0B OpenClaw Gateway \u7684\u914D\u5957\u63D2\u4EF6\u9700\u5728\u6240\u5728\u4E3B\u673A\u66F4\u65B0\uFF1Breload \u5C06\u68C0\u67E5\u5176\u534F\u8BAE\u3002
16
+ `)}),!0}async sessionCancel(t){let r=u(t.sessionId),n=this.active.get(r);return n?(g("info","runtime.cli","cancelling runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid}),nt(n),{ok:!0,cancelled:!0}):{ok:!0,cancelled:!1}}async stop(t="stop"){for(let[r,n]of this.active.entries())g("info","runtime.cli","stopping runtime child",{target:this.agent.targetCode,sessionId:r,pid:n.pid,reason:t}),nt(n);this.active.clear(),await this.taskMcp?.close(),this.taskMcp=null}};var re=e=>Object.assign(new Error(e),{code:"RUNTIME_MODEL_DISCOVERY_FAILED"});async function Zn(e,t,r,n=3e4){let s=ra(e.command,t,{cwd:K(e,e.workspace),env:{...process.env,...e.env},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});s.stderr.resume();let i;try{return await Promise.race([r(s),new Promise((o,a)=>{i=setTimeout(()=>a(re("Native model discovery timed out")),n),s.once("error",a),s.once("exit",()=>a(re("Native process exited before returning its model catalog")))})])}finally{clearTimeout(i),nt(s)}}async function ne(e){return e.terminalProtocol==="codex"?Zn(e,e.args,async t=>{let r=Gt(t);return await r.request("initialize",{clientInfo:{name:"orcha_runtime_bridge",version:B},capabilities:null}),r.notify("initialized"),Je(r,e.workspace)}):e.terminalProtocol==="claude"?Zn(e,["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--no-session-persistence","--permission-prompt-tool","stdio"],t=>new Promise((r,n)=>{let s=sa();na({input:t.stdout}).on("line",i=>{let o;try{o=JSON.parse(i)}catch{return}if(o.type!=="control_response"||o.response?.request_id!==s)return;let a=o.response.response;if(o.response.subtype==="error"||!Array.isArray(a?.models)){n(re("Claude Code did not return its model catalog; update the native CLI"));return}r({supported:!0,models:a.models.map(c=>({id:c.value,name:c.displayName,efforts:c.supportsEffort===!0?c.supportedEffortLevels||[]:[],isDefault:c.value==="default"})),defaultModel:a.models.find(c=>c.value==="default")?.value||null})}),t.stdin.write(`${JSON.stringify({type:"control_request",request_id:s,request:{subtype:"initialize"}})}
17
+ `)})):{supported:!1,models:[]}}async function Je(e,t){let r=(await e.request("config/read",{cwd:t})).config,n=[],s;do{let i=await e.request("model/list",{limit:100,...s?{cursor:s}:{}});for(let o of i.data||[])n.push({id:o.model,name:o.displayName,efforts:(o.supportedReasoningEfforts||[]).map(a=>a.reasoningEffort),defaultEffort:o.defaultReasoningEffort||null,isDefault:o.isDefault===!0});s=i.nextCursor}while(s&&n.length<1e3);if(s)throw re("Codex returned an invalid model catalog");return{supported:!0,models:n,defaultModel:r.model||n.find(i=>i.isDefault)?.id||null,defaultEffort:r.model_reasoning_effort||null}}var Xe={terminalProtocol:"claude",args:["-p","--output-format","stream-json","--verbose","--include-partial-messages"],promptMode:"stdin",outputMode:"json-lines"},rs={terminalProtocol:"codex",args:["app-server"]},da=[{protocol:"claude",promptMode:"args",args:JSON.stringify(["-p","--output-format","json","--no-session-persistence"]),launch:Xe},{protocol:"claude",promptMode:"stdin",args:JSON.stringify(["-p","--output-format","stream-json","--verbose"]),launch:Xe},{protocol:"codex",promptMode:"stdin",args:JSON.stringify(["exec","--skip-git-repo-check","--json"]),launch:rs}];async function We(e,t){let r=`${e}.${process.pid}.tmp`;await aa(r,JSON.stringify(t),{mode:384}),await ca(r,e)}function Qe(e){let t=new URL(e);if(t.username||t.password||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new Error("\u8FDE\u63A5\u5730\u5740\u5FC5\u987B\u4F7F\u7528 HTTPS\uFF1B\u4EC5\u672C\u673A\u5F00\u53D1\u5141\u8BB8 HTTP");let r=ts(ua(),".orcha","devices"),n=ts(r,es("sha256").update(t.toString()).digest("hex").slice(0,20));return{address:t,root:r,profile:`${n}.json`,pidFile:`${n}.pid`,logFile:`${n}.log`}}async function se(e,{url:t,pairCode:r}){let{address:n,root:s,profile:i}=Qe(t||e.orchaUrl);await ia(s,{recursive:!0,mode:448});let o;if(r){let a=await fetch(new URL("api/agent-devices/pairings/exchange",`${n.toString().replace(/\/+$/,"")}/`),{method:"POST",redirect:"error",headers:{"content-type":"application/json"},signal:AbortSignal.timeout(15e3),body:JSON.stringify({code:r,name:la()})}),c=await a.json();if(!a.ok||!c.success)throw new Error(c.message||c.detail||"\u8BBE\u5907\u8FDE\u63A5\u5931\u8D25");o={...c.data,targets:{}},await We(i,o)}else{try{o=JSON.parse(await oa(i,"utf8"))}catch{throw new Error("\u6CA1\u6709\u5DF2\u8FDE\u63A5\u8BBE\u5907\uFF0C\u8BF7\u4ECE\u667A\u80FD\u4F53\u9875\u9762\u751F\u6210\u8FDE\u63A5\u7801")}let a=!1;for(let[c,l]of Object.entries(o.targets||{})){let p=da.find(E=>E.protocol===l.terminalProtocol&&E.promptMode===l.promptMode&&E.args===JSON.stringify(l.args));if(!p)continue;let{terminalProtocol:m,args:f,promptMode:h,outputMode:_,captureLastMessage:w,...I}=l;o.targets[c]={...I,...structuredClone(p.launch)},a=!0}a&&await We(i,o)}e.orchaUrl=n.toString().replace(/\/+$/,""),e.mode="node",e.nodeId=o.nodeCode,e.nodeName=o.nodeName,e.nodeToken=o.token,e.targets=o.targets,e.defaultTargetCode="",e.deviceConnection=new Ye(e,o,async()=>We(i,o))}var Ye=class{constructor(t,r,n,s=Qr,i=ne){this.config=t,this.profile=r,this.persist=n,this.discover=s,this.models=i}async candidates(){return{candidates:(await this.discover()).map(({command:r,localAgentId:n,...s})=>s)}}async configure(t,r){if(!Array.isArray(t.selections)||!t.selections.length||t.selections.length>32)throw new Error("\u6DFB\u52A0\u9879\u65E0\u6548");let n=new Map((await this.discover()).map(c=>[c.id,c])),s={...r.targets},i=[],o=new Set;for(let c of t.selections){let l=n.get(c.candidateId);if(!l||l.status!=="ready"||o.has(l.id))throw new Error("\u53D1\u73B0\u7ED3\u679C\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u6D4B");o.add(l.id);let p=String(c.name||"").trim();if(!p||p.length>128)throw new Error("\u667A\u80FD\u4F53\u540D\u79F0\u65E0\u6548");let m=await Ae(String(c.workspace||""));if(l.managed&&m!==await Ae(l.workspace))throw new Error("\u5DF2\u6709\u667A\u80FD\u4F53\u5FC5\u987B\u6CBF\u7528\u672C\u673A\u5DE5\u4F5C\u76EE\u5F55");let f=`${this.config.nodeId}:${es("sha256").update(l.id).digest("hex").slice(0,20)}`;if([...r.sessions.values()].some(h=>h.targetCode===f))throw new Error("\u6B64\u667A\u80FD\u4F53\u4ECD\u6709\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u7ED3\u675F\u4F1A\u8BDD\u518D\u4FEE\u6539\u63A5\u5165");s[f]={name:p,workspace:m,command:l.command,type:l.managed?"openclaw":"cli",...l.managed?{openclawAgentId:l.localAgentId}:structuredClone(l.framework==="codex"?rs:Xe)},i.push({candidateId:l.id,name:p,workspace:m,targetCode:f,framework:l.framework,modelCatalog:await this.models(s[f])})}let a=this.profile.targets;this.profile.targets=s;try{await this.persist()}catch(c){throw this.profile.targets=a,c}return r.targets=s,this.config.targets=s,r.notifyCapacityChanged(),{agents:i}}};import{execFile as pa}from"node:child_process";import{constants as fa}from"node:fs";import{access as is,readFile as os,realpath as ma}from"node:fs/promises";import{join as Ze}from"node:path";import{promisify as ha}from"node:util";var pt="application/x-orcha-channel-events-v2+ndjson";function D(e,t){return Object.assign(new Error(t||(["run_timeout","RUNTIME_NODE_TIMEOUT"].includes(e)?"OpenClaw \u539F\u751F IM \u6267\u884C\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002":e==="OPENCLAW_CHANNEL_PROTOCOL_MISMATCH"?"OpenClaw \u63D2\u4EF6\u4E0E Bridge \u7684\u539F\u751F IM \u534F\u8BAE\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u914D\u5957\u5347\u7EA7\u3002":`OpenClaw \u539F\u751F IM \u6267\u884C\u5931\u8D25\uFF08${e}\uFF09`)),{code:e})}function ns(e,t){let r=e.cause?.code||e.code;return t?.reason?.name==="TimeoutError"||e.name==="TimeoutError"||["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","ETIMEDOUT"].includes(r)?Object.assign(D("RUNTIME_NODE_TIMEOUT","OpenClaw \u8FDE\u63A5\u6216\u7B49\u5F85\u54CD\u5E94\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002"),{detail:{causeCode:r||"REQUEST_TIMEOUT"}}):e}async function ss(e,t){if(e.headers.get("content-type")!==pt)throw await e.body?.cancel(),D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH");let r=Buffer.alloc(0);for await(let n of e.body){r=Buffer.concat([r,n]);let s;for(;(s=r.indexOf(10))>=0;){if(s>2097152)throw D("OPENCLAW_CHANNEL_FRAME_TOO_LARGE");let i=r.subarray(0,s).toString("utf8");r=r.subarray(s+1);let o;try{o=JSON.parse(i)}catch{throw D("OPENCLAW_CHANNEL_INVALID_FRAME")}if(o.type!=="heartbeat")if(o.type==="update"&&o.payload?.update&&o.payload?._meta?.channelUpdateId)await t(o.payload);else{if(o.type==="result"&&o.result?.stopReason)return o.result;throw o.type==="error"&&typeof o.code=="string"?D(o.code):D("OPENCLAW_CHANNEL_INVALID_FRAME")}}if(r.length>2097152)throw D("OPENCLAW_CHANNEL_FRAME_TOO_LARGE")}throw D("OPENCLAW_CHANNEL_STREAM_INTERRUPTED","OpenClaw \u8FC7\u7A0B\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u4EFB\u52A1\u7EC8\u6001\uFF0C\u8BF7\u68C0\u67E5\u8282\u70B9\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}var st=class{constructor(t,r){this.target=t,this.identity=r,this.bound=!1}async request(t,r,n=!1,s="mcp-bindings",i=3e4,o=null){let a=u(this.target.mcpBridgeUrl),c=u(this.target.mcpBridgeTokenEnv),l=this.target.env?.[c]||process.env[c];if(!a||!c||!l)throw Object.assign(new Error("OpenClaw requires the Orcha tool plugin, mcpBridgeUrl and mcpBridgeTokenEnv"),{code:"OPENCLAW_MCP_NOT_CONFIGURED"});let p=new URL(a);if(!["http:","https:"].includes(p.protocol)||p.username||p.password||p.pathname!=="/plugins/orcha-runtime/mcp-bindings"||p.search||p.hash)throw new Error("OpenClaw MCP binding URL must be the trusted Gateway plugin route");if(!["mcp-bindings","deliveries","background"].includes(s))throw new Error("Unsupported Orcha plugin route");p.pathname=`/plugins/orcha-runtime/${s}`;let m=AbortSignal.timeout(i);try{let f=await fetch(p,{method:t,redirect:"error",signal:m,headers:{authorization:`Bearer ${l}`,"content-type":"application/json",...o?{accept:pt}:{},...n?{"if-match":this.identity.runId}:{}},...r!==void 0?{body:JSON.stringify(r)}:{}});if(t==="GET"&&s==="deliveries"&&[404,405].includes(f.status))throw await f.body?.cancel(),D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH");if(f.ok&&o)return await ss(f,o);let h=await f.json();if(!f.ok)throw D(h.error||"OPENCLAW_MCP_BINDING_FAILED");return h}catch(f){throw ns(f,m)}}async bind(t,r=!1){Jt(t),await this.request("PUT",{...this.identity,mcpServer:t[0]},r),this.bound=!0}async close(){this.bound&&(await this.request("DELETE",{runId:this.identity.runId,sessionKey:this.identity.sessionKey}),this.bound=!1)}};var ga=ha(pa),_a=12e4;async function as(e,t){let r=new Map,n=[];for(let s of Object.values(e)){if(s.type!=="openclaw")continue;if(s.mcpBridgeUrl&&(n.push(s),!["localhost","127.0.0.1","[::1]"].includes(new URL(s.mcpBridgeUrl).hostname))){process.stderr.write(`\u8FDC\u7A0B OpenClaw Gateway \u7684\u914D\u5957\u63D2\u4EF6\u9700\u5728\u6240\u5728\u4E3B\u673A\u66F4\u65B0\uFF1Breload \u5C06\u68C0\u67E5\u5176\u534F\u8BAE\u3002
18
18
  `);continue}let i={...process.env,...s.env},o=u(s.command)||"openclaw",a=o.includes("/")?o:await xe(o,i);if(!a)throw new Error("\u627E\u4E0D\u5230\u5DF2\u63A5\u5165\u7684 OpenClaw\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u5B89\u88C5\u540E\u91CD\u8BD5 reload");let c=await ma(a);await is(c,fa.X_OK);let l=JSON.stringify([c,Object.entries(i).sort(([p],[m])=>p.localeCompare(m))]);r.has(l)||r.set(l,{command:c,env:i})}if(r.size)try{let s=JSON.parse(await os(Ze(t,"openclaw.plugin.json"),"utf8")),i=JSON.parse(await os(Ze(t,"package.json"),"utf8"));if(await is(Ze(t,"index.js")),s.id!=="orcha-runtime"||i.version!==B)throw new Error("\u63D2\u4EF6\u6807\u8BC6\u6216\u7248\u672C\u4E0D\u5339\u914D")}catch(s){throw new Error("\u914D\u5957 OpenClaw \u63D2\u4EF6\u7F3A\u5931\u3001\u635F\u574F\u6216\u7248\u672C\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5 Bridge\uFF1B\u6E90\u7801\u8FD0\u884C\u8BF7\u5148 npm run build",{cause:s})}return async()=>{for(let s of r.values()){process.stderr.write(`\u6B63\u5728\u5B89\u88C5\u914D\u5957 OpenClaw \u63D2\u4EF6\u5E76\u91CD\u542F Gateway\u2026
19
19
  `),await tr(s,["plugins","install",t,"--force"]),await tr(s,["gateway","restart"]);let i=await tr(s,["health","--json"]);if(JSON.parse(i).ok!==!0)throw new Error("OpenClaw Gateway \u5065\u5EB7\u68C0\u67E5\u5931\u8D25\uFF0CBridge \u672A\u542F\u52A8\uFF0C\u8BF7\u4FEE\u590D\u540E\u91CD\u8BD5 reload");process.stderr.write(`OpenClaw \u914D\u5957\u63D2\u4EF6\u5DF2\u66F4\u65B0\uFF0CGateway \u5065\u5EB7\u68C0\u67E5\u901A\u8FC7\u3002
20
- `)}for(let s of n)if((await new st(s,{}).request("GET",void 0,!1,"deliveries")).streamType!==pt)throw D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH")}}async function tr(e,t){try{let{stdout:r}=await ga(e.command,t,{env:e.env,timeout:_a,killSignal:"SIGKILL",maxBuffer:1048576,windowsHide:!0});return r}catch(r){let n=Object.entries(e.env).filter(([i])=>rt(i)).map(([,i])=>i),s=ct(r.stderr||r.message,n).trim();throw new Error(`OpenClaw ${t.slice(0,2).join(" ")} \u5931\u8D25\uFF0CBridge \u672A\u542F\u52A8\uFF0C\u8BF7\u4FEE\u590D\u540E\u91CD\u8BD5 reload\uFF1A${s}`)}}import{createHash as _c,randomUUID as _e}from"node:crypto";var ie=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=yt(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 ya}from"node:child_process";var vt="2.0",er=3e4,wa=4e3;function oe(e,t){let r=Object.entries(d(t)?t:{}).filter(([n])=>rt(n)).map(([,n])=>n);return ct(e,r)}function Ta(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:u(e?.message)||String(e),data:d(e?.data)?e.data:void 0}}function Ea(e){if(!d(e))return new Error(String(e||"runtime error"));let t=u(e.message)||"runtime error",r="data"in e?tn(e.data,4e3):"",n=new Error(r?`${t}; data=${r}`:t);return n.rpcCode=e.code,n.data=e.data,n}function Oa(e){return d(e)&&"id"in e&&!("method"in e)}function Sa(e){return d(e)&&typeof e.method=="string"&&"id"in e}function Ra(e){return d(e)&&typeof e.method=="string"&&!("id"in e)}var ae=class{constructor({command:t,args:r=[],cwd:n,env:s,label:i,framing:o="line",detached:a=!0}){this.command=t,this.args=Array.isArray(r)?r.map(String):[],this.cwd=n||process.cwd(),this.env=d(s)?{...s}:{...process.env},this.label=i||t,this.framing=o==="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.stderrTail="",this.spawnError=null,this.lineBuffer="",this.headerBuffer=Buffer.alloc(0),this.seq=0,this.pending=new Map,this.notificationHandlers=new Map,this.requestHandlers=new Map,this.exitHandlers=new Set}async start({initialize:t=!0,initializeParams:r={},initializeTimeoutMs:n=er}={}){if(!(this.child&&!this.exited)&&(this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stderrTail="",this.spawnError=null,this.child=ya(this.command,this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"],detached:this.detached}),this.child.stdout.on("data",s=>this.onStdout(s)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",s=>{this.stderrTail=`${this.stderrTail}${s}`.slice(-wa);let i=oe(s.trimEnd(),this.env);i&&_("debug","runtime.stderr","runtime stderr",{target:this.label,text:i})}),this.child.on("exit",(s,i)=>this.handleExit(s,i)),this.child.on("error",s=>{this.spawnError=s,this.rejectAll(s)}),t)){let s=Math.max(1,R(n,er));try{await this.call("initialize",{protocolVersion:1,clientCapabilities:{},...r},s)}catch(i){let o=this.startupFailureDetail(),a=oe(i?.message||i,this.env);_("warn","runtime.initialize","runtime initialize failed",{target:this.label,timeoutMs:s,cause:a,...o}),await this.stop("initialize failed",{termTimeoutMs:1e3,killTimeoutMs:1e3});let c=o.stderr?`; stderr: ${o.stderr}`:`; command=${o.command}; cwd=${o.cwd}`;throw Object.assign(new Error(`runtime initialize failed: ${a}${c}`,{cause:i}),{code:"RUNTIME_INITIALIZE_FAILED",detail:o})}}}startupFailureDetail(){return{command:this.command,cwd:this.cwd,exited:this.exited,exitCode:this.exitCode,exitSignal:this.exitSignal,...this.spawnError?{spawnError:oe(this.spawnError.message,this.env)}:{},...this.stderrTail.trim()?{stderr:oe(this.stderrTail.trim(),this.env)}:{}}}onStdout(t){if(this.framing==="content-length"){this.onContentLengthData(Buffer.isBuffer(t)?t:Buffer.from(t));return}this.onLineData(t.toString("utf8"))}onLineData(t){this.lineBuffer+=t;let r=this.lineBuffer.split(/\r?\n/);this.lineBuffer=r.pop()||"";for(let n of r){let s=n.trim();s&&this.dispatchRaw(s)}}onContentLengthData(t){for(this.headerBuffer=Buffer.concat([this.headerBuffer,t]);this.headerBuffer.length>0;){let r=this.headerBuffer.indexOf(`\r
20
+ `)}for(let s of n)if((await new st(s,{}).request("GET",void 0,!1,"deliveries")).streamType!==pt)throw D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH")}}async function tr(e,t){try{let{stdout:r}=await ga(e.command,t,{env:e.env,timeout:_a,killSignal:"SIGKILL",maxBuffer:1048576,windowsHide:!0});return r}catch(r){let n=Object.entries(e.env).filter(([i])=>rt(i)).map(([,i])=>i),s=ct(r.stderr||r.message,n).trim();throw new Error(`OpenClaw ${t.slice(0,2).join(" ")} \u5931\u8D25\uFF0CBridge \u672A\u542F\u52A8\uFF0C\u8BF7\u4FEE\u590D\u540E\u91CD\u8BD5 reload\uFF1A${s}`)}}import{createHash as _c,randomUUID as _e}from"node:crypto";var ie=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=yt(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 ya}from"node:child_process";var vt="2.0",er=3e4,wa=4e3;function oe(e,t){let r=Object.entries(d(t)?t:{}).filter(([n])=>rt(n)).map(([,n])=>n);return ct(e,r)}function Ta(e){return{code:Number.isInteger(e?.code)?e.code:-32e3,message:u(e?.message)||String(e),data:d(e?.data)?e.data:void 0}}function Ea(e){if(!d(e))return new Error(String(e||"runtime error"));let t=u(e.message)||"runtime error",r="data"in e?tn(e.data,4e3):"",n=new Error(r?`${t}; data=${r}`:t);return n.rpcCode=e.code,n.data=e.data,n}function Oa(e){return d(e)&&"id"in e&&!("method"in e)}function Sa(e){return d(e)&&typeof e.method=="string"&&"id"in e}function Ra(e){return d(e)&&typeof e.method=="string"&&!("id"in e)}var ae=class{constructor({command:t,args:r=[],cwd:n,env:s,label:i,framing:o="line",detached:a=!0}){this.command=t,this.args=Array.isArray(r)?r.map(String):[],this.cwd=n||process.cwd(),this.env=d(s)?{...s}:{...process.env},this.label=i||t,this.framing=o==="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.stderrTail="",this.spawnError=null,this.lineBuffer="",this.headerBuffer=Buffer.alloc(0),this.seq=0,this.pending=new Map,this.notificationHandlers=new Map,this.requestHandlers=new Map,this.exitHandlers=new Set}async start({initialize:t=!0,initializeParams:r={},initializeTimeoutMs:n=er}={}){if(!(this.child&&!this.exited)&&(this.exited=!1,this.exitCode=null,this.exitSignal=null,this.stderrTail="",this.spawnError=null,this.child=ya(this.command,this.args,{cwd:this.cwd,env:this.env,stdio:["pipe","pipe","pipe"],detached:this.detached}),this.child.stdout.on("data",s=>this.onStdout(s)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",s=>{this.stderrTail=`${this.stderrTail}${s}`.slice(-wa);let i=oe(s.trimEnd(),this.env);i&&g("debug","runtime.stderr","runtime stderr",{target:this.label,text:i})}),this.child.on("exit",(s,i)=>this.handleExit(s,i)),this.child.on("error",s=>{this.spawnError=s,this.rejectAll(s)}),t)){let s=Math.max(1,R(n,er));try{await this.call("initialize",{protocolVersion:1,clientCapabilities:{},...r},s)}catch(i){let o=this.startupFailureDetail(),a=oe(i?.message||i,this.env);g("warn","runtime.initialize","runtime initialize failed",{target:this.label,timeoutMs:s,cause:a,...o}),await this.stop("initialize failed",{termTimeoutMs:1e3,killTimeoutMs:1e3});let c=o.stderr?`; stderr: ${o.stderr}`:`; command=${o.command}; cwd=${o.cwd}`;throw Object.assign(new Error(`runtime initialize failed: ${a}${c}`,{cause:i}),{code:"RUNTIME_INITIALIZE_FAILED",detail:o})}}}startupFailureDetail(){return{command:this.command,cwd:this.cwd,exited:this.exited,exitCode:this.exitCode,exitSignal:this.exitSignal,...this.spawnError?{spawnError:oe(this.spawnError.message,this.env)}:{},...this.stderrTail.trim()?{stderr:oe(this.stderrTail.trim(),this.env)}:{}}}onStdout(t){if(this.framing==="content-length"){this.onContentLengthData(Buffer.isBuffer(t)?t:Buffer.from(t));return}this.onLineData(t.toString("utf8"))}onLineData(t){this.lineBuffer+=t;let r=this.lineBuffer.split(/\r?\n/);this.lineBuffer=r.pop()||"";for(let n of r){let s=n.trim();s&&this.dispatchRaw(s)}}onContentLengthData(t){for(this.headerBuffer=Buffer.concat([this.headerBuffer,t]);this.headerBuffer.length>0;){let r=this.headerBuffer.indexOf(`\r
21
21
  \r
22
- `);if(r<0)return;let s=this.headerBuffer.subarray(0,r).toString("utf8").match(/content-length:\s*(\d+)/i);if(!s){_("warn","runtime.protocol","missing Content-Length header",{target:this.label}),this.headerBuffer=Buffer.alloc(0);return}let i=Number.parseInt(s[1],10),o=r+4,a=o+i;if(this.headerBuffer.length<a)return;let c=this.headerBuffer.subarray(o,a).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(a),this.dispatchRaw(c)}}dispatchRaw(t){let r;try{r=JSON.parse(t)}catch(n){_("warn","runtime.protocol","invalid JSON frame",{target:this.label,error:String(n)});return}this.dispatch(r)}dispatch(t){if(Oa(t)){this.resolveResponse(t);return}if(Sa(t)){this.handleRequest(t);return}Ra(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?(_("warn","runtime.protocol","runtime rpc error",{target:this.label,method:n.method,requestId:r,error:t.error}),n.reject(Ea(t.error))):n.resolve(t.result))}async handleRequest(t){let r=this.requestHandlers.get(t.method);if(!r){this.writeFrame({jsonrpc:vt,id:t.id,error:{code:-32601,message:`method not found: ${t.method}`}});return}try{let n=await r(d(t.params)?t.params:{},t);this.writeFrame({jsonrpc:vt,id:t.id,result:n??{}})}catch(n){this.writeFrame({jsonrpc:vt,id:t.id,error:Ta(n)})}}handleNotification(t){let r=this.notificationHandlers.get(t.method);if(r)for(let n of r)n(d(t.params)?t.params:{},t)}call(t,r={},n=er){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:vt,id:s,method:t,params:r};return new Promise((o,a)=>{let c=setTimeout(()=>{this.pending.delete(s),a(new Error(`${t} timed out after ${n}ms`))},n);this.pending.set(s,{resolve:o,reject:a,timer:c,method:t}),this.writeFrame(i,l=>{l&&(clearTimeout(c),this.pending.delete(s),a(l))})})}notify(t,r={}){this.writeFrame({jsonrpc:vt,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
22
+ `);if(r<0)return;let s=this.headerBuffer.subarray(0,r).toString("utf8").match(/content-length:\s*(\d+)/i);if(!s){g("warn","runtime.protocol","missing Content-Length header",{target:this.label}),this.headerBuffer=Buffer.alloc(0);return}let i=Number.parseInt(s[1],10),o=r+4,a=o+i;if(this.headerBuffer.length<a)return;let c=this.headerBuffer.subarray(o,a).toString("utf8");this.headerBuffer=this.headerBuffer.subarray(a),this.dispatchRaw(c)}}dispatchRaw(t){let r;try{r=JSON.parse(t)}catch(n){g("warn","runtime.protocol","invalid JSON frame",{target:this.label,error:String(n)});return}this.dispatch(r)}dispatch(t){if(Oa(t)){this.resolveResponse(t);return}if(Sa(t)){this.handleRequest(t);return}Ra(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?(g("warn","runtime.protocol","runtime rpc error",{target:this.label,method:n.method,requestId:r,error:t.error}),n.reject(Ea(t.error))):n.resolve(t.result))}async handleRequest(t){let r=this.requestHandlers.get(t.method);if(!r){this.writeFrame({jsonrpc:vt,id:t.id,error:{code:-32601,message:`method not found: ${t.method}`}});return}try{let n=await r(d(t.params)?t.params:{},t);this.writeFrame({jsonrpc:vt,id:t.id,result:n??{}})}catch(n){this.writeFrame({jsonrpc:vt,id:t.id,error:Ta(n)})}}handleNotification(t){let r=this.notificationHandlers.get(t.method);if(r)for(let n of r)n(d(t.params)?t.params:{},t)}call(t,r={},n=er){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:vt,id:s,method:t,params:r};return new Promise((o,a)=>{let c=setTimeout(()=>{this.pending.delete(s),a(new Error(`${t} timed out after ${n}ms`))},n);this.pending.set(s,{resolve:o,reject:a,timer:c,method:t}),this.writeFrame(i,l=>{l&&(clearTimeout(c),this.pending.delete(s),a(l))})})}notify(t,r={}){this.writeFrame({jsonrpc:vt,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
23
23
  \r
24
24
  ${n}`:`${n}
25
- `;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"&&_("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;_("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&&(_("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}}}};function cs(e,t){let r=R(e,t);return r>0?r:t}var Et=class{constructor(t,r,n={},s={}){this.agent=t,this.target=r,this.callbacks=n,this.options=s,this.proc=null,this.launch=null,this.launchCleanup=null,this.permissionHandlers=new Map}async ensureStarted(){if(this.proc)return;let t=u(this.target.command);if(!t)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let r={command:t,args:k(this.target.args),cwd:K(this.target,this.agent.workspace),environment:d(this.target.env)?this.target.env:{}},n=this.options.prepareLaunch?await this.options.prepareLaunch(r):{...r,environment:{...process.env,...r.environment},cleanup:async()=>{}};this.launch=n,this.launchCleanup=n.cleanup,this.proc=new ae({command:n.command,args:n.args,cwd:n.cwd,env:n.environment,label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:u(this.target.framing||"line")}),this.proc.onRequest("session/request_permission",s=>this.handlePermissionRequest(s)),this.proc.onRequest("session/requestPermission",s=>this.handlePermissionRequest(s));try{await this.proc.start({initialize:this.target.initialize!==!1,initializeTimeoutMs:cs(this.target.initializeTimeoutMs,cs(this.options.initializeTimeoutMs,3e4)),initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:B},...d(this.target.initializeParams)?this.target.initializeParams:{}}})}catch(s){throw await this.proc?.stop("runtime startup failed"),this.proc=null,await this.cleanupLaunch(),s}}async sessionNew(t={}){return await this.ensureStarted(),this.proc.call("session/new",this.sessionNewParams(t))}sessionNewParams(t={}){let r=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return{...t,mcpServers:r}}async sessionPrompt(t,r){await this.ensureStarted();let n=u(t.sessionId),s=new Map,i=this.artifactOptions(),o=this.proc.onNotification("session/update",c=>{let l=u(c.sessionId);(!l||l===n)&&r(dn(c,s,i))}),a=async c=>this.callbacks.onPermissionRequest?.({agent:this.agent,runtimeSessionId:n,request:c,emitUpdate:r})||{outcome:"denied",reason:"permission handler is not configured"};n&&this.permissionHandlers.set(n,a),this.permissionHandlers.set("*",a);try{let c=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return pn(c,s,i)}finally{o(),n&&this.permissionHandlers.delete(n),this.permissionHandlers.delete("*")}}async sessionCancel(t){return await this.ensureStarted(),this.proc.call("session/cancel",t,5e3).catch(()=>({ok:!0}))}async handlePermissionRequest(t){let r=u(t.sessionId),n=this.permissionHandlers.get(r)||this.permissionHandlers.get("*");return n?n(t):{outcome:"denied",reason:"no active Orcha permission handler"}}artifactSource(){return u(this.target.type||"acp")==="openclaw"?"openclaw_image_generation":"acp_runtime_image_generation"}artifactOptions(){let t=d(this.target.env)?this.target.env:{};return{source:this.artifactSource(),trustedFileRoots:[u(this.launch?.artifactDirectory),u(this.launch?.homeDirectory),u(this.target.artifactRoot),u(this.target.artifactDir),u(this.target.runtimeArtifactRoot),u(t.ORCHA_RUNTIME_ARTIFACT_DIR),...k(this.target.trustedArtifactRoots),...k(this.target.trustedFileRoots),...k(this.target.artifactRoots),...k(this.target.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(this.launch?.pathMappings)?this.launch.pathMappings:[]}}async stop(t){try{await this.proc?.stop(t)}finally{this.proc=null,await this.cleanupLaunch()}}async cleanupLaunch(){let t=this.launchCleanup;this.launchCleanup=null,this.launch=null,await t?.()}};var ce=class{constructor(t,r,n,s,i={}){this.agent=t,this.target=r,this.options=i,this.sessionKey=n,this.mcp=null,this.metadata=null,this.finished=!1,this.transport=new st(r,{runId:i.runId}),this.expiresAt=new Date(Date.now()+Number(i.sandboxPolicy?.maxRuntimeSeconds||i.sessionPromptTimeoutMs/1e3||J/1e3)*1e3).toISOString()}async sessionNew({mcpServers:t,metadata:r}){if(r?.source!=="channel_message"||r.delivery?.dispatchMode!=="bridge")throw new Error("Invalid native Channel dispatch");return this.mcp=t[0],this.metadata=r,{sessionId:this.sessionKey}}async refreshMcpServers(t){this.mcp=t[0],this.promptBody&&await this.transport.request("PATCH",{...this.promptBody,mcpServer:this.mcp,attachOnly:!0},!1,"deliveries")}async sessionPrompt({prompt:t},r){if((await this.transport.request("GET",void 0,!1,"deliveries")).streamType!==pt)throw D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH");this.promptBody={runId:this.options.runId,agentCode:this.target.openclawAgentId||this.metadata.agentCode,delivery:this.metadata.delivery,expiresAt:this.expiresAt,mcpServer:this.mcp,attachOnly:this.options.attachOnly===!0,prompt:t};let s=await this.transport.request("POST",this.promptBody,!1,"deliveries",Number(this.options.sessionPromptTimeoutMs||J),i=>r?.(i));return this.finished=!0,s}async stop(){!this.finished&&this.promptBody&&await this.transport.request("DELETE",{runId:this.options.runId},!1,"deliveries")}};function rr(e){let t=d(e.metadata)?e.metadata:{};return u(t.agentCode)}function us(e,t,r){let n=u(r?.openclawAgentId)||rr(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var ue=class extends Et{constructor(t,r,n,s={},i={}){if(i.source==="channel_message")return new ce(t,r,n,s,i);let o=u(n).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",a=u(r.command)||"openclaw",c=Array.isArray(r.args)?r.args.map(String):[],l=c.length>0?c:["acp","--session",us(t,o,r)];super(t,{...r,command:a,args:l},s,i),this.boundSessionKey=us(t,o,r),this.binding=null}async sessionNew(t={}){if(t.mcpServers?.length){let r=[...this.target.args],n=r.indexOf("--session"),s=r.find(c=>c.startsWith("--session=")),i=s?s.slice(10):n<0?null:r[n+1];if(i&&i!==this.boundSessionKey)throw Object.assign(new Error("OpenClaw --session must match this Orcha task's private session"),{code:"OPENCLAW_SESSION_BINDING_CONFLICT"});i===null&&r.push("--session",this.boundSessionKey),this.target.args=r;let o=u(this.options.runId),a=Number(this.options.sandboxPolicy?.maxRuntimeSeconds||this.options.sessionPromptTimeoutMs/1e3||J/1e3);if(!o||!rr(this.agent))throw new Error("OpenClaw MCP requires a trusted task and Agent identity");this.binding=new st(this.target,{runId:o,sessionKey:this.boundSessionKey,agentCode:u(this.target.openclawAgentId)||rr(this.agent),expiresAt:new Date(Date.now()+a*1e3).toISOString()}),await this.binding.bind(t.mcpServers)}try{return await super.sessionNew(t)}catch(r){throw await this.binding?.close(),r}}async refreshMcpServers(t){if(!this.binding)throw Object.assign(new Error("The original OpenClaw task binding is unavailable"),{code:"RUNTIME_OPERATION_NOT_FOUND"});await this.binding.bind(t,!0)}async stop(t){try{await super.stop(t)}finally{await this.binding?.close()}}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as Ia}from"node:child_process";import{randomUUID as Ca}from"node:crypto";var xa=new Set(["item/commandExecution/requestApproval","item/fileChange/requestApproval","item/permissions/requestApproval"]),Aa={commandExecution:"shell",fileChange:"apply_patch",webSearch:"web_search",imageGeneration:"image_generation",imageView:"view_image"},ba=new Set(["failed","declined"]);function ps(e){return te(e)==="codex"&&k(e.args)[0]==="app-server"}function Ot(e,t){return Object.assign(new Error(t),{code:e})}function ls(e){return e.type==="mcpToolCall"?`mcp__${e.server}__${e.tool}`:e.type==="dynamicToolCall"||e.type==="collabAgentToolCall"?u(e.tool)||e.type:Aa[e.type]||""}function Na(e){if(e.type==="commandExecution")return{command:e.command,cwd:e.cwd};if(e.type==="fileChange")return{paths:(e.changes||[]).map(i=>i?.path).filter(Boolean)};if(e.type==="mcpToolCall"||e.type==="dynamicToolCall")return ut(e.arguments);let{id:t,type:r,status:n,...s}=e;return ut(s)}function ds(e){return Array.isArray(e)?e.filter(t=>t?.type==="text").map(t=>t.text).join(`
25
+ `;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"&&g("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;g("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&&(g("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}}}};function cs(e,t){let r=R(e,t);return r>0?r:t}var Et=class{constructor(t,r,n={},s={}){this.agent=t,this.target=r,this.callbacks=n,this.options=s,this.proc=null,this.launch=null,this.launchCleanup=null,this.permissionHandlers=new Map}async ensureStarted(){if(this.proc)return;let t=u(this.target.command);if(!t)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);let r={command:t,args:k(this.target.args),cwd:K(this.target,this.agent.workspace),environment:d(this.target.env)?this.target.env:{}},n=this.options.prepareLaunch?await this.options.prepareLaunch(r):{...r,environment:{...process.env,...r.environment},cleanup:async()=>{}};this.launch=n,this.launchCleanup=n.cleanup,this.proc=new ae({command:n.command,args:n.args,cwd:n.cwd,env:n.environment,label:`${this.agent.agentId}:${this.agent.targetCode}`,framing:u(this.target.framing||"line")}),this.proc.onRequest("session/request_permission",s=>this.handlePermissionRequest(s)),this.proc.onRequest("session/requestPermission",s=>this.handlePermissionRequest(s));try{await this.proc.start({initialize:this.target.initialize!==!1,initializeTimeoutMs:cs(this.target.initializeTimeoutMs,cs(this.options.initializeTimeoutMs,3e4)),initializeParams:{clientInfo:{name:"orcha-runtime-bridge",version:B},...d(this.target.initializeParams)?this.target.initializeParams:{}}})}catch(s){throw await this.proc?.stop("runtime startup failed"),this.proc=null,await this.cleanupLaunch(),s}}async sessionNew(t={}){return await this.ensureStarted(),this.proc.call("session/new",this.sessionNewParams(t))}sessionNewParams(t={}){let r=Array.isArray(t.mcpServers)?t.mcpServers:Array.isArray(this.target.mcpServers)?this.target.mcpServers:[];return{...t,mcpServers:r}}async sessionPrompt(t,r){await this.ensureStarted();let n=u(t.sessionId),s=new Map,i=this.artifactOptions(),o=this.proc.onNotification("session/update",c=>{let l=u(c.sessionId);(!l||l===n)&&r(dn(c,s,i))}),a=async c=>this.callbacks.onPermissionRequest?.({agent:this.agent,runtimeSessionId:n,request:c,emitUpdate:r})||{outcome:"denied",reason:"permission handler is not configured"};n&&this.permissionHandlers.set(n,a),this.permissionHandlers.set("*",a);try{let c=await this.proc.call("session/prompt",t,this.options.sessionPromptTimeoutMs);return pn(c,s,i)}finally{o(),n&&this.permissionHandlers.delete(n),this.permissionHandlers.delete("*")}}async sessionCancel(t){return await this.ensureStarted(),this.proc.call("session/cancel",t,5e3).catch(()=>({ok:!0}))}async handlePermissionRequest(t){let r=u(t.sessionId),n=this.permissionHandlers.get(r)||this.permissionHandlers.get("*");return n?n(t):{outcome:"denied",reason:"no active Orcha permission handler"}}artifactSource(){return u(this.target.type||"acp")==="openclaw"?"openclaw_image_generation":"acp_runtime_image_generation"}artifactOptions(){let t=d(this.target.env)?this.target.env:{};return{source:this.artifactSource(),trustedFileRoots:[u(this.launch?.artifactDirectory),u(this.launch?.homeDirectory),u(this.target.artifactRoot),u(this.target.artifactDir),u(this.target.runtimeArtifactRoot),u(t.ORCHA_RUNTIME_ARTIFACT_DIR),...k(this.target.trustedArtifactRoots),...k(this.target.trustedFileRoots),...k(this.target.artifactRoots),...k(this.target.artifactFileRoots)].filter(Boolean),pathMappings:Array.isArray(this.launch?.pathMappings)?this.launch.pathMappings:[]}}async stop(t){try{await this.proc?.stop(t)}finally{this.proc=null,await this.cleanupLaunch()}}async cleanupLaunch(){let t=this.launchCleanup;this.launchCleanup=null,this.launch=null,await t?.()}};var ce=class{constructor(t,r,n,s,i={}){this.agent=t,this.target=r,this.options=i,this.sessionKey=n,this.mcp=null,this.metadata=null,this.finished=!1,this.transport=new st(r,{runId:i.runId}),this.expiresAt=new Date(Date.now()+Number(i.sandboxPolicy?.maxRuntimeSeconds||i.sessionPromptTimeoutMs/1e3||J/1e3)*1e3).toISOString()}async sessionNew({mcpServers:t,metadata:r}){if(r?.source!=="channel_message"||r.delivery?.dispatchMode!=="bridge")throw new Error("Invalid native Channel dispatch");return this.mcp=t[0],this.metadata=r,{sessionId:this.sessionKey}}async refreshMcpServers(t){this.mcp=t[0],this.promptBody&&await this.transport.request("PATCH",{...this.promptBody,mcpServer:this.mcp,attachOnly:!0},!1,"deliveries")}async sessionPrompt({prompt:t},r){if((await this.transport.request("GET",void 0,!1,"deliveries")).streamType!==pt)throw D("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH");this.promptBody={runId:this.options.runId,agentCode:this.target.openclawAgentId||this.metadata.agentCode,delivery:this.metadata.delivery,expiresAt:this.expiresAt,mcpServer:this.mcp,attachOnly:this.options.attachOnly===!0,prompt:t};let s=await this.transport.request("POST",this.promptBody,!1,"deliveries",Number(this.options.sessionPromptTimeoutMs||J),i=>r?.(i));return this.finished=!0,s}async stop(){!this.finished&&this.promptBody&&await this.transport.request("DELETE",{runId:this.options.runId},!1,"deliveries")}};function rr(e){let t=d(e.metadata)?e.metadata:{};return u(t.agentCode)}function us(e,t,r){let n=u(r?.openclawAgentId)||rr(e);return n?`agent:${n}:${t}`:`orcha-${t}`}var ue=class extends Et{constructor(t,r,n,s={},i={}){if(i.source==="channel_message")return new ce(t,r,n,s,i);let o=u(n).replace(/[^A-Za-z0-9._-]+/g,"-")||"default",a=u(r.command)||"openclaw",c=Array.isArray(r.args)?r.args.map(String):[],l=c.length>0?c:["acp","--session",us(t,o,r)];super(t,{...r,command:a,args:l},s,i),this.boundSessionKey=us(t,o,r),this.binding=null}async sessionNew(t={}){if(t.mcpServers?.length){let r=[...this.target.args],n=r.indexOf("--session"),s=r.find(c=>c.startsWith("--session=")),i=s?s.slice(10):n<0?null:r[n+1];if(i&&i!==this.boundSessionKey)throw Object.assign(new Error("OpenClaw --session must match this Orcha task's private session"),{code:"OPENCLAW_SESSION_BINDING_CONFLICT"});i===null&&r.push("--session",this.boundSessionKey),this.target.args=r;let o=u(this.options.runId),a=Number(this.options.sandboxPolicy?.maxRuntimeSeconds||this.options.sessionPromptTimeoutMs/1e3||J/1e3);if(!o||!rr(this.agent))throw new Error("OpenClaw MCP requires a trusted task and Agent identity");this.binding=new st(this.target,{runId:o,sessionKey:this.boundSessionKey,agentCode:u(this.target.openclawAgentId)||rr(this.agent),expiresAt:new Date(Date.now()+a*1e3).toISOString()}),await this.binding.bind(t.mcpServers)}try{return await super.sessionNew(t)}catch(r){throw await this.binding?.close(),r}}async refreshMcpServers(t){if(!this.binding)throw Object.assign(new Error("The original OpenClaw task binding is unavailable"),{code:"RUNTIME_OPERATION_NOT_FOUND"});await this.binding.bind(t,!0)}async stop(t){try{await super.stop(t)}finally{await this.binding?.close()}}sessionNewParams(t={}){return{...t,mcpServers:[]}}};import{spawn as Ia}from"node:child_process";import{randomUUID as Ca}from"node:crypto";var xa=new Set(["item/commandExecution/requestApproval","item/fileChange/requestApproval","item/permissions/requestApproval"]),Aa={commandExecution:"shell",fileChange:"apply_patch",webSearch:"web_search",imageGeneration:"image_generation",imageView:"view_image"},ba=new Set(["failed","declined"]);function ps(e){return te(e)==="codex"&&k(e.args)[0]==="app-server"}function Ot(e,t){return Object.assign(new Error(t),{code:e})}function ls(e){return e.type==="mcpToolCall"?`mcp__${e.server}__${e.tool}`:e.type==="dynamicToolCall"||e.type==="collabAgentToolCall"?u(e.tool)||e.type:Aa[e.type]||""}function Na(e){if(e.type==="commandExecution")return{command:e.command,cwd:e.cwd};if(e.type==="fileChange")return{paths:(e.changes||[]).map(i=>i?.path).filter(Boolean)};if(e.type==="mcpToolCall"||e.type==="dynamicToolCall")return ut(e.arguments);let{id:t,type:r,status:n,...s}=e;return ut(s)}function ds(e){return Array.isArray(e)?e.filter(t=>t?.type==="text").map(t=>t.text).join(`
26
26
  `):""}function Ma(e){return e.type==="commandExecution"?e.aggregatedOutput||"":e.type==="mcpToolCall"?e.error?.message||ds(e.result?.content):e.type==="dynamicToolCall"?ds(e.contentItems):e.type==="fileChange"?(e.changes||[]).map(t=>t?.path).filter(Boolean).join(`
27
- `):""}var le=class extends Tt{async runPrompt(t,r,n,s){let i=u(this.target.command);if(!i)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);if(this.options.prepareLaunch)throw Ot("BAD_REQUEST","Codex app-server \u53EA\u652F\u6301\u5DF2\u63A5\u5165\u7684\u672C\u673A\u8BBE\u5907\uFF0C\u4E0D\u652F\u6301\u6C99\u7BB1\u542F\u52A8");let o=u(t.sessionId)||Ca(),a=K(this.target,this.agent.workspace),c=Ge(this.target,o);this.deliveryCwd=a,this.deliveryRoots=[a,...ze(this.target,c.root).trustedFileRoots],this.deliveryThreadId=s||null;let l=qe(t,this.target),p=R(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,R(this.options.sessionPromptTimeoutMs,J)),m={sessionId:o,emitUpdate:r,ended:new AbortController};this.approvalTurn=m;let f=Ia(i,[...k(this.target.args),...this.taskMcp?.args||[]],{cwd:a,env:{...process.env,...d(this.target.env)?this.target.env:{},...this.taskMcp?.environment||{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:o,ORCHA_RUNTIME_ARTIFACT_DIR:c.root},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(o,f),_("info","runtime.codex","app-server turn started",{target:this.agent.targetCode,sessionId:o,pid:f.pid,timeoutMs:p});let h=w=>r({sessionId:o,update:w}),g="";return f.stderr.setEncoding("utf8"),f.stderr.on("data",w=>{g=`${g}${w}`.slice(-4e3)}),await new Promise((w,I)=>{let E={threadId:null,turnId:null,items:new Map,pending:"",lastError:"",nativeModel:null},C=!1,y=(T,x)=>{C||(C=!0,clearTimeout(O),m.ended.abort(),this.approvalTurn===m&&(this.approvalTurn=null),this.active.delete(o),nt(f),Ke(c,{target:this.agent.targetCode,sessionId:o}),_("info","runtime.codex","app-server turn finished",{target:this.agent.targetCode,sessionId:o,status:T?"failed":"completed",...T?{error:String(T.message||T)}:{}}),T?I(T):w(x))},O=setTimeout(()=>y(Ot("RUNTIME_CLI_TIMEOUT",`runtime CLI timed out after ${p}ms`)),p);O.unref?.(),f.on("error",T=>y(T)),f.on("exit",(T,x)=>y(Object.assign(new Error(`Codex app-server exited before the turn completed (${x||T})${g.trim()?`: ${g.trim().slice(-500)}`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:T,signal:x})));let M=()=>{E.pending&&l&&h({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:E.pending}}),E.pending=""},A=Gt(f,{onRequest:async(T,x)=>{if(xa.has(T)){let S=await this.requestApproval(Sn(T,x,E.items.get(x.itemId)),{});return Rn(T,x,S?.outcome==="approved")}if(T==="mcpServer/elicitation/request")return x.serverName==="orcha"&&x.mode!=="url"?{action:"accept",content:{},_meta:null}:{action:"decline",content:null,_meta:null};throw new Error(`OrchaAI does not handle Codex request ${T}`)},onNotification:(T,x)=>{if(x.threadId&&E.threadId&&x.threadId!==E.threadId)return;let S=d(x.item)?x.item:null;if(T==="item/started"&&S){E.items.set(S.id,S);let U=ls(S);if(!U)return;M(),h({sessionUpdate:"tool_call",toolCallId:S.id,title:U,status:"in_progress",rawInput:Na(S)})}else if(T==="item/completed"&&S)E.items.set(S.id,S),S.type==="agentMessage"&&u(S.text)?(M(),S.phase==="commentary"?l&&h({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:S.text}}):E.pending=S.text):S.type==="contextCompaction"?h({sessionUpdate:"runtime_event",event:{payload:{type:"context_compacted",id:S.id}}}):ls(S)&&h({sessionUpdate:"tool_call_update",toolCallId:S.id,status:ba.has(S.status)||S.success===!1?"failed":"completed",rawOutput:Ma(S)});else if(T==="mcpServer/startupStatus/updated"&&x.name==="orcha"&&x.status==="failed")y(Ot("RUNTIME_CODEX_MCP_UNAVAILABLE",`Codex \u672A\u80FD\u8FDE\u63A5 OrchaAI \u4EFB\u52A1\u5DE5\u5177\uFF1A${u(x.error)||"\u542F\u52A8\u5931\u8D25"}`));else if(T==="error"&&x.willRetry!==!0)E.lastError=u(x.error?.message);else if(T==="turn/completed"&&(!E.turnId||x.turn?.id===E.turnId)){let U=d(x.turn)?x.turn:{};if(U.status!=="completed"){y(Ot(U.status==="interrupted"?"RUNTIME_CODEX_TURN_INTERRUPTED":"RUNTIME_CODEX_TURN_FAILED",u(U.error?.message)||E.lastError||`Codex turn ${U.status||"failed"}`));return}E.pending&&h({sessionUpdate:"agent_message_chunk",content:{type:"text",text:E.pending}}),y(null,{stopReason:"end_turn",_artifacts:[],...E.nativeModel?{nativeModel:E.nativeModel}:{}})}}});(async()=>{await A.request("initialize",{clientInfo:{name:"orcha_runtime_bridge",title:"OrchaAI Runtime Bridge",version:B},capabilities:null}),A.notify("initialized");let T=t.modelOptions,x=T?await Je(A,a):null,S=T?T.model||x.defaultModel:void 0,U=x?.models.find(xt=>xt.id===S);if(T&&(!U||T.effort&&!U.efforts.includes(T.effort)))throw Ot("RUNTIME_MODEL_OPTIONS_INVALID","The selected model or effort is no longer available on this device");let z=T?T.effort||x.defaultEffort||U.defaultEffort:void 0,b={...S?{model:S}:{}},_t=s?await A.request("thread/resume",{threadId:s,cwd:a,excludeTurns:!0,...b}):await A.request("thread/start",{cwd:a,...b}),X=u(_t?.thread?.id);if(!X)throw Ot("RUNTIME_CODEX_APP_SERVER_ERROR","Codex app-server did not return a thread");E.threadId=X,E.nativeModel=typeof _t.model=="string"?_t.model:null,this.deliveryThreadId=X,h({sessionUpdate:"runtime_event",event:{type:"thread.started",thread_id:X}});let P=await A.request("turn/start",{threadId:X,...S?{model:S}:{},...z?{effort:z}:{},input:[{type:"text",text:yt(t.prompt),text_elements:[]}]});E.turnId=u(P?.turn?.id)||null})().catch(T=>y(T))})}};var nr="ORCHA_RUNTIME_OUTPUT_START",sr="ORCHA_RUNTIME_OUTPUT_END",ir="ORCHA_RUNTIME_CONTROL_START",or="ORCHA_RUNTIME_CONTROL_END",ar=nr,cr=sr,ur=ir,lr=or,dr=[nr,sr,ir,or],Ua=new Set(["_artifacts","_decision","_meta"]),Pa=new RegExp(`(?:^|(?<=[\\r\\n]))[ \\t]*(?<marker>${dr.join("|")})[ \\t]*(?=\\r\\n?|\\n|$)`,"g"),H=class extends Error{constructor(t,r,n){super(r),this.name="RuntimeResultProtocolError",this.code=t,this.detail={rawOutput:n}}};function pr(e){let t=typeof e=="string"?e.trimStart():"";return dr.some(r=>t.startsWith(r))}function fr(e){if(typeof e!="string")return null;let t=e,r=La(t);if(![...r.values()].some(h=>h.length>0))return null;let n=[],s=[];for(let[h,g]of r)g.length===0?n.push(h):g.length>1&&s.push(h);if(n.length>0||s.length>0){let h=[];throw n.length>0&&h.push(`\u7F3A\u5C11 ${n.join(", ")}`),s.length>0&&h.push(`\u91CD\u590D ${s.join(", ")}`),new H("invalid_markers",`Runtime Result \u534F\u8BAE\u6807\u8BB0\u4E0D\u5B8C\u6574\uFF1A${h.join("\uFF1B")}`,t)}let i=r.get(nr)[0],o=r.get(sr)[0],a=r.get(ir)[0],c=r.get(or)[0];if(!(i.end<=o.start&&o.end<=a.start&&a.end<=c.start))throw new H("invalid_marker_order","Runtime Result \u534F\u8BAE\u6807\u8BB0\u987A\u5E8F\u9519\u8BEF\uFF1A\u5FC5\u987B\u5148\u8F93\u51FA OUTPUT \u5757\uFF0C\u518D\u8F93\u51FA CONTROL \u5757",t);let l=ka(t.slice(i.end,o.start));if(!l.trim())throw new H("empty_output","Runtime Result OUTPUT \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let p=t.slice(a.end,c.start).trim();if(!p)throw new H("empty_control","Runtime Result CONTROL \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let m;try{m=JSON.parse(p)}catch(h){throw new H("invalid_control_json",`Runtime Result CONTROL \u5757\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(h?.message||h)}`,t)}if(!fs(m))throw new H("invalid_control_type","Runtime Result CONTROL \u5757\u5FC5\u987B\u662F JSON \u5BF9\u8C61",t);let f=Object.keys(m).filter(h=>!Ua.has(h)).sort();if(f.length>0)throw new H("invalid_control_keys",`Runtime Result CONTROL \u5757\u5305\u542B\u975E\u6807\u51C6\u5B57\u6BB5\uFF1A${f.join(", ")}`,t);if("_artifacts"in m&&!Array.isArray(m._artifacts))throw new H("invalid_control_field_type","Runtime Result CONTROL \u5757\u7684 _artifacts \u5FC5\u987B\u662F JSON \u6570\u7EC4",t);for(let h of["_decision","_meta"])if(h in m&&!fs(m[h]))throw new H("invalid_control_field_type",`Runtime Result CONTROL \u5757\u7684 ${h} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`,t);return{output:l,...m}}function La(e){let t=new Map(dr.map(r=>[r,[]]));for(let r of e.matchAll(Pa))t.get(r.groups.marker).push({start:r.index,end:r.index+r[0].length});return t}function ka(e){let t=e.match(/^(?:\r\n|\r|\n)/)?.[0]||"",r=t?e.slice(t.length):e;return t&&r.endsWith(t)?r.slice(0,-t.length):r}function fs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{createHash as va}from"node:crypto";var Da="orcha.goal-contract/v1",$a=new Set(["complete","completed","done","ok","passed","success","succeeded"]),Ha=new Set(["aborted","blocked","cancelled","canceled","denied","error","failed","failure","timeout","timed_out"]),Fa=new Map([["exec_command","run_command"],["local_shell_call","run_command"],["run_command","run_command"],["apply_patch","apply_patch"],["read_file","read_file"],["list_files","list_files"],["plugin_operation","plugin_operation"]]);function _r(e){return va("sha256").update(Z(e)).digest("hex")}function hs(e){if(!_s(e))return"";let t=["The following Orcha goal contract is immutable for this turn. Do not narrow its outcome or constraints.",`<goal_contract>${JSON.stringify(e)}</goal_contract>`];return e.verificationPlan?.required===!0&&t.push("Every verification check must be satisfied by a real successful tool call from one of its toolNames.","Each check requires requiredMatches distinct successful tool call IDs; repeated updates for one call count once.","A final text claim is not verification; missing or failed tool evidence prevents completion."),t.join(`
28
- `)}function gs(e,t,r=""){if(!_s(e))return e==null?null:{required:!0,status:"failed",outcome:u(e?.outcome),goalContractHash:"",checks:[],errorCode:"invalid_goal_contract"};let n=_r(e),s=e.verificationPlan.required===!0;if(u(r)&&u(r)!==n)return{required:s,status:"failed",outcome:e.outcome,goalContractHash:n,checks:[],errorCode:"goal_contract_hash_mismatch"};if(!s)return{required:!1,status:"not_required",outcome:e.outcome,goalContractHash:n,checks:[]};let i=Ba(t),o=e.verificationPlan.checks.map(c=>Ja(c,i));return{required:!0,status:o.some(c=>c.status==="failed")?"failed":o.some(c=>c.status==="missing")?"missing":"passed",outcome:e.outcome,goalContractHash:n,checks:o}}function _s(e){if(!d(e)||e.schemaVersion!==Da||!u(e.outcome))return!1;let t=e.verificationPlan;if(!d(t)||typeof t.required!="boolean"||!Array.isArray(t.checks)||t.required&&t.checks.length===0)return!1;let r=new Set;for(let n of t.checks)if(!d(n)||!u(n.id)||r.has(u(n.id))||(r.add(u(n.id)),!Array.isArray(n.toolNames)||n.toolNames.length===0||n.toolNames.some(s=>!u(s)))||!Number.isSafeInteger(n.requiredMatches)||n.requiredMatches<1||n.arguments!==void 0&&!d(n.arguments))return!1;return!0}function Ba(e){let t=new Map,r=[];for(let n of Array.isArray(e)?e:[]){let s=d(n?.update)?n.update:{},i=u(s.sessionUpdate);if(i==="runtime_event"){ja(s.event,t,r);continue}if(i==="tool_call"){let o=pe(s)||`tool-${r.length+1}`,a=de(t,r,o),c=hr(s,s.name||s.toolName||s.kind);a.toolName=c.toolName,a.arguments=c.arguments,a.status=Dt(s.status),a.evidence=me(s);continue}if(i==="tool_call_update"){let o=pe(s);if(!o)continue;let a=de(t,r,o),c=hr(s,s.name||s.toolName||s.kind);a.toolName||=c.toolName,Object.keys(a.arguments).length===0&&(a.arguments=c.arguments),a.status=Dt(s.status),a.evidence.push(...me(s))}}return r}function ja(e,t,r){let n=d(e)&&d(e.payload)?e.payload:d(e)?e:{},s=u(n.type);if(["function_call","custom_tool_call","local_shell_call","mcp_tool_call"].includes(s)){let a=pe(n)||`runtime-${r.length+1}`,c=de(t,r,a),l=hr(n,n.name||n.tool||s,s);c.toolName=l.toolName,c.arguments=l.arguments,c.status=Dt(n.status),c.evidence.push(...me(n));return}if(!["function_call_output","custom_tool_call_output","local_shell_call_output","mcp_tool_call_output"].includes(s))return;let i=pe(n);if(!i)return;let o=de(t,r,i);o.status=za(n,o.toolName),o.evidence.push(...me(n))}function de(e,t,r){let n=e.get(r);return n||(n={toolCallId:r,toolName:"",arguments:{},status:"unknown",evidence:[]},e.set(r,n),t.push(n)),n}function qa(e){let t=u(e).toLowerCase();return Fa.get(t)||t}function hr(e,t,r=""){let n=Ga(e),s=u(r)==="mcp_tool_call"||u(e?.kind).toLowerCase()==="mcp",i=d(e?._meta)?e._meta:{},o=u(e?.server||e?.serverName||e?.server_name||e?.mcpServer||i.server||i.serverName).toLowerCase();if(s&&o==="orcha"){let a=u(e?.tool||e?.toolName||e?.name||t);return{toolName:"plugin_operation",arguments:{...n,...a?{operationCode:a}:{}}}}return{toolName:qa(t),arguments:n}}function pe(e){return d(e)?u(e.call_id||e.callId||e.toolCallId||e.id):""}function Ga(e){if(!d(e))return{};for(let r of["arguments","args","rawInput","input","params","parameters"]){let n=Ka(e[r]);if(n)return n}let t={};for(let r of["cmd","command","cwd","operationCode","path","query","url"])e[r]!==void 0&&(t[r]=e[r]);return t}function Ka(e){if(d(e))return structuredClone(e);if(typeof e!="string")return null;try{let t=JSON.parse(e);return d(t)?t:null}catch{return null}}function za(e,t){if(!d(e))return"unknown";let r=fe(e,0,{parseCliExitCode:t==="run_command"||t==="apply_patch"});return r.includes("failed")?"failed":r.includes("success")?"success":"unknown"}function fe(e,t=0,r={}){if(t>8||e===null||e===void 0)return[];if(typeof e=="string")return Va(e,t,r);if(Array.isArray(e))return e.flatMap(o=>fe(o,t+1,r));if(!d(e))return[];let n=[];typeof e.isError=="boolean"&&n.push(e.isError?"failed":"success"),typeof e.ok=="boolean"&&n.push(e.ok?"success":"failed"),typeof e.success=="boolean"&&n.push(e.success?"success":"failed");let s=Dt(e.status);s!=="unknown"&&n.push(s);let i=e.exitCode??e.exit_code;typeof i=="number"&&Number.isFinite(i)&&n.push(i===0?"success":"failed");for(let o of["output","result","structuredContent","content"])e[o]!==void 0&&n.push(...fe(e[o],t+1,r));return n}function Va(e,t,r){let n=e.trim();if(!n)return[];try{return fe(JSON.parse(n),t+1,r)}catch{}if(r.parseCliExitCode!==!0)return[];let s=[];for(let i of n.matchAll(/(?:process\s+exited\s+with\s+code|exit\s+code\s*:?)\s*(-?\d+)/gi))s.push(Number(i[1])===0?"success":"failed");return s}function Dt(e){let t=u(e).toLowerCase();return $a.has(t)?"success":Ha.has(t)?"failed":"unknown"}function me(e){if(!d(e))return[];let t=d(e.output)?e.output:{},r=[e.verificationEvidence,d(e.verification)?e.verification.evidence:null,t.verificationEvidence,d(t.verification)?t.verification.evidence:null],n=[];for(let s of r)for(let i of Array.isArray(s)?s:s?[s]:[])!d(i)||!u(i.id)||n.push({id:u(i.id),status:Dt(i.status??(i.passed===!0?"passed":i.passed===!1?"failed":"")),...u(i.message)?{message:u(i.message)}:{}});return n}function Ja(e,t){let r=t.filter(o=>e.toolNames.includes(o.toolName)&&gr(e.arguments||{},o.arguments)),n=u(e.evidenceId),s=r.filter(o=>o.status==="success"&&(!n||o.evidence.some(a=>a.id===n&&a.status==="success")));if(s.length>=e.requiredMatches)return mr(e,"passed",s,`Runtime tool evidence passed ${s.length} times.`);let i=r.filter(o=>o.status==="failed"||n&&o.evidence.some(a=>a.id===n&&a.status==="failed"));return s.length===0&&i.length?mr(e,"failed",i,"Runtime tool evidence failed."):mr(e,"missing",s,`Only ${s.length}/${e.requiredMatches} required tool executions passed.`)}function mr(e,t,r,n){let s=r.map(i=>i.toolCallId).filter(Boolean);return{id:e.id,status:t,message:n,...u(e.description)?{description:u(e.description)}:{},toolNames:e.toolNames,requiredMatches:e.requiredMatches,observedMatches:s.length,toolCallIds:s,...d(e.arguments)?{arguments:e.arguments}:{},...u(e.evidenceId)?{evidenceId:u(e.evidenceId)}:{}}}function gr(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>gr(r,t[n])):d(e)?d(t)?Object.entries(e).every(([r,n])=>Object.hasOwn(t,r)&&gr(n,t[r])):!1:Object.is(e,t)}function Z(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string")return ms(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("invalid_jcs_number");return JSON.stringify(Object.is(e,-0)?0:e)}if(Array.isArray(e))return`[${Array.from({length:e.length},(t,r)=>{if(!Object.hasOwn(e,r))throw new Error("invalid_jcs_json_value");return Z(e[r])}).join(",")}]`;if(d(e))return`{${Object.keys(e).sort().map(t=>`${ms(t)}:${Z(e[t])}`).join(",")}}`;throw new Error("invalid_jcs_json_value")}function ms(e){return Wa(e),JSON.stringify(e)}function Wa(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw new Error("invalid_jcs_unicode");t+=1}else if(r>=56320&&r<=57343)throw new Error("invalid_jcs_unicode")}}import{spawn as Xa}from"node:child_process";import{createHash as Ya,randomUUID as Qa}from"node:crypto";import{constants as Za}from"node:fs";import{access as tc,mkdir as yr,readdir as ec,realpath as $t,rm as rc,stat as nc}from"node:fs/promises";import sc from"node:http";import{tmpdir as ic}from"node:os";import{isAbsolute as Ht,join as St,relative as ys,resolve as Tr}from"node:path";var Er=1,oc="orcha.process-isolation/v1",Or="orcha.egress-proxy/v1",ac="--disable-wasm-trap-handler",he={read_only:0,workspace_write:1,workspace_network:2},wr={read_only:["read_only","denied"],workspace_write:["workspace_write","denied"],workspace_network:["workspace_write","restricted"]},cc=new Set([".env",".git-credentials",".netrc",".npmrc",".pypirc","credentials.json","secrets.json","id_rsa","id_ed25519"]);function ft(e){if(!d(e))throw N("RUNTIME_SANDBOX_POLICY_REQUIRED","sandboxPolicy is required");let t=structuredClone(e),r=u(t.accessMode),n=u(t.accessModeCeiling);if(!(r in wr)||!(n in wr))throw N("RUNTIME_SANDBOX_POLICY_INVALID","unsupported runtime access mode");if(he[r]>he[n])throw N("RUNTIME_SANDBOX_POLICY_INVALID","access mode exceeds its ceiling");let[s,i]=wr[r];if(t.filesystemMode!==s||t.networkMode!==i)throw N("RUNTIME_SANDBOX_POLICY_INVALID","runtime access profile does not match its mode");if(Number(t.policySchemaVersion)!==Er||!Number.isInteger(Number(t.policyRevision))||Number(t.policyRevision)<1)throw N("RUNTIME_SANDBOX_POLICY_INVALID","unsupported sandbox policy schema or revision");for(let[a,c]of Object.entries({outsideWorkspaceAccess:"denied",hostAccess:"denied",hostEnvironmentAccess:"denied",dockerSocketAccess:"denied",environmentMode:"allowlist"}))if(t[a]!==c)throw N("RUNTIME_SANDBOX_POLICY_INVALID",`${a} cannot be relaxed`);let o=d(t.processIsolation)?t.processIsolation:{};if(o.mode!=="required"||o.backend==="direct")throw N("RUNTIME_SANDBOX_POLICY_INVALID","strong process isolation is required");if(Array.isArray(t.alwaysApprovedApprovalKeys)&&t.alwaysApprovedApprovalKeys.length)throw N("RUNTIME_SANDBOX_POLICY_INVALID","persistent runtime approvals are forbidden");return t}function ws(e,t){let r=ft(e),n=ft(t);return he[n.accessMode]<he[r.accessMode]}async function Ts(e){if(!e.sandboxRequired)return{dispatchable:!0,enforced:!1,backend:"direct",daemonStatus:"not_required",daemonProtocolVersion:"",policySchemaVersions:[Er],runtimePolicyUpdates:!1,workspaceSync:!1,egressProxy:!1,reason:"external_runtime_sandbox_not_required"};let t=await Os(e.sandboxBrokerCommand,process.env.PATH||"");if(!t)throw N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let r=await fc(t,k(e.sandboxBrokerArguments),e.sandboxProbeTimeoutMs);if(r.enforced!==!0||u(r.protocolVersion)!=="orcha.runtime-sandbox-broker/v1"||!["bubblewrap","broker"].includes(u(r.backend)))throw N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker did not report enforced isolation");let n=d(r.probes)?r.probes:{};for(let s of["emptyRoot","outsideWorkspaceDenied","hostFilesystemDenied","sensitiveFilesDenied","environmentAllowlist","dockerSocketDenied","networkNamespace","workspaceReadOnly","workspaceWrite","resourceLimits"])if(n[s]!==!0)throw N("RUNTIME_SANDBOX_UNAVAILABLE",`sandbox broker probe failed: ${s}`);return e.egressProxyRequired&&await gc(e),{dispatchable:!0,enforced:!0,backend:u(r.backend),daemonStatus:"ok",daemonProtocolVersion:u(r.protocolVersion||"orcha.runtime-sandbox-broker/v1"),policySchemaVersions:[Er],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:e.egressProxyRequired}}async function Sr(e,t,r){let n=u(t.workspace||t.cwd),s=u(r),i=n||(t.allowRequestWorkspace===!0?s:"");if(!i||!Ht(i))throw N("RUNTIME_WORKSPACE_NOT_CONFIGURED","runtime target must configure an absolute trusted workspace");let o=await $t(i);if(!(await nc(o)).isDirectory())throw N("RUNTIME_WORKSPACE_INVALID","runtime workspace is not a directory");if(!(e.trustedWorkspaceRoots.length?await Promise.all(e.trustedWorkspaceRoots.map(l=>$t(l))):[o]).some(l=>Ir(l,o)))throw N("RUNTIME_WORKSPACE_OUTSIDE_TRUSTED_ROOT","runtime workspace is outside trusted roots");return o}async function Es({config:e,target:t,command:r,args:n,cwd:s,environment:i,runId:o,agentId:a,sessionId:c,sandboxPolicy:l}){if(!e.sandboxRequired)return{command:r,args:[...n],cwd:s,environment:{...process.env,...i},tempDirectory:"",isolation:{enforced:!1,backend:"development_direct"},cleanup:async()=>{}};let p=ft(l),m=await Sr(e,t,s),f=await $t(s);if(!Ir(m,f))throw N("RUNTIME_WORKSPACE_CWD_INVALID","runtime cwd is outside its workspace");let h=await Os(e.sandboxBrokerCommand,process.env.PATH||"");if(!h)throw N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let g=`runtime-${Ya("sha256").update(String(o)).digest("hex").slice(0,32)}`,w=Tr(e.sandboxTempRoot||St(ic(),"orcha-runtime-sandboxes"));await yr(w,{recursive:!0,mode:448});let I=St(w,`${g}-${Qa()}`),E=St(I,"home"),C=St(I,"artifacts");await yr(E,{recursive:!0,mode:448}),await yr(C,{recursive:!0,mode:448});let y=p.networkMode==="restricted"?await mc(e,{runId:String(o),instanceId:g,policyRevision:Number(p.policyRevision),ttlMs:Math.min(R(p.maxRuntimeSeconds,900)*1e3,e.egressGrantMaxTtlMs),maxTransferBytes:R(p.maxNetworkBytes,64*1024*1024)}):null,O={PATH:u(i.PATH||process.env.PATH),LANG:u(i.LANG||process.env.LANG||"C.UTF-8"),HOME:"/tmp/home",TMPDIR:"/tmp",USER:"orcha",LOGNAME:"orcha",SHELL:"/bin/sh",ORCHA_AGENT_ID:String(a),ORCHA_SESSION_ID:String(c),ORCHA_RUN_ID:String(o),ORCHA_RUNTIME_ARTIFACT_DIR:"/tmp/artifacts",...lc(t,i)};O.HOME="/tmp/home",O.TMPDIR="/tmp",O.ORCHA_RUNTIME_ARTIFACT_DIR="/tmp/artifacts",O.NODE_OPTIONS=ac;let M={schemaVersion:oc,runId:String(o),instanceId:g,workspace:m,cwd:f,filesystemMode:p.filesystemMode,networkMode:p.networkMode,environmentMode:"allowlist",deniedRelativePaths:await dc(m),temporaryDirectory:I,egressProxy:y,environment:O,resourceLimits:pc(p),readOnlyToolchainRoots:await uc(e,t)},A=!1,T=async()=>{if(!A){A=!0;try{y&&await hc(e,y,{runId:String(o),instanceId:g})}finally{await rc(I,{recursive:!0,force:!0})}}};return{command:h,args:[...k(e.sandboxBrokerArguments),"--",r,...n],cwd:f,environment:{PATH:process.env.PATH||"",LANG:process.env.LANG||"C.UTF-8",ORCHA_PROCESS_ISOLATION_REQUEST:JSON.stringify(M)},tempDirectory:I,homeDirectory:E,artifactDirectory:C,pathMappings:[{runtimeRoot:"/tmp/artifacts",hostRoot:C},{runtimeRoot:"/tmp/home",hostRoot:E}],isolation:{enforced:!0,backend:"broker",instanceId:g,policyRevision:p.policyRevision},cleanup:T}}async function uc(e,t){let r=k(t.toolchainRoots||t.sandboxToolchainRoots);if(!r.length)return[];let n=await Promise.all(k(e.trustedToolchainRoots).map(i=>$t(i)));if(!n.length)throw N("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","target toolchain roots require ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS");let s=[];for(let i of r){if(!Ht(i))throw N("RUNTIME_TOOLCHAIN_ROOT_INVALID","toolchain roots must be absolute");let o=await $t(i);if(!n.some(a=>Ir(a,o)))throw N("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","toolchain root is outside trusted roots");s.push(o)}return[...new Set(s)]}function lc(e,t){let r=d(e.env)?e.env:{},n={};for(let[s,i]of Object.entries(r))/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&i!=null&&(n[s]=String(i));for(let s of["ORCHA_RUNTIME_PROMPT","ORCHA_RUNTIME_ARTIFACT_DIR"])t[s]!=null&&(n[s]=String(t[s]));return n}async function dc(e){let t=[],r=0,n=async s=>{let i;try{i=await ec(s,{withFileTypes:!0})}catch(o){if(s===e)throw o;return}for(let o of i){if(r+=1,r>1e4)throw N("RUNTIME_WORKSPACE_SCAN_LIMIT_EXCEEDED","workspace contains more than 10000 entries");let a=St(s,o.name),c=ys(e,a),l=o.name.toLowerCase();(cc.has(l)||l.startsWith(".env."))&&t.push(c),o.isDirectory()&&!o.isSymbolicLink()&&await n(a)}};return await n(e),t.sort()}function pc(e){return{maxCpuSeconds:Math.max(1,R(e.maxRuntimeSeconds,900)),maxMemoryBytes:R(e.maxMemoryBytes,2*1024*1024*1024),maxProcesses:R(e.maxProcesses,128),maxOpenFiles:R(e.maxOpenFiles,1024),maxFileBytes:R(e.maxFileBytes,64*1024*1024)}}async function fc(e,t,r){return await new Promise((n,s)=>{let i=Xa(e,[...t,"--probe"],{env:{PATH:process.env.PATH||"",LANG:"C.UTF-8"},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=[],a=[];i.stdout.on("data",l=>o.push(Buffer.from(l))),i.stderr.on("data",l=>a.push(Buffer.from(l)));let c=setTimeout(()=>i.kill("SIGKILL"),Math.max(1e3,r));i.once("error",s),i.once("close",l=>{if(clearTimeout(c),l!==0){s(N("RUNTIME_SANDBOX_UNAVAILABLE",Buffer.concat(a).toString("utf8").trim()||`sandbox probe exited with ${l}`));return}try{n(JSON.parse(Buffer.concat(o).toString("utf8")))}catch{s(N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox probe returned invalid JSON"))}})})}async function Os(e,t){let r=u(e);if(!r)return"";let n=Ht(r)?[r]:String(t||"").split(":").filter(Boolean).map(s=>St(s,r));for(let s of n)try{return await tc(s,Za.X_OK),s}catch{}return""}async function mc(e,t){if(!e.egressProxyRequired)throw N("RUNTIME_EGRESS_UNAVAILABLE","restricted network requires the Egress Proxy");let r=await Rr(e,"POST","/v1/grants",{protocolVersion:Or,...t}),n={socketPath:e.egressProxySocket,grantId:u(r.grantId),credential:u(r.credential)};if(!n.grantId||!n.credential)throw N("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy returned an invalid grant");return n}async function hc(e,t,r){await Rr(e,"POST",`/v1/grants/${encodeURIComponent(t.grantId)}/revoke`,{protocolVersion:Or,...r}).catch(()=>{})}async function gc(e){let t=await Rr(e,"GET","/health");if(t.status!=="ok"||t.proxy!=="orcha-egress-proxy"||t.protocolVersion!==Or)throw N("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy is unavailable or incompatible")}async function Rr(e,t,r,n){if(!Ht(e.egressProxySocket)||!e.egressProxyToken)throw N("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy socket and token are required");return await new Promise((s,i)=>{let o=sc.request({socketPath:e.egressProxySocket,path:r,method:t,headers:{Authorization:`Bearer ${e.egressProxyToken}`,Accept:"application/json",...n?{"Content-Type":"application/json"}:{}}},a=>{let c=[],l=0;a.on("data",p=>{l+=p.length,l>1048576?o.destroy(new Error("egress response is too large")):c.push(Buffer.from(p))}),a.once("end",()=>{try{let p=JSON.parse(Buffer.concat(c).toString("utf8")||"{}");(a.statusCode||500)>=400?i(N("RUNTIME_EGRESS_UNAVAILABLE",u(p.error)||"Egress Proxy rejected the request")):s(p)}catch(p){i(p)}})});o.once("error",i),o.setTimeout(3e3,()=>o.destroy(new Error("Egress Proxy request timed out"))),n?o.end(JSON.stringify(n)):o.end()})}function Ir(e,t){let r=ys(Tr(e),Tr(t));return r===""||!r.startsWith("..")&&!Ht(r)}function N(e,t){return Object.assign(new Error(t),{code:e})}var Cr=24e3,xr=8,Ar=50,br=6e3,yc=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),wc=10*60*1e3,Tc=60*1e3,Ec=8,Oc=30*60*1e3,Sc=100,Rc=new Set(["agent_message_chunk","agent_thought_chunk"]),Ic=60*1e3,Cc=1,Cs=2400,xc=new Set(["max_tokens","max_output_tokens","length"]),Ac=new Set(["agent_message_chunk","tool_call","tool_call_update"]),bc=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions"]),Nc=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Mc(e){if(!d(e))return{};let t={};for(let r of["name","code","serverName","serverCode","type","transport","url","command","protocolVersion"]){let n=u(e[r]);n&&(t[r]=n)}return t}function Uc(e){return(Array.isArray(e)?e:[]).map(Mc).sort((t,r)=>{let n=Z(t),s=Z(r);return n<s?-1:n>s?1:0})}function Pc(e){return!d(e)||e.verificationPlan?.required!==!0?!1:(Array.isArray(e.verificationPlan.checks)?e.verificationPlan.checks:[]).some(r=>d(r)&&Array.isArray(r.toolNames)&&r.toolNames.some(n=>u(n)==="plugin_operation"))}function Lc(e,t,r){let n=d(e?._meta)?e._meta:{};return{...d(e)?e:{},sessionId:t,update:d(e?.update)?e.update:{},_meta:{...n,orchaAgentId:r.agentId,runtimeSessionId:r.runtimeSessionId,bridgeUpdateId:_e()}}}function kc(e){if(!d(e)||Object.keys(e).some(n=>n!=="sessionId"&&n!=="update"))return"";let t=e.update,r=d(t)?t.content:null;return!Rc.has(t?.sessionUpdate)||Object.keys(t).length!==2?"":d(r)&&r.type==="text"&&typeof r.text=="string"&&Object.keys(r).length===2?t.sessionUpdate:""}function vc(e){let t=null,r=null,n=()=>{r&&clearTimeout(r),r=null;let i=t;t=null,i&&e(i)};return{push:i=>{let o=kc(i),a=o?i.update.content.text:"",c=t?.update.content.text;if(t&&o===t.update.sessionUpdate&&i.sessionId===t.sessionId&&!a.startsWith(c)&&!pr(a)){t.update.content.text=c+a;return}if(n(),!o){e(i);return}t={...i,update:{...i.update,content:{...i.update.content}}},r=setTimeout(n,Sc),r.unref?.()},flush:n}}function F(e){return e==null||e===""?!1:typeof e=="string"?u(e)!=="":Array.isArray(e)?e.length>0:d(e)?Object.keys(e).length>0:!0}function xs(e){let t=u(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return yc.has(t)}function it(e,t){let r=R(e,t);return Number.isFinite(r)&&r>0?r:t}function Ft(e,t=!1){if(typeof e=="boolean")return e;let r=u(e).toLowerCase();return["true","1","yes","y","on"].includes(r)?!0:["false","0","no","n","off"].includes(r)?!1:t}function et(e){return u(e?.type||"echo")}function As(e){let t=et(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function Ur(e){if(d(e)){if(Object.prototype.hasOwnProperty.call(e,"releaseAfterPrompt"))return e.releaseAfterPrompt;if(Object.prototype.hasOwnProperty.call(e,"disposeAfterPrompt"))return e.disposeAfterPrompt}}function Dc(e){let t=String(e||"");if(Nc.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 Pr(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=br)return e;let r=e.length-br;return`${e.slice(0,br)}... [truncated ${r} characters]`}if(t>=xr)return Array.isArray(e)?`[array truncated at depth ${xr}, items=${e.length}]`:d(e)?`[object truncated at depth ${xr}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let r=e.slice(0,Ar).map(n=>Pr(n,t+1));return e.length>Ar&&r.push(`[truncated ${e.length-Ar} items]`),r}if(d(e)){let r={};for(let[n,s]of Object.entries(e))r[n]=Dc(n)?"[REDACTED]":Pr(s,t+1);return r}return String(e)}var $c=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 Hc(e){if(!d(e))return e;let t={};for(let r of $c)F(e[r])&&(t[r]=e[r]);return t}function Fc(e){if(!d(e))return e;let t={...e};return d(t.renderedPayload)&&(t.renderedPayload=Hc(t.renderedPayload)),t}function Bc(e){let t=d(e)?e:{},r={};F(t.metadata)&&(r.metadata=Fc(t.metadata));for(let[n,s]of Object.entries(t))bc.has(n)||n==="metadata"||F(s)&&(r[n]=s);return r}function jc(e){let t=d(e)?e:{},r=d(t.metadata)?t.metadata:{},n=d(r.renderedPayload)?r.renderedPayload:{};return d(t.resultContract)?t.resultContract:d(n.resultContract)?n.resultContract:{}}function bs(e){return u(jc(e).kind).toLowerCase()==="decision"}function qc(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:et(e)==="cli"}function Ss(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return Ft(t,As(e))}function Gc(e,t){let r=d(e?.metadata)?{...e.metadata}:{},n=d(r._runtimeBridge)?{...r._runtimeBridge}:{},s=Ur(n);return r._runtimeBridge={...n,promptKind:"dispatch",finalTextOnly:qc(t),releaseAfterPrompt:s===void 0?Ss(t):Ft(s,Ss(t)),requiresRuntimeResult:bs(e)},r}function Kc(e){let t=Bc(e);if(!F(t))return"";let r=JSON.stringify(Pr(t),null,2);if(r.length<=Cr)return r;let n=r.length-Cr;return`${r.slice(0,Cr)}
27
+ `):""}var le=class extends Tt{async runPrompt(t,r,n,s){let i=u(this.target.command);if(!i)throw new Error(`runtime target ${this.agent.targetCode} is missing command`);if(this.options.prepareLaunch)throw Ot("BAD_REQUEST","Codex app-server \u53EA\u652F\u6301\u5DF2\u63A5\u5165\u7684\u672C\u673A\u8BBE\u5907\uFF0C\u4E0D\u652F\u6301\u6C99\u7BB1\u542F\u52A8");let o=u(t.sessionId)||Ca(),a=K(this.target,this.agent.workspace),c=Ge(this.target,o);this.deliveryCwd=a,this.deliveryRoots=[a,...ze(this.target,c.root).trustedFileRoots],this.deliveryThreadId=s||null;let l=qe(t,this.target),p=R(this.target.timeoutMs||this.target.sessionPromptTimeoutMs,R(this.options.sessionPromptTimeoutMs,J)),m={sessionId:o,emitUpdate:r,ended:new AbortController};this.approvalTurn=m;let f=Ia(i,[...k(this.target.args),...this.taskMcp?.args||[]],{cwd:a,env:{...process.env,...d(this.target.env)?this.target.env:{},...this.taskMcp?.environment||{},ORCHA_AGENT_ID:this.agent.agentId,ORCHA_SESSION_ID:o,ORCHA_RUNTIME_ARTIFACT_DIR:c.root},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0});this.active.set(o,f),g("info","runtime.codex","app-server turn started",{target:this.agent.targetCode,sessionId:o,pid:f.pid,timeoutMs:p});let h=w=>r({sessionId:o,update:w}),_="";return f.stderr.setEncoding("utf8"),f.stderr.on("data",w=>{_=`${_}${w}`.slice(-4e3)}),await new Promise((w,I)=>{let E={threadId:null,turnId:null,items:new Map,pending:"",lastError:"",nativeModel:null},C=!1,y=(T,x)=>{C||(C=!0,clearTimeout(O),m.ended.abort(),this.approvalTurn===m&&(this.approvalTurn=null),this.active.delete(o),nt(f),Ke(c,{target:this.agent.targetCode,sessionId:o}),g("info","runtime.codex","app-server turn finished",{target:this.agent.targetCode,sessionId:o,status:T?"failed":"completed",...T?{error:String(T.message||T)}:{}}),T?I(T):w(x))},O=setTimeout(()=>y(Ot("RUNTIME_CLI_TIMEOUT",`runtime CLI timed out after ${p}ms`)),p);O.unref?.(),f.on("error",T=>y(T)),f.on("exit",(T,x)=>y(Object.assign(new Error(`Codex app-server exited before the turn completed (${x||T})${_.trim()?`: ${_.trim().slice(-500)}`:""}`),{code:"RUNTIME_CLI_EXIT_NONZERO",exitCode:T,signal:x})));let M=()=>{E.pending&&l&&h({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:E.pending}}),E.pending=""},A=Gt(f,{onRequest:async(T,x)=>{if(xa.has(T)){let S=await this.requestApproval(Sn(T,x,E.items.get(x.itemId)),{});return Rn(T,x,S?.outcome==="approved")}if(T==="mcpServer/elicitation/request")return x.serverName==="orcha"&&x.mode!=="url"?{action:"accept",content:{},_meta:null}:{action:"decline",content:null,_meta:null};throw new Error(`OrchaAI does not handle Codex request ${T}`)},onNotification:(T,x)=>{if(x.threadId&&E.threadId&&x.threadId!==E.threadId)return;let S=d(x.item)?x.item:null;if(T==="item/started"&&S){E.items.set(S.id,S);let U=ls(S);if(!U)return;M(),h({sessionUpdate:"tool_call",toolCallId:S.id,title:U,status:"in_progress",rawInput:Na(S)})}else if(T==="item/completed"&&S)E.items.set(S.id,S),S.type==="agentMessage"&&u(S.text)?(M(),S.phase==="commentary"?l&&h({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:S.text}}):E.pending=S.text):S.type==="contextCompaction"?h({sessionUpdate:"runtime_event",event:{payload:{type:"context_compacted",id:S.id}}}):ls(S)&&h({sessionUpdate:"tool_call_update",toolCallId:S.id,status:ba.has(S.status)||S.success===!1?"failed":"completed",rawOutput:Ma(S)});else if(T==="mcpServer/startupStatus/updated"&&x.name==="orcha"&&x.status==="failed")y(Ot("RUNTIME_CODEX_MCP_UNAVAILABLE",`Codex \u672A\u80FD\u8FDE\u63A5 OrchaAI \u4EFB\u52A1\u5DE5\u5177\uFF1A${u(x.error)||"\u542F\u52A8\u5931\u8D25"}`));else if(T==="error"&&x.willRetry!==!0)E.lastError=u(x.error?.message);else if(T==="turn/completed"&&(!E.turnId||x.turn?.id===E.turnId)){let U=d(x.turn)?x.turn:{};if(U.status!=="completed"){y(Ot(U.status==="interrupted"?"RUNTIME_CODEX_TURN_INTERRUPTED":"RUNTIME_CODEX_TURN_FAILED",u(U.error?.message)||E.lastError||`Codex turn ${U.status||"failed"}`));return}E.pending&&h({sessionUpdate:"agent_message_chunk",content:{type:"text",text:E.pending}}),y(null,{stopReason:"end_turn",_artifacts:[],...E.nativeModel?{nativeModel:E.nativeModel}:{}})}}});(async()=>{await A.request("initialize",{clientInfo:{name:"orcha_runtime_bridge",title:"OrchaAI Runtime Bridge",version:B},capabilities:null}),A.notify("initialized");let T=t.modelOptions,x=T?await Je(A,a):null,S=T?T.model||x.defaultModel:void 0,U=x?.models.find(xt=>xt.id===S);if(T&&(!U||T.effort&&!U.efforts.includes(T.effort)))throw Ot("RUNTIME_MODEL_OPTIONS_INVALID","The selected model or effort is no longer available on this device");let z=T?T.effort||x.defaultEffort||U.defaultEffort:void 0,b={...S?{model:S}:{}},_t=s?await A.request("thread/resume",{threadId:s,cwd:a,excludeTurns:!0,...b}):await A.request("thread/start",{cwd:a,...b}),X=u(_t?.thread?.id);if(!X)throw Ot("RUNTIME_CODEX_APP_SERVER_ERROR","Codex app-server did not return a thread");E.threadId=X,E.nativeModel=typeof _t.model=="string"?_t.model:null,this.deliveryThreadId=X,h({sessionUpdate:"runtime_event",event:{type:"thread.started",thread_id:X}});let P=await A.request("turn/start",{threadId:X,...S?{model:S}:{},...z?{effort:z}:{},input:[{type:"text",text:yt(t.prompt),text_elements:[]}]});E.turnId=u(P?.turn?.id)||null})().catch(T=>y(T))})}};var nr="ORCHA_RUNTIME_OUTPUT_START",sr="ORCHA_RUNTIME_OUTPUT_END",ir="ORCHA_RUNTIME_CONTROL_START",or="ORCHA_RUNTIME_CONTROL_END",ar=nr,cr=sr,ur=ir,lr=or,dr=[nr,sr,ir,or],Ua=new Set(["_artifacts","_decision","_meta"]),Pa=new RegExp(`(?:^|(?<=[\\r\\n]))[ \\t]*(?<marker>${dr.join("|")})[ \\t]*(?=\\r\\n?|\\n|$)`,"g"),H=class extends Error{constructor(t,r,n){super(r),this.name="RuntimeResultProtocolError",this.code=t,this.detail={rawOutput:n}}};function pr(e){let t=typeof e=="string"?e.trimStart():"";return dr.some(r=>t.startsWith(r))}function fr(e){if(typeof e!="string")return null;let t=e,r=La(t);if(![...r.values()].some(h=>h.length>0))return null;let n=[],s=[];for(let[h,_]of r)_.length===0?n.push(h):_.length>1&&s.push(h);if(n.length>0||s.length>0){let h=[];throw n.length>0&&h.push(`\u7F3A\u5C11 ${n.join(", ")}`),s.length>0&&h.push(`\u91CD\u590D ${s.join(", ")}`),new H("invalid_markers",`Runtime Result \u534F\u8BAE\u6807\u8BB0\u4E0D\u5B8C\u6574\uFF1A${h.join("\uFF1B")}`,t)}let i=r.get(nr)[0],o=r.get(sr)[0],a=r.get(ir)[0],c=r.get(or)[0];if(!(i.end<=o.start&&o.end<=a.start&&a.end<=c.start))throw new H("invalid_marker_order","Runtime Result \u534F\u8BAE\u6807\u8BB0\u987A\u5E8F\u9519\u8BEF\uFF1A\u5FC5\u987B\u5148\u8F93\u51FA OUTPUT \u5757\uFF0C\u518D\u8F93\u51FA CONTROL \u5757",t);let l=ka(t.slice(i.end,o.start));if(!l.trim())throw new H("empty_output","Runtime Result OUTPUT \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let p=t.slice(a.end,c.start).trim();if(!p)throw new H("empty_control","Runtime Result CONTROL \u5757\u4E0D\u80FD\u4E3A\u7A7A",t);let m;try{m=JSON.parse(p)}catch(h){throw new H("invalid_control_json",`Runtime Result CONTROL \u5757\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(h?.message||h)}`,t)}if(!fs(m))throw new H("invalid_control_type","Runtime Result CONTROL \u5757\u5FC5\u987B\u662F JSON \u5BF9\u8C61",t);let f=Object.keys(m).filter(h=>!Ua.has(h)).sort();if(f.length>0)throw new H("invalid_control_keys",`Runtime Result CONTROL \u5757\u5305\u542B\u975E\u6807\u51C6\u5B57\u6BB5\uFF1A${f.join(", ")}`,t);if("_artifacts"in m&&!Array.isArray(m._artifacts))throw new H("invalid_control_field_type","Runtime Result CONTROL \u5757\u7684 _artifacts \u5FC5\u987B\u662F JSON \u6570\u7EC4",t);for(let h of["_decision","_meta"])if(h in m&&!fs(m[h]))throw new H("invalid_control_field_type",`Runtime Result CONTROL \u5757\u7684 ${h} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`,t);return{output:l,...m}}function La(e){let t=new Map(dr.map(r=>[r,[]]));for(let r of e.matchAll(Pa))t.get(r.groups.marker).push({start:r.index,end:r.index+r[0].length});return t}function ka(e){let t=e.match(/^(?:\r\n|\r|\n)/)?.[0]||"",r=t?e.slice(t.length):e;return t&&r.endsWith(t)?r.slice(0,-t.length):r}function fs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}import{createHash as va}from"node:crypto";var Da="orcha.goal-contract/v1",$a=new Set(["complete","completed","done","ok","passed","success","succeeded"]),Ha=new Set(["aborted","blocked","cancelled","canceled","denied","error","failed","failure","timeout","timed_out"]),Fa=new Map([["exec_command","run_command"],["local_shell_call","run_command"],["run_command","run_command"],["apply_patch","apply_patch"],["read_file","read_file"],["list_files","list_files"],["plugin_operation","plugin_operation"]]);function _r(e){return va("sha256").update(Z(e)).digest("hex")}function hs(e){if(!_s(e))return"";let t=["The following Orcha goal contract is immutable for this turn. Do not narrow its outcome or constraints.",`<goal_contract>${JSON.stringify(e)}</goal_contract>`];return e.verificationPlan?.required===!0&&t.push("Every verification check must be satisfied by a real successful tool call from one of its toolNames.","Each check requires requiredMatches distinct successful tool call IDs; repeated updates for one call count once.","A final text claim is not verification; missing or failed tool evidence prevents completion."),t.join(`
28
+ `)}function gs(e,t,r=""){if(!_s(e))return e==null?null:{required:!0,status:"failed",outcome:u(e?.outcome),goalContractHash:"",checks:[],errorCode:"invalid_goal_contract"};let n=_r(e),s=e.verificationPlan.required===!0;if(u(r)&&u(r)!==n)return{required:s,status:"failed",outcome:e.outcome,goalContractHash:n,checks:[],errorCode:"goal_contract_hash_mismatch"};if(!s)return{required:!1,status:"not_required",outcome:e.outcome,goalContractHash:n,checks:[]};let i=Ba(t),o=e.verificationPlan.checks.map(c=>Ja(c,i));return{required:!0,status:o.some(c=>c.status==="failed")?"failed":o.some(c=>c.status==="missing")?"missing":"passed",outcome:e.outcome,goalContractHash:n,checks:o}}function _s(e){if(!d(e)||e.schemaVersion!==Da||!u(e.outcome))return!1;let t=e.verificationPlan;if(!d(t)||typeof t.required!="boolean"||!Array.isArray(t.checks)||t.required&&t.checks.length===0)return!1;let r=new Set;for(let n of t.checks)if(!d(n)||!u(n.id)||r.has(u(n.id))||(r.add(u(n.id)),!Array.isArray(n.toolNames)||n.toolNames.length===0||n.toolNames.some(s=>!u(s)))||!Number.isSafeInteger(n.requiredMatches)||n.requiredMatches<1||n.arguments!==void 0&&!d(n.arguments))return!1;return!0}function Ba(e){let t=new Map,r=[];for(let n of Array.isArray(e)?e:[]){let s=d(n?.update)?n.update:{},i=u(s.sessionUpdate);if(i==="runtime_event"){ja(s.event,t,r);continue}if(i==="tool_call"){let o=pe(s)||`tool-${r.length+1}`,a=de(t,r,o),c=hr(s,s.name||s.toolName||s.kind);a.toolName=c.toolName,a.arguments=c.arguments,a.status=Dt(s.status),a.evidence=me(s);continue}if(i==="tool_call_update"){let o=pe(s);if(!o)continue;let a=de(t,r,o),c=hr(s,s.name||s.toolName||s.kind);a.toolName||=c.toolName,Object.keys(a.arguments).length===0&&(a.arguments=c.arguments),a.status=Dt(s.status),a.evidence.push(...me(s))}}return r}function ja(e,t,r){let n=d(e)&&d(e.payload)?e.payload:d(e)?e:{},s=u(n.type);if(["function_call","custom_tool_call","local_shell_call","mcp_tool_call"].includes(s)){let a=pe(n)||`runtime-${r.length+1}`,c=de(t,r,a),l=hr(n,n.name||n.tool||s,s);c.toolName=l.toolName,c.arguments=l.arguments,c.status=Dt(n.status),c.evidence.push(...me(n));return}if(!["function_call_output","custom_tool_call_output","local_shell_call_output","mcp_tool_call_output"].includes(s))return;let i=pe(n);if(!i)return;let o=de(t,r,i);o.status=za(n,o.toolName),o.evidence.push(...me(n))}function de(e,t,r){let n=e.get(r);return n||(n={toolCallId:r,toolName:"",arguments:{},status:"unknown",evidence:[]},e.set(r,n),t.push(n)),n}function qa(e){let t=u(e).toLowerCase();return Fa.get(t)||t}function hr(e,t,r=""){let n=Ga(e),s=u(r)==="mcp_tool_call"||u(e?.kind).toLowerCase()==="mcp",i=d(e?._meta)?e._meta:{},o=u(e?.server||e?.serverName||e?.server_name||e?.mcpServer||i.server||i.serverName).toLowerCase();if(s&&o==="orcha"){let a=u(e?.tool||e?.toolName||e?.name||t);return{toolName:"plugin_operation",arguments:{...n,...a?{operationCode:a}:{}}}}return{toolName:qa(t),arguments:n}}function pe(e){return d(e)?u(e.call_id||e.callId||e.toolCallId||e.id):""}function Ga(e){if(!d(e))return{};for(let r of["arguments","args","rawInput","input","params","parameters"]){let n=Ka(e[r]);if(n)return n}let t={};for(let r of["cmd","command","cwd","operationCode","path","query","url"])e[r]!==void 0&&(t[r]=e[r]);return t}function Ka(e){if(d(e))return structuredClone(e);if(typeof e!="string")return null;try{let t=JSON.parse(e);return d(t)?t:null}catch{return null}}function za(e,t){if(!d(e))return"unknown";let r=fe(e,0,{parseCliExitCode:t==="run_command"||t==="apply_patch"});return r.includes("failed")?"failed":r.includes("success")?"success":"unknown"}function fe(e,t=0,r={}){if(t>8||e===null||e===void 0)return[];if(typeof e=="string")return Va(e,t,r);if(Array.isArray(e))return e.flatMap(o=>fe(o,t+1,r));if(!d(e))return[];let n=[];typeof e.isError=="boolean"&&n.push(e.isError?"failed":"success"),typeof e.ok=="boolean"&&n.push(e.ok?"success":"failed"),typeof e.success=="boolean"&&n.push(e.success?"success":"failed");let s=Dt(e.status);s!=="unknown"&&n.push(s);let i=e.exitCode??e.exit_code;typeof i=="number"&&Number.isFinite(i)&&n.push(i===0?"success":"failed");for(let o of["output","result","structuredContent","content"])e[o]!==void 0&&n.push(...fe(e[o],t+1,r));return n}function Va(e,t,r){let n=e.trim();if(!n)return[];try{return fe(JSON.parse(n),t+1,r)}catch{}if(r.parseCliExitCode!==!0)return[];let s=[];for(let i of n.matchAll(/(?:process\s+exited\s+with\s+code|exit\s+code\s*:?)\s*(-?\d+)/gi))s.push(Number(i[1])===0?"success":"failed");return s}function Dt(e){let t=u(e).toLowerCase();return $a.has(t)?"success":Ha.has(t)?"failed":"unknown"}function me(e){if(!d(e))return[];let t=d(e.output)?e.output:{},r=[e.verificationEvidence,d(e.verification)?e.verification.evidence:null,t.verificationEvidence,d(t.verification)?t.verification.evidence:null],n=[];for(let s of r)for(let i of Array.isArray(s)?s:s?[s]:[])!d(i)||!u(i.id)||n.push({id:u(i.id),status:Dt(i.status??(i.passed===!0?"passed":i.passed===!1?"failed":"")),...u(i.message)?{message:u(i.message)}:{}});return n}function Ja(e,t){let r=t.filter(o=>e.toolNames.includes(o.toolName)&&gr(e.arguments||{},o.arguments)),n=u(e.evidenceId),s=r.filter(o=>o.status==="success"&&(!n||o.evidence.some(a=>a.id===n&&a.status==="success")));if(s.length>=e.requiredMatches)return mr(e,"passed",s,`Runtime tool evidence passed ${s.length} times.`);let i=r.filter(o=>o.status==="failed"||n&&o.evidence.some(a=>a.id===n&&a.status==="failed"));return s.length===0&&i.length?mr(e,"failed",i,"Runtime tool evidence failed."):mr(e,"missing",s,`Only ${s.length}/${e.requiredMatches} required tool executions passed.`)}function mr(e,t,r,n){let s=r.map(i=>i.toolCallId).filter(Boolean);return{id:e.id,status:t,message:n,...u(e.description)?{description:u(e.description)}:{},toolNames:e.toolNames,requiredMatches:e.requiredMatches,observedMatches:s.length,toolCallIds:s,...d(e.arguments)?{arguments:e.arguments}:{},...u(e.evidenceId)?{evidenceId:u(e.evidenceId)}:{}}}function gr(e,t){return Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>gr(r,t[n])):d(e)?d(t)?Object.entries(e).every(([r,n])=>Object.hasOwn(t,r)&&gr(n,t[r])):!1:Object.is(e,t)}function Z(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string")return ms(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("invalid_jcs_number");return JSON.stringify(Object.is(e,-0)?0:e)}if(Array.isArray(e))return`[${Array.from({length:e.length},(t,r)=>{if(!Object.hasOwn(e,r))throw new Error("invalid_jcs_json_value");return Z(e[r])}).join(",")}]`;if(d(e))return`{${Object.keys(e).sort().map(t=>`${ms(t)}:${Z(e[t])}`).join(",")}}`;throw new Error("invalid_jcs_json_value")}function ms(e){return Wa(e),JSON.stringify(e)}function Wa(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw new Error("invalid_jcs_unicode");t+=1}else if(r>=56320&&r<=57343)throw new Error("invalid_jcs_unicode")}}import{spawn as Xa}from"node:child_process";import{createHash as Ya,randomUUID as Qa}from"node:crypto";import{constants as Za}from"node:fs";import{access as tc,mkdir as yr,readdir as ec,realpath as $t,rm as rc,stat as nc}from"node:fs/promises";import sc from"node:http";import{tmpdir as ic}from"node:os";import{isAbsolute as Ht,join as St,relative as ys,resolve as Tr}from"node:path";var Er=1,oc="orcha.process-isolation/v1",Or="orcha.egress-proxy/v1",ac="--disable-wasm-trap-handler",he={read_only:0,workspace_write:1,workspace_network:2},wr={read_only:["read_only","denied"],workspace_write:["workspace_write","denied"],workspace_network:["workspace_write","restricted"]},cc=new Set([".env",".git-credentials",".netrc",".npmrc",".pypirc","credentials.json","secrets.json","id_rsa","id_ed25519"]);function ft(e){if(!d(e))throw N("RUNTIME_SANDBOX_POLICY_REQUIRED","sandboxPolicy is required");let t=structuredClone(e),r=u(t.accessMode),n=u(t.accessModeCeiling);if(!(r in wr)||!(n in wr))throw N("RUNTIME_SANDBOX_POLICY_INVALID","unsupported runtime access mode");if(he[r]>he[n])throw N("RUNTIME_SANDBOX_POLICY_INVALID","access mode exceeds its ceiling");let[s,i]=wr[r];if(t.filesystemMode!==s||t.networkMode!==i)throw N("RUNTIME_SANDBOX_POLICY_INVALID","runtime access profile does not match its mode");if(Number(t.policySchemaVersion)!==Er||!Number.isInteger(Number(t.policyRevision))||Number(t.policyRevision)<1)throw N("RUNTIME_SANDBOX_POLICY_INVALID","unsupported sandbox policy schema or revision");for(let[a,c]of Object.entries({outsideWorkspaceAccess:"denied",hostAccess:"denied",hostEnvironmentAccess:"denied",dockerSocketAccess:"denied",environmentMode:"allowlist"}))if(t[a]!==c)throw N("RUNTIME_SANDBOX_POLICY_INVALID",`${a} cannot be relaxed`);let o=d(t.processIsolation)?t.processIsolation:{};if(o.mode!=="required"||o.backend==="direct")throw N("RUNTIME_SANDBOX_POLICY_INVALID","strong process isolation is required");if(Array.isArray(t.alwaysApprovedApprovalKeys)&&t.alwaysApprovedApprovalKeys.length)throw N("RUNTIME_SANDBOX_POLICY_INVALID","persistent runtime approvals are forbidden");return t}function ws(e,t){let r=ft(e),n=ft(t);return he[n.accessMode]<he[r.accessMode]}async function Ts(e){if(!e.sandboxRequired)return{dispatchable:!0,enforced:!1,backend:"direct",daemonStatus:"not_required",daemonProtocolVersion:"",policySchemaVersions:[Er],runtimePolicyUpdates:!1,workspaceSync:!1,egressProxy:!1,reason:"external_runtime_sandbox_not_required"};let t=await Os(e.sandboxBrokerCommand,process.env.PATH||"");if(!t)throw N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let r=await fc(t,k(e.sandboxBrokerArguments),e.sandboxProbeTimeoutMs);if(r.enforced!==!0||u(r.protocolVersion)!=="orcha.runtime-sandbox-broker/v1"||!["bubblewrap","broker"].includes(u(r.backend)))throw N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker did not report enforced isolation");let n=d(r.probes)?r.probes:{};for(let s of["emptyRoot","outsideWorkspaceDenied","hostFilesystemDenied","sensitiveFilesDenied","environmentAllowlist","dockerSocketDenied","networkNamespace","workspaceReadOnly","workspaceWrite","resourceLimits"])if(n[s]!==!0)throw N("RUNTIME_SANDBOX_UNAVAILABLE",`sandbox broker probe failed: ${s}`);return e.egressProxyRequired&&await gc(e),{dispatchable:!0,enforced:!0,backend:u(r.backend),daemonStatus:"ok",daemonProtocolVersion:u(r.protocolVersion||"orcha.runtime-sandbox-broker/v1"),policySchemaVersions:[Er],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:e.egressProxyRequired}}async function Sr(e,t,r){let n=u(t.workspace||t.cwd),s=u(r),i=n||(t.allowRequestWorkspace===!0?s:"");if(!i||!Ht(i))throw N("RUNTIME_WORKSPACE_NOT_CONFIGURED","runtime target must configure an absolute trusted workspace");let o=await $t(i);if(!(await nc(o)).isDirectory())throw N("RUNTIME_WORKSPACE_INVALID","runtime workspace is not a directory");if(!(e.trustedWorkspaceRoots.length?await Promise.all(e.trustedWorkspaceRoots.map(l=>$t(l))):[o]).some(l=>Ir(l,o)))throw N("RUNTIME_WORKSPACE_OUTSIDE_TRUSTED_ROOT","runtime workspace is outside trusted roots");return o}async function Es({config:e,target:t,command:r,args:n,cwd:s,environment:i,runId:o,agentId:a,sessionId:c,sandboxPolicy:l}){if(!e.sandboxRequired)return{command:r,args:[...n],cwd:s,environment:{...process.env,...i},tempDirectory:"",isolation:{enforced:!1,backend:"development_direct"},cleanup:async()=>{}};let p=ft(l),m=await Sr(e,t,s),f=await $t(s);if(!Ir(m,f))throw N("RUNTIME_WORKSPACE_CWD_INVALID","runtime cwd is outside its workspace");let h=await Os(e.sandboxBrokerCommand,process.env.PATH||"");if(!h)throw N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox broker is not executable");let _=`runtime-${Ya("sha256").update(String(o)).digest("hex").slice(0,32)}`,w=Tr(e.sandboxTempRoot||St(ic(),"orcha-runtime-sandboxes"));await yr(w,{recursive:!0,mode:448});let I=St(w,`${_}-${Qa()}`),E=St(I,"home"),C=St(I,"artifacts");await yr(E,{recursive:!0,mode:448}),await yr(C,{recursive:!0,mode:448});let y=p.networkMode==="restricted"?await mc(e,{runId:String(o),instanceId:_,policyRevision:Number(p.policyRevision),ttlMs:Math.min(R(p.maxRuntimeSeconds,900)*1e3,e.egressGrantMaxTtlMs),maxTransferBytes:R(p.maxNetworkBytes,64*1024*1024)}):null,O={PATH:u(i.PATH||process.env.PATH),LANG:u(i.LANG||process.env.LANG||"C.UTF-8"),HOME:"/tmp/home",TMPDIR:"/tmp",USER:"orcha",LOGNAME:"orcha",SHELL:"/bin/sh",ORCHA_AGENT_ID:String(a),ORCHA_SESSION_ID:String(c),ORCHA_RUN_ID:String(o),ORCHA_RUNTIME_ARTIFACT_DIR:"/tmp/artifacts",...lc(t,i)};O.HOME="/tmp/home",O.TMPDIR="/tmp",O.ORCHA_RUNTIME_ARTIFACT_DIR="/tmp/artifacts",O.NODE_OPTIONS=ac;let M={schemaVersion:oc,runId:String(o),instanceId:_,workspace:m,cwd:f,filesystemMode:p.filesystemMode,networkMode:p.networkMode,environmentMode:"allowlist",deniedRelativePaths:await dc(m),temporaryDirectory:I,egressProxy:y,environment:O,resourceLimits:pc(p),readOnlyToolchainRoots:await uc(e,t)},A=!1,T=async()=>{if(!A){A=!0;try{y&&await hc(e,y,{runId:String(o),instanceId:_})}finally{await rc(I,{recursive:!0,force:!0})}}};return{command:h,args:[...k(e.sandboxBrokerArguments),"--",r,...n],cwd:f,environment:{PATH:process.env.PATH||"",LANG:process.env.LANG||"C.UTF-8",ORCHA_PROCESS_ISOLATION_REQUEST:JSON.stringify(M)},tempDirectory:I,homeDirectory:E,artifactDirectory:C,pathMappings:[{runtimeRoot:"/tmp/artifacts",hostRoot:C},{runtimeRoot:"/tmp/home",hostRoot:E}],isolation:{enforced:!0,backend:"broker",instanceId:_,policyRevision:p.policyRevision},cleanup:T}}async function uc(e,t){let r=k(t.toolchainRoots||t.sandboxToolchainRoots);if(!r.length)return[];let n=await Promise.all(k(e.trustedToolchainRoots).map(i=>$t(i)));if(!n.length)throw N("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","target toolchain roots require ORCHA_RUNTIME_TRUSTED_TOOLCHAIN_ROOTS");let s=[];for(let i of r){if(!Ht(i))throw N("RUNTIME_TOOLCHAIN_ROOT_INVALID","toolchain roots must be absolute");let o=await $t(i);if(!n.some(a=>Ir(a,o)))throw N("RUNTIME_TOOLCHAIN_ROOT_NOT_TRUSTED","toolchain root is outside trusted roots");s.push(o)}return[...new Set(s)]}function lc(e,t){let r=d(e.env)?e.env:{},n={};for(let[s,i]of Object.entries(r))/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&i!=null&&(n[s]=String(i));for(let s of["ORCHA_RUNTIME_PROMPT","ORCHA_RUNTIME_ARTIFACT_DIR"])t[s]!=null&&(n[s]=String(t[s]));return n}async function dc(e){let t=[],r=0,n=async s=>{let i;try{i=await ec(s,{withFileTypes:!0})}catch(o){if(s===e)throw o;return}for(let o of i){if(r+=1,r>1e4)throw N("RUNTIME_WORKSPACE_SCAN_LIMIT_EXCEEDED","workspace contains more than 10000 entries");let a=St(s,o.name),c=ys(e,a),l=o.name.toLowerCase();(cc.has(l)||l.startsWith(".env."))&&t.push(c),o.isDirectory()&&!o.isSymbolicLink()&&await n(a)}};return await n(e),t.sort()}function pc(e){return{maxCpuSeconds:Math.max(1,R(e.maxRuntimeSeconds,900)),maxMemoryBytes:R(e.maxMemoryBytes,2*1024*1024*1024),maxProcesses:R(e.maxProcesses,128),maxOpenFiles:R(e.maxOpenFiles,1024),maxFileBytes:R(e.maxFileBytes,64*1024*1024)}}async function fc(e,t,r){return await new Promise((n,s)=>{let i=Xa(e,[...t,"--probe"],{env:{PATH:process.env.PATH||"",LANG:"C.UTF-8"},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=[],a=[];i.stdout.on("data",l=>o.push(Buffer.from(l))),i.stderr.on("data",l=>a.push(Buffer.from(l)));let c=setTimeout(()=>i.kill("SIGKILL"),Math.max(1e3,r));i.once("error",s),i.once("close",l=>{if(clearTimeout(c),l!==0){s(N("RUNTIME_SANDBOX_UNAVAILABLE",Buffer.concat(a).toString("utf8").trim()||`sandbox probe exited with ${l}`));return}try{n(JSON.parse(Buffer.concat(o).toString("utf8")))}catch{s(N("RUNTIME_SANDBOX_UNAVAILABLE","sandbox probe returned invalid JSON"))}})})}async function Os(e,t){let r=u(e);if(!r)return"";let n=Ht(r)?[r]:String(t||"").split(":").filter(Boolean).map(s=>St(s,r));for(let s of n)try{return await tc(s,Za.X_OK),s}catch{}return""}async function mc(e,t){if(!e.egressProxyRequired)throw N("RUNTIME_EGRESS_UNAVAILABLE","restricted network requires the Egress Proxy");let r=await Rr(e,"POST","/v1/grants",{protocolVersion:Or,...t}),n={socketPath:e.egressProxySocket,grantId:u(r.grantId),credential:u(r.credential)};if(!n.grantId||!n.credential)throw N("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy returned an invalid grant");return n}async function hc(e,t,r){await Rr(e,"POST",`/v1/grants/${encodeURIComponent(t.grantId)}/revoke`,{protocolVersion:Or,...r}).catch(()=>{})}async function gc(e){let t=await Rr(e,"GET","/health");if(t.status!=="ok"||t.proxy!=="orcha-egress-proxy"||t.protocolVersion!==Or)throw N("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy is unavailable or incompatible")}async function Rr(e,t,r,n){if(!Ht(e.egressProxySocket)||!e.egressProxyToken)throw N("RUNTIME_EGRESS_UNAVAILABLE","Egress Proxy socket and token are required");return await new Promise((s,i)=>{let o=sc.request({socketPath:e.egressProxySocket,path:r,method:t,headers:{Authorization:`Bearer ${e.egressProxyToken}`,Accept:"application/json",...n?{"Content-Type":"application/json"}:{}}},a=>{let c=[],l=0;a.on("data",p=>{l+=p.length,l>1048576?o.destroy(new Error("egress response is too large")):c.push(Buffer.from(p))}),a.once("end",()=>{try{let p=JSON.parse(Buffer.concat(c).toString("utf8")||"{}");(a.statusCode||500)>=400?i(N("RUNTIME_EGRESS_UNAVAILABLE",u(p.error)||"Egress Proxy rejected the request")):s(p)}catch(p){i(p)}})});o.once("error",i),o.setTimeout(3e3,()=>o.destroy(new Error("Egress Proxy request timed out"))),n?o.end(JSON.stringify(n)):o.end()})}function Ir(e,t){let r=ys(Tr(e),Tr(t));return r===""||!r.startsWith("..")&&!Ht(r)}function N(e,t){return Object.assign(new Error(t),{code:e})}var Cr=24e3,xr=8,Ar=50,br=6e3,yc=new Set(["fail","failed","failure","error","errored","timeout","timed_out","cancelled","canceled","aborted"]),wc=10*60*1e3,Tc=60*1e3,Ec=8,Oc=30*60*1e3,Sc=100,Rc=new Set(["agent_message_chunk","agent_thought_chunk"]),Ic=60*1e3,Cc=1,Cs=2400,xc=new Set(["max_tokens","max_output_tokens","length"]),Ac=new Set(["agent_message_chunk","tool_call","tool_call_update"]),bc=new Set(["agentId","taskId","executionId","sessionId","nodeId","targetCode","framework","workspace","instructions"]),Nc=/(^|[_-])(token|secret|password|authorization|api[-_]?key|private[-_]?key|credential|cookie|jwt|access[-_]?token|refresh[-_]?token|service[-_]?token|execution[-_]?token)([_-]|$)/i;function Mc(e){if(!d(e))return{};let t={};for(let r of["name","code","serverName","serverCode","type","transport","url","command","protocolVersion"]){let n=u(e[r]);n&&(t[r]=n)}return t}function Uc(e){return(Array.isArray(e)?e:[]).map(Mc).sort((t,r)=>{let n=Z(t),s=Z(r);return n<s?-1:n>s?1:0})}function Pc(e){return!d(e)||e.verificationPlan?.required!==!0?!1:(Array.isArray(e.verificationPlan.checks)?e.verificationPlan.checks:[]).some(r=>d(r)&&Array.isArray(r.toolNames)&&r.toolNames.some(n=>u(n)==="plugin_operation"))}function Lc(e,t,r){let n=d(e?._meta)?e._meta:{};return{...d(e)?e:{},sessionId:t,update:d(e?.update)?e.update:{},_meta:{...n,orchaAgentId:r.agentId,runtimeSessionId:r.runtimeSessionId,bridgeUpdateId:_e()}}}function kc(e){if(!d(e)||Object.keys(e).some(n=>n!=="sessionId"&&n!=="update"))return"";let t=e.update,r=d(t)?t.content:null;return!Rc.has(t?.sessionUpdate)||Object.keys(t).length!==2?"":d(r)&&r.type==="text"&&typeof r.text=="string"&&Object.keys(r).length===2?t.sessionUpdate:""}function vc(e){let t=null,r=null,n=()=>{r&&clearTimeout(r),r=null;let i=t;t=null,i&&e(i)};return{push:i=>{let o=kc(i),a=o?i.update.content.text:"",c=t?.update.content.text;if(t&&o===t.update.sessionUpdate&&i.sessionId===t.sessionId&&!a.startsWith(c)&&!pr(a)){t.update.content.text=c+a;return}if(n(),!o){e(i);return}t={...i,update:{...i.update,content:{...i.update.content}}},r=setTimeout(n,Sc),r.unref?.()},flush:n}}function F(e){return e==null||e===""?!1:typeof e=="string"?u(e)!=="":Array.isArray(e)?e.length>0:d(e)?Object.keys(e).length>0:!0}function xs(e){let t=u(e).toLowerCase().replace(/[.。!!]+$/g,"").replace(/[\s-]+/g,"_");return yc.has(t)}function it(e,t){let r=R(e,t);return Number.isFinite(r)&&r>0?r:t}function Ft(e,t=!1){if(typeof e=="boolean")return e;let r=u(e).toLowerCase();return["true","1","yes","y","on"].includes(r)?!0:["false","0","no","n","off"].includes(r)?!1:t}function et(e){return u(e?.type||"echo")}function As(e){let t=et(e);return t==="acp"||t==="stdio-acp"||t==="openclaw"}function Ur(e){if(d(e)){if(Object.prototype.hasOwnProperty.call(e,"releaseAfterPrompt"))return e.releaseAfterPrompt;if(Object.prototype.hasOwnProperty.call(e,"disposeAfterPrompt"))return e.disposeAfterPrompt}}function Dc(e){let t=String(e||"");if(Nc.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 Pr(e,t=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(e.length<=br)return e;let r=e.length-br;return`${e.slice(0,br)}... [truncated ${r} characters]`}if(t>=xr)return Array.isArray(e)?`[array truncated at depth ${xr}, items=${e.length}]`:d(e)?`[object truncated at depth ${xr}, keys=${Object.keys(e).length}]`:String(e);if(Array.isArray(e)){let r=e.slice(0,Ar).map(n=>Pr(n,t+1));return e.length>Ar&&r.push(`[truncated ${e.length-Ar} items]`),r}if(d(e)){let r={};for(let[n,s]of Object.entries(e))r[n]=Dc(n)?"[REDACTED]":Pr(s,t+1);return r}return String(e)}var $c=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 Hc(e){if(!d(e))return e;let t={};for(let r of $c)F(e[r])&&(t[r]=e[r]);return t}function Fc(e){if(!d(e))return e;let t={...e};return d(t.renderedPayload)&&(t.renderedPayload=Hc(t.renderedPayload)),t}function Bc(e){let t=d(e)?e:{},r={};F(t.metadata)&&(r.metadata=Fc(t.metadata));for(let[n,s]of Object.entries(t))bc.has(n)||n==="metadata"||F(s)&&(r[n]=s);return r}function jc(e){let t=d(e)?e:{},r=d(t.metadata)?t.metadata:{},n=d(r.renderedPayload)?r.renderedPayload:{};return d(t.resultContract)?t.resultContract:d(n.resultContract)?n.resultContract:{}}function bs(e){return u(jc(e).kind).toLowerCase()==="decision"}function qc(e){return e?.dispatchFinalTextOnly===!0||e?.dispatchFinalOutputOnly===!0?!0:e?.dispatchFinalTextOnly===!1||e?.dispatchFinalOutputOnly===!1?!1:et(e)==="cli"}function Ss(e){let t=e?.dispatchReleaseAfterPrompt??e?.dispatchDisposeAfterPrompt;return Ft(t,As(e))}function Gc(e,t){let r=d(e?.metadata)?{...e.metadata}:{},n=d(r._runtimeBridge)?{...r._runtimeBridge}:{},s=Ur(n);return r._runtimeBridge={...n,promptKind:"dispatch",finalTextOnly:qc(t),releaseAfterPrompt:s===void 0?Ss(t):Ft(s,Ss(t)),requiresRuntimeResult:bs(e)},r}function Kc(e){let t=Bc(e);if(!F(t))return"";let r=JSON.stringify(Pr(t),null,2);if(r.length<=Cr)return r;let n=r.length-Cr;return`${r.slice(0,Cr)}
29
29
  ... [truncated ${n} characters]`}function kr(e){if(!d(e))return"";let t=d(e.update)?e.update:e,n=(d(t.content)?t.content:{}).text??t.text;return n==null?"":String(n)}function Lr(e){if(!d(e))return"";let t=d(e.update)?e.update:e;return u(t.sessionUpdate)}function vr(e){if(!Array.isArray(e))return"";let t=!1,r=[],n=[],s=[],i=()=>{r.length>0&&(n.push(r),r=[])};for(let a of e){let c=Lr(a),l=kr(a);if(!c){l&&s.push(l);continue}if(t=!0,c==="agent_message_chunk"){l&&r.push(l);continue}if(c==="agent_message_snapshot"){n.length=0,r=l?[l]:[];continue}(c==="agent_thought_chunk"||c==="user_message_chunk"||c==="tool_call"||c==="tool_call_update"||c==="plan")&&i()}if(i(),!t)return Rt(s);let o=n[n.length-1]||[];return Rt(o)}function zc(e){return Array.isArray(e)?e.map(kr).filter(t=>t!==""):[]}function ye(e){return Array.isArray(e)?e.some(r=>Lr(r))?e.filter(r=>Ac.has(Lr(r))).map(kr).filter(r=>r!==""):zc(e):[]}function Vc(e){if(!d(e))return null;let t=d(e.update)?e.update:e;return u(t.sessionUpdate)!=="runtime_event"?null:d(t.event)?t.event:null}function Jc(e){if(!d(e))return"";let t=d(e.payload)?e.payload:{},r=u(e.type),n=u(t.type);if(r==="event_msg"){if(n==="task_complete")return u(t.last_agent_message||t.message||t.output);if(n==="agent_message"){let s=u(t.phase||t.status||t.stage).toLowerCase();if(["final_answer","final","complete","completed","done"].includes(s))return u(t.message||t.text||t.content)}}return""}function Wc(e){if(!Array.isArray(e))return"";for(let t=e.length-1;t>=0;t-=1){let r=Jc(Vc(e[t]));if(r)return r}return""}function Rt(e){let t="";for(let r of e){let n=String(r||"");if(n)if(!t)t=n;else if(n.length>t.length&&n.startsWith(t))t=n;else{let s=pr(n)&&!/[\r\n]$/.test(t)?`
30
30
  `:"";t+=`${s}${n}`}}return t.trim()}function Xc(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]===`
31
- `?1:0)).trim()}function Rs(e){let t=String(e||"").trim();if(!t)return null;try{let r=JSON.parse(t);if(d(r)&&(Ns(r)||F(r._artifacts)||F(r.artifacts)||F(r._decision)||F(r._meta)))return r}catch{}return null}function Bt(e){try{return fr(e)}catch{return null}}function ge(...e){let t=null;for(let r of e)try{if(fr(r))return}catch(n){t||=n}if(t)throw t}function Nr(e){let t=String(e||"").trim();if(!t)return null;let r=Bt(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=Rs(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=Rs(t.slice(s));if(i)return i}return null}function Yc(e){let t=Bt(vr(e));if(t)return t;let r=ye(e);for(let n=r.length-1;n>=0;n-=1){let s=Bt(r[n]);if(s)return s}return Bt(Rt(r))}function Ns(e){if(!d(e))return!1;if(F(e.output))return!0;for(let t of["content","text","message","summary"])if(u(e[t]))return!0;return!!(xs(e.status)||u(e.error)||u(e.errorMessage))}function W(e){let t=d(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 Qc(e){return d(e)?typeof(d(e._decision)?e._decision:d(e.decision)?e.decision:e).passed=="boolean":!1}function Ms(e){return d(e)?d(e._decision)&&typeof e._decision.passed=="boolean"?!0:Qc(e.output):!1}function Mr(e,t,r){let n=d(e)?{...e}:{};if(!F(n.output)){for(let s of["summary","message","content","text"])if(u(n[s])){n.output=u(n[s]);break}}return!F(n.output)&&u(r)&&(n.output=u(r)),{...n,_meta:{...d(n._meta)?n._meta:{},runtimeOutputSource:t,requiredRuntimeResult:!0,finalMessagePreview:u(r).slice(0,1e3)}}}var Zc=["dataUrl","dataURL","contentDataUrl","contentDataURL","contentBase64","base64","data"];function Is(e){if(!d(e))return"";let t=d(e.content)?e.content:{},r=d(e.metadata)?e.metadata:{};return u(e.fieldKey||e.field_key||t.fieldKey||r.fieldKey)}function tu(e,t){let r=d(e.content)?e.content:{},n=d(t.content)?t.content:{},s={...e,...t,content:{...r,...n},metadata:{...d(e.metadata)?e.metadata:{},...d(t.metadata)?t.metadata:{}}};for(let i of Zc)F(e[i])&&(s[i]=e[i]),F(r[i])&&(s.content[i]=r[i]);return s}function Us(e,t){let r=Array.isArray(e)?e.filter(d):[],n=Array.isArray(t)?t.filter(d):[];if(!r.length)return n;if(!n.length)return r;let s=[...r],i=new Map;for(let a=0;a<r.length;a+=1){let c=Is(r[a]),l=i.get(c)||[];l.push(a),i.set(c,l)}let o=new Map;for(let a of n){let c=Is(a),l=o.get(c)||0;o.set(c,l+1);let p=i.get(c)?.[l];p===void 0?s.push(a):s[p]=tu(s[p],a)}return s}function tt(e,t,r){let n={...e,...t,_meta:{...d(e._meta)?e._meta:{},...d(t._meta)?t._meta:{},runtimeOutputSource:r}};return(Array.isArray(e._artifacts)||Array.isArray(t._artifacts))&&(n._artifacts=Us(e._artifacts,t._artifacts)),n}function Ps(e,t,r={}){let n=u(r.promptKind),s=r.requiresRuntimeResult===!0,i=s||n==="dispatch",o=W(e),a=typeof o.output=="string"?Bt(o.output):null;if(a)return tt(o,W(a),"result_block");let c=Wc(t),l=c?Nr(c):null,p=i?Yc(t):null;if(Ns(o))return xs(o.status)||u(o.error)||u(o.errorMessage)?o:n==="dispatch"&&l?tt(o,W(l),"final_event"):n==="dispatch"&&p?tt(o,W(p),"updates"):!s||Ms(o)?o:l?tt(o,W(l),"final_event"):p?tt(o,W(p),"updates"):(ge(o.output,c,Rt(ye(t))),Mr(o,"result",o.output));if(l)return tt(o,W(l),"final_event");if(p)return tt(o,W(p),"updates");if(c)return s?(ge(c,Rt(ye(t))),Mr(o,"final_event",c)):{...o,output:c,_meta:{...d(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let m=vr(t),f=Nr(m);if(f)return tt(o,W(f),"updates");let h=Xc(m);if(!h)return s&&ge(Rt(ye(t))),o;let g=Nr(h);return g?tt(o,W(g),"updates"):s?(ge(m,h),Mr(o,"updates",h)):{...o,output:h,_meta:{...d(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}function Dr(e){return d(e)?u(e.stopReason||e.stop_reason).toLowerCase():""}function Ls(e){return xc.has(Dr(e))}function eu(e,t,r){if(r.promptKind!=="dispatch"||r.requiresRuntimeResult!==!0||!Ls(e))return!1;try{return!Ms(Ps(e,t,r))}catch{return!0}}function ru(){return["Your previous final response reached the output limit before the Runtime Result protocol was complete.","Re-emit the complete final Runtime Result from scratch using the conclusion you already reached.","Do not repeat analysis, process notes, tool calls, or task work.",`Keep the OUTPUT report within ${Cs} Unicode characters.`,`Output ${ar}, ${cr}, ${ur}, and ${lr} on their own lines.`,"The CONTROL block must be valid JSON containing _decision and must be fully closed.","Return only the two protocol blocks."].join(`
32
- `)}function nu(e,t){let r=d(t)?{...t}:{},n=Us(e?._artifacts,t?._artifacts);return n.length>0&&(r._artifacts=n),r}function su(e,t){return{...e,_meta:{...d(e?._meta)?e._meta:{},runtimeProtocolRetry:{attempted:!0,recovered:!0,reason:Dr(t)||"max_tokens"}}}}function iu(e,t){let r=typeof e?.output=="string"?e.output:vr(t),n=new H("runtime_output_truncated","Runtime Result \u8FBE\u5230\u6700\u5927\u8F93\u51FA\u957F\u5EA6\uFF0C\u7D27\u51D1\u91CD\u8BD5\u540E\u4ECD\u672A\u5B8C\u6574\u8FD4\u56DE",r);return n.detail={...n.detail,stopReason:Dr(e)||"max_tokens",retryAttempted:!0},n}var we=class{constructor(t){this.config=t,this.targets=t.targets||{},this.agents=new Map,this.sessions=new Map,this.startingSessions=new Set,this.targetReservations=new Map,this.runtimeSessionIndex=new Map,this.pendingPermissions=new Map,this.operations=new Map,this.startedAt=Mt(),this.sandboxCapabilities={dispatchable:t.sandboxRequired!==!0,enforced:!1,backend:t.sandboxRequired?"unavailable":"direct",daemonStatus:t.sandboxRequired?"pending":"not_required",policySchemaVersions:[1],runtimePolicyUpdates:t.sandboxRequired===!0,workspaceSync:!1,egressProxy:!1},this.cleanupTimer=null,this.onCapacityChanged=null,this.startSessionCleanup()}async start(){try{this.sandboxCapabilities=await Ts(this.config)}catch(t){this.sandboxCapabilities={...this.sandboxCapabilities,dispatchable:!1,enforced:!1,backend:"unavailable",daemonStatus:"unavailable",reason:u(t?.code||t?.message||t)||"sandbox_probe_failed"},_("error","runtime-bridge","runtime node sandbox probe failed; node will not accept work",{reason:this.sandboxCapabilities.reason})}return this.sandboxCapabilities}assertDispatchable(){if(this.config.sandboxRequired&&!(this.sandboxCapabilities.dispatchable===!0&&this.sandboxCapabilities.enforced===!0))throw Object.assign(new Error("runtime node strong sandbox is unavailable"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"})}operationIdentity(t,r,n){let s=d(t.goalContract)?_r(t.goalContract):u(t.goalContractHash),i=_c("sha256").update(Z({prompt:Array.isArray(t.prompt)?t.prompt:[],mcpServers:Uc(t.mcpServers),metadata:d(t.metadata)?t.metadata:{},modelOptions:d(t.modelOptions)?t.modelOptions:null})).digest("hex");return{agentId:r,runId:u(t.runId),sessionId:n,targetCode:u(t.targetCode||t.framework),workspace:u(t.workspace),goalContractHash:s,requestHash:i}}assertOperationIdentity(t,r,n,s){let i=this.operationIdentity(r,n,s),o=Object.keys(t.identity).find(a=>t.identity[a]!==i[a]);if(o)throw Object.assign(new Error(`runtime operation correlation conflict: ${t.correlationId}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT",field:o})}createOperation(t,r,n,s){let i={correlationId:t,agentId:n,sessionId:s,identity:this.operationIdentity(r,n,s),sandboxPolicy:d(r.sandboxPolicy)?structuredClone(r.sandboxPolicy):null,status:"running",updates:[],listeners:new Set,waiters:[],response:null,error:null,mcpServers:r.mcpServers,createdAtMs:Date.now(),completedAtMs:null};return this.operations.set(t,i),i}async attachOperation(t,r={}){let n=()=>{if(r.onUpdate)for(let s of t.updates)r.onUpdate(s)};if(t.status==="completed")return n(),t.response;if(t.status==="failed")throw n(),t.error;r.onUpdate&&t.listeners.add(r.onUpdate);try{return n(),await new Promise((s,i)=>t.waiters.push({resolve:s,reject:i}))}finally{r.onUpdate&&t.listeners.delete(r.onUpdate)}}completeOperation(t,r){if(t.status==="running"){t.status="completed",t.response=r,t.mcpServers=null,t.completedAtMs=Date.now();for(let n of t.waiters.splice(0))n.resolve(r);t.listeners.clear()}}promptResponse(t,r,n,s,i,o=s){let a=d(t.metadata)?t.metadata:{},c=d(a._runtimeBridge)?a._runtimeBridge:{},l=a.source==="channel_message"?i:Ps(i,o,c),p=gs(t.goalContract,s,t.goalContractHash);return{sessionId:n,runtimeSessionId:r.runtimeSessionId,result:l,updates:s,...p?{verification:p}:{}}}failOperation(t,r){if(t.status!=="running")return;let n=r instanceof Error?r:Object.assign(new Error(String(r||"runtime operation failed")),{code:"RUNTIME_NODE_ERROR"});t.status="failed",t.error=n,t.mcpServers=null,t.completedAtMs=Date.now();for(let s of t.waiters.splice(0))s.reject(n);t.listeners.clear()}cleanupOperations(t=Date.now()){let r=it(this.config.operationTtlMs,Oc);for(let[n,s]of this.operations)s.status!=="running"&&t-(s.completedAtMs||s.createdAtMs)>r&&this.operations.delete(n)}targetFor(t){let r=u(t)||this.config.defaultTargetCode,n=this.targets[r];if(!r||!d(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=et(t)==="openclaw"?it(this.config.openClawSessionIdleTtlMs,Ic):it(this.config.sessionIdleTtlMs,wc);return it(t?.sessionIdleTtlMs??t?.idleTtlMs,n)}targetMaxSessions(t){let n=et(t)==="openclaw"?it(this.config.openClawMaxSessions,Cc):it(this.config.maxSessionsPerTarget,Ec);return it(t?.maxSessions,n)}targetReservationCount(t){return Number(this.targetReservations.get(t)||0)}notifyCapacityChanged(){try{this.onCapacityChanged?.()}catch(t){_("warn","runtime-bridge","capacity heartbeat callback failed",{error:String(t)})}}targetCapacitySnapshot(t=!0){return Object.entries(this.targets).map(([r,n])=>{let s=[...this.sessions.values()].filter(p=>p.targetCode===r),i=s.filter(p=>p.busy).length,o=s.length-i,a=this.targetReservationCount(r),c=this.targetMaxSessions(n),l=t?Math.max(0,c-i-a):0;return{targetCode:r,targetName:u(n?.name||n?.targetName||r),targetType:u(n?.type||"echo"),status:t?l>0?"available":"busy":"unavailable",maxSessions:c,busySessions:i,idleSessions:o,reservedSessions:a,availableSessions:l}})}targetReleaseAfterPrompt(t,r={}){let n=et(t),s=d(r?._runtimeBridge)?r._runtimeBridge:{},i=Ur(s);return i!==void 0?Ft(i,!1):Ft(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}promptReleaseAfterPrompt(t,r={}){if(this.config.sandboxRequired)return!0;let n=d(r?._runtimeBridge)?r._runtimeBridge:{},s=Ur(n);return s!==void 0?Ft(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=it(this.config.sessionCleanupIntervalMs,Tc);t<=0||(this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions().catch(r=>{_("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){_("warn","runtime-bridge","runtime session stop failed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,error:String(s)})}return this.sessions.delete(t),this.runtimeSessionIndex.delete(`${n.agentId}:${n.runtimeSessionId}`),this.notifyCapacityChanged(),_("info","runtime-bridge","runtime session closed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,reason:r}),!0}async closeAllSessions(t="bridge_shutdown"){for(let r of[...this.sessions.keys()])await this.closeSession(r,t)}async stop(t="bridge_stop"){this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=null,await this.closeAllSessions(t)}async cleanupExpiredSessions(t=Date.now()){for(let[r,n]of[...this.sessions.entries()])n.busy||t-(n.lastUsedAtMs||n.createdAtMs||t)>n.idleTtlMs&&await this.closeSession(r,"idle_timeout")}async reserveTargetSlot(t,r){let n=this.targetMaxSessions(r);for(;this.sessionCountForTarget(t)+this.targetReservationCount(t)>=n;){let s=this.idleTargetSessions(t);if(!s.length){let i=new Error(`runtime target session limit reached: ${t}`);throw i.code="RUNTIME_TARGET_SESSION_LIMIT",i}await this.closeSession(s[0][0],"target_session_limit")}this.targetReservations.set(t,this.targetReservationCount(t)+1),this.notifyCapacityChanged()}releaseTargetSlot(t){let r=Math.max(0,this.targetReservationCount(t)-1);r>0?this.targetReservations.set(t,r):this.targetReservations.delete(t),this.notifyCapacityChanged()}async createAgent(t){let r=u(t.agentId);if(!r)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});let{code:n,target:s}=this.targetFor(t.targetCode||t.framework),i=this.agents.get(r);if(i&&i.targetCode!==n)throw Object.assign(new Error(`runtime agent target conflict: ${r}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});let o=this.config.sandboxRequired?await Sr(this.config,s,t.workspace):u(t.workspace),a={agentId:r,targetCode:n,framework:u(t.framework||n),workspace:o,metadata:d(t.metadata)?t.metadata:{},createdAt:Mt(),runtimeKind:et(s)};return this.agents.set(r,a),{agent:a}}runtimeFor(t,r,n={}){let{target:s}=this.targetFor(t.targetCode),i=et(s),o={onPermissionRequest:c=>n.source==="conversation_delegation"?{outcome:"denied",reason:"External group member permission continuation is not supported"}:this.requestPermission(c)},a={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs,initializeTimeoutMs:this.config.initializeTimeoutMs,sandboxRequired:this.config.sandboxRequired,runId:n.runId,source:n.source,cloudSessionId:r,orchaUrl:this.config.orchaUrl,attachOnly:n.attachOnly,sandboxPolicy:n.sandboxPolicy,...this.config.sandboxRequired?{prepareLaunch:c=>Es({config:this.config,target:s,...c,runId:n.runId,agentId:t.agentId,sessionId:r,sandboxPolicy:n.sandboxPolicy})}:{}};return i==="stdio-acp"||i==="acp"?new Et(t,s,o,a):i==="openclaw"?new ue(t,s,r,o,a):i==="cli"?ps(s)?new le(t,s,a,o):new Tt(t,s,a,o):new ie(t)}async prompt(t,r={}){if(this.assertDispatchable(),this.config.sandboxRequired){let a=u(t.runId);if(!a)throw Object.assign(new Error("runId is required"),{code:"BAD_REQUEST"});t={...t,runId:a,sandboxPolicy:ft(t.sandboxPolicy)}}let n=u(t.agentId),s=u(t.sessionId)||_e(),i=u(t.correlationId);if(!n)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});if(this.cleanupOperations(),i){let a=this.operations.get(i);if(a){if(this.assertOperationIdentity(a,t,n,s),a.status==="running"&&(["conversation_delegation","channel_message"].includes(t.metadata?.source)||t.metadata?.source==="ai_chat_runtime_node"&&Object.hasOwn(dt,t.framework||""))){a.mcpServers=t.mcpServers;let c=this.sessions.get(`${n}:${s}`);if(c){if(!c.runtime.refreshMcpServers)throw Object.assign(new Error("This runtime cannot refresh task MCP credentials"),{code:"unsupported_dynamic_mcp"});await c.runtime.refreshMcpServers(t.mcpServers)}}return this.attachOperation(a,r)}if(t.attachOnly===!0&&!(t.metadata?.source==="channel_message"&&this.targetFor(t.targetCode||t.framework).target.type==="openclaw"))throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"})}else if(t.attachOnly===!0)throw Object.assign(new Error("correlationId is required for attachOnly"),{code:"BAD_REQUEST"});let o=i?this.createOperation(i,t,n,s):null;if(o){let a=this.attachOperation(o,r);return(async()=>{try{await this._promptOwned(t,{},o,n,s)}catch(c){let l=o.status==="completed";this.failOperation(o,c),l&&_("warn","runtime-bridge","runtime cleanup failed after operation completion",{correlationId:o.correlationId,error:String(c)})}})(),await a}return await this._promptOwned(t,r,o,n,s)}async _promptOwned(t,r,n,s,i){let o=u(t.runId),a=this.config.sandboxRequired?ft(n?.sandboxPolicy||t.sandboxPolicy):null,c=this.agents.get(s),l=this.targetFor(t.targetCode||t.framework||c?.targetCode);if(c&&c.targetCode!==l.code)throw Object.assign(new Error(`runtime agent target conflict: ${s}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});if(et(l.target)==="cli"&&Pc(t.goalContract))throw Object.assign(new Error("CLI runtimes do not support per-run dynamic MCP required by plugin_operation"),{code:"unsupported_dynamic_mcp"});let p=c||(await this.createAgent({agentId:s,targetCode:l.code,framework:t.framework,workspace:t.workspace,metadata:t.metadata})).agent;if(!this.config.sandboxRequired){let y=u(t.workspace);y&&y!==p.workspace&&(p.workspace=y)}let m=`${s}:${i}`;await this.cleanupExpiredSessions();let f=this.sessions.get(m),h=null;if(f&&f.targetCode!==l.code)throw Object.assign(new Error(`runtime session target conflict: ${i}`),{code:"RUNTIME_SESSION_TARGET_CONFLICT"});if(f&&this.config.sandboxRequired&&f.runId!==o)throw Object.assign(new Error(`runtime session cannot be shared across runs: ${i}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});if(!f){if(this.startingSessions.has(m))throw Object.assign(new Error(`runtime session is already starting: ${i}`),{code:"RUNTIME_SESSION_BUSY"});this.startingSessions.add(m);let{code:y,target:O}=l,M;try{await this.reserveTargetSlot(y,O),h=y;let A=this.runtimeFor(p,i,{runId:o,sandboxPolicy:a,source:t.metadata?.source,attachOnly:t.attachOnly});M=A;let T=n?.mcpServers||t.mcpServers||[],x=await A.sessionNew({cwd:K(O,p.workspace),mcpServers:T,metadata:d(t.metadata)?t.metadata:{}});if(n&&n.status!=="running")throw Object.assign(new Error("Runtime operation was cancelled before prompt dispatch"),{code:"RUNTIME_OPERATION_CANCELLED"});let S=Date.now();f={agentId:s,sessionId:i,runtime:A,targetCode:y,runtimeKind:et(O),runId:o,sandboxPolicy:a?structuredClone(a):null,runtimeSessionId:u(d(x)?x.sessionId:"")||i,idleTtlMs:this.targetIdleTtlMs(O),releaseAfterPrompt:this.config.sandboxRequired?!0:this.targetReleaseAfterPrompt(O,t.metadata),createdAtMs:S,lastUsedAtMs:S,busy:!1,createdAt:Mt()},this.sessions.set(m,f),this.runtimeSessionIndex.set(`${s}:${f.runtimeSessionId}`,f),n?.mcpServers!==T&&n?.mcpServers&&A.refreshMcpServers&&await A.refreshMcpServers(n.mcpServers)}catch(A){throw this.sessions.get(m)?.runtime===M?await this.closeSession(m,"session_start_failed"):await M?.stop("session_start_failed"),h&&(this.releaseTargetSlot(h),h=null),A}finally{this.startingSessions.delete(m)}}if(f.busy){let y=new Error(`runtime session is already running: ${i}`);throw y.code="RUNTIME_SESSION_BUSY",y}f.busy=!0,h&&this.releaseTargetSlot(h),this.notifyCapacityChanged(),f.operationCorrelationId=n?.correlationId||null,f.lastUsedAtMs=Date.now();let g=n?.updates||[],w=vc(y=>{let O=Lc(y,i,f);if(g.push(O),n)for(let M of n.listeners)try{M?.(O)}catch(A){_("warn","runtime-bridge","runtime operation update listener failed",{correlationId:n.correlationId,error:String(A)})}else r.onUpdate?.(O)}),I=w.push,E=y=>{if(w.flush(),!(!n||n.status!=="running"||!d(y))){if(y.status==="failed"){let O=y.error;if(O instanceof Error){this.failOperation(n,O);return}let M=d(O)?O:{},A=Object.assign(new Error(u(M.message||y.message)||"runtime terminal failure"),{code:u(M.code||y.code)||"RUNTIME_TERMINAL_FAILED"});this.failOperation(n,A);return}this.completeOperation(n,this.promptResponse(t,f,i,g,d(y.result)?y.result:{stopReason:"end_turn"}))}},C=async y=>{try{return await f.runtime.sessionPrompt(y,I,E)}finally{w.flush()}};try{let y=hs(t.goalContract),O=Array.isArray(t.prompt)?[...t.prompt]:[];y&&O.unshift({type:"text",text:y,metadata:{source:"orcha_goal_contract"}});let M=d(t.metadata)?t.metadata:{},A=d(M._runtimeBridge)?M._runtimeBridge:{},T=await C({sessionId:f.runtimeSessionId,...t.modelOptions?{modelOptions:t.modelOptions}:{},prompt:O,metadata:M}),x=g,S=null;if(As({type:f.runtimeKind})&&eu(T,g,A)){S=T;let z=g.length,b=await C({sessionId:f.runtimeSessionId,...t.modelOptions?{modelOptions:t.modelOptions}:{},prompt:[{type:"text",text:ru()}],metadata:M,_meta:{thinking:"off"}});T=nu(S,b),x=g.slice(z)}let U;try{U=this.promptResponse(t,f,i,g,T,x)}catch(z){throw S&&Ls(T)?iu(T,x):z}return S&&(U.result=su(U.result,S)),n&&this.completeOperation(n,U),U}finally{f.busy=!1,this.notifyCapacityChanged(),f.operationCorrelationId===n?.correlationId&&(f.operationCorrelationId=null),f.lastUsedAtMs=Date.now(),this.promptReleaseAfterPrompt(f,d(t.metadata)?t.metadata:{})&&await this.closeSession(m,"release_after_prompt"),n&&(n.mcpServers=null)}}async updatePolicy(t){if(this.assertDispatchable(),!this.config.sandboxRequired)throw Object.assign(new Error("runtime sandbox policy updates require an enforced sandbox"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"});let r=u(t.agentId),n=u(t.runId),s=u(t.sessionId),i=u(t.correlationId);if(!r||!n||!s||!i)throw Object.assign(new Error("agentId, runId, sessionId and correlationId are required"),{code:"BAD_REQUEST"});let o=ft(t.sandboxPolicy),a=this.operations.get(i);if(a&&(a.agentId!==r||a.sessionId!==s||a.identity.runId!==n))throw Object.assign(new Error(`runtime operation policy identity conflict: ${i}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let c=`${r}:${s}`,l=this.sessions.get(c);if(l&&l.runId!==n)throw Object.assign(new Error(`runtime session policy identity conflict: ${s}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});let p=l?.sandboxPolicy||a?.sandboxPolicy;if(!p)throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"});let m=Number(p.policyRevision),f=Number(o.policyRevision);if(f<m)throw Object.assign(new Error("runtime sandbox policy revision is stale"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:m});if(f===m){if(Z(p)!==Z(o))throw Object.assign(new Error("runtime sandbox policy revision payload conflicts"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:m});return{updated:!1,idempotent:!0,policyRevision:m,accessMode:p.accessMode}}let h=ws(p,o);a&&(a.sandboxPolicy=structuredClone(o)),l&&(l.sandboxPolicy=structuredClone(o));let g=!1;return h&&l?.busy===!0&&(await l.runtime.sessionCancel({sessionId:l.runtimeSessionId}),g=await this.closeSession(c,"sandbox_policy_downgrade")),{updated:!0,policyRevision:f,accessMode:o.accessMode,activeCommandCancelled:g,deferredToNextLaunch:!h&&l?.busy===!0}}async cancel(t){let r=u(t.agentId),n=u(t.sessionId),s=u(t.correlationId);if(s){let a=this.operations.get(s);if(!a||a.status!=="running")return{cancelled:!1,correlationId:s,reason:"operation_not_running"};if(a.agentId!==r||a.sessionId!==n)throw Object.assign(new Error(`runtime operation cancellation identity conflict: ${s}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let c=this.sessions.get(`${r}:${n}`);return!c||c.busy!==!0||c.operationCorrelationId!==s?(this.failOperation(a,Object.assign(new Error("Runtime operation cancelled before dispatch"),{code:"RUNTIME_OPERATION_CANCELLED"})),{cancelled:!0,correlationId:s,reason:"cancelled_before_dispatch"}):(await c.runtime.sessionCancel({sessionId:c.runtimeSessionId}),await this.closeSession(`${r}:${n}`,"cancelled"),{cancelled:!0,correlationId:s})}let i=`${r}:${n}`,o=this.sessions.get(i);return o?(await o.runtime.sessionCancel({sessionId:o.runtimeSessionId}),await this.closeSession(i,"cancelled"),{cancelled:!0}):{cancelled:!1}}async dispatch(t,r={}){let n=u(t.agentId),s=u(t.taskId),i=u(t.executionId);if(!n||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let o=u(t.sessionId)||`dispatch-${i||s}`,a=u(t.instructions),c=Kc(t),l=bs(t),{target:p}=this.targetFor(t.targetCode||t.framework),m=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",a?`instructions: ${a}`:"",c?"orchaContext:":"",c,c?"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.",l?`For decision results, put the raw report between ${ar} and ${cr}.`:"",l?`Then put a JSON object containing _decision between ${ur} and ${lr}.`:"",l?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"",l?`Keep the report within ${Cs} Unicode characters so the CONTROL block fits before the output limit.`:"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
33
- `)}];return this.prompt({...t,agentId:n,sessionId:o,prompt:m,metadata:Gc(t,p)},r)}async requestPermission({agent:t,runtimeSessionId:r,request:n,emitUpdate:s,signal:i}){let o=_e(),c=this.runtimeSessionIndex.get(`${t.agentId}:${r}`)?.sessionId||r||_e(),l=R(n?.timeoutMs,this.config.permissionRequestTimeoutMs),p={permissionId:o,agentId:t.agentId,sessionId:c,runtimeSessionId:r,request:d(n)?n:{},status:"pending",createdAt:Mt(),expiresAt:new Date(Date.now()+l).toISOString()};return i?.aborted?{permissionId:o,outcome:"cancelled",response:{reason:"runtime turn ended"}}:await new Promise(m=>{let f=(w,I)=>{clearTimeout(g),i?.removeEventListener("abort",h),this.pendingPermissions.delete(o),s?.({sessionId:r,update:{sessionUpdate:"permission_resolved",permissionId:o,outcome:I}}),m(w)},h=()=>f({permissionId:o,outcome:"cancelled",response:{reason:"runtime turn ended"}},"cancelled"),g=setTimeout(()=>f({permissionId:o,outcome:"denied",response:{reason:"permission request timed out"}},"expired"),l);i?.addEventListener("abort",h,{once:!0}),this.pendingPermissions.set(o,{settle:f,permission:p}),s?.({sessionId:r,update:{sessionUpdate:"permission_request",permission:p}})})}async respondPermission(t){let r=u(t.permissionId),n=this.pendingPermissions.get(r),s=u(t.outcome||"approved")||"approved";return n?(n.settle({permissionId:r,outcome:s,response:d(t.response)?t.response:{},userId:u(t.userId),metadata:d(t.metadata)?t.metadata:{}},s),{accepted:!0,permissionId:r,outcome:s}):{accepted:!1,permissionId:r,outcome:s}}health(){return{status:this.config.sandboxRequired&&!this.sandboxCapabilities.dispatchable?"unavailable":"ok",bridgeVersion:B,startedAt:this.startedAt,agents:[...this.agents.values()].map(t=>({agentId:t.agentId,targetCode:t.targetCode,framework:t.framework,runtimeKind:t.runtimeKind})),sessions:this.sessions.size,pendingPermissions:this.pendingPermissions.size,targets:Object.keys(this.targets),sandboxCapabilities:this.sandboxCapabilities}}};import ou from"node:http";import au from"node:https";import{randomBytes as ks}from"node:crypto";var It=1,mt=3,cu=1e4,Te=class{constructor(t,r={}){this.url=t,this.readyState=0,this.socket=null,this.request=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,this.connectTimeoutMs=uu(r.connectTimeoutMs,cu),this.connectTimer=null,this.connect()}addEventListener(t,r){let n=this.listeners.get(t)||new Set;n.add(r),this.listeners.set(t,n)}emit(t,r={}){let n=this.listeners.get(t);if(n)for(let s of n)s(r)}connect(){let t=new URL(this.url),r=t.protocol==="wss:"?au:ou,n=ks(16).toString("base64"),s=r.request({protocol:t.protocol==="wss:"?"https:":"http:",hostname:t.hostname,port:t.port||(t.protocol==="wss:"?443:80),path:`${t.pathname}${t.search}`,method:"GET",headers:{Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Key":n,"Sec-WebSocket-Version":"13"}});this.request=s,this.startConnectTimer(s),s.on("upgrade",(i,o,a)=>{if(this.clearConnectTimer(),this.readyState===mt){o.destroy();return}this.socket=o,this.readyState=It,o.on("data",c=>this.onData(c)),o.on("close",()=>this.onClose()),o.on("error",c=>{this.readyState!==mt&&this.emit("error",{error:c,message:c.message,type:"error"}),this.onClose()}),a?.length&&this.onData(a),this.emit("open")}),s.on("response",i=>{this.clearConnectTimer(),this.emit("error",{message:`websocket upgrade failed: HTTP ${i.statusCode}`,type:"error"}),i.resume(),this.onClose()}),s.on("error",i=>{this.clearConnectTimer(),this.readyState!==mt&&this.emit("error",{error:i,message:i.message,type:"error"}),this.onClose()}),s.end()}startConnectTimer(t){this.connectTimeoutMs<=0||(this.connectTimer=setTimeout(()=>{if(this.readyState===It||this.readyState===mt)return;let r=`websocket connect timeout after ${this.connectTimeoutMs}ms`;this.emit("error",{message:r,type:"timeout"}),this.onClose(),t.destroy(new Error(r))},this.connectTimeoutMs),this.connectTimer.unref?.())}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}send(t){!this.socket||this.readyState!==It||this.socket.write($r(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==mt){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===It&&this.socket.write($r(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==mt&&(this.clearConnectTimer(),this.readyState=mt,this.request=null,this.emit("close"))}onData(t){for(this.buffer=Buffer.concat([this.buffer,t]);this.buffer.length>=2;){let r=this.buffer[0],n=this.buffer[1],s=r&15,i=(n&128)!==0,o=n&127,a=2;if(o===126){if(this.buffer.length<a+2)return;o=this.buffer.readUInt16BE(a),a+=2}else if(o===127){if(this.buffer.length<a+8)return;let p=this.buffer.readUInt32BE(a),m=this.buffer.readUInt32BE(a+4);o=p*2**32+m,a+=8}let c=a;if(i&&(a+=4),this.buffer.length<a+o)return;let l=this.buffer.subarray(a,a+o);if(i){let p=this.buffer.subarray(c,c+4);l=Buffer.from(l.map((m,f)=>m^p[f%4]))}this.buffer=this.buffer.subarray(a+o),s===1?this.emit("message",{data:l.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write($r(10,l))}}};function uu(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function $r(e,t){let r=t.length,n=2;r>=126&&r<=65535?n+=2:r>65535&&(n+=8);let s=ks(4),i=Buffer.alloc(n+4+r);i[0]=128|e;let o=2;r<126?i[1]=128|r:r<=65535?(i[1]=254,i.writeUInt16BE(r,o),o+=2):(i[1]=255,i.writeUInt32BE(Math.floor(r/2**32),o),i.writeUInt32BE(r>>>0,o+4),o+=8),s.copy(i,o),o+=4;for(let a=0;a<r;a+=1)i[o+a]=t[a]^s[a%4];return i}function lu(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 du(e,t=!0){return Object.entries(e||{}).map(([r,n])=>({targetCode:r,targetName:u(n?.name||n?.targetName||r),targetType:u(n?.type||"echo"),status:t?"available":"unavailable"}))}var pu=Object.freeze(["health","agents/create","agents/dispatch","sessions/prompt","sessions/policy","sessions/cancel","permissions/respond"]),Ee=class{constructor(t,r){this.config=t,this.bridge=r,this.ws=null,this.stopped=!1,this.connected=!1,this.reconnectTimer=null,this.heartbeatTimer=null,this.capacityHeartbeatTimer=null,this.bridge.onCapacityChanged=()=>this.scheduleCapacityHeartbeat()}sandboxCapabilities(){return this.bridge.sandboxCapabilities||{dispatchable:this.config.sandboxRequired!==!0,enforced:!1,backend:"development_direct",daemonStatus:"development_only",policySchemaVersions:[1],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:!1}}supportedMethods(){return[...pu,...this.config.deviceConnection?["devices/discover","devices/configure","agents/models"]:[]]}runtimeTargets(){let t=this.sandboxCapabilities().dispatchable===!0;return typeof this.bridge.targetCapacitySnapshot=="function"?this.bridge.targetCapacitySnapshot(t):du(this.config.targets,t)}start(){this.connect()}stop(){this.stopped=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.capacityHeartbeatTimer&&clearTimeout(this.capacityHeartbeatTimer),this.capacityHeartbeatTimer=null,this.bridge.onCapacityChanged=null,this.ws?.close()}connect(){if(this.stopped)return;let t=lu(this.config.orchaUrl),r=new Te(t,{connectTimeoutMs:this.config.connectTimeoutMs});this.ws=r,r.addEventListener("open",()=>{if(this.ws!==r||this.stopped){r.close();return}this.authenticate(r)}),r.addEventListener("message",n=>this.handleMessage(n.data,r)),r.addEventListener("close",()=>this.scheduleReconnect("close",r)),r.addEventListener("error",n=>{_("warn","orcha-client","runtime node websocket error",{error:String(n?.message||n?.type||n)})})}authenticate(t=this.ws){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:B,protocolVersion:"orcha-runtime-node.v2",defaultTargetCode:this.config.defaultTargetCode,supportedMethods:this.supportedMethods(),sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()},t)}scheduleReconnect(t,r=this.ws){r&&this.ws!==r||(this.connected=!1,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.capacityHeartbeatTimer&&clearTimeout(this.capacityHeartbeatTimer),this.capacityHeartbeatTimer=null,r&&this.ws===r&&(this.ws=null),!this.stopped&&(this.reconnectTimer||(_("info","orcha-client","runtime node disconnected; reconnect scheduled",{reason:t,reconnectMs:this.config.reconnectMs}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},this.config.reconnectMs))))}async handleMessage(t,r=this.ws){if(r&&this.ws!==r)return;let n;try{n=JSON.parse(String(t))}catch(s){_("warn","orcha-client","invalid Orcha websocket frame",{error:String(s)});return}if(d(n)){if(n.type==="runtime_node.authenticated"){if(r&&this.ws!==r)return;this.connected=!0,this.startHeartbeat(r),_("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:n.connectionId});return}if(n.type==="orcha.runtime.request"){await this.handleRequest(n);return}n.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString(),supportedMethods:this.supportedMethods(),sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()})}}startHeartbeat(t){this.heartbeatTimer&&clearInterval(this.heartbeatTimer);let r=Math.max(1e3,Number(this.config.heartbeatIntervalMs||15e3)),n=()=>this.sendCapacityHeartbeat(t);n(),this.heartbeatTimer=setInterval(n,r),this.heartbeatTimer.unref?.()}scheduleCapacityHeartbeat(){if(!this.connected||this.capacityHeartbeatTimer)return;let t=Math.max(25,Math.min(1e3,Number(this.config.capacityHeartbeatDebounceMs||100)));this.capacityHeartbeatTimer=setTimeout(()=>{this.capacityHeartbeatTimer=null,this.sendCapacityHeartbeat()},t),this.capacityHeartbeatTimer.unref?.()}sendCapacityHeartbeat(t=this.ws){return this.connected?this.send({type:"runtime_node.heartbeat",ts:new Date().toISOString(),supportedMethods:this.supportedMethods(),sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()},t):!1}async handleRequest(t){let r=u(t.id),n=u(t.method),s=d(t.params)?t.params:{};try{let i=await this.invoke(n,s,r);this.send({type:"orcha.runtime.response",id:r,ok:!0,result:i})}catch(i){this.send({type:"orcha.runtime.response",id:r,ok:!1,error:{code:i.code||"RUNTIME_NODE_ERROR",message:i.message||String(i),...i.detail===void 0?{}:{detail:i.detail}}})}}async invoke(t,r,n){if(t==="agents/models"&&this.config.deviceConnection)return ne(this.bridge.targetFor(r.targetCode).target);if(t==="devices/discover"&&this.config.deviceConnection)return this.config.deviceConnection.candidates();if(t==="devices/configure"&&this.config.deviceConnection)return this.config.deviceConnection.configure(r,this.bridge);if(t==="health")return this.bridge.health();if(t==="agents/create")return this.bridge.createAgent(r);if(t==="agents/dispatch")return this.bridge.dispatch(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/prompt")return this.bridge.prompt(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/policy")return this.bridge.updatePolicy(r);if(t==="sessions/cancel")return this.bridge.cancel(r);if(t==="permissions/respond")return this.bridge.respondPermission(r);throw Object.assign(new Error(`unsupported Orcha runtime method: ${t}`),{code:"METHOD_NOT_FOUND"})}sendUpdate(t,r){this.send({type:"orcha.runtime.event",requestId:t,eventType:"runtime.update",payload:r})}send(t,r=this.ws){return!r||r!==this.ws||r.readyState!==It?!1:(r.send(JSON.stringify(t)),!0)}};import{createServer as fu}from"node:http";function Oe(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 ht(e={}){return{ok:!0,...e}}function Hr(e,t,r){return{ok:!1,error:{code:e,message:t,...r===void 0?{}:{detail:r}}}}async function vs(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(!d(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 Ds(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 $s(e,t){let r={"GET /health":async()=>ht(t.health()),"POST /agents/create":async n=>ht(await t.createAgent(n)),"POST /agents/dispatch":async n=>ht(await t.dispatch(n)),"POST /sessions/prompt":async n=>ht(await t.prompt(n)),"POST /sessions/cancel":async n=>ht(await t.cancel(n)),"POST /permissions/respond":async n=>ht(await t.respondPermission(n))};return fu(async(n,s)=>{let i=new URL(n.url||"/",`http://${n.headers.host||`${e.host}:${e.port}`}`),o=`${n.method||"GET"} ${i.pathname}`,a=r[o];if(!a){Oe(s,404,Hr("NOT_FOUND",`No route for ${o}`));return}try{Ds(n,e.token);let c=n.method==="GET"?{}:await vs(n,e.requestLimitBytes);Oe(s,200,await a(c))}catch(c){let l=c.status||500,p=c.code||"BRIDGE_INTERNAL";Oe(s,l,Hr(p,c.message||String(c),c.detail))}})}var zs=wu(import.meta.url),Tu=".orcha-runtime-bridge.pid",Eu=".orcha-runtime-bridge.log",Ou=3,Su=36e5,{command:Ru,options:Vs}=xu(process.argv.slice(2));Au(Vs);Mn();var Iu=Un();await Js(Ru,Iu,Vs);async function Js(e,t,r){if(r.url){let s=Qe(r.url);r.pidFile||(process.env.ORCHA_RUNTIME_PID_FILE=s.pidFile),r.logFile||(process.env.ORCHA_RUNTIME_LOG_FILE=s.logFile)}let n=()=>["connect","--url",t.orchaUrl,"--foreground"];switch(e){case"connect":if(r.pairCode&&gt(Re(Se())))throw new Error("\u8BBE\u5907\u8FDE\u63A5\u4ECD\u5728\u540E\u53F0\u8FD0\u884C\uFF0C\u8BF7\u5148\u6267\u884C stop --url \u540E\u91CD\u65B0\u914D\u5BF9");await se(t,r),r.foreground?await Fr(t):Br(n());return;case"run":case"foreground":r.url&&await se(t,r),await Fr(t);return;case"start":if(r.url)return Js("connect",t,r);if(r.foreground){await Fr(t);return}Br();return;case"reload":case"restart":{r.url&&await se(t,{url:r.url});let s=Ct(Ks(zs),".."),i=Ct(s,...Kr(Ct(s,"src","index.js"))?["dist","package"]:[],"openclaw-plugin"),o=await as(t.targets,i);await Bs({quiet:!0}),await o(),Br(r.url?n():void 0);return}case"stop":await Bs();return;case"status":Cu();return;case"help":case"--help":case"-h":Uu();return;default:throw new Error(`Unknown command: ${e}`)}}async function Fr(e){bu();let t=new we(e);if(await t.start(),e.mode==="server"){let n=$s(e,t);Fs({bridge:t,server:n}),n.listen(e.port,e.host,()=>{_("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 Ee(e,t);Fs({bridge:t,client:r}),r.start(),_("info","runtime-bridge","Orcha runtime node started",{nodeId:e.nodeId,nodeName:e.nodeName,orchaUrl:e.orchaUrl,targets:Object.keys(t.targets)})}function Fs({bridge:e,client:t,server:r}){let n=!1,s=i=>{if(n)return;n=!0;let o=Number(e?.sessions?.size||0)>0;_("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(a){_("warn","runtime-bridge","runtime client stop failed",{error:String(a)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(a=>{_("warn","runtime-bridge","runtime bridge stop failed",{error:String(a)})}).finally(()=>{try{r?.close?.()}catch(a){_("warn","runtime-bridge","runtime server close failed",{error:String(a)})}}),setTimeout(()=>process.exit(0),o?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function Br(e=["run"]){let t=Se(),r=Ws(),n=Re(t);if(n&&gt(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:t,logFile:r}));return}n&&Gr(t),qs(t),qs(r),qr(r);let s=_u(r,"a"),i={...process.env,ORCHA_RUNTIME_PID_FILE:t,ORCHA_RUNTIME_LOG_FILE:r},o=mu(process.execPath,[zs,...e,"--pid-file",t,"--log-file",r],{cwd:process.cwd(),detached:!0,env:i,stdio:["ignore",s,s]});o.unref(),hu(s),Gs(t,`${o.pid}
34
- `),console.log(JSON.stringify({status:"started",pid:o.pid,pidFile:t,logFile:r}))}async function Bs({quiet:e=!1}={}){let t=Se(),r=Re(t);if(!r){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!gt(r)){Gr(t),e||console.log(JSON.stringify({status:"not_running",pid:r,pidFile:t}));return}process.kill(r,"SIGTERM"),!await js(r,1e4)&&gt(r)&&(process.kill(r,"SIGKILL"),await js(r,3e3)),Gr(t),e||console.log(JSON.stringify({status:"stopped",pid:r,pidFile:t}))}function Cu(){let e=Se(),t=Ws(),r=Re(e),n=!!(r&&gt(r));console.log(JSON.stringify({status:n?"running":"not_running",running:n,pid:n?r:null,pidFile:e,logFile:t}))}function xu(e){let t=[],r={};for(let s=0;s<e.length;s+=1){let i=e[s];i==="--url"?r.url=e[++s]:i==="--pair-code"?r.pairCode=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 Au(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 Se(){return Ct(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Tu)}function Ws(){return Ct(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||Eu)}function bu(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=Xs();if(t<=0)return;let r=Ct(process.cwd(),e);qr(r,t);let n=Mu();n<=0||setInterval(()=>qr(r,t),n).unref()}function qr(e,t=Xs()){if(t<=0||!Kr(e))return;let r=0,n="";try{if(r=Hs(e).size,r<=0)return;n=jr(e,"utf8")}catch(l){_("warn","runtime-bridge","runtime log cleanup skipped",{logFile:e,error:String(l)});return}let s=Date.now()-t*24*60*60*1e3,i=n.split(/\r?\n/),o=[],a=0;for(let l of i)l&&(Nu(l,s)?o.push(l):a+=1);if(a===0)return;let c="";try{Hs(e).size>r&&(c=jr(e,"utf8").slice(n.length));let p=[...o,...c.split(/\r?\n/).filter(Boolean)].join(`
31
+ `?1:0)).trim()}function Rs(e){let t=String(e||"").trim();if(!t)return null;try{let r=JSON.parse(t);if(d(r)&&(Ns(r)||F(r._artifacts)||F(r.artifacts)||F(r._decision)||F(r._meta)))return r}catch{}return null}function Bt(e){try{return fr(e)}catch{return null}}function ge(...e){let t=null;for(let r of e)try{if(fr(r))return}catch(n){t||=n}if(t)throw t}function Nr(e){let t=String(e||"").trim();if(!t)return null;let r=Bt(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=Rs(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=Rs(t.slice(s));if(i)return i}return null}function Yc(e){let t=Bt(vr(e));if(t)return t;let r=ye(e);for(let n=r.length-1;n>=0;n-=1){let s=Bt(r[n]);if(s)return s}return Bt(Rt(r))}function Ns(e){if(!d(e))return!1;if(F(e.output))return!0;for(let t of["content","text","message","summary"])if(u(e[t]))return!0;return!!(xs(e.status)||u(e.error)||u(e.errorMessage))}function W(e){let t=d(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 Qc(e){return d(e)?typeof(d(e._decision)?e._decision:d(e.decision)?e.decision:e).passed=="boolean":!1}function Ms(e){return d(e)?d(e._decision)&&typeof e._decision.passed=="boolean"?!0:Qc(e.output):!1}function Mr(e,t,r){let n=d(e)?{...e}:{};if(!F(n.output)){for(let s of["summary","message","content","text"])if(u(n[s])){n.output=u(n[s]);break}}return!F(n.output)&&u(r)&&(n.output=u(r)),{...n,_meta:{...d(n._meta)?n._meta:{},runtimeOutputSource:t,requiredRuntimeResult:!0,finalMessagePreview:u(r).slice(0,1e3)}}}var Zc=["dataUrl","dataURL","contentDataUrl","contentDataURL","contentBase64","base64","data"];function Is(e){if(!d(e))return"";let t=d(e.content)?e.content:{},r=d(e.metadata)?e.metadata:{};return u(e.fieldKey||e.field_key||t.fieldKey||r.fieldKey)}function tu(e,t){let r=d(e.content)?e.content:{},n=d(t.content)?t.content:{},s={...e,...t,content:{...r,...n},metadata:{...d(e.metadata)?e.metadata:{},...d(t.metadata)?t.metadata:{}}};for(let i of Zc)F(e[i])&&(s[i]=e[i]),F(r[i])&&(s.content[i]=r[i]);return s}function Us(e,t){let r=Array.isArray(e)?e.filter(d):[],n=Array.isArray(t)?t.filter(d):[];if(!r.length)return n;if(!n.length)return r;let s=[...r],i=new Map;for(let a=0;a<r.length;a+=1){let c=Is(r[a]),l=i.get(c)||[];l.push(a),i.set(c,l)}let o=new Map;for(let a of n){let c=Is(a),l=o.get(c)||0;o.set(c,l+1);let p=i.get(c)?.[l];p===void 0?s.push(a):s[p]=tu(s[p],a)}return s}function tt(e,t,r){let n={...e,...t,_meta:{...d(e._meta)?e._meta:{},...d(t._meta)?t._meta:{},runtimeOutputSource:r}};return(Array.isArray(e._artifacts)||Array.isArray(t._artifacts))&&(n._artifacts=Us(e._artifacts,t._artifacts)),n}function Ps(e,t,r={}){let n=u(r.promptKind),s=r.requiresRuntimeResult===!0,i=s||n==="dispatch",o=W(e),a=typeof o.output=="string"?Bt(o.output):null;if(a)return tt(o,W(a),"result_block");let c=Wc(t),l=c?Nr(c):null,p=i?Yc(t):null;if(Ns(o))return xs(o.status)||u(o.error)||u(o.errorMessage)?o:n==="dispatch"&&l?tt(o,W(l),"final_event"):n==="dispatch"&&p?tt(o,W(p),"updates"):!s||Ms(o)?o:l?tt(o,W(l),"final_event"):p?tt(o,W(p),"updates"):(ge(o.output,c,Rt(ye(t))),Mr(o,"result",o.output));if(l)return tt(o,W(l),"final_event");if(p)return tt(o,W(p),"updates");if(c)return s?(ge(c,Rt(ye(t))),Mr(o,"final_event",c)):{...o,output:c,_meta:{...d(o._meta)?o._meta:{},runtimeOutputSource:"final_event"}};let m=vr(t),f=Nr(m);if(f)return tt(o,W(f),"updates");let h=Xc(m);if(!h)return s&&ge(Rt(ye(t))),o;let _=Nr(h);return _?tt(o,W(_),"updates"):s?(ge(m,h),Mr(o,"updates",h)):{...o,output:h,_meta:{...d(o._meta)?o._meta:{},runtimeOutputSource:"updates"}}}function Dr(e){return d(e)?u(e.stopReason||e.stop_reason).toLowerCase():""}function Ls(e){return xc.has(Dr(e))}function eu(e,t,r){if(r.promptKind!=="dispatch"||r.requiresRuntimeResult!==!0||!Ls(e))return!1;try{return!Ms(Ps(e,t,r))}catch{return!0}}function ru(){return["Your previous final response reached the output limit before the Runtime Result protocol was complete.","Re-emit the complete final Runtime Result from scratch using the conclusion you already reached.","Do not repeat analysis, process notes, tool calls, or task work.",`Keep the OUTPUT report within ${Cs} Unicode characters.`,`Output ${ar}, ${cr}, ${ur}, and ${lr} on their own lines.`,"The CONTROL block must be valid JSON containing _decision and must be fully closed.","Return only the two protocol blocks."].join(`
32
+ `)}function nu(e,t){let r=d(t)?{...t}:{},n=Us(e?._artifacts,t?._artifacts);return n.length>0&&(r._artifacts=n),r}function su(e,t){return{...e,_meta:{...d(e?._meta)?e._meta:{},runtimeProtocolRetry:{attempted:!0,recovered:!0,reason:Dr(t)||"max_tokens"}}}}function iu(e,t){let r=typeof e?.output=="string"?e.output:vr(t),n=new H("runtime_output_truncated","Runtime Result \u8FBE\u5230\u6700\u5927\u8F93\u51FA\u957F\u5EA6\uFF0C\u7D27\u51D1\u91CD\u8BD5\u540E\u4ECD\u672A\u5B8C\u6574\u8FD4\u56DE",r);return n.detail={...n.detail,stopReason:Dr(e)||"max_tokens",retryAttempted:!0},n}var we=class{constructor(t){this.config=t,this.targets=t.targets||{},this.agents=new Map,this.sessions=new Map,this.startingSessions=new Set,this.targetReservations=new Map,this.runtimeSessionIndex=new Map,this.pendingPermissions=new Map,this.operations=new Map,this.startedAt=Mt(),this.sandboxCapabilities={dispatchable:t.sandboxRequired!==!0,enforced:!1,backend:t.sandboxRequired?"unavailable":"direct",daemonStatus:t.sandboxRequired?"pending":"not_required",policySchemaVersions:[1],runtimePolicyUpdates:t.sandboxRequired===!0,workspaceSync:!1,egressProxy:!1},this.cleanupTimer=null,this.onCapacityChanged=null,this.startSessionCleanup()}async start(){try{this.sandboxCapabilities=await Ts(this.config)}catch(t){this.sandboxCapabilities={...this.sandboxCapabilities,dispatchable:!1,enforced:!1,backend:"unavailable",daemonStatus:"unavailable",reason:u(t?.code||t?.message||t)||"sandbox_probe_failed"},g("error","runtime-bridge","runtime node sandbox probe failed; node will not accept work",{reason:this.sandboxCapabilities.reason})}return this.sandboxCapabilities}assertDispatchable(){if(this.config.sandboxRequired&&!(this.sandboxCapabilities.dispatchable===!0&&this.sandboxCapabilities.enforced===!0))throw Object.assign(new Error("runtime node strong sandbox is unavailable"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"})}operationIdentity(t,r,n){let s=d(t.goalContract)?_r(t.goalContract):u(t.goalContractHash),i=_c("sha256").update(Z({prompt:Array.isArray(t.prompt)?t.prompt:[],mcpServers:Uc(t.mcpServers),metadata:d(t.metadata)?t.metadata:{},modelOptions:d(t.modelOptions)?t.modelOptions:null})).digest("hex");return{agentId:r,runId:u(t.runId),sessionId:n,targetCode:u(t.targetCode||t.framework),workspace:u(t.workspace),goalContractHash:s,requestHash:i}}assertOperationIdentity(t,r,n,s){let i=this.operationIdentity(r,n,s),o=Object.keys(t.identity).find(a=>t.identity[a]!==i[a]);if(o)throw Object.assign(new Error(`runtime operation correlation conflict: ${t.correlationId}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT",field:o})}createOperation(t,r,n,s){let i={correlationId:t,agentId:n,sessionId:s,identity:this.operationIdentity(r,n,s),sandboxPolicy:d(r.sandboxPolicy)?structuredClone(r.sandboxPolicy):null,status:"running",updates:[],listeners:new Set,waiters:[],response:null,error:null,mcpServers:r.mcpServers,createdAtMs:Date.now(),completedAtMs:null};return this.operations.set(t,i),i}async attachOperation(t,r={}){let n=()=>{if(r.onUpdate)for(let s of t.updates)r.onUpdate(s)};if(t.status==="completed")return n(),t.response;if(t.status==="failed")throw n(),t.error;r.onUpdate&&t.listeners.add(r.onUpdate);try{return n(),await new Promise((s,i)=>t.waiters.push({resolve:s,reject:i}))}finally{r.onUpdate&&t.listeners.delete(r.onUpdate)}}completeOperation(t,r){if(t.status==="running"){t.status="completed",t.response=r,t.mcpServers=null,t.completedAtMs=Date.now();for(let n of t.waiters.splice(0))n.resolve(r);t.listeners.clear()}}promptResponse(t,r,n,s,i,o=s){let a=d(t.metadata)?t.metadata:{},c=d(a._runtimeBridge)?a._runtimeBridge:{},l=a.source==="channel_message"?i:Ps(i,o,c),p=gs(t.goalContract,s,t.goalContractHash);return{sessionId:n,runtimeSessionId:r.runtimeSessionId,result:l,updates:s,...p?{verification:p}:{}}}failOperation(t,r){if(t.status!=="running")return;let n=r instanceof Error?r:Object.assign(new Error(String(r||"runtime operation failed")),{code:"RUNTIME_NODE_ERROR"});t.status="failed",t.error=n,t.mcpServers=null,t.completedAtMs=Date.now();for(let s of t.waiters.splice(0))s.reject(n);t.listeners.clear()}cleanupOperations(t=Date.now()){let r=it(this.config.operationTtlMs,Oc);for(let[n,s]of this.operations)s.status!=="running"&&t-(s.completedAtMs||s.createdAtMs)>r&&this.operations.delete(n)}targetFor(t){let r=u(t)||this.config.defaultTargetCode,n=this.targets[r];if(!r||!d(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=et(t)==="openclaw"?it(this.config.openClawSessionIdleTtlMs,Ic):it(this.config.sessionIdleTtlMs,wc);return it(t?.sessionIdleTtlMs??t?.idleTtlMs,n)}targetMaxSessions(t){let n=et(t)==="openclaw"?it(this.config.openClawMaxSessions,Cc):it(this.config.maxSessionsPerTarget,Ec);return it(t?.maxSessions,n)}targetReservationCount(t){return Number(this.targetReservations.get(t)||0)}notifyCapacityChanged(){try{this.onCapacityChanged?.()}catch(t){g("warn","runtime-bridge","capacity heartbeat callback failed",{error:String(t)})}}targetCapacitySnapshot(t=!0){return Object.entries(this.targets).map(([r,n])=>{let s=[...this.sessions.values()].filter(p=>p.targetCode===r),i=s.filter(p=>p.busy).length,o=s.length-i,a=this.targetReservationCount(r),c=this.targetMaxSessions(n),l=t?Math.max(0,c-i-a):0;return{targetCode:r,targetName:u(n?.name||n?.targetName||r),targetType:u(n?.type||"echo"),status:t?l>0?"available":"busy":"unavailable",maxSessions:c,busySessions:i,idleSessions:o,reservedSessions:a,availableSessions:l}})}targetReleaseAfterPrompt(t,r={}){let n=et(t),s=d(r?._runtimeBridge)?r._runtimeBridge:{},i=Ur(s);return i!==void 0?Ft(i,!1):Ft(t?.releaseAfterPrompt??t?.disposeAfterPrompt,n==="openclaw")}promptReleaseAfterPrompt(t,r={}){if(this.config.sandboxRequired)return!0;let n=d(r?._runtimeBridge)?r._runtimeBridge:{},s=Ur(n);return s!==void 0?Ft(s,t.releaseAfterPrompt):t.releaseAfterPrompt}startSessionCleanup(){let t=it(this.config.sessionCleanupIntervalMs,Tc);t<=0||(this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions().catch(r=>{g("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){g("warn","runtime-bridge","runtime session stop failed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,error:String(s)})}return this.sessions.delete(t),this.runtimeSessionIndex.delete(`${n.agentId}:${n.runtimeSessionId}`),this.notifyCapacityChanged(),g("info","runtime-bridge","runtime session closed",{sessionId:n.sessionId,runtimeSessionId:n.runtimeSessionId,targetCode:n.targetCode,runtimeKind:n.runtimeKind,reason:r}),!0}async closeAllSessions(t="bridge_shutdown"){for(let r of[...this.sessions.keys()])await this.closeSession(r,t)}async stop(t="bridge_stop"){this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=null,await this.closeAllSessions(t)}async cleanupExpiredSessions(t=Date.now()){for(let[r,n]of[...this.sessions.entries()])n.busy||t-(n.lastUsedAtMs||n.createdAtMs||t)>n.idleTtlMs&&await this.closeSession(r,"idle_timeout")}async reserveTargetSlot(t,r){let n=this.targetMaxSessions(r);for(;this.sessionCountForTarget(t)+this.targetReservationCount(t)>=n;){let s=this.idleTargetSessions(t);if(!s.length){let i=new Error(`runtime target session limit reached: ${t}`);throw i.code="RUNTIME_TARGET_SESSION_LIMIT",i}await this.closeSession(s[0][0],"target_session_limit")}this.targetReservations.set(t,this.targetReservationCount(t)+1),this.notifyCapacityChanged()}releaseTargetSlot(t){let r=Math.max(0,this.targetReservationCount(t)-1);r>0?this.targetReservations.set(t,r):this.targetReservations.delete(t),this.notifyCapacityChanged()}async createAgent(t){let r=u(t.agentId);if(!r)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});let{code:n,target:s}=this.targetFor(t.targetCode||t.framework),i=this.agents.get(r);if(i&&i.targetCode!==n)throw Object.assign(new Error(`runtime agent target conflict: ${r}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});let o=this.config.sandboxRequired?await Sr(this.config,s,t.workspace):u(t.workspace),a={agentId:r,targetCode:n,framework:u(t.framework||n),workspace:o,metadata:d(t.metadata)?t.metadata:{},createdAt:Mt(),runtimeKind:et(s)};return this.agents.set(r,a),{agent:a}}runtimeFor(t,r,n={}){let{target:s}=this.targetFor(t.targetCode),i=et(s),o={onPermissionRequest:c=>n.source==="conversation_delegation"?{outcome:"denied",reason:"External group member permission continuation is not supported"}:this.requestPermission(c)},a={sessionPromptTimeoutMs:this.config.sessionPromptTimeoutMs,initializeTimeoutMs:this.config.initializeTimeoutMs,sandboxRequired:this.config.sandboxRequired,runId:n.runId,source:n.source,cloudSessionId:r,orchaUrl:this.config.orchaUrl,attachOnly:n.attachOnly,sandboxPolicy:n.sandboxPolicy,...this.config.sandboxRequired?{prepareLaunch:c=>Es({config:this.config,target:s,...c,runId:n.runId,agentId:t.agentId,sessionId:r,sandboxPolicy:n.sandboxPolicy})}:{}};return i==="stdio-acp"||i==="acp"?new Et(t,s,o,a):i==="openclaw"?new ue(t,s,r,o,a):i==="cli"?ps(s)?new le(t,s,a,o):new Tt(t,s,a,o):new ie(t)}async prompt(t,r={}){if(this.assertDispatchable(),this.config.sandboxRequired){let a=u(t.runId);if(!a)throw Object.assign(new Error("runId is required"),{code:"BAD_REQUEST"});t={...t,runId:a,sandboxPolicy:ft(t.sandboxPolicy)}}let n=u(t.agentId),s=u(t.sessionId)||_e(),i=u(t.correlationId);if(!n)throw Object.assign(new Error("agentId is required"),{status:400,code:"BAD_REQUEST"});if(this.cleanupOperations(),i){let a=this.operations.get(i);if(a){if(this.assertOperationIdentity(a,t,n,s),a.status==="running"&&(["conversation_delegation","channel_message"].includes(t.metadata?.source)||t.metadata?.source==="ai_chat_runtime_node"&&Object.hasOwn(dt,t.framework||""))){a.mcpServers=t.mcpServers;let c=this.sessions.get(`${n}:${s}`);if(c){if(!c.runtime.refreshMcpServers)throw Object.assign(new Error("This runtime cannot refresh task MCP credentials"),{code:"unsupported_dynamic_mcp"});await c.runtime.refreshMcpServers(t.mcpServers)}}return this.attachOperation(a,r)}if(t.attachOnly===!0&&!(t.metadata?.source==="channel_message"&&this.targetFor(t.targetCode||t.framework).target.type==="openclaw"))throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"})}else if(t.attachOnly===!0)throw Object.assign(new Error("correlationId is required for attachOnly"),{code:"BAD_REQUEST"});let o=i?this.createOperation(i,t,n,s):null;if(o){let a=this.attachOperation(o,r);return(async()=>{try{await this._promptOwned(t,{},o,n,s)}catch(c){let l=o.status==="completed";this.failOperation(o,c),l&&g("warn","runtime-bridge","runtime cleanup failed after operation completion",{correlationId:o.correlationId,error:String(c)})}})(),await a}return await this._promptOwned(t,r,o,n,s)}async _promptOwned(t,r,n,s,i){let o=u(t.runId),a=this.config.sandboxRequired?ft(n?.sandboxPolicy||t.sandboxPolicy):null,c=this.agents.get(s),l=this.targetFor(t.targetCode||t.framework||c?.targetCode);if(c&&c.targetCode!==l.code)throw Object.assign(new Error(`runtime agent target conflict: ${s}`),{code:"RUNTIME_AGENT_TARGET_CONFLICT"});if(et(l.target)==="cli"&&Pc(t.goalContract))throw Object.assign(new Error("CLI runtimes do not support per-run dynamic MCP required by plugin_operation"),{code:"unsupported_dynamic_mcp"});let p=c||(await this.createAgent({agentId:s,targetCode:l.code,framework:t.framework,workspace:t.workspace,metadata:t.metadata})).agent;if(!this.config.sandboxRequired){let y=u(t.workspace);y&&y!==p.workspace&&(p.workspace=y)}let m=`${s}:${i}`;await this.cleanupExpiredSessions();let f=this.sessions.get(m),h=null;if(f&&f.targetCode!==l.code)throw Object.assign(new Error(`runtime session target conflict: ${i}`),{code:"RUNTIME_SESSION_TARGET_CONFLICT"});if(f&&this.config.sandboxRequired&&f.runId!==o)throw Object.assign(new Error(`runtime session cannot be shared across runs: ${i}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});if(!f){if(this.startingSessions.has(m))throw Object.assign(new Error(`runtime session is already starting: ${i}`),{code:"RUNTIME_SESSION_BUSY"});this.startingSessions.add(m);let{code:y,target:O}=l,M;try{await this.reserveTargetSlot(y,O),h=y;let A=this.runtimeFor(p,i,{runId:o,sandboxPolicy:a,source:t.metadata?.source,attachOnly:t.attachOnly});M=A;let T=n?.mcpServers||t.mcpServers||[],x=await A.sessionNew({cwd:K(O,p.workspace),mcpServers:T,metadata:d(t.metadata)?t.metadata:{}});if(n&&n.status!=="running")throw Object.assign(new Error("Runtime operation was cancelled before prompt dispatch"),{code:"RUNTIME_OPERATION_CANCELLED"});let S=Date.now();f={agentId:s,sessionId:i,runtime:A,targetCode:y,runtimeKind:et(O),runId:o,sandboxPolicy:a?structuredClone(a):null,runtimeSessionId:u(d(x)?x.sessionId:"")||i,idleTtlMs:this.targetIdleTtlMs(O),releaseAfterPrompt:this.config.sandboxRequired?!0:this.targetReleaseAfterPrompt(O,t.metadata),createdAtMs:S,lastUsedAtMs:S,busy:!1,createdAt:Mt()},this.sessions.set(m,f),this.runtimeSessionIndex.set(`${s}:${f.runtimeSessionId}`,f),n?.mcpServers!==T&&n?.mcpServers&&A.refreshMcpServers&&await A.refreshMcpServers(n.mcpServers)}catch(A){throw this.sessions.get(m)?.runtime===M?await this.closeSession(m,"session_start_failed"):await M?.stop("session_start_failed"),h&&(this.releaseTargetSlot(h),h=null),A}finally{this.startingSessions.delete(m)}}if(f.busy){let y=new Error(`runtime session is already running: ${i}`);throw y.code="RUNTIME_SESSION_BUSY",y}f.busy=!0,h&&this.releaseTargetSlot(h),this.notifyCapacityChanged(),f.operationCorrelationId=n?.correlationId||null,f.lastUsedAtMs=Date.now();let _=n?.updates||[],w=vc(y=>{let O=Lc(y,i,f);if(_.push(O),n)for(let M of n.listeners)try{M?.(O)}catch(A){g("warn","runtime-bridge","runtime operation update listener failed",{correlationId:n.correlationId,error:String(A)})}else r.onUpdate?.(O)}),I=w.push,E=y=>{if(w.flush(),!(!n||n.status!=="running"||!d(y))){if(y.status==="failed"){let O=y.error;if(O instanceof Error){this.failOperation(n,O);return}let M=d(O)?O:{},A=Object.assign(new Error(u(M.message||y.message)||"runtime terminal failure"),{code:u(M.code||y.code)||"RUNTIME_TERMINAL_FAILED"});this.failOperation(n,A);return}this.completeOperation(n,this.promptResponse(t,f,i,_,d(y.result)?y.result:{stopReason:"end_turn"}))}},C=async y=>{try{return await f.runtime.sessionPrompt(y,I,E)}finally{w.flush()}};try{let y=hs(t.goalContract),O=Array.isArray(t.prompt)?[...t.prompt]:[];y&&O.unshift({type:"text",text:y,metadata:{source:"orcha_goal_contract"}});let M=d(t.metadata)?t.metadata:{},A=d(M._runtimeBridge)?M._runtimeBridge:{},T=await C({sessionId:f.runtimeSessionId,...t.modelOptions?{modelOptions:t.modelOptions}:{},prompt:O,metadata:M}),x=_,S=null;if(As({type:f.runtimeKind})&&eu(T,_,A)){S=T;let z=_.length,b=await C({sessionId:f.runtimeSessionId,...t.modelOptions?{modelOptions:t.modelOptions}:{},prompt:[{type:"text",text:ru()}],metadata:M,_meta:{thinking:"off"}});T=nu(S,b),x=_.slice(z)}let U;try{U=this.promptResponse(t,f,i,_,T,x)}catch(z){throw S&&Ls(T)?iu(T,x):z}return S&&(U.result=su(U.result,S)),n&&this.completeOperation(n,U),U}finally{f.busy=!1,this.notifyCapacityChanged(),f.operationCorrelationId===n?.correlationId&&(f.operationCorrelationId=null),f.lastUsedAtMs=Date.now(),this.promptReleaseAfterPrompt(f,d(t.metadata)?t.metadata:{})&&await this.closeSession(m,"release_after_prompt"),n&&(n.mcpServers=null)}}async updatePolicy(t){if(this.assertDispatchable(),!this.config.sandboxRequired)throw Object.assign(new Error("runtime sandbox policy updates require an enforced sandbox"),{code:"RUNTIME_NODE_SANDBOX_UNAVAILABLE"});let r=u(t.agentId),n=u(t.runId),s=u(t.sessionId),i=u(t.correlationId);if(!r||!n||!s||!i)throw Object.assign(new Error("agentId, runId, sessionId and correlationId are required"),{code:"BAD_REQUEST"});let o=ft(t.sandboxPolicy),a=this.operations.get(i);if(a&&(a.agentId!==r||a.sessionId!==s||a.identity.runId!==n))throw Object.assign(new Error(`runtime operation policy identity conflict: ${i}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let c=`${r}:${s}`,l=this.sessions.get(c);if(l&&l.runId!==n)throw Object.assign(new Error(`runtime session policy identity conflict: ${s}`),{code:"RUNTIME_SESSION_RUN_CONFLICT"});let p=l?.sandboxPolicy||a?.sandboxPolicy;if(!p)throw Object.assign(new Error(`runtime operation is no longer available: ${i}`),{code:"RUNTIME_OPERATION_NOT_FOUND"});let m=Number(p.policyRevision),f=Number(o.policyRevision);if(f<m)throw Object.assign(new Error("runtime sandbox policy revision is stale"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:m});if(f===m){if(Z(p)!==Z(o))throw Object.assign(new Error("runtime sandbox policy revision payload conflicts"),{code:"RUNTIME_POLICY_REVISION_CONFLICT",currentPolicyRevision:m});return{updated:!1,idempotent:!0,policyRevision:m,accessMode:p.accessMode}}let h=ws(p,o);a&&(a.sandboxPolicy=structuredClone(o)),l&&(l.sandboxPolicy=structuredClone(o));let _=!1;return h&&l?.busy===!0&&(await l.runtime.sessionCancel({sessionId:l.runtimeSessionId}),_=await this.closeSession(c,"sandbox_policy_downgrade")),{updated:!0,policyRevision:f,accessMode:o.accessMode,activeCommandCancelled:_,deferredToNextLaunch:!h&&l?.busy===!0}}async cancel(t){let r=u(t.agentId),n=u(t.sessionId),s=u(t.correlationId);if(s){let a=this.operations.get(s);if(!a||a.status!=="running")return{cancelled:!1,correlationId:s,reason:"operation_not_running"};if(a.agentId!==r||a.sessionId!==n)throw Object.assign(new Error(`runtime operation cancellation identity conflict: ${s}`),{code:"RUNTIME_OPERATION_CORRELATION_CONFLICT"});let c=this.sessions.get(`${r}:${n}`);return!c||c.busy!==!0||c.operationCorrelationId!==s?(this.failOperation(a,Object.assign(new Error("Runtime operation cancelled before dispatch"),{code:"RUNTIME_OPERATION_CANCELLED"})),{cancelled:!0,correlationId:s,reason:"cancelled_before_dispatch"}):(await c.runtime.sessionCancel({sessionId:c.runtimeSessionId}),await this.closeSession(`${r}:${n}`,"cancelled"),{cancelled:!0,correlationId:s})}let i=`${r}:${n}`,o=this.sessions.get(i);return o?(await o.runtime.sessionCancel({sessionId:o.runtimeSessionId}),await this.closeSession(i,"cancelled"),{cancelled:!0}):{cancelled:!1}}async dispatch(t,r={}){let n=u(t.agentId),s=u(t.taskId),i=u(t.executionId);if(!n||!s)throw Object.assign(new Error("agentId and taskId are required"),{status:400,code:"BAD_REQUEST"});let o=u(t.sessionId)||`dispatch-${i||s}`,a=u(t.instructions),c=Kc(t),l=bs(t),{target:p}=this.targetFor(t.targetCode||t.framework),m=[{type:"text",text:["Task dispatch received.",`taskId: ${s}`,i?`executionId: ${i}`:"",a?`instructions: ${a}`:"",c?"orchaContext:":"",c,c?"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.",l?`For decision results, put the raw report between ${ar} and ${cr}.`:"",l?`Then put a JSON object containing _decision between ${ur} and ${lr}.`:"",l?"Do not JSON-escape the report. Keep output out of the CONTROL JSON, and put every protocol marker on its own line.":"",l?`Keep the report within ${Cs} Unicode characters so the CONTROL block fits before the output limit.`:"","Return only the final answer required by that protocol.","Do not include process notes, logs, or explanations."].filter(Boolean).join(`
33
+ `)}];return this.prompt({...t,agentId:n,sessionId:o,prompt:m,metadata:Gc(t,p)},r)}async requestPermission({agent:t,runtimeSessionId:r,request:n,emitUpdate:s,signal:i}){let o=_e(),c=this.runtimeSessionIndex.get(`${t.agentId}:${r}`)?.sessionId||r||_e(),l=R(n?.timeoutMs,this.config.permissionRequestTimeoutMs),p={permissionId:o,agentId:t.agentId,sessionId:c,runtimeSessionId:r,request:d(n)?n:{},status:"pending",createdAt:Mt(),expiresAt:new Date(Date.now()+l).toISOString()};return i?.aborted?{permissionId:o,outcome:"cancelled",response:{reason:"runtime turn ended"}}:await new Promise(m=>{let f=(w,I)=>{clearTimeout(_),i?.removeEventListener("abort",h),this.pendingPermissions.delete(o),s?.({sessionId:r,update:{sessionUpdate:"permission_resolved",permissionId:o,outcome:I}}),m(w)},h=()=>f({permissionId:o,outcome:"cancelled",response:{reason:"runtime turn ended"}},"cancelled"),_=setTimeout(()=>f({permissionId:o,outcome:"denied",response:{reason:"permission request timed out"}},"expired"),l);i?.addEventListener("abort",h,{once:!0}),this.pendingPermissions.set(o,{settle:f,permission:p}),s?.({sessionId:r,update:{sessionUpdate:"permission_request",permission:p}})})}async respondPermission(t){let r=u(t.permissionId),n=this.pendingPermissions.get(r),s=u(t.outcome||"approved")||"approved";return n?(n.settle({permissionId:r,outcome:s,response:d(t.response)?t.response:{},userId:u(t.userId),metadata:d(t.metadata)?t.metadata:{}},s),{accepted:!0,permissionId:r,outcome:s}):{accepted:!1,permissionId:r,outcome:s}}health(){return{status:this.config.sandboxRequired&&!this.sandboxCapabilities.dispatchable?"unavailable":"ok",bridgeVersion:B,startedAt:this.startedAt,agents:[...this.agents.values()].map(t=>({agentId:t.agentId,targetCode:t.targetCode,framework:t.framework,runtimeKind:t.runtimeKind})),sessions:this.sessions.size,pendingPermissions:this.pendingPermissions.size,targets:Object.keys(this.targets),sandboxCapabilities:this.sandboxCapabilities}}};import ou from"node:http";import au from"node:https";import{randomBytes as ks}from"node:crypto";var It=1,mt=3,cu=1e4,Te=class{constructor(t,r={}){this.url=t,this.readyState=0,this.socket=null,this.request=null,this.buffer=Buffer.alloc(0),this.listeners=new Map,this.connectTimeoutMs=uu(r.connectTimeoutMs,cu),this.connectTimer=null,this.connect()}addEventListener(t,r){let n=this.listeners.get(t)||new Set;n.add(r),this.listeners.set(t,n)}emit(t,r={}){let n=this.listeners.get(t);if(n)for(let s of n)s(r)}connect(){let t=new URL(this.url),r=t.protocol==="wss:"?au:ou,n=ks(16).toString("base64"),s=r.request({protocol:t.protocol==="wss:"?"https:":"http:",hostname:t.hostname,port:t.port||(t.protocol==="wss:"?443:80),path:`${t.pathname}${t.search}`,method:"GET",headers:{Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Key":n,"Sec-WebSocket-Version":"13"}});this.request=s,this.startConnectTimer(s),s.on("upgrade",(i,o,a)=>{if(this.clearConnectTimer(),this.readyState===mt){o.destroy();return}this.socket=o,this.readyState=It,o.on("data",c=>this.onData(c)),o.on("close",()=>this.onClose()),o.on("error",c=>{this.readyState!==mt&&this.emit("error",{error:c,message:c.message,type:"error"}),this.onClose()}),a?.length&&this.onData(a),this.emit("open")}),s.on("response",i=>{this.clearConnectTimer(),this.emit("error",{message:`websocket upgrade failed: HTTP ${i.statusCode}`,statusCode:i.statusCode,type:"error"}),i.resume(),this.onClose()}),s.on("error",i=>{this.clearConnectTimer(),this.readyState!==mt&&this.emit("error",{error:i,message:i.message,type:"error"}),this.onClose()}),s.end()}startConnectTimer(t){this.connectTimeoutMs<=0||(this.connectTimer=setTimeout(()=>{if(this.readyState===It||this.readyState===mt)return;let r=`websocket connect timeout after ${this.connectTimeoutMs}ms`;this.emit("error",{message:r,type:"timeout"}),this.onClose(),t.destroy(new Error(r))},this.connectTimeoutMs),this.connectTimer.unref?.())}clearConnectTimer(){this.connectTimer&&(clearTimeout(this.connectTimer),this.connectTimer=null)}send(t){!this.socket||this.readyState!==It||this.socket.write($r(1,Buffer.from(String(t),"utf8")))}close(){if(this.readyState!==mt){if(this.clearConnectTimer(),!this.socket){this.request?.destroy(),this.onClose();return}try{this.readyState===It&&this.socket.write($r(8,Buffer.alloc(0))),this.socket.end()}catch{this.socket.destroy()}this.onClose()}}onClose(){this.readyState!==mt&&(this.clearConnectTimer(),this.readyState=mt,this.request=null,this.emit("close"))}onData(t){for(this.buffer=Buffer.concat([this.buffer,t]);this.buffer.length>=2;){let r=this.buffer[0],n=this.buffer[1],s=r&15,i=(n&128)!==0,o=n&127,a=2;if(o===126){if(this.buffer.length<a+2)return;o=this.buffer.readUInt16BE(a),a+=2}else if(o===127){if(this.buffer.length<a+8)return;let p=this.buffer.readUInt32BE(a),m=this.buffer.readUInt32BE(a+4);o=p*2**32+m,a+=8}let c=a;if(i&&(a+=4),this.buffer.length<a+o)return;let l=this.buffer.subarray(a,a+o);if(i){let p=this.buffer.subarray(c,c+4);l=Buffer.from(l.map((m,f)=>m^p[f%4]))}this.buffer=this.buffer.subarray(a+o),s===1?this.emit("message",{data:l.toString("utf8")}):s===8?this.close():s===9&&this.socket?.write($r(10,l))}}};function uu(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function $r(e,t){let r=t.length,n=2;r>=126&&r<=65535?n+=2:r>65535&&(n+=8);let s=ks(4),i=Buffer.alloc(n+4+r);i[0]=128|e;let o=2;r<126?i[1]=128|r:r<=65535?(i[1]=254,i.writeUInt16BE(r,o),o+=2):(i[1]=255,i.writeUInt32BE(Math.floor(r/2**32),o),i.writeUInt32BE(r>>>0,o+4),o+=8),s.copy(i,o),o+=4;for(let a=0;a<r;a+=1)i[o+a]=t[a]^s[a%4];return i}var lu=6e4;function du(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 pu(e,t=!0){return Object.entries(e||{}).map(([r,n])=>({targetCode:r,targetName:u(n?.name||n?.targetName||r),targetType:u(n?.type||"echo"),status:t?"available":"unavailable"}))}var fu=Object.freeze(["health","agents/create","agents/dispatch","sessions/prompt","sessions/policy","sessions/cancel","permissions/respond"]),Ee=class{constructor(t,r){this.config=t,this.bridge=r,this.ws=null,this.stopped=!1,this.connected=!1,this.reconnectTimer=null,this.reconnectAttempts=0,this.heartbeatTimer=null,this.capacityHeartbeatTimer=null,this.bridge.onCapacityChanged=()=>this.scheduleCapacityHeartbeat()}sandboxCapabilities(){return this.bridge.sandboxCapabilities||{dispatchable:this.config.sandboxRequired!==!0,enforced:!1,backend:"development_direct",daemonStatus:"development_only",policySchemaVersions:[1],runtimePolicyUpdates:!0,workspaceSync:!1,egressProxy:!1}}supportedMethods(){return[...fu,...this.config.deviceConnection?["devices/discover","devices/configure","agents/models"]:[]]}runtimeTargets(){let t=this.sandboxCapabilities().dispatchable===!0;return typeof this.bridge.targetCapacitySnapshot=="function"?this.bridge.targetCapacitySnapshot(t):pu(this.config.targets,t)}start(){this.connect()}stop(){this.stopped=!0,this.connected=!1,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.capacityHeartbeatTimer&&clearTimeout(this.capacityHeartbeatTimer),this.capacityHeartbeatTimer=null,this.bridge.onCapacityChanged=null,this.ws?.close()}connect(){if(this.stopped)return;let t=du(this.config.orchaUrl),r=new Te(t,{connectTimeoutMs:this.config.connectTimeoutMs});this.ws=r,r.addEventListener("open",()=>{if(this.ws!==r||this.stopped){r.close();return}this.authenticate(r)}),r.addEventListener("message",n=>this.handleMessage(n.data,r)),r.addEventListener("close",()=>this.scheduleReconnect("close",r)),r.addEventListener("error",n=>{if(!(this.ws!==r||this.stopped)){if(n.statusCode===401||n.statusCode===403){this.rejectAuthentication(n.statusCode);return}g("warn","orcha-client","runtime node websocket error",{error:String(n?.message||n?.type||n)})}})}authenticate(t=this.ws){this.send({type:"runtime_node.authenticate",token:this.config.nodeToken,nodeId:this.config.nodeId,nodeName:this.config.nodeName,version:B,protocolVersion:"orcha-runtime-node.v2",defaultTargetCode:this.config.defaultTargetCode,supportedMethods:this.supportedMethods(),sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()},t)}scheduleReconnect(t,r=this.ws){if(r&&this.ws!==r||(this.connected=!1,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.capacityHeartbeatTimer&&clearTimeout(this.capacityHeartbeatTimer),this.capacityHeartbeatTimer=null,r&&this.ws===r&&(this.ws=null),this.stopped)||this.reconnectTimer)return;let n=Math.min(lu,this.config.reconnectMs*2**Math.min(this.reconnectAttempts,16)),s=Math.round(n*(.75+Math.random()*.25));this.reconnectAttempts+=1,g("info","orcha-client","runtime node disconnected; reconnect scheduled",{reason:t,reconnectMs:s}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},s)}rejectAuthentication(t){g("error","orcha-client","runtime node authentication rejected; update credentials and restart the bridge",{code:t}),this.stop()}async handleMessage(t,r=this.ws){if(this.stopped||r&&this.ws!==r)return;let n;try{n=JSON.parse(String(t))}catch(s){g("warn","orcha-client","invalid Orcha websocket frame",{error:String(s)});return}if(d(n)){if(n.type==="runtime_node.authenticated"){if(r&&this.ws!==r)return;this.connected=!0,this.reconnectAttempts=0,this.startHeartbeat(r),g("info","orcha-client","runtime node authenticated",{nodeId:this.config.nodeId,connectionId:n.connectionId});return}if(n.type==="runtime_node.error"){n.code===401||n.code===403?this.rejectAuthentication(n.code):g("warn","orcha-client","runtime node server error",{code:n.code});return}if(n.type==="orcha.runtime.request"){await this.handleRequest(n);return}n.type==="runtime_node.ping"&&this.send({type:"runtime_node.pong",ts:new Date().toISOString(),supportedMethods:this.supportedMethods(),sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()})}}startHeartbeat(t){this.heartbeatTimer&&clearInterval(this.heartbeatTimer);let r=Math.max(1e3,Number(this.config.heartbeatIntervalMs||15e3)),n=()=>this.sendCapacityHeartbeat(t);n(),this.heartbeatTimer=setInterval(n,r),this.heartbeatTimer.unref?.()}scheduleCapacityHeartbeat(){if(!this.connected||this.capacityHeartbeatTimer)return;let t=Math.max(25,Math.min(1e3,Number(this.config.capacityHeartbeatDebounceMs||100)));this.capacityHeartbeatTimer=setTimeout(()=>{this.capacityHeartbeatTimer=null,this.sendCapacityHeartbeat()},t),this.capacityHeartbeatTimer.unref?.()}sendCapacityHeartbeat(t=this.ws){return this.connected?this.send({type:"runtime_node.heartbeat",ts:new Date().toISOString(),supportedMethods:this.supportedMethods(),sandboxCapabilities:this.sandboxCapabilities(),targets:this.runtimeTargets()},t):!1}async handleRequest(t){let r=u(t.id),n=u(t.method),s=d(t.params)?t.params:{};try{let i=await this.invoke(n,s,r);this.send({type:"orcha.runtime.response",id:r,ok:!0,result:i})}catch(i){this.send({type:"orcha.runtime.response",id:r,ok:!1,error:{code:i.code||"RUNTIME_NODE_ERROR",message:i.message||String(i),...i.detail===void 0?{}:{detail:i.detail}}})}}async invoke(t,r,n){if(t==="agents/models"&&this.config.deviceConnection)return ne(this.bridge.targetFor(r.targetCode).target);if(t==="devices/discover"&&this.config.deviceConnection)return this.config.deviceConnection.candidates();if(t==="devices/configure"&&this.config.deviceConnection)return this.config.deviceConnection.configure(r,this.bridge);if(t==="health")return this.bridge.health();if(t==="agents/create")return this.bridge.createAgent(r);if(t==="agents/dispatch")return this.bridge.dispatch(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/prompt")return this.bridge.prompt(r,{onUpdate:s=>this.sendUpdate(n,s)});if(t==="sessions/policy")return this.bridge.updatePolicy(r);if(t==="sessions/cancel")return this.bridge.cancel(r);if(t==="permissions/respond")return this.bridge.respondPermission(r);throw Object.assign(new Error(`unsupported Orcha runtime method: ${t}`),{code:"METHOD_NOT_FOUND"})}sendUpdate(t,r){this.send({type:"orcha.runtime.event",requestId:t,eventType:"runtime.update",payload:r})}send(t,r=this.ws){return!r||r!==this.ws||r.readyState!==It?!1:(r.send(JSON.stringify(t)),!0)}};import{createServer as mu}from"node:http";function Oe(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 ht(e={}){return{ok:!0,...e}}function Hr(e,t,r){return{ok:!1,error:{code:e,message:t,...r===void 0?{}:{detail:r}}}}async function vs(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(!d(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 Ds(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 $s(e,t){let r={"GET /health":async()=>ht(t.health()),"POST /agents/create":async n=>ht(await t.createAgent(n)),"POST /agents/dispatch":async n=>ht(await t.dispatch(n)),"POST /sessions/prompt":async n=>ht(await t.prompt(n)),"POST /sessions/cancel":async n=>ht(await t.cancel(n)),"POST /permissions/respond":async n=>ht(await t.respondPermission(n))};return mu(async(n,s)=>{let i=new URL(n.url||"/",`http://${n.headers.host||`${e.host}:${e.port}`}`),o=`${n.method||"GET"} ${i.pathname}`,a=r[o];if(!a){Oe(s,404,Hr("NOT_FOUND",`No route for ${o}`));return}try{Ds(n,e.token);let c=n.method==="GET"?{}:await vs(n,e.requestLimitBytes);Oe(s,200,await a(c))}catch(c){let l=c.status||500,p=c.code||"BRIDGE_INTERNAL";Oe(s,l,Hr(p,c.message||String(c),c.detail))}})}var zs=Tu(import.meta.url),Eu=".orcha-runtime-bridge.pid",Ou=".orcha-runtime-bridge.log",Su=3,Ru=36e5,{command:Iu,options:Vs}=Au(process.argv.slice(2));bu(Vs);Mn();var Cu=Un();await Js(Iu,Cu,Vs);async function Js(e,t,r){if(r.url){let s=Qe(r.url);r.pidFile||(process.env.ORCHA_RUNTIME_PID_FILE=s.pidFile),r.logFile||(process.env.ORCHA_RUNTIME_LOG_FILE=s.logFile)}let n=()=>["connect","--url",t.orchaUrl,"--foreground"];switch(e){case"connect":if(r.pairCode&&gt(Re(Se())))throw new Error("\u8BBE\u5907\u8FDE\u63A5\u4ECD\u5728\u540E\u53F0\u8FD0\u884C\uFF0C\u8BF7\u5148\u6267\u884C stop --url \u540E\u91CD\u65B0\u914D\u5BF9");await se(t,r),r.foreground?await Fr(t):Br(n());return;case"run":case"foreground":r.url&&await se(t,r),await Fr(t);return;case"start":if(r.url)return Js("connect",t,r);if(r.foreground){await Fr(t);return}Br();return;case"reload":case"restart":{r.url&&await se(t,{url:r.url});let s=Ct(Ks(zs),".."),i=Ct(s,...Kr(Ct(s,"src","index.js"))?["dist","package"]:[],"openclaw-plugin"),o=await as(t.targets,i);await Bs({quiet:!0}),await o(),Br(r.url?n():void 0);return}case"stop":await Bs();return;case"status":xu();return;case"help":case"--help":case"-h":Pu();return;default:throw new Error(`Unknown command: ${e}`)}}async function Fr(e){Nu();let t=new we(e);if(await t.start(),e.mode==="server"){let n=$s(e,t);Fs({bridge:t,server:n}),n.listen(e.port,e.host,()=>{g("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 Ee(e,t);Fs({bridge:t,client:r}),r.start(),g("info","runtime-bridge","Orcha runtime node started",{nodeId:e.nodeId,nodeName:e.nodeName,orchaUrl:e.orchaUrl,targets:Object.keys(t.targets)})}function Fs({bridge:e,client:t,server:r}){let n=!1,s=i=>{if(n)return;n=!0;let o=Number(e?.sessions?.size||0)>0;g("info","runtime-bridge","runtime bridge shutting down",{signal:i});try{t?.stop?.()}catch(a){g("warn","runtime-bridge","runtime client stop failed",{error:String(a)})}Promise.resolve(e?.stop?.(`process_${String(i||"shutdown").toLowerCase()}`)).catch(a=>{g("warn","runtime-bridge","runtime bridge stop failed",{error:String(a)})}).finally(()=>{try{r?.close?.()}catch(a){g("warn","runtime-bridge","runtime server close failed",{error:String(a)})}}),setTimeout(()=>process.exit(0),o?8500:200)};process.once("SIGTERM",()=>s("SIGTERM")),process.once("SIGINT",()=>s("SIGINT"))}function Br(e=["run"]){let t=Se(),r=Ws(),n=Re(t);if(n&&gt(n)){console.log(JSON.stringify({status:"already_running",pid:n,pidFile:t,logFile:r}));return}n&&Gr(t),qs(t),qs(r),qr(r);let s=yu(r,"a"),i={...process.env,ORCHA_RUNTIME_PID_FILE:t,ORCHA_RUNTIME_LOG_FILE:r},o=hu(process.execPath,[zs,...e,"--pid-file",t,"--log-file",r],{cwd:process.cwd(),detached:!0,env:i,stdio:["ignore",s,s]});o.unref(),gu(s),Gs(t,`${o.pid}
34
+ `),console.log(JSON.stringify({status:"started",pid:o.pid,pidFile:t,logFile:r}))}async function Bs({quiet:e=!1}={}){let t=Se(),r=Re(t);if(!r){e||console.log(JSON.stringify({status:"not_running",pidFile:t}));return}if(!gt(r)){Gr(t),e||console.log(JSON.stringify({status:"not_running",pid:r,pidFile:t}));return}process.kill(r,"SIGTERM"),!await js(r,1e4)&&gt(r)&&(process.kill(r,"SIGKILL"),await js(r,3e3)),Gr(t),e||console.log(JSON.stringify({status:"stopped",pid:r,pidFile:t}))}function xu(){let e=Se(),t=Ws(),r=Re(e),n=!!(r&&gt(r));console.log(JSON.stringify({status:n?"running":"not_running",running:n,pid:n?r:null,pidFile:e,logFile:t}))}function Au(e){let t=[],r={};for(let s=0;s<e.length;s+=1){let i=e[s];i==="--url"?r.url=e[++s]:i==="--pair-code"?r.pairCode=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 bu(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 Se(){return Ct(process.cwd(),process.env.ORCHA_RUNTIME_PID_FILE||Eu)}function Ws(){return Ct(process.cwd(),process.env.ORCHA_RUNTIME_LOG_FILE||Ou)}function Nu(){let e=process.env.ORCHA_RUNTIME_LOG_FILE;if(!e)return;let t=Xs();if(t<=0)return;let r=Ct(process.cwd(),e);qr(r,t);let n=Uu();n<=0||setInterval(()=>qr(r,t),n).unref()}function qr(e,t=Xs()){if(t<=0||!Kr(e))return;let r=0,n="";try{if(r=Hs(e).size,r<=0)return;n=jr(e,"utf8")}catch(l){g("warn","runtime-bridge","runtime log cleanup skipped",{logFile:e,error:String(l)});return}let s=Date.now()-t*24*60*60*1e3,i=n.split(/\r?\n/),o=[],a=0;for(let l of i)l&&(Mu(l,s)?o.push(l):a+=1);if(a===0)return;let c="";try{Hs(e).size>r&&(c=jr(e,"utf8").slice(n.length));let p=[...o,...c.split(/\r?\n/).filter(Boolean)].join(`
35
35
  `);Gs(e,p?`${p}
36
- `:""),_("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:a})}catch(l){_("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(l)})}}function Nu(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 Xs(){return Ys(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,Ou)}function Mu(){return Ys(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Su)}function Ys(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function Re(e){if(!Kr(e))return null;let t=Number.parseInt(jr(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function gt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function js(e,t){let r=Date.now();for(;Date.now()-r<t;){if(!gt(e))return!0;await new Promise(n=>setTimeout(n,100))}return!gt(e)}function qs(e){gu(Ks(e),{recursive:!0})}function Gr(e){try{yu(e,{force:!0})}catch{}}function Uu(){console.log(`Usage: orcha-runtime-bridge [command] [options]
36
+ `:""),g("info","runtime-bridge","runtime log cleanup completed",{logFile:e,retentionDays:t,removed:a})}catch(l){g("warn","runtime-bridge","runtime log cleanup failed",{logFile:e,error:String(l)})}}function Mu(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 Xs(){return Ys(process.env.ORCHA_RUNTIME_LOG_RETENTION_DAYS,Su)}function Uu(){return Ys(process.env.ORCHA_RUNTIME_LOG_CLEANUP_INTERVAL_MS,Ru)}function Ys(e,t){let r=Number.parseInt(String(e??""),10);return Number.isFinite(r)&&r>=0?r:t}function Re(e){if(!Kr(e))return null;let t=Number.parseInt(jr(e,"utf8").trim(),10);return Number.isInteger(t)&&t>0?t:null}function gt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}async function js(e,t){let r=Date.now();for(;Date.now()-r<t;){if(!gt(e))return!0;await new Promise(n=>setTimeout(n,100))}return!gt(e)}function qs(e){_u(Ks(e),{recursive:!0})}function Gr(e){try{wu(e,{force:!0})}catch{}}function Pu(){console.log(`Usage: orcha-runtime-bridge [command] [options]
37
37
 
38
38
  Commands:
39
39
  connect Pair or reconnect this device, then run in the background.
@@ -1,8 +1,8 @@
1
- import{getPluginRuntimeGatewayRequestScope as Ke}from"openclaw/plugin-sdk/plugin-runtime";import{loadOutboundMediaFromUrl as Ye}from"openclaw/plugin-sdk/outbound-media";function Ce(e){return String(e??"").trim()}var Q="[redacted]",Re=/(authorization|api[_-]?key|credential|password|secret|token)/i;function ce(e){return Re.test(Ce(e))}function le(e,t=[]){let i=String(e??"");for(let g of t){let l=String(g??"");l.length>=4&&(i=i.split(l).join(Q))}return i.replace(/((?:authorization|api[_-]?key|credential|password|secret|token)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,`$1${Q}`).replace(/([?&](?:api[_-]?key|credential|password|secret|token)=)[^&\s]+/gi,`$1${Q}`)}var z={controlTools:["find_capabilities_and_skills","describe_capability","inspect_result","execute_capability"],residentTools:["search_orcha_docs","knowledge_search"]};var Z=Object.freeze([...z.controlTools,...z.residentTools]),xe=new Set(Z),Pe=8*1024*1024;function de(e,t){if(!Array.isArray(e)||e.length!==1)throw new Error("one task-scoped Orcha MCP server is required");let i=e[0],g=new URL(i.url);if(i.name!=="orcha"||i.type!=="http"||!["http:","https:"].includes(g.protocol)||g.username||g.password||g.hash||t&&g.href!==new URL(t).href)throw new Error("Orcha MCP server does not match the trusted binding");let l=Object.fromEntries((i.headers||[]).map(({name:T,value:s})=>[T.toLowerCase(),s]));if(!String(l.authorization||"").startsWith("Bearer "))throw new Error("Orcha MCP task credentials are missing");return{url:g.href,headers:{...l,"content-type":"application/json",accept:"application/json"}}}async function B(e){let t=0,i=[];for await(let g of e){if(t+=g.length,t>Pe)throw new Error("MCP payload exceeds the size limit");i.push(Buffer.from(g))}return JSON.parse(Buffer.concat(i).toString("utf8"))}async function q(e,t,i){let g=await fetch(e.url,{method:"POST",headers:e.headers,body:JSON.stringify(t),redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(36e5),...i?[i]:[]])});if(!g.ok)throw new Error(`Orcha MCP request failed (${g.status})`);if(g.status===202||g.status===204)return null;let l=await B(g.body);if(!l||l.jsonrpc!=="2.0"||l.id!==t.id)throw new Error("Orcha MCP response identity mismatch");return l}async function ue(e,t){let i=await q(e,{jsonrpc:"2.0",id:"orcha-bind-tools",method:"tools/list"},t),g=i?.result?.tools;if(i?.error){let l=Object.entries(e.headers).filter(([u])=>ce(u)).flatMap(([,u])=>[u,String(u).replace(/^Bearer\s+/i,"")]),T=typeof i.error.message=="string"?le(i.error.message,l).slice(0,512):"",s=Number.isInteger(i.error.code)?` (${i.error.code})`:"";throw new Error(`Orcha MCP tool discovery failed${s}${T?`: ${T}`:""}`)}return Le(g)}function Le(e){if(!Array.isArray(e)||e.some(t=>!t||!xe.has(t.name)||t.inputSchema?.type!=="object"||typeof t.description!="string")||new Set(e.map(t=>t.name)).size!==e.length||e.length&&z.controlTools.some(t=>!e.some(i=>i.name===t)))throw new Error("Orcha MCP returned an unsupported or invalid authorized tool catalog");return e}function pe(e,t){let i=l=>Array.isArray(l)?l.map(i):l&&typeof l=="object"?Object.fromEntries(Object.keys(l).sort().map(T=>[T,i(l[T])])):l,g=l=>l.map(({name:T,inputSchema:s})=>({name:T,inputSchema:s})).sort((T,s)=>T.name.localeCompare(s.name));return JSON.stringify(i(g(e)))===JSON.stringify(i(g(t)))}var X=e=>Object.assign(new Error(e),{status:409});function fe(e){let t=new Map,i=e.pluginConfig?.allowedOrchaMcpUrl;if(!i)throw new Error("Orcha plugin requires allowedOrchaMcpUrl");function g(s,u=t.get(s)){!u||t.get(s)!==u||(u.lifetime.abort(),clearTimeout(u.timer),t.delete(s))}function l(s){let u=t.get(s);return u&&u.deadline<=Date.now()?(g(s,u),null):u}async function T(s,{refresh:u=!1}={}){let{runId:_,sessionKey:c,agentCode:M,expiresAt:k,mcpServer:n}=s,m=Date.parse(k);if(typeof _!="string"||!_||typeof c!="string"||!c||typeof M!="string"||!M||!c.startsWith(`agent:${M}:`)||!Number.isFinite(m)||m<=Date.now()||m>Date.now()+24*36e5)throw new Error("invalid_binding_scope");let h=l(c);if(u&&!h||h&&(h.runId!==_||h.agentCode!==M||h.deadline!==m))throw X("original_binding_unavailable_or_changed");let L=de([n],i),r=h?.lifetime||new AbortController,d=await ue(L,r.signal);if(l(c)!==h)throw X("binding_changed");if(h){if(!pe(h.tools,d))throw X("frozen_tool_catalog_changed");h.upstream=L}else{let o={runId:_,agentCode:M,deadline:m,upstream:L,tools:d,lifetime:r};o.timer=setTimeout(()=>g(c,o),m-Date.now()),o.timer.unref?.(),t.set(c,o)}}return e.registerTool(s=>{let u=l(s.sessionKey);return!u||s.agentId!==u.agentCode?null:u.tools.map(_=>({name:`orcha_${_.name}`,label:`Orcha ${_.name}`,description:_.description,parameters:_.inputSchema,async execute(c,M,k){if(l(s.sessionKey)!==u||s.agentId!==u.agentCode||!c||!u.tools.some(m=>m.name===_.name))throw new Error("Orcha task binding expired or changed");let n=await q(u.upstream,{jsonrpc:"2.0",id:c,method:"tools/call",params:{name:_.name,arguments:M}},AbortSignal.any([u.lifetime.signal,...k?[k]:[]]));if(n?.error||!n?.result)throw new Error("Orcha rejected this task-scoped tool call");return{content:n.result.content,details:n.result.structuredContent,isError:n.result.isError===!0}}}))},{names:Z.map(s=>`orcha_${s}`)}),{bind:T,active:l,release:g,allowedUrl:i}}import{createHash as $e}from"node:crypto";import{mkdirSync as He,readFileSync as De,renameSync as ve,writeFileSync as Be}from"node:fs";import{join as ye}from"node:path";import{createHash as ke}from"node:crypto";var me=e=>ke("sha256").update(JSON.stringify(e)).digest("hex"),j=e=>Object.assign(new Error(e),{code:e}),ee=e=>{let t=String(e||"").replace(/^orcha:/,"");return/^[1-9]\d{0,18}$/.test(t)?t:void 0},he={normalizeTarget:ee,targetResolver:{looksLikeId:e=>!!ee(e),hint:"Orcha session ID"}};function ge({core:e,load:t,save:i,loadMedia:g,activeRun:l}){let T=new Map,s=(n,m)=>me([n,m]),u=n=>({channel:"orcha",messageId:n.messageId,chatId:n.sessionId,receipt:{primaryPlatformMessageId:n.messageId,platformMessageIds:[n.messageId],parts:[{platformMessageId:n.messageId,kind:"unknown",index:0}],sentAt:Date.now()}});async function _(n,m,h={}){return await h.onPlatformSendDispatch?.(),h.signal?.throwIfAborted(),u(await e(n,"/messages",m.payload,{cfg:h.cfg,signal:h.signal}))}async function c(n){n.signal?.throwIfAborted();let m=ee(n.to);if(!m)throw j("invalid_conversation");if(!n.deliveryQueueId)throw j("OPENCLAW_DURABLE_DELIVERY_ID_REQUIRED");let h=n.run&&n.run.delivery.bindingId===n.accountId&&n.run.delivery.sessionId===m?n.run:null,L=n.replyToId||h?.delivery.messageId||null,r=n.payload||{text:n.text||"",mediaUrl:n.mediaUrl},d=r.mediaUrls||(r.mediaUrl?[r.mediaUrl]:[]),o=s(n.accountId,n.deliveryQueueId),a=me([m,r.text||"",d,L,h?.runId||null]),p=t(o,"sends");if(p&&p.requestHash!==a)throw j("channel_send_conflict");let y=T.get(o);if(y){if(y.requestHash!==a)throw j("channel_send_conflict");return y.promise}let E=(async()=>{let O=p;if(!O){let S=[];for(let I of d){let P=await g(I,{maxBytes:33554432,mediaAccess:n.mediaAccess,mediaReadFile:n.mediaReadFile,mediaLocalRoots:n.mediaLocalRoots}),N=new FormData;N.set("sessionId",m),N.set("file",new Blob([P.buffer],{type:P.contentType||"application/octet-stream"}),P.fileName||"attachment"),S.push((await e(n.accountId,"/files",N,{cfg:n.cfg,signal:n.signal})).inputPart)}O={requestHash:a,payload:{sourceMessageId:`openclaw:${o}`,sessionId:m,content:r.text||"",inputParts:S,...L?{replyToMessageId:L}:{},...h?{agentRunId:h.runId}:{}}},i(o,O,"sends")}let w=await _(n.accountId,O,n);return h&&!h.messageIds.includes(w.messageId)&&h.messageIds.push(w.messageId),w})().finally(()=>T.delete(o));return T.set(o,{requestHash:a,promise:E}),E}return{send:c,message:{send:{text:c,media:c,payload:c},durableFinal:{capabilities:{text:!0,media:!0,payload:!0,replyTo:!0,reconcileUnknownSend:!0},reconcileUnknownSendKinds:{text:!0,media:!0,payload:!0},async reconcileUnknownSend(n){let m=t(s(n.accountId,n.queueId),"sends");if(!m)return{status:"not_sent"};if(m.payload.sessionId!==String(n.to).replace(/^orcha:/,""))throw j("channel_send_conflict");let h=await _(n.accountId,m,n);return{status:"sent",receipt:h.receipt,messageId:h.messageId}}}},actions:{describeMessageTool:()=>({actions:["send"],mediaSourceParams:{send:["media"]}}),supportsAction:({action:n})=>n==="send",isToolDeliveryAction:({args:n})=>n.action==="send",extractToolSend:({args:n})=>typeof(n.to||n.target)=="string"?{to:n.to||n.target,accountId:n.accountId}:null,async handleAction(n){if(n.action!=="send")throw j("unsupported_channel_action");let m=n.params;if(n.dryRun)return{content:[{type:"text",text:"Orcha send dry run"}],details:{dryRun:!0}};let h=l(n.sessionKey),L=await c({cfg:n.cfg,accountId:n.accountId,to:m.to||m.target,text:m.message,mediaUrl:m.media,replyToId:m.replyTo,deliveryQueueId:m.idempotencyKey,mediaAccess:n.mediaAccess,mediaLocalRoots:n.mediaLocalRoots,mediaReadFile:n.mediaReadFile,run:h,signal:h?.controller.signal});return{content:[{type:"text",text:JSON.stringify(L)}],details:L}}}}}var K="application/x-orcha-channel-events-v2+ndjson";function Y(e,t){return Object.assign(new Error(t||(["run_timeout","RUNTIME_NODE_TIMEOUT"].includes(e)?"OpenClaw \u539F\u751F IM \u6267\u884C\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002":e==="OPENCLAW_CHANNEL_PROTOCOL_MISMATCH"?"OpenClaw \u63D2\u4EF6\u4E0E Bridge \u7684\u539F\u751F IM \u534F\u8BAE\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u914D\u5957\u5347\u7EA7\u3002":`OpenClaw \u539F\u751F IM \u6267\u884C\u5931\u8D25\uFF08${e}\uFF09`)),{code:e})}function te(e,t){let i=e.cause?.code||e.code;return t?.reason?.name==="TimeoutError"||e.name==="TimeoutError"||["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","ETIMEDOUT"].includes(i)?Object.assign(Y("RUNTIME_NODE_TIMEOUT","OpenClaw \u8FDE\u63A5\u6216\u7B49\u5F85\u54CD\u5E94\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002"),{detail:{causeCode:i||"REQUEST_TIMEOUT"}}):e}var Ie=e=>$e("sha256").update(JSON.stringify(e)).digest("hex"),R=(e,t=409)=>Object.assign(new Error(e),{status:t,code:e}),V=e=>typeof e=="string"&&/^[1-9]\d{0,18}$/.test(e),je=e=>new Promise(t=>setTimeout(t,e));function we(e,t,i){return`agent:${e}:orcha:task:${Ie([i,t.bindingId,t.bindingRevision,t.sessionId,t.taskContextId,t.memberId,t.historyFromSeq,t.runtimePolicyRevision])}`}function _e(e,t,i,g,l,T){let s=new Map;e.on("before_message_write",({message:r},d)=>{if(r?.role!=="assistant")return;let o=t.active(d.sessionKey),a=s.get(o?.runId);a&&d.agentId===o.agentCode&&(a.silentFinal=T(r))});let u=()=>e.config;function _(r,d=u()){let o=d?.channels?.orcha?.accounts?.[r];if(!V(r)||!o||o.enabled===!1||!o.serviceToken||!o.agentId)throw R("orcha_channel_account_unavailable",403);return{...o,accountId:r}}async function c(r,d,o,{cfg:a,signal:p,method:y="POST"}={}){let E=_(r,a),O=new URL(`/api/agent-channels${d}`,t.allowedUrl),w=o instanceof FormData,S=AbortSignal.any([AbortSignal.timeout(3e4),...p?[p]:[]]);try{let I=await fetch(O,{method:y,redirect:"error",signal:S,headers:{authorization:`Bearer ${E.serviceToken}`,...w?{}:{"content-type":"application/json"}},...o!==void 0?{body:w?o:JSON.stringify(o)}:{}}),P=await B(I.body);if(!I.ok||P.success!==!0)throw R(`orcha_channel_request_${I.status}`,I.status);return P.data}catch(I){throw te(I,S)}}function M(r,d="runs"){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(r))throw R("invalid_record_identity",422);let o=ye(e.runtime.state.resolveStateDir(),"plugins","orcha-runtime",d);return He(o,{recursive:!0,mode:448}),ye(o,`${r}.json`)}function k(r,d){try{return JSON.parse(De(M(r,d),"utf8"))}catch(o){if(o.code==="ENOENT")return null;throw o}}function n(r,d,o){let a=M(r,o),p=`${a}.pending`;Be(p,JSON.stringify(d),{mode:384}),ve(p,a)}async function m(r,d=!1,o){let a=_(r.delivery?.bindingId),{runId:p,delivery:y}=r;if(!V(p)||!V(y.sessionId)||y.taskContextId!==null&&!V(y.taskContextId)||y.mode!=="channel"||r.agentCode!==a.agentId)throw R("invalid_channel_delivery",422);if(!Array.isArray(r.prompt)||r.prompt.some(C=>!["text","image","file"].includes(C.type)||(C.type==="text"?typeof C.text!="string":typeof C.uri!="string")))throw R("invalid_channel_prompt",422);let E=Ie({agentCode:r.agentCode,delivery:y,prompt:r.prompt}),O=k(p);if(O&&O.requestHash!==E)throw R("channel_delivery_conflict");if(O?.status==="completed")return O.result;if(O?.status==="failed")throw R(O.error);let w=s.get(p),S=O?.expiresAt||r.expiresAt,I=we(a.agentId,y,t.allowedUrl),P=()=>{let C=t.active(I);C?.runId===p&&t.release(I,C)},N=O?.hostRunId||`orcha-${p}`;if(O&&!w||r.attachOnly&&!w&&!O)throw R("RUNTIME_OPERATION_NOT_FOUND");if(w){try{await t.bind({runId:p,sessionKey:I,agentCode:a.agentId,expiresAt:S,mcpServer:r.mcpServer},{refresh:!0})}catch(C){if(s.get(p)!==w)return await w.promise;throw C}if(d)return{refreshed:!0};w.listeners.add(o);try{for(let C of w.updates)o?.(C);return await w.promise}finally{w.listeners.delete(o)}}if(d)throw R("RUNTIME_OPERATION_NOT_FOUND");let b=new AbortController,x={runId:p,delivery:y,messageIds:[],controller:b,promise:null,listeners:new Set(o?[o]:[]),updates:[],bytes:0},H=C=>{let U={type:"update",payload:{sessionId:I,update:C,_meta:{channelUpdateId:`${N}:${x.updates.length+1}`}}},D=Buffer.byteLength(JSON.stringify(U));if(D>2097152||x.bytes+D>16777216){b.abort(Y("OPENCLAW_CHANNEL_PROGRESS_LIMIT"));return}x.bytes+=D,x.updates.push(U);for(let G of x.listeners)G?.(U)};return s.set(p,x),x.promise=(async()=>{await t.bind({runId:p,sessionKey:I,agentCode:a.agentId,expiresAt:S,mcpServer:r.mcpServer}),n(p,{requestHash:E,status:"running",sessionKey:I,hostRunId:N,expiresAt:S});let C=0,U,D,G=setTimeout(()=>b.abort(R("run_timeout")),Date.parse(S)-Date.now());try{let J=e.runtime.channel.reply;if(typeof J?.dispatchReplyWithBufferedBlockDispatcher!="function"||typeof e.runtime.events?.onAgentEvent!="function")throw R("OPENCLAW_CHANNEL_RUNTIME_UNAVAILABLE");D=e.runtime.events.onAgentEvent(f=>{let A=f.data;f.runId!==N||f.stream!=="tool"||!A?.toolCallId||A.hideFromChannelProgress||!["start","update","result"].includes(A.phase)||H({sessionUpdate:A.phase==="start"?"tool_call":"tool_call_update",toolCallId:A.toolCallId,title:A.name,status:A.phase==="result"?A.isError?"failed":"completed":"in_progress",...A.args?{rawInput:A.args}:{},...A.result!==void 0?{rawOutput:A.result}:{}})});let $="",re="",F="",Se=f=>{if(typeof f.text!="string")return;let A=[re,f.text].filter(Boolean).join(`
1
+ import{getPluginRuntimeGatewayRequestScope as Ve}from"openclaw/plugin-sdk/plugin-runtime";import{loadOutboundMediaFromUrl as Ge}from"openclaw/plugin-sdk/outbound-media";function Re(e){return String(e??"").trim()}var q="[redacted]",Me=/(authorization|api[_-]?key|credential|password|secret|token)/i;function de(e){return Me.test(Re(e))}function ue(e,t=[]){let a=String(e??"");for(let w of t){let d=String(w??"");d.length>=4&&(a=a.split(d).join(q))}return a.replace(/((?:authorization|api[_-]?key|credential|password|secret|token)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,`$1${q}`).replace(/([?&](?:api[_-]?key|credential|password|secret|token)=)[^&\s]+/gi,`$1${q}`)}var Y={controlTools:["find_capabilities_and_skills","describe_capability","inspect_result","execute_capability"],residentTools:["search_orcha_docs","knowledge_search"]};var X=Object.freeze([...Y.controlTools,...Y.residentTools]),Pe=new Set(X),xe=8*1024*1024;function pe(e,t){if(!Array.isArray(e)||e.length!==1)throw new Error("one task-scoped Orcha MCP server is required");let a=e[0],w=new URL(a.url);if(a.name!=="orcha"||a.type!=="http"||!["http:","https:"].includes(w.protocol)||w.username||w.password||w.hash||t&&w.href!==new URL(t).href)throw new Error("Orcha MCP server does not match the trusted binding");let d=Object.fromEntries((a.headers||[]).map(({name:T,value:s})=>[T.toLowerCase(),s]));if(!String(d.authorization||"").startsWith("Bearer "))throw new Error("Orcha MCP task credentials are missing");return{url:w.href,headers:{...d,"content-type":"application/json",accept:"application/json"}}}async function j(e){let t=0,a=[];for await(let w of e){if(t+=w.length,t>xe)throw new Error("MCP payload exceeds the size limit");a.push(Buffer.from(w))}return JSON.parse(Buffer.concat(a).toString("utf8"))}async function ee(e,t,a){let w=await fetch(e.url,{method:"POST",headers:e.headers,body:JSON.stringify(t),redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(36e5),...a?[a]:[]])});if(!w.ok)throw new Error(`Orcha MCP request failed (${w.status})`);if(w.status===202||w.status===204)return null;let d=await j(w.body);if(!d||d.jsonrpc!=="2.0"||d.id!==t.id)throw new Error("Orcha MCP response identity mismatch");return d}async function fe(e,t){let a=await ee(e,{jsonrpc:"2.0",id:"orcha-bind-tools",method:"tools/list"},t),w=a?.result?.tools;if(a?.error){let d=Object.entries(e.headers).filter(([u])=>de(u)).flatMap(([,u])=>[u,String(u).replace(/^Bearer\s+/i,"")]),T=typeof a.error.message=="string"?ue(a.error.message,d).slice(0,512):"",s=Number.isInteger(a.error.code)?` (${a.error.code})`:"";throw new Error(`Orcha MCP tool discovery failed${s}${T?`: ${T}`:""}`)}return Ue(w)}function Ue(e){if(!Array.isArray(e)||e.some(t=>!t||!Pe.has(t.name)||t.inputSchema?.type!=="object"||typeof t.description!="string")||new Set(e.map(t=>t.name)).size!==e.length||e.length&&Y.controlTools.some(t=>!e.some(a=>a.name===t)))throw new Error("Orcha MCP returned an unsupported or invalid authorized tool catalog");return e}function me(e,t){let a=d=>Array.isArray(d)?d.map(a):d&&typeof d=="object"?Object.fromEntries(Object.keys(d).sort().map(T=>[T,a(d[T])])):d,w=d=>d.map(({name:T,inputSchema:s})=>({name:T,inputSchema:s})).sort((T,s)=>T.name.localeCompare(s.name));return JSON.stringify(a(w(e)))===JSON.stringify(a(w(t)))}var te=e=>Object.assign(new Error(e),{status:409});function he(e){let t=new Map,a=e.pluginConfig?.allowedOrchaMcpUrl;if(!a)throw new Error("Orcha plugin requires allowedOrchaMcpUrl");function w(s,u=t.get(s)){!u||t.get(s)!==u||(u.lifetime.abort(),clearTimeout(u.timer),t.delete(s))}function d(s){let u=t.get(s);return u&&u.deadline<=Date.now()?(w(s,u),null):u}async function T(s,{refresh:u=!1}={}){let{runId:I,sessionKey:p,agentCode:N,expiresAt:U,mcpServer:n}=s,_=Date.parse(U);if(typeof I!="string"||!I||typeof p!="string"||!p||typeof N!="string"||!N||!p.startsWith(`agent:${N}:`)||!Number.isFinite(_)||_<=Date.now()||_>Date.now()+24*36e5)throw new Error("invalid_binding_scope");let f=d(p);if(u&&!f||f&&(f.runId!==I||f.agentCode!==N||f.deadline!==_))throw te("original_binding_unavailable_or_changed");let L=pe([n],a),x=f?.lifetime||new AbortController,v=await fe(L,x.signal);if(d(p)!==f)throw te("binding_changed");if(f){if(!me(f.tools,v))throw te("frozen_tool_catalog_changed");f.upstream=L}else{let r={runId:I,agentCode:N,deadline:_,upstream:L,tools:v,lifetime:x};r.timer=setTimeout(()=>w(p,r),_-Date.now()),r.timer.unref?.(),t.set(p,r)}}return e.registerTool(s=>{let u=d(s.sessionKey);return!u||s.agentId!==u.agentCode?null:u.tools.map(I=>({name:`orcha_${I.name}`,label:`Orcha ${I.name}`,description:I.description,parameters:I.inputSchema,async execute(p,N,U){if(d(s.sessionKey)!==u||s.agentId!==u.agentCode||!p||!u.tools.some(_=>_.name===I.name))throw new Error("Orcha task binding expired or changed");let n=await ee(u.upstream,{jsonrpc:"2.0",id:p,method:"tools/call",params:{name:I.name,arguments:N}},AbortSignal.any([u.lifetime.signal,...U?[U]:[]]));if(n?.error||!n?.result)throw new Error("Orcha rejected this task-scoped tool call");return{content:n.result.content,details:n.result.structuredContent,isError:n.result.isError===!0}}}))},{names:X.map(s=>`orcha_${s}`)}),{bind:T,active:d,release:w,allowedUrl:a}}import{createHash as De}from"node:crypto";import{once as He}from"node:events";import{mkdirSync as $e,readFileSync as Be,renameSync as je,writeFileSync as Fe}from"node:fs";import{join as _e}from"node:path";import{createHash as ke}from"node:crypto";var ge=e=>ke("sha256").update(JSON.stringify(e)).digest("hex"),F=e=>Object.assign(new Error(e),{code:e}),ne=e=>{let t=String(e||"").replace(/^orcha:/,"");return/^[1-9]\d{0,18}$/.test(t)?t:void 0},ye={normalizeTarget:ne,targetResolver:{looksLikeId:e=>!!ne(e),hint:"Orcha session ID"}};function we({core:e,load:t,save:a,loadMedia:w,activeRun:d}){let T=new Map,s=(n,_)=>ge([n,_]),u=n=>({channel:"orcha",messageId:n.messageId,chatId:n.sessionId,receipt:{primaryPlatformMessageId:n.messageId,platformMessageIds:[n.messageId],parts:[{platformMessageId:n.messageId,kind:"unknown",index:0}],sentAt:Date.now()}});async function I(n,_,f={}){return await f.onPlatformSendDispatch?.(),f.signal?.throwIfAborted(),f.assertDirectAdapterHandoff?.(),u(await e(n,"/messages",_.payload,{cfg:f.cfg,signal:f.signal}))}async function p(n){n.signal?.throwIfAborted();let _=ne(n.to);if(!_)throw F("invalid_conversation");if(!n.deliveryQueueId)throw F("OPENCLAW_DURABLE_DELIVERY_ID_REQUIRED");let f=n.run&&n.run.delivery.bindingId===n.accountId&&n.run.delivery.sessionId===_?n.run:null,L=n.replyToId||f?.delivery.messageId||null,x=n.payload||{text:n.text||"",mediaUrl:n.mediaUrl},v=x.mediaUrls||(x.mediaUrl?[x.mediaUrl]:[]),r=s(n.accountId,n.deliveryQueueId),i=ge([_,x.text||"",v,L,f?.runId||null]),o=t(r,"sends");if(o&&o.requestHash!==i)throw F("channel_send_conflict");let c=T.get(r);if(c){if(c.requestHash!==i)throw F("channel_send_conflict");return c.promise}let m=(async()=>{let h=o;if(!h){let O=[];for(let E of v){let A=await w(E,{maxBytes:33554432,mediaAccess:n.mediaAccess,mediaReadFile:n.mediaReadFile,mediaLocalRoots:n.mediaLocalRoots}),y=new FormData;y.set("sessionId",_),y.set("file",new Blob([A.buffer],{type:A.contentType||"application/octet-stream"}),A.fileName||"attachment"),O.push((await e(n.accountId,"/files",y,{cfg:n.cfg,signal:n.signal})).inputPart)}h={requestHash:i,payload:{sourceMessageId:`openclaw:${r}`,sessionId:_,content:x.text||"",inputParts:O,...L?{replyToMessageId:L}:{},...f?{agentRunId:f.runId}:{}}},a(r,h,"sends")}let l=await I(n.accountId,h,n);return f&&!f.messageIds.includes(l.messageId)&&f.messageIds.push(l.messageId),l})().finally(()=>T.delete(r));return T.set(r,{requestHash:i,promise:m}),m}return{send:p,message:{send:{text:p,media:p,payload:p},durableFinal:{capabilities:{text:!0,media:!0,payload:!0,replyTo:!0,reconcileUnknownSend:!0},automaticUnknownSendReconciliation:!0,reconcileUnknownSendKinds:{text:!0,media:!0,payload:!0},async reconcileUnknownSend(n){let _=t(s(n.accountId,n.queueId),"sends");if(!_)return{status:"not_sent"};if(_.payload.sessionId!==String(n.to).replace(/^orcha:/,""))throw F("channel_send_conflict");let f=await I(n.accountId,_,n);return{status:"sent",receipt:f.receipt,messageId:f.messageId}}}},actions:{describeMessageTool:()=>({actions:["send"],mediaSourceParams:{send:["media"]}}),supportsAction:({action:n})=>n==="send",isToolDeliveryAction:({args:n})=>n.action==="send",extractToolSend:({args:n})=>typeof(n.to||n.target)=="string"?{to:n.to||n.target,accountId:n.accountId}:null,async handleAction(n){if(n.action!=="send")throw F("unsupported_channel_action");let _=n.params;if(n.dryRun)return{content:[{type:"text",text:"Orcha send dry run"}],details:{dryRun:!0}};let f=d(n.sessionKey),L=await p({cfg:n.cfg,accountId:n.accountId,to:_.to||_.target,text:_.message,mediaUrl:_.media,replyToId:_.replyTo,deliveryQueueId:_.idempotencyKey,mediaAccess:n.mediaAccess,mediaLocalRoots:n.mediaLocalRoots,mediaReadFile:n.mediaReadFile,run:f,signal:f?.controller.signal});return{content:[{type:"text",text:JSON.stringify(L)}],details:L}}}}}var V="application/x-orcha-channel-events-v2+ndjson";function G(e,t){return Object.assign(new Error(t||(["run_timeout","RUNTIME_NODE_TIMEOUT"].includes(e)?"OpenClaw \u539F\u751F IM \u6267\u884C\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002":e==="OPENCLAW_CHANNEL_PROTOCOL_MISMATCH"?"OpenClaw \u63D2\u4EF6\u4E0E Bridge \u7684\u539F\u751F IM \u534F\u8BAE\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u914D\u5957\u5347\u7EA7\u3002":`OpenClaw \u539F\u751F IM \u6267\u884C\u5931\u8D25\uFF08${e}\uFF09`)),{code:e})}function re(e,t){let a=e.cause?.code||e.code;return t?.reason?.name==="TimeoutError"||e.name==="TimeoutError"||["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","ETIMEDOUT"].includes(a)?Object.assign(G("RUNTIME_NODE_TIMEOUT","OpenClaw \u8FDE\u63A5\u6216\u7B49\u5F85\u54CD\u5E94\u8D85\u65F6\uFF0C\u4EFB\u52A1\u5DF2\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002"),{detail:{causeCode:a||"REQUEST_TIMEOUT"}}):e}var Ie=e=>De("sha256").update(JSON.stringify(e)).digest("hex"),b=(e,t=409)=>Object.assign(new Error(e),{status:t,code:e}),Q=e=>typeof e=="string"&&/^[1-9]\d{0,18}$/.test(e),Je=e=>new Promise(t=>setTimeout(t,e));function Ee(e,t,a){return`agent:${e}:orcha:task:${Ie([a,t.bindingId,t.bindingRevision,t.sessionId,t.taskContextId,t.memberId,t.historyFromSeq,t.runtimePolicyRevision])}`}function Oe(e,t,a,w,d,T){let s=new Map,u=new Map;e.on("before_message_write",({message:r},i)=>{if(r?.role!=="assistant")return;let o=t.active(i.sessionKey),c=s.get(o?.runId);c&&i.agentId===o.agentCode&&(c.silentFinal=T(r))});let I=()=>e.runtime.config.current();function p(r){let i=u.get(r);if(!i||i.aborted)throw b("OPENCLAW_CHANNEL_RUNTIME_UNAVAILABLE",503);return i}function N(r,i=I()){let o=i?.channels?.orcha?.accounts?.[r];if(!Q(r)||!o||o.enabled===!1||!o.serviceToken||!o.agentId)throw b("orcha_channel_account_unavailable",403);return{...o,accountId:r}}async function U(r,i,o,{cfg:c,signal:m,method:h="POST"}={}){let l=N(r,c),O=new URL(`/api/agent-channels${i}`,t.allowedUrl),E=o instanceof FormData,A=AbortSignal.any([AbortSignal.timeout(3e4),p(r),...m?[m]:[]]);try{A.throwIfAborted();let y=await fetch(O,{method:h,redirect:"error",signal:A,headers:{authorization:`Bearer ${l.serviceToken}`,...E?{}:{"content-type":"application/json"}},...o!==void 0?{body:E?o:JSON.stringify(o)}:{}}),k=await j(y.body);if(!y.ok||k.success!==!0)throw b(`orcha_channel_request_${y.status}`,y.status);return k.data}catch(y){throw re(y,A)}}function n(r,i="runs"){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(r))throw b("invalid_record_identity",422);let o=_e(e.runtime.state.resolveStateDir(),"plugins","orcha-runtime",i);return $e(o,{recursive:!0,mode:448}),_e(o,`${r}.json`)}function _(r,i){try{return JSON.parse(Be(n(r,i),"utf8"))}catch(o){if(o.code==="ENOENT")return null;throw o}}function f(r,i,o){let c=n(r,o),m=`${c}.pending`;Fe(m,JSON.stringify(i),{mode:384}),je(m,c)}async function L(r,i=!1,o){let c=N(r.delivery?.bindingId);p(c.accountId);let{runId:m,delivery:h}=r;if(!Q(m)||!Q(h.sessionId)||h.taskContextId!==null&&!Q(h.taskContextId)||h.mode!=="channel"||r.agentCode!==c.agentId)throw b("invalid_channel_delivery",422);if(!Array.isArray(r.prompt)||r.prompt.some(R=>!["text","image","file"].includes(R.type)||(R.type==="text"?typeof R.text!="string":typeof R.uri!="string")))throw b("invalid_channel_prompt",422);let l=Ie({agentCode:r.agentCode,delivery:h,prompt:r.prompt}),O=_(m);if(O&&O.requestHash!==l)throw b("channel_delivery_conflict");if(O?.status==="completed")return O.result;if(O?.status==="failed")throw b(O.error);let E=s.get(m),A=O?.expiresAt||r.expiresAt,y=Ee(c.agentId,h,t.allowedUrl),k=()=>{let R=t.active(y);R?.runId===m&&t.release(y,R)},P=O?.hostRunId||`orcha-${m}`;if(O&&!E||r.attachOnly&&!E&&!O)throw b("RUNTIME_OPERATION_NOT_FOUND");if(E){try{await t.bind({runId:m,sessionKey:y,agentCode:c.agentId,expiresAt:A,mcpServer:r.mcpServer},{refresh:!0})}catch(R){if(s.get(m)!==E)return await E.promise;throw R}if(i)return{refreshed:!0};E.listeners.add(o);try{for(let R of E.updates)o?.(R);return await E.promise}finally{E.listeners.delete(o)}}if(i)throw b("RUNTIME_OPERATION_NOT_FOUND");let C=new AbortController,M={runId:m,delivery:h,messageIds:[],controller:C,promise:null,listeners:new Set(o?[o]:[]),updates:[],bytes:0},$=R=>{let D={type:"update",payload:{sessionId:y,update:R,_meta:{channelUpdateId:`${P}:${M.updates.length+1}`}}},B=Buffer.byteLength(JSON.stringify(D));if(B>2097152||M.bytes+B>16777216){C.abort(G("OPENCLAW_CHANNEL_PROGRESS_LIMIT"));return}M.bytes+=B,M.updates.push(D);for(let Z of M.listeners)Z?.(D)};return s.set(m,M),M.promise=(async()=>{await t.bind({runId:m,sessionKey:y,agentCode:c.agentId,expiresAt:A,mcpServer:r.mcpServer}),f(m,{requestHash:l,status:"running",sessionKey:y,hostRunId:P,expiresAt:A});let R=0,D,B,Z=setTimeout(()=>C.abort(b("run_timeout")),Date.parse(A)-Date.now());try{let z=e.runtime.channel.reply;if(typeof z?.dispatchReplyWithBufferedBlockDispatcher!="function"||typeof e.runtime.events?.onAgentEvent!="function")throw b("OPENCLAW_CHANNEL_RUNTIME_UNAVAILABLE");B=e.runtime.events.onAgentEvent(g=>{let S=g.data;g.runId!==P||g.stream!=="tool"||!S?.toolCallId||S.hideFromChannelProgress||!["start","update","result"].includes(S.phase)||$({sessionUpdate:S.phase==="start"?"tool_call":"tool_call_update",toolCallId:S.toolCallId,title:S.name,status:S.phase==="result"?S.isError?"failed":"completed":"in_progress",...S.args?{rawInput:S.args}:{},...S.result!==void 0?{rawOutput:S.result}:{}})});let H="",ie="",J="",be=g=>{if(typeof g.text!="string")return;let S=[ie,g.text].filter(Boolean).join(`
2
2
 
3
- `);if(A===F)return;let v=A.startsWith(F);H({sessionUpdate:v?"agent_message_chunk":"agent_message_snapshot",content:{type:"text",text:v?A.slice(F.length):A}}),F=A},oe=f=>{if(f.requiresReasoningProgressOptIn||typeof f.text!="string")return;let A=f.text.startsWith($)?f.text.slice($.length):f.text;$=f.text,A&&H({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:A}})},W=r.prompt.filter(f=>f.type==="text").map(f=>f.text).join(`
3
+ `);if(S===J)return;let W=S.startsWith(J);$({sessionUpdate:W?"agent_message_chunk":"agent_message_snapshot",content:{type:"text",text:W?S.slice(J.length):S}}),J=S},ae=g=>{if(g.requiresReasoningProgressOptIn||typeof g.text!="string")return;let S=g.text.startsWith(H)?g.text.slice(H.length):g.text;H=g.text,S&&$({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:S}})},K=r.prompt.filter(g=>g.type==="text").map(g=>g.text).join(`
4
4
 
5
- `),ie=r.prompt.filter(f=>f.type!=="text"),be={Body:W,BodyForAgent:W,BodyForCommands:W,RawBody:W,From:`orcha:${y.memberId}`,To:`orcha:${y.sessionId}`,SessionKey:I,AccountId:y.bindingId,Provider:"orcha",Surface:"orcha",ChatType:"direct",OriginatingChannel:"orcha",OriginatingTo:y.sessionId,MessageSid:y.messageId||p,MediaUrls:ie.map(f=>f.uri),MediaTypes:ie.map(f=>f.mimeType||"application/octet-stream"),CommandAuthorized:!1,WasMentioned:!0};if(await J.dispatchReplyWithBufferedBlockDispatcher({ctx:be,cfg:u(),replyOptions:{runId:N,abortSignal:b.signal,suppressTyping:!0,suppressDefaultToolProgressMessages:!0,suppressToolErrorWarnings:!0,disableBlockStreaming:!0,reasoningPayloadsEnabled:!0,commentaryPayloadsEnabled:!0,onAssistantMessageStart:()=>{$="",re=F},onPartialReply:Se,onReasoningStream:oe},dispatcherOptions:{deliver:async(f,A)=>{if(b.signal.throwIfAborted(),f.isReasoning&&oe(f),f.isCommentary&&f.text&&H({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:f.text}}),A.kind==="final"&&g(f)){if(x.silentFinal&&x.messageIds.length&&!f.isError)return;let v=u(),ae=v?.agents?.list?.find(Ne=>Ne.id===a.agentId)?.workspace||v?.agents?.defaults?.workspace;await h.send({cfg:v,accountId:y.bindingId,to:y.sessionId,payload:f,run:x,deliveryQueueId:`${N}:final:${++C}`,signal:b.signal,mediaLocalRoots:ae?[ae]:void 0})}},onError:f=>{U??=f}}}),U)throw U;if(b.signal.throwIfAborted(),!x.messageIds.length)throw R("runtime_node_empty_result");let se={stopReason:"end_turn",messageIds:x.messageIds,sessionId:I};return n(p,{requestHash:E,status:"completed",sessionKey:I,hostRunId:N,expiresAt:S,result:se}),se}catch(J){let $=b.signal.aborted?b.signal.reason:te(J,b.signal);throw n(p,{requestHash:E,status:"failed",sessionKey:I,hostRunId:N,expiresAt:S,error:$.code||"channel_host_failed"}),$}finally{D?.(),clearTimeout(G),P(),s.delete(p)}})().catch(C=>{throw P(),s.delete(p),C}),x.promise}let h=ge({core:c,load:k,save:n,loadMedia:l,activeRun:r=>s.get(t.active(r)?.runId)});e.registerChannel({plugin:{id:"orcha",meta:{id:"orcha",label:"Orcha",selectionLabel:"Orcha",docsPath:"/channels/orcha",blurb:"Enterprise people and Agent conversations"},capabilities:{chatTypes:["direct","group"],media:!0},config:{listAccountIds:r=>Object.keys(r?.channels?.orcha?.accounts||{}),inspectAccount:(r,d)=>{let o=r?.channels?.orcha?.accounts?.[d];return{enabled:!!(o&&o.enabled!==!1),configured:!!(o?.serviceToken&&o?.agentId),tokenStatus:o?.serviceToken?"available":"missing"}},resolveAccount:(r,d)=>_(d,r),isEnabled:r=>r.enabled!==!1,isConfigured:r=>!!(r.serviceToken&&r.agentId)},outbound:{deliveryMode:"direct",textChunkLimit:1e5},message:h.message,actions:h.actions,messaging:he}});async function L(r){let{accountId:d,grantId:o,externalInvocationId:a}=r;_(d);let p=await c(d,"/runs",{grantId:o,externalInvocationId:a,input:r.input||{}}),y=p.agentRunId;if(["completed","failed","cancelled","expired"].includes(p.status))return p;let E;do E=await c(d,`/runs/${y}/claim`,{}),E.attemptId||await je(Math.max(1,E.retryAfterSeconds||2)*1e3);while(!E.attemptId);let O=we(_(d).agentId,E.delivery,t.allowedUrl),w,S=!1,I=setInterval(async()=>{if(!S){S=!0;try{let b=await c(d,`/runs/${y}/heartbeat`,{attemptId:E.attemptId});t.active(O)&&await t.bind({runId:y,sessionKey:O,agentCode:_(d).agentId,expiresAt:E.expiresAt,mcpServer:b.mcpServer},{refresh:!0})}catch(b){w=b,s.get(y)?.controller.abort(b),t.release(O)}finally{S=!1}}},Math.max(1,E.heartbeatIntervalSeconds)*1e3),P,N;try{let b;try{b=await m({runId:y,agentCode:_(d).agentId,delivery:E.delivery,prompt:[{type:"text",text:JSON.stringify({task:E.prompt,eventInput:E.input})}],mcpServer:E.mcpServer,expiresAt:E.expiresAt,attachOnly:E.recovery})}catch(H){N=H}if(w)throw w;P=N?{attemptId:E.attemptId,errorMessage:Y(N.code||"channel_host_failed").message,status:"failed"}:{attemptId:E.attemptId,messageIds:b.messageIds,status:"completed"};let x=await c(d,`/runs/${y}/complete`,P);if(N)throw N;return x}finally{clearInterval(I),t.release(O)}}for(let[r,d]of[["deliveries",m],["background",L]])e.registerHttpRoute({path:`/plugins/orcha-runtime/${r}`,auth:"gateway",match:"exact",async handler(o,a){let p,y=Promise.resolve(),E=0,O=w=>{if(a.destroyed||a.writableEnded)return;let S=JSON.stringify(w)+`
6
- `,I=Buffer.byteLength(S);if(I>2097152||E+a.writableLength+I>2097152){a.destroy();return}return E+=I,y=y.then(async()=>{a.destroyed||a.writableEnded||(await i(),a.write(S))}).catch(P=>{!a.destroyed&&!a.writableEnded&&a.end(JSON.stringify({type:"error",code:P.code||"OPENCLAW_CHANNEL_AUTH_FAILED"})+`
7
- `)}).finally(()=>{E-=I}),y};try{if(r==="deliveries"&&o.method==="GET"){await i(),a.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({streamType:K}));return}if(!["POST","PATCH","DELETE"].includes(o.method))throw R("method_not_allowed",405);let w=await B(o);if(await i(),r==="deliveries"&&o.method==="POST"){if(o.headers.accept!==K)throw R("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH",409);a.writeHead(200,{"content-type":K,"cache-control":"no-store","x-accel-buffering":"no"}),O({type:"heartbeat"}),p=setInterval(()=>O({type:"heartbeat"}),15e3),a.once("close",()=>clearInterval(p));let I=await m(w,!1,O);await i(),await O({type:"result",result:I}),a.end();return}if(o.method==="DELETE"){let I=s.get(w.runId);I?.controller.abort(R("RUNTIME_OPERATION_CANCELLED")),a.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({cancelled:!!I}));return}if(o.method==="PATCH"&&r!=="deliveries")throw R("method_not_allowed",405);let S=await d(w,o.method==="PATCH");await i(),a.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(S))}catch(w){a.headersSent?(await O({type:"error",code:w.code||"channel_host_failed"}),a.end()):a.writableEnded||a.writeHead(w.status||500,{"content-type":"application/json"}).end(JSON.stringify({error:w.code||w.message}))}finally{clearInterval(p)}}})}function Ee(e,t,i,g){return{id:"orcha-runtime",name:"Orcha Channel and authorized tools",register(l){let T=fe(l);l.registerHttpRoute({path:"/plugins/orcha-runtime/mcp-bindings",auth:"gateway",match:"exact",async handler(s,u){let _=(c,M)=>{u.writeHead(c,{"content-type":"application/json"}),u.end(JSON.stringify(M))};try{if(s.method==="GET"){_(200,{ready:!0});return}if(!["PUT","DELETE"].includes(s.method)){_(405,{error:"method_not_allowed"});return}let c=await B(s);if(await e(),typeof c.runId!="string"||!c.runId||typeof c.sessionKey!="string"||!c.sessionKey){_(422,{error:"invalid_binding_identity"});return}let M=T.active(c.sessionKey);if(s.headers["if-match"]&&s.headers["if-match"]!==c.runId){_(409,{error:"binding_run_conflict"});return}if(M&&M.runId!==c.runId){_(409,{error:"session_already_bound"});return}s.method==="DELETE"?T.release(c.sessionKey):await T.bind(c,{refresh:!!s.headers["if-match"]}),_(200,{[s.method==="DELETE"?"released":"bound"]:!0})}catch(c){u.writableEnded||_(c.status||422,{error:c.message})}}}),_e(l,T,e,t,i,g)}}}import{isFastModeAutoProgressPayload as Fe,isReasoningReplyPayload as Je,isReplyPayloadNonTerminalToolErrorWarning as We,isReplyPayloadTtsSupplement as ze}from"openclaw/plugin-sdk/reply-payload";import{isSilentReplyText as Oe}from"openclaw/plugin-sdk/reply-chunking";function Te(e){return e?.role!=="assistant"||e.stopReason!=="stop"?!1:typeof e.content=="string"?Oe(e.content):!Array.isArray(e.content)||e.content.some(t=>!["text","thinking"].includes(t.type))?!1:Oe(e.content.filter(t=>t.type==="text").map(t=>t.text).join(`
8
- `))}function Ae(e){return!Je(e)&&!e.isCommentary&&!e.isCompactionNotice&&!e.isFallbackNotice&&!e.isStatusNotice&&!Fe(e)&&!We(e)&&!ze(e)}var Tt=Ee(async()=>{await Ke()?.revalidate?.()},Ae,Ye,Te);export{Tt as default};
5
+ `),se=r.prompt.filter(g=>g.type!=="text"),Ce={Body:K,BodyForAgent:K,BodyForCommands:K,RawBody:K,From:`orcha:${h.memberId}`,To:`orcha:${h.sessionId}`,SessionKey:y,AccountId:h.bindingId,Provider:"orcha",Surface:"orcha",ChatType:"direct",OriginatingChannel:"orcha",OriginatingTo:h.sessionId,MessageSid:h.messageId||m,MediaUrls:se.map(g=>g.uri),MediaTypes:se.map(g=>g.mimeType||"application/octet-stream"),CommandAuthorized:!1,WasMentioned:!0};if(await z.dispatchReplyWithBufferedBlockDispatcher({ctx:Ce,cfg:I(),replyOptions:{runId:P,abortSignal:C.signal,suppressTyping:!0,suppressDefaultToolProgressMessages:!0,suppressToolErrorWarnings:!0,disableBlockStreaming:!0,reasoningPayloadsEnabled:!0,commentaryPayloadsEnabled:!0,onAssistantMessageStart:()=>{H="",ie=J},onPartialReply:be,onReasoningStream:ae},dispatcherOptions:{deliver:async(g,S)=>{if(C.signal.throwIfAborted(),g.isReasoning&&ae(g),g.isCommentary&&g.text&&$({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g.text}}),S.kind==="final"&&w(g)){if(M.silentFinal&&M.messageIds.length&&!g.isError)return;let W=I(),le=e.runtime.agent.resolveAgentWorkspaceDir(W,c.agentId);await x.send({cfg:W,accountId:h.bindingId,to:h.sessionId,payload:g,run:M,deliveryQueueId:`${P}:final:${++R}`,signal:C.signal,mediaLocalRoots:le?[le]:void 0})}},onError:g=>{D??=g}}}),D)throw D;if(C.signal.throwIfAborted(),!M.messageIds.length)throw b("runtime_node_empty_result");let ce={stopReason:"end_turn",messageIds:M.messageIds,sessionId:y};return f(m,{requestHash:l,status:"completed",sessionKey:y,hostRunId:P,expiresAt:A,result:ce}),ce}catch(z){let H=C.signal.aborted?C.signal.reason:re(z,C.signal);throw f(m,{requestHash:l,status:"failed",sessionKey:y,hostRunId:P,expiresAt:A,error:H.code||"channel_host_failed"}),H}finally{B?.(),clearTimeout(Z),k(),s.delete(m)}})().catch(R=>{throw k(),s.delete(m),R}),M.promise}let x=we({core:U,load:_,save:f,loadMedia:d,activeRun:r=>s.get(t.active(r)?.runId)});e.registerChannel({plugin:{id:"orcha",meta:{id:"orcha",label:"Orcha",selectionLabel:"Orcha",docsPath:"/channels/orcha",blurb:"Enterprise people and Agent conversations"},capabilities:{chatTypes:["direct","group"],media:!0},config:{listAccountIds:r=>Object.keys(r?.channels?.orcha?.accounts||{}),inspectAccount:(r,i)=>{let o=r?.channels?.orcha?.accounts?.[i];return{enabled:!!(o&&o.enabled!==!1),configured:!!(o?.serviceToken&&o?.agentId),tokenStatus:o?.serviceToken?"available":"missing"}},resolveAccount:(r,i)=>N(i,r),isEnabled:r=>r.enabled!==!1,isConfigured:r=>!!(r.serviceToken&&r.agentId)},gateway:{async startAccount({cfg:r,accountId:i,abortSignal:o,setStatus:c}){if(N(i,r),o.aborted)return;if(u.has(i))throw b("channel_delivery_conflict");u.set(i,o);let m=He(o,"abort");try{c({accountId:i,running:!0,lifecycle:"ready",lastError:null}),await m}finally{u.delete(i);let h=[...s.values()].filter(l=>l.delivery.bindingId===i);for(let l of h)l.controller.abort(b("RUNTIME_OPERATION_CANCELLED"));await Promise.allSettled(h.map(l=>l.promise)),c({accountId:i,running:!1,lifecycle:"stopped"})}}},outbound:{deliveryMode:"direct",textChunkLimit:1e5},message:x.message,actions:x.actions,messaging:ye}});async function v(r){let{accountId:i,grantId:o,externalInvocationId:c}=r;N(i),p(i);let m=await U(i,"/runs",{grantId:o,externalInvocationId:c,input:r.input||{}}),h=m.agentRunId;if(["completed","failed","cancelled","expired"].includes(m.status))return m;let l;do l=await U(i,`/runs/${h}/claim`,{}),l.attemptId||await Je(Math.max(1,l.retryAfterSeconds||2)*1e3);while(!l.attemptId);let O=Ee(N(i).agentId,l.delivery,t.allowedUrl),E,A=!1,y=setInterval(async()=>{if(!A){A=!0;try{let C=await U(i,`/runs/${h}/heartbeat`,{attemptId:l.attemptId});t.active(O)&&await t.bind({runId:h,sessionKey:O,agentCode:N(i).agentId,expiresAt:l.expiresAt,mcpServer:C.mcpServer},{refresh:!0})}catch(C){E=C,s.get(h)?.controller.abort(C),t.release(O)}finally{A=!1}}},Math.max(1,l.heartbeatIntervalSeconds)*1e3),k,P;try{let C;try{C=await L({runId:h,agentCode:N(i).agentId,delivery:l.delivery,prompt:[{type:"text",text:JSON.stringify({task:l.prompt,eventInput:l.input})}],mcpServer:l.mcpServer,expiresAt:l.expiresAt,attachOnly:l.recovery})}catch($){P=$}if(E)throw E;k=P?{attemptId:l.attemptId,errorMessage:G(P.code||"channel_host_failed").message,status:"failed"}:{attemptId:l.attemptId,messageIds:C.messageIds,status:"completed"};let M=await U(i,`/runs/${h}/complete`,k);if(P)throw P;return M}finally{clearInterval(y),t.release(O)}}for(let[r,i]of[["deliveries",L],["background",v]])e.registerHttpRoute({path:`/plugins/orcha-runtime/${r}`,auth:"gateway",match:"exact",async handler(o,c){let m,h=Promise.resolve(),l=0,O=E=>{if(c.destroyed||c.writableEnded)return;let A=JSON.stringify(E)+`
6
+ `,y=Buffer.byteLength(A);if(y>2097152||l+c.writableLength+y>2097152){c.destroy();return}return l+=y,h=h.then(async()=>{c.destroyed||c.writableEnded||(await a(),c.write(A))}).catch(k=>{!c.destroyed&&!c.writableEnded&&c.end(JSON.stringify({type:"error",code:k.code||"OPENCLAW_CHANNEL_AUTH_FAILED"})+`
7
+ `)}).finally(()=>{l-=y}),h};try{if(r==="deliveries"&&o.method==="GET"){await a(),c.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({streamType:V}));return}if(!["POST","PATCH","DELETE"].includes(o.method))throw b("method_not_allowed",405);let E=await j(o);if(await a(),r==="deliveries"&&o.method==="POST"){if(o.headers.accept!==V)throw b("OPENCLAW_CHANNEL_PROTOCOL_MISMATCH",409);c.writeHead(200,{"content-type":V,"cache-control":"no-store","x-accel-buffering":"no"}),O({type:"heartbeat"}),m=setInterval(()=>O({type:"heartbeat"}),15e3),c.once("close",()=>clearInterval(m));let y=await L(E,!1,O);await a(),await O({type:"result",result:y}),c.end();return}if(o.method==="DELETE"){let y=s.get(E.runId);y?.controller.abort(b("RUNTIME_OPERATION_CANCELLED")),c.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({cancelled:!!y}));return}if(o.method==="PATCH"&&r!=="deliveries")throw b("method_not_allowed",405);let A=await i(E,o.method==="PATCH");await a(),c.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(A))}catch(E){c.headersSent?(await O({type:"error",code:E.code||"channel_host_failed"}),c.end()):c.writableEnded||c.writeHead(E.status||500,{"content-type":"application/json"}).end(JSON.stringify({error:E.code||E.message}))}finally{clearInterval(m)}}})}function Te(e,t,a,w){return{id:"orcha-runtime",name:"Orcha Channel and authorized tools",register(d){let T=he(d);d.registerHttpRoute({path:"/plugins/orcha-runtime/mcp-bindings",auth:"gateway",match:"exact",async handler(s,u){let I=(p,N)=>{u.writeHead(p,{"content-type":"application/json"}),u.end(JSON.stringify(N))};try{if(s.method==="GET"){I(200,{ready:!0});return}if(!["PUT","DELETE"].includes(s.method)){I(405,{error:"method_not_allowed"});return}let p=await j(s);if(await e(),typeof p.runId!="string"||!p.runId||typeof p.sessionKey!="string"||!p.sessionKey){I(422,{error:"invalid_binding_identity"});return}let N=T.active(p.sessionKey);if(s.headers["if-match"]&&s.headers["if-match"]!==p.runId){I(409,{error:"binding_run_conflict"});return}if(N&&N.runId!==p.runId){I(409,{error:"session_already_bound"});return}s.method==="DELETE"?T.release(p.sessionKey):await T.bind(p,{refresh:!!s.headers["if-match"]}),I(200,{[s.method==="DELETE"?"released":"bound"]:!0})}catch(p){u.writableEnded||I(p.status||422,{error:p.message})}}}),Oe(d,T,e,t,a,w)}}}import{isFastModeAutoProgressPayload as We,isReasoningReplyPayload as ze,isReplyPayloadNonTerminalToolErrorWarning as Ke,isReplyPayloadTtsSupplement as Ye}from"openclaw/plugin-sdk/reply-payload";import{isSilentReplyText as Ae}from"openclaw/plugin-sdk/reply-chunking";function Se(e){return e?.role!=="assistant"||e.stopReason!=="stop"?!1:typeof e.content=="string"?Ae(e.content):!Array.isArray(e.content)||e.content.some(t=>!["text","thinking"].includes(t.type))?!1:Ae(e.content.filter(t=>t.type==="text").map(t=>t.text).join(`
8
+ `))}function Ne(e){return!ze(e)&&!e.isCommentary&&!e.isCompactionNotice&&!e.isFallbackNotice&&!e.isStatusNotice&&!We(e)&&!Ke(e)&&!Ye(e)}var St=Te(async()=>{await Ve()?.revalidate?.()},Ne,Ge,Se);export{St as default};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orcha-ai/openclaw-tools",
3
- "version": "0.1.57",
3
+ "version": "0.1.59",
4
4
  "type": "module",
5
5
  "private": true,
6
6
  "openclaw": { "extensions": ["./index.js"] }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orcha-ai/runtime-bridge",
3
- "version": "0.1.57",
3
+ "version": "0.1.59",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local Orcha runtime bridge for ACP-compatible agent runtimes.",