@oxgeneral/orch 1.0.11 → 1.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/App-BMY7F63C.js +22 -0
- package/dist/{agent-SI4JF5MV.js → agent-TU6OC7ZT.js} +2 -2
- package/dist/{chunk-OLKQBQ4I.js → chunk-C6II4C6Y.js} +18 -6
- package/dist/chunk-C6II4C6Y.js.map +1 -0
- package/dist/chunk-JM2WRI46.js +2 -0
- package/dist/{claude-OTQ2NSJR.js → claude-EMBYYPW4.js} +5 -2
- package/dist/claude-EMBYYPW4.js.map +1 -0
- package/dist/claude-GIGROCH5.js +2 -0
- package/dist/cli.js +1 -1
- package/dist/{container-NS3YS47A.js → container-DUCZ7DUL.js} +2 -2
- package/dist/disk-observer-B3NOZ2QA.js +4 -0
- package/dist/{doctor-Q3GHJNZL.js → doctor-SKIWAKHW.js} +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/orchestrator-NC2NCJBC.js +6 -0
- package/dist/{orchestrator-47LRXS6X.js.map → orchestrator-NC2NCJBC.js.map} +1 -1
- package/dist/orchestrator-YXZUSS54.js +17 -0
- package/dist/{task-HEPJYY7D.js → task-7FTB4EC3.js} +1 -1
- package/dist/tui-SWKBOSF3.js +2 -0
- package/package.json +1 -1
- package/skills/orch/SKILL.md +40 -0
- package/dist/App-AMHLKLQC.js +0 -22
- package/dist/chunk-HYPSQAQX.js +0 -2
- package/dist/chunk-OLKQBQ4I.js.map +0 -1
- package/dist/claude-ADMRIWTR.js +0 -2
- package/dist/claude-OTQ2NSJR.js.map +0 -1
- package/dist/orchestrator-47LRXS6X.js +0 -6
- package/dist/orchestrator-R23BOZDZ.js +0 -17
- package/dist/tui-H3L67RHY.js +0 -2
|
@@ -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
|
-
`);}}}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,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.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-ADMRIWTR.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-R23BOZDZ.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};
|
|
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};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {d}from'./chunk-ZMLF5HI5.js';import {open}from'fs/promises';var y=5*6e4,m=512*1024,I=64*1024,f=class{constructor(t){this.opts=t;this.pollIntervalMs=t.pollIntervalMs??1e3;}pollIntervalMs;handler=null;intervalHandle=null;tracked=new Map;prevRunning=new Map;isPolling=false;subscribe(t){return this.handler=t,this.intervalHandle||(this.poll().catch(()=>{}),this.intervalHandle=setInterval(()=>{this.poll().catch(()=>{});},this.pollIntervalMs)),()=>{this.handler=null,this.stop();}}stop(){this.intervalHandle&&(clearInterval(this.intervalHandle),this.intervalHandle=null);}emit(t){try{this.handler?.(t);}catch{}}async poll(){if(!(!this.handler||this.isPolling)){this.isPolling=true;try{await this.doPoll();}finally{this.isPolling=false;}}}async doPoll(){let t;try{t=await this.opts.stateStore.read();}catch{return}let a=Date.now(),n=Object.values(t.running),s=new Set;for(let e of n){let r=e.run_id;s.add(r);let i=this.tracked.get(r);if(i){i.lastSeenAt=a;continue}this.tracked.set(r,{runId:r,agentId:e.agent_id,taskId:e.task_id,offset:0,remainder:"",lastSeenAt:a}),this.emit({type:"agent:started",agentId:e.agent_id,taskId:e.task_id,runId:r});}for(let[e,r]of this.prevRunning){if(s.has(e))continue;let i=this.tracked.get(e);i&&await this.tailRunEvents(i);let o=await d(this.opts.paths.runPath(e)).catch(()=>null),d$1=o?.status==="succeeded";this.emit({type:"agent:completed",runId:e,agentId:r.agent_id,success:d$1}),o?.task_id&&this.emit({type:"task:status_changed",taskId:o.task_id,from:"in_progress",to:d$1?"review":"failed"});}for(let e of this.tracked.values())s.has(e.runId)&&await this.tailRunEvents(e);s.size>0&&this.emit({type:"orchestrator:tick",running:s.size,queued:0});let l=new Map;for(let e of n)l.set(e.run_id,e);this.prevRunning=l;for(let[e]of this.tracked)!s.has(e)&&a-this.tracked.get(e).lastSeenAt>y&&this.tracked.delete(e);}async tailRunEvents(t){let a=this.opts.paths.runEventsPath(t.runId),n=null;try{n=await open(a,"r");let s=await n.stat();if(s.size<=t.offset)return;let l=Math.min(s.size-t.offset,m),e=Buffer.alloc(l),{bytesRead:r}=await n.read(e,0,l,t.offset);if(r===0)return;let i=t.remainder+e.subarray(0,r).toString("utf8"),o=i.split(`
|
|
3
|
+
`),d=o.pop()??"";if(i.endsWith(`
|
|
4
|
+
`))t.remainder="",t.offset+=r;else {t.remainder=d.length>I?"":d;let c=t.remainder?Buffer.byteLength(d,"utf8"):0;t.offset+=r-c;}for(let c of o){let u=c.trim();if(u)try{let g=JSON.parse(u),p=this.translateEvent(g,t);p&&this.emit(p);}catch{}}}catch{}finally{await n?.close().catch(()=>{});}}translateEvent(t,a){switch(t.type){case "agent_output":{let n=typeof t.data=="string"?t.data:JSON.stringify(t.data);return {type:"agent:output",runId:a.runId,agentId:a.agentId,data:n}}case "file_changed":{let n=typeof t.data=="string"?t.data:t.data?.path??"";return {type:"agent:file_changed",runId:a.runId,agentId:a.agentId,path:n}}case "error":{let n=typeof t.data=="string"?t.data:JSON.stringify(t.data);return {type:"agent:error",runId:a.runId,agentId:a.agentId,error:n}}case "tool_call":case "command_run":{let n=typeof t.data=="string"?t.data:JSON.stringify(t.data);return {type:"agent:output",runId:a.runId,agentId:a.agentId,data:n}}case "done":return null;default:return null}}};export{f as DiskObserver};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$4}from'./chunk-HMMPM7MF.js';import {b}from'./chunk-3AXNSYCM.js';import'./chunk-ZMLF5HI5.js';import {p,c,q}from'./chunk-64WUDYEM.js';import {a as a$1}from'./chunk-CDFA4IIQ.js';import {a as a$2}from'./chunk-
|
|
2
|
+
import {a as a$4}from'./chunk-HMMPM7MF.js';import {b}from'./chunk-3AXNSYCM.js';import'./chunk-ZMLF5HI5.js';import {p,c,q}from'./chunk-64WUDYEM.js';import {a as a$1}from'./chunk-CDFA4IIQ.js';import {a as a$2}from'./chunk-JM2WRI46.js';import {a as a$3}from'./chunk-LOJ26OVK.js';import'./chunk-FQ5YUP4J.js';import'./chunk-P4JTJBWO.js';import'./chunk-IKNBPOQL.js';import {a}from'./chunk-6MJ7V6VY.js';import i from'chalk';function P(u,t){u.command("doctor").description("Check adapters and dependencies").action(async()=>{let c$1,n,d=false;if(t)c$1=t.doctorService,n=t.paths,d=true;else {let o=new a,e=new a$1;e.register(new a$2(o)),e.register(new a$3(o)),c$1=new a$4(e,o,process.cwd()),n=new b(process.cwd());}console.log(),console.log(` ${p("orch doctor")} \xB7 checking adapters and dependencies`),console.log();let a$5=await c$1.runAll();if(t?.context.json){console.log(JSON.stringify(a$5,null,2));return}for(let o of a$5.checks){let e=o.status==="ok"?i.ansi256(72)(c("done")):o.status==="fail"?i.ansi256(167)(c("failed")):q("\u2014"),l=o.detail?q(` ${o.detail}`):"";console.log(` ${e} ${o.name.padEnd(12)}${l}`);}if(n){let o=await n.isInitialized();if(o&&d){let e=await t.agentService.list(),l=await t.taskService.list();console.log(),console.log(` ${i.ansi256(72)(c("done"))} .orchestry/ ${q(`exists \xB7 ${e.length} agents \xB7 ${l.length} tasks`)}`);}else o||(console.log(),console.log(` ${i.ansi256(167)(c("failed"))} .orchestry/ ${q("not found \u2014 run: orch init")}`));}console.log(),console.log(` ${a$5.adaptersReady} of ${a$5.adaptersTotal} adapters ready`),console.log();});}export{P as registerDoctorCommand};
|
package/dist/index.d.ts
CHANGED
|
@@ -67,9 +67,11 @@ interface CreateTaskInput {
|
|
|
67
67
|
*/
|
|
68
68
|
type AgentStatus = 'idle' | 'running' | 'error' | 'disabled';
|
|
69
69
|
type ApprovalPolicy = 'suggest' | 'auto' | 'manual';
|
|
70
|
+
type ReasoningEffort = 'low' | 'medium' | 'high';
|
|
70
71
|
interface AgentConfig {
|
|
71
72
|
command?: string;
|
|
72
73
|
model?: string;
|
|
74
|
+
effort?: ReasoningEffort;
|
|
73
75
|
approval_policy?: ApprovalPolicy;
|
|
74
76
|
max_turns?: number;
|
|
75
77
|
timeout_ms?: number;
|
|
@@ -109,6 +111,7 @@ interface CreateAgentInput {
|
|
|
109
111
|
role?: string;
|
|
110
112
|
command?: string;
|
|
111
113
|
model?: string;
|
|
114
|
+
effort?: ReasoningEffort;
|
|
112
115
|
approval_policy?: ApprovalPolicy;
|
|
113
116
|
max_turns?: number;
|
|
114
117
|
timeout_ms?: number;
|
|
@@ -811,6 +814,7 @@ declare class AgentService {
|
|
|
811
814
|
name?: string;
|
|
812
815
|
role?: string;
|
|
813
816
|
model?: string;
|
|
817
|
+
effort?: Agent['config']['effort'];
|
|
814
818
|
approval_policy?: Agent['config']['approval_policy'];
|
|
815
819
|
}): Promise<Agent>;
|
|
816
820
|
disable(id: string): Promise<Agent>;
|
|
@@ -1534,4 +1538,4 @@ declare function buildFullContainer(context: CliContext): Promise<Container>;
|
|
|
1534
1538
|
*/
|
|
1535
1539
|
declare function buildContainer(context: CliContext): Promise<Container>;
|
|
1536
1540
|
|
|
1537
|
-
export { type AdapterErrorHint, AdapterErrorKind, AdapterRegistry, type AdapterTestResult, type Agent, type AgentConfig, type AgentEvent, type AgentLastError, AgentNotFoundError, AgentService, type AgentStats, type AgentStatus, type ApprovalPolicy, type ClipboardContentType, type ClipboardImage, type Container, type CreateAgentInput, type CreateTaskInput, ERROR_HINTS, EventBus, type EventPayload, type ExecuteParams, type IAgentAdapter, type ISkillLoader, type LightContainer, NotInitializedError, Orchestrator, type OrchestratorConfig, type OrchestratorEvent, type OrchestratorEventType, type OrchestratorState, OrchestryError, type ProjectConfig, type RetryEntry, type Run, type RunEvent, type RunEventType, RunService, type RunStatus, type RunningEntry, type SchedulingConfig, SkillLoader, type Task, TaskNotFoundError, type TaskProof, TaskService, type TaskStatus, type TokenUsage, WorkspaceError, type WorkspaceMode, buildContainer, buildFullContainer, buildLightContainer, canTransition, classifyAdapterError, createTokenUsage, detectClipboardType, getClipboardImage, isBlocked, isClipboardToolAvailable, isDispatchable, isTerminal, resolveFailureStatus };
|
|
1541
|
+
export { type AdapterErrorHint, AdapterErrorKind, AdapterRegistry, type AdapterTestResult, type Agent, type AgentConfig, type AgentEvent, type AgentLastError, AgentNotFoundError, AgentService, type AgentStats, type AgentStatus, type ApprovalPolicy, type ClipboardContentType, type ClipboardImage, type Container, type CreateAgentInput, type CreateTaskInput, ERROR_HINTS, EventBus, type EventPayload, type ExecuteParams, type IAgentAdapter, type ISkillLoader, type LightContainer, NotInitializedError, Orchestrator, type OrchestratorConfig, type OrchestratorEvent, type OrchestratorEventType, type OrchestratorState, OrchestryError, type ProjectConfig, type ReasoningEffort, type RetryEntry, type Run, type RunEvent, type RunEventType, RunService, type RunStatus, type RunningEntry, type SchedulingConfig, SkillLoader, type Task, TaskNotFoundError, type TaskProof, TaskService, type TaskStatus, type TokenUsage, WorkspaceError, type WorkspaceMode, buildContainer, buildFullContainer, buildLightContainer, canTransition, classifyAdapterError, createTokenUsage, detectClipboardType, getClipboardImage, isBlocked, isClipboardToolAvailable, isDispatchable, isTerminal, resolveFailureStatus };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Paths } from './chunk-J7ITYXE6.js';
|
|
2
|
-
import { canTransition, isTerminal } from './chunk-
|
|
3
|
-
export { Orchestrator, canTransition, isBlocked, isDispatchable, isTerminal, resolveFailureStatus } from './chunk-
|
|
2
|
+
import { canTransition, isTerminal } from './chunk-C6II4C6Y.js';
|
|
3
|
+
export { Orchestrator, canTransition, isBlocked, isDispatchable, isTerminal, resolveFailureStatus } from './chunk-C6II4C6Y.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';
|
|
@@ -339,6 +339,7 @@ var AgentService = class {
|
|
|
339
339
|
config: {
|
|
340
340
|
command: input.command,
|
|
341
341
|
model: input.model,
|
|
342
|
+
effort: input.effort,
|
|
342
343
|
approval_policy: input.approval_policy ?? this.config.defaults.agent.approval_policy,
|
|
343
344
|
max_turns: input.max_turns ?? this.config.defaults.agent.max_turns,
|
|
344
345
|
timeout_ms: input.timeout_ms ?? this.config.defaults.agent.timeout_ms,
|
|
@@ -392,6 +393,7 @@ var AgentService = class {
|
|
|
392
393
|
}
|
|
393
394
|
if (fields.role !== void 0) agent.role = fields.role || void 0;
|
|
394
395
|
if (fields.model !== void 0) agent.config.model = fields.model || void 0;
|
|
396
|
+
if (fields.effort !== void 0) agent.config.effort = fields.effort || void 0;
|
|
395
397
|
if (fields.approval_policy !== void 0) agent.config.approval_policy = fields.approval_policy;
|
|
396
398
|
await this.agentStore.save(agent);
|
|
397
399
|
return agent;
|
|
@@ -1944,7 +1946,7 @@ async function buildFullContainer(context) {
|
|
|
1944
1946
|
] = await Promise.all([
|
|
1945
1947
|
import('./process-manager-A36Y7LHP.js'),
|
|
1946
1948
|
import('./registry-JXXRLJ5J.js'),
|
|
1947
|
-
import('./claude-
|
|
1949
|
+
import('./claude-EMBYYPW4.js'),
|
|
1948
1950
|
import('./codex-WQ3LU3MM.js'),
|
|
1949
1951
|
import('./cursor-TKV5FFCN.js'),
|
|
1950
1952
|
import('./shell-PMLIRG3N.js'),
|
|
@@ -1952,7 +1954,7 @@ async function buildFullContainer(context) {
|
|
|
1952
1954
|
import('./workspace-manager-KUU7UMMC.js'),
|
|
1953
1955
|
import('./template-engine-XOH3FZPU.js'),
|
|
1954
1956
|
import('./skill-loader-RHCFIK74.js'),
|
|
1955
|
-
import('./orchestrator-
|
|
1957
|
+
import('./orchestrator-NC2NCJBC.js'),
|
|
1956
1958
|
import('./doctor-service-F2SXDWHS.js')
|
|
1957
1959
|
]);
|
|
1958
1960
|
const processManager = new ProcessManager();
|