@oxgeneral/orch 1.0.20 → 1.0.22

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.
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import {d as d$2,e as e$2,c as c$1}from'./chunk-LY3X2UHQ.js';import {e,c,b,d as d$1,g,f}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {a as a$1}from'./chunk-P4JTJBWO.js';import {d,m,h,e as e$1,o}from'./chunk-LRYVT4D4.js';import {dirname}from'path';import R from'fs/promises';import {execFile}from'child_process';function st(h,t){if(!h?.length||!t?.length)return false;for(let e of h)for(let s of t)if(ft(e,s))return true;return false}function q(h){let t=h.split("*")[0],e=!t.endsWith("/"),s=e?dirname(t):"";return {raw:h,base:t,isFile:e,dir:s}}var O=class{entries;constructor(t){this.entries=[];for(let e of t)if(e?.length)for(let s of e)this.entries.push(q(s));}overlapsAny(t){if(!t?.length||this.entries.length===0)return false;for(let e of t){let s=q(e);for(let i of this.entries)if(pt(s,i))return true}return false}add(t){if(t?.length)for(let e of t)this.entries.push(q(e));}get size(){return this.entries.length}};function pt(h,t){return h.raw===t.raw||h.base.startsWith(t.base)||t.base.startsWith(h.base)?true:h.isFile&&t.isFile?h.dir===t.dir&&h.dir!==".":false}function ft(h,t){if(h===t)return true;let e=h.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let i=dirname(e),r=dirname(s);return i===r&&i!=="."}return false}var it=Promise.resolve();async function G(h){let t,e=new Promise(i=>{t=i;}),s=it;it=e,await s;try{return await mt(h)}finally{t();}}var gt=6e4;async function mt(h){let t=await at(h);if(t!==null){if(St(t)&&!await vt(h))return {acquired:false,pid:t};await R.unlink(h).catch(()=>{});}try{let e=await R.open(h,"wx");return await e.writeFile(String(process.pid),"utf-8"),await e.close(),{acquired:!0,pid:process.pid}}catch(e){if(e.code==="EEXIST")return {acquired:false,pid:await at(h)??void 0};throw e}}async function I(h){await R.unlink(h).catch(()=>{});}async function rt(h){let t=Date.now()/1e3;await R.utimes(h,t,t).catch(()=>{});}async function at(h){try{let t=await R.readFile(h,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function vt(h){try{let t=await R.stat(h);return Date.now()-t.mtimeMs>gt}catch{return true}}function St(h){try{return process.kill(h,0),!0}catch(t){return t.code==="EPERM"}}var B=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?`${t.status??""}:${t.goalId??""}`:"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}},M=class{constructor(t){this.inner=t;}listCache=null;nameCache=new Map;async list(){if(this.listCache)return this.listCache;let t=await this.inner.list();return this.listCache=t,t}async get(t){return this.inner.get(t)}async getByName(t){if(this.nameCache.has(t))return this.nameCache.get(t)??null;let e=await this.inner.getByName(t);return this.nameCache.set(t,e),e}async save(t){await this.inner.save(t),this.listCache=null,this.nameCache.clear();}async delete(t){await this.inner.delete(t),this.listCache=null,this.nameCache.clear();}invalidate(){this.listCache=null,this.nameCache.clear();}},$=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?.status??"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}};var yt={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},nt=["typecheck","lint","test_pass"],E=class{cwd;timeoutMs;failFast;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4,this.failFast=t.fail_fast??true;}async runAll(t){let e=kt(t),s=[];for(let i of e){let r=await this.runCriterion(i);if(s.push(r),this.failFast&&!r.passed)break}return s}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let i=s.passed?"\u2713":"\u2717",r=s.output;return `${i} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
3
+ ${r}`}).join(`
4
+
5
+ `)}runCriterion(t){let{cmd:e,args:s}=yt[t];return new Promise(i=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,o,n)=>{let d=(o+`
6
+ `+n).trim();i({criterion:t,passed:!r,output:d.slice(0,2e3)});});})}};function kt(h){return [...h].sort((t,e)=>{let s=nt.indexOf(t),i=nt.indexOf(e);return (s===-1?1/0:s)-(i===-1?1/0:i)})}var _t=8192,Tt=4096,ot=class h$1{constructor(t){this.deps=t;this.cachedTaskStore=new B(t.taskStore),this.cachedAgentStore=new M(t.agentStore),this.cachedGoalStore=t.goalStore?new $(t.goalStore):null;}intervalId=null;shuttingDown=false;state=null;abortControllers=new Map;cachedTaskStore;cachedAgentStore;cachedGoalStore;saveStateTimer=null;saveStateDirty=false;lockAcquired=false;consecutiveTickFailures=0;maxConsecutiveTickFailures=5;maxRetryQueueSize=100;signalHandlers=[];immediateDispatchTimer=null;taskCreatedUnsub=null;tickInProgress=false;stoppedResolvers=[];activeCollectors=new Set;skipAutonomousSeeding=false;lastAutoSeedAt=new Map;static AUTO_SEED_COOLDOWN_MS=3e4;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(r=>{e=r;}),i=this.stateMutex;return this.stateMutex=s,i.then(async()=>{try{return await t()}finally{e();}})}async runTask(t){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchTask(t));return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchTask(t)));}async runAll(){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchAll());return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchAll()));}async freshDispatch(t){await this.withStateLock(async()=>{this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),await this.loadState(),await t(),await this.saveState();});}async withTemporaryLock(t){let e=await G(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true;try{await t();}finally{this.lockAcquired=false,await I(this.deps.lockPath);}}async startWatch(t){this.skipAutonomousSeeding=t?.skipAutonomousSeeding??false;let e=await G(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true,await this.loadState(),await this.cleanupStaleRunningEntries(),this.state.pid=process.pid,this.state.started_at=new Date().toISOString(),await this.saveState(),this.registerSignalHandlers(),this.taskCreatedUnsub=this.deps.eventBus.on("task:created",()=>{this.scheduleImmediateDispatch();}),await this.tick(),this.intervalId=setInterval(()=>this.tick().then(()=>{this.consecutiveTickFailures=0;},s=>{this.consecutiveTickFailures++;let i=s instanceof Error?s.message:String(s);this.deps.eventBus.emit({type:"orchestrator:error",error:i,context:"tick",fatal:this.consecutiveTickFailures>=this.maxConsecutiveTickFailures}),this.consecutiveTickFailures>=this.maxConsecutiveTickFailures&&(this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`${this.consecutiveTickFailures} consecutive tick failures`}),this.stop().catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:"stop after consecutive tick failures",fatal:false});}));}),this.deps.config.scheduling.poll_interval_ms);}waitForStop(){return this.shuttingDown?Promise.resolve():new Promise(t=>{this.stoppedResolvers.push(t);})}registerSignalHandlers(){let t=e=>{this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`Received ${e}`}),this.stop().catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`stop after ${e} signal`,fatal:false});});};for(let e of ["SIGINT","SIGTERM"]){let s=()=>t(e);this.signalHandlers.push([e,s]),process.on(e,s);}}removeSignalHandlers(){for(let[t,e]of this.signalHandlers)process.removeListener(t,e);this.signalHandlers=[];}async stop(){if(!this.shuttingDown){this.shuttingDown=true,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.taskCreatedUnsub&&(this.taskCreatedUnsub(),this.taskCreatedUnsub=null),this.immediateDispatchTimer&&(clearTimeout(this.immediateDispatchTimer),this.immediateDispatchTimer=null),await this.flushStateLazy(),await this.withStateLock(async()=>{if(this.state){for(let[t,e$1]of Object.entries(this.state.running)){this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(e$1.pid),await this.deps.runService.finish(e$1.run_id,"cancelled");let s=await this.deps.taskStore.get(t);s&&await this.deps.taskService.updateStatus(t,e(s)),await this.deps.agentService.setStatus(e$1.agent_id,"idle");}this.state.running={},this.state.claimed=new Set,this.state.pid=void 0,this.state.started_at=void 0,await this.saveState();}}),this.lockAcquired&&(await I(this.deps.lockPath),this.lockAcquired=false),this.removeSignalHandlers();for(let t of this.stoppedResolvers)t();this.stoppedResolvers=[];}}async cancelTask(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.cancelTask(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state,s=e.running[t];s&&(this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(s.pid,3e3).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask setStatus idle for agent ${s.agent_id}`,fatal:false});}),delete e.running[t],await this.saveState()),e.retry_queue=e.retry_queue.filter(i=>i.task_id!==t);try{await this.deps.taskService.cancel(t);}catch{try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{}}await this.saveState();});}async forceStopAgent(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.forceStopAgent(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state;for(let[s,i]of Object.entries(e.running))if(i.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(i.pid,3e3),await this.deps.runService.finish(i.run_id,"cancelled");try{await this.deps.taskService.updateStatus(s,"failed");}catch{}delete e.running[s];}await this.deps.agentService.setStatus(t,"idle"),await this.saveState();});}async tick(){if(!this.shuttingDown){this.tickInProgress=true;try{await this.withStateLock(async()=>{if(this.shuttingDown)return;this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),this.cachedGoalStore?.invalidate(),await this.loadState(),await this.reconcile(),this.skipAutonomousSeeding||await this.seedAutonomousTasks(),await this.dispatchAll();let t=await this.cachedTaskStore.list(),e=Object.keys(this.state.running).length,s=t.filter(i=>c(i.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});}),await rt(this.deps.lockPath);}finally{this.tickInProgress=false;}}}scheduleImmediateDispatch(t=0){this.shuttingDown||this.immediateDispatchTimer||(this.immediateDispatchTimer=setTimeout(()=>{if(this.immediateDispatchTimer=null,!this.shuttingDown){if(this.tickInProgress){t<10&&this.scheduleImmediateDispatch(t+1);return}this.immediateDispatch().catch(e=>{this.deps.eventBus.emit({type:"orchestrator:error",error:e instanceof Error?e.message:String(e),context:"immediate dispatch on task:created",fatal:false});});}},500));}async immediateDispatch(){this.shuttingDown||await this.freshDispatch(()=>this.shuttingDown?Promise.resolve():this.dispatchAll());}async reconcile(){let t=this.state,e=Date.now(),s=Object.entries(t.running),[i,r]=await Promise.all([Promise.all(s.map(([c])=>this.deps.taskStore.get(c))),Promise.all(s.map(([,c])=>this.deps.agentStore.get(c.agent_id)))]);for(let c=0;c<s.length;c++){let[l,f]=s[c],y=i[c];if(!y||b(y.status)){this.abortControllers.delete(l),delete t.running[l],await this.deps.agentService.setStatus(f.agent_id,"idle").catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`reconcile setStatus idle for stale agent ${f.agent_id} (task ${l})`,fatal:false});});continue}if(this.activeCollectors.has(l))continue;if(!this.deps.processManager.isAlive(f.pid)){try{await this._handleRunFailure(l,f,"Process crashed unexpectedly");}catch{delete t.running[l],await this.deps.agentService.setStatus(f.agent_id,"idle").catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`reconcile crash fallback setStatus idle for agent ${f.agent_id} (task ${l})`,fatal:false});});}continue}let v=new Date(f.last_event_at).getTime(),u=r[c]?.config.stall_timeout_ms??this.deps.config.defaults.agent.stall_timeout_ms;if(e-v>u){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:f.run_id}),this.abortControllers.get(l)?.abort(),await this.deps.processManager.killWithGrace(f.pid,5e3);try{await this._handleRunFailure(l,f,"Agent stalled (no events)");}catch{delete t.running[l],await this.deps.agentService.setStatus(f.agent_id,"idle").catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`reconcile stall fallback setStatus idle for agent ${f.agent_id} (task ${l})`,fatal:false});});}}}let o=new Set(Object.values(t.running).map(c=>c.agent_id)),[n,d]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),m=n.filter(c=>c.status==="running"&&!o.has(c.id));m.length>0&&await Promise.all(m.map(c=>this.deps.agentService.setStatus(c.id,"idle")));let p=d.filter(c=>c.status==="in_progress"&&!t.running[c.id]);p.length>0&&await Promise.all(p.map(async c=>{try{await this.deps.taskService.updateStatus(c.id,"failed");}catch{c.status="failed",c.updated_at=new Date().toISOString(),await this.deps.taskStore.save(c).catch(l=>{this.deps.eventBus.emit({type:"orchestrator:error",error:l instanceof Error?l.message:String(l),context:`force-write orphaned task ${c.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:c.id});}));let a=[];t.retry_queue=t.retry_queue.filter(c=>e>=new Date(c.due_at).getTime()?(a.push(c.task_id),false):true);for(let c$1 of a){let l=await this.deps.taskStore.get(c$1);!l||!c(l.status)||await this.dispatchTask(c$1,l);}await this.saveState();}async seedAutonomousTasks(){let e=(await this.cachedAgentStore.list()).filter(n=>n.autonomous&&n.status==="idle");if(e.length===0)return;let s=await this.cachedTaskStore.list(),i=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],r=false,o=new Set;for(let n of e){if(s.some(f=>f.assignee===n.id&&!b(f.status)))continue;let m=this.lastAutoSeedAt.get(n.id)??0;if(Date.now()-m<h$1.AUTO_SEED_COOLDOWN_MS)continue;let p=i.find(f=>f.assignee===n.id&&!o.has(f.id))??i.find(f=>!f.assignee&&!o.has(f.id));p&&o.add(p.id);let a$1=n.role??"general assistant",c=p?`[auto] ${n.name}: ${p.title.slice(0,60)}`:`[auto] ${n.name}: ${a$1.slice(0,60)}`,l=p?`## GOAL (highest priority)
7
+
8
+ ${p.description||p.title}
9
+
10
+ ---
11
+ Agent role: ${a$1}`:`Autonomous work cycle. Agent role: ${a$1}`;try{await this.deps.taskService.create({title:c,description:l,assignee:n.id,labels:[a],priority:3,goalId:p?.id}),this.lastAutoSeedAt.set(n.id,Date.now()),r=!0;}catch(f){this.deps.eventBus.emit({type:"orchestrator:error",error:f instanceof Error?f.message:String(f),context:`autonomous task for agent ${n.id}`,fatal:false});}}r&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e$1=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,i=e$1-s;if(i<=0)return;let r=await this.cachedTaskStore.list(),o=new Map(r.map(a=>[a.id,a])),n=r.filter(a=>c(a.status)&&!d$1(a,o)&&!t.running[a.id]&&!t.claimed.has(a.id)).sort((a,c)=>{let l=(a.priority??3)-(c.priority??3);if(l!==0)return l;let f=(a.goalId?0:1)-(c.goalId?0:1);if(f!==0)return f;let y=c.updated_at??"",v=a.updated_at??"";return y<v?-1:y>v?1:0}).slice(0,i),d=new Set,m$1=r.filter(a=>a.status==="in_progress"&&a.scope?.length),p=new O(m$1.map(a=>a.scope));for(let a of n)if(a.scope?.length)if(p.overlapsAny(a.scope)){let c=m$1.find(l=>st(a.scope,l.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:a.id,overlappingTaskId:c?.id??a.id,patterns:a.scope}),d.add(a.id);}else p.add(a.scope);for(let a of n)if(!d.has(a.id))try{await this.dispatchTask(a.id);}catch(c){if(c instanceof m)try{let l=await this.deps.taskStore.get(a.id);if(l&&!b(l.status)){let f={...l,attempts:(l.attempts??0)+1,updated_at:new Date().toISOString()},y=e(f),v={...f,status:y};if(await this.deps.taskStore.save(v),y==="failed"){let w=r.map(u=>u.id===v.id?v:u);this.cachedTaskStore.invalidate(),await this.cascadeFailDependents(v.id,w,`dependency ${v.id} failed: ${c.message}`);}else {let w=g(v.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);this.enqueueRetry(t,v.id,v.attempts,w,c.message),await this.saveState();}}}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`dispatch task ${a.id}`,fatal:false});}}enqueueRetry(t,e,s,i,r){t.retry_queue.some(o=>o.task_id===e)||(t.retry_queue.length>=this.maxRetryQueueSize&&t.retry_queue.shift(),t.retry_queue.push({task_id:e,attempt:s,due_at:new Date(Date.now()+i).toISOString(),error:r}));}async cascadeFailDependents(t,e,s){let i=new Map;for(let m of e)for(let p of m.depends_on){let a=i.get(p);a||(a=[],i.set(p,a)),a.push(m);}let r=[t],o=0,n=new Set,d=false;for(;o<r.length;){let m=r[o++];if(n.has(m))continue;n.add(m);let p=i.get(m);if(!p)continue;let a=[];for(let l of p)b(l.status)||n.has(l.id)||(a.push({task:l,previousStatus:l.status}),r.push(l.id));if(a.length===0)continue;let c=new Date().toISOString();await Promise.all(a.map(({task:l})=>this.deps.taskStore.save({...l,status:"failed",updated_at:c})));for(let{task:l,previousStatus:f}of a)this.deps.eventBus.emit({type:"task:status_changed",taskId:l.id,from:f,to:"failed"}),this.deps.eventBus.emit({type:"task:cascade_failed",taskId:l.id,failedDependencyId:t,reason:s});d=true;}d&&this.cachedTaskStore.invalidate();}async dispatchTask(t,e){let s=this.state;if(s.running[t]){let r=s.running[t];throw new h(t,r.run_id,r.agent_id)}let i=e??await this.deps.taskService.get(t);if(c(i.status)){s.claimed.add(t),await this.saveState();try{let r=await this.cachedAgentStore.list(),o=await this.deps.agentService.findBestAgent(i);if(!o){if(r.length===0)throw new e$1;this.unclaim(t),await this.saveState();return}let{path:n,branch:d}=await this.deps.workspaceManager.prepare(i,o,this.deps.config),m=this.deps.config.prompt?.system_template??d$2,p=this.deps.config.prompt?.user_template??e$2,a=this.deps.config.prompt?.template,c=i.attempts+1,l;if(c>1){let S=await this.deps.runService.getLastFailedRunContext(i.id);S&&(l={previous_error:S.error,previous_output:S.output});}let f=i.goalId,[y,v,w]=await Promise.all([this.deps.contextStore?.getAll(),this.deps.messageService?this.deps.messageService.drainMailbox(o.id,i.id):[],f&&this.cachedGoalStore?this.cachedGoalStore.get(f).catch(()=>null):null]),u;if(w){let dt=(await this.cachedTaskStore.list()).filter(x=>x.goalId===f),ut=await this.deps.contextStore?.get(`${f}-progress`),ht=dt.map(x=>`[${x.status}] ${x.title}`);u={id:w.id,title:w.title,description:w.description,status:w.status,task_names:ht,progress:ut?.value};}let g=c$1(i,o,c,n,this.deps.config,{allAgents:r,retryContext:l,sharedContext:y,feedback:i.feedback,messages:v.length?v:void 0,goal:u}),k,_;if(a?k=await this.deps.templateEngine.render(a,g):(_=await this.deps.templateEngine.render(m,g),k=await this.deps.templateEngine.render(p,g)),this.deps.skillLoader&&o.config.skills?.length){let S=await this.deps.skillLoader.loadSkills(o.config.skills);S&&(_!==void 0?_=_+`
12
+
13
+ `+S:k=k+`
14
+
15
+ `+S);}let P=await this.deps.runService.create({taskId:i.id,agentId:o.id,attempt:c,prompt:k,workspacePath:n});if((i.status==="failed"||i.status==="cancelled")&&(await this.deps.taskService.retry(t),i.status="todo",i.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,o.id),await this.deps.taskService.incrementAttempts(t),d){let S=await this.deps.taskStore.get(t);S&&(S.proof={...S.proof??{files_changed:[]},branch:d},S.workspace=n,await this.deps.taskStore.save(S));}await this.deps.agentService.setStatus(o.id,"running");let T=await this.deps.agentService.get(o.id);T.current_task=t,T.last_error=void 0,await this.deps.agentStore.save(T);let lt=this.deps.adapterRegistry.require(o.adapter),N=new AbortController;this.abortControllers.set(t,N);let U=lt.execute({prompt:k,systemPrompt:_,workspace:n,env:{...o.config.env,ORCH_AGENT_ID:o.id,ORCH_AGENT_NAME:o.name,ORCH_TASK_ID:i.id},config:T.config,signal:N.signal}),W=U.pid,K=new Date().toISOString();await this.deps.runService.start(P.id,W),this.unclaim(t),s.running[t]={run_id:P.id,agent_id:o.id,task_id:t,pid:W,started_at:K,last_event_at:K},await this.saveState(),this.activeCollectors.add(t),this.collectEvents(U.events,P.id,t,o.id).catch(S=>{this.deps.eventBus.emit({type:"orchestrator:error",error:S instanceof Error?S.message:String(S),context:`adapter execution for ${t}`,fatal:!1});}).finally(()=>{this.activeCollectors.delete(t);});}catch(r){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),r}}}async collectEvents(t,e,s,i){let r,o,n,d,m=new Set;try{for await(let a of t){if(this.shuttingDown)break;if(a.type==="done"){if(a.tokens){let{input:g,output:k,reasoning:_,cache_read:P,cache_write:T}=a.tokens;r=a$1(g,k,{reasoning:_,cache_read:P,cache_write:T});}let u=a.data;u&&typeof u.result=="string"&&(o=u.result);}if(a.type==="output"){let u=a.data;if(u){let g=typeof u.text=="string"?u.text:typeof u.message=="string"?u.message:void 0;g?.trim()&&(n=g);}}if(a.type==="file_change"){let u=a.data;if(u&&Array.isArray(u.paths))for(let g of u.paths)typeof g=="string"&&m.add(g);else {let g=u&&typeof u.path=="string"?u.path:typeof a.data=="string"?a.data:String(a.data);m.add(g);}}let c=null;if(a.type==="tool_call"){let u=a.data;if(u){let g=u.input,k=typeof u.name=="string"?u.name:"";g&&typeof g.file_path=="string"&&/^(Write|Edit|MultiEdit|NotebookEdit)$/i.test(k)&&(c=g.file_path,m.add(c));}}let l=At(a.timestamp)?a.timestamp:new Date().toISOString(),f=a.type==="file_change"?(()=>{let u=a.data;return u&&typeof u.path=="string"?u.path:typeof a.data=="string"?a.data:String(a.data)})():null,y=ct(a.data,_t);a.data=void 0;let v={timestamp:l,type:a.type==="output"?"agent_output":a.type==="file_change"?"file_changed":a.type==="command"?"command_run":a.type==="tool_call"?"tool_call":a.type==="error"?"error":"done",data:y};await this.deps.runService.appendEvent(e,v),this.state?.running[s]&&(this.state.running[s].last_event_at=l,this.saveStateLazy());let w=ct(y,Tt);a.type==="output"||a.type==="tool_call"?(this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:i,data:w}),c&&this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:c})):a.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:f}):a.type==="error"&&(a.errorKind&&(d=a.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:i,error:w,...a.errorKind?{errorKind:a.errorKind}:{}}));}let p=o??n;await this.handleRunSuccess(s,e,i,r,p,[...m]);}catch(p){let a=p instanceof Error?p.message:String(p),c=d??(p instanceof Error?p.errorKind:void 0),l=this.state?.running[s];l?await this.handleRunFailure(s,l,a,c):await this.deps.runService.finish(e,"failed",void 0,a).catch(()=>{});}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,i,r,o){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,i,r,o))}async _handleRunSuccess(t,e,s,i,r,o){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let d=await this.deps.taskStore.get(t);if(!d)return;let m=o;(!m||m.length===0)&&d.proof?.branch&&(m=await this.deps.workspaceManager.getChangedFiles(d.proof.branch)),d.proof={...d.proof,agent_summary:r?.slice(0,2e3)??d.proof?.agent_summary,files_changed:m?.length?m:d.proof?.files_changed??[]},delete d.feedback,await this.deps.taskStore.save(d);let p=await this.deps.agentStore.get(s),c=d.labels?.includes(a)||p?.config.approval_policy==="auto",l=f(d,true,c);await this.deps.runService.finish(e,"succeeded",i);let f$1=n.running[t],y=f$1?Date.now()-new Date(f$1.started_at).getTime():0;f$1&&(n.stats.total_runtime_ms+=y),delete n.running[t];let v={tasks_completed:(p?.stats.tasks_completed??0)+1,total_runs:(p?.stats.total_runs??0)+1,total_runtime_ms:(p?.stats.total_runtime_ms??0)+y};if(i&&(v.tokens_used=(p?.stats.tokens_used??0)+i.total),await this.deps.agentService.updateStats(s,v).catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),context:`agent stats update for ${s}`,fatal:false});}),n.stats.total_tasks_completed++,n.stats.total_runs++,i&&(n.stats.total_tokens.input+=i.input,n.stats.total_tokens.output+=i.output,n.stats.total_tokens.reasoning+=i.reasoning,n.stats.total_tokens.cache_read+=i.cache_read,n.stats.total_tokens.cache_write+=i.cache_write,n.stats.total_tokens.total=n.stats.total_tokens.input+n.stats.total_tokens.output+n.stats.total_tokens.reasoning),d.proof?.branch)try{let u=await this.deps.workspaceManager.mergeBack(d.proof.branch);if(u.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:d.proof.branch}),await this.deps.workspaceManager.cleanup(t,d.proof.branch).catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:d.proof.branch,conflictInfo:u.conflictInfo}),await this.forceTaskToReview(d,s,`MERGE CONFLICT: ${u.conflictInfo}`);return}}catch(u){let g=u instanceof Error?u.message:String(u);await this.forceTaskToReview(d,s,`MERGE ERROR: ${g}`);return}try{await this.deps.taskService.updateStatus(t,l);}catch(u){let g=u instanceof Error?u.message:String(u);this.deps.eventBus.emit({type:"orchestrator:error",error:g,context:`state machine validation failed for task ${t} -> ${l}, force-writing`,fatal:false}),d.status=l,d.updated_at=new Date().toISOString(),await this.deps.taskStore.save(d).catch(k=>{this.deps.eventBus.emit({type:"orchestrator:error",error:k instanceof Error?k.message:String(k),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let w=await this.deps.agentStore.get(s);w&&(w.current_task=void 0,await this.deps.agentStore.save(w)),l==="review"&&d.review_criteria?.length?await this.runAutoReview(t,d.review_criteria,d.workspace??this.deps.projectRoot,c):l==="review"&&c&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s,i){return this.withStateLock(()=>this._handleRunFailure(t,e,s,i))}async _handleRunFailure(t,e$1,s,i){await this.flushStateLazy(),this.abortControllers.delete(t);let r=this.state;if(!r.running[t])return;let o$1=await this.deps.taskStore.get(t);if(!o$1)return;await this.deps.runService.finish(e$1.run_id,"failed",void 0,s),await this.deps.agentService.setStatus(e$1.agent_id,"idle");let n=await this.deps.agentStore.get(e$1.agent_id);n&&(n.current_task=void 0,n.last_error={message:s.slice(0,500),kind:i??o(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n));let d=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(n?.stats.tasks_failed??0)+1,total_runs:(n?.stats.total_runs??0)+1,total_runtime_ms:(n?.stats.total_runtime_ms??0)+d});let m=e(o$1);if(await this.deps.taskService.updateStatus(t,m),m==="retrying"){let p=g(o$1.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);this.enqueueRetry(r,t,o$1.attempts+1,p,s),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:o$1.attempts+1,delay_ms:p});}else {r.stats.total_tasks_failed++,this.cachedTaskStore.invalidate();let p=await this.cachedTaskStore.list();await this.cascadeFailDependents(t,p,`dependency ${t} failed: ${s}`);}r.stats.total_runtime_ms+=d,o$1.proof?.branch&&await this.deps.workspaceManager.cleanup(t,o$1.proof.branch).catch(p=>{this.deps.eventBus.emit({type:"orchestrator:error",error:p instanceof Error?p.message:String(p),context:`workspace cleanup for ${t}`,fatal:false});}),delete r.running[t],r.stats.total_runs++,await this.saveState(),this.scheduleImmediateDispatch();}async runAutoReview(t,e,s,i=false){let o=await new E({cwd:s}).runAll(e),n=E.allPassed(o),d=await this.deps.taskStore.get(t);if(d&&(d.review_results=o,d.proof={...d.proof,test_results:E.formatReport(o),files_changed:d.proof?.files_changed??[]},await this.deps.taskStore.save(d),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:o}),n||i)){n||this.deps.eventBus.emit({type:"orchestrator:error",error:`Review criteria failed for task ${t} but autoApprove is set \u2014 force-approving`,context:"auto-review-with-auto-approve",fatal:false});try{await this.deps.taskService.updateStatus(t,"done");}catch(m){let p=m instanceof Error?m.message:String(m);this.deps.eventBus.emit({type:"orchestrator:error",error:p,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),d.status="done",d.updated_at=new Date().toISOString(),await this.deps.taskStore.save(d).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`force-write task ${t} to store failed (auto-review)`,fatal:false});});}}}async forceTaskToReview(t,e,s){t.proof={...t.proof,agent_summary:`${s}
16
+
17
+ ${t.proof?.agent_summary??""}`.slice(0,2e3),files_changed:t.proof?.files_changed??[]},t.status="review",t.updated_at=new Date().toISOString(),await this.deps.taskStore.save(t),await this.deps.agentService.setStatus(e,"idle").catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:`forceTaskToReview setStatus idle for agent ${e}`,fatal:false});});let i=await this.deps.agentStore.get(e);i&&(i.current_task=void 0,await this.deps.agentStore.save(i)),await this.saveState();}unclaim(t){this.state.claimed.delete(t);}requireOwnership(){if(!this.lockAcquired)throw new d(0)}async loadState(){this.state=await this.deps.stateStore.read();}async cleanupStaleRunningEntries(){let t=this.state,e=Object.entries(t.running).filter(([,i])=>!this.deps.processManager.isAlive(i.pid)),s=new Set;if(e.length>0){for(let[i]of e)delete t.running[i],s.add(i);await Promise.all(e.map(async([i,r])=>{await this.deps.agentService.setStatus(r.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: setStatus idle for agent ${r.agent_id}`,fatal:false});}),await this.forceTaskCancelled(i),await this.deps.runService.finish(r.run_id,"cancelled",void 0,"Orchestrator restarted").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: finish run ${r.run_id}`,fatal:false});});}));}if(t.claimed=new Set,s.size>0){let r=(await this.cachedTaskStore.list()).filter(n=>n.status==="in_progress"&&!t.running[n.id]);r.length>0&&await Promise.all(r.map(n=>this.forceTaskCancelled(n.id)));let o=new Set([...s,...r.map(n=>n.id)]);t.retry_queue=t.retry_queue.filter(n=>!o.has(n.task_id)),await this.saveState();}await this.cleanupOrphanedPreparingRuns();}async cleanupOrphanedPreparingRuns(){try{let e=(await this.deps.runStore.listAll()).filter(r=>r.status==="preparing");if(e.length===0)return;let s=new Set(Object.values(this.state.running).map(r=>r.run_id)),i=e.filter(r=>!s.has(r.id));if(i.length===0)return;await Promise.all(i.map(r=>this.deps.runService.finish(r.id,"cancelled",void 0,"Orphaned preparing run (orchestrator restarted)").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: finish orphaned preparing run ${r.id}`,fatal:!1});})));}catch(t){this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"startup cleanup: cleanupOrphanedPreparingRuns",fatal:false});}}async forceTaskCancelled(t){try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{let e=await this.deps.taskStore.get(t);e&&!b(e.status)&&(e.status="cancelled",e.updated_at=new Date().toISOString(),await this.deps.taskStore.save(e).catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`startup cleanup: force-cancel task ${t}`,fatal:false});}));}}async saveState(){this.state&&await this.deps.stateStore.write(this.state);}saveStateLazy(){this.saveStateDirty=true,!this.saveStateTimer&&(this.saveStateTimer=setTimeout(()=>{this.saveStateTimer=null,this.saveStateDirty&&(this.saveStateDirty=false,this.saveState().catch(t=>{this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"debounced state save",fatal:false});}));},500));}async flushStateLazy(){this.saveStateTimer&&(clearTimeout(this.saveStateTimer),this.saveStateTimer=null),this.saveStateDirty&&(this.saveStateDirty=false,await this.saveState());}};function At(h){if(typeof h!="string")return false;let t=new Date(h);return !isNaN(t.getTime())&&t.toISOString()===h}function ct(h,t){let e=typeof h=="string"?h:JSON.stringify(h);return e.length>t?e.slice(0,t)+"\u2026":e}export{ot as Orchestrator};
@@ -0,0 +1,6 @@
1
+ export { Orchestrator } from './chunk-FGQJYB6G.js';
2
+ import './chunk-XUZZJCKG.js';
3
+ import './chunk-RHFRHCN5.js';
4
+ import './chunk-IESAV453.js';
5
+ //# sourceMappingURL=orchestrator-KV3VVGZR.js.map
6
+ //# sourceMappingURL=orchestrator-KV3VVGZR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-53KIAROT.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-KV3VVGZR.js"}
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import {j,q,g,d,e,o,l,n,m}from'./chunk-64WUDYEM.js';function x(_,a){let c=_.command("task").description("Manage tasks");c.command("add <title>").description("Create a new task").option("-d, --description <desc>","Task description").option("-p, --priority <n>","Priority (1-4)","3").option("-l, --labels <labels>","Comma-separated labels").option("--depends-on <ids>","Comma-separated dependency task IDs").option("--max-attempts <n>","Max retry attempts").option("--workspace-mode <mode>","Workspace mode: shared|worktree|isolated").option("--assignee <agent-id>","Assign to agent").option("--review-criteria <criteria>","Comma-separated auto-review criteria: test_pass,typecheck,lint").option("--scope <patterns>","Comma-separated glob patterns for file scope (e.g. src/auth/**,src/session/**)").option("--goal-id <goalId>","Associate task with a goal").option("--attach <paths>","Comma-separated file paths to attach (screenshots, docs)").option("-e, --edit","Open $EDITOR to write the description").action(async(e,t)=>{let i=t.description;if(t.edit){let{openInEditor:n,toEditorContent:l,fromEditorContent:d}=await import('./editor-7IFRWVTL.js'),s=await n(l({title:e,priority:parseInt(t.priority,10),description:i}));i=d(s).description;}let o=await a.taskService.create({title:e,description:i,priority:parseInt(t.priority,10),labels:t.labels?.split(",").map(n=>n.trim()),depends_on:t.dependsOn?.split(",").map(n=>n.trim()),max_attempts:t.maxAttempts?parseInt(t.maxAttempts,10):void 0,workspace_mode:t.workspaceMode,assignee:t.assignee,review_criteria:t.reviewCriteria?.split(",").map(n=>n.trim()),scope:t.scope?.split(",").map(n=>n.trim()),goalId:t.goalId,attachments:t.attach?.split(",").map(n=>n.trim())});a.context.json?console.log(JSON.stringify(o,null,2)):a.context.quiet?console.log(o.id):j(`Created ${o.id} "${o.title}"`);}),c.command("list").description("List all tasks").option("--status <status>","Filter by status").action(async e$1=>{let t=await a.taskService.list(e$1.status?{status:e$1.status}:void 0);if(a.context.json){console.log(JSON.stringify(t,null,2));return}if(a.context.quiet){t.forEach(s=>console.log(s.id));return}if(t.length===0){console.log(`
2
+ import {j,q,g,d,e,o,l,n,m}from'./chunk-64WUDYEM.js';function x(_,a){let c=_.command("task").description("Manage tasks");c.command("add <title>").description("Create a new task").option("-d, --description <desc>","Task description").option("-p, --priority <n>","Priority (1-4)","3").option("-l, --labels <labels>","Comma-separated labels").option("--depends-on <ids>","Comma-separated dependency task IDs").option("--max-attempts <n>","Max retry attempts").option("--workspace-mode <mode>","Workspace mode: shared|worktree|isolated").option("--assignee <agent-id>","Assign to agent").option("--review-criteria <criteria>","Comma-separated auto-review criteria: test_pass,typecheck,lint").option("--scope <patterns>","Comma-separated glob patterns for file scope (e.g. src/auth/**,src/session/**)").option("--goal-id <goalId>","Associate task with a goal").option("--attach <paths>","Comma-separated file paths to attach (screenshots, docs)").option("-e, --edit","Open $EDITOR to write the description").action(async(e,t)=>{let s=t.description;if(t.edit){let{openInEditor:n,toEditorContent:l,fromEditorContent:d}=await import('./editor-7IFRWVTL.js'),i=await n(l({title:e,priority:parseInt(t.priority,10),description:s}));s=d(i).description;}let o=await a.taskService.create({title:e,description:s,priority:parseInt(t.priority,10),labels:t.labels?.split(",").map(n=>n.trim()),depends_on:t.dependsOn?.split(",").map(n=>n.trim()),max_attempts:t.maxAttempts?parseInt(t.maxAttempts,10):void 0,workspace_mode:t.workspaceMode,assignee:t.assignee,review_criteria:t.reviewCriteria?.split(",").map(n=>n.trim()),scope:t.scope?.split(",").map(n=>n.trim()),goalId:t.goalId,attachments:t.attach?.split(",").map(n=>n.trim())});a.context.json?console.log(JSON.stringify(o,null,2)):a.context.quiet?console.log(o.id):j(`Created ${o.id} "${o.title}"`);}),c.command("list").description("List all tasks").option("--status <status>","Filter by status").action(async e$1=>{let t=await a.taskService.list(e$1.status?{status:e$1.status}:void 0);if(a.context.json){console.log(JSON.stringify(t,null,2));return}if(a.context.quiet){t.forEach(i=>console.log(i.id));return}if(t.length===0){console.log(`
3
3
  No tasks. Create one: ${q('orch task add "Title"')}
4
- `);return}let i=["STATUS","PRI","TASK","AGENT","TIME"],o$1=t.map(s=>{let r=(s.status==="in_progress"||s.status==="done")&&s.updated_at?g(s.updated_at):q("\u2014");return [`${d(s.status)} ${s.status}`,e(s.priority),s.title.slice(0,35),s.assignee?o(s.assignee):q("\u2014"),r]});console.log(),l(i,o$1);let n=t.filter(s=>s.status==="in_progress").length,l$1=t.filter(s=>s.status==="review").length,d$1=t.filter(s=>s.status==="done").length;console.log(`
4
+ `);return}let s=["STATUS","PRI","TASK","AGENT","TIME"],o$1=t.map(i=>{let r=(i.status==="in_progress"||i.status==="done")&&i.updated_at?g(i.updated_at):q("\u2014");return [`${d(i.status)} ${i.status}`,e(i.priority),i.title.slice(0,35),i.assignee?o(i.assignee):q("\u2014"),r]});console.log(),l(s,o$1);let n=t.filter(i=>i.status==="in_progress").length,l$1=t.filter(i=>i.status==="review").length,d$1=t.filter(i=>i.status==="done").length;console.log(`
5
5
  ${t.length} tasks${n?` \xB7 ${n} running`:""}${l$1?` \xB7 ${l$1} review`:""}${d$1?` \xB7 ${d$1} done`:""}
6
6
  `);}),c.command("show <id>").description("Show task details").action(async e$1=>{let t=await a.taskService.get(e$1);if(a.context.json){console.log(JSON.stringify(t,null,2));return}console.log(`
7
- ${t.title}`),console.log(` ${"\u2550".repeat(42)}`),console.log();let i=[["Status",`${d(t.status)} ${t.status} \xB7 attempt ${t.attempts}/${t.max_attempts}`],["Priority",e(t.priority)]];if(t.assignee&&i.push(["Agent",o(t.assignee)]),t.labels.length&&i.push(["Labels",t.labels.join(", ")]),t.scope?.length&&i.push(["Scope",t.scope.join(", ")]),t.workspace_mode&&i.push(["Workspace",t.workspace_mode]),t.workspace&&i.push(["Path",n(t.workspace)]),t.review_criteria?.length&&i.push(["Review",t.review_criteria.join(", ")]),t.feedback&&i.push(["Feedback",t.feedback]),i.push(["Created",t.created_at]),m(i),t.attachments?.length){console.log(`
7
+ ${t.title}`),console.log(` ${"\u2550".repeat(42)}`),console.log();let s=[["Status",`${d(t.status)} ${t.status} \xB7 attempt ${t.attempts}/${t.max_attempts}`],["Priority",e(t.priority)]];if(t.assignee&&s.push(["Agent",o(t.assignee)]),t.labels.length&&s.push(["Labels",t.labels.join(", ")]),t.scope?.length&&s.push(["Scope",t.scope.join(", ")]),t.workspace_mode&&s.push(["Workspace",t.workspace_mode]),t.workspace&&s.push(["Path",n(t.workspace)]),t.review_criteria?.length&&s.push(["Review",t.review_criteria.join(", ")]),t.feedback&&s.push(["Feedback",t.feedback]),s.push(["Created",t.created_at]),m(s),t.attachments?.length){console.log(`
8
8
  Attachments (${t.attachments.length})
9
9
  ${"\u2500".repeat(42)}`);for(let o of t.attachments)console.log(` ${n(o)}`);}if(t.description){console.log(`
10
10
  Description
@@ -16,5 +16,5 @@ import {j,q,g,d,e,o,l,n,m}from'./chunk-64WUDYEM.js';function x(_,a){let c=_.comm
16
16
  `))console.log(` ${o}`);}}if(t.review_results?.length){console.log(`
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
- `))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:i,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,s=await i(d),r=n(s),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 i=await a.taskService.assign(e,t);j(`Assigned ${i.id} \u2192 ${t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:i}=await import('./container-LVIBTBG4.js');await(await i(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};
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-PKAEIRCI.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-63TC4QG3.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};
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-23IBDXAF.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.20",
3
+ "version": "1.0.22",
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": {