@oxgeneral/orch 1.0.23 → 1.0.25
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/dist/{App-FNVF4LSA.js → App-IC2HLH6T.js} +20 -19
- package/dist/chunk-SJG3HXO5.js +5 -0
- package/dist/cli.js +1 -1
- package/dist/{container-KP4ANWU5.js → container-KJNQCG2C.js} +1 -1
- package/dist/{doctor-5TND6NNP.js → doctor-DEGM2HCD.js} +1 -1
- package/dist/index.d.ts +29 -0
- package/dist/index.js +1 -1
- package/dist/{pi-NQ2AD7VM.js → pi-GFJCLRZJ.js} +28 -25
- package/dist/pi-GFJCLRZJ.js.map +1 -0
- package/dist/pi-XEINSHUN.js +2 -0
- package/dist/{task-OSGO6IJQ.js → task-YMPSU6YE.js} +1 -1
- package/dist/{tui-VGIXVVJP.js → tui-NZ55TCHU.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-SSMOFT7C.js +0 -5
- package/dist/pi-NQ2AD7VM.js.map +0 -1
- package/dist/pi-WHXXXVBE.js +0 -2
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a}from'./chunk-P4JTJBWO.js';import {o}from'./chunk-LRYVT4D4.js';import {execFile}from'child_process';var E=class{constructor(e){this.processManager=e;}kind="pi";async test(){try{return {ok:!0,version:(await new Promise((t,r)=>{execFile("pi",["--version"],(o,s)=>{o?r(o):t(s);});})).trim()}}catch(e){let t=e instanceof Error?e.message:String(e);return {ok:false,error:"Pi CLI not found. Install: npm i -g @mariozechner/pi-coding-agent",errorKind:o(t)}}}execute(e){let t=["--mode","rpc"];e.config.model&&t.push("--model",e.config.model),e.config.effort&&t.push("--thinking",e.config.effort);let r=e.systemPrompt??e.config.system_prompt;r&&t.push("--append-system-prompt",r);let{process:o,pid:s}=this.processManager.spawn("pi",t,{cwd:e.workspace,env:{...process.env,...e.env},signal:e.signal,stdio:["pipe","pipe","pipe"]}),i=U(o.stderr);o.stdin&&o.stdin.write(JSON.stringify({id:`orch-${Date.now()}`,type:"prompt",message:e.prompt})+`
|
|
3
|
+
`);let u=R(o,s,this.processManager,i,e.signal);return {pid:s,events:u}}async stop(e){await this.processManager.killWithGrace(e);}};function R(n,e,t,r,o$1){async function*s(){let i=false,u=false,f="",p,d=null,y=null,T=new Promise(c=>{n.on("close",a=>{d=a,c();}),n.on("error",a=>{y=a,c();});}),m=null;try{if(n.stdout)try{for await(let c of J(n.stdout)){if(o$1?.aborted)break;let a=b(c,{finalText:f,lastTokens:p});if(a&&(a.finalText!==void 0&&(f=a.finalText),a.tokens&&(p=a.tokens),a.agentEvent&&(a.agentEvent.type==="done"&&(i=!0),yield a.agentEvent,a.agentEvent.type==="done"))){await t.killWithGrace(e,1e3).catch(()=>{});return}}}catch(c){m=c instanceof Error?c:new Error(String(c)),!o$1?.aborted&&!i&&(u=!0,yield {type:"error",timestamp:new Date().toISOString(),data:{message:m.message},errorKind:o(m.message)});}}finally{n.stdout?.destroy(),!i&&(o$1?.aborted||m)&&t.killWithGrace(e,1e3).catch(()=>{});}if(await T,u)return;let h=y;if(h&&!o$1?.aborted&&!i){let c=_(h.message,r()),a=o(c,d??void 0);throw Object.assign(new Error(c),{errorKind:a})}if(d!==0&&d!==null&&!o$1?.aborted&&!i){let c=`Pi process exited with code ${d}`,a=_(c,r()),P=o(a,d);throw Object.assign(new Error(a),{errorKind:P})}}return s()}function _(n,e){return e?`${n}
|
|
4
|
+
--- pi stderr (tail) ---
|
|
5
|
+
${e}`:n}function b(n,e){if(!n.trim())return null;let t;try{t=JSON.parse(n);}catch{return {agentEvent:{type:"output",timestamp:new Date().toISOString(),data:{text:n}}}}let r=new Date().toISOString();switch(typeof t.type=="string"?t.type:""){case "extension_ui_request":case "agent_start":case "turn_start":case "message_start":case "message_end":case "turn_end":case "queue_update":case "compaction_start":case "compaction_end":case "auto_retry_start":case "auto_retry_end":return O(t);case "response":{if(t.success===false){let s=typeof t.error=="string"?t.error:JSON.stringify(t);return {agentEvent:{type:"error",timestamp:r,data:{message:s,raw:t},errorKind:o(s)}}}return null}case "message_update":return A(t,r,e);case "tool_execution_start":return {agentEvent:{type:"tool_call",timestamp:r,data:{name:t.toolName,input:t.args,raw:t}}};case "tool_execution_update":return null;case "tool_execution_end":return B(t,r);case "agent_end":{let s=N(t)??e.finalText,i=K(t)??e.lastTokens;return {finalText:s,tokens:i,agentEvent:{type:"done",timestamp:r,data:{result:s,raw:t},tokens:i}}}case "extension_error":{let s=typeof t.message=="string"?t.message:JSON.stringify(t);return {agentEvent:{type:"error",timestamp:r,data:{message:s,raw:t},errorKind:o(s)}}}default:return null}}function A(n,e,t){let r=n.assistantMessageEvent,o$1=typeof r?.type=="string"?r.type:"";if(o$1==="text_delta"){let s=typeof r?.delta=="string"?r.delta:"";return {finalText:t.finalText+s}}if(o$1==="text_end"){let s=typeof r?.content=="string"?r.content:t.finalText;return s?{finalText:"",agentEvent:{type:"output",timestamp:e,data:{text:s}}}:{finalText:""}}if(o$1==="error"){let s=typeof r?.reason=="string"?r.reason:JSON.stringify(n);return {agentEvent:{type:"error",timestamp:e,data:{message:s,raw:n},errorKind:o(s)}}}return null}function B(n,e){let t=typeof n.toolName=="string"?n.toolName:"",r=n.args,o$1=I(n.result);if(n.isError===true){let i=o$1||JSON.stringify(n.result??n);return {agentEvent:{type:"error",timestamp:e,data:{message:i,raw:n},errorKind:o(i)}}}if(t==="bash"){let i=typeof r?.command=="string"?r.command:JSON.stringify(r??{});return {agentEvent:{type:"command",timestamp:e,data:{command:i,result:o$1,raw:n}}}}if(/^(write|edit)$/i.test(t)){let i=M(r);if(i)return {agentEvent:{type:"file_change",timestamp:e,data:{paths:[i],raw:n}}}}let s=o$1||`${t||"tool"} completed`;return {agentEvent:{type:"output",timestamp:e,data:{text:s,raw:n}}}}function I(n){return typeof n=="string"?n:!n||typeof n!="object"?"":x(n.content)??""}function O(n){let e=v(n);return e?{tokens:e}:null}function N(n){let e=n.messages;if(Array.isArray(e))for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.role!=="assistant")continue;let o=x(r.content);if(o)return o}}function x(n){if(typeof n=="string")return n;if(!Array.isArray(n))return;let e=n.map(t=>{let r=t;return typeof r.text=="string"?r.text:""}).filter(Boolean);return e.length?e.join(""):void 0}function M(n){if(n){if(typeof n.path=="string")return n.path;if(typeof n.file_path=="string")return n.file_path}}function K(n){let e=n.messages;if(Array.isArray(e))for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.role!=="assistant")continue;let o=v(r);if(o)return o}}var l={input:["input","input_tokens"],output:["output","output_tokens"],reasoning:["reasoning","reasoning_tokens"],cache_read:["cacheRead","cache_read","cache_read_input_tokens"],cache_write:["cacheWrite","cache_write","cache_creation_input_tokens"]};function v(n){let e=n.usage;if(!e)return;let t=f=>{for(let p of f){let d=e[p];if(typeof d=="number")return d}return 0},r=t(l.input),o=t(l.output),s=t(l.reasoning),i=t(l.cache_read),u=t(l.cache_write);if(!(r===0&&o===0&&s===0&&i===0&&u===0))return a(r,o,{reasoning:s,cache_read:i,cache_write:u})}var k=4096;function U(n){if(!n)return ()=>"";let e=Buffer.alloc(0);return n.on("data",t=>{let r=Buffer.isBuffer(t)?t:Buffer.from(t,"utf-8");e=e.length===0?r:Buffer.concat([e,r],e.length+r.length),e.length>k&&(e=Buffer.from(e.subarray(e.length-k)));}),n.on("error",()=>{}),()=>e.toString("utf-8").trimEnd()}async function*J(n){let e=[],t=0;for await(let r of n){let o=Buffer.isBuffer(r)?r:Buffer.from(r,"utf-8");if(o.length===0)continue;e.push(o),t+=o.length;let s=e.length===1?e[0]:Buffer.concat(e,t);e.length=0,t=0;let i=0,u;for(;(u=s.indexOf(10,i))!==-1;){if(u>i){let f=s.toString("utf-8",i,u);yield f.endsWith("\r")?f.slice(0,-1):f;}i=u+1;}if(i<s.length){let f=s.subarray(i);e.push(f),t=f.length;}}if(t>0){let o=(e.length===1?e[0]:Buffer.concat(e,t)).toString("utf-8");o&&(yield o.endsWith("\r")?o.slice(0,-1):o);}}export{E as a};
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$1,b,i}from'./chunk-64WUDYEM.js';import {a as a$3,e}from'./chunk-6E6DC7OE.js';import {k as k$1}from'./chunk-ZMLF5HI5.js';import {a as a$2,b as b$1}from'./chunk-LRYVT4D4.js';import R from'path';import {Command}from'commander';function l(o){let t=o.noColor||"NO_COLOR"in process.env||false,i=o.ascii||process.env.TERM==="dumb"||false;return {projectRoot:e(),json:o.json??false,quiet:o.quiet??false,noColor:t,ascii:i}}var d={task:async(o,t)=>{(await import('./task-
|
|
2
|
+
import {a as a$1,b,i}from'./chunk-64WUDYEM.js';import {a as a$3,e}from'./chunk-6E6DC7OE.js';import {k as k$1}from'./chunk-ZMLF5HI5.js';import {a as a$2,b as b$1}from'./chunk-LRYVT4D4.js';import R from'path';import {Command}from'commander';function l(o){let t=o.noColor||"NO_COLOR"in process.env||false,i=o.ascii||process.env.TERM==="dumb"||false;return {projectRoot:e(),json:o.json??false,quiet:o.quiet??false,noColor:t,ascii:i}}var d={task:async(o,t)=>{(await import('./task-YMPSU6YE.js')).registerTaskCommand(o,t);},agent:async(o,t)=>{(await import('./agent-6PI3NNZ5.js')).registerAgentCommand(o,t);},status:async(o,t)=>{(await import('./status-NYHZ7Q5G.js')).registerStatusCommand(o,t);},logs:async(o,t)=>{(await import('./logs-EUOQ2UZL.js')).registerLogsCommand(o,t);},config:async(o,t)=>{(await import('./config-OOB7QEKM.js')).registerConfigCommand(o,t);},context:async(o,t)=>{(await import('./context-FXRERFSP.js')).registerContextCommand(o,t);},msg:async(o,t)=>{(await import('./msg-4ELI7Q52.js')).registerMsgCommand(o,t);},goal:async(o,t)=>{(await import('./goal-KQ4XOSRH.js')).registerGoalCommand(o,t);},team:async(o,t)=>{(await import('./team-VCJSUDWX.js')).registerTeamCommand(o,t);},org:async(o,t)=>{(await import('./org-RL6SBZI4.js')).registerOrgCommand(o,t);}},m={run:async(o,t)=>{(await import('./run-PX7O3ILN.js')).registerRunCommand(o,t);},doctor:async(o,t)=>{(await import('./doctor-DEGM2HCD.js')).registerDoctorCommand(o,t);},tui:async(o,t)=>{(await import('./tui-NZ55TCHU.js')).registerTuiCommand(o,t);},serve:async(o,t)=>{(await import('./serve-DE7ES7Q5.js')).registerServeCommand(o,t);}},a=new Command;a.name("orchestry").description("Agents Organizations \u2014 CLI orchestrator for AI agents").version("1.0.25").option("--json","Output as JSON").option("--quiet","Minimal output (IDs only)").option("--no-color","Disable colors").option("--ascii","ASCII-only output (no Unicode)").hook("preAction",async o=>{let t=o.opts();t.ascii&&a$1(true),t.color===false&&b(true);});var x=[["task","Manage tasks"],["agent","Manage agents"],["status","Show orchestrator status"],["logs","View run logs"],["config","Manage configuration"],["context","Shared context store for inter-agent data exchange"],["msg","Inter-agent messaging"],["goal","Manage goals"],["team","Manage teams"],["org","Pre-built AI companies"],["run","Run tasks"],["doctor","Check adapters and dependencies"],["tui","Launch TUI dashboard"],["serve","Headless daemon mode with structured logs"],["init","Initialize project"],["update","Check for updates"]],L=new Set(x.map(([o])=>o));async function k(){a.parseOptions(process.argv);let o=a.opts(),t=process.argv.slice(2).find(e=>!e.startsWith("-")),i$1=t!==void 0&&L.has(t);if((process.argv.includes("--help")||process.argv.includes("-h")||process.argv.includes("--version")||process.argv.includes("-V"))&&!i$1){for(let[e,n]of x)a.command(e).description(n);await a.parseAsync(process.argv);return}if(t==="init"){let{registerInitCommand:e}=await import('./init-4D6QMPQL.js');e(a);}else if(t==="update"){let{registerUpdateCommand:e}=await import('./update-W54LAATS.js');e(a);}let g=process.argv.length<=2;if(g&&!await k$1(R.join(process.cwd(),a$3))){let{runInit:e}=await import('./init-4D6QMPQL.js');await e();let n=l({json:o.json,quiet:o.quiet,noColor:o.color===false,ascii:o.ascii}),{buildFullContainer:s}=await import('./container-KJNQCG2C.js'),p=await s(n);await m.tui(a,p),await a.parseAsync([...process.argv,"tui"]);return}let u=l({json:o.json,quiet:o.quiet,noColor:o.color===false,ascii:o.ascii}),j=!t||t in m,{buildFullContainer:A,buildLightContainer:M}=await import('./container-KJNQCG2C.js');try{if(j){let e=await A(u),n=t?m[t]:void 0;n?await n(a,e):await Promise.all(Object.values(m).map(p=>p(a,e)));let s=t?d[t]:void 0;s&&await s(a,e);}else {let e=await M(u),n=d[t];n?await n(a,e):await Promise.all(Object.values(d).map(s=>s(a,e)));}}catch(e){if(e instanceof b$1){if(t==="doctor"){let{registerDoctorCommand:n}=await import('./doctor-DEGM2HCD.js');n(a);}if(t==="init"||t==="doctor"||t==="update"){await a.parseAsync(process.argv);return}i(e.message,e.hint),process.exit(e.exitCode);}throw e}g&&process.argv.push("tui");let r,f=t==="tui"||t==="update"||t==="serve",S=f?Promise.resolve(null):import('./update-check-R5ABF6HE.js').then(e=>(r=e,e.checkForUpdateSWR(a.version()??"0.0.0")));if(await a.parseAsync(process.argv),!f){let e=await S;e&&r&&(r.printUpdateNotification(e),e.updateAvailable&&r.backgroundInstall(e.latest).catch(()=>{}));}}k().catch(o=>{o instanceof a$2&&(i(o.message,o.hint),process.exit(o.exitCode)),i(o instanceof Error?o.message:String(o)),process.env.ORCHESTRY_DEBUG&&console.error(o),process.exit(1);});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {a as a$2}from'./chunk-N4OXN2HW.js';import {c as c$1,b as b$3}from'./chunk-HXOMNULD.js';import {b as b$2,a as a$1}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {b}from'./chunk-6E6DC7OE.js';import {b as b$1,c,j,d,e,l as l$1,f as f$1,h,i as i$1,g as g$1,k as k$1}from'./chunk-ZMLF5HI5.js';import {c as c$2,l,j as j$1,k,g,f,i}from'./chunk-LRYVT4D4.js';import tt from'path';import Z,{mkdir}from'fs/promises';import {createReadStream}from'fs';import {homedir}from'os';import {nanoid}from'nanoid';var P={tui:{activity_filter:"all",notifications:{toast:true,bell:false}}};var w=class{indexPath;dir;ext;itemPath;fileFilter;readItemFn;mutex=Promise.resolve();insideMutex=false;constructor(t){this.dir=t.dir,this.ext=t.ext,this.itemPath=t.itemPath,this.indexPath=tt.join(t.dir,"_index.json"),this.fileFilter=t.fileFilter??(()=>true),t.readItem?this.readItemFn=t.readItem:t.ext===".yml"?this.readItemFn=e=>b$1(e):this.readItemFn=e=>d(e);}async readIndex(){try{let t=await d(this.indexPath);if(Array.isArray(t))return t}catch{}return this.rebuildIndex()}async rebuildIndex(){await j(this.dir);let t=await l$1(this.dir,this.ext),e=await Promise.all(t.filter(this.fileFilter).map(r=>{let a=r.replace(this.ext,"");return this.readItemFn(this.itemPath(a))})),s=[];for(let r of e)r!=null&&s.push(r);return this.insideMutex?await this.writeIndexUnsafe(s):await this.withMutex(()=>this.writeIndexUnsafe(s)),s}async writeIndex(t){return this.withMutex(()=>this.writeIndexUnsafe(t))}async updateIndex(t){return this.withMutex(async()=>{let e=await this.readIndex(),s=t(e);await this.writeIndexUnsafe(s);})}async writeIndexUnsafe(t){await j(this.dir),await e(this.indexPath,t);}withMutex(t){let e,s=new Promise(a=>{e=a;}),r=this.mutex;return this.mutex=s,r.then(async()=>{this.insideMutex=true;try{return await t()}finally{this.insideMutex=false,e();}})}};var M=class{constructor(t){this.paths=t;this.index=new w({dir:t.tasksDir,ext:".yml",itemPath:e=>t.taskPath(e)});}index;async list(t){return (await this.index.readIndex()).filter(r=>r!==null&&(!t?.status||r.status===t.status)&&(!t?.goalId||r.goalId===t.goalId)).sort((r,a)=>{let n=ht(r.status)-ht(a.status);if(n!==0)return n;let i=a.updated_at??"",o=r.updated_at??"";return i<o?-1:i>o?1:0})}async get(t){return b$1(this.paths.taskPath(t))}async save(t){await j(this.paths.tasksDir),await c(this.paths.taskPath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async delete(t){try{await Z.unlink(this.paths.taskPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}};function ht(m){return {in_progress:0,retrying:1,review:2,todo:3,done:4,failed:5,cancelled:6}[m]}var D=class{constructor(t){this.paths=t;this.index=new w({dir:t.agentsDir,ext:".yml",itemPath:e=>t.agentPath(e)});}index;async list(){return this.index.readIndex()}async get(t){return b$1(this.paths.agentPath(t))}async getByName(t){return (await this.list()).find(s=>s.name===t)??null}async save(t){await j(this.paths.agentsDir),await c(this.paths.agentPath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async delete(t){try{await Z.unlink(this.paths.agentPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}};var R=class{constructor(t){this.paths=t;}async save(t){await j(this.paths.runsDir),await e(this.paths.runPath(t.id),t);}async get(t){return d(this.paths.runPath(t))}async listAll(){return this.listFiltered(()=>true)}async listForTask(t){return this.listFiltered(e=>e.task_id===t)}async listForAgent(t){return this.listFiltered(e=>e.agent_id===t)}async appendEvent(t,e){await j(this.paths.runsDir),await f$1(this.paths.runEventsPath(t),e);}async readEvents(t){return h(this.paths.runEventsPath(t))}async readEventsTail(t,e){return i$1(this.paths.runEventsPath(t),e)}closeRunEvents(t){g$1(this.paths.runEventsPath(t));}async*streamEvents(t,e){let s=this.paths.runEventsPath(t),r=Date.now()+3e4;for(;!e?.aborted&&Date.now()<r&&!await k$1(s);)await new Promise(i=>setTimeout(i,100));if(e?.aborted||Date.now()>=r)return;let a=createReadStream(s),{readLines:n}=await import('./process-manager-33H27MQF.js');try{for await(let i of n(a)){if(e?.aborted)break;if(i.trim())try{yield JSON.parse(i);}catch{process.stderr.write(`[RunStore] skipping corrupt JSONL line: ${i.slice(0,200)}
|
|
3
3
|
`);}}}finally{a.destroy();}}async listFiltered(t){await j(this.paths.runsDir);let e=await l$1(this.paths.runsDir,".json"),s=64,r=[];for(let a=0;a<e.length;a+=s){let n=e.slice(a,a+s),i=await Promise.all(n.map(o=>{let c=o.endsWith(".json")?o.slice(0,-5):o;return d(this.paths.runPath(c))}));for(let o of i)o!==null&&t(o)&&r.push(o);}return r.sort((a,n)=>new Date(n.started_at).getTime()-new Date(a.started_at).getTime())}};var Q={version:1,onboardingCompleted:false,running:{},claimed:new Set,retry_queue:[],stats:{total_runs:0,total_tasks_completed:0,total_tasks_failed:0,total_tokens:{input:0,output:0,reasoning:0,total:0,cache_read:0,cache_write:0},total_runtime_ms:0}};var O=class{constructor(t){this.paths=t;}async read(){let t=await d(this.paths.statePath);if(!t)return structuredClone(Q);let e=structuredClone(Q);return {version:t.version??e.version,pid:t.pid,started_at:t.started_at,onboardingCompleted:typeof t.onboardingCompleted=="boolean"?t.onboardingCompleted:false,running:t.running&&typeof t.running=="object"?t.running:e.running,claimed:Array.isArray(t.claimed)?new Set(t.claimed):new Set(e.claimed),retry_queue:Array.isArray(t.retry_queue)?t.retry_queue:e.retry_queue,stats:{total_runs:t.stats?.total_runs??e.stats.total_runs,total_tasks_completed:t.stats?.total_tasks_completed??e.stats.total_tasks_completed,total_tasks_failed:t.stats?.total_tasks_failed??e.stats.total_tasks_failed,total_tokens:{...e.stats.total_tokens,...t.stats?.total_tokens??{}},total_runtime_ms:t.stats?.total_runtime_ms??e.stats.total_runtime_ms}}}async write(t){let e$1={...t,claimed:Array.from(t.claimed)};await e(this.paths.statePath,e$1);}};var G=class{constructor(t){this.paths=t;}async read(){let t=await b$1(this.paths.configPath);return ft(a$2,t??{})}async write(t){await c(this.paths.configPath,t);}async get(t){let e=await this.read();return jt(e,t)}async set(t,e){let s=await this.read();Mt(s,t,e),await this.write(s);}};function jt(m,t){let e=t.split("."),s=m;for(let r of e){if(s==null||typeof s!="object")return;s=s[r];}return s}function Mt(m,t,e){let s=t.split("."),r=m;for(let n=0;n<s.length-1;n++){let i=s[n];(typeof r[i]!="object"||r[i]===null)&&(r[i]={}),r=r[i];}let a=s[s.length-1];r[a]=e;}function ft(m,t){let e={...m};for(let s of Object.keys(t)){let r=t[s],a=e[s];r!=null&&typeof r=="object"&&!Array.isArray(r)&&typeof a=="object"&&a!==null&&!Array.isArray(a)?e[s]=ft(a,r):e[s]=r;}return e}var St=tt.join(homedir(),".orchestry"),wt=tt.join(St,"global.yml"),L=class{async read(){let t=await b$1(wt);if(!t)return {...P,tui:{...P.tui,notifications:{...P.tui.notifications}}};let e=t.tui,s=e?.notifications;return {tui:{activity_filter:e?.activity_filter??P.tui.activity_filter,notifications:{toast:typeof s?.toast=="boolean"?s.toast:P.tui.notifications.toast,bell:typeof s?.bell=="boolean"?s.bell:P.tui.notifications.bell}}}}async write(t){await mkdir(St,{recursive:true}),await c(wt,t);}async set(t,e){let s=await this.read();s.tui[t]=e,await this.write(s);}};var B=class m{constructor(t){this.paths=t;this.index=new w({dir:t.contextDir,ext:".json",itemPath:e=>t.contextPath(e),fileFilter:e=>e!=="_index.json"});}index;async get(t){let e=await d(this.paths.contextPath(t));return e?_t(e)?(await this.delete(t),null):e:null}static MAX_TTL_MS=720*60*60*1e3;async set(t,e$1,s){if(s!==void 0&&(!Number.isFinite(s)||s<=0||s>m.MAX_TTL_MS))throw new Error(`TTL must be a positive number up to ${m.MAX_TTL_MS}ms (30 days)`);await j(this.paths.contextDir);let r=new Date().toISOString(),a=await d(this.paths.contextPath(t)),n={key:t,value:e$1,created_at:a?.created_at??r,updated_at:r,ttl_ms:s,expires_at:s?new Date(Date.now()+s).toISOString():void 0};await e(this.paths.contextPath(t),n),await this.index.updateIndex(i=>{let o=i.filter(c=>c.key!==t);return o.push(n),o});}async delete(t){try{await Z.unlink(this.paths.contextPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.key!==t));}async list(){let t=await this.index.readIndex(),e=[],s=[];for(let r of t)_t(r)?e.push(r):s.push(r);return e.length>0&&(await Promise.all(e.map(r=>this.deleteFile(r.key))),await this.index.writeIndex(s)),s.sort((r,a)=>r.key.localeCompare(a.key))}async getAll(){let t=await this.list(),e={};for(let s of t)e[s.key]=s.value;return e}async deleteFile(t){try{await Z.unlink(this.paths.contextPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}};function _t(m){return m.expires_at?new Date(m.expires_at).getTime()<Date.now():false}var F=class{constructor(t){this.paths=t;this.index=new w({dir:t.messagesDir,ext:".json",itemPath:e=>t.messagePath(e),fileFilter:e=>e!=="_index.json"});}index;async save(t){await j(this.paths.messagesDir),await e(this.paths.messagePath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async get(t){return d(this.paths.messagePath(t))}async list(){return (await this.index.readIndex()).filter(e=>e!==null).sort((e,s)=>e.created_at.localeCompare(s.created_at))}async listPending(t){let e=await this.list(),s=Date.now();return e.filter(r=>r.status!=="pending"||r.expires_at&&new Date(r.expires_at).getTime()<s?false:r.to_agent_id===t)}async markDelivered(t){let e$1=await this.get(t);e$1&&(e$1.status="delivered",e$1.delivered_at=new Date().toISOString(),await e(this.paths.messagePath(t),e$1),await this.index.updateIndex(s=>{let r=s.filter(a=>a.id!==t);return r.push(e$1),r}));}async delete(t){try{await Z.unlink(this.paths.messagePath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}async purgeExpired(){let t=await this.list(),e=Date.now(),s=t.filter(a=>{let n=a.expires_at&&new Date(a.expires_at).getTime()<e,i=a.delivered_at&&e-new Date(a.delivered_at).getTime()>36e5;return n||i}),r=new Set(s.map(a=>a.id));return await Promise.all(s.map(async a=>{try{await Z.unlink(this.paths.messagePath(a.id));}catch(n){if(n.code!=="ENOENT")throw n}})),await this.index.updateIndex(a=>a.filter(n=>!r.has(n.id))),s.length}};var N=class{constructor(t){this.paths=t;this.index=new w({dir:t.goalsDir,ext:".yml",itemPath:e=>t.goalPath(e)});}index;async list(t){return (await this.index.readIndex()).filter(r=>r!==null&&(!t?.status||r.status===t.status)).sort((r,a)=>{let n=c$1[r.status]-c$1[a.status];if(n!==0)return n;let i=a.updated_at??"",o=r.updated_at??"";return i<o?-1:i>o?1:0})}async get(t){return b$1(this.paths.goalPath(t))}async save(t){await j(this.paths.goalsDir),await c(this.paths.goalPath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async delete(t){try{await Z.unlink(this.paths.goalPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}};var $=class{constructor(t){this.paths=t;}async save(t){await j(this.paths.teamsDir),await c(this.paths.teamPath(t.id),t);}async get(t){return b$1(this.paths.teamPath(t))}async getByName(t){return (await this.list()).find(s=>s.name===t)??null}async list(){await j(this.paths.teamsDir);let t=await l$1(this.paths.teamsDir,".yml");return (await Promise.all(t.map(s=>b$1(this.paths.teamPath(s.replace(".yml","")))))).filter(s=>s!==null)}async delete(t){try{await Z.unlink(this.paths.teamPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}};var U=class{handlers=new Map;wildcardHandlers=new Set;maxListeners=10;warnedTypes=new Set;setMaxListeners(t){this.maxListeners=t;}getMaxListeners(){return this.maxListeners}listenerCount(t){return this.handlers.get(t)?.size??0}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set);let s=this.handlers.get(t);return s.add(e),this.maxListeners>0&&s.size>this.maxListeners&&!this.warnedTypes.has(t)&&(this.warnedTypes.add(t),console.warn(`EventBus: possible memory leak detected. ${s.size} listeners added for "${t}". Use setMaxListeners() to increase limit if this is intentional.`)),()=>this.off(t,e)}once(t,e){let s=r=>{this.off(t,s),e(r);};return this.on(t,s)}off(t,e){this.handlers.get(t)?.delete(e);}emit(t){let e=this.handlers.get(t.type);e&&this.dispatchToSet(e,t,"handler"),this.dispatchToSet(this.wildcardHandlers,t,"wildcard handler");}dispatchToSet(t,e,s){for(let r of t)try{r(e);}catch(a){console.error(`EventBus ${s} error for "${e.type}":`,a);}}onAny(t){return this.wildcardHandlers.add(t),this.maxListeners>0&&this.wildcardHandlers.size>this.maxListeners&&!this.warnedTypes.has("*")&&(this.warnedTypes.add("*"),console.warn(`EventBus: possible memory leak detected. ${this.wildcardHandlers.size} wildcard listeners added. Use setMaxListeners() to increase limit if this is intentional.`)),()=>{this.wildcardHandlers.delete(t);}}clear(){this.handlers.clear(),this.wildcardHandlers.clear(),this.warnedTypes.clear();}};var J=class{constructor(t,e,s,r,a){this.taskStore=t;this.eventBus=e;this.config=s;this.paths=r;this.agentStore=a;}async create(t){if(!t.title.trim())throw new c$2("Task title is required");let e=t.priority??this.config.defaults.task.priority;if(!Number.isInteger(e)||e<1||e>4)throw new c$2("Priority must be an integer between 1 and 4");if(t.depends_on?.length){let i=(await Promise.all(t.depends_on.map(async o=>({depId:o,exists:!!await this.taskStore.get(o)})))).filter(o=>!o.exists).map(o=>o.depId);if(i.length>0)throw new c$2(`Unknown depends_on task ID(s): ${i.join(", ")}`)}let s=await this.resolveAssignee(t.assignee),r=new Date().toISOString(),a={id:`tsk_${nanoid(7)}`,title:t.title.trim(),description:t.description?.trim()??"",status:"todo",priority:e,assignee:s,labels:t.labels??[],depends_on:t.depends_on??[],created_at:r,updated_at:r,attempts:0,max_attempts:t.max_attempts??this.config.defaults.task.max_attempts,workspace_mode:t.workspace_mode,review_criteria:t.review_criteria,scope:t.scope,goalId:t.goalId};if(t.attachments?.length&&this.paths){let n=await this.copyAttachments(a.id,t.attachments);a.attachments=n;}return await this.taskStore.save(a),this.eventBus.emit({type:"task:created",task:a}),a}async list(t){return this.taskStore.list(t)}async get(t){let e=await this.taskStore.get(t);if(!e)throw new f(t);return e}async updateStatus(t,e){let s=await this.get(t),r=s.status;if(!a$1(r,e))throw new i(t,r,e);return s.status=e,s.updated_at=new Date().toISOString(),await this.taskStore.save(s),this.eventBus.emit({type:"task:status_changed",taskId:t,from:r,to:e}),s}async assign(t,e){let s=await this.get(t);return s.assignee=await this.resolveAssignee(e),s.updated_at=new Date().toISOString(),await this.taskStore.save(s),this.eventBus.emit({type:"task:assigned",taskId:t,agentId:e}),s}async cancel(t){let e=await this.get(t);if(b$2(e.status))throw new i(t,e.status,"cancelled");return this.updateStatus(t,"cancelled")}async retry(t){let e=await this.get(t);if(e.status!=="failed"&&e.status!=="cancelled")throw new i(t,e.status,"todo");let s=e.status;return e.status="todo",e.attempts=0,e.updated_at=new Date().toISOString(),await this.taskStore.save(e),this.eventBus.emit({type:"task:status_changed",taskId:t,from:s,to:"todo"}),e}async reject(t,e){let s=await this.get(t);if(s.status!=="review")throw new i(t,s.status,"todo");let r=s.status;return s.status="todo",s.attempts=0,s.feedback=e,s.updated_at=new Date().toISOString(),await this.taskStore.save(s),this.eventBus.emit({type:"task:status_changed",taskId:t,from:r,to:"todo"}),s}async update(t,e){let s=await this.get(t);if(e.title!==void 0){if(!e.title.trim())throw new c$2("Task title cannot be empty");s.title=e.title.trim();}if(e.description!==void 0&&(s.description=e.description.trim()),e.priority!==void 0){if(!Number.isInteger(e.priority)||e.priority<1||e.priority>4)throw new c$2("Priority must be an integer between 1 and 4");s.priority=e.priority;}if(e.labels!==void 0&&(s.labels=e.labels),e.attachments?.length&&this.paths){let r=await this.copyAttachments(t,e.attachments);s.attachments=[...s.attachments??[],...r];}return s.updated_at=new Date().toISOString(),await this.taskStore.save(s),s}async delete(t){if((await this.get(t)).status==="in_progress")throw new c$2("Cannot delete a running task. Cancel it first.");if(await this.taskStore.delete(t),this.paths){let s=this.paths.taskAttachmentsDir(t);await Z.rm(s,{recursive:true,force:true});}}getAttachmentPath(t,e){if(!this.paths)throw new c$2("Paths not configured");return tt.join(this.paths.taskAttachmentsDir(t),e)}async copyAttachments(t,e){if(!this.paths)return [];let s=this.paths.taskAttachmentsDir(t);return await j(s),await Promise.all(e.map(async a=>{try{await Z.access(a);}catch{throw new c$2(`Attachment file not found: ${a}`)}})),await Promise.all(e.map(async a=>{let n=tt.basename(a);return await Z.copyFile(a,tt.join(s,n)),n}))}async incrementAttempts(t){let e=await this.get(t);return e.attempts+=1,e.updated_at=new Date().toISOString(),await this.taskStore.save(e),e}async resolveAssignee(t){if(!t)return;if(!this.agentStore)return t;if(t.startsWith("agt_")){let s=await this.agentStore.get(t);if(s)return s.id;throw new c$2(`Unknown agent ID: "${t}". No agent with this ID exists.`)}let e=await this.agentStore.getByName(t);if(e)return e.id;throw new c$2(`Unknown agent: "${t}". Use an agent ID (agt_xxx) or an exact agent name.`)}};var H=class{constructor(t,e,s,r){this.agentStore=t;this.stateStore=e;this.eventBus=s;this.config=r;}async create(t){if(!t.name.trim())throw new c$2("Agent name is required");if(await this.agentStore.getByName(t.name))throw new c$2(`Agent "${t.name}" already exists`);let s={id:`agt_${nanoid(7)}`,name:t.name.trim(),adapter:t.adapter||this.config.defaults.agent.adapter,role:t.role,config:{command:t.command,model:t.model,effort:t.effort,approval_policy:t.approval_policy??this.config.defaults.agent.approval_policy,max_turns:t.max_turns??this.config.defaults.agent.max_turns,timeout_ms:t.timeout_ms??this.config.defaults.agent.timeout_ms,stall_timeout_ms:t.stall_timeout_ms??this.config.defaults.agent.stall_timeout_ms,env:t.env,system_prompt:t.system_prompt,workspace_mode:t.workspace_mode,skills:t.skills},status:"idle",stats:{tasks_completed:0,tasks_failed:0,total_runs:0,total_runtime_ms:0}};return await this.agentStore.save(s),s}async list(){return this.agentStore.list()}async get(t){let e=await this.agentStore.get(t);if(!e)throw new g(t);return e}async remove(t){let e=await this.get(t);if(e.status==="running"){let s=await this.stateStore.read();if(Object.values(s.running).some(a=>a.agent_id===t))throw new c$2("Cannot remove a running agent. Stop it first.");e.status="idle",await this.agentStore.save(e);}await this.agentStore.delete(t);}async update(t,e){let s=await this.get(t);if(e.name!==void 0){if(!e.name.trim())throw new c$2("Agent name cannot be empty");let r=await this.agentStore.getByName(e.name.trim());if(r&&r.id!==t)throw new c$2(`Agent "${e.name}" already exists`);s.name=e.name.trim();}return e.role!==void 0&&(s.role=e.role||void 0),e.model!==void 0&&(s.config.model=e.model||void 0),e.effort!==void 0&&(s.config.effort=e.effort||void 0),e.approval_policy!==void 0&&(s.config.approval_policy=e.approval_policy),await this.agentStore.save(s),s}async disable(t){return this.setStatus(t,"disabled")}async enable(t){return this.setStatus(t,"idle")}async setAutonomous(t,e){let s=await this.get(t);return s.autonomous=e,await this.agentStore.save(s),this.eventBus.emit({type:"agent:autonomous_toggled",agentId:t,autonomous:e}),s}async setStatus(t,e){let s=await this.get(t);return s.status=e,await this.agentStore.save(s),s}async updateStats(t,e){let s=await this.get(t);return Object.assign(s.stats,e),await this.agentStore.save(s),s}async findBestAgent(t){let e=await this.agentStore.list(),s=e.filter(n=>n.status==="idle");if(s.length===0)return null;if(t.assignee){let n=e.find(i=>i.id===t.assignee||i.name===t.assignee);return n&&n.status==="idle"?n:null}let r=t.labels?.length?t.labels.map(n=>n.toLowerCase()):void 0,a=s.map(n=>{let i=0;if(r&&n.config.skills?.length){let c=new Set(n.config.skills.map(d=>d.toLowerCase()));for(let d of r)c.has(d)&&(i+=50);}if(r&&n.role){let c=n.role.toLowerCase();r.some(d=>c.includes(d))&&(i+=30);}n.status==="idle"&&(i+=20);let o=n.stats.tasks_completed+n.stats.tasks_failed;return o>0&&(i+=Math.round(n.stats.tasks_completed/o*10)),{agent:n,score:i}});return a.sort((n,i)=>i.score-n.score),a[0]?.agent??null}};var q=class{constructor(t,e){this.runStore=t;this.eventBus=e;}async create(t){let e={id:`run_${nanoid(7)}`,task_id:t.taskId,agent_id:t.agentId,attempt:t.attempt,status:"preparing",started_at:new Date().toISOString(),workspace_path:t.workspacePath,prompt:t.prompt};return await this.runStore.save(e),e}async get(t){return this.runStore.get(t)}async start(t,e){let s=await this.runStore.get(t);if(!s)throw new Error(`Run not found: ${t}`);return s.status="running",s.pid=e,await this.runStore.save(s),this.eventBus.emit({type:"agent:started",agentId:s.agent_id,taskId:s.task_id,runId:t}),s}async finish(t,e,s,r){let a=await this.runStore.get(t);if(!a)throw new Error(`Run not found: ${t}`);return a.status=e,a.finished_at=new Date().toISOString(),a.tokens=s,a.error=r,await this.runStore.save(a),this.eventBus.emit({type:"agent:completed",runId:t,agentId:a.agent_id,success:e==="succeeded"}),a}async appendEvent(t,e){await this.runStore.appendEvent(t,e);}async listAll(){return this.runStore.listAll()}async listForTask(t){return this.runStore.listForTask(t)}async listForAgent(t){return this.runStore.listForAgent(t)}async readEvents(t){return this.runStore.readEvents(t)}async readEventsTail(t,e){return this.runStore.readEventsTail(t,e)}async getLastFailedRunContext(t){let s=(await this.runStore.listForTask(t)).filter(n=>n.status==="failed").sort((n,i)=>(i.finished_at??"").localeCompare(n.finished_at??""))[0];if(!s)return null;let r=s.error??"Unknown error",a="";try{a=(await this.runStore.readEventsTail(s.id,50)).filter(i=>i.type==="agent_output"||i.type==="error").map(i=>typeof i.data=="string"?i.data:JSON.stringify(i.data)).join(`
|
|
4
|
-
`);}catch{}return {error:r,output:a}}};var Y=class{constructor(t,e,s,r){this.messageStore=t;this.agentStore=e;this.teamStore=s;this.eventBus=r;}async send(t){if(!t.body.trim())throw new c$2("Message body is required");let e=t.ttl_ms??864e5;if(e<=0||e>6048e5)throw new c$2(`TTL must be between 1ms and ${6048e5}ms`);if(!await this.agentStore.get(t.from_agent_id)&&t.from_agent_id!=="cli")throw new c$2(`Sender agent not found: ${t.from_agent_id}`);let r=new Date,a={channel:t.channel,from_agent_id:t.from_agent_id,subject:(t.subject||"(no subject)").slice(0,200),body:t.body.slice(0,4e3),created_at:r.toISOString(),expires_at:new Date(r.getTime()+e).toISOString(),status:"pending",team_id:t.team_id,reply_to:t.reply_to},n=[];if(t.channel==="broadcast"){let i=await this.agentStore.list();if(t.team_id){let d=await this.teamStore.get(t.team_id);if(d){let k=new Set(d.members.map(S=>S.agent_id));i=i.filter(S=>k.has(S.id));}}let c=i.filter(d=>d.id!==t.from_agent_id&&d.status!=="disabled").map(d=>({...a,id:`msg_${nanoid(7)}`,to_agent_id:d.id}));await Promise.all(c.map(d=>this.messageStore.save(d)));for(let d of c)n.push(d),this.emitSent(d);}else if(t.channel==="lead"){if(!t.team_id)throw new c$2("team_id is required for lead channel");let i=await this.teamStore.get(t.team_id);if(!i)throw new c$2(`Team not found: ${t.team_id}`);let o={...a,id:`msg_${nanoid(7)}`,to_agent_id:i.lead_agent_id};await this.messageStore.save(o),n.push(o),this.emitSent(o);}else {if(!t.to_agent_id)throw new c$2("to_agent_id is required for direct messages");if(!await this.agentStore.get(t.to_agent_id))throw new c$2(`Recipient agent not found: ${t.to_agent_id}`);let o={...a,id:`msg_${nanoid(7)}`,to_agent_id:t.to_agent_id};await this.messageStore.save(o),n.push(o),this.emitSent(o);}return n}async drainMailbox(t,e){let s=await this.messageStore.listPending(t);await Promise.all(s.map(r=>this.messageStore.markDelivered(r.id)));for(let r of s)this.eventBus.emit({type:"message:delivered",messageId:r.id,toAgentId:t,taskId:e});return s}async listAll(){return this.messageStore.list()}async listPendingForAgent(t){return this.messageStore.listPending(t)}async listForAgent(t){return (await this.messageStore.list()).filter(s=>s.to_agent_id===t||s.from_agent_id===t)}async purgeExpired(){return this.messageStore.purgeExpired()}emitSent(t){this.eventBus.emit({type:"message:sent",messageId:t.id,fromAgentId:t.from_agent_id,toAgentId:t.to_agent_id,channel:t.channel});}};var Ut={active:["paused","achieved","abandoned"],paused:["active","achieved","abandoned"],achieved:[],abandoned:[]},z=class{constructor(t,e,s,r,a){this.goalStore=t;this.eventBus=e;this.agentService=s;this.taskService=r;this.contextStore=a;}async create(t){if(!t.title.trim())throw new c$2("Goal title is required");let e=new Date().toISOString(),s={id:`goal_${nanoid(7)}`,title:t.title.trim(),description:t.description?.trim()??"",status:"active",assignee:t.assignee,created_at:e,updated_at:e};return await this.goalStore.save(s),this.eventBus.emit({type:"goal:created",goalId:s.id,title:s.title}),s.assignee&&await this.enableAutonomous(s.assignee),s}async list(t){return this.goalStore.list(t)}async get(t){let e=await this.goalStore.get(t);if(!e)throw new j$1(t);return e}async updateStatus(t,e,s){let r=await this.get(t),a$1=r.status;if(!Ut[a$1].includes(e))throw new c$2(`Cannot transition goal from '${a$1}' to '${e}'`);if(e==="achieved"&&this.taskService){let i=(await this.taskService.list({goalId:t})).filter(o=>!b$2(o.status)&&!o.labels?.includes(a));if(i.length>0)if(s?.force){let o=i.filter(d=>d.status!=="in_progress"),c=i.filter(d=>d.status==="in_progress");if(await Promise.all(o.map(d=>this.taskService.cancel(d.id).catch(()=>{}))),c.length>0){let d=c.map(k=>`${k.id} (in_progress)`).join(", ");throw new k(t,c.length,d)}}else {let o=i.map(c=>`${c.id} (${c.status})`).join(", ");throw new k(t,i.length,o)}}return r.status=e,r.updated_at=new Date().toISOString(),await this.goalStore.save(r),this.eventBus.emit({type:"goal:status_changed",goalId:t,from:a$1,to:e}),r.assignee&&(e==="paused"?(await this.maybeDisableAutonomous(r.assignee),await this.cancelPendingAutonomousTasks(r.assignee)):e==="active"&&a$1==="paused"?await this.enableAutonomous(r.assignee):b$3(e)&&await this.maybeDisableAutonomous(r.assignee)),r}async update(t,e){let s=await this.get(t),r=s.assignee;if(e.title!==void 0){if(!e.title.trim())throw new c$2("Goal title cannot be empty");s.title=e.title.trim();}e.description!==void 0&&(s.description=e.description.trim()),e.assignee!==void 0&&(s.assignee=e.assignee||void 0),s.updated_at=new Date().toISOString(),await this.goalStore.save(s),this.eventBus.emit({type:"goal:updated",goalId:t});let a=s.assignee;if(a!==r){let n=[];a&&n.push(this.enableAutonomous(a)),r&&n.push(this.maybeDisableAutonomous(r)),await Promise.all(n);}return s}async delete(t){let e=await this.get(t),{assignee:s}=e;await this.goalStore.delete(t),this.eventBus.emit({type:"goal:deleted",goalId:t}),s&&await this.maybeDisableAutonomous(s);}async listTasksForGoal(t){return this.taskService?.list({goalId:t})??[]}async getProgressReport(t){return this.contextStore?(await this.contextStore.get(`${t}-progress`))?.value:void 0}async enableAutonomous(t){if(this.agentService)try{await this.agentService.setAutonomous(t,!0);}catch{}}async hasActiveGoalsForAgent(t){return (await this.goalStore.list({status:"active"})).some(s=>s.assignee===t)}async cancelPendingAutonomousTasks(t){if(this.taskService)try{let[e,s]=await Promise.all([this.taskService.list({status:"todo"}),this.taskService.list({status:"retrying"})]),r=[...e,...s].filter(a$1=>a$1.assignee===t&&a$1.labels?.includes(a));await Promise.all(r.map(a=>this.taskService.cancel(a.id).catch(()=>{})));}catch{}}async maybeDisableAutonomous(t){if(this.agentService)try{await this.hasActiveGoalsForAgent(t)||await this.agentService.setAutonomous(t,!1);}catch{}}};var xt={auto_claim:true,message_ttl_ms:864e5};var W=class{constructor(t,e,s,r){this.teamStore=t;this.agentStore=e;this.taskStore=s;this.eventBus=r;}async create(t){if(!t.name.trim())throw new c$2("Team name is required");if(!await this.agentStore.get(t.lead_agent_id))throw new c$2(`Lead agent not found: ${t.lead_agent_id}`);if(await this.teamStore.getByName(t.name.trim()))throw new c$2(`Team "${t.name}" already exists`);let r=new Date().toISOString(),a={agent_id:t.lead_agent_id,role:"lead",joined_at:r},n=[];for(let o of t.member_agent_ids??[]){if(o===t.lead_agent_id)continue;if(!await this.agentStore.get(o))throw new c$2(`Member agent not found: ${o}`);n.push({agent_id:o,role:"member",joined_at:r});}let i={id:`team_${nanoid(7)}`,name:t.name.trim(),description:t.description,status:"active",members:[a,...n],task_pool:[],lead_agent_id:t.lead_agent_id,created_at:r,updated_at:r,config:{...xt,...t.config??{}}};await this.teamStore.save(i),this.eventBus.emit({type:"team:created",teamId:i.id,name:i.name,leadAgentId:i.lead_agent_id});for(let o of n)this.eventBus.emit({type:"team:member_joined",teamId:i.id,agentId:o.agent_id});return i}async get(t){let e=await this.teamStore.get(t);if(!e)throw new l(t);return e}async list(){return this.teamStore.list()}async join(t,e){let s=await this.get(t);if(s.members.some(a=>a.agent_id===e))throw new c$2(`Agent ${e} is already a member of team ${t}`);if(!await this.agentStore.get(e))throw new c$2(`Agent not found: ${e}`);return s.members.push({agent_id:e,role:"member",joined_at:new Date().toISOString()}),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:member_joined",teamId:t,agentId:e}),s}async leave(t,e){let s=await this.get(t);if(e===s.lead_agent_id)throw new c$2("Lead cannot leave team. Disband the team or transfer lead first.");return s.members=s.members.filter(r=>r.agent_id!==e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:member_left",teamId:t,agentId:e}),s}async addTask(t,e){let s=await this.get(t);if(!await this.taskStore.get(e))throw new c$2(`Task not found: ${e}`);return s.task_pool.includes(e)||(s.task_pool.push(e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:task_added",teamId:t,taskId:e})),s}async removeTask(t,e){let s=await this.get(t);return s.task_pool=s.task_pool.filter(r=>r!==e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),s}async setLead(t,e){let s=await this.get(t),r=s.members.find(n=>n.agent_id===e);if(!r)throw new c$2(`Agent ${e} is not a member of team ${t}`);let a=s.members.find(n=>n.agent_id===s.lead_agent_id);return a&&(a.role="member"),r.role="lead",s.lead_agent_id=e,s.updated_at=new Date().toISOString(),await this.teamStore.save(s),s}async disband(t){let e=await this.get(t);e.status="disbanded",e.updated_at=new Date().toISOString(),await this.teamStore.save(e),this.eventBus.emit({type:"team:disbanded",teamId:t});}async findTeamForAgent(t){return (await this.teamStore.list()).find(s=>s.status==="active"&&s.members.some(r=>r.agent_id===t))??null}};async function Ht(m){let t=new b(m.projectRoot),e=new G(t),s=new L,[,r]=await Promise.all([t.requireInit(),e.read()]),a=new M(t),n=new D(t),i=new R(t),o=new O(t),c=new B(t),d=new F(t),k=new N(t),S=new $(t),v=new U,b$1=new J(a,v,r,t,n),I=new H(n,o,v,r),h=new q(i,v),A=new Y(d,n,S,v),E=new z(k,v,I,b$1,c),C=new W(S,n,a,v);return {context:m,paths:t,config:r,taskStore:a,agentStore:n,runStore:i,stateStore:o,configStore:e,globalConfigStore:s,globalConfig:P,contextStore:c,messageStore:d,goalStore:k,teamStore:S,eventBus:v,taskService:b$1,agentService:I,runService:h,messageService:A,goalService:E,teamService:C}}async function qt(m){let t=await Ht(m),e=await t.globalConfigStore.read();t.globalConfig=e;let[{ProcessManager:s},{AdapterRegistry:r},{ClaudeAdapter:a},{CodexAdapter:n},{CursorAdapter:i},{ShellAdapter:o},{OpenCodeAdapter:c},{PiAdapter:d},{WorkspaceManager:k},{LiquidTemplateEngine:S},{SkillLoader:v},{Orchestrator:b},{DoctorService:I}]=await Promise.all([import('./process-manager-33H27MQF.js'),import('./registry-BO2PPRNG.js'),import('./claude-PH7LT3OH.js'),import('./codex-URQN4JLZ.js'),import('./cursor-EMX3ECDY.js'),import('./shell-NPNTWDMU.js'),import('./opencode-K22RCQ5C.js'),import('./pi-WHXXXVBE.js'),import('./workspace-manager-ZI5SVXJU.js'),import('./template-engine-VLIOJ3WX.js'),import('./skill-loader-IGRIELEM.js'),import('./orchestrator-AVJ23Q5T.js'),import('./doctor-service-PB7YBH3F.js')]),h=new s,A=new S,E=new v,C=new k(m.projectRoot,t.paths.root,h),_=new r;_.register(new a(h)),_.register(new n(h)),_.register(new i(h)),_.register(new o(h)),_.register(new c(h)),_.register(new d(h));let Tt=new I(_,h,m.projectRoot),bt=new b({taskStore:t.taskStore,agentStore:t.agentStore,runStore:t.runStore,stateStore:t.stateStore,adapterRegistry:_,workspaceManager:C,templateEngine:A,processManager:h,eventBus:t.eventBus,taskService:t.taskService,agentService:t.agentService,runService:t.runService,contextStore:t.contextStore,messageService:t.messageService,goalStore:t.goalStore,skillLoader:E,config:t.config,projectRoot:m.projectRoot,lockPath:t.paths.lockPath});return {...t,processManager:h,adapterRegistry:_,workspaceManager:C,templateEngine:A,skillLoader:E,doctorService:Tt,orchestrator:bt}}async function Cs(m){return qt(m)}export{Cs as buildContainer,qt as buildFullContainer,Ht as buildLightContainer};
|
|
4
|
+
`);}catch{}return {error:r,output:a}}};var Y=class{constructor(t,e,s,r){this.messageStore=t;this.agentStore=e;this.teamStore=s;this.eventBus=r;}async send(t){if(!t.body.trim())throw new c$2("Message body is required");let e=t.ttl_ms??864e5;if(e<=0||e>6048e5)throw new c$2(`TTL must be between 1ms and ${6048e5}ms`);if(!await this.agentStore.get(t.from_agent_id)&&t.from_agent_id!=="cli")throw new c$2(`Sender agent not found: ${t.from_agent_id}`);let r=new Date,a={channel:t.channel,from_agent_id:t.from_agent_id,subject:(t.subject||"(no subject)").slice(0,200),body:t.body.slice(0,4e3),created_at:r.toISOString(),expires_at:new Date(r.getTime()+e).toISOString(),status:"pending",team_id:t.team_id,reply_to:t.reply_to},n=[];if(t.channel==="broadcast"){let i=await this.agentStore.list();if(t.team_id){let d=await this.teamStore.get(t.team_id);if(d){let k=new Set(d.members.map(S=>S.agent_id));i=i.filter(S=>k.has(S.id));}}let c=i.filter(d=>d.id!==t.from_agent_id&&d.status!=="disabled").map(d=>({...a,id:`msg_${nanoid(7)}`,to_agent_id:d.id}));await Promise.all(c.map(d=>this.messageStore.save(d)));for(let d of c)n.push(d),this.emitSent(d);}else if(t.channel==="lead"){if(!t.team_id)throw new c$2("team_id is required for lead channel");let i=await this.teamStore.get(t.team_id);if(!i)throw new c$2(`Team not found: ${t.team_id}`);let o={...a,id:`msg_${nanoid(7)}`,to_agent_id:i.lead_agent_id};await this.messageStore.save(o),n.push(o),this.emitSent(o);}else {if(!t.to_agent_id)throw new c$2("to_agent_id is required for direct messages");if(!await this.agentStore.get(t.to_agent_id))throw new c$2(`Recipient agent not found: ${t.to_agent_id}`);let o={...a,id:`msg_${nanoid(7)}`,to_agent_id:t.to_agent_id};await this.messageStore.save(o),n.push(o),this.emitSent(o);}return n}async drainMailbox(t,e){let s=await this.messageStore.listPending(t);await Promise.all(s.map(r=>this.messageStore.markDelivered(r.id)));for(let r of s)this.eventBus.emit({type:"message:delivered",messageId:r.id,toAgentId:t,taskId:e});return s}async listAll(){return this.messageStore.list()}async listPendingForAgent(t){return this.messageStore.listPending(t)}async listForAgent(t){return (await this.messageStore.list()).filter(s=>s.to_agent_id===t||s.from_agent_id===t)}async purgeExpired(){return this.messageStore.purgeExpired()}emitSent(t){this.eventBus.emit({type:"message:sent",messageId:t.id,fromAgentId:t.from_agent_id,toAgentId:t.to_agent_id,channel:t.channel});}};var Ut={active:["paused","achieved","abandoned"],paused:["active","achieved","abandoned"],achieved:[],abandoned:[]},z=class{constructor(t,e,s,r,a){this.goalStore=t;this.eventBus=e;this.agentService=s;this.taskService=r;this.contextStore=a;}async create(t){if(!t.title.trim())throw new c$2("Goal title is required");let e=new Date().toISOString(),s={id:`goal_${nanoid(7)}`,title:t.title.trim(),description:t.description?.trim()??"",status:"active",assignee:t.assignee,created_at:e,updated_at:e};return await this.goalStore.save(s),this.eventBus.emit({type:"goal:created",goalId:s.id,title:s.title}),s.assignee&&await this.enableAutonomous(s.assignee),s}async list(t){return this.goalStore.list(t)}async get(t){let e=await this.goalStore.get(t);if(!e)throw new j$1(t);return e}async updateStatus(t,e,s){let r=await this.get(t),a$1=r.status;if(!Ut[a$1].includes(e))throw new c$2(`Cannot transition goal from '${a$1}' to '${e}'`);if(e==="achieved"&&this.taskService){let i=(await this.taskService.list({goalId:t})).filter(o=>!b$2(o.status)&&!o.labels?.includes(a));if(i.length>0)if(s?.force){let o=i.filter(d=>d.status!=="in_progress"),c=i.filter(d=>d.status==="in_progress");if(await Promise.all(o.map(d=>this.taskService.cancel(d.id).catch(()=>{}))),c.length>0){let d=c.map(k=>`${k.id} (in_progress)`).join(", ");throw new k(t,c.length,d)}}else {let o=i.map(c=>`${c.id} (${c.status})`).join(", ");throw new k(t,i.length,o)}}return r.status=e,r.updated_at=new Date().toISOString(),await this.goalStore.save(r),this.eventBus.emit({type:"goal:status_changed",goalId:t,from:a$1,to:e}),r.assignee&&(e==="paused"?(await this.maybeDisableAutonomous(r.assignee),await this.cancelPendingAutonomousTasks(r.assignee)):e==="active"&&a$1==="paused"?await this.enableAutonomous(r.assignee):b$3(e)&&await this.maybeDisableAutonomous(r.assignee)),r}async update(t,e){let s=await this.get(t),r=s.assignee;if(e.title!==void 0){if(!e.title.trim())throw new c$2("Goal title cannot be empty");s.title=e.title.trim();}e.description!==void 0&&(s.description=e.description.trim()),e.assignee!==void 0&&(s.assignee=e.assignee||void 0),s.updated_at=new Date().toISOString(),await this.goalStore.save(s),this.eventBus.emit({type:"goal:updated",goalId:t});let a=s.assignee;if(a!==r){let n=[];a&&n.push(this.enableAutonomous(a)),r&&n.push(this.maybeDisableAutonomous(r)),await Promise.all(n);}return s}async delete(t){let e=await this.get(t),{assignee:s}=e;await this.goalStore.delete(t),this.eventBus.emit({type:"goal:deleted",goalId:t}),s&&await this.maybeDisableAutonomous(s);}async listTasksForGoal(t){return this.taskService?.list({goalId:t})??[]}async getProgressReport(t){return this.contextStore?(await this.contextStore.get(`${t}-progress`))?.value:void 0}async enableAutonomous(t){if(this.agentService)try{await this.agentService.setAutonomous(t,!0);}catch{}}async hasActiveGoalsForAgent(t){return (await this.goalStore.list({status:"active"})).some(s=>s.assignee===t)}async cancelPendingAutonomousTasks(t){if(this.taskService)try{let[e,s]=await Promise.all([this.taskService.list({status:"todo"}),this.taskService.list({status:"retrying"})]),r=[...e,...s].filter(a$1=>a$1.assignee===t&&a$1.labels?.includes(a));await Promise.all(r.map(a=>this.taskService.cancel(a.id).catch(()=>{})));}catch{}}async maybeDisableAutonomous(t){if(this.agentService)try{await this.hasActiveGoalsForAgent(t)||await this.agentService.setAutonomous(t,!1);}catch{}}};var xt={auto_claim:true,message_ttl_ms:864e5};var W=class{constructor(t,e,s,r){this.teamStore=t;this.agentStore=e;this.taskStore=s;this.eventBus=r;}async create(t){if(!t.name.trim())throw new c$2("Team name is required");if(!await this.agentStore.get(t.lead_agent_id))throw new c$2(`Lead agent not found: ${t.lead_agent_id}`);if(await this.teamStore.getByName(t.name.trim()))throw new c$2(`Team "${t.name}" already exists`);let r=new Date().toISOString(),a={agent_id:t.lead_agent_id,role:"lead",joined_at:r},n=[];for(let o of t.member_agent_ids??[]){if(o===t.lead_agent_id)continue;if(!await this.agentStore.get(o))throw new c$2(`Member agent not found: ${o}`);n.push({agent_id:o,role:"member",joined_at:r});}let i={id:`team_${nanoid(7)}`,name:t.name.trim(),description:t.description,status:"active",members:[a,...n],task_pool:[],lead_agent_id:t.lead_agent_id,created_at:r,updated_at:r,config:{...xt,...t.config??{}}};await this.teamStore.save(i),this.eventBus.emit({type:"team:created",teamId:i.id,name:i.name,leadAgentId:i.lead_agent_id});for(let o of n)this.eventBus.emit({type:"team:member_joined",teamId:i.id,agentId:o.agent_id});return i}async get(t){let e=await this.teamStore.get(t);if(!e)throw new l(t);return e}async list(){return this.teamStore.list()}async join(t,e){let s=await this.get(t);if(s.members.some(a=>a.agent_id===e))throw new c$2(`Agent ${e} is already a member of team ${t}`);if(!await this.agentStore.get(e))throw new c$2(`Agent not found: ${e}`);return s.members.push({agent_id:e,role:"member",joined_at:new Date().toISOString()}),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:member_joined",teamId:t,agentId:e}),s}async leave(t,e){let s=await this.get(t);if(e===s.lead_agent_id)throw new c$2("Lead cannot leave team. Disband the team or transfer lead first.");return s.members=s.members.filter(r=>r.agent_id!==e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:member_left",teamId:t,agentId:e}),s}async addTask(t,e){let s=await this.get(t);if(!await this.taskStore.get(e))throw new c$2(`Task not found: ${e}`);return s.task_pool.includes(e)||(s.task_pool.push(e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:task_added",teamId:t,taskId:e})),s}async removeTask(t,e){let s=await this.get(t);return s.task_pool=s.task_pool.filter(r=>r!==e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),s}async setLead(t,e){let s=await this.get(t),r=s.members.find(n=>n.agent_id===e);if(!r)throw new c$2(`Agent ${e} is not a member of team ${t}`);let a=s.members.find(n=>n.agent_id===s.lead_agent_id);return a&&(a.role="member"),r.role="lead",s.lead_agent_id=e,s.updated_at=new Date().toISOString(),await this.teamStore.save(s),s}async disband(t){let e=await this.get(t);e.status="disbanded",e.updated_at=new Date().toISOString(),await this.teamStore.save(e),this.eventBus.emit({type:"team:disbanded",teamId:t});}async findTeamForAgent(t){return (await this.teamStore.list()).find(s=>s.status==="active"&&s.members.some(r=>r.agent_id===t))??null}};async function Ht(m){let t=new b(m.projectRoot),e=new G(t),s=new L,[,r]=await Promise.all([t.requireInit(),e.read()]),a=new M(t),n=new D(t),i=new R(t),o=new O(t),c=new B(t),d=new F(t),k=new N(t),S=new $(t),v=new U,b$1=new J(a,v,r,t,n),I=new H(n,o,v,r),h=new q(i,v),A=new Y(d,n,S,v),E=new z(k,v,I,b$1,c),C=new W(S,n,a,v);return {context:m,paths:t,config:r,taskStore:a,agentStore:n,runStore:i,stateStore:o,configStore:e,globalConfigStore:s,globalConfig:P,contextStore:c,messageStore:d,goalStore:k,teamStore:S,eventBus:v,taskService:b$1,agentService:I,runService:h,messageService:A,goalService:E,teamService:C}}async function qt(m){let t=await Ht(m),e=await t.globalConfigStore.read();t.globalConfig=e;let[{ProcessManager:s},{AdapterRegistry:r},{ClaudeAdapter:a},{CodexAdapter:n},{CursorAdapter:i},{ShellAdapter:o},{OpenCodeAdapter:c},{PiAdapter:d},{WorkspaceManager:k},{LiquidTemplateEngine:S},{SkillLoader:v},{Orchestrator:b},{DoctorService:I}]=await Promise.all([import('./process-manager-33H27MQF.js'),import('./registry-BO2PPRNG.js'),import('./claude-PH7LT3OH.js'),import('./codex-URQN4JLZ.js'),import('./cursor-EMX3ECDY.js'),import('./shell-NPNTWDMU.js'),import('./opencode-K22RCQ5C.js'),import('./pi-XEINSHUN.js'),import('./workspace-manager-ZI5SVXJU.js'),import('./template-engine-VLIOJ3WX.js'),import('./skill-loader-IGRIELEM.js'),import('./orchestrator-AVJ23Q5T.js'),import('./doctor-service-PB7YBH3F.js')]),h=new s,A=new S,E=new v,C=new k(m.projectRoot,t.paths.root,h),_=new r;_.register(new a(h)),_.register(new n(h)),_.register(new i(h)),_.register(new o(h)),_.register(new c(h)),_.register(new d(h));let Tt=new I(_,h,m.projectRoot),bt=new b({taskStore:t.taskStore,agentStore:t.agentStore,runStore:t.runStore,stateStore:t.stateStore,adapterRegistry:_,workspaceManager:C,templateEngine:A,processManager:h,eventBus:t.eventBus,taskService:t.taskService,agentService:t.agentService,runService:t.runService,contextStore:t.contextStore,messageService:t.messageService,goalStore:t.goalStore,skillLoader:E,config:t.config,projectRoot:m.projectRoot,lockPath:t.paths.lockPath});return {...t,processManager:h,adapterRegistry:_,workspaceManager:C,templateEngine:A,skillLoader:E,doctorService:Tt,orchestrator:bt}}async function Cs(m){return qt(m)}export{Cs as buildContainer,qt as buildFullContainer,Ht as buildLightContainer};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$4}from'./chunk-
|
|
2
|
+
import {a as a$4}from'./chunk-SJG3HXO5.js';import {a as a$5}from'./chunk-HMMPM7MF.js';import {p,c,q}from'./chunk-64WUDYEM.js';import {b}from'./chunk-6E6DC7OE.js';import'./chunk-ZMLF5HI5.js';import {a as a$1}from'./chunk-CDFA4IIQ.js';import {a as a$2}from'./chunk-DEHFYICU.js';import {a as a$3}from'./chunk-ITMAWW3J.js';import'./chunk-C7C7Q7XO.js';import'./chunk-P4JTJBWO.js';import'./chunk-LRYVT4D4.js';import {a}from'./chunk-6MJ7V6VY.js';import a$6 from'chalk';function z(y,t){y.command("doctor").description("Check adapters and dependencies").action(async()=>{let c$1,n,d=false;if(t)c$1=t.doctorService,n=t.paths,d=true;else {let o=new a,e=new a$1;e.register(new a$2(o)),e.register(new a$3(o)),e.register(new a$4(o)),c$1=new a$5(e,o,process.cwd()),n=new b(process.cwd());}console.log(),console.log(` ${p("orch doctor")} \xB7 checking adapters and dependencies`),console.log();let i=await c$1.runAll();if(t?.context.json){console.log(JSON.stringify(i,null,2));return}for(let o of i.checks){let e=o.status==="ok"?a$6.ansi256(72)(c("done")):o.status==="fail"?a$6.ansi256(167)(c("failed")):q("\u2014"),l=o.detail?q(` ${o.detail}`):"";console.log(` ${e} ${o.name.padEnd(12)}${l}`);}if(n){let o=await n.isInitialized();if(o&&d){let e=await t.agentService.list(),l=await t.taskService.list();console.log(),console.log(` ${a$6.ansi256(72)(c("done"))} .orchestry/ ${q(`exists \xB7 ${e.length} agents \xB7 ${l.length} tasks`)}`);}else o||(console.log(),console.log(` ${a$6.ansi256(167)(c("failed"))} .orchestry/ ${q("not found \u2014 run: orch init")}`));}console.log(),console.log(` ${i.adaptersReady} of ${i.adaptersTotal} adapters ready`),console.log();});}export{z as registerDoctorCommand};
|
package/dist/index.d.ts
CHANGED
|
@@ -1012,6 +1012,35 @@ interface ExecuteParams {
|
|
|
1012
1012
|
config: AgentConfig;
|
|
1013
1013
|
signal?: AbortSignal;
|
|
1014
1014
|
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Canonical `data` shape per AgentEvent type. Each adapter should emit `data`
|
|
1017
|
+
* that matches its event's row below so that downstream consumers (TUI logs,
|
|
1018
|
+
* `orch logs` CLI, serve daemon) can render events without knowing adapter
|
|
1019
|
+
* internals.
|
|
1020
|
+
*
|
|
1021
|
+
* | type | data shape |
|
|
1022
|
+
* |-------------|---------------------------------------------------|
|
|
1023
|
+
* | output | { text: string, raw?: unknown } |
|
|
1024
|
+
* | tool_call | { name: string, input?: unknown, raw?: unknown } |
|
|
1025
|
+
* | command | { command: string, result?: unknown, raw?: unknown } |
|
|
1026
|
+
* | file_change | { paths: string[], raw?: unknown } |
|
|
1027
|
+
* | error | { message: string, raw?: unknown } |
|
|
1028
|
+
* | done | { result?: string, raw?: unknown } |
|
|
1029
|
+
*
|
|
1030
|
+
* - `raw` is an optional escape hatch for the full provider payload; logs
|
|
1031
|
+
* renderers must not include it in the default summary.
|
|
1032
|
+
* - Adapters should emit ONE `output` per logical assistant message (per
|
|
1033
|
+
* text-block or per turn), not per-character delta. Use adapter-local state
|
|
1034
|
+
* to aggregate streaming deltas before emitting.
|
|
1035
|
+
* - Intermediate progress events (tool-in-flight, "thinking" pings) should be
|
|
1036
|
+
* dropped at the adapter boundary — they belong in adapter-specific UIs,
|
|
1037
|
+
* not in the orchestrator event stream.
|
|
1038
|
+
*
|
|
1039
|
+
* Existing adapters predate this contract and emit a variety of shapes
|
|
1040
|
+
* (claude/cursor: full `parsed.message`; codex: `item`). The TUI renderer
|
|
1041
|
+
* (`formatAgentOutput` in src/tui/App.tsx) is defensive and accepts both
|
|
1042
|
+
* canonical and legacy shapes during the migration window.
|
|
1043
|
+
*/
|
|
1015
1044
|
interface AgentEvent {
|
|
1016
1045
|
type: 'output' | 'file_change' | 'command' | 'tool_call' | 'error' | 'done';
|
|
1017
1046
|
timestamp: string;
|
package/dist/index.js
CHANGED
|
@@ -2557,7 +2557,7 @@ async function buildFullContainer(context) {
|
|
|
2557
2557
|
import('./cursor-O6M6XOMT.js'),
|
|
2558
2558
|
import('./shell-C2J4AIAV.js'),
|
|
2559
2559
|
import('./opencode-HOX5TCMD.js'),
|
|
2560
|
-
import('./pi-
|
|
2560
|
+
import('./pi-GFJCLRZJ.js'),
|
|
2561
2561
|
import('./workspace-manager-QH27FF55.js'),
|
|
2562
2562
|
import('./template-engine-XOH3FZPU.js'),
|
|
2563
2563
|
import('./skill-loader-RHCFIK74.js'),
|
|
@@ -147,7 +147,7 @@ function parsePiRpcEvent(line, state) {
|
|
|
147
147
|
try {
|
|
148
148
|
parsed = JSON.parse(line);
|
|
149
149
|
} catch {
|
|
150
|
-
return { agentEvent: { type: "output", timestamp: (/* @__PURE__ */ new Date()).toISOString(), data: line } };
|
|
150
|
+
return { agentEvent: { type: "output", timestamp: (/* @__PURE__ */ new Date()).toISOString(), data: { text: line } } };
|
|
151
151
|
}
|
|
152
152
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
153
153
|
const type = typeof parsed.type === "string" ? parsed.type : "";
|
|
@@ -166,9 +166,9 @@ function parsePiRpcEvent(line, state) {
|
|
|
166
166
|
return extractPassiveUpdate(parsed);
|
|
167
167
|
case "response": {
|
|
168
168
|
if (parsed.success === false) {
|
|
169
|
-
const
|
|
169
|
+
const message = typeof parsed.error === "string" ? parsed.error : JSON.stringify(parsed);
|
|
170
170
|
return {
|
|
171
|
-
agentEvent: { type: "error", timestamp, data: parsed, errorKind: classifyAdapterError(
|
|
171
|
+
agentEvent: { type: "error", timestamp, data: { message, raw: parsed }, errorKind: classifyAdapterError(message) }
|
|
172
172
|
};
|
|
173
173
|
}
|
|
174
174
|
return null;
|
|
@@ -184,13 +184,7 @@ function parsePiRpcEvent(line, state) {
|
|
|
184
184
|
}
|
|
185
185
|
};
|
|
186
186
|
case "tool_execution_update":
|
|
187
|
-
return
|
|
188
|
-
agentEvent: {
|
|
189
|
-
type: "output",
|
|
190
|
-
timestamp,
|
|
191
|
-
data: parsed
|
|
192
|
-
}
|
|
193
|
-
};
|
|
187
|
+
return null;
|
|
194
188
|
case "tool_execution_end":
|
|
195
189
|
return parseToolExecutionEnd(parsed, timestamp);
|
|
196
190
|
case "agent_end": {
|
|
@@ -208,13 +202,13 @@ function parsePiRpcEvent(line, state) {
|
|
|
208
202
|
};
|
|
209
203
|
}
|
|
210
204
|
case "extension_error": {
|
|
211
|
-
const
|
|
205
|
+
const message = typeof parsed.message === "string" ? parsed.message : JSON.stringify(parsed);
|
|
212
206
|
return {
|
|
213
|
-
agentEvent: { type: "error", timestamp, data: parsed, errorKind: classifyAdapterError(
|
|
207
|
+
agentEvent: { type: "error", timestamp, data: { message, raw: parsed }, errorKind: classifyAdapterError(message) }
|
|
214
208
|
};
|
|
215
209
|
}
|
|
216
210
|
default:
|
|
217
|
-
return
|
|
211
|
+
return null;
|
|
218
212
|
}
|
|
219
213
|
}
|
|
220
214
|
function parseMessageUpdate(parsed, timestamp, state) {
|
|
@@ -222,19 +216,20 @@ function parseMessageUpdate(parsed, timestamp, state) {
|
|
|
222
216
|
const updateType = typeof assistantMessageEvent?.type === "string" ? assistantMessageEvent.type : "";
|
|
223
217
|
if (updateType === "text_delta") {
|
|
224
218
|
const delta = typeof assistantMessageEvent?.delta === "string" ? assistantMessageEvent.delta : "";
|
|
225
|
-
return {
|
|
226
|
-
finalText: state.finalText + delta,
|
|
227
|
-
agentEvent: { type: "output", timestamp, data: { text: delta, raw: parsed } }
|
|
228
|
-
};
|
|
219
|
+
return { finalText: state.finalText + delta };
|
|
229
220
|
}
|
|
230
221
|
if (updateType === "text_end") {
|
|
231
222
|
const content = typeof assistantMessageEvent?.content === "string" ? assistantMessageEvent.content : state.finalText;
|
|
232
|
-
return { finalText:
|
|
223
|
+
if (!content) return { finalText: "" };
|
|
224
|
+
return {
|
|
225
|
+
finalText: "",
|
|
226
|
+
agentEvent: { type: "output", timestamp, data: { text: content } }
|
|
227
|
+
};
|
|
233
228
|
}
|
|
234
229
|
if (updateType === "error") {
|
|
235
230
|
const reason = typeof assistantMessageEvent?.reason === "string" ? assistantMessageEvent.reason : JSON.stringify(parsed);
|
|
236
231
|
return {
|
|
237
|
-
agentEvent: { type: "error", timestamp, data: parsed, errorKind: classifyAdapterError(reason) }
|
|
232
|
+
agentEvent: { type: "error", timestamp, data: { message: reason, raw: parsed }, errorKind: classifyAdapterError(reason) }
|
|
238
233
|
};
|
|
239
234
|
}
|
|
240
235
|
return null;
|
|
@@ -242,18 +237,20 @@ function parseMessageUpdate(parsed, timestamp, state) {
|
|
|
242
237
|
function parseToolExecutionEnd(parsed, timestamp) {
|
|
243
238
|
const toolName = typeof parsed.toolName === "string" ? parsed.toolName : "";
|
|
244
239
|
const args = parsed.args;
|
|
240
|
+
const resultText = extractToolResultText(parsed.result);
|
|
245
241
|
if (parsed.isError === true) {
|
|
246
|
-
const
|
|
242
|
+
const message = resultText || JSON.stringify(parsed.result ?? parsed);
|
|
247
243
|
return {
|
|
248
|
-
agentEvent: { type: "error", timestamp, data: parsed, errorKind: classifyAdapterError(
|
|
244
|
+
agentEvent: { type: "error", timestamp, data: { message, raw: parsed }, errorKind: classifyAdapterError(message) }
|
|
249
245
|
};
|
|
250
246
|
}
|
|
251
247
|
if (toolName === "bash") {
|
|
248
|
+
const command = typeof args?.command === "string" ? args.command : JSON.stringify(args ?? {});
|
|
252
249
|
return {
|
|
253
250
|
agentEvent: {
|
|
254
251
|
type: "command",
|
|
255
252
|
timestamp,
|
|
256
|
-
data: { command
|
|
253
|
+
data: { command, result: resultText, raw: parsed }
|
|
257
254
|
}
|
|
258
255
|
};
|
|
259
256
|
}
|
|
@@ -269,7 +266,13 @@ function parseToolExecutionEnd(parsed, timestamp) {
|
|
|
269
266
|
};
|
|
270
267
|
}
|
|
271
268
|
}
|
|
272
|
-
|
|
269
|
+
const summary = resultText || `${toolName || "tool"} completed`;
|
|
270
|
+
return { agentEvent: { type: "output", timestamp, data: { text: summary, raw: parsed } } };
|
|
271
|
+
}
|
|
272
|
+
function extractToolResultText(result) {
|
|
273
|
+
if (typeof result === "string") return result;
|
|
274
|
+
if (!result || typeof result !== "object") return "";
|
|
275
|
+
return extractTextFromContent(result.content) ?? "";
|
|
273
276
|
}
|
|
274
277
|
function extractPassiveUpdate(parsed) {
|
|
275
278
|
const tokens = extractPiTokensFromMessage(parsed);
|
|
@@ -386,5 +389,5 @@ async function* readPiRpcLines(stream) {
|
|
|
386
389
|
}
|
|
387
390
|
|
|
388
391
|
export { PiAdapter };
|
|
389
|
-
//# sourceMappingURL=pi-
|
|
390
|
-
//# sourceMappingURL=pi-
|
|
392
|
+
//# sourceMappingURL=pi-GFJCLRZJ.js.map
|
|
393
|
+
//# sourceMappingURL=pi-GFJCLRZJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/infrastructure/adapters/pi.ts"],"names":[],"mappings":";;;;AAgBO,IAAM,YAAN,MAAyC;AAAA,EAG9C,YAA6B,cAAA,EAAiC;AAAjC,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAAA,EAAkC;AAAA,EAFtD,IAAA,GAAO,IAAA;AAAA,EAIhB,MAAM,IAAA,GAAmC;AACvC,IAAA,IAAI;AACF,MAAA,MAAM,SAAS,MAAM,IAAI,OAAA,CAAgB,CAAC,SAAS,MAAA,KAAW;AAC5D,QAAA,QAAA,CAAS,MAAM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AO,OAAA,CAAQ,EAAA,EAAM,MAAM,OAAO,EAAA,EAAI;AACzD,MAAA,IAAI,aAAa,MAAA,EAAQ;AACvB,QAAA,MAAM,IAAA,GAAO,MAAA,CAAO,QAAA,CAAS,OAAA,EAAS,QAAQ,UAAU,CAAA;AACxD,QAAA,MAAM,IAAA,CAAK,SAAS,IAAI,CAAA,GAAI,KAAK,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,GAAI,IAAA;AAAA,MAClD;AACA,MAAA,MAAA,GAAS,UAAA,GAAa,CAAA;AAAA,IACxB;AAEA,IAAA,IAAI,MAAA,GAAS,OAAO,MAAA,EAAQ;AAC1B,MAAA,MAAM,SAAA,GAAY,MAAA,CAAO,QAAA,CAAS,MAAM,CAAA;AACxC,MAAA,MAAA,CAAO,KAAK,SAAS,CAAA;AACrB,MAAA,QAAA,GAAW,SAAA,CAAU,MAAA;AAAA,IACvB;AAAA,EACF;AAEA,EAAA,IAAI,WAAW,CAAA,EAAG;AAChB,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,MAAA,KAAW,CAAA,GAAI,MAAA,CAAO,CAAC,CAAA,GAAK,MAAA,CAAO,MAAA,CAAO,MAAA,EAAQ,QAAQ,CAAA;AAC/E,IAAA,MAAM,IAAA,GAAO,KAAA,CAAM,QAAA,CAAS,OAAO,CAAA;AACnC,IAAA,IAAI,IAAA,EAAM,MAAM,IAAA,CAAK,QAAA,CAAS,IAAI,IAAI,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,GAAI,IAAA;AAAA,EAC5D;AACF","file":"pi-GFJCLRZJ.js","sourcesContent":["/**\n * Pi coding agent adapter.\n *\n * Spawns `pi --mode rpc` in headless RPC mode.\n * Sends the ORCH prompt as a JSONL `prompt` command over stdin and maps Pi\n * RPC events from stdout into ORCH AgentEvents. Pi extensions/skills/context\n * remain enabled by default; UI-only extension events are ignored.\n */\n\nimport type { IAgentAdapter, AdapterTestResult, ExecuteParams, AgentEvent, ExecuteHandle } from './interface.js';\nimport type { IProcessManager } from '../process/process-manager.js';\nimport type { Readable } from 'node:stream';\nimport { createTokenUsage, type TokenUsage } from '../../domain/run.js';\nimport { classifyAdapterError } from '../../domain/errors.js';\nimport { execFile } from 'node:child_process';\n\nexport class PiAdapter implements IAgentAdapter {\n readonly kind = 'pi';\n\n constructor(private readonly processManager: IProcessManager) {}\n\n async test(): Promise<AdapterTestResult> {\n try {\n const stdout = await new Promise<string>((resolve, reject) => {\n execFile('pi', ['--version'], (err, out) => {\n if (err) reject(err);\n else resolve(out);\n });\n });\n return { ok: true, version: stdout.trim() };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n ok: false,\n error: 'Pi CLI not found. Install: npm i -g @mariozechner/pi-coding-agent',\n errorKind: classifyAdapterError(msg),\n };\n }\n }\n\n execute(params: ExecuteParams): ExecuteHandle {\n const args = [\n '--mode', 'rpc',\n ];\n\n if (params.config.model) {\n args.push('--model', params.config.model);\n }\n\n if (params.config.effort) {\n args.push('--thinking', params.config.effort);\n }\n\n // Preserve Pi's own coding-agent harness prompt. ORCH's system prompt is\n // appended as additional project/task governance rather than replacing it.\n const effectiveSystemPrompt = params.systemPrompt ?? params.config.system_prompt;\n if (effectiveSystemPrompt) {\n args.push('--append-system-prompt', effectiveSystemPrompt);\n }\n\n const { process: proc, pid } = this.processManager.spawn('pi', args, {\n cwd: params.workspace,\n env: { ...process.env, ...params.env },\n signal: params.signal,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n // Capture stderr tail so auth/extension-load errors surface in non-zero exits\n // rather than being silently drained. Drains backpressure at the same time.\n const stderrTail = createStderrTailCapture(proc.stderr);\n\n if (proc.stdin) {\n proc.stdin.write(JSON.stringify({\n id: `orch-${Date.now()}`,\n type: 'prompt',\n message: params.prompt,\n }) + '\\n');\n // DO NOT call proc.stdin.end() here. Pi --mode rpc is a long-lived\n // persistent session: it sends a prompt preflight response, then drives\n // the LLM call asynchronously, streaming message_update / turn_end /\n // agent_end as the model responds. Closing stdin after the write breaks\n // that pipeline — verified on pi-coding-agent 0.73.1: pi stalls right\n // after the user-message_end event and never produces an assistant turn.\n // We terminate the long-lived process via processManager.killWithGrace\n // immediately after the terminal `done` event (see createPiRpcEvents).\n }\n\n const events = createPiRpcEvents(proc, pid, this.processManager, stderrTail, params.signal);\n return { pid, events };\n }\n\n async stop(pid: number): Promise<void> {\n await this.processManager.killWithGrace(pid);\n }\n}\n\nfunction createPiRpcEvents(\n proc: import('node:child_process').ChildProcess,\n pid: number,\n processManager: IProcessManager,\n stderrTail: () => string,\n signal?: AbortSignal,\n): AsyncGenerator<AgentEvent> {\n async function* generate(): AsyncGenerator<AgentEvent> {\n let gotDoneEvent = false;\n let streamErrorYielded = false;\n let finalText = '';\n let lastTokens: TokenUsage | undefined;\n let exitCode: number | null = null;\n let exitError: Error | null = null;\n\n const exitPromise = new Promise<void>((resolve) => {\n proc.on('close', (code) => { exitCode = code; resolve(); });\n proc.on('error', (err) => { exitError = err; resolve(); });\n });\n\n let streamError: Error | null = null;\n try {\n if (proc.stdout) {\n try {\n for await (const line of readPiRpcLines(proc.stdout)) {\n if (signal?.aborted) break;\n const event = parsePiRpcEvent(line, { finalText, lastTokens });\n if (!event) continue;\n\n if (event.finalText !== undefined) finalText = event.finalText;\n if (event.tokens) lastTokens = event.tokens;\n\n if (event.agentEvent) {\n if (event.agentEvent.type === 'done') gotDoneEvent = true;\n yield event.agentEvent;\n if (event.agentEvent.type === 'done') {\n // Pi RPC is a long-lived process. ORCH tasks are one-shot runs, so\n // stop Pi after the terminal event instead of waiting forever.\n await processManager.killWithGrace(pid, 1_000).catch(() => {});\n return;\n }\n }\n }\n } catch (err) {\n // stdout emitted 'error' (ECONNRESET, EPIPE, etc) before a terminal event.\n // Without this catch the rejection propagates out of the async generator\n // as an unhandled error and the orchestrator only sees the run hang.\n streamError = err instanceof Error ? err : new Error(String(err));\n if (!signal?.aborted && !gotDoneEvent) {\n streamErrorYielded = true;\n yield {\n type: 'error',\n timestamp: new Date().toISOString(),\n data: { message: streamError.message },\n errorKind: classifyAdapterError(streamError.message),\n };\n }\n }\n }\n } finally {\n proc.stdout?.destroy();\n // Pi RPC is long-lived. If we leave via abort/break without a 'done' event,\n // the process is still alive — kill it so exitPromise resolves and the\n // generator doesn't pin the ChildProcess via dangling 'close' / 'error' listeners.\n if (!gotDoneEvent && (signal?.aborted || streamError)) {\n processManager.killWithGrace(pid, 1_000).catch(() => {});\n }\n }\n\n await exitPromise;\n\n // streamError was already surfaced as an error event — don't double-report.\n if (streamErrorYielded) return;\n\n const spawnError = exitError as Error | null;\n if (spawnError && !signal?.aborted && !gotDoneEvent) {\n const message = appendStderrTail(spawnError.message, stderrTail());\n const classified = classifyAdapterError(message, exitCode ?? undefined);\n throw Object.assign(new Error(message), { errorKind: classified });\n }\n if (exitCode !== 0 && exitCode !== null && !signal?.aborted && !gotDoneEvent) {\n const baseMsg = `Pi process exited with code ${exitCode}`;\n const message = appendStderrTail(baseMsg, stderrTail());\n const classified = classifyAdapterError(message, exitCode);\n throw Object.assign(new Error(message), { errorKind: classified });\n }\n }\n\n return generate();\n}\n\nfunction appendStderrTail(message: string, tail: string): string {\n return tail ? `${message}\\n--- pi stderr (tail) ---\\n${tail}` : message;\n}\n\ninterface ParseState {\n finalText: string;\n lastTokens?: TokenUsage;\n}\n\ninterface ParsedPiEvent {\n agentEvent?: AgentEvent;\n finalText?: string;\n tokens?: TokenUsage;\n}\n\nfunction parsePiRpcEvent(line: string, state: ParseState): ParsedPiEvent | null {\n if (!line.trim()) return null;\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n return { agentEvent: { type: 'output', timestamp: new Date().toISOString(), data: { text: line } } };\n }\n\n const timestamp = new Date().toISOString();\n const type = typeof parsed.type === 'string' ? parsed.type : '';\n\n switch (type) {\n case 'extension_ui_request':\n case 'agent_start':\n case 'turn_start':\n case 'message_start':\n case 'message_end':\n case 'turn_end':\n case 'queue_update':\n case 'compaction_start':\n case 'compaction_end':\n case 'auto_retry_start':\n case 'auto_retry_end':\n return extractPassiveUpdate(parsed);\n\n case 'response': {\n if (parsed.success === false) {\n const message = typeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed);\n return {\n agentEvent: { type: 'error', timestamp, data: { message, raw: parsed }, errorKind: classifyAdapterError(message) },\n };\n }\n return null;\n }\n\n case 'message_update':\n return parseMessageUpdate(parsed, timestamp, state);\n\n case 'tool_execution_start':\n return {\n agentEvent: {\n type: 'tool_call',\n timestamp,\n data: { name: parsed.toolName, input: parsed.args, raw: parsed },\n },\n };\n\n case 'tool_execution_update':\n // Intermediate progress: pi emits one of these per chunk of tool output\n // (e.g. streaming bash stdout). Other adapters don't surface this in\n // their event streams — drop it so the canonical contract holds.\n return null;\n\n case 'tool_execution_end':\n return parseToolExecutionEnd(parsed, timestamp);\n\n case 'agent_end': {\n const final = extractFinalText(parsed) ?? state.finalText;\n const tokens = extractPiTokensFromAgentEnd(parsed) ?? state.lastTokens;\n return {\n finalText: final,\n tokens,\n agentEvent: {\n type: 'done',\n timestamp,\n data: { result: final, raw: parsed },\n tokens,\n },\n };\n }\n\n case 'extension_error': {\n const message = typeof parsed.message === 'string' ? parsed.message : JSON.stringify(parsed);\n return {\n agentEvent: { type: 'error', timestamp, data: { message, raw: parsed }, errorKind: classifyAdapterError(message) },\n };\n }\n\n default:\n // Unknown pi event types are silently dropped: they would otherwise\n // pollute logs with raw RPC envelopes the renderer can't summarize.\n // Adding a known type above is the right way to surface a new event.\n return null;\n }\n}\n\nfunction parseMessageUpdate(parsed: Record<string, unknown>, timestamp: string, state: ParseState): ParsedPiEvent | null {\n const assistantMessageEvent = parsed.assistantMessageEvent as Record<string, unknown> | undefined;\n const updateType = typeof assistantMessageEvent?.type === 'string' ? assistantMessageEvent.type : '';\n\n if (updateType === 'text_delta') {\n // Aggregate deltas into state.finalText; emit nothing here. A long LLM\n // response is hundreds of deltas — flushing one event per delta floods\n // the activity feed with character-level fragments. text_end emits the\n // full message in one canonical `output` event below.\n const delta = typeof assistantMessageEvent?.delta === 'string' ? assistantMessageEvent.delta : '';\n return { finalText: state.finalText + delta };\n }\n\n if (updateType === 'text_end') {\n const content = typeof assistantMessageEvent?.content === 'string' ? assistantMessageEvent.content : state.finalText;\n // Reset the delta buffer so a follow-up assistant message in the same pi\n // session doesn't get concatenated onto this one (agent_end uses its own\n // messages[] extraction, not state.finalText, so this is safe to drop).\n if (!content) return { finalText: '' };\n return {\n finalText: '',\n agentEvent: { type: 'output', timestamp, data: { text: content } },\n };\n }\n\n if (updateType === 'error') {\n const reason = typeof assistantMessageEvent?.reason === 'string' ? assistantMessageEvent.reason : JSON.stringify(parsed);\n return {\n agentEvent: { type: 'error', timestamp, data: { message: reason, raw: parsed }, errorKind: classifyAdapterError(reason) },\n };\n }\n\n return null;\n}\n\nfunction parseToolExecutionEnd(parsed: Record<string, unknown>, timestamp: string): ParsedPiEvent {\n const toolName = typeof parsed.toolName === 'string' ? parsed.toolName : '';\n const args = parsed.args as Record<string, unknown> | undefined;\n const resultText = extractToolResultText(parsed.result);\n\n if (parsed.isError === true) {\n const message = resultText || JSON.stringify(parsed.result ?? parsed);\n return {\n agentEvent: { type: 'error', timestamp, data: { message, raw: parsed }, errorKind: classifyAdapterError(message) },\n };\n }\n\n if (toolName === 'bash') {\n const command = typeof args?.command === 'string' ? args.command : JSON.stringify(args ?? {});\n return {\n agentEvent: {\n type: 'command',\n timestamp,\n data: { command, result: resultText, raw: parsed },\n },\n };\n }\n\n if (/^(write|edit)$/i.test(toolName)) {\n const path = extractPath(args);\n if (path) {\n return {\n agentEvent: {\n type: 'file_change',\n timestamp,\n data: { paths: [path], raw: parsed },\n },\n };\n }\n }\n\n // Generic tool result (read, grep, ls, …) — surface the result text so logs\n // show what came back, not the raw RPC envelope.\n const summary = resultText || `${toolName || 'tool'} completed`;\n return { agentEvent: { type: 'output', timestamp, data: { text: summary, raw: parsed } } };\n}\n\n/** Pi tool results wrap content arrays in `{ content: [...] }`; messages don't. */\nfunction extractToolResultText(result: unknown): string {\n if (typeof result === 'string') return result;\n if (!result || typeof result !== 'object') return '';\n return extractTextFromContent((result as { content?: unknown }).content) ?? '';\n}\n\nfunction extractPassiveUpdate(parsed: Record<string, unknown>): ParsedPiEvent | null {\n const tokens = extractPiTokensFromMessage(parsed);\n return tokens ? { tokens } : null;\n}\n\nfunction extractFinalText(parsed: Record<string, unknown>): string | undefined {\n const messages = parsed.messages;\n if (!Array.isArray(messages)) return undefined;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i] as Record<string, unknown>;\n if (message.role !== 'assistant') continue;\n const text = extractTextFromContent(message.content);\n if (text) return text;\n }\n return undefined;\n}\n\nfunction extractTextFromContent(content: unknown): string | undefined {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return undefined;\n const parts = content\n .map((part) => {\n const p = part as Record<string, unknown>;\n return typeof p.text === 'string' ? p.text : '';\n })\n .filter(Boolean);\n return parts.length ? parts.join('') : undefined;\n}\n\nfunction extractPath(args: Record<string, unknown> | undefined): string | undefined {\n if (!args) return undefined;\n if (typeof args.path === 'string') return args.path;\n if (typeof args.file_path === 'string') return args.file_path;\n return undefined;\n}\n\nfunction extractPiTokensFromAgentEnd(parsed: Record<string, unknown>): TokenUsage | undefined {\n const messages = parsed.messages;\n if (!Array.isArray(messages)) return undefined;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i] as Record<string, unknown>;\n if (message.role !== 'assistant') continue;\n const tokens = extractPiTokensFromMessage(message);\n if (tokens) return tokens;\n }\n return undefined;\n}\n\n// Pi exposes usage under multiple key shapes across versions and across the\n// `message_*` vs `agent_end` paths — Pi-native names, snake_case shims, and\n// Anthropic-style names when Pi forwards Claude usage records unchanged.\n// First match per field wins, in this order.\nconst PI_TOKEN_ALIASES: Record<'input' | 'output' | 'reasoning' | 'cache_read' | 'cache_write', readonly string[]> = {\n input: ['input', 'input_tokens'],\n output: ['output', 'output_tokens'],\n reasoning: ['reasoning', 'reasoning_tokens'],\n cache_read: ['cacheRead', 'cache_read', 'cache_read_input_tokens'],\n cache_write: ['cacheWrite', 'cache_write', 'cache_creation_input_tokens'],\n};\n\nfunction extractPiTokensFromMessage(parsed: Record<string, unknown>): TokenUsage | undefined {\n const usage = parsed.usage as Record<string, unknown> | undefined;\n if (!usage) return undefined;\n\n const pick = (keys: readonly string[]): number => {\n for (const k of keys) {\n const v = usage[k];\n if (typeof v === 'number') return v;\n }\n return 0;\n };\n\n const input = pick(PI_TOKEN_ALIASES.input);\n const output = pick(PI_TOKEN_ALIASES.output);\n const reasoning = pick(PI_TOKEN_ALIASES.reasoning);\n const cache_read = pick(PI_TOKEN_ALIASES.cache_read);\n const cache_write = pick(PI_TOKEN_ALIASES.cache_write);\n\n if (input === 0 && output === 0 && reasoning === 0 && cache_read === 0 && cache_write === 0) return undefined;\n return createTokenUsage(input, output, { reasoning, cache_read, cache_write });\n}\n\n/**\n * Drain stderr while keeping the last STDERR_TAIL_BYTES bytes for diagnostics.\n * Returns a closure that yields the captured tail as a UTF-8 string.\n *\n * Single backing Buffer with subarray-based truncation — no array shifts, no\n * repeated concats on overflow. Without draining a chatty stderr can fill the\n * pipe buffer and stall Pi; without the tail, auth or extension-load failures\n * vanish on non-zero exit.\n */\nconst STDERR_TAIL_BYTES = 4096;\nfunction createStderrTailCapture(stderr: Readable | null | undefined): () => string {\n if (!stderr) return () => '';\n let buf: Buffer = Buffer.alloc(0);\n stderr.on('data', (chunk: Buffer | string) => {\n const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8');\n buf = buf.length === 0 ? next : Buffer.concat([buf, next], buf.length + next.length);\n if (buf.length > STDERR_TAIL_BYTES) {\n // Buffer.from materializes a fresh, exactly-sized copy. Plain subarray\n // would keep a view into the larger backing ArrayBuffer (sized to the\n // last chunk), wasting memory on every oversized burst until GC.\n buf = Buffer.from(buf.subarray(buf.length - STDERR_TAIL_BYTES));\n }\n });\n stderr.on('error', () => {});\n return () => buf.toString('utf-8').trimEnd();\n}\n\n/**\n * Pi RPC can emit very large JSONL records (notably agent_end with the full\n * message transcript). Do not use the generic process `readLines` helper: it\n * caps lines at 16 KB, which corrupts large JSON records before the adapter\n * can parse the terminal event. Same algorithm otherwise — see readLines() in\n * src/infrastructure/process/process-manager.ts for the cap-applied variant.\n *\n * Concats once per chunk arrival and scans with an offset to avoid the\n * O(n²) \"concat([pending, buf]) per chunk\" anti-pattern.\n */\nasync function* readPiRpcLines(stream: Readable): AsyncGenerator<string> {\n const chunks: Buffer[] = [];\n let totalLen = 0;\n\n for await (const chunk of stream) {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string, 'utf-8');\n if (buf.length === 0) continue;\n chunks.push(buf);\n totalLen += buf.length;\n\n const buffer = chunks.length === 1 ? chunks[0]! : Buffer.concat(chunks, totalLen);\n chunks.length = 0;\n totalLen = 0;\n\n let offset = 0;\n let newlineIdx: number;\n while ((newlineIdx = buffer.indexOf(0x0a, offset)) !== -1) {\n if (newlineIdx > offset) {\n const line = buffer.toString('utf-8', offset, newlineIdx);\n yield line.endsWith('\\r') ? line.slice(0, -1) : line;\n }\n offset = newlineIdx + 1;\n }\n\n if (offset < buffer.length) {\n const remainder = buffer.subarray(offset);\n chunks.push(remainder);\n totalLen = remainder.length;\n }\n }\n\n if (totalLen > 0) {\n const final = chunks.length === 1 ? chunks[0]! : Buffer.concat(chunks, totalLen);\n const line = final.toString('utf-8');\n if (line) yield line.endsWith('\\r') ? line.slice(0, -1) : line;\n }\n}\n"]}
|
|
@@ -17,4 +17,4 @@ import {j,q,g,d,e,o,l,n,m}from'./chunk-64WUDYEM.js';function x(_,a){let c=_.comm
|
|
|
17
17
|
Review Results
|
|
18
18
|
${"\u2500".repeat(42)}`);for(let o of t.review_results){let n=o.passed?"\u2713":"\u2717";if(console.log(` ${n} ${o.criterion}: ${o.passed?"passed":"failed"}`),o.output)for(let l of o.output.split(`
|
|
19
19
|
`))console.log(` ${l}`);}}console.log();}),c.command("edit <id>").description("Open task in $EDITOR to modify title, priority and description").action(async e=>{let t=await a.taskService.get(e),{openInEditor:s,toEditorContent:o,fromEditorContent:n}=await import('./editor-7IFRWVTL.js'),l=t.attachments?.length?`
|
|
20
|
-
# Attachments: ${t.attachments.join(", ")}`:"",d=o({title:t.title,priority:t.priority,description:t.description})+l,i=await s(d),r=n(i),g={};if(r.title&&r.title!==t.title&&(g.title=r.title),r.priority&&r.priority!==t.priority&&(g.priority=r.priority),r.description!==void 0&&r.description!==t.description&&(g.description=r.description??""),Object.keys(g).length===0){console.log(" No changes.");return}let w=await a.taskService.update(e,g);j(`Updated ${w.id} "${w.title}"`);}),c.command("assign <task-id> <agent-id>").description("Assign task to agent").action(async(e,t)=>{let s=await a.taskService.assign(e,t);j(`Assigned ${s.id} \u2192 ${s.assignee??t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:s}=await import('./container-
|
|
20
|
+
# Attachments: ${t.attachments.join(", ")}`:"",d=o({title:t.title,priority:t.priority,description:t.description})+l,i=await s(d),r=n(i),g={};if(r.title&&r.title!==t.title&&(g.title=r.title),r.priority&&r.priority!==t.priority&&(g.priority=r.priority),r.description!==void 0&&r.description!==t.description&&(g.description=r.description??""),Object.keys(g).length===0){console.log(" No changes.");return}let w=await a.taskService.update(e,g);j(`Updated ${w.id} "${w.title}"`);}),c.command("assign <task-id> <agent-id>").description("Assign task to agent").action(async(e,t)=>{let s=await a.taskService.assign(e,t);j(`Assigned ${s.id} \u2192 ${s.assignee??t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:s}=await import('./container-KJNQCG2C.js');await(await s(a.context)).orchestrator.cancelTask(e);}else await a.taskService.cancel(e);j(`Cancelled ${e}`);}),c.command("approve <id>").description("Approve a task in review").action(async e=>{await a.taskService.updateStatus(e,"done"),j(`Approved ${e}`);}),c.command("reject <id>").description("Reject a task and send it back for rework").option("-r, --reason <reason>","Feedback for the agent explaining what to fix").action(async(e,t)=>{await a.taskService.reject(e,t.reason),j(`Rejected ${e} \u2192 todo${t.reason?` (reason: ${t.reason})`:""}`);}),c.command("retry <id>").description("Retry a failed task").action(async e=>{await a.taskService.retry(e),j(`Reset ${e} to todo`);});}export{x as registerTaskCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
function ct(d,e){d.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let S=await e.taskService.list(),w=await e.agentService.list(),h=await e.stateStore.read(),{render:k}=await import('ink'),{createElement:T}=await import('react'),{App:b}=await import('./App-
|
|
2
|
+
function ct(d,e){d.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let S=await e.taskService.list(),w=await e.agentService.list(),h=await e.stateStore.read(),{render:k}=await import('ink'),{createElement:T}=await import('react'),{App:b}=await import('./App-IC2HLH6T.js'),A=async t=>{await e.orchestrator.runTask(t);},R=async(t,s)=>e.taskService.create({title:t,priority:s?.priority,description:s?.description,attachments:s?.attachments}),C=async t=>{await e.orchestrator.cancelTask(t);},_=async t=>{await e.taskService.retry(t);},E=async(t,s)=>{await e.taskService.assign(t,s);},j=async()=>{await e.orchestrator.runAll();},D=async t=>{await e.agentService.disable(t);},U=async t=>{await e.agentService.enable(t);},m=t=>e.eventBus.onAny(t),P=async()=>e.taskService.list(),G=async()=>e.agentService.list(),x=async()=>e.stateStore.read(),I=async(t,s,a)=>e.agentService.create({name:t,adapter:s??e.config.defaults.agent.adapter,model:a?.model||void 0,effort:a?.effort||void 0,role:a?.role||void 0,approval_policy:a?.approval_policy||void 0,skills:a?.skills||void 0}),L=async t=>{await e.agentService.remove(t);},F=async t=>{await e.taskService.delete(t);},H=async t=>{await e.taskService.updateStatus(t,"done");},O=async(t,s)=>{await e.taskService.reject(t,s);},W=async(t,s)=>e.taskService.update(t,s),N=async(t,s)=>e.agentService.update(t,{...s,effort:s.effort,approval_policy:s.approval_policy}),B=async t=>{await e.orchestrator.forceStopAgent(t);},M=async(t,s)=>e.agentService.setAutonomous(t,s),V=async t=>{let s=await e.runService.listAll();s.sort((n,i)=>new Date(i.started_at).getTime()-new Date(n.started_at).getTime());let a=s.filter(n=>n.status==="succeeded"||n.status==="failed"),u=3,ot=10,y=a.slice(0,u),v=a.slice(u,ot),f=async n=>(await e.runService.readEventsTail(n.id,30)).map(r=>({timestamp:r.timestamp,agentId:n.agent_id,taskId:n.task_id,type:r.type,data:r.data}));if(y.length>0){let n=(await Promise.all(y.map(f))).flat();n.sort((i,r)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime()),t(n.slice(-200));}if(v.length>0){let n=(await Promise.all(v.map(f))).flat();n.sort((i,r)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime()),t(n.slice(-200));}},J=async t=>e.teamService.create(t),K=async()=>e.teamService.list(),q=async(t,s)=>e.teamService.join(t,s),z=async(t,s)=>e.teamService.leave(t,s),Q=async t=>{await e.teamService.disband(t);},X=async(t,s)=>e.teamService.setLead(t,s),Y=async()=>e.goalService.list(),Z=async t=>e.goalService.create(t),$=async(t,s)=>e.goalService.update(t,s),tt=async(t,s,a)=>e.goalService.updateStatus(t,s,a),et=async t=>{await e.goalService.delete(t);},st=async t=>e.goalService.getProgressReport(t),at=async()=>{await e.orchestrator.startWatch();},nt=async()=>{await e.orchestrator.stop();},c=d.version()??"0.0.0",rt=import('./update-check-R5ABF6HE.js').then(t=>t.checkForUpdateSWR(c)).catch(()=>null),l=false,p,g=false,o;try{await e.orchestrator.startWatch(),l=!0;}catch(t){p=t instanceof Error?t.message:String(t);let{DiskObserver:s}=await import('./disk-observer-B3NOZ2QA.js');o=new s({paths:e.paths,stateStore:e.stateStore}),g=true,m=a=>o.subscribe(a);}let{waitUntilExit:it}=k(T(b,{projectName:e.config.project.name,tasks:S,agents:w,state:h,onRunTask:A,onCreateTask:R,onCancelTask:C,onRetryTask:_,onAssignTask:E,onRunAll:j,onDisableAgent:D,onEnableAgent:U,onSubscribeEvents:m,onRefreshTasks:P,onRefreshAgents:G,onRefreshState:x,onLoadHistory:V,onAddAgent:I,onDeleteAgent:L,onApproveTask:H,onRejectTask:O,onDeleteTask:F,onUpdateTask:W,onUpdateAgent:N,onForceStopAgent:B,onToggleAutonomous:M,onRefreshGoals:Y,onCreateGoal:Z,onUpdateGoal:$,onUpdateGoalStatus:tt,onDeleteGoal:et,onGetGoalProgress:st,onCreateTeam:J,onListTeams:K,onJoinTeam:q,onLeaveTeam:z,onDisbandTeam:Q,onSetTeamLead:X,onStartWatch:at,onStopWatch:nt,initialWatchActive:l,observerMode:g,watchError:g?void 0:p,version:c,latestVersion:void 0,onCheckUpdate:async()=>{let t=await rt;if(t?.updateAvailable)return t.latest;let a=await(await import('./update-check-R5ABF6HE.js')).checkForUpdateNow(c);return a?.updateAvailable?a.latest:void 0},onBackgroundInstall:async t=>(await import('./update-check-R5ABF6HE.js')).backgroundInstall(t),initialActivityFilter:e.globalConfig.tui.activity_filter,onSaveActivityFilter:async t=>{await e.globalConfigStore.set("activity_filter",t);},initialNotifications:e.globalConfig.tui.notifications,onSaveNotifications:async t=>{await e.globalConfigStore.set("notifications",t);},initialMaxConcurrent:e.config.scheduling.max_concurrent_agents,onSaveMaxConcurrent:async t=>{await e.configStore.set("scheduling.max_concurrent_agents",t),e.config.scheduling.max_concurrent_agents=t;},onCompleteOnboarding:async()=>{let t=await e.stateStore.read();t.onboardingCompleted=true,await e.stateStore.write(t);},defaultAdapter:e.config.defaults.agent.adapter}),{incrementalRendering:true,kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await it(),l&&await e.orchestrator.stop().catch(()=>{}),o&&o.stop(),e.eventBus.clear();});}export{ct as registerTuiCommand};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oxgeneral/orch",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.25",
|
|
4
4
|
"description": "AI agent runtime — orchestrate Claude, Cursor, Codex & OpenCode as one team. Multi-agent task automation with state machine, auto-retry, inter-agent messaging, goals and teams. Zero-config CLI + programmatic API.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
package/dist/chunk-SSMOFT7C.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a}from'./chunk-P4JTJBWO.js';import {o}from'./chunk-LRYVT4D4.js';import {execFile}from'child_process';var _=class{constructor(e){this.processManager=e;}kind="pi";async test(){try{return {ok:!0,version:(await new Promise((t,r)=>{execFile("pi",["--version"],(s,o)=>{s?r(s):t(o);});})).trim()}}catch(e){let t=e instanceof Error?e.message:String(e);return {ok:false,error:"Pi CLI not found. Install: npm i -g @mariozechner/pi-coding-agent",errorKind:o(t)}}}execute(e){let t=["--mode","rpc"];e.config.model&&t.push("--model",e.config.model),e.config.effort&&t.push("--thinking",e.config.effort);let r=e.systemPrompt??e.config.system_prompt;r&&t.push("--append-system-prompt",r);let{process:s,pid:o}=this.processManager.spawn("pi",t,{cwd:e.workspace,env:{...process.env,...e.env},signal:e.signal,stdio:["pipe","pipe","pipe"]}),i=K(s.stderr);s.stdin&&s.stdin.write(JSON.stringify({id:`orch-${Date.now()}`,type:"prompt",message:e.prompt})+`
|
|
3
|
-
`);let u=S(s,o,this.processManager,i,e.signal);return {pid:o,events:u}}async stop(e){await this.processManager.killWithGrace(e);}};function S(n,e,t,r,s){async function*o$1(){let i=false,u=false,f="",p,d=null,m=null,v=new Promise(c=>{n.on("close",a=>{d=a,c();}),n.on("error",a=>{m=a,c();});}),y=null;try{if(n.stdout)try{for await(let c of U(n.stdout)){if(s?.aborted)break;let a=R(c,{finalText:f,lastTokens:p});if(a&&(a.finalText!==void 0&&(f=a.finalText),a.tokens&&(p=a.tokens),a.agentEvent&&(a.agentEvent.type==="done"&&(i=!0),yield a.agentEvent,a.agentEvent.type==="done"))){await t.killWithGrace(e,1e3).catch(()=>{});return}}}catch(c){y=c instanceof Error?c:new Error(String(c)),!s?.aborted&&!i&&(u=!0,yield {type:"error",timestamp:new Date().toISOString(),data:{message:y.message},errorKind:o(y.message)});}}finally{n.stdout?.destroy(),!i&&(s?.aborted||y)&&t.killWithGrace(e,1e3).catch(()=>{});}if(await v,u)return;let h=m;if(h&&!s?.aborted&&!i){let c=w(h.message,r()),a=o(c,d??void 0);throw Object.assign(new Error(c),{errorKind:a})}if(d!==0&&d!==null&&!s?.aborted&&!i){let c=`Pi process exited with code ${d}`,a=w(c,r()),P=o(a,d);throw Object.assign(new Error(a),{errorKind:P})}}return o$1()}function w(n,e){return e?`${n}
|
|
4
|
-
--- pi stderr (tail) ---
|
|
5
|
-
${e}`:n}function R(n,e){if(!n.trim())return null;let t;try{t=JSON.parse(n);}catch{return {agentEvent:{type:"output",timestamp:new Date().toISOString(),data:n}}}let r=new Date().toISOString();switch(typeof t.type=="string"?t.type:""){case "extension_ui_request":case "agent_start":case "turn_start":case "message_start":case "message_end":case "turn_end":case "queue_update":case "compaction_start":case "compaction_end":case "auto_retry_start":case "auto_retry_end":return B(t);case "response":{if(t.success===false){let o$1=typeof t.error=="string"?t.error:JSON.stringify(t);return {agentEvent:{type:"error",timestamp:r,data:t,errorKind:o(o$1)}}}return null}case "message_update":return b(t,r,e);case "tool_execution_start":return {agentEvent:{type:"tool_call",timestamp:r,data:{name:t.toolName,input:t.args,raw:t}}};case "tool_execution_update":return {agentEvent:{type:"output",timestamp:r,data:t}};case "tool_execution_end":return A(t,r);case "agent_end":{let o=I(t)??e.finalText,i=N(t)??e.lastTokens;return {finalText:o,tokens:i,agentEvent:{type:"done",timestamp:r,data:{result:o,raw:t},tokens:i}}}case "extension_error":{let o$1=typeof t.message=="string"?t.message:JSON.stringify(t);return {agentEvent:{type:"error",timestamp:r,data:t,errorKind:o(o$1)}}}default:return {agentEvent:{type:"output",timestamp:r,data:t}}}}function b(n,e,t){let r=n.assistantMessageEvent,s=typeof r?.type=="string"?r.type:"";if(s==="text_delta"){let o=typeof r?.delta=="string"?r.delta:"";return {finalText:t.finalText+o,agentEvent:{type:"output",timestamp:e,data:{text:o,raw:n}}}}if(s==="text_end")return {finalText:typeof r?.content=="string"?r.content:t.finalText};if(s==="error"){let o$1=typeof r?.reason=="string"?r.reason:JSON.stringify(n);return {agentEvent:{type:"error",timestamp:e,data:n,errorKind:o(o$1)}}}return null}function A(n,e){let t=typeof n.toolName=="string"?n.toolName:"",r=n.args;if(n.isError===true){let s=JSON.stringify(n.result??n);return {agentEvent:{type:"error",timestamp:e,data:n,errorKind:o(s)}}}if(t==="bash")return {agentEvent:{type:"command",timestamp:e,data:{command:r?.command,result:n.result,raw:n}}};if(/^(write|edit)$/i.test(t)){let s=O(r);if(s)return {agentEvent:{type:"file_change",timestamp:e,data:{paths:[s],raw:n}}}}return {agentEvent:{type:"output",timestamp:e,data:n}}}function B(n){let e=x(n);return e?{tokens:e}:null}function I(n){let e=n.messages;if(Array.isArray(e))for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.role!=="assistant")continue;let s=M(r.content);if(s)return s}}function M(n){if(typeof n=="string")return n;if(!Array.isArray(n))return;let e=n.map(t=>{let r=t;return typeof r.text=="string"?r.text:""}).filter(Boolean);return e.length?e.join(""):void 0}function O(n){if(n){if(typeof n.path=="string")return n.path;if(typeof n.file_path=="string")return n.file_path}}function N(n){let e=n.messages;if(Array.isArray(e))for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.role!=="assistant")continue;let s=x(r);if(s)return s}}var l={input:["input","input_tokens"],output:["output","output_tokens"],reasoning:["reasoning","reasoning_tokens"],cache_read:["cacheRead","cache_read","cache_read_input_tokens"],cache_write:["cacheWrite","cache_write","cache_creation_input_tokens"]};function x(n){let e=n.usage;if(!e)return;let t=f=>{for(let p of f){let d=e[p];if(typeof d=="number")return d}return 0},r=t(l.input),s=t(l.output),o=t(l.reasoning),i=t(l.cache_read),u=t(l.cache_write);if(!(r===0&&s===0&&o===0&&i===0&&u===0))return a(r,s,{reasoning:o,cache_read:i,cache_write:u})}var k=4096;function K(n){if(!n)return ()=>"";let e=Buffer.alloc(0);return n.on("data",t=>{let r=Buffer.isBuffer(t)?t:Buffer.from(t,"utf-8");e=e.length===0?r:Buffer.concat([e,r],e.length+r.length),e.length>k&&(e=Buffer.from(e.subarray(e.length-k)));}),n.on("error",()=>{}),()=>e.toString("utf-8").trimEnd()}async function*U(n){let e=[],t=0;for await(let r of n){let s=Buffer.isBuffer(r)?r:Buffer.from(r,"utf-8");if(s.length===0)continue;e.push(s),t+=s.length;let o=e.length===1?e[0]:Buffer.concat(e,t);e.length=0,t=0;let i=0,u;for(;(u=o.indexOf(10,i))!==-1;){if(u>i){let f=o.toString("utf-8",i,u);yield f.endsWith("\r")?f.slice(0,-1):f;}i=u+1;}if(i<o.length){let f=o.subarray(i);e.push(f),t=f.length;}}if(t>0){let s=(e.length===1?e[0]:Buffer.concat(e,t)).toString("utf-8");s&&(yield s.endsWith("\r")?s.slice(0,-1):s);}}export{_ as a};
|