@oxgeneral/orch 1.0.19 → 1.0.21

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,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$2}from'./chunk-N4OXN2HW.js';import {c as c$1,b as b$3}from'./chunk-HXOMNULD.js';import {b as b$2,a as a$1}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {b}from'./chunk-6E6DC7OE.js';import {b as b$1,c,j as j$1,d,e,l as l$1,f as f$1,h,i as i$1,g as g$1,k as k$1}from'./chunk-ZMLF5HI5.js';import {c as c$2,l,j as j$2,k,g,f,i}from'./chunk-LRYVT4D4.js';import Q from'path';import V,{mkdir}from'fs/promises';import {createReadStream}from'fs';import {homedir}from'os';import {nanoid}from'nanoid';var P={tui:{activity_filter:"all",notifications:{toast:true,bell:false}}};var w=class{indexPath;dir;ext;itemPath;fileFilter;readItemFn;mutex=Promise.resolve();insideMutex=false;constructor(t){this.dir=t.dir,this.ext=t.ext,this.itemPath=t.itemPath,this.indexPath=Q.join(t.dir,"_index.json"),this.fileFilter=t.fileFilter??(()=>true),t.readItem?this.readItemFn=t.readItem:t.ext===".yml"?this.readItemFn=e=>b$1(e):this.readItemFn=e=>d(e);}async readIndex(){try{let t=await d(this.indexPath);if(Array.isArray(t))return t}catch{}return this.rebuildIndex()}async rebuildIndex(){await j$1(this.dir);let t=await l$1(this.dir,this.ext),e=await Promise.all(t.filter(this.fileFilter).map(r=>{let a=r.replace(this.ext,"");return this.readItemFn(this.itemPath(a))})),s=[];for(let r of e)r!=null&&s.push(r);return this.insideMutex?await this.writeIndexUnsafe(s):await this.withMutex(()=>this.writeIndexUnsafe(s)),s}async writeIndex(t){return this.withMutex(()=>this.writeIndexUnsafe(t))}async updateIndex(t){return this.withMutex(async()=>{let e=await this.readIndex(),s=t(e);await this.writeIndexUnsafe(s);})}async writeIndexUnsafe(t){await j$1(this.dir),await e(this.indexPath,t);}withMutex(t){let e,s=new Promise(a=>{e=a;}),r=this.mutex;return this.mutex=s,r.then(async()=>{this.insideMutex=true;try{return await t()}finally{this.insideMutex=false,e();}})}};var j=class{constructor(t){this.paths=t;this.index=new w({dir:t.tasksDir,ext:".yml",itemPath:e=>t.taskPath(e)});}index;async list(t){return (await this.index.readIndex()).filter(r=>r!==null&&(!t?.status||r.status===t.status)&&(!t?.goalId||r.goalId===t.goalId)).sort((r,a)=>{let n=pt(r.status)-pt(a.status);if(n!==0)return n;let i=a.updated_at??"",o=r.updated_at??"";return i<o?-1:i>o?1:0})}async get(t){return b$1(this.paths.taskPath(t))}async save(t){await j$1(this.paths.tasksDir),await c(this.paths.taskPath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async delete(t){try{await V.unlink(this.paths.taskPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}};function pt(m){return {in_progress:0,retrying:1,review:2,todo:3,done:4,failed:5,cancelled:6}[m]}var M=class{constructor(t){this.paths=t;this.index=new w({dir:t.agentsDir,ext:".yml",itemPath:e=>t.agentPath(e)});}index;async list(){return this.index.readIndex()}async get(t){return b$1(this.paths.agentPath(t))}async getByName(t){return (await this.list()).find(s=>s.name===t)??null}async save(t){await j$1(this.paths.agentsDir),await c(this.paths.agentPath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async delete(t){try{await V.unlink(this.paths.agentPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}};var R=class{constructor(t){this.paths=t;}async save(t){await j$1(this.paths.runsDir),await e(this.paths.runPath(t.id),t);}async get(t){return d(this.paths.runPath(t))}async listAll(){return this.listFiltered(()=>true)}async listForTask(t){return this.listFiltered(e=>e.task_id===t)}async listForAgent(t){return this.listFiltered(e=>e.agent_id===t)}async appendEvent(t,e){await j$1(this.paths.runsDir),await f$1(this.paths.runEventsPath(t),e);}async readEvents(t){return h(this.paths.runEventsPath(t))}async readEventsTail(t,e){return i$1(this.paths.runEventsPath(t),e)}closeRunEvents(t){g$1(this.paths.runEventsPath(t));}async*streamEvents(t,e){let s=this.paths.runEventsPath(t),r=Date.now()+3e4;for(;!e?.aborted&&Date.now()<r&&!await k$1(s);)await new Promise(i=>setTimeout(i,100));if(e?.aborted||Date.now()>=r)return;let a=createReadStream(s),{readLines:n}=await import('./process-manager-33H27MQF.js');try{for await(let i of n(a)){if(e?.aborted)break;if(i.trim())try{yield JSON.parse(i);}catch{process.stderr.write(`[RunStore] skipping corrupt JSONL line: ${i.slice(0,200)}
3
- `);}}}finally{a.destroy();}}async listFiltered(t){await j$1(this.paths.runsDir);let e=await l$1(this.paths.runsDir,".json"),s=64,r=[];for(let a=0;a<e.length;a+=s){let n=e.slice(a,a+s),i=await Promise.all(n.map(o=>{let c=o.endsWith(".json")?o.slice(0,-5):o;return d(this.paths.runPath(c))}));for(let o of i)o!==null&&t(o)&&r.push(o);}return r.sort((a,n)=>new Date(n.started_at).getTime()-new Date(a.started_at).getTime())}};var W={version:1,onboardingCompleted:false,running:{},claimed:new Set,retry_queue:[],stats:{total_runs:0,total_tasks_completed:0,total_tasks_failed:0,total_tokens:{input:0,output:0,reasoning:0,total:0,cache_read:0,cache_write:0},total_runtime_ms:0}};var D=class{constructor(t){this.paths=t;}async read(){let t=await d(this.paths.statePath);if(!t)return structuredClone(W);let e=structuredClone(W);return {version:t.version??e.version,pid:t.pid,started_at:t.started_at,onboardingCompleted:typeof t.onboardingCompleted=="boolean"?t.onboardingCompleted:false,running:t.running&&typeof t.running=="object"?t.running:e.running,claimed:Array.isArray(t.claimed)?new Set(t.claimed):new Set(e.claimed),retry_queue:Array.isArray(t.retry_queue)?t.retry_queue:e.retry_queue,stats:{total_runs:t.stats?.total_runs??e.stats.total_runs,total_tasks_completed:t.stats?.total_tasks_completed??e.stats.total_tasks_completed,total_tasks_failed:t.stats?.total_tasks_failed??e.stats.total_tasks_failed,total_tokens:{...e.stats.total_tokens,...t.stats?.total_tokens??{}},total_runtime_ms:t.stats?.total_runtime_ms??e.stats.total_runtime_ms}}}async write(t){let e$1={...t,claimed:Array.from(t.claimed)};await e(this.paths.statePath,e$1);}};var O=class{constructor(t){this.paths=t;}async read(){let t=await b$1(this.paths.configPath);return ht(a$2,t??{})}async write(t){await c(this.paths.configPath,t);}async get(t){let e=await this.read();return Ct(e,t)}async set(t,e){let s=await this.read();jt(s,t,e),await this.write(s);}};function Ct(m,t){let e=t.split("."),s=m;for(let r of e){if(s==null||typeof s!="object")return;s=s[r];}return s}function jt(m,t,e){let s=t.split("."),r=m;for(let n=0;n<s.length-1;n++){let i=s[n];(typeof r[i]!="object"||r[i]===null)&&(r[i]={}),r=r[i];}let a=s[s.length-1];r[a]=e;}function ht(m,t){let e={...m};for(let s of Object.keys(t)){let r=t[s],a=e[s];r!=null&&typeof r=="object"&&!Array.isArray(r)&&typeof a=="object"&&a!==null&&!Array.isArray(a)?e[s]=ht(a,r):e[s]=r;}return e}var yt=Q.join(homedir(),".orchestry"),ft=Q.join(yt,"global.yml"),G=class{async read(){let t=await b$1(ft);if(!t)return {...P,tui:{...P.tui,notifications:{...P.tui.notifications}}};let e=t.tui,s=e?.notifications;return {tui:{activity_filter:e?.activity_filter??P.tui.activity_filter,notifications:{toast:typeof s?.toast=="boolean"?s.toast:P.tui.notifications.toast,bell:typeof s?.bell=="boolean"?s.bell:P.tui.notifications.bell}}}}async write(t){await mkdir(yt,{recursive:true}),await c(ft,t);}async set(t,e){let s=await this.read();s.tui[t]=e,await this.write(s);}};var L=class m{constructor(t){this.paths=t;this.index=new w({dir:t.contextDir,ext:".json",itemPath:e=>t.contextPath(e),fileFilter:e=>e!=="_index.json"});}index;async get(t){let e=await d(this.paths.contextPath(t));return e?vt(e)?(await this.delete(t),null):e:null}static MAX_TTL_MS=720*60*60*1e3;async set(t,e$1,s){if(s!==void 0&&(!Number.isFinite(s)||s<=0||s>m.MAX_TTL_MS))throw new Error(`TTL must be a positive number up to ${m.MAX_TTL_MS}ms (30 days)`);await j$1(this.paths.contextDir);let r=new Date().toISOString(),a=await d(this.paths.contextPath(t)),n={key:t,value:e$1,created_at:a?.created_at??r,updated_at:r,ttl_ms:s,expires_at:s?new Date(Date.now()+s).toISOString():void 0};await e(this.paths.contextPath(t),n),await this.index.updateIndex(i=>{let o=i.filter(c=>c.key!==t);return o.push(n),o});}async delete(t){try{await V.unlink(this.paths.contextPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.key!==t));}async list(){let t=await this.index.readIndex(),e=[],s=[];for(let r of t)vt(r)?e.push(r):s.push(r);return e.length>0&&(await Promise.all(e.map(r=>this.deleteFile(r.key))),await this.index.writeIndex(s)),s.sort((r,a)=>r.key.localeCompare(a.key))}async getAll(){let t=await this.list(),e={};for(let s of t)e[s.key]=s.value;return e}async deleteFile(t){try{await V.unlink(this.paths.contextPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}};function vt(m){return m.expires_at?new Date(m.expires_at).getTime()<Date.now():false}var B=class{constructor(t){this.paths=t;this.index=new w({dir:t.messagesDir,ext:".json",itemPath:e=>t.messagePath(e),fileFilter:e=>e!=="_index.json"});}index;async save(t){await j$1(this.paths.messagesDir),await e(this.paths.messagePath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async get(t){return d(this.paths.messagePath(t))}async list(){return (await this.index.readIndex()).filter(e=>e!==null).sort((e,s)=>e.created_at.localeCompare(s.created_at))}async listPending(t){let e=await this.list(),s=Date.now();return e.filter(r=>r.status!=="pending"||r.expires_at&&new Date(r.expires_at).getTime()<s?false:r.to_agent_id===t)}async markDelivered(t){let e$1=await this.get(t);e$1&&(e$1.status="delivered",e$1.delivered_at=new Date().toISOString(),await e(this.paths.messagePath(t),e$1),await this.index.updateIndex(s=>{let r=s.filter(a=>a.id!==t);return r.push(e$1),r}));}async delete(t){try{await V.unlink(this.paths.messagePath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}async purgeExpired(){let t=await this.list(),e=Date.now(),s=t.filter(a=>{let n=a.expires_at&&new Date(a.expires_at).getTime()<e,i=a.delivered_at&&e-new Date(a.delivered_at).getTime()>36e5;return n||i}),r=new Set(s.map(a=>a.id));return await Promise.all(s.map(async a=>{try{await V.unlink(this.paths.messagePath(a.id));}catch(n){if(n.code!=="ENOENT")throw n}})),await this.index.updateIndex(a=>a.filter(n=>!r.has(n.id))),s.length}};var F=class{constructor(t){this.paths=t;this.index=new w({dir:t.goalsDir,ext:".yml",itemPath:e=>t.goalPath(e)});}index;async list(t){return (await this.index.readIndex()).filter(r=>r!==null&&(!t?.status||r.status===t.status)).sort((r,a)=>{let n=c$1[r.status]-c$1[a.status];if(n!==0)return n;let i=a.updated_at??"",o=r.updated_at??"";return i<o?-1:i>o?1:0})}async get(t){return b$1(this.paths.goalPath(t))}async save(t){await j$1(this.paths.goalsDir),await c(this.paths.goalPath(t.id),t),await this.index.updateIndex(e=>{let s=e.filter(r=>r.id!==t.id);return s.push(t),s});}async delete(t){try{await V.unlink(this.paths.goalPath(t));}catch(e){if(e.code!=="ENOENT")throw e}await this.index.updateIndex(e=>e.filter(s=>s.id!==t));}};var N=class{constructor(t){this.paths=t;}async save(t){await j$1(this.paths.teamsDir),await c(this.paths.teamPath(t.id),t);}async get(t){return b$1(this.paths.teamPath(t))}async getByName(t){return (await this.list()).find(s=>s.name===t)??null}async list(){await j$1(this.paths.teamsDir);let t=await l$1(this.paths.teamsDir,".yml");return (await Promise.all(t.map(s=>b$1(this.paths.teamPath(s.replace(".yml","")))))).filter(s=>s!==null)}async delete(t){try{await V.unlink(this.paths.teamPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}};var $=class{handlers=new Map;wildcardHandlers=new Set;maxListeners=10;warnedTypes=new Set;setMaxListeners(t){this.maxListeners=t;}getMaxListeners(){return this.maxListeners}listenerCount(t){return this.handlers.get(t)?.size??0}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set);let s=this.handlers.get(t);return s.add(e),this.maxListeners>0&&s.size>this.maxListeners&&!this.warnedTypes.has(t)&&(this.warnedTypes.add(t),console.warn(`EventBus: possible memory leak detected. ${s.size} listeners added for "${t}". Use setMaxListeners() to increase limit if this is intentional.`)),()=>this.off(t,e)}once(t,e){let s=r=>{this.off(t,s),e(r);};return this.on(t,s)}off(t,e){this.handlers.get(t)?.delete(e);}emit(t){let e=this.handlers.get(t.type);e&&this.dispatchToSet(e,t,"handler"),this.dispatchToSet(this.wildcardHandlers,t,"wildcard handler");}dispatchToSet(t,e,s){for(let r of t)try{r(e);}catch(a){console.error(`EventBus ${s} error for "${e.type}":`,a);}}onAny(t){return this.wildcardHandlers.add(t),this.maxListeners>0&&this.wildcardHandlers.size>this.maxListeners&&!this.warnedTypes.has("*")&&(this.warnedTypes.add("*"),console.warn(`EventBus: possible memory leak detected. ${this.wildcardHandlers.size} wildcard listeners added. Use setMaxListeners() to increase limit if this is intentional.`)),()=>{this.wildcardHandlers.delete(t);}}clear(){this.handlers.clear(),this.wildcardHandlers.clear(),this.warnedTypes.clear();}};var U=class{constructor(t,e,s,r){this.taskStore=t;this.eventBus=e;this.config=s;this.paths=r;}async create(t){if(!t.title.trim())throw new c$2("Task title is required");let e=t.priority??this.config.defaults.task.priority;if(!Number.isInteger(e)||e<1||e>4)throw new c$2("Priority must be an integer between 1 and 4");if(t.depends_on?.length){let n=(await Promise.all(t.depends_on.map(async i=>({depId:i,exists:!!await this.taskStore.get(i)})))).filter(i=>!i.exists).map(i=>i.depId);if(n.length>0)throw new c$2(`Unknown depends_on task ID(s): ${n.join(", ")}`)}let s=new Date().toISOString(),r={id:`tsk_${nanoid(7)}`,title:t.title.trim(),description:t.description?.trim()??"",status:"todo",priority:e,assignee:t.assignee,labels:t.labels??[],depends_on:t.depends_on??[],created_at:s,updated_at:s,attempts:0,max_attempts:t.max_attempts??this.config.defaults.task.max_attempts,workspace_mode:t.workspace_mode,review_criteria:t.review_criteria,scope:t.scope,goalId:t.goalId};if(t.attachments?.length&&this.paths){let a=await this.copyAttachments(r.id,t.attachments);r.attachments=a;}return await this.taskStore.save(r),this.eventBus.emit({type:"task:created",task:r}),r}async list(t){return this.taskStore.list(t)}async get(t){let e=await this.taskStore.get(t);if(!e)throw new f(t);return e}async updateStatus(t,e){let s=await this.get(t),r=s.status;if(!a$1(r,e))throw new i(t,r,e);return s.status=e,s.updated_at=new Date().toISOString(),await this.taskStore.save(s),this.eventBus.emit({type:"task:status_changed",taskId:t,from:r,to:e}),s}async assign(t,e){let s=await this.get(t);return s.assignee=e,s.updated_at=new Date().toISOString(),await this.taskStore.save(s),this.eventBus.emit({type:"task:assigned",taskId:t,agentId:e}),s}async cancel(t){let e=await this.get(t);if(b$2(e.status))throw new i(t,e.status,"cancelled");return this.updateStatus(t,"cancelled")}async retry(t){let e=await this.get(t);if(e.status!=="failed"&&e.status!=="cancelled")throw new i(t,e.status,"todo");let s=e.status;return e.status="todo",e.attempts=0,e.updated_at=new Date().toISOString(),await this.taskStore.save(e),this.eventBus.emit({type:"task:status_changed",taskId:t,from:s,to:"todo"}),e}async reject(t,e){let s=await this.get(t);if(s.status!=="review")throw new i(t,s.status,"todo");let r=s.status;return s.status="todo",s.attempts=0,s.feedback=e,s.updated_at=new Date().toISOString(),await this.taskStore.save(s),this.eventBus.emit({type:"task:status_changed",taskId:t,from:r,to:"todo"}),s}async update(t,e){let s=await this.get(t);if(e.title!==void 0){if(!e.title.trim())throw new c$2("Task title cannot be empty");s.title=e.title.trim();}if(e.description!==void 0&&(s.description=e.description.trim()),e.priority!==void 0){if(!Number.isInteger(e.priority)||e.priority<1||e.priority>4)throw new c$2("Priority must be an integer between 1 and 4");s.priority=e.priority;}if(e.labels!==void 0&&(s.labels=e.labels),e.attachments?.length&&this.paths){let r=await this.copyAttachments(t,e.attachments);s.attachments=[...s.attachments??[],...r];}return s.updated_at=new Date().toISOString(),await this.taskStore.save(s),s}async delete(t){if((await this.get(t)).status==="in_progress")throw new c$2("Cannot delete a running task. Cancel it first.");if(await this.taskStore.delete(t),this.paths){let s=this.paths.taskAttachmentsDir(t);await V.rm(s,{recursive:true,force:true});}}getAttachmentPath(t,e){if(!this.paths)throw new c$2("Paths not configured");return Q.join(this.paths.taskAttachmentsDir(t),e)}async copyAttachments(t,e){if(!this.paths)return [];let s=this.paths.taskAttachmentsDir(t);return await j$1(s),await Promise.all(e.map(async a=>{try{await V.access(a);}catch{throw new c$2(`Attachment file not found: ${a}`)}})),await Promise.all(e.map(async a=>{let n=Q.basename(a);return await V.copyFile(a,Q.join(s,n)),n}))}async incrementAttempts(t){let e=await this.get(t);return e.attempts+=1,e.updated_at=new Date().toISOString(),await this.taskStore.save(e),e}};var J=class{constructor(t,e,s,r){this.agentStore=t;this.stateStore=e;this.eventBus=s;this.config=r;}async create(t){if(!t.name.trim())throw new c$2("Agent name is required");if(await this.agentStore.getByName(t.name))throw new c$2(`Agent "${t.name}" already exists`);let s={id:`agt_${nanoid(7)}`,name:t.name.trim(),adapter:t.adapter||this.config.defaults.agent.adapter,role:t.role,config:{command:t.command,model:t.model,effort:t.effort,approval_policy:t.approval_policy??this.config.defaults.agent.approval_policy,max_turns:t.max_turns??this.config.defaults.agent.max_turns,timeout_ms:t.timeout_ms??this.config.defaults.agent.timeout_ms,stall_timeout_ms:t.stall_timeout_ms??this.config.defaults.agent.stall_timeout_ms,env:t.env,system_prompt:t.system_prompt,workspace_mode:t.workspace_mode,skills:t.skills},status:"idle",stats:{tasks_completed:0,tasks_failed:0,total_runs:0,total_runtime_ms:0}};return await this.agentStore.save(s),s}async list(){return this.agentStore.list()}async get(t){let e=await this.agentStore.get(t);if(!e)throw new g(t);return e}async remove(t){let e=await this.get(t);if(e.status==="running"){let s=await this.stateStore.read();if(Object.values(s.running).some(a=>a.agent_id===t))throw new c$2("Cannot remove a running agent. Stop it first.");e.status="idle",await this.agentStore.save(e);}await this.agentStore.delete(t);}async update(t,e){let s=await this.get(t);if(e.name!==void 0){if(!e.name.trim())throw new c$2("Agent name cannot be empty");let r=await this.agentStore.getByName(e.name.trim());if(r&&r.id!==t)throw new c$2(`Agent "${e.name}" already exists`);s.name=e.name.trim();}return e.role!==void 0&&(s.role=e.role||void 0),e.model!==void 0&&(s.config.model=e.model||void 0),e.effort!==void 0&&(s.config.effort=e.effort||void 0),e.approval_policy!==void 0&&(s.config.approval_policy=e.approval_policy),await this.agentStore.save(s),s}async disable(t){return this.setStatus(t,"disabled")}async enable(t){return this.setStatus(t,"idle")}async setAutonomous(t,e){let s=await this.get(t);return s.autonomous=e,await this.agentStore.save(s),this.eventBus.emit({type:"agent:autonomous_toggled",agentId:t,autonomous:e}),s}async setStatus(t,e){let s=await this.get(t);return s.status=e,await this.agentStore.save(s),s}async updateStats(t,e){let s=await this.get(t);return Object.assign(s.stats,e),await this.agentStore.save(s),s}async findBestAgent(t){let e=await this.agentStore.list(),s=e.filter(n=>n.status==="idle");if(s.length===0)return null;if(t.assignee){let n=e.find(i=>i.id===t.assignee);return n&&n.status==="idle"?n:null}let r=t.labels?.length?t.labels.map(n=>n.toLowerCase()):void 0,a=s.map(n=>{let i=0;if(r&&n.config.skills?.length){let c=new Set(n.config.skills.map(d=>d.toLowerCase()));for(let d of r)c.has(d)&&(i+=50);}if(r&&n.role){let c=n.role.toLowerCase();r.some(d=>c.includes(d))&&(i+=30);}n.status==="idle"&&(i+=20);let o=n.stats.tasks_completed+n.stats.tasks_failed;return o>0&&(i+=Math.round(n.stats.tasks_completed/o*10)),{agent:n,score:i}});return a.sort((n,i)=>i.score-n.score),a[0]?.agent??null}};var H=class{constructor(t,e){this.runStore=t;this.eventBus=e;}async create(t){let e={id:`run_${nanoid(7)}`,task_id:t.taskId,agent_id:t.agentId,attempt:t.attempt,status:"preparing",started_at:new Date().toISOString(),workspace_path:t.workspacePath,prompt:t.prompt};return await this.runStore.save(e),e}async get(t){return this.runStore.get(t)}async start(t,e){let s=await this.runStore.get(t);if(!s)throw new Error(`Run not found: ${t}`);return s.status="running",s.pid=e,await this.runStore.save(s),this.eventBus.emit({type:"agent:started",agentId:s.agent_id,taskId:s.task_id,runId:t}),s}async finish(t,e,s,r){let a=await this.runStore.get(t);if(!a)throw new Error(`Run not found: ${t}`);return a.status=e,a.finished_at=new Date().toISOString(),a.tokens=s,a.error=r,await this.runStore.save(a),this.eventBus.emit({type:"agent:completed",runId:t,agentId:a.agent_id,success:e==="succeeded"}),a}async appendEvent(t,e){await this.runStore.appendEvent(t,e);}async listAll(){return this.runStore.listAll()}async listForTask(t){return this.runStore.listForTask(t)}async listForAgent(t){return this.runStore.listForAgent(t)}async readEvents(t){return this.runStore.readEvents(t)}async readEventsTail(t,e){return this.runStore.readEventsTail(t,e)}async getLastFailedRunContext(t){let s=(await this.runStore.listForTask(t)).filter(n=>n.status==="failed").sort((n,i)=>(i.finished_at??"").localeCompare(n.finished_at??""))[0];if(!s)return null;let r=s.error??"Unknown error",a="";try{a=(await this.runStore.readEventsTail(s.id,50)).filter(i=>i.type==="agent_output"||i.type==="error").map(i=>typeof i.data=="string"?i.data:JSON.stringify(i.data)).join(`
4
- `);}catch{}return {error:r,output:a}}};var q=class{constructor(t,e,s,r){this.messageStore=t;this.agentStore=e;this.teamStore=s;this.eventBus=r;}async send(t){if(!t.body.trim())throw new c$2("Message body is required");let e=t.ttl_ms??864e5;if(e<=0||e>6048e5)throw new c$2(`TTL must be between 1ms and ${6048e5}ms`);if(!await this.agentStore.get(t.from_agent_id)&&t.from_agent_id!=="cli")throw new c$2(`Sender agent not found: ${t.from_agent_id}`);let r=new Date,a={channel:t.channel,from_agent_id:t.from_agent_id,subject:(t.subject||"(no subject)").slice(0,200),body:t.body.slice(0,4e3),created_at:r.toISOString(),expires_at:new Date(r.getTime()+e).toISOString(),status:"pending",team_id:t.team_id,reply_to:t.reply_to},n=[];if(t.channel==="broadcast"){let i=await this.agentStore.list();if(t.team_id){let d=await this.teamStore.get(t.team_id);if(d){let k=new Set(d.members.map(v=>v.agent_id));i=i.filter(v=>k.has(v.id));}}let c=i.filter(d=>d.id!==t.from_agent_id&&d.status!=="disabled").map(d=>({...a,id:`msg_${nanoid(7)}`,to_agent_id:d.id}));await Promise.all(c.map(d=>this.messageStore.save(d)));for(let d of c)n.push(d),this.emitSent(d);}else if(t.channel==="lead"){if(!t.team_id)throw new c$2("team_id is required for lead channel");let i=await this.teamStore.get(t.team_id);if(!i)throw new c$2(`Team not found: ${t.team_id}`);let o={...a,id:`msg_${nanoid(7)}`,to_agent_id:i.lead_agent_id};await this.messageStore.save(o),n.push(o),this.emitSent(o);}else {if(!t.to_agent_id)throw new c$2("to_agent_id is required for direct messages");if(!await this.agentStore.get(t.to_agent_id))throw new c$2(`Recipient agent not found: ${t.to_agent_id}`);let o={...a,id:`msg_${nanoid(7)}`,to_agent_id:t.to_agent_id};await this.messageStore.save(o),n.push(o),this.emitSent(o);}return n}async drainMailbox(t,e){let s=await this.messageStore.listPending(t);await Promise.all(s.map(r=>this.messageStore.markDelivered(r.id)));for(let r of s)this.eventBus.emit({type:"message:delivered",messageId:r.id,toAgentId:t,taskId:e});return s}async listAll(){return this.messageStore.list()}async listPendingForAgent(t){return this.messageStore.listPending(t)}async listForAgent(t){return (await this.messageStore.list()).filter(s=>s.to_agent_id===t||s.from_agent_id===t)}async purgeExpired(){return this.messageStore.purgeExpired()}emitSent(t){this.eventBus.emit({type:"message:sent",messageId:t.id,fromAgentId:t.from_agent_id,toAgentId:t.to_agent_id,channel:t.channel});}};var $t={active:["paused","achieved","abandoned"],paused:["active","abandoned"],achieved:[],abandoned:[]},Y=class{constructor(t,e,s,r,a){this.goalStore=t;this.eventBus=e;this.agentService=s;this.taskService=r;this.contextStore=a;}async create(t){if(!t.title.trim())throw new c$2("Goal title is required");let e=new Date().toISOString(),s={id:`goal_${nanoid(7)}`,title:t.title.trim(),description:t.description?.trim()??"",status:"active",assignee:t.assignee,created_at:e,updated_at:e};return await this.goalStore.save(s),this.eventBus.emit({type:"goal:created",goalId:s.id,title:s.title}),s.assignee&&await this.enableAutonomous(s.assignee),s}async list(t){return this.goalStore.list(t)}async get(t){let e=await this.goalStore.get(t);if(!e)throw new j$2(t);return e}async updateStatus(t,e,s){let r=await this.get(t),a=r.status;if(!$t[a].includes(e))throw new c$2(`Cannot transition goal from '${a}' to '${e}'`);if(e==="achieved"&&this.taskService){let i=(await this.taskService.list({goalId:t})).filter(o=>!b$2(o.status));if(i.length>0)if(s?.force){let o=i.filter(d=>d.status!=="in_progress"),c=i.filter(d=>d.status==="in_progress");if(await Promise.all(o.map(d=>this.taskService.cancel(d.id).catch(()=>{}))),c.length>0){let d=c.map(k=>`${k.id} (in_progress)`).join(", ");throw new k(t,c.length,d)}}else {let o=i.map(c=>`${c.id} (${c.status})`).join(", ");throw new k(t,i.length,o)}}return r.status=e,r.updated_at=new Date().toISOString(),await this.goalStore.save(r),this.eventBus.emit({type:"goal:status_changed",goalId:t,from:a,to:e}),r.assignee&&(e==="paused"?(await this.maybeDisableAutonomous(r.assignee),await this.cancelPendingAutonomousTasks(r.assignee)):e==="active"&&a==="paused"?await this.enableAutonomous(r.assignee):b$3(e)&&await this.maybeDisableAutonomous(r.assignee)),r}async update(t,e){let s=await this.get(t),r=s.assignee;if(e.title!==void 0){if(!e.title.trim())throw new c$2("Goal title cannot be empty");s.title=e.title.trim();}e.description!==void 0&&(s.description=e.description.trim()),e.assignee!==void 0&&(s.assignee=e.assignee||void 0),s.updated_at=new Date().toISOString(),await this.goalStore.save(s),this.eventBus.emit({type:"goal:updated",goalId:t});let a=s.assignee;if(a!==r){let n=[];a&&n.push(this.enableAutonomous(a)),r&&n.push(this.maybeDisableAutonomous(r)),await Promise.all(n);}return s}async delete(t){let e=await this.get(t),{assignee:s}=e;await this.goalStore.delete(t),this.eventBus.emit({type:"goal:deleted",goalId:t}),s&&await this.maybeDisableAutonomous(s);}async listTasksForGoal(t){return this.taskService?.list({goalId:t})??[]}async getProgressReport(t){return this.contextStore?(await this.contextStore.get(`${t}-progress`))?.value:void 0}async enableAutonomous(t){if(this.agentService)try{await this.agentService.setAutonomous(t,!0);}catch{}}async hasActiveGoalsForAgent(t){return (await this.goalStore.list({status:"active"})).some(s=>s.assignee===t)}async cancelPendingAutonomousTasks(t){if(this.taskService)try{let[e,s]=await Promise.all([this.taskService.list({status:"todo"}),this.taskService.list({status:"retrying"})]),r=[...e,...s].filter(a$1=>a$1.assignee===t&&a$1.labels?.includes(a));await Promise.all(r.map(a=>this.taskService.cancel(a.id).catch(()=>{})));}catch{}}async maybeDisableAutonomous(t){if(this.agentService)try{await this.hasActiveGoalsForAgent(t)||await this.agentService.setAutonomous(t,!1);}catch{}}};var kt={auto_claim:true,message_ttl_ms:864e5};var z=class{constructor(t,e,s,r){this.teamStore=t;this.agentStore=e;this.taskStore=s;this.eventBus=r;}async create(t){if(!t.name.trim())throw new c$2("Team name is required");if(!await this.agentStore.get(t.lead_agent_id))throw new c$2(`Lead agent not found: ${t.lead_agent_id}`);if(await this.teamStore.getByName(t.name.trim()))throw new c$2(`Team "${t.name}" already exists`);let r=new Date().toISOString(),a={agent_id:t.lead_agent_id,role:"lead",joined_at:r},n=[];for(let o of t.member_agent_ids??[]){if(o===t.lead_agent_id)continue;if(!await this.agentStore.get(o))throw new c$2(`Member agent not found: ${o}`);n.push({agent_id:o,role:"member",joined_at:r});}let i={id:`team_${nanoid(7)}`,name:t.name.trim(),description:t.description,status:"active",members:[a,...n],task_pool:[],lead_agent_id:t.lead_agent_id,created_at:r,updated_at:r,config:{...kt,...t.config??{}}};await this.teamStore.save(i),this.eventBus.emit({type:"team:created",teamId:i.id,name:i.name,leadAgentId:i.lead_agent_id});for(let o of n)this.eventBus.emit({type:"team:member_joined",teamId:i.id,agentId:o.agent_id});return i}async get(t){let e=await this.teamStore.get(t);if(!e)throw new l(t);return e}async list(){return this.teamStore.list()}async join(t,e){let s=await this.get(t);if(s.members.some(a=>a.agent_id===e))throw new c$2(`Agent ${e} is already a member of team ${t}`);if(!await this.agentStore.get(e))throw new c$2(`Agent not found: ${e}`);return s.members.push({agent_id:e,role:"member",joined_at:new Date().toISOString()}),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:member_joined",teamId:t,agentId:e}),s}async leave(t,e){let s=await this.get(t);if(e===s.lead_agent_id)throw new c$2("Lead cannot leave team. Disband the team or transfer lead first.");return s.members=s.members.filter(r=>r.agent_id!==e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:member_left",teamId:t,agentId:e}),s}async addTask(t,e){let s=await this.get(t);if(!await this.taskStore.get(e))throw new c$2(`Task not found: ${e}`);return s.task_pool.includes(e)||(s.task_pool.push(e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),this.eventBus.emit({type:"team:task_added",teamId:t,taskId:e})),s}async removeTask(t,e){let s=await this.get(t);return s.task_pool=s.task_pool.filter(r=>r!==e),s.updated_at=new Date().toISOString(),await this.teamStore.save(s),s}async setLead(t,e){let s=await this.get(t),r=s.members.find(n=>n.agent_id===e);if(!r)throw new c$2(`Agent ${e} is not a member of team ${t}`);let a=s.members.find(n=>n.agent_id===s.lead_agent_id);return a&&(a.role="member"),r.role="lead",s.lead_agent_id=e,s.updated_at=new Date().toISOString(),await this.teamStore.save(s),s}async disband(t){let e=await this.get(t);e.status="disbanded",e.updated_at=new Date().toISOString(),await this.teamStore.save(e),this.eventBus.emit({type:"team:disbanded",teamId:t});}async findTeamForAgent(t){return (await this.teamStore.list()).find(s=>s.status==="active"&&s.members.some(r=>r.agent_id===t))??null}};async function Jt(m){let t=new b(m.projectRoot),e=new O(t),s=new G,[,r]=await Promise.all([t.requireInit(),e.read()]),a=new j(t),n=new M(t),i=new R(t),o=new D(t),c=new L(t),d=new B(t),k=new F(t),v=new N(t),_=new $,b$1=new U(a,_,r,t),h=new J(n,o,_,r),I=new H(i,_),A=new q(d,n,v,_),E=new Y(k,_,h,b$1,c),S=new z(v,n,a,_);return {context:m,paths:t,config:r,taskStore:a,agentStore:n,runStore:i,stateStore:o,configStore:e,globalConfigStore:s,globalConfig:P,contextStore:c,messageStore:d,goalStore:k,teamStore:v,eventBus:_,taskService:b$1,agentService:h,runService:I,messageService:A,goalService:E,teamService:S}}async function Ht(m){let t=await Jt(m),e=await t.globalConfigStore.read();t.globalConfig=e;let[{ProcessManager:s},{AdapterRegistry:r},{ClaudeAdapter:a},{CodexAdapter:n},{CursorAdapter:i},{ShellAdapter:o},{OpenCodeAdapter:c},{WorkspaceManager:d},{LiquidTemplateEngine:k},{SkillLoader:v},{Orchestrator:_},{DoctorService:b}]=await Promise.all([import('./process-manager-33H27MQF.js'),import('./registry-BO2PPRNG.js'),import('./claude-PH7LT3OH.js'),import('./codex-URQN4JLZ.js'),import('./cursor-EMX3ECDY.js'),import('./shell-NPNTWDMU.js'),import('./opencode-K22RCQ5C.js'),import('./workspace-manager-ZI5SVXJU.js'),import('./template-engine-VLIOJ3WX.js'),import('./skill-loader-IGRIELEM.js'),import('./orchestrator-Z6C5OE4A.js'),import('./doctor-service-PB7YBH3F.js')]),h=new s,I=new k,A=new v,E=new d(m.projectRoot,t.paths.root,h),S=new r;S.register(new a(h)),S.register(new n(h)),S.register(new i(h)),S.register(new o(h)),S.register(new c(h));let xt=new b(S,h,m.projectRoot),Tt=new _({taskStore:t.taskStore,agentStore:t.agentStore,runStore:t.runStore,stateStore:t.stateStore,adapterRegistry:S,workspaceManager:E,templateEngine:I,processManager:h,eventBus:t.eventBus,taskService:t.taskService,agentService:t.agentService,runService:t.runService,contextStore:t.contextStore,messageService:t.messageService,goalStore:t.goalStore,skillLoader:A,config:t.config,projectRoot:m.projectRoot,lockPath:t.paths.lockPath});return {...t,processManager:h,adapterRegistry:S,workspaceManager:E,templateEngine:I,skillLoader:A,doctorService:xt,orchestrator:Tt}}async function Es(m){return Ht(m)}export{Es as buildContainer,Ht as buildFullContainer,Jt as buildLightContainer};
@@ -1,6 +0,0 @@
1
- export { Orchestrator } from './chunk-WM64PSY4.js';
2
- import './chunk-XUZZJCKG.js';
3
- import './chunk-RHFRHCN5.js';
4
- import './chunk-IESAV453.js';
5
- //# sourceMappingURL=orchestrator-53KIAROT.js.map
6
- //# sourceMappingURL=orchestrator-53KIAROT.js.map
@@ -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 R from'fs/promises';import {execFile}from'child_process';function st(h,t){if(!h?.length||!t?.length)return false;for(let e of h)for(let s of t)if(ft(e,s))return true;return false}function q(h){let t=h.split("*")[0],e=!t.endsWith("/"),s=e?dirname(t):"";return {raw:h,base:t,isFile:e,dir:s}}var O=class{entries;constructor(t){this.entries=[];for(let e of t)if(e?.length)for(let s of e)this.entries.push(q(s));}overlapsAny(t){if(!t?.length||this.entries.length===0)return false;for(let e of t){let s=q(e);for(let i of this.entries)if(pt(s,i))return true}return false}add(t){if(t?.length)for(let e of t)this.entries.push(q(e));}get size(){return this.entries.length}};function pt(h,t){return h.raw===t.raw||h.base.startsWith(t.base)||t.base.startsWith(h.base)?true:h.isFile&&t.isFile?h.dir===t.dir&&h.dir!==".":false}function ft(h,t){if(h===t)return true;let e=h.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let i=dirname(e),r=dirname(s);return i===r&&i!=="."}return false}var it=Promise.resolve();async function G(h){let t,e=new Promise(i=>{t=i;}),s=it;it=e,await s;try{return await mt(h)}finally{t();}}var gt=6e4;async function mt(h){let t=await at(h);if(t!==null){if(St(t)&&!await vt(h))return {acquired:false,pid:t};await R.unlink(h).catch(()=>{});}try{let e=await R.open(h,"wx");return await e.writeFile(String(process.pid),"utf-8"),await e.close(),{acquired:!0,pid:process.pid}}catch(e){if(e.code==="EEXIST")return {acquired:false,pid:await at(h)??void 0};throw e}}async function I(h){await R.unlink(h).catch(()=>{});}async function rt(h){let t=Date.now()/1e3;await R.utimes(h,t,t).catch(()=>{});}async function at(h){try{let t=await R.readFile(h,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function vt(h){try{let t=await R.stat(h);return Date.now()-t.mtimeMs>gt}catch{return true}}function St(h){try{return process.kill(h,0),!0}catch(t){return t.code==="EPERM"}}var B=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?`${t.status??""}:${t.goalId??""}`:"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}},M=class{constructor(t){this.inner=t;}listCache=null;nameCache=new Map;async list(){if(this.listCache)return this.listCache;let t=await this.inner.list();return this.listCache=t,t}async get(t){return this.inner.get(t)}async getByName(t){if(this.nameCache.has(t))return this.nameCache.get(t)??null;let e=await this.inner.getByName(t);return this.nameCache.set(t,e),e}async save(t){await this.inner.save(t),this.listCache=null,this.nameCache.clear();}async delete(t){await this.inner.delete(t),this.listCache=null,this.nameCache.clear();}invalidate(){this.listCache=null,this.nameCache.clear();}},$=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?.status??"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}};var yt={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},nt=["typecheck","lint","test_pass"],E=class{cwd;timeoutMs;failFast;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4,this.failFast=t.fail_fast??true;}async runAll(t){let e=kt(t),s=[];for(let i of e){let r=await this.runCriterion(i);if(s.push(r),this.failFast&&!r.passed)break}return s}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let i=s.passed?"\u2713":"\u2717",r=s.output;return `${i} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
3
- ${r}`}).join(`
4
-
5
- `)}runCriterion(t){let{cmd:e,args:s}=yt[t];return new Promise(i=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,o,n)=>{let d=(o+`
6
- `+n).trim();i({criterion:t,passed:!r,output:d.slice(0,2e3)});});})}};function kt(h){return [...h].sort((t,e)=>{let s=nt.indexOf(t),i=nt.indexOf(e);return (s===-1?1/0:s)-(i===-1?1/0:i)})}var _t=8192,Tt=4096,ot=class h$1{constructor(t){this.deps=t;this.cachedTaskStore=new B(t.taskStore),this.cachedAgentStore=new M(t.agentStore),this.cachedGoalStore=t.goalStore?new $(t.goalStore):null;}intervalId=null;shuttingDown=false;state=null;abortControllers=new Map;cachedTaskStore;cachedAgentStore;cachedGoalStore;saveStateTimer=null;saveStateDirty=false;lockAcquired=false;consecutiveTickFailures=0;maxConsecutiveTickFailures=5;maxRetryQueueSize=100;signalHandlers=[];immediateDispatchTimer=null;taskCreatedUnsub=null;tickInProgress=false;stoppedResolvers=[];skipAutonomousSeeding=false;lastAutoSeedAt=new Map;static AUTO_SEED_COOLDOWN_MS=3e4;stateMutex=Promise.resolve();get isOwner(){return this.lockAcquired}withStateLock(t){let e,s=new Promise(r=>{e=r;}),i=this.stateMutex;return this.stateMutex=s,i.then(async()=>{try{return await t()}finally{e();}})}async runTask(t){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchTask(t));return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchTask(t)));}async runAll(){if(this.lockAcquired){await this.freshDispatch(()=>this.dispatchAll());return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchAll()));}async freshDispatch(t){await this.withStateLock(async()=>{this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),await this.loadState(),await t(),await this.saveState();});}async withTemporaryLock(t){let e=await G(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true;try{await t();}finally{this.lockAcquired=false,await I(this.deps.lockPath);}}async startWatch(t){this.skipAutonomousSeeding=t?.skipAutonomousSeeding??false;let e=await G(this.deps.lockPath);if(!e.acquired)throw new d(e.pid);this.lockAcquired=true,await this.loadState(),await this.cleanupStaleRunningEntries(),this.state.pid=process.pid,this.state.started_at=new Date().toISOString(),await this.saveState(),this.registerSignalHandlers(),this.taskCreatedUnsub=this.deps.eventBus.on("task:created",()=>{this.scheduleImmediateDispatch();}),await this.tick(),this.intervalId=setInterval(()=>this.tick().then(()=>{this.consecutiveTickFailures=0;},s=>{this.consecutiveTickFailures++;let i=s instanceof Error?s.message:String(s);this.deps.eventBus.emit({type:"orchestrator:error",error:i,context:"tick",fatal:this.consecutiveTickFailures>=this.maxConsecutiveTickFailures}),this.consecutiveTickFailures>=this.maxConsecutiveTickFailures&&(this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`${this.consecutiveTickFailures} consecutive tick failures`}),this.stop().catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:"stop after consecutive tick failures",fatal:false});}));}),this.deps.config.scheduling.poll_interval_ms);}waitForStop(){return this.shuttingDown?Promise.resolve():new Promise(t=>{this.stoppedResolvers.push(t);})}registerSignalHandlers(){let t=e=>{this.deps.eventBus.emit({type:"orchestrator:shutdown",reason:`Received ${e}`}),this.stop().catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`stop after ${e} signal`,fatal:false});});};for(let e of ["SIGINT","SIGTERM"]){let s=()=>t(e);this.signalHandlers.push([e,s]),process.on(e,s);}}removeSignalHandlers(){for(let[t,e]of this.signalHandlers)process.removeListener(t,e);this.signalHandlers=[];}async stop(){if(!this.shuttingDown){this.shuttingDown=true,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.taskCreatedUnsub&&(this.taskCreatedUnsub(),this.taskCreatedUnsub=null),this.immediateDispatchTimer&&(clearTimeout(this.immediateDispatchTimer),this.immediateDispatchTimer=null),await this.flushStateLazy(),await this.withStateLock(async()=>{if(this.state){for(let[t,e$1]of Object.entries(this.state.running)){this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(e$1.pid),await this.deps.runService.finish(e$1.run_id,"cancelled");let s=await this.deps.taskStore.get(t);s&&await this.deps.taskService.updateStatus(t,e(s)),await this.deps.agentService.setStatus(e$1.agent_id,"idle");}this.state.running={},this.state.claimed=new Set,this.state.pid=void 0,this.state.started_at=void 0,await this.saveState();}}),this.lockAcquired&&(await I(this.deps.lockPath),this.lockAcquired=false),this.removeSignalHandlers();for(let t of this.stoppedResolvers)t();this.stoppedResolvers=[];}}async cancelTask(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.cancelTask(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state,s=e.running[t];s&&(this.abortControllers.get(t)?.abort(),this.abortControllers.delete(t),await this.deps.processManager.killWithGrace(s.pid,3e3).catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask kill process ${s.pid} for task ${t}`,fatal:false});}),await this.deps.runService.finish(s.run_id,"cancelled").catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask finish run ${s.run_id}`,fatal:false});}),await this.deps.agentService.setStatus(s.agent_id,"idle").catch(i=>{this.deps.eventBus.emit({type:"orchestrator:error",error:i instanceof Error?i.message:String(i),context:`cancelTask setStatus idle for agent ${s.agent_id}`,fatal:false});}),delete e.running[t],await this.saveState()),e.retry_queue=e.retry_queue.filter(i=>i.task_id!==t);try{await this.deps.taskService.cancel(t);}catch{try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{}}await this.saveState();});}async forceStopAgent(t){if(!this.lockAcquired)return this.withTemporaryLock(()=>this.forceStopAgent(t));await this.withStateLock(async()=>{await this.loadState();let e=this.state;for(let[s,i]of Object.entries(e.running))if(i.agent_id===t){this.abortControllers.get(s)?.abort(),this.abortControllers.delete(s),await this.deps.processManager.killWithGrace(i.pid,3e3),await this.deps.runService.finish(i.run_id,"cancelled");try{await this.deps.taskService.updateStatus(s,"failed");}catch{}delete e.running[s];}await this.deps.agentService.setStatus(t,"idle"),await this.saveState();});}async tick(){if(!this.shuttingDown){this.tickInProgress=true;try{await this.withStateLock(async()=>{if(this.shuttingDown)return;this.cachedTaskStore.invalidate(),this.cachedAgentStore.invalidate(),this.cachedGoalStore?.invalidate(),await this.loadState(),await this.reconcile(),this.skipAutonomousSeeding||await this.seedAutonomousTasks(),await this.dispatchAll();let t=await this.cachedTaskStore.list(),e=Object.keys(this.state.running).length,s=t.filter(i=>c(i.status)).length;this.deps.eventBus.emit({type:"orchestrator:tick",running:e,queued:s});}),await rt(this.deps.lockPath);}finally{this.tickInProgress=false;}}}scheduleImmediateDispatch(t=0){this.shuttingDown||this.immediateDispatchTimer||(this.immediateDispatchTimer=setTimeout(()=>{if(this.immediateDispatchTimer=null,!this.shuttingDown){if(this.tickInProgress){t<10&&this.scheduleImmediateDispatch(t+1);return}this.immediateDispatch().catch(e=>{this.deps.eventBus.emit({type:"orchestrator:error",error:e instanceof Error?e.message:String(e),context:"immediate dispatch on task:created",fatal:false});});}},500));}async immediateDispatch(){this.shuttingDown||await this.freshDispatch(()=>this.shuttingDown?Promise.resolve():this.dispatchAll());}async reconcile(){let t=this.state,e=Date.now(),s=Object.entries(t.running),[i,r]=await Promise.all([Promise.all(s.map(([c])=>this.deps.taskStore.get(c))),Promise.all(s.map(([,c])=>this.deps.agentStore.get(c.agent_id)))]);for(let c=0;c<s.length;c++){let[l,f]=s[c],y=i[c];if(!y||b(y.status)){this.abortControllers.delete(l),delete t.running[l],await this.deps.agentService.setStatus(f.agent_id,"idle").catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`reconcile setStatus idle for stale agent ${f.agent_id} (task ${l})`,fatal:false});});continue}if(!this.deps.processManager.isAlive(f.pid)){try{await this._handleRunFailure(l,f,"Process crashed unexpectedly");}catch{delete t.running[l],await this.deps.agentService.setStatus(f.agent_id,"idle").catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`reconcile crash fallback setStatus idle for agent ${f.agent_id} (task ${l})`,fatal:false});});}continue}let v=new Date(f.last_event_at).getTime(),u=r[c]?.config.stall_timeout_ms??this.deps.config.defaults.agent.stall_timeout_ms;if(e-v>u){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:f.run_id}),this.abortControllers.get(l)?.abort(),await this.deps.processManager.killWithGrace(f.pid,5e3);try{await this._handleRunFailure(l,f,"Agent stalled (no events)");}catch{delete t.running[l],await this.deps.agentService.setStatus(f.agent_id,"idle").catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`reconcile stall fallback setStatus idle for agent ${f.agent_id} (task ${l})`,fatal:false});});}}}let o=new Set(Object.values(t.running).map(c=>c.agent_id)),[n,d]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),m=n.filter(c=>c.status==="running"&&!o.has(c.id));m.length>0&&await Promise.all(m.map(c=>this.deps.agentService.setStatus(c.id,"idle")));let p=d.filter(c=>c.status==="in_progress"&&!t.running[c.id]);p.length>0&&await Promise.all(p.map(async c=>{try{await this.deps.taskService.updateStatus(c.id,"failed");}catch{c.status="failed",c.updated_at=new Date().toISOString(),await this.deps.taskStore.save(c).catch(l=>{this.deps.eventBus.emit({type:"orchestrator:error",error:l instanceof Error?l.message:String(l),context:`force-write orphaned task ${c.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:c.id});}));let a=[];t.retry_queue=t.retry_queue.filter(c=>e>=new Date(c.due_at).getTime()?(a.push(c.task_id),false):true);for(let c$1 of a){let l=await this.deps.taskStore.get(c$1);!l||!c(l.status)||await this.dispatchTask(c$1,l);}await this.saveState();}async seedAutonomousTasks(){let e=(await this.cachedAgentStore.list()).filter(n=>n.autonomous&&n.status==="idle");if(e.length===0)return;let s=await this.cachedTaskStore.list(),i=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],r=false,o=new Set;for(let n of e){if(s.some(f=>f.assignee===n.id&&!b(f.status)))continue;let m=this.lastAutoSeedAt.get(n.id)??0;if(Date.now()-m<h$1.AUTO_SEED_COOLDOWN_MS)continue;let p=i.find(f=>f.assignee===n.id&&!o.has(f.id))??i.find(f=>!f.assignee&&!o.has(f.id));p&&o.add(p.id);let a$1=n.role??"general assistant",c=p?`[auto] ${n.name}: ${p.title.slice(0,60)}`:`[auto] ${n.name}: ${a$1.slice(0,60)}`,l=p?`## GOAL (highest priority)
7
-
8
- ${p.description||p.title}
9
-
10
- ---
11
- Agent role: ${a$1}`:`Autonomous work cycle. Agent role: ${a$1}`;try{await this.deps.taskService.create({title:c,description:l,assignee:n.id,labels:[a],priority:3,goalId:p?.id}),this.lastAutoSeedAt.set(n.id,Date.now()),r=!0;}catch(f){this.deps.eventBus.emit({type:"orchestrator:error",error:f instanceof Error?f.message:String(f),context:`autonomous task for agent ${n.id}`,fatal:false});}}r&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e$1=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,i=e$1-s;if(i<=0)return;let r=await this.cachedTaskStore.list(),o=new Map(r.map(a=>[a.id,a])),n=r.filter(a=>c(a.status)&&!d$1(a,o)&&!t.running[a.id]&&!t.claimed.has(a.id)).sort((a,c)=>{let l=(a.priority??3)-(c.priority??3);if(l!==0)return l;let f=(a.goalId?0:1)-(c.goalId?0:1);if(f!==0)return f;let y=c.updated_at??"",v=a.updated_at??"";return y<v?-1:y>v?1:0}).slice(0,i),d=new Set,m$1=r.filter(a=>a.status==="in_progress"&&a.scope?.length),p=new O(m$1.map(a=>a.scope));for(let a of n)if(a.scope?.length)if(p.overlapsAny(a.scope)){let c=m$1.find(l=>st(a.scope,l.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:a.id,overlappingTaskId:c?.id??a.id,patterns:a.scope}),d.add(a.id);}else p.add(a.scope);for(let a of n)if(!d.has(a.id))try{await this.dispatchTask(a.id);}catch(c){if(c instanceof m)try{let l=await this.deps.taskStore.get(a.id);if(l&&!b(l.status)){let f={...l,attempts:(l.attempts??0)+1,updated_at:new Date().toISOString()},y=e(f),v={...f,status:y};if(await this.deps.taskStore.save(v),y==="failed"){let w=r.map(u=>u.id===v.id?v:u);this.cachedTaskStore.invalidate(),await this.cascadeFailDependents(v.id,w,`dependency ${v.id} failed: ${c.message}`);}else {let w=g(v.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);this.enqueueRetry(t,v.id,v.attempts,w,c.message),await this.saveState();}}}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`dispatch task ${a.id}`,fatal:false});}}enqueueRetry(t,e,s,i,r){t.retry_queue.some(o=>o.task_id===e)||(t.retry_queue.length>=this.maxRetryQueueSize&&t.retry_queue.shift(),t.retry_queue.push({task_id:e,attempt:s,due_at:new Date(Date.now()+i).toISOString(),error:r}));}async cascadeFailDependents(t,e,s){let i=new Map;for(let m of e)for(let p of m.depends_on){let a=i.get(p);a||(a=[],i.set(p,a)),a.push(m);}let r=[t],o=0,n=new Set,d=false;for(;o<r.length;){let m=r[o++];if(n.has(m))continue;n.add(m);let p=i.get(m);if(!p)continue;let a=[];for(let l of p)b(l.status)||n.has(l.id)||(a.push({task:l,previousStatus:l.status}),r.push(l.id));if(a.length===0)continue;let c=new Date().toISOString();await Promise.all(a.map(({task:l})=>this.deps.taskStore.save({...l,status:"failed",updated_at:c})));for(let{task:l,previousStatus:f}of a)this.deps.eventBus.emit({type:"task:status_changed",taskId:l.id,from:f,to:"failed"}),this.deps.eventBus.emit({type:"task:cascade_failed",taskId:l.id,failedDependencyId:t,reason:s});d=true;}d&&this.cachedTaskStore.invalidate();}async dispatchTask(t,e){let s=this.state;if(s.running[t]){let r=s.running[t];throw new h(t,r.run_id,r.agent_id)}let i=e??await this.deps.taskService.get(t);if(c(i.status)){s.claimed.add(t),await this.saveState();try{let r=await this.cachedAgentStore.list(),o=await this.deps.agentService.findBestAgent(i);if(!o){if(r.length===0)throw new e$1;this.unclaim(t),await this.saveState();return}let{path:n,branch:d}=await this.deps.workspaceManager.prepare(i,o,this.deps.config),m=this.deps.config.prompt?.system_template??d$2,p=this.deps.config.prompt?.user_template??e$2,a=this.deps.config.prompt?.template,c=i.attempts+1,l;if(c>1){let S=await this.deps.runService.getLastFailedRunContext(i.id);S&&(l={previous_error:S.error,previous_output:S.output});}let f=i.goalId,[y,v,w]=await Promise.all([this.deps.contextStore?.getAll(),this.deps.messageService?this.deps.messageService.drainMailbox(o.id,i.id):[],f&&this.cachedGoalStore?this.cachedGoalStore.get(f).catch(()=>null):null]),u;if(w){let dt=(await this.cachedTaskStore.list()).filter(x=>x.goalId===f),ut=await this.deps.contextStore?.get(`${f}-progress`),ht=dt.map(x=>`[${x.status}] ${x.title}`);u={id:w.id,title:w.title,description:w.description,status:w.status,task_names:ht,progress:ut?.value};}let g=c$1(i,o,c,n,this.deps.config,{allAgents:r,retryContext:l,sharedContext:y,feedback:i.feedback,messages:v.length?v:void 0,goal:u}),k,_;if(a?k=await this.deps.templateEngine.render(a,g):(_=await this.deps.templateEngine.render(m,g),k=await this.deps.templateEngine.render(p,g)),this.deps.skillLoader&&o.config.skills?.length){let S=await this.deps.skillLoader.loadSkills(o.config.skills);S&&(_!==void 0?_=_+`
12
-
13
- `+S:k=k+`
14
-
15
- `+S);}let P=await this.deps.runService.create({taskId:i.id,agentId:o.id,attempt:c,prompt:k,workspacePath:n});if((i.status==="failed"||i.status==="cancelled")&&(await this.deps.taskService.retry(t),i.status="todo",i.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,o.id),await this.deps.taskService.incrementAttempts(t),d){let S=await this.deps.taskStore.get(t);S&&(S.proof={...S.proof??{files_changed:[]},branch:d},S.workspace=n,await this.deps.taskStore.save(S));}await this.deps.agentService.setStatus(o.id,"running");let T=await this.deps.agentService.get(o.id);T.current_task=t,T.last_error=void 0,await this.deps.agentStore.save(T);let lt=this.deps.adapterRegistry.require(o.adapter),N=new AbortController;this.abortControllers.set(t,N);let U=lt.execute({prompt:k,systemPrompt:_,workspace:n,env:{...o.config.env,ORCH_AGENT_ID:o.id,ORCH_AGENT_NAME:o.name,ORCH_TASK_ID:i.id},config:T.config,signal:N.signal}),W=U.pid,K=new Date().toISOString();await this.deps.runService.start(P.id,W),this.unclaim(t),s.running[t]={run_id:P.id,agent_id:o.id,task_id:t,pid:W,started_at:K,last_event_at:K},await this.saveState(),this.collectEvents(U.events,P.id,t,o.id).catch(S=>{this.deps.eventBus.emit({type:"orchestrator:error",error:S instanceof Error?S.message:String(S),context:`adapter execution for ${t}`,fatal:!1});});}catch(r){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),r}}}async collectEvents(t,e,s,i){let r,o,n,d,m=new Set;try{for await(let a of t){if(this.shuttingDown)break;if(a.type==="done"){if(a.tokens){let{input:g,output:k,reasoning:_,cache_read:P,cache_write:T}=a.tokens;r=a$1(g,k,{reasoning:_,cache_read:P,cache_write:T});}let u=a.data;u&&typeof u.result=="string"&&(o=u.result);}if(a.type==="output"){let u=a.data;if(u){let g=typeof u.text=="string"?u.text:typeof u.message=="string"?u.message:void 0;g?.trim()&&(n=g);}}if(a.type==="file_change"){let u=a.data;if(u&&Array.isArray(u.paths))for(let g of u.paths)typeof g=="string"&&m.add(g);else {let g=u&&typeof u.path=="string"?u.path:typeof a.data=="string"?a.data:String(a.data);m.add(g);}}let c=null;if(a.type==="tool_call"){let u=a.data;if(u){let g=u.input,k=typeof u.name=="string"?u.name:"";g&&typeof g.file_path=="string"&&/^(Write|Edit|MultiEdit|NotebookEdit)$/i.test(k)&&(c=g.file_path,m.add(c));}}let l=At(a.timestamp)?a.timestamp:new Date().toISOString(),f=a.type==="file_change"?(()=>{let u=a.data;return u&&typeof u.path=="string"?u.path:typeof a.data=="string"?a.data:String(a.data)})():null,y=ct(a.data,_t);a.data=void 0;let v={timestamp:l,type:a.type==="output"?"agent_output":a.type==="file_change"?"file_changed":a.type==="command"?"command_run":a.type==="tool_call"?"tool_call":a.type==="error"?"error":"done",data:y};await this.deps.runService.appendEvent(e,v),this.state?.running[s]&&(this.state.running[s].last_event_at=l,this.saveStateLazy());let w=ct(y,Tt);a.type==="output"||a.type==="tool_call"?(this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:i,data:w}),c&&this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:c})):a.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:f}):a.type==="error"&&(a.errorKind&&(d=a.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:i,error:w,...a.errorKind?{errorKind:a.errorKind}:{}}));}let p=o??n;await this.handleRunSuccess(s,e,i,r,p,[...m]);}catch(p){let a=p instanceof Error?p.message:String(p),c=d??(p instanceof Error?p.errorKind:void 0),l=this.state?.running[s];l&&await this.handleRunFailure(s,l,a,c);}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,i,r,o){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,i,r,o))}async _handleRunSuccess(t,e,s,i,r,o){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let d=await this.deps.taskStore.get(t);if(!d)return;let m=o;(!m||m.length===0)&&d.proof?.branch&&(m=await this.deps.workspaceManager.getChangedFiles(d.proof.branch)),d.proof={...d.proof,agent_summary:r?.slice(0,2e3)??d.proof?.agent_summary,files_changed:m?.length?m:d.proof?.files_changed??[]},delete d.feedback,await this.deps.taskStore.save(d);let p=await this.deps.agentStore.get(s),c=d.labels?.includes(a)||p?.config.approval_policy==="auto",l=f(d,true,c);await this.deps.runService.finish(e,"succeeded",i);let f$1=n.running[t],y=f$1?Date.now()-new Date(f$1.started_at).getTime():0;f$1&&(n.stats.total_runtime_ms+=y),delete n.running[t];let v={tasks_completed:(p?.stats.tasks_completed??0)+1,total_runs:(p?.stats.total_runs??0)+1,total_runtime_ms:(p?.stats.total_runtime_ms??0)+y};if(i&&(v.tokens_used=(p?.stats.tokens_used??0)+i.total),await this.deps.agentService.updateStats(s,v).catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),context:`agent stats update for ${s}`,fatal:false});}),n.stats.total_tasks_completed++,n.stats.total_runs++,i&&(n.stats.total_tokens.input+=i.input,n.stats.total_tokens.output+=i.output,n.stats.total_tokens.reasoning+=i.reasoning,n.stats.total_tokens.cache_read+=i.cache_read,n.stats.total_tokens.cache_write+=i.cache_write,n.stats.total_tokens.total=n.stats.total_tokens.input+n.stats.total_tokens.output+n.stats.total_tokens.reasoning),d.proof?.branch)try{let u=await this.deps.workspaceManager.mergeBack(d.proof.branch);if(u.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:d.proof.branch}),await this.deps.workspaceManager.cleanup(t,d.proof.branch).catch(g=>{this.deps.eventBus.emit({type:"orchestrator:error",error:g instanceof Error?g.message:String(g),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:d.proof.branch,conflictInfo:u.conflictInfo}),await this.forceTaskToReview(d,s,`MERGE CONFLICT: ${u.conflictInfo}`);return}}catch(u){let g=u instanceof Error?u.message:String(u);await this.forceTaskToReview(d,s,`MERGE ERROR: ${g}`);return}try{await this.deps.taskService.updateStatus(t,l);}catch(u){let g=u instanceof Error?u.message:String(u);this.deps.eventBus.emit({type:"orchestrator:error",error:g,context:`state machine validation failed for task ${t} -> ${l}, force-writing`,fatal:false}),d.status=l,d.updated_at=new Date().toISOString(),await this.deps.taskStore.save(d).catch(k=>{this.deps.eventBus.emit({type:"orchestrator:error",error:k instanceof Error?k.message:String(k),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(u=>{this.deps.eventBus.emit({type:"orchestrator:error",error:u instanceof Error?u.message:String(u),context:`_handleRunSuccess setStatus idle for agent ${s}`,fatal:false});});let w=await this.deps.agentStore.get(s);w&&(w.current_task=void 0,await this.deps.agentStore.save(w)),l==="review"&&d.review_criteria?.length?await this.runAutoReview(t,d.review_criteria,d.workspace??this.deps.projectRoot,c):l==="review"&&c&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s,i){return this.withStateLock(()=>this._handleRunFailure(t,e,s,i))}async _handleRunFailure(t,e$1,s,i){await this.flushStateLazy(),this.abortControllers.delete(t);let r=this.state;if(!r.running[t])return;let o$1=await this.deps.taskStore.get(t);if(!o$1)return;await this.deps.runService.finish(e$1.run_id,"failed",void 0,s),await this.deps.agentService.setStatus(e$1.agent_id,"idle");let n=await this.deps.agentStore.get(e$1.agent_id);n&&(n.current_task=void 0,n.last_error={message:s.slice(0,500),kind:i??o(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n));let d=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(n?.stats.tasks_failed??0)+1,total_runs:(n?.stats.total_runs??0)+1,total_runtime_ms:(n?.stats.total_runtime_ms??0)+d});let m=e(o$1);if(await this.deps.taskService.updateStatus(t,m),m==="retrying"){let p=g(o$1.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);this.enqueueRetry(r,t,o$1.attempts+1,p,s),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:o$1.attempts+1,delay_ms:p});}else {r.stats.total_tasks_failed++,this.cachedTaskStore.invalidate();let p=await this.cachedTaskStore.list();await this.cascadeFailDependents(t,p,`dependency ${t} failed: ${s}`);}r.stats.total_runtime_ms+=d,o$1.proof?.branch&&await this.deps.workspaceManager.cleanup(t,o$1.proof.branch).catch(p=>{this.deps.eventBus.emit({type:"orchestrator:error",error:p instanceof Error?p.message:String(p),context:`workspace cleanup for ${t}`,fatal:false});}),delete r.running[t],r.stats.total_runs++,await this.saveState(),this.scheduleImmediateDispatch();}async runAutoReview(t,e,s,i=false){let o=await new E({cwd:s}).runAll(e),n=E.allPassed(o),d=await this.deps.taskStore.get(t);if(d&&(d.review_results=o,d.proof={...d.proof,test_results:E.formatReport(o),files_changed:d.proof?.files_changed??[]},await this.deps.taskStore.save(d),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:o}),n||i)){n||this.deps.eventBus.emit({type:"orchestrator:error",error:`Review criteria failed for task ${t} but autoApprove is set \u2014 force-approving`,context:"auto-review-with-auto-approve",fatal:false});try{await this.deps.taskService.updateStatus(t,"done");}catch(m){let p=m instanceof Error?m.message:String(m);this.deps.eventBus.emit({type:"orchestrator:error",error:p,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),d.status="done",d.updated_at=new Date().toISOString(),await this.deps.taskStore.save(d).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`force-write task ${t} to store failed (auto-review)`,fatal:false});});}}}async forceTaskToReview(t,e,s){t.proof={...t.proof,agent_summary:`${s}
16
-
17
- ${t.proof?.agent_summary??""}`.slice(0,2e3),files_changed:t.proof?.files_changed??[]},t.status="review",t.updated_at=new Date().toISOString(),await this.deps.taskStore.save(t),await this.deps.agentService.setStatus(e,"idle").catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:`forceTaskToReview setStatus idle for agent ${e}`,fatal:false});});let i=await this.deps.agentStore.get(e);i&&(i.current_task=void 0,await this.deps.agentStore.save(i)),await this.saveState();}unclaim(t){this.state.claimed.delete(t);}requireOwnership(){if(!this.lockAcquired)throw new d(0)}async loadState(){this.state=await this.deps.stateStore.read();}async cleanupStaleRunningEntries(){let t=this.state,e=Object.entries(t.running).filter(([,i])=>!this.deps.processManager.isAlive(i.pid)),s=new Set;if(e.length>0){for(let[i]of e)delete t.running[i],s.add(i);await Promise.all(e.map(async([i,r])=>{await this.deps.agentService.setStatus(r.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: setStatus idle for agent ${r.agent_id}`,fatal:false});}),await this.forceTaskCancelled(i),await this.deps.runService.finish(r.run_id,"cancelled",void 0,"Orchestrator restarted").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: finish run ${r.run_id}`,fatal:false});});}));}if(t.claimed=new Set,s.size>0){let r=(await this.cachedTaskStore.list()).filter(n=>n.status==="in_progress"&&!t.running[n.id]);r.length>0&&await Promise.all(r.map(n=>this.forceTaskCancelled(n.id)));let o=new Set([...s,...r.map(n=>n.id)]);t.retry_queue=t.retry_queue.filter(n=>!o.has(n.task_id)),await this.saveState();}await this.cleanupOrphanedPreparingRuns();}async cleanupOrphanedPreparingRuns(){try{let e=(await this.deps.runStore.listAll()).filter(r=>r.status==="preparing");if(e.length===0)return;let s=new Set(Object.values(this.state.running).map(r=>r.run_id)),i=e.filter(r=>!s.has(r.id));if(i.length===0)return;await Promise.all(i.map(r=>this.deps.runService.finish(r.id,"cancelled",void 0,"Orphaned preparing run (orchestrator restarted)").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: finish orphaned preparing run ${r.id}`,fatal:!1});})));}catch(t){this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"startup cleanup: cleanupOrphanedPreparingRuns",fatal:false});}}async forceTaskCancelled(t){try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{let e=await this.deps.taskStore.get(t);e&&!b(e.status)&&(e.status="cancelled",e.updated_at=new Date().toISOString(),await this.deps.taskStore.save(e).catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`startup cleanup: force-cancel task ${t}`,fatal:false});}));}}async saveState(){this.state&&await this.deps.stateStore.write(this.state);}saveStateLazy(){this.saveStateDirty=true,!this.saveStateTimer&&(this.saveStateTimer=setTimeout(()=>{this.saveStateTimer=null,this.saveStateDirty&&(this.saveStateDirty=false,this.saveState().catch(t=>{this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"debounced state save",fatal:false});}));},500));}async flushStateLazy(){this.saveStateTimer&&(clearTimeout(this.saveStateTimer),this.saveStateTimer=null),this.saveStateDirty&&(this.saveStateDirty=false,await this.saveState());}};function At(h){if(typeof h!="string")return false;let t=new Date(h);return !isNaN(t.getTime())&&t.toISOString()===h}function ct(h,t){let e=typeof h=="string"?h:JSON.stringify(h);return e.length>t?e.slice(0,t)+"\u2026":e}export{ot as Orchestrator};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- function ct(d,e){d.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let S=await e.taskService.list(),w=await e.agentService.list(),h=await e.stateStore.read(),{render:k}=await import('ink'),{createElement:T}=await import('react'),{App:b}=await import('./App-Q7J4JGDF.js'),A=async t=>{await e.orchestrator.runTask(t);},R=async(t,s)=>e.taskService.create({title:t,priority:s?.priority,description:s?.description,attachments:s?.attachments}),C=async t=>{await e.orchestrator.cancelTask(t);},_=async t=>{await e.taskService.retry(t);},E=async(t,s)=>{await e.taskService.assign(t,s);},j=async()=>{await e.orchestrator.runAll();},D=async t=>{await e.agentService.disable(t);},U=async t=>{await e.agentService.enable(t);},m=t=>e.eventBus.onAny(t),P=async()=>e.taskService.list(),G=async()=>e.agentService.list(),x=async()=>e.stateStore.read(),I=async(t,s,n)=>e.agentService.create({name:t,adapter:s??e.config.defaults.agent.adapter,model:n?.model||void 0,effort:n?.effort||void 0,role:n?.role||void 0,approval_policy:n?.approval_policy||void 0,skills:n?.skills||void 0}),L=async t=>{await e.agentService.remove(t);},F=async t=>{await e.taskService.delete(t);},H=async t=>{await e.taskService.updateStatus(t,"done");},O=async(t,s)=>{await e.taskService.reject(t,s);},W=async(t,s)=>e.taskService.update(t,s),N=async(t,s)=>e.agentService.update(t,{...s,effort:s.effort,approval_policy:s.approval_policy}),B=async t=>{await e.orchestrator.forceStopAgent(t);},M=async(t,s)=>e.agentService.setAutonomous(t,s),V=async t=>{let s=await e.runService.listAll();s.sort((a,i)=>new Date(i.started_at).getTime()-new Date(a.started_at).getTime());let n=s.filter(a=>a.status==="succeeded"||a.status==="failed"),u=3,ot=10,y=n.slice(0,u),v=n.slice(u,ot),f=async a=>(await e.runService.readEventsTail(a.id,30)).map(r=>({timestamp:r.timestamp,agentId:a.agent_id,taskId:a.task_id,type:r.type,data:r.data}));if(y.length>0){let a=(await Promise.all(y.map(f))).flat();a.sort((i,r)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime()),t(a.slice(-200));}if(v.length>0){let a=(await Promise.all(v.map(f))).flat();a.sort((i,r)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime()),t(a.slice(-200));}},J=async t=>e.teamService.create(t),K=async()=>e.teamService.list(),q=async(t,s)=>e.teamService.join(t,s),z=async(t,s)=>e.teamService.leave(t,s),Q=async t=>{await e.teamService.disband(t);},X=async(t,s)=>e.teamService.setLead(t,s),Y=async()=>e.goalService.list(),Z=async t=>e.goalService.create(t),$=async(t,s)=>e.goalService.update(t,s),tt=async(t,s)=>e.goalService.updateStatus(t,s),et=async t=>{await e.goalService.delete(t);},st=async t=>e.goalService.getProgressReport(t),at=async()=>{await e.orchestrator.startWatch();},nt=async()=>{await e.orchestrator.stop();},c=d.version()??"0.0.0",rt=import('./update-check-R5ABF6HE.js').then(t=>t.checkForUpdateSWR(c)).catch(()=>null),l=false,p,g=false,o;try{await e.orchestrator.startWatch(),l=!0;}catch(t){p=t instanceof Error?t.message:String(t);let{DiskObserver:s}=await import('./disk-observer-B3NOZ2QA.js');o=new s({paths:e.paths,stateStore:e.stateStore}),g=true,m=n=>o.subscribe(n);}let{waitUntilExit:it}=k(T(b,{projectName:e.config.project.name,tasks:S,agents:w,state:h,onRunTask:A,onCreateTask:R,onCancelTask:C,onRetryTask:_,onAssignTask:E,onRunAll:j,onDisableAgent:D,onEnableAgent:U,onSubscribeEvents:m,onRefreshTasks:P,onRefreshAgents:G,onRefreshState:x,onLoadHistory:V,onAddAgent:I,onDeleteAgent:L,onApproveTask:H,onRejectTask:O,onDeleteTask:F,onUpdateTask:W,onUpdateAgent:N,onForceStopAgent:B,onToggleAutonomous:M,onRefreshGoals:Y,onCreateGoal:Z,onUpdateGoal:$,onUpdateGoalStatus:tt,onDeleteGoal:et,onGetGoalProgress:st,onCreateTeam:J,onListTeams:K,onJoinTeam:q,onLeaveTeam:z,onDisbandTeam:Q,onSetTeamLead:X,onStartWatch:at,onStopWatch:nt,initialWatchActive:l,observerMode:g,watchError:g?void 0:p,version:c,latestVersion:void 0,onCheckUpdate:async()=>{let t=await rt;if(t?.updateAvailable)return t.latest;let n=await(await import('./update-check-R5ABF6HE.js')).checkForUpdateNow(c);return n?.updateAvailable?n.latest:void 0},onBackgroundInstall:async t=>(await import('./update-check-R5ABF6HE.js')).backgroundInstall(t),initialActivityFilter:e.globalConfig.tui.activity_filter,onSaveActivityFilter:async t=>{await e.globalConfigStore.set("activity_filter",t);},initialNotifications:e.globalConfig.tui.notifications,onSaveNotifications:async t=>{await e.globalConfigStore.set("notifications",t);},initialMaxConcurrent:e.config.scheduling.max_concurrent_agents,onSaveMaxConcurrent:async t=>{await e.configStore.set("scheduling.max_concurrent_agents",t),e.config.scheduling.max_concurrent_agents=t;},onCompleteOnboarding:async()=>{let t=await e.stateStore.read();t.onboardingCompleted=true,await e.stateStore.write(t);},defaultAdapter:e.config.defaults.agent.adapter}),{incrementalRendering:true,kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await it(),l&&await e.orchestrator.stop().catch(()=>{}),o&&o.stop(),e.eventBus.clear();});}export{ct as registerTuiCommand};