@oxgeneral/orch 1.0.14 → 1.0.15

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 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import {a as a$2}from'./chunk-N4OXN2HW.js';import {c as c$1,b as b$2}from'./chunk-HXOMNULD.js';import {a as a$1,b as b$3}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {b}from'./chunk-3AXNSYCM.js';import {b as b$1,c,j as j$1,d,e,l,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,k,j as j$2,g,f,i}from'./chunk-IKNBPOQL.js';import W from'path';import K,{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=W.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(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 C=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=ut(r.status)-ut(a.status);if(n!==0)return n;let i=a.updated_at??"",m=r.updated_at??"";return i<m?-1:i>m?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 K.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 ut(o){return {in_progress:0,retrying:1,review:2,todo:3,done:4,failed:5,cancelled:6}[o]}var j=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 K.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 M=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
3
  `);}}}finally{a.destroy();}}async listFiltered(t){await j$1(this.paths.runsDir);let e=await l(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(m=>{let g=m.endsWith(".json")?m.slice(0,-5):m;return d(this.paths.runPath(g))}));for(let m of i)m!==null&&t(m)&&r.push(m);}return r.sort((a,n)=>new Date(n.started_at).getTime()-new Date(a.started_at).getTime())}};var X={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 R=class{constructor(t){this.paths=t;}async read(){let t=await d(this.paths.statePath);if(!t)return structuredClone(X);let e=structuredClone(X);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 D=class{constructor(t){this.paths=t;}async read(){let t=await b$1(this.paths.configPath);return pt(a$2,t??{})}async write(t){await c(this.paths.configPath,t);}async get(t){let e=await this.read();return Et(e,t)}async set(t,e){let s=await this.read();Ct(s,t,e),await this.write(s);}};function Et(o,t){let e=t.split("."),s=o;for(let r of e){if(s==null||typeof s!="object")return;s=s[r];}return s}function Ct(o,t,e){let s=t.split("."),r=o;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 pt(o,t){let e={...o};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]=pt(a,r):e[s]=r;}return e}var wt=W.join(homedir(),".orchestry"),ht=W.join(wt,"global.yml"),O=class{async read(){let t=await b$1(ht);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(wt,{recursive:true}),await c(ht,t);}async set(t,e){let s=await this.read();s.tui[t]=e,await this.write(s);}};var G=class o{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?St(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>o.MAX_TTL_MS))throw new Error(`TTL must be a positive number up to ${o.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 m=i.filter(g=>g.key!==t);return m.push(n),m});}async delete(t){try{await K.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)St(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 K.unlink(this.paths.contextPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}};function St(o){return o.expires_at?new Date(o.expires_at).getTime()<Date.now():false}var L=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 K.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 K.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 B=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??"",m=r.updated_at??"";return i<m?-1:i>m?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 K.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 F=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(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 K.unlink(this.paths.teamPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}};var N=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 $=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$3(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 K.rm(s,{recursive:true,force:true});}}getAttachmentPath(t,e){if(!this.paths)throw new c$2("Paths not configured");return W.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 K.access(a);}catch{throw new c$2(`Attachment file not found: ${a}`)}})),await Promise.all(e.map(async a=>{let n=W.basename(a);return await K.copyFile(a,W.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 U=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 g=new Set(n.config.skills.map(d=>d.toLowerCase()));for(let d of r)g.has(d)&&(i+=50);}if(r&&n.role){let g=n.role.toLowerCase();r.some(d=>g.includes(d))&&(i+=30);}n.status==="idle"&&(i+=20);let m=n.stats.tasks_completed+n.stats.tasks_failed;return m>0&&(i+=Math.round(n.stats.tasks_completed/m*10)),{agent:n,score:i}});return a.sort((n,i)=>i.score-n.score),a[0]?.agent??null}};var J=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 H=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 x=new Set(d.members.map(v=>v.agent_id));i=i.filter(v=>x.has(v.id));}}let g=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(g.map(d=>this.messageStore.save(d)));for(let d of g)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 m={...a,id:`msg_${nanoid(7)}`,to_agent_id:i.lead_agent_id};await this.messageStore.save(m),n.push(m),this.emitSent(m);}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 m={...a,id:`msg_${nanoid(7)}`,to_agent_id:t.to_agent_id};await this.messageStore.save(m),n.push(m),this.emitSent(m);}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 Nt={active:["paused","achieved","abandoned"],paused:["active","abandoned"],achieved:[],abandoned:[]},q=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){let s=await this.get(t),r=s.status;if(!Nt[r].includes(e))throw new c$2(`Cannot transition goal from '${r}' to '${e}'`);return s.status=e,s.updated_at=new Date().toISOString(),await this.goalStore.save(s),this.eventBus.emit({type:"goal:status_changed",goalId:t,from:r,to:e}),s.assignee&&(e==="paused"?(await this.maybeDisableAutonomous(s.assignee),await this.cancelPendingAutonomousTasks(s.assignee)):e==="active"&&r==="paused"?await this.enableAutonomous(s.assignee):b$2(e)&&await this.maybeDisableAutonomous(s.assignee)),s}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 Pt={auto_claim:true,message_ttl_ms:864e5};var Y=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 m of t.member_agent_ids??[]){if(m===t.lead_agent_id)continue;if(!await this.agentStore.get(m))throw new c$2(`Member agent not found: ${m}`);n.push({agent_id:m,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:{...Pt,...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 m of n)this.eventBus.emit({type:"team:member_joined",teamId:i.id,agentId:m.agent_id});return i}async get(t){let e=await this.teamStore.get(t);if(!e)throw new k(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 Ut(o){let t=new b(o.projectRoot),e=new D(t),s=new O,[,r]=await Promise.all([t.requireInit(),e.read()]),a=new C(t),n=new j(t),i=new M(t),m=new R(t),g=new G(t),d=new L(t),x=new B(t),v=new F(t),_=new N,b$1=new $(a,_,r,t),h=new U(n,m,_,r),I=new J(i,_),A=new H(d,n,v,_),E=new q(x,_,h,b$1,g),S=new Y(v,n,a,_);return {context:o,paths:t,config:r,taskStore:a,agentStore:n,runStore:i,stateStore:m,configStore:e,globalConfigStore:s,globalConfig:P,contextStore:g,messageStore:d,goalStore:x,teamStore:v,eventBus:_,taskService:b$1,agentService:h,runService:I,messageService:A,goalService:E,teamService:S}}async function Jt(o){let t=await Ut(o),e=await t.globalConfigStore.read();t.globalConfig=e;let[{ProcessManager:s},{AdapterRegistry:r},{ClaudeAdapter:a},{CodexAdapter:n},{CursorAdapter:i},{ShellAdapter:m},{OpenCodeAdapter:g},{WorkspaceManager:d},{LiquidTemplateEngine:x},{SkillLoader:v},{Orchestrator:_},{DoctorService:b}]=await Promise.all([import('./process-manager-33H27MQF.js'),import('./registry-BO2PPRNG.js'),import('./claude-GIGROCH5.js'),import('./codex-AZD52UPS.js'),import('./cursor-M3EJ432K.js'),import('./shell-JC2WDWBR.js'),import('./opencode-4G7VAZGY.js'),import('./workspace-manager-DG4IFFG3.js'),import('./template-engine-VLIOJ3WX.js'),import('./skill-loader-IGRIELEM.js'),import('./orchestrator-YXZUSS54.js'),import('./doctor-service-PB7YBH3F.js')]),h=new s,I=new x,A=new v,E=new d(o.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 m(h)),S.register(new g(h));let xt=new b(S,h,o.projectRoot),kt=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:o.projectRoot,lockPath:t.paths.lockPath});return {...t,processManager:h,adapterRegistry:S,workspaceManager:E,templateEngine:I,skillLoader:A,doctorService:xt,orchestrator:kt}}async function Is(o){return Jt(o)}export{Is as buildContainer,Jt as buildFullContainer,Ut as buildLightContainer};
4
+ `);}catch{}return {error:r,output:a}}};var H=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 x=new Set(d.members.map(v=>v.agent_id));i=i.filter(v=>x.has(v.id));}}let g=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(g.map(d=>this.messageStore.save(d)));for(let d of g)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 m={...a,id:`msg_${nanoid(7)}`,to_agent_id:i.lead_agent_id};await this.messageStore.save(m),n.push(m),this.emitSent(m);}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 m={...a,id:`msg_${nanoid(7)}`,to_agent_id:t.to_agent_id};await this.messageStore.save(m),n.push(m),this.emitSent(m);}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 Nt={active:["paused","achieved","abandoned"],paused:["active","abandoned"],achieved:[],abandoned:[]},q=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){let s=await this.get(t),r=s.status;if(!Nt[r].includes(e))throw new c$2(`Cannot transition goal from '${r}' to '${e}'`);return s.status=e,s.updated_at=new Date().toISOString(),await this.goalStore.save(s),this.eventBus.emit({type:"goal:status_changed",goalId:t,from:r,to:e}),s.assignee&&(e==="paused"?(await this.maybeDisableAutonomous(s.assignee),await this.cancelPendingAutonomousTasks(s.assignee)):e==="active"&&r==="paused"?await this.enableAutonomous(s.assignee):b$2(e)&&await this.maybeDisableAutonomous(s.assignee)),s}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 Pt={auto_claim:true,message_ttl_ms:864e5};var Y=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 m of t.member_agent_ids??[]){if(m===t.lead_agent_id)continue;if(!await this.agentStore.get(m))throw new c$2(`Member agent not found: ${m}`);n.push({agent_id:m,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:{...Pt,...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 m of n)this.eventBus.emit({type:"team:member_joined",teamId:i.id,agentId:m.agent_id});return i}async get(t){let e=await this.teamStore.get(t);if(!e)throw new k(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 Ut(o){let t=new b(o.projectRoot),e=new D(t),s=new O,[,r]=await Promise.all([t.requireInit(),e.read()]),a=new C(t),n=new j(t),i=new M(t),m=new R(t),g=new G(t),d=new L(t),x=new B(t),v=new F(t),_=new N,b$1=new $(a,_,r,t),h=new U(n,m,_,r),I=new J(i,_),A=new H(d,n,v,_),E=new q(x,_,h,b$1,g),S=new Y(v,n,a,_);return {context:o,paths:t,config:r,taskStore:a,agentStore:n,runStore:i,stateStore:m,configStore:e,globalConfigStore:s,globalConfig:P,contextStore:g,messageStore:d,goalStore:x,teamStore:v,eventBus:_,taskService:b$1,agentService:h,runService:I,messageService:A,goalService:E,teamService:S}}async function Jt(o){let t=await Ut(o),e=await t.globalConfigStore.read();t.globalConfig=e;let[{ProcessManager:s},{AdapterRegistry:r},{ClaudeAdapter:a},{CodexAdapter:n},{CursorAdapter:i},{ShellAdapter:m},{OpenCodeAdapter:g},{WorkspaceManager:d},{LiquidTemplateEngine:x},{SkillLoader:v},{Orchestrator:_},{DoctorService:b}]=await Promise.all([import('./process-manager-33H27MQF.js'),import('./registry-BO2PPRNG.js'),import('./claude-GIGROCH5.js'),import('./codex-AZD52UPS.js'),import('./cursor-M3EJ432K.js'),import('./shell-JC2WDWBR.js'),import('./opencode-4G7VAZGY.js'),import('./workspace-manager-DG4IFFG3.js'),import('./template-engine-VLIOJ3WX.js'),import('./skill-loader-IGRIELEM.js'),import('./orchestrator-YZHLOVJO.js'),import('./doctor-service-PB7YBH3F.js')]),h=new s,I=new x,A=new v,E=new d(o.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 m(h)),S.register(new g(h));let xt=new b(S,h,o.projectRoot),kt=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:o.projectRoot,lockPath:t.paths.lockPath});return {...t,processManager:h,adapterRegistry:S,workspaceManager:E,templateEngine:I,skillLoader:A,doctorService:xt,orchestrator:kt}}async function Is(o){return Jt(o)}export{Is as buildContainer,Jt as buildFullContainer,Ut as buildLightContainer};
package/dist/index.d.ts CHANGED
@@ -1287,6 +1287,11 @@ declare class Orchestrator {
1287
1287
  * specific tasks if needed.
1288
1288
  */
1289
1289
  private cleanupStaleRunningEntries;
1290
+ /**
1291
+ * Find runs stuck in 'preparing' status (orphaned by a crash before adapter.execute)
1292
+ * and mark them as cancelled. Called once at startup.
1293
+ */
1294
+ private cleanupOrphanedPreparingRuns;
1290
1295
  /** Cancel a task, falling back to direct store write if transition is invalid. */
1291
1296
  private forceTaskCancelled;
1292
1297
  private saveState;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Paths } from './chunk-J7ITYXE6.js';
2
- import { canTransition, isTerminal } from './chunk-C6II4C6Y.js';
3
- export { Orchestrator, canTransition, isBlocked, isDispatchable, isTerminal, resolveFailureStatus } from './chunk-C6II4C6Y.js';
2
+ import { canTransition, isTerminal } from './chunk-XJ6KTO3E.js';
3
+ export { Orchestrator, canTransition, isBlocked, isDispatchable, isTerminal, resolveFailureStatus } from './chunk-XJ6KTO3E.js';
4
4
  import { AUTONOMOUS_LABEL } from './chunk-XUZZJCKG.js';
5
5
  export { AdapterRegistry } from './chunk-6DWHQPTE.js';
6
6
  export { SkillLoader } from './chunk-U2JVMD2G.js';
@@ -1954,7 +1954,7 @@ async function buildFullContainer(context) {
1954
1954
  import('./workspace-manager-KUU7UMMC.js'),
1955
1955
  import('./template-engine-XOH3FZPU.js'),
1956
1956
  import('./skill-loader-RHCFIK74.js'),
1957
- import('./orchestrator-NC2NCJBC.js'),
1957
+ import('./orchestrator-FWROY4JD.js'),
1958
1958
  import('./doctor-service-F2SXDWHS.js')
1959
1959
  ]);
1960
1960
  const processManager = new ProcessManager();
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import {i,q,c}from'./chunk-64WUDYEM.js';import {c as c$1}from'./chunk-IKNBPOQL.js';function L(o,s){o.command("logs [run-id]").description("View run logs").option("--agent <agent-id>","Filter by agent").option("--task <task-id>","Filter by task").option("--follow","Live stream").option("--since <duration>","Filter by time (e.g. 5m, 1h)").action(async(i$1,e)=>{let r=e.since?k(e.since):void 0;e.follow?await S(s,{runId:i$1,taskId:e.task,agentId:e.agent}):i$1?await w(s,i$1,r):e.task?await p(s,e.task,r):e.agent?await v(s,e.agent,r):r!==void 0?await y(s,r):(i("Specify a run ID, --task, --agent, or --since <duration>"),process.exit(2));});}function u(o){let s=new Date(o.timestamp).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"}),i=o.type==="error"?c("failed"):c("agentAction"),e=typeof o.data=="string"?o.data:JSON.stringify(o.data);return ` ${q(s)} ${i} ${e.slice(0,80)}`}function f(o,s){if(!s)return o;let i=Date.now()-s;return o.filter(e=>new Date(e.timestamp).getTime()>=i)}async function w(o,s,i){let e=i?f(await o.runService.readEventsTail(s,500),i):await o.runService.readEventsTail(s,50);if(o.context.json){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(`
3
+ No events for run ${s}
4
+ `);return}console.log();for(let r of e)console.log(u(r));console.log();}async function p(o,s,i){let e=await o.runService.listForTask(s);if(o.context.json){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(`
5
+ No runs for task ${s}
6
+ `);return}let r=i?e.slice(-20):e,g=await Promise.all(r.map(n=>i?o.runService.readEventsTail(n.id,500).then(t=>f(t,i)):o.runService.readEventsTail(n.id,10)));for(let n=0;n<r.length;n++){let t=r[n],a=g[n];console.log(`
7
+ Run ${t.id} \xB7 attempt ${t.attempt} \xB7 ${t.status}`);for(let d of a.slice(-10))console.log(u(d));}console.log();}async function v(o,s,i){let e=await o.runService.listForAgent(s);if(o.context.json){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(`
8
+ No runs for agent ${s}
9
+ `);return}let r=e.slice(-5),g=await Promise.all(r.map(n=>i?o.runService.readEventsTail(n.id,500).then(t=>f(t,i)):o.runService.readEventsTail(n.id,5)));for(let n=0;n<r.length;n++){let t=r[n],a=g[n];console.log(`
10
+ Run ${t.id} \xB7 task ${t.task_id} \xB7 ${t.status}`);for(let d of a.slice(-5))console.log(u(d));}console.log();}async function y(o,s){let i=await o.runService.listAll(),e=Date.now()-s,r=i.filter(t=>{let a=new Date(t.started_at).getTime();return (t.finished_at?new Date(t.finished_at).getTime():Date.now())>=e||a>=e});if(o.context.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(`
11
+ No runs in the specified time window
12
+ `);return}let g=r.slice(0,20),n=await Promise.all(g.map(t=>o.runService.readEventsTail(t.id,500).then(a=>f(a,s))));for(let t=0;t<g.length;t++){let a=g[t],d=n[t];if(d.length!==0){console.log(`
13
+ Run ${a.id} \xB7 task ${a.task_id} \xB7 agent ${a.agent_id} \xB7 ${a.status}`);for(let $ of d.slice(-10))console.log(u($));}}r.length>20&&console.log(`
14
+ ${q(`(showing 20 of ${r.length} matching runs)`)}`),console.log();}async function S(o,s){let i=new Set,e=new Set;if(s.runId&&i.add(s.runId),s.taskId){let n=await o.runService.listForTask(s.taskId);for(let t of n)i.add(t.id);}s.agentId&&e.add(s.agentId);let r=i.size>0||e.size>0;console.log(`
15
+ ${q("Following live events...")} ${q("(Ctrl+C to stop)")}
16
+ `);let g=o.eventBus.onAny(n=>{let t=new Date().toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"});if(r){if("runId"in n&&i.size>0&&!i.has(n.runId))return;if("agentId"in n&&e.size>0){let a=n;if(!e.has(a.agentId))return}}switch(n.type){case "agent:output":{let a=typeof n.data=="string"?n.data.slice(0,80):"";console.log(` ${q(t)} ${c("agentAction")} ${a}`);break}case "agent:file_changed":console.log(` ${q(t)} ${c("agentAction")} Modified ${n.path}`);break;case "agent:error":console.log(` ${q(t)} ${c("failed")} ${n.error}`);break;case "agent:started":console.log(` ${q(t)} ${c("orchestratorEvent")} Started ${n.runId} (agent: ${n.agentId})`);break;case "agent:completed":n.success?console.log(` ${q(t)} ${c("done")} DONE ${n.runId}`):console.log(` ${q(t)} ${c("failed")} FAIL ${n.runId}`);break;case "run:retry":console.log(` ${q(t)} ${c("retrying")} RETRY attempt ${n.attempt} \xB7 next in ${Math.round(n.delay_ms/1e3)}s`);break;case "orchestrator:stall_detected":console.log(` ${q(t)} ${c("warning")} STALL ${n.runId}`);break}});await new Promise(n=>{let t=()=>{g(),n();};process.once("SIGINT",t),process.once("SIGTERM",t);});}function k(o){let s=o.match(/^(\d+)(s|m|h|d)$/);if(!s)throw new c$1(`Invalid duration: "${o}". Use format: 5m, 1h, 30s, 1d`);let i=parseInt(s[1],10);switch(s[2]){case "s":return i*1e3;case "m":return i*6e4;case "h":return i*36e5;case "d":return i*864e5;default:return i*6e4}}export{L as registerLogsCommand};
@@ -0,0 +1,6 @@
1
+ export { Orchestrator } from './chunk-XJ6KTO3E.js';
2
+ import './chunk-XUZZJCKG.js';
3
+ import './chunk-RHFRHCN5.js';
4
+ import './chunk-NLQAJ7TW.js';
5
+ //# sourceMappingURL=orchestrator-FWROY4JD.js.map
6
+ //# sourceMappingURL=orchestrator-FWROY4JD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-NC2NCJBC.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-FWROY4JD.js"}
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import {d as d$2,e as e$2,c as c$1}from'./chunk-LY3X2UHQ.js';import {e,c,b,d as d$1,g,f}from'./chunk-KR7VDF23.js';import {a}from'./chunk-CHRW4CLD.js';import {a as a$1}from'./chunk-P4JTJBWO.js';import {d,l,h,e as e$1,n}from'./chunk-IKNBPOQL.js';import {dirname}from'path';import A from'fs/promises';import {execFile}from'child_process';function 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=r.filter(a=>a.status==="in_progress"&&a.scope?.length),p=new x(m.map(a=>a.scope));for(let a of n)if(a.scope?.length)if(p.overlapsAny(a.scope)){let o=m.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 l)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$1=await this.deps.agentStore.get(e$1.agent_id);n$1&&(n$1.current_task=void 0,n$1.last_error={message:s.slice(0,500),kind:i??n(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n$1));let u=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(n$1?.stats.tasks_failed??0)+1,total_runs:(n$1?.stats.total_runs??0)+1,total_runtime_ms:(n$1?.stats.total_runtime_ms??0)+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};
@@ -17,4 +17,4 @@ import {j,q,g,d,e,o,l,n,m}from'./chunk-64WUDYEM.js';function x(_,a){let c=_.comm
17
17
  Review Results
18
18
  ${"\u2500".repeat(42)}`);for(let o of t.review_results){let n=o.passed?"\u2713":"\u2717";if(console.log(` ${n} ${o.criterion}: ${o.passed?"passed":"failed"}`),o.output)for(let l of o.output.split(`
19
19
  `))console.log(` ${l}`);}}console.log();}),c.command("edit <id>").description("Open task in $EDITOR to modify title, priority and description").action(async e=>{let t=await a.taskService.get(e),{openInEditor:i,toEditorContent:o,fromEditorContent:n}=await import('./editor-7IFRWVTL.js'),l=t.attachments?.length?`
20
- # Attachments: ${t.attachments.join(", ")}`:"",d=o({title:t.title,priority:t.priority,description:t.description})+l,s=await i(d),r=n(s),g={};if(r.title&&r.title!==t.title&&(g.title=r.title),r.priority&&r.priority!==t.priority&&(g.priority=r.priority),r.description!==void 0&&r.description!==t.description&&(g.description=r.description??""),Object.keys(g).length===0){console.log(" No changes.");return}let w=await a.taskService.update(e,g);j(`Updated ${w.id} "${w.title}"`);}),c.command("assign <task-id> <agent-id>").description("Assign task to agent").action(async(e,t)=>{let i=await a.taskService.assign(e,t);j(`Assigned ${i.id} \u2192 ${t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:i}=await import('./container-DUCZ7DUL.js');await(await i(a.context)).orchestrator.cancelTask(e);}else await a.taskService.cancel(e);j(`Cancelled ${e}`);}),c.command("approve <id>").description("Approve a task in review").action(async e=>{await a.taskService.updateStatus(e,"done"),j(`Approved ${e}`);}),c.command("reject <id>").description("Reject a task and send it back for rework").option("-r, --reason <reason>","Feedback for the agent explaining what to fix").action(async(e,t)=>{await a.taskService.reject(e,t.reason),j(`Rejected ${e} \u2192 todo${t.reason?` (reason: ${t.reason})`:""}`);}),c.command("retry <id>").description("Retry a failed task").action(async e=>{await a.taskService.retry(e),j(`Reset ${e} to todo`);});}export{x as registerTaskCommand};
20
+ # Attachments: ${t.attachments.join(", ")}`:"",d=o({title:t.title,priority:t.priority,description:t.description})+l,s=await i(d),r=n(s),g={};if(r.title&&r.title!==t.title&&(g.title=r.title),r.priority&&r.priority!==t.priority&&(g.priority=r.priority),r.description!==void 0&&r.description!==t.description&&(g.description=r.description??""),Object.keys(g).length===0){console.log(" No changes.");return}let w=await a.taskService.update(e,g);j(`Updated ${w.id} "${w.title}"`);}),c.command("assign <task-id> <agent-id>").description("Assign task to agent").action(async(e,t)=>{let i=await a.taskService.assign(e,t);j(`Assigned ${i.id} \u2192 ${t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:i}=await import('./container-RFWMXKD6.js');await(await i(a.context)).orchestrator.cancelTask(e);}else await a.taskService.cancel(e);j(`Cancelled ${e}`);}),c.command("approve <id>").description("Approve a task in review").action(async e=>{await a.taskService.updateStatus(e,"done"),j(`Approved ${e}`);}),c.command("reject <id>").description("Reject a task and send it back for rework").option("-r, --reason <reason>","Feedback for the agent explaining what to fix").action(async(e,t)=>{await a.taskService.reject(e,t.reason),j(`Rejected ${e} \u2192 todo${t.reason?` (reason: ${t.reason})`:""}`);}),c.command("retry <id>").description("Retry a failed task").action(async e=>{await a.taskService.retry(e),j(`Reset ${e} to todo`);});}export{x as registerTaskCommand};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function ct(d,e){d.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let S=await e.taskService.list(),w=await e.agentService.list(),h=await e.stateStore.read(),{render:k}=await import('ink'),{createElement:T}=await import('react'),{App:b}=await import('./App-BMY7F63C.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??"claude",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);}}),{kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await it(),l&&await e.orchestrator.stop().catch(()=>{}),o&&o.stop(),e.eventBus.clear();});}export{ct as registerTuiCommand};
2
+ function ct(d,e){d.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let S=await e.taskService.list(),w=await e.agentService.list(),h=await e.stateStore.read(),{render:k}=await import('ink'),{createElement:T}=await import('react'),{App:b}=await import('./App-MY7AVM3X.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??"claude",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);}}),{incrementalRendering:true,kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await it(),l&&await e.orchestrator.stop().catch(()=>{}),o&&o.stop(),e.eventBus.clear();});}export{ct as registerTuiCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxgeneral/orch",
3
- "version": "1.0.14",
3
+ "version": "1.0.15",
4
4
  "description": "AI agent runtime — orchestrate Claude, Cursor, Codex & OpenCode as one team. Multi-agent task automation with state machine, auto-retry, inter-agent messaging, goals and teams. Zero-config CLI + programmatic API.",
5
5
  "type": "module",
6
6
  "engines": {