@oxgeneral/orch 1.0.18 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-NNF3VEVJ.js → chunk-WM64PSY4.js} +11 -5
- package/dist/chunk-WM64PSY4.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{container-5FLJ4QYD.js → container-4VRJ7G6U.js} +1 -1
- package/dist/index.js +3 -3
- package/dist/orchestrator-53KIAROT.js +6 -0
- package/dist/{orchestrator-I3CXUOH7.js.map → orchestrator-53KIAROT.js.map} +1 -1
- package/dist/orchestrator-Z6C5OE4A.js +17 -0
- package/dist/{task-TTOAOVM7.js → task-IVKKK22G.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-NNF3VEVJ.js.map +0 -1
- package/dist/orchestrator-I3CXUOH7.js +0 -6
- package/dist/orchestrator-L34ZPKAB.js +0 -17
|
@@ -1,17 +0,0 @@
|
|
|
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 A 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(pt(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 x=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(ht(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 ht(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 pt(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 gt(h)}finally{t();}}var ft=6e4;async function gt(h){let t=await at(h);if(t!==null){if(vt(t)&&!await mt(h))return {acquired:false,pid:t};await A.unlink(h).catch(()=>{});}try{let e=await A.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 A.unlink(h).catch(()=>{});}async function rt(h){let t=Date.now()/1e3;await A.utimes(h,t,t).catch(()=>{});}async function at(h){try{let t=await A.readFile(h,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function mt(h){try{let t=await A.stat(h);return Date.now()-t.mtimeMs>ft}catch{return true}}function vt(h){try{return process.kill(h,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();}},O=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 wt={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},nt=["typecheck","lint","test_pass"],R=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=yt(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}=wt[t];return new Promise(i=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,d,n)=>{let u=(d+`
|
|
6
|
-
`+n).trim();i({criterion:t,passed:!r,output:u.slice(0,2e3)});});})}};function yt(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 kt=8192,_t=4096,ot=class h$1{constructor(t){this.deps=t;this.cachedTaskStore=new C(t.taskStore),this.cachedAgentStore=new O(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;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(([o])=>this.deps.taskStore.get(o))),Promise.all(s.map(([,o])=>this.deps.agentStore.get(o.agent_id)))]);for(let o=0;o<s.length;o++){let[c,f]=s[o],w=i[o];if(!w||b(w.status)){this.abortControllers.delete(c),delete t.running[c],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 ${c})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(f.pid)){try{await this._handleRunFailure(c,f,"Process crashed unexpectedly");}catch{delete t.running[c],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 ${c})`,fatal:false});});}continue}let v=new Date(f.last_event_at).getTime(),l=r[o]?.config.stall_timeout_ms??this.deps.config.defaults.agent.stall_timeout_ms;if(e-v>l){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:f.run_id}),this.abortControllers.get(c)?.abort(),await this.deps.processManager.killWithGrace(f.pid,5e3);try{await this._handleRunFailure(c,f,"Agent stalled (no events)");}catch{delete t.running[c],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 ${c})`,fatal:false});});}}}let d=new Set(Object.values(t.running).map(o=>o.agent_id)),[n,u]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),m=n.filter(o=>o.status==="running"&&!d.has(o.id));m.length>0&&await Promise.all(m.map(o=>this.deps.agentService.setStatus(o.id,"idle")));let p=u.filter(o=>o.status==="in_progress"&&!t.running[o.id]);p.length>0&&await Promise.all(p.map(async o=>{try{await this.deps.taskService.updateStatus(o.id,"failed");}catch{o.status="failed",o.updated_at=new Date().toISOString(),await this.deps.taskStore.save(o).catch(c=>{this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`force-write orphaned task ${o.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:o.id});}));let a=[];t.retry_queue=t.retry_queue.filter(o=>e>=new Date(o.due_at).getTime()?(a.push(o.task_id),false):true);for(let o of a)await this.dispatchTask(o);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,d=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&&!d.has(f.id))??i.find(f=>!f.assignee&&!d.has(f.id));p&&d.add(p.id);let a$1=n.role??"general assistant",o=p?`[auto] ${n.name}: ${p.title.slice(0,60)}`:`[auto] ${n.name}: ${a$1.slice(0,60)}`,c=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:o,description:c,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(),d=new Map(r.map(a=>[a.id,a])),n=r.filter(a=>c(a.status)&&!d$1(a,d)&&!t.running[a.id]&&!t.claimed.has(a.id)).sort((a,o)=>{let c=(a.priority??3)-(o.priority??3);if(c!==0)return c;let f=(a.goalId?0:1)-(o.goalId?0:1);if(f!==0)return f;let w=o.updated_at??"",v=a.updated_at??"";return w<v?-1:w>v?1:0}).slice(0,i),u=new Set,m$1=r.filter(a=>a.status==="in_progress"&&a.scope?.length),p=new x(m$1.map(a=>a.scope));for(let a of n)if(a.scope?.length)if(p.overlapsAny(a.scope)){let o=m$1.find(c=>st(a.scope,c.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:a.id,overlappingTaskId:o?.id??a.id,patterns:a.scope}),u.add(a.id);}else p.add(a.scope);for(let a of n)if(!u.has(a.id))try{await this.dispatchTask(a.id);}catch(o){if(o instanceof m)try{let c=await this.deps.taskStore.get(a.id);if(c&&!b(c.status)){let f={...c,attempts:(c.attempts??0)+1,updated_at:new Date().toISOString()},w=e(f),v={...f,status:w};if(await this.deps.taskStore.save(v),w==="failed"){let y=r.map(l=>l.id===v.id?v:l);this.cachedTaskStore.invalidate(),await this.cascadeFailDependents(v.id,y,`dependency ${v.id} failed: ${o.message}`);}else {let y=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,y,o.message),await this.saveState();}}}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`dispatch task ${a.id}`,fatal:false});}}enqueueRetry(t,e,s,i,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()+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],d=0,n=new Set,u=false;for(;d<r.length;){let m=r[d++];if(n.has(m))continue;n.add(m);let p=i.get(m);if(!p)continue;let a=[];for(let c of p)b(c.status)||n.has(c.id)||(a.push({task:c,previousStatus:c.status}),r.push(c.id));if(a.length===0)continue;let o=new Date().toISOString();await Promise.all(a.map(({task:c})=>this.deps.taskStore.save({...c,status:"failed",updated_at:o})));for(let{task:c,previousStatus:f}of a)this.deps.eventBus.emit({type:"task:status_changed",taskId:c.id,from:f,to:"failed"}),this.deps.eventBus.emit({type:"task:cascade_failed",taskId:c.id,failedDependencyId:t,reason:s});u=true;}u&&this.cachedTaskStore.invalidate();}async dispatchTask(t){let e=this.state;if(e.running[t]){let i=e.running[t];throw new h(t,i.run_id,i.agent_id)}let s=await this.deps.taskService.get(t);e.claimed.add(t),await this.saveState();try{let i=await this.cachedAgentStore.list(),r=await this.deps.agentService.findBestAgent(s);if(!r){if(i.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),u=this.deps.config.prompt?.system_template??d$2,m=this.deps.config.prompt?.user_template??e$2,p=this.deps.config.prompt?.template,a=s.attempts+1,o;if(a>1){let S=await this.deps.runService.getLastFailedRunContext(s.id);S&&(o={previous_error:S.error,previous_output:S.output});}let c=s.goalId,[f,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]),y;if(v){let lt=(await this.cachedTaskStore.list()).filter(b=>b.goalId===c),dt=await this.deps.contextStore?.get(`${c}-progress`),ut=lt.map(b=>`[${b.status}] ${b.title}`);y={id:v.id,title:v.title,description:v.description,status:v.status,task_names:ut,progress:dt?.value};}let l=c$1(s,r,a,d,this.deps.config,{allAgents:i,retryContext:o,sharedContext:f,feedback:s.feedback,messages:w.length?w:void 0,goal:y}),g,k;if(p?g=await this.deps.templateEngine.render(p,l):(k=await this.deps.templateEngine.render(u,l),g=await this.deps.templateEngine.render(m,l)),this.deps.skillLoader&&r.config.skills?.length){let S=await this.deps.skillLoader.loadSkills(r.config.skills);S&&(k!==void 0?k=k+`
|
|
12
|
-
|
|
13
|
-
`+S:g=g+`
|
|
14
|
-
|
|
15
|
-
`+S);}let E=await this.deps.runService.create({taskId:s.id,agentId:r.id,attempt:a,prompt:g,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 M=this.deps.adapterRegistry.require(r.adapter),N=new AbortController;this.abortControllers.set(t,N);let U=M.execute({prompt:g,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:N.signal}),W=U.pid,K=new Date().toISOString();await this.deps.runService.start(E.id,W),this.unclaim(t),e.running[t]={run_id:E.id,agent_id:r.id,task_id:t,pid:W,started_at:K,last_event_at:K},await this.saveState(),this.collectEvents(U.events,E.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(i){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),i}}async collectEvents(t,e,s,i){let r,d,n,u,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:E,cache_read:_,cache_write:M}=a.tokens;r=a$1(g,k,{reasoning:E,cache_read:_,cache_write:M});}let l=a.data;l&&typeof l.result=="string"&&(d=l.result);}if(a.type==="output"){let l=a.data;if(l){let g=typeof l.text=="string"?l.text:typeof l.message=="string"?l.message:void 0;g?.trim()&&(n=g);}}if(a.type==="file_change"){let l=a.data;if(l&&Array.isArray(l.paths))for(let g of l.paths)typeof g=="string"&&m.add(g);else {let g=l&&typeof l.path=="string"?l.path:typeof a.data=="string"?a.data:String(a.data);m.add(g);}}let o=null;if(a.type==="tool_call"){let l=a.data;if(l){let g=l.input,k=typeof l.name=="string"?l.name:"";g&&typeof g.file_path=="string"&&/^(Write|Edit|MultiEdit|NotebookEdit)$/i.test(k)&&(o=g.file_path,m.add(o));}}let c=Tt(a.timestamp)?a.timestamp:new Date().toISOString(),f=a.type==="file_change"?(()=>{let l=a.data;return l&&typeof l.path=="string"?l.path:typeof a.data=="string"?a.data:String(a.data)})():null,w=ct(a.data,kt);a.data=void 0;let v={timestamp:c,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:w};await this.deps.runService.appendEvent(e,v),this.state?.running[s]&&(this.state.running[s].last_event_at=c,this.saveStateLazy());let y=ct(w,_t);a.type==="output"||a.type==="tool_call"?(this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:i,data:y}),o&&this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:o})):a.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:f}):a.type==="error"&&(a.errorKind&&(u=a.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:i,error:y,...a.errorKind?{errorKind:a.errorKind}:{}}));}let p=d??n;await this.handleRunSuccess(s,e,i,r,p,[...m]);}catch(p){let a=p instanceof Error?p.message:String(p),o=u??(p instanceof Error?p.errorKind:void 0),c=this.state?.running[s];c&&await this.handleRunFailure(s,c,a,o);}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,i,r,d){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,i,r,d))}async _handleRunSuccess(t,e,s,i,r,d){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let u=await this.deps.taskStore.get(t);if(!u)return;let m=d;(!m||m.length===0)&&u.proof?.branch&&(m=await this.deps.workspaceManager.getChangedFiles(u.proof.branch)),u.proof={...u.proof,agent_summary:r?.slice(0,2e3)??u.proof?.agent_summary,files_changed:m?.length?m:u.proof?.files_changed??[]},delete u.feedback,await this.deps.taskStore.save(u);let p=await this.deps.agentStore.get(s),o=u.labels?.includes(a)||p?.config.approval_policy==="auto",c=f(u,true,o);await this.deps.runService.finish(e,"succeeded",i);let f$1=n.running[t],w=f$1?Date.now()-new Date(f$1.started_at).getTime():0;f$1&&(n.stats.total_runtime_ms+=w),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)+w};if(i&&(v.tokens_used=(p?.stats.tokens_used??0)+i.total),await this.deps.agentService.updateStats(s,v).catch(l=>{this.deps.eventBus.emit({type:"orchestrator:error",error:l instanceof Error?l.message:String(l),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),u.proof?.branch)try{let l=await this.deps.workspaceManager.mergeBack(u.proof.branch);if(l.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:u.proof.branch}),await this.deps.workspaceManager.cleanup(t,u.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:u.proof.branch,conflictInfo:l.conflictInfo}),await this.forceTaskToReview(u,s,`MERGE CONFLICT: ${l.conflictInfo}`);return}}catch(l){let g=l instanceof Error?l.message:String(l);await this.forceTaskToReview(u,s,`MERGE ERROR: ${g}`);return}try{await this.deps.taskService.updateStatus(t,c);}catch(l){let g=l instanceof Error?l.message:String(l);this.deps.eventBus.emit({type:"orchestrator:error",error:g,context:`state machine validation failed for task ${t} -> ${c}, force-writing`,fatal:false}),u.status=c,u.updated_at=new Date().toISOString(),await this.deps.taskStore.save(u).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(l=>{this.deps.eventBus.emit({type:"orchestrator:error",error:l instanceof Error?l.message:String(l),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let y=await this.deps.agentStore.get(s);y&&(y.current_task=void 0,await this.deps.agentStore.save(y)),c==="review"&&u.review_criteria?.length?await this.runAutoReview(t,u.review_criteria,u.workspace??this.deps.projectRoot,o):c==="review"&&o&&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,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=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 u=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)+u});let m=e(d);if(await this.deps.taskService.updateStatus(t,m),m==="retrying"){let p=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,p,s),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:d.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+=u,d.proof?.branch&&await this.deps.workspaceManager.cleanup(t,d.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 d=await new R({cwd:s}).runAll(e),n=R.allPassed(d),u=await this.deps.taskStore.get(t);if(u&&(u.review_results=d,u.proof={...u.proof,test_results:R.formatReport(d),files_changed:u.proof?.files_changed??[]},await this.deps.taskStore.save(u),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:d}),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}),u.status="done",u.updated_at=new Date().toISOString(),await this.deps.taskStore.save(u).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(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(i),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();}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(d=>{this.deps.eventBus.emit({type:"orchestrator:error",error:d instanceof Error?d.message:String(d),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 Tt(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};
|