@oxgeneral/orch 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import {d as d$2,e as e$2,c as c$1}from'./chunk-4MMHVHA6.js';import {e,c,b as b$1,d as d$1,f,g}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {a as a$1}from'./chunk-P4JTJBWO.js';import {d,l,h,e as e$1,n}from'./chunk-IKNBPOQL.js';import {dirname}from'path';import T from'fs/promises';import {execFile}from'child_process';function et(d,t){if(!d?.length||!t?.length)return false;for(let e of d)for(let s of t)if(ht(e,s))return true;return false}function O(d){let t=d.split("*")[0],e=!t.endsWith("/"),s=e?dirname(t):"";return {raw:d,base:t,isFile:e,dir:s}}var b=class{entries;constructor(t){this.entries=[];for(let e of t)if(e?.length)for(let s of e)this.entries.push(O(s));}overlapsAny(t){if(!t?.length||this.entries.length===0)return false;for(let e of t){let s=O(e);for(let a of this.entries)if(ut(s,a))return true}return false}add(t){if(t?.length)for(let e of t)this.entries.push(O(e));}get size(){return this.entries.length}};function ut(d,t){return d.raw===t.raw||d.base.startsWith(t.base)||t.base.startsWith(d.base)?true:d.isFile&&t.isFile?d.dir===t.dir&&d.dir!==".":false}function ht(d,t){if(d===t)return true;let e=d.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let a=dirname(e),r=dirname(s);return a===r&&a!=="."}return false}var st=Promise.resolve();async function q(d){let t,e=new Promise(a=>{t=a;}),s=st;st=e,await s;try{return await ft(d)}finally{t();}}var pt=6e4;async function ft(d){let t=await it(d);if(t!==null){if(mt(t)&&!await gt(d))return {acquired:false,pid:t};await T.unlink(d).catch(()=>{});}try{let e=await T.open(d,"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 it(d)??void 0};throw e}}async function G(d){await T.unlink(d).catch(()=>{});}async function at(d){let t=Date.now()/1e3;await T.utimes(d,t,t).catch(()=>{});}async function it(d){try{let t=await T.readFile(d,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function gt(d){try{let t=await T.stat(d);return Date.now()-t.mtimeMs>pt}catch{return true}}function mt(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}var D=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();}},C=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();}},B=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 St={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},A=class{cwd;timeoutMs;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4;}async runAll(t){let e=[];for(let s of t){let a=await this.runCriterion(s);e.push(a);}return e}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let a=s.passed?"\u2713":"\u2717",r=s.output.slice(0,500);return `${a} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
2
+ import {d as d$2,e as e$2,c as c$1}from'./chunk-4MMHVHA6.js';import {e,c,b as b$1,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,l,h,e as e$1,n}from'./chunk-IKNBPOQL.js';import {dirname}from'path';import A from'fs/promises';import {execFile}from'child_process';function et(u,t){if(!u?.length||!t?.length)return false;for(let e of u)for(let s of t)if(ht(e,s))return true;return false}function j(u){let t=u.split("*")[0],e=!t.endsWith("/"),s=e?dirname(t):"";return {raw:u,base:t,isFile:e,dir:s}}var b=class{entries;constructor(t){this.entries=[];for(let e of t)if(e?.length)for(let s of e)this.entries.push(j(s));}overlapsAny(t){if(!t?.length||this.entries.length===0)return false;for(let e of t){let s=j(e);for(let a of this.entries)if(ut(s,a))return true}return false}add(t){if(t?.length)for(let e of t)this.entries.push(j(e));}get size(){return this.entries.length}};function ut(u,t){return u.raw===t.raw||u.base.startsWith(t.base)||t.base.startsWith(u.base)?true:u.isFile&&t.isFile?u.dir===t.dir&&u.dir!==".":false}function ht(u,t){if(u===t)return true;let e=u.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let a=dirname(e),r=dirname(s);return a===r&&a!=="."}return false}var st=Promise.resolve();async function G(u){let t,e=new Promise(a=>{t=a;}),s=st;st=e,await s;try{return await ft(u)}finally{t();}}var pt=6e4;async function ft(u){let t=await it(u);if(t!==null){if(mt(t)&&!await gt(u))return {acquired:false,pid:t};await A.unlink(u).catch(()=>{});}try{let e=await A.open(u,"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 it(u)??void 0};throw e}}async function F(u){await A.unlink(u).catch(()=>{});}async function at(u){let t=Date.now()/1e3;await A.utimes(u,t,t).catch(()=>{});}async function it(u){try{let t=await A.readFile(u,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function gt(u){try{let t=await A.stat(u);return Date.now()-t.mtimeMs>pt}catch{return true}}function mt(u){try{return process.kill(u,0),!0}catch(t){return t.code==="EPERM"}}var C=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();}},B=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();}},M=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 St={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},R=class{cwd;timeoutMs;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4;}async runAll(t){let e=[];for(let s of t){let a=await this.runCriterion(s);e.push(a);}return e}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let a=s.passed?"\u2713":"\u2717",r=s.output.slice(0,500);return `${a} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
3
3
  ${r}`}).join(`
4
4
 
5
- `)}runCriterion(t){let{cmd:e,args:s}=St[t];return new Promise(a=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,u,n)=>{let l=(u+`
6
- `+n).trim();a({criterion:t,passed:!r,output:l.slice(0,2e3)});});})}};var wt=8192,yt=4096,rt=class{constructor(t){this.deps=t;this.cachedTaskStore=new D(t.taskStore),this.cachedAgentStore=new C(t.agentStore),this.cachedGoalStore=t.goalStore?new B(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=[];skipAutonomousSeeding=false;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(r=>{e=r;}),a=this.stateMutex;return this.stateMutex=s,a.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 q(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true;try{await t();}finally{this.lockAcquired=false,await G(this.deps.lockPath);}}async startWatch(t){this.skipAutonomousSeeding=t?.skipAutonomousSeeding??false;let e=await q(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 a=s instanceof Error?s.message:String(s);this.deps.eventBus.emit({type:"orchestrator:error",error:a,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 G(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(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),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(a=>a.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,a]of Object.entries(e.running))if(a.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(a.pid,3e3),await this.deps.runService.finish(a.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(a=>c(a.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});}),await at(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),a=await Promise.all(s.map(([i])=>this.deps.taskStore.get(i)));for(let i=0;i<s.length;i++){let[h,c]=s[i],S=a[i];if(!S||b$1(S.status)){this.abortControllers.delete(h),delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile setStatus idle for stale agent ${c.agent_id} (task ${h})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(c.pid)){try{await this._handleRunFailure(h,c,"Process crashed unexpectedly");}catch{delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile crash fallback setStatus idle for agent ${c.agent_id} (task ${h})`,fatal:false});});}continue}let w=new Date(c.last_event_at).getTime(),v=this.deps.config.defaults.agent.stall_timeout_ms;if(e-w>v){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:c.run_id}),this.abortControllers.get(h)?.abort(),await this.deps.processManager.killWithGrace(c.pid,5e3);try{await this._handleRunFailure(h,c,"Agent stalled (no events)");}catch{delete t.running[h],await this.deps.agentService.setStatus(c.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`reconcile stall fallback setStatus idle for agent ${c.agent_id} (task ${h})`,fatal:false});});}}}let r=new Set(Object.values(t.running).map(i=>i.agent_id)),[u,n]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),l=u.filter(i=>i.status==="running"&&!r.has(i.id));l.length>0&&await Promise.all(l.map(i=>this.deps.agentService.setStatus(i.id,"idle")));let p=n.filter(i=>i.status==="in_progress"&&!t.running[i.id]);p.length>0&&await Promise.all(p.map(async i=>{try{await this.deps.taskService.updateStatus(i.id,"failed");}catch{i.status="failed",i.updated_at=new Date().toISOString(),await this.deps.taskStore.save(i).catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`force-write orphaned task ${i.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:i.id});}));let f=[];t.retry_queue=t.retry_queue.filter(i=>e>=new Date(i.due_at).getTime()?(f.push(i.task_id),false):true);for(let i of f)await this.dispatchTask(i);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(),a$1=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],r=false,u=new Set;for(let n of e){if(s.some(c=>c.assignee===n.id&&!b$1(c.status)))continue;let p=a$1.find(c=>c.assignee===n.id&&!u.has(c.id))??a$1.find(c=>!c.assignee&&!u.has(c.id));p&&u.add(p.id);let f=n.role??"general assistant",i=p?`[auto] ${n.name}: ${p.title.slice(0,60)}`:`[auto] ${n.name}: ${f.slice(0,60)}`,h=p?`## GOAL (highest priority)
5
+ `)}runCriterion(t){let{cmd:e,args:s}=St[t];return new Promise(a=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,d,n)=>{let l=(d+`
6
+ `+n).trim();a({criterion:t,passed:!r,output:l.slice(0,2e3)});});})}};var wt=8192,yt=4096,rt=class{constructor(t){this.deps=t;this.cachedTaskStore=new C(t.taskStore),this.cachedAgentStore=new B(t.agentStore),this.cachedGoalStore=t.goalStore?new M(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=[];skipAutonomousSeeding=false;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(r=>{e=r;}),a=this.stateMutex;return this.stateMutex=s,a.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 F(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 a=s instanceof Error?s.message:String(s);this.deps.eventBus.emit({type:"orchestrator:error",error:a,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 F(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(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),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(a=>a.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,a]of Object.entries(e.running))if(a.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(a.pid,3e3),await this.deps.runService.finish(a.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(a=>c(a.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});}),await at(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),a=await Promise.all(s.map(([i])=>this.deps.taskStore.get(i)));for(let i=0;i<s.length;i++){let[h,o]=s[i],v=a[i];if(!v||b$1(v.status)){this.abortControllers.delete(h),delete t.running[h],await this.deps.agentService.setStatus(o.agent_id,"idle").catch(c=>{this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`reconcile setStatus idle for stale agent ${o.agent_id} (task ${h})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(o.pid)){try{await this._handleRunFailure(h,o,"Process crashed unexpectedly");}catch{delete t.running[h],await this.deps.agentService.setStatus(o.agent_id,"idle").catch(c=>{this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`reconcile crash fallback setStatus idle for agent ${o.agent_id} (task ${h})`,fatal:false});});}continue}let w=new Date(o.last_event_at).getTime(),g=this.deps.config.defaults.agent.stall_timeout_ms;if(e-w>g){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:o.run_id}),this.abortControllers.get(h)?.abort(),await this.deps.processManager.killWithGrace(o.pid,5e3);try{await this._handleRunFailure(h,o,"Agent stalled (no events)");}catch{delete t.running[h],await this.deps.agentService.setStatus(o.agent_id,"idle").catch(c=>{this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`reconcile stall fallback setStatus idle for agent ${o.agent_id} (task ${h})`,fatal:false});});}}}let r=new Set(Object.values(t.running).map(i=>i.agent_id)),[d,n]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),l=d.filter(i=>i.status==="running"&&!r.has(i.id));l.length>0&&await Promise.all(l.map(i=>this.deps.agentService.setStatus(i.id,"idle")));let p=n.filter(i=>i.status==="in_progress"&&!t.running[i.id]);p.length>0&&await Promise.all(p.map(async i=>{try{await this.deps.taskService.updateStatus(i.id,"failed");}catch{i.status="failed",i.updated_at=new Date().toISOString(),await this.deps.taskStore.save(i).catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`force-write orphaned task ${i.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:i.id});}));let f=[];t.retry_queue=t.retry_queue.filter(i=>e>=new Date(i.due_at).getTime()?(f.push(i.task_id),false):true);for(let i of f)await this.dispatchTask(i);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(),a$1=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],r=false,d=new Set;for(let n of e){if(s.some(o=>o.assignee===n.id&&!b$1(o.status)))continue;let p=a$1.find(o=>o.assignee===n.id&&!d.has(o.id))??a$1.find(o=>!o.assignee&&!d.has(o.id));p&&d.add(p.id);let f=n.role??"general assistant",i=p?`[auto] ${n.name}: ${p.title.slice(0,60)}`:`[auto] ${n.name}: ${f.slice(0,60)}`,h=p?`## GOAL (highest priority)
7
7
 
8
8
  ${p.description||p.title}
9
9
 
10
10
  ---
11
- Agent role: ${f}`:`Autonomous work cycle. Agent role: ${f}`;try{await this.deps.taskService.create({title:i,description:h,assignee:n.id,labels:[a],priority:3,goalId:p?.id}),r=!0;}catch(c){this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`autonomous task for agent ${n.id}`,fatal:false});}}r&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,a=e-s;if(a<=0)return;let r=await this.cachedTaskStore.list(),u=new Map(r.map(i=>[i.id,i])),n=r.filter(i=>c(i.status)&&!d$1(i,u)&&!t.running[i.id]&&!t.claimed.has(i.id)).sort((i,h)=>{let c=(i.priority??3)-(h.priority??3);if(c!==0)return c;let S=(i.goalId?0:1)-(h.goalId?0:1);if(S!==0)return S;let w=h.updated_at??"",v=i.updated_at??"";return w<v?-1:w>v?1:0}).slice(0,a),l$1=new Set,p=r.filter(i=>i.status==="in_progress"&&i.scope?.length),f=new b(p.map(i=>i.scope));for(let i of n)if(i.scope?.length)if(f.overlapsAny(i.scope)){let h=p.find(c=>et(i.scope,c.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:i.id,overlappingTaskId:h?.id??i.id,patterns:i.scope}),l$1.add(i.id);}else f.add(i.scope);for(let i of n)if(!l$1.has(i.id))try{await this.dispatchTask(i.id);}catch(h){if(h instanceof l)try{let c=await this.deps.taskStore.get(i.id);c&&!b$1(c.status)&&(c.status="failed",c.updated_at=new Date().toISOString(),await this.deps.taskStore.save(c));}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`dispatch task ${i.id}`,fatal:false});}}async dispatchTask(t){let e=this.state;if(e.running[t]){let a=e.running[t];throw new h(t,a.run_id,a.agent_id)}let s=await this.deps.taskService.get(t);e.claimed.add(t),await this.saveState();try{let a=await this.cachedAgentStore.list(),r=await this.deps.agentService.findBestAgent(s);if(!r){if(a.length===0)throw new e$1;this.unclaim(t),await this.saveState();return}let{path:u,branch:n}=await this.deps.workspaceManager.prepare(s,r,this.deps.config),l=this.deps.config.prompt?.system_template??d$2,p=this.deps.config.prompt?.user_template??e$2,f=this.deps.config.prompt?.template,i=s.attempts+1,h;if(i>1){let m=await this.deps.runService.getLastFailedRunContext(s.id);m&&(h={previous_error:m.error,previous_output:m.output});}let c=s.goalId,[S,w,v]=await Promise.all([this.deps.contextStore?.getAll(),this.deps.messageService?this.deps.messageService.drainMailbox(r.id,s.id):[],c&&this.cachedGoalStore?this.cachedGoalStore.get(c).catch(()=>null):null]),o;if(v){let ct=(await this.cachedTaskStore.list()).filter(x=>x.goalId===c),lt=await this.deps.contextStore?.get(`${c}-progress`),dt=ct.map(x=>`[${x.status}] ${x.title}`);o={id:v.id,title:v.title,description:v.description,status:v.status,task_names:dt,progress:lt?.value};}let g=c$1(s,r,i,u,this.deps.config,{allAgents:a,retryContext:h,sharedContext:S,feedback:s.feedback,messages:w.length?w:void 0,goal:o}),y,k;if(f?y=await this.deps.templateEngine.render(f,g):(k=await this.deps.templateEngine.render(l,g),y=await this.deps.templateEngine.render(p,g)),this.deps.skillLoader&&r.config.skills?.length){let m=await this.deps.skillLoader.loadSkills(r.config.skills);m&&(k!==void 0?k=k+`
11
+ Agent role: ${f}`:`Autonomous work cycle. Agent role: ${f}`;try{await this.deps.taskService.create({title:i,description:h,assignee:n.id,labels:[a],priority:3,goalId:p?.id}),r=!0;}catch(o){this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),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,a=e$1-s;if(a<=0)return;let r=await this.cachedTaskStore.list(),d=new Map(r.map(i=>[i.id,i])),n=r.filter(i=>c(i.status)&&!d$1(i,d)&&!t.running[i.id]&&!t.claimed.has(i.id)).sort((i,h)=>{let o=(i.priority??3)-(h.priority??3);if(o!==0)return o;let v=(i.goalId?0:1)-(h.goalId?0:1);if(v!==0)return v;let w=h.updated_at??"",g=i.updated_at??"";return w<g?-1:w>g?1:0}).slice(0,a),l$1=new Set,p=r.filter(i=>i.status==="in_progress"&&i.scope?.length),f=new b(p.map(i=>i.scope));for(let i of n)if(i.scope?.length)if(f.overlapsAny(i.scope)){let h=p.find(o=>et(i.scope,o.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:i.id,overlappingTaskId:h?.id??i.id,patterns:i.scope}),l$1.add(i.id);}else f.add(i.scope);for(let i of n)if(!l$1.has(i.id))try{await this.dispatchTask(i.id);}catch(h){if(h instanceof l)try{let o=await this.deps.taskStore.get(i.id);if(o&&!b$1(o.status)){let v={...o,attempts:(o.attempts??0)+1,updated_at:new Date().toISOString()},w=e(v),g$1={...v,status:w};if(await this.deps.taskStore.save(g$1),w==="failed"){let c=await this.cachedTaskStore.list();await this.cascadeFailDependents(g$1.id,c,`dependency ${g$1.id} failed: ${h.message}`);}else {let c=g(g$1.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);this.enqueueRetry(t,g$1.id,g$1.attempts,c,h.message),await this.saveState();}}}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`dispatch task ${i.id}`,fatal:false});}}enqueueRetry(t,e,s,a,r){t.retry_queue.some(d=>d.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()+a).toISOString(),error:r}));}async cascadeFailDependents(t,e,s){let a=new Map;for(let p of e)for(let f of p.depends_on){let i=a.get(f);i||(i=[],a.set(f,i)),i.push(p);}let r=[t],d=0,n=new Set,l=false;for(;d<r.length;){let p=r[d++];if(n.has(p))continue;n.add(p);let f=a.get(p);if(!f)continue;let i=[];for(let o of f)b$1(o.status)||n.has(o.id)||(i.push({task:o,previousStatus:o.status}),r.push(o.id));if(i.length===0)continue;let h=new Date().toISOString();await Promise.all(i.map(({task:o})=>this.deps.taskStore.save({...o,status:"failed",updated_at:h})));for(let{task:o,previousStatus:v}of i)this.deps.eventBus.emit({type:"task:status_changed",taskId:o.id,from:v,to:"failed"}),this.deps.eventBus.emit({type:"task:cascade_failed",taskId:o.id,failedDependencyId:t,reason:s});l=true;}l&&this.cachedTaskStore.invalidate();}async dispatchTask(t){let e=this.state;if(e.running[t]){let a=e.running[t];throw new h(t,a.run_id,a.agent_id)}let s=await this.deps.taskService.get(t);e.claimed.add(t),await this.saveState();try{let a=await this.cachedAgentStore.list(),r=await this.deps.agentService.findBestAgent(s);if(!r){if(a.length===0)throw new e$1;this.unclaim(t),await this.saveState();return}let{path:d,branch:n}=await this.deps.workspaceManager.prepare(s,r,this.deps.config),l=this.deps.config.prompt?.system_template??d$2,p=this.deps.config.prompt?.user_template??e$2,f=this.deps.config.prompt?.template,i=s.attempts+1,h;if(i>1){let S=await this.deps.runService.getLastFailedRunContext(s.id);S&&(h={previous_error:S.error,previous_output:S.output});}let o=s.goalId,[v,w,g]=await Promise.all([this.deps.contextStore?.getAll(),this.deps.messageService?this.deps.messageService.drainMailbox(r.id,s.id):[],o&&this.cachedGoalStore?this.cachedGoalStore.get(o).catch(()=>null):null]),c;if(g){let ct=(await this.cachedTaskStore.list()).filter(x=>x.goalId===o),lt=await this.deps.contextStore?.get(`${o}-progress`),dt=ct.map(x=>`[${x.status}] ${x.title}`);c={id:g.id,title:g.title,description:g.description,status:g.status,task_names:dt,progress:lt?.value};}let m=c$1(s,r,i,d,this.deps.config,{allAgents:a,retryContext:h,sharedContext:v,feedback:s.feedback,messages:w.length?w:void 0,goal:c}),y,k;if(f?y=await this.deps.templateEngine.render(f,m):(k=await this.deps.templateEngine.render(l,m),y=await this.deps.templateEngine.render(p,m)),this.deps.skillLoader&&r.config.skills?.length){let S=await this.deps.skillLoader.loadSkills(r.config.skills);S&&(k!==void 0?k=k+`
12
12
 
13
- `+m:y=y+`
13
+ `+S:y=y+`
14
14
 
15
- `+m);}let R=await this.deps.runService.create({taskId:s.id,agentId:r.id,attempt:i,prompt:y,workspacePath:u});if((s.status==="failed"||s.status==="cancelled")&&(await this.deps.taskService.retry(t),s.status="todo",s.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,r.id),await this.deps.taskService.incrementAttempts(t),n){let m=await this.deps.taskStore.get(t);m&&(m.proof={...m.proof??{files_changed:[]},branch:n},m.workspace=u,await this.deps.taskStore.save(m));}await this.deps.agentService.setStatus(r.id,"running");let _=await this.deps.agentService.get(r.id);_.current_task=t,_.last_error=void 0,await this.deps.agentStore.save(_);let ot=this.deps.adapterRegistry.require(r.adapter),F=new AbortController;this.abortControllers.set(t,F);let I=ot.execute({prompt:y,systemPrompt:k,workspace:u,env:{...r.config.env,ORCH_AGENT_ID:r.id,ORCH_AGENT_NAME:r.name,ORCH_TASK_ID:s.id},config:_.config,signal:F.signal}),N=I.pid,U=new Date().toISOString();await this.deps.runService.start(R.id,N),this.unclaim(t),e.running[t]={run_id:R.id,agent_id:r.id,task_id:t,pid:N,started_at:U,last_event_at:U},await this.saveState(),this.collectEvents(I.events,R.id,t,r.id).catch(m=>{this.deps.eventBus.emit({type:"orchestrator:error",error:m instanceof Error?m.message:String(m),context:`adapter execution for ${t}`,fatal:!1});});}catch(a){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),a}}async collectEvents(t,e,s,a){let r,u,n,l,p=new Set;try{for await(let i of t){if(this.shuttingDown)break;if(i.type==="done"){if(i.tokens){let{input:g,output:y,reasoning:k,cache_read:R,cache_write:_}=i.tokens;r=a$1(g,y,{reasoning:k,cache_read:R,cache_write:_});}let o=i.data;o&&typeof o.result=="string"&&(u=o.result);}if(i.type==="output"){let o=i.data;if(o){let g=typeof o.text=="string"?o.text:typeof o.message=="string"?o.message:void 0;g?.trim()&&(n=g);}}if(i.type==="file_change"){let o=i.data;if(o&&Array.isArray(o.paths))for(let g of o.paths)typeof g=="string"&&p.add(g);else {let g=o&&typeof o.path=="string"?o.path:typeof i.data=="string"?i.data:String(i.data);p.add(g);}}let h=kt(i.timestamp)?i.timestamp:new Date().toISOString(),c=i.type==="file_change"?(()=>{let o=i.data;return o&&typeof o.path=="string"?o.path:typeof i.data=="string"?i.data:String(i.data)})():null,S=nt(i.data,wt);i.data=void 0;let w={timestamp:h,type:i.type==="output"?"agent_output":i.type==="file_change"?"file_changed":i.type==="command"?"command_run":i.type==="tool_call"?"tool_call":i.type==="error"?"error":"done",data:S};await this.deps.runService.appendEvent(e,w),this.state?.running[s]&&(this.state.running[s].last_event_at=h,this.saveStateLazy());let v=nt(S,yt);i.type==="output"||i.type==="tool_call"?this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:a,data:v}):i.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:a,path:c}):i.type==="error"&&(i.errorKind&&(l=i.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:a,error:v,...i.errorKind?{errorKind:i.errorKind}:{}}));}let f=u??n;await this.handleRunSuccess(s,e,a,r,f,[...p]);}catch(f){let i=f instanceof Error?f.message:String(f),h=l??(f instanceof Error?f.errorKind:void 0),c=this.state?.running[s];c&&await this.handleRunFailure(s,c,i,h);}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,a,r,u){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,a,r,u))}async _handleRunSuccess(t,e,s,a$1,r,u){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let l=await this.deps.taskStore.get(t);if(!l)return;l.proof={...l.proof,agent_summary:r?.slice(0,2e3)??l.proof?.agent_summary,files_changed:u?.length?u:l.proof?.files_changed??[]},delete l.feedback,await this.deps.taskStore.save(l);let p=await this.deps.agentStore.get(s),i=l.labels?.includes(a)||p?.config.approval_policy==="auto",h=f(l,true,i);await this.deps.runService.finish(e,"succeeded",a$1);let c=n.running[t],S=c?Date.now()-new Date(c.started_at).getTime():0;c&&(n.stats.total_runtime_ms+=S),delete n.running[t];let w={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)+S};if(a$1&&(w.tokens_used=(p?.stats.tokens_used??0)+a$1.total),await this.deps.agentService.updateStats(s,w).catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`agent stats update for ${s}`,fatal:false});}),n.stats.total_tasks_completed++,n.stats.total_runs++,a$1&&(n.stats.total_tokens.input+=a$1.input,n.stats.total_tokens.output+=a$1.output,n.stats.total_tokens.reasoning+=a$1.reasoning,n.stats.total_tokens.cache_read+=a$1.cache_read,n.stats.total_tokens.cache_write+=a$1.cache_write,n.stats.total_tokens.total=n.stats.total_tokens.input+n.stats.total_tokens.output+n.stats.total_tokens.reasoning),l.proof?.branch)try{let o=await this.deps.workspaceManager.mergeBack(l.proof.branch);if(o.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:l.proof.branch}),await this.deps.workspaceManager.cleanup(t,l.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:l.proof.branch,conflictInfo:o.conflictInfo}),await this.forceTaskToReview(l,s,`MERGE CONFLICT: ${o.conflictInfo}`);return}}catch(o){let g=o instanceof Error?o.message:String(o);await this.forceTaskToReview(l,s,`MERGE ERROR: ${g}`);return}try{await this.deps.taskService.updateStatus(t,h);}catch(o){let g=o instanceof Error?o.message:String(o);this.deps.eventBus.emit({type:"orchestrator:error",error:g,context:`state machine validation failed for task ${t} -> ${h}, force-writing`,fatal:false}),l.status=h,l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(y=>{this.deps.eventBus.emit({type:"orchestrator:error",error:y instanceof Error?y.message:String(y),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let v=await this.deps.agentStore.get(s);v&&(v.current_task=void 0,await this.deps.agentStore.save(v)),h==="review"&&l.review_criteria?.length?await this.runAutoReview(t,l.review_criteria,l.workspace??this.deps.projectRoot,i):h==="review"&&i&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s,a){return this.withStateLock(()=>this._handleRunFailure(t,e,s,a))}async _handleRunFailure(t,e$1,s,a){await this.flushStateLazy(),this.abortControllers.delete(t);let r=this.state,u=await this.deps.taskStore.get(t);if(!u)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$1=await this.deps.agentStore.get(e$1.agent_id);n$1&&(n$1.current_task=void 0,n$1.last_error={message:s.slice(0,500),kind:a??n(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n$1));let l=await this.deps.agentStore.get(e$1.agent_id),p=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(l?.stats.tasks_failed??0)+1,total_runs:(l?.stats.total_runs??0)+1,total_runtime_ms:(l?.stats.total_runtime_ms??0)+p});let f=e(u);if(await this.deps.taskService.updateStatus(t,f),f==="retrying"){let i=g(u.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);r.retry_queue.some(c=>c.task_id===t)||(r.retry_queue.length>=this.maxRetryQueueSize&&r.retry_queue.shift(),r.retry_queue.push({task_id:t,attempt:u.attempts+1,due_at:new Date(Date.now()+i).toISOString(),error:s})),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:u.attempts+1,delay_ms:i});}else r.stats.total_tasks_failed++;r.stats.total_runtime_ms+=p,u.proof?.branch&&await this.deps.workspaceManager.cleanup(t,u.proof.branch).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),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,a=false){let u=await new A({cwd:s}).runAll(e),n=A.allPassed(u),l=await this.deps.taskStore.get(t);if(l&&(l.review_results=u,l.proof={...l.proof,test_results:A.formatReport(u),files_changed:l.proof?.files_changed??[]},await this.deps.taskStore.save(l),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:u}),n||a)){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(p){let f=p instanceof Error?p.message:String(p);this.deps.eventBus.emit({type:"orchestrator:error",error:f,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),l.status="done",l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`force-write task ${t} to store failed (auto-review)`,fatal:false});});}}}async forceTaskToReview(t,e,s){t.proof={...t.proof,agent_summary:`${s}
15
+ `+S);}let P=await this.deps.runService.create({taskId:s.id,agentId:r.id,attempt:i,prompt:y,workspacePath:d});if((s.status==="failed"||s.status==="cancelled")&&(await this.deps.taskService.retry(t),s.status="todo",s.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,r.id),await this.deps.taskService.incrementAttempts(t),n){let S=await this.deps.taskStore.get(t);S&&(S.proof={...S.proof??{files_changed:[]},branch:n},S.workspace=d,await this.deps.taskStore.save(S));}await this.deps.agentService.setStatus(r.id,"running");let _=await this.deps.agentService.get(r.id);_.current_task=t,_.last_error=void 0,await this.deps.agentStore.save(_);let ot=this.deps.adapterRegistry.require(r.adapter),I=new AbortController;this.abortControllers.set(t,I);let N=ot.execute({prompt:y,systemPrompt:k,workspace:d,env:{...r.config.env,ORCH_AGENT_ID:r.id,ORCH_AGENT_NAME:r.name,ORCH_TASK_ID:s.id},config:_.config,signal:I.signal}),U=N.pid,K=new Date().toISOString();await this.deps.runService.start(P.id,U),this.unclaim(t),e.running[t]={run_id:P.id,agent_id:r.id,task_id:t,pid:U,started_at:K,last_event_at:K},await this.saveState(),this.collectEvents(N.events,P.id,t,r.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});});}catch(a){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),a}}async collectEvents(t,e,s,a){let r,d,n,l,p=new Set;try{for await(let i of t){if(this.shuttingDown)break;if(i.type==="done"){if(i.tokens){let{input:m,output:y,reasoning:k,cache_read:P,cache_write:_}=i.tokens;r=a$1(m,y,{reasoning:k,cache_read:P,cache_write:_});}let c=i.data;c&&typeof c.result=="string"&&(d=c.result);}if(i.type==="output"){let c=i.data;if(c){let m=typeof c.text=="string"?c.text:typeof c.message=="string"?c.message:void 0;m?.trim()&&(n=m);}}if(i.type==="file_change"){let c=i.data;if(c&&Array.isArray(c.paths))for(let m of c.paths)typeof m=="string"&&p.add(m);else {let m=c&&typeof c.path=="string"?c.path:typeof i.data=="string"?i.data:String(i.data);p.add(m);}}let h=kt(i.timestamp)?i.timestamp:new Date().toISOString(),o=i.type==="file_change"?(()=>{let c=i.data;return c&&typeof c.path=="string"?c.path:typeof i.data=="string"?i.data:String(i.data)})():null,v=nt(i.data,wt);i.data=void 0;let w={timestamp:h,type:i.type==="output"?"agent_output":i.type==="file_change"?"file_changed":i.type==="command"?"command_run":i.type==="tool_call"?"tool_call":i.type==="error"?"error":"done",data:v};await this.deps.runService.appendEvent(e,w),this.state?.running[s]&&(this.state.running[s].last_event_at=h,this.saveStateLazy());let g=nt(v,yt);i.type==="output"||i.type==="tool_call"?this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:a,data:g}):i.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:a,path:o}):i.type==="error"&&(i.errorKind&&(l=i.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:a,error:g,...i.errorKind?{errorKind:i.errorKind}:{}}));}let f=d??n;await this.handleRunSuccess(s,e,a,r,f,[...p]);}catch(f){let i=f instanceof Error?f.message:String(f),h=l??(f instanceof Error?f.errorKind:void 0),o=this.state?.running[s];o&&await this.handleRunFailure(s,o,i,h);}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,a,r,d){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,a,r,d))}async _handleRunSuccess(t,e,s,a$1,r,d){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let l=await this.deps.taskStore.get(t);if(!l)return;l.proof={...l.proof,agent_summary:r?.slice(0,2e3)??l.proof?.agent_summary,files_changed:d?.length?d:l.proof?.files_changed??[]},delete l.feedback,await this.deps.taskStore.save(l);let p=await this.deps.agentStore.get(s),i=l.labels?.includes(a)||p?.config.approval_policy==="auto",h=f(l,true,i);await this.deps.runService.finish(e,"succeeded",a$1);let o=n.running[t],v=o?Date.now()-new Date(o.started_at).getTime():0;o&&(n.stats.total_runtime_ms+=v),delete n.running[t];let w={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)+v};if(a$1&&(w.tokens_used=(p?.stats.tokens_used??0)+a$1.total),await this.deps.agentService.updateStats(s,w).catch(c=>{this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`agent stats update for ${s}`,fatal:false});}),n.stats.total_tasks_completed++,n.stats.total_runs++,a$1&&(n.stats.total_tokens.input+=a$1.input,n.stats.total_tokens.output+=a$1.output,n.stats.total_tokens.reasoning+=a$1.reasoning,n.stats.total_tokens.cache_read+=a$1.cache_read,n.stats.total_tokens.cache_write+=a$1.cache_write,n.stats.total_tokens.total=n.stats.total_tokens.input+n.stats.total_tokens.output+n.stats.total_tokens.reasoning),l.proof?.branch)try{let c=await this.deps.workspaceManager.mergeBack(l.proof.branch);if(c.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:l.proof.branch}),await this.deps.workspaceManager.cleanup(t,l.proof.branch).catch(m=>{this.deps.eventBus.emit({type:"orchestrator:error",error:m instanceof Error?m.message:String(m),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:l.proof.branch,conflictInfo:c.conflictInfo}),await this.forceTaskToReview(l,s,`MERGE CONFLICT: ${c.conflictInfo}`);return}}catch(c){let m=c instanceof Error?c.message:String(c);await this.forceTaskToReview(l,s,`MERGE ERROR: ${m}`);return}try{await this.deps.taskService.updateStatus(t,h);}catch(c){let m=c instanceof Error?c.message:String(c);this.deps.eventBus.emit({type:"orchestrator:error",error:m,context:`state machine validation failed for task ${t} -> ${h}, force-writing`,fatal:false}),l.status=h,l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(y=>{this.deps.eventBus.emit({type:"orchestrator:error",error:y instanceof Error?y.message:String(y),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(c=>{this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let g=await this.deps.agentStore.get(s);g&&(g.current_task=void 0,await this.deps.agentStore.save(g)),h==="review"&&l.review_criteria?.length?await this.runAutoReview(t,l.review_criteria,l.workspace??this.deps.projectRoot,i):h==="review"&&i&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s,a){return this.withStateLock(()=>this._handleRunFailure(t,e,s,a))}async _handleRunFailure(t,e$1,s,a){await this.flushStateLazy(),this.abortControllers.delete(t);let r=this.state,d=await this.deps.taskStore.get(t);if(!d)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$1=await this.deps.agentStore.get(e$1.agent_id);n$1&&(n$1.current_task=void 0,n$1.last_error={message:s.slice(0,500),kind:a??n(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n$1));let l=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(n$1?.stats.tasks_failed??0)+1,total_runs:(n$1?.stats.total_runs??0)+1,total_runtime_ms:(n$1?.stats.total_runtime_ms??0)+l});let p=e(d);if(await this.deps.taskService.updateStatus(t,p),p==="retrying"){let f=g(d.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);this.enqueueRetry(r,t,d.attempts+1,f,s),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:d.attempts+1,delay_ms:f});}else {r.stats.total_tasks_failed++;let f=await this.cachedTaskStore.list();await this.cascadeFailDependents(t,f,`dependency ${t} failed: ${s}`);}r.stats.total_runtime_ms+=l,d.proof?.branch&&await this.deps.workspaceManager.cleanup(t,d.proof.branch).catch(f=>{this.deps.eventBus.emit({type:"orchestrator:error",error:f instanceof Error?f.message:String(f),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,a=false){let d=await new R({cwd:s}).runAll(e),n=R.allPassed(d),l=await this.deps.taskStore.get(t);if(l&&(l.review_results=d,l.proof={...l.proof,test_results:R.formatReport(d),files_changed:l.proof?.files_changed??[]},await this.deps.taskStore.save(l),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:d}),n||a)){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(p){let f=p instanceof Error?p.message:String(p);this.deps.eventBus.emit({type:"orchestrator:error",error:f,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),l.status="done",l.updated_at=new Date().toISOString(),await this.deps.taskStore.save(l).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),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
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 a=await this.deps.agentStore.get(e);a&&(a.current_task=void 0,await this.deps.agentStore.save(a)),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(([,a])=>!this.deps.processManager.isAlive(a.pid)),s=new Set;if(e.length>0){for(let[a]of e)delete t.running[a],s.add(a);await Promise.all(e.map(async([a,r])=>{await this.deps.agentService.setStatus(r.agent_id,"idle").catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),context:`startup cleanup: setStatus idle for agent ${r.agent_id}`,fatal:false});}),await this.forceTaskCancelled(a),await this.deps.runService.finish(r.run_id,"cancelled",void 0,"Orchestrator restarted").catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),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 u=new Set([...s,...r.map(n=>n.id)]);t.retry_queue=t.retry_queue.filter(n=>!u.has(n.task_id)),await this.saveState();}}async forceTaskCancelled(t){try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{let e=await this.deps.taskStore.get(t);e&&!b$1(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 kt(d){if(typeof d!="string")return false;let t=new Date(d);return !isNaN(t.getTime())&&t.toISOString()===d}function nt(d,t){let e=typeof d=="string"?d:JSON.stringify(d);return e.length>t?e.slice(0,t)+"\u2026":e}export{rt as Orchestrator};
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 a=await this.deps.agentStore.get(e);a&&(a.current_task=void 0,await this.deps.agentStore.save(a)),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(([,a])=>!this.deps.processManager.isAlive(a.pid)),s=new Set;if(e.length>0){for(let[a]of e)delete t.running[a],s.add(a);await Promise.all(e.map(async([a,r])=>{await this.deps.agentService.setStatus(r.agent_id,"idle").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),context:`startup cleanup: setStatus idle for agent ${r.agent_id}`,fatal:false});}),await this.forceTaskCancelled(a),await this.deps.runService.finish(r.run_id,"cancelled",void 0,"Orchestrator restarted").catch(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),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 d=new Set([...s,...r.map(n=>n.id)]);t.retry_queue=t.retry_queue.filter(n=>!d.has(n.task_id)),await this.saveState();}}async forceTaskCancelled(t){try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{let e=await this.deps.taskStore.get(t);e&&!b$1(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 kt(u){if(typeof u!="string")return false;let t=new Date(u);return !isNaN(t.getTime())&&t.toISOString()===u}function nt(u,t){let e=typeof u=="string"?u:JSON.stringify(u);return e.length>t?e.slice(0,t)+"\u2026":e}export{rt as Orchestrator};
@@ -0,0 +1,6 @@
1
+ export { Orchestrator } from './chunk-5YSW77VI.js';
2
+ import './chunk-VG4465AG.js';
3
+ import './chunk-RHFRHCN5.js';
4
+ import './chunk-NLQAJ7TW.js';
5
+ //# sourceMappingURL=orchestrator-WLWIAFXH.js.map
6
+ //# sourceMappingURL=orchestrator-WLWIAFXH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-G3Y7THMG.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-WLWIAFXH.js"}
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {i}from'./chunk-64WUDYEM.js';import g from'fs';var f=6;function w(o,n){let e=o.version()??"0.0.0";o.command("serve").description("Headless daemon mode \u2014 structured logs to stdout").option("--once","Process todo tasks and exit when all are terminal").option("--tick-interval <ms>","Override polling interval (ms)").option("--log-file <path>","Also write logs to file (append mode)").option("--log-format <format>","Log format: json or text (default: json)","json").option("--verbose","Include high-frequency agent:output events").action(async a=>{await u(n,e,a);});}var p=new Set(["json","text"]);async function u(o,n,e){if(e.logFormat&&!p.has(e.logFormat)){i(`Unknown --log-format "${e.logFormat}". Valid: json, text`),process.exitCode=2;return}let a=e.logFormat==="text"?"text":"json",l=[process.stdout],s;if(e.logFile&&(s=g.createWriteStream(e.logFile,{flags:"a"}),s.on("error",t=>{process.stderr.write(`Log file error: ${t.message}
3
+ `);}),l.push(s)),e.tickInterval){let t=parseInt(e.tickInterval,10);!isNaN(t)&&t>0&&(o.config.scheduling.poll_interval_ms=t);}let{StructuredLogger:c}=await import('./structured-logger-EXMGTUDB.js'),r=new c({format:a,verbose:e.verbose??false,streams:l,idleLogInterval:f}),d=r.subscribe(o.eventBus);r.log("info","serve:started",{mode:e.once?"once":"watch",pid:process.pid,poll_interval_ms:o.config.scheduling.poll_interval_ms}),import('./update-check-CZJC7VW6.js').then(t=>t.checkForUpdateSWR(n)).catch(()=>null).then(t=>{t?.updateAvailable&&r.log("warn","update:available",{current:t.current,latest:t.latest,hint:"Run: npm install -g @oxgeneral/orch"});});try{if(e.once){let{runOnce:t}=await import('./once-runner-AMKCFW22.js'),i=await t(o.orchestrator,o.taskStore,o.eventBus);r.log("info","serve:finished",{result:i,exit_code:i==="has_failed"?1:0}),process.exitCode=i==="has_failed"?1:0;}else await o.orchestrator.startWatch(),await o.orchestrator.waitForStop();}finally{d(),await r.flush();}}export{w as registerServeCommand};
@@ -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: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-SEIWOLHY.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};
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-LV3WOPMS.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};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ function rt(c,e){c.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let y=await e.taskService.list(),v=await e.agentService.list(),S=await e.stateStore.read(),{render:w}=await import('ink'),{createElement:f}=await import('react'),{App:h}=await import('./App-Q6LOPAZT.js'),T=async t=>{await e.orchestrator.runTask(t);},k=async(t,s)=>e.taskService.create({title:t,priority:s?.priority,description:s?.description,attachments:s?.attachments}),A=async t=>{await e.orchestrator.cancelTask(t);},C=async t=>{await e.taskService.retry(t);},b=async(t,s)=>{await e.taskService.assign(t,s);},R=async()=>{await e.orchestrator.runAll();},_=async t=>{await e.agentService.disable(t);},E=async t=>{await e.agentService.enable(t);},j=t=>e.eventBus.onAny(t),D=async()=>e.taskService.list(),P=async()=>e.agentService.list(),U=async()=>e.stateStore.read(),G=async(t,s,n)=>e.agentService.create({name:t,adapter:s??"claude",model:n?.model||void 0,role:n?.role||void 0,approval_policy:n?.approval_policy||void 0,skills:n?.skills||void 0}),x=async t=>{await e.agentService.remove(t);},L=async t=>{await e.taskService.delete(t);},H=async t=>{await e.taskService.updateStatus(t,"done");},W=async(t,s)=>{await e.taskService.reject(t,s);},F=async(t,s)=>e.taskService.update(t,s),I=async(t,s)=>e.agentService.update(t,{...s,approval_policy:s.approval_policy}),N=async t=>{await e.orchestrator.forceStopAgent(t);},O=async(t,s)=>e.agentService.setAutonomous(t,s),B=async t=>{let s=await e.runService.listAll();s.sort((a,r)=>new Date(r.started_at).getTime()-new Date(a.started_at).getTime());let n=s.filter(a=>a.status==="succeeded"||a.status==="failed"),d=3,it=10,m=n.slice(0,d),p=n.slice(d,it),u=async a=>(await e.runService.readEventsTail(a.id,30)).map(i=>({timestamp:i.timestamp,agentId:a.agent_id,taskId:a.task_id,type:i.type,data:i.data}));if(m.length>0){let a=(await Promise.all(m.map(u))).flat();a.sort((r,i)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime()),t(a.slice(-200));}if(p.length>0){let a=(await Promise.all(p.map(u))).flat();a.sort((r,i)=>new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime()),t(a.slice(-200));}},M=async t=>e.teamService.create(t),V=async()=>e.teamService.list(),J=async(t,s)=>e.teamService.join(t,s),K=async(t,s)=>e.teamService.leave(t,s),q=async t=>{await e.teamService.disband(t);},z=async(t,s)=>e.teamService.setLead(t,s),Q=async()=>e.goalService.list(),X=async t=>e.goalService.create(t),Y=async(t,s)=>e.goalService.update(t,s),Z=async(t,s)=>e.goalService.updateStatus(t,s),$=async t=>{await e.goalService.delete(t);},tt=async t=>e.goalService.getProgressReport(t),et=async()=>{await e.orchestrator.startWatch();},st=async()=>{await e.orchestrator.stop();},l=c.version()??"0.0.0",at=import('./update-check-CZJC7VW6.js').then(t=>t.checkForUpdateSWR(l)).catch(()=>null),o=false,g;try{await e.orchestrator.startWatch(),o=!0;}catch(t){g=t instanceof Error?t.message:String(t);}let{waitUntilExit:nt}=w(f(h,{projectName:e.config.project.name,tasks:y,agents:v,state:S,onRunTask:T,onCreateTask:k,onCancelTask:A,onRetryTask:C,onAssignTask:b,onRunAll:R,onDisableAgent:_,onEnableAgent:E,onSubscribeEvents:j,onRefreshTasks:D,onRefreshAgents:P,onRefreshState:U,onLoadHistory:B,onAddAgent:G,onDeleteAgent:x,onApproveTask:H,onRejectTask:W,onDeleteTask:L,onUpdateTask:F,onUpdateAgent:I,onForceStopAgent:N,onToggleAutonomous:O,onRefreshGoals:Q,onCreateGoal:X,onUpdateGoal:Y,onUpdateGoalStatus:Z,onDeleteGoal:$,onGetGoalProgress:tt,onCreateTeam:M,onListTeams:V,onJoinTeam:J,onLeaveTeam:K,onDisbandTeam:q,onSetTeamLead:z,onStartWatch:et,onStopWatch:st,initialWatchActive:o,watchError:g,version:l,latestVersion:void 0,onCheckUpdate:async()=>{let t=await at;return t?.updateAvailable?t.latest:void 0},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);}}),{kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await nt(),o&&await e.orchestrator.stop().catch(()=>{}),e.eventBus.clear();});}export{rt as registerTuiCommand};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import {a}from'./chunk-UMZEA3JT.js';import {p,q}from'./chunk-64WUDYEM.js';import {execFile}from'child_process';import e from'chalk';var c="@oxgeneral/orch";function u(){return new Promise(n=>{let t=execFile("npm",["install","-g",`${c}@latest`],{timeout:6e4},(s,o,a)=>{let d=(o??"")+(a??"");n({code:s?1:0,output:d});});t.stdout?.pipe(process.stdout),t.stderr?.pipe(process.stderr);})}function h(n){n.command("update").description("Check for updates and install the latest version").option("--check","Only check, do not install").action(async t=>{console.log(),console.log(` ${p("orch update")} \xB7 checking for updates\u2026`),console.log();let s=n.version()??"0.0.0",o=await a(s);if(o||(console.log(` ${e.ansi256(167)("\u2715")} Could not reach npm registry`),console.log(" Check your network connection and try again."),console.log(),process.exit(1)),!o.updateAvailable){console.log(` ${e.ansi256(72)("\u2713")} Already up to date ${q(`(${o.current})`)}`),console.log();return}if(console.log(` ${e.ansi256(214)("\u25CF")} Update available: ${q(o.current)} \u2192 ${e.ansi256(72)(o.latest)}`),console.log(),t.check){console.log(` Run ${q("orch update")} to install.`),console.log();return}console.log(` Installing ${c}@${o.latest}\u2026`),console.log(),(await u()).code!==0&&(console.log(),console.log(` ${e.ansi256(167)("\u2715")} Update failed. Try manually:`),console.log(` npm install -g ${c}@latest`),console.log(),process.exit(1)),console.log(),console.log(` ${e.ansi256(72)("\u2713")} Updated to ${o.latest}`),console.log();});}export{h as registerUpdateCommand};
2
+ import {a}from'./chunk-XLBV2PFL.js';import {p,q}from'./chunk-64WUDYEM.js';import {execFile}from'child_process';import e from'chalk';var c="@oxgeneral/orch";function u(){return new Promise(n=>{let t=execFile("npm",["install","-g",`${c}@latest`],{timeout:6e4},(s,o,a)=>{let d=(o??"")+(a??"");n({code:s?1:0,output:d});});t.stdout?.pipe(process.stdout),t.stderr?.pipe(process.stderr);})}function h(n){n.command("update").description("Check for updates and install the latest version").option("--check","Only check, do not install").action(async t=>{console.log(),console.log(` ${p("orch update")} \xB7 checking for updates\u2026`),console.log();let s=n.version()??"0.0.0",o=await a(s);if(o||(console.log(` ${e.ansi256(167)("\u2715")} Could not reach npm registry`),console.log(" Check your network connection and try again."),console.log(),process.exit(1)),!o.updateAvailable){console.log(` ${e.ansi256(72)("\u2713")} Already up to date ${q(`(${o.current})`)}`),console.log();return}if(console.log(` ${e.ansi256(214)("\u25CF")} Update available: ${q(o.current)} \u2192 ${e.ansi256(72)(o.latest)}`),console.log(),t.check){console.log(` Run ${q("orch update")} to install.`),console.log();return}console.log(` Installing ${c}@${o.latest}\u2026`),console.log(),(await u()).code!==0&&(console.log(),console.log(` ${e.ansi256(167)("\u2715")} Update failed. Try manually:`),console.log(` npm install -g ${c}@latest`),console.log(),process.exit(1)),console.log(),console.log(` ${e.ansi256(72)("\u2713")} Updated to ${o.latest}`),console.log();});}export{h as registerUpdateCommand};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{a as checkForUpdateNow,b as checkForUpdateSWR,c as printUpdateNotification}from'./chunk-UMZEA3JT.js';
2
+ export{a as checkForUpdateNow,b as checkForUpdateSWR,c as printUpdateNotification}from'./chunk-XLBV2PFL.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxgeneral/orch",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
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/readme.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <a href="https://www.orch.one/"><img src="https://img.shields.io/badge/website-orch.one-f59e0b?style=for-the-badge&labelColor=0a0a0a" alt="Website" /></a>&nbsp;
16
16
  <a href="https://www.npmjs.com/package/@oxgeneral/orch"><img src="https://img.shields.io/npm/v/@oxgeneral/orch?style=for-the-badge&color=f59e0b&labelColor=0a0a0a" alt="npm" /></a>&nbsp;
17
17
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-f59e0b?style=for-the-badge&labelColor=0a0a0a" alt="MIT License" /></a>&nbsp;
18
- <a href="#development"><img src="https://img.shields.io/badge/tests-1647%20passing-f59e0b?style=for-the-badge&labelColor=0a0a0a" alt="Tests" /></a>
18
+ <a href="#development"><img src="https://img.shields.io/badge/tests-1694%20passing-f59e0b?style=for-the-badge&labelColor=0a0a0a" alt="Tests" /></a>
19
19
  </p>
20
20
 
21
21
  <br/>
@@ -621,7 +621,7 @@ src/
621
621
  ```bash
622
622
  npm run dev # Run via tsx
623
623
  npm run build # Build ESM + DTS
624
- npm test # 1647 tests via Vitest
624
+ npm test # 1694 tests via Vitest
625
625
  npm run typecheck # Strict TypeScript
626
626
  ```
627
627