@oxgeneral/orch 1.0.25 → 1.0.27

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.
Files changed (40) hide show
  1. package/dist/App-YVHDT4VD.js +23 -0
  2. package/dist/{agent-6PI3NNZ5.js → agent-6ADS3VE2.js} +2 -2
  3. package/dist/agent-factory-XLLE3SJQ.js +2 -0
  4. package/dist/antigravity-LGKZHZL7.js +2 -0
  5. package/dist/antigravity-W43JJLR2.js +105 -0
  6. package/dist/antigravity-W43JJLR2.js.map +1 -0
  7. package/dist/chunk-AOJZCMUE.js +2 -0
  8. package/dist/chunk-DZK72HOZ.js +2 -0
  9. package/dist/chunk-HYQXUJYV.js +4 -0
  10. package/dist/{chunk-JDG6ZKIM.js → chunk-SLMXPTXV.js} +1 -1
  11. package/dist/{chunk-FGQJYB6G.js → chunk-TKGW23QJ.js} +43 -6
  12. package/dist/chunk-TKGW23QJ.js.map +1 -0
  13. package/dist/chunk-YKUO5PD4.js +3 -0
  14. package/dist/cli.js +1 -1
  15. package/dist/container-TQGRDHAU.js +4 -0
  16. package/dist/doctor-X2D67Q6Q.js +2 -0
  17. package/dist/grok-GIH3ESBQ.js +179 -0
  18. package/dist/grok-GIH3ESBQ.js.map +1 -0
  19. package/dist/grok-YX757Y3M.js +2 -0
  20. package/dist/index.d.ts +15 -2
  21. package/dist/index.js +34 -4
  22. package/dist/index.js.map +1 -1
  23. package/dist/{init-4D6QMPQL.js → init-CPL6DJ7W.js} +7 -7
  24. package/dist/orchestrator-QIRX6DKR.js +6 -0
  25. package/dist/{orchestrator-KV3VVGZR.js.map → orchestrator-QIRX6DKR.js.map} +1 -1
  26. package/dist/orchestrator-TY5HYXUH.js +17 -0
  27. package/dist/{org-RL6SBZI4.js → org-T5DCYQI6.js} +1 -1
  28. package/dist/{task-YMPSU6YE.js → task-XTZZZBBJ.js} +1 -1
  29. package/dist/tui-25JIN7MP.js +2 -0
  30. package/package.json +3 -1
  31. package/readme.md +3 -3
  32. package/dist/App-IC2HLH6T.js +0 -23
  33. package/dist/agent-factory-T6WZIQPM.js +0 -2
  34. package/dist/chunk-4O4L3Y2U.js +0 -2
  35. package/dist/chunk-FGQJYB6G.js.map +0 -1
  36. package/dist/container-KJNQCG2C.js +0 -4
  37. package/dist/doctor-DEGM2HCD.js +0 -2
  38. package/dist/orchestrator-AVJ23Q5T.js +0 -17
  39. package/dist/orchestrator-KV3VVGZR.js +0 -6
  40. package/dist/tui-NZ55TCHU.js +0 -2
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {c as c$1,b as b$1,a as a$2}from'./chunk-4O4L3Y2U.js';import {f}from'./chunk-LY3X2UHQ.js';import {a}from'./chunk-N4OXN2HW.js';import'./chunk-CHRW4CLD.js';import {k as k$1,j as j$1,q,i}from'./chunk-64WUDYEM.js';import {b}from'./chunk-6E6DC7OE.js';import {k,j,c,a as a$1}from'./chunk-ZMLF5HI5.js';import'./chunk-LRYVT4D4.js';import T from'path';import _ from'fs/promises';import I from'readline';import {execFile}from'child_process';import {promisify}from'util';var E=`Agent architect \u2014 designs and creates AI agents for the orchestrator via \`orch agent add\`.
2
+ import {a}from'./chunk-N4OXN2HW.js';import {c as c$1,b as b$1,a as a$2}from'./chunk-DZK72HOZ.js';import {f}from'./chunk-LY3X2UHQ.js';import'./chunk-CHRW4CLD.js';import {k as k$1,j as j$1,q,i}from'./chunk-64WUDYEM.js';import {b}from'./chunk-6E6DC7OE.js';import {k,j,c,a as a$1}from'./chunk-ZMLF5HI5.js';import'./chunk-LRYVT4D4.js';import T from'path';import _ from'fs/promises';import I from'readline';import {execFile}from'child_process';import {promisify}from'util';var E=`Agent architect \u2014 designs and creates AI agents for the orchestrator via \`orch agent add\`.
3
3
 
4
4
  ## CREATION PROCESS
5
5
 
@@ -13,7 +13,7 @@ import {c as c$1,b as b$1,a as a$2}from'./chunk-4O4L3Y2U.js';import {f}from'./ch
13
13
  Do NOT include CLI documentation or goal-mode instructions \u2014 these are already injected by the system prompt template.
14
14
 
15
15
  3) CHOOSE CONFIGURATION:
16
- - adapter: \`claude\` (AI tasks), \`shell\` (bash scripts), \`codex\` (OpenAI Codex), \`pi\` (Pi coding agent RPC), \`cursor\` (Cursor IDE), \`opencode\` (OpenCode \u2014 multi-provider)
16
+ - adapter: \`claude\` (AI tasks), \`shell\` (bash scripts), \`codex\` (OpenAI Codex), \`pi\` (Pi coding agent RPC), \`cursor\` (Cursor IDE), \`opencode\` (OpenCode \u2014 multi-provider), \`grok\` (Grok CLI), \`antigravity\` (Google Antigravity CLI)
17
17
  - model: choose based on task complexity \u2014 use the \`capable\` tier for architecture/review, \`balanced\` for routine work, \`fast\` for simple/templated tasks. Model names vary by adapter.
18
18
  - approval_policy: \`auto\` (no confirmation) / \`suggest\` (proposes actions) / \`manual\` (human approval)
19
19
  - max_turns: 50 (default), up to 100 for complex tasks
@@ -25,7 +25,7 @@ import {c as c$1,b as b$1,a as a$2}from'./chunk-4O4L3Y2U.js';import {f}from'./ch
25
25
 
26
26
  There are two types of skills:
27
27
 
28
- **Library skills** \u2014 ORCH loads Markdown content and injects it into the agent's system prompt. Works with ALL adapters (claude, opencode, codex, pi, cursor, shell). Use plain names without colons:
28
+ **Library skills** \u2014 ORCH loads Markdown content and injects it into the agent's system prompt. Works with ALL adapters (claude, opencode, codex, pi, cursor, grok, antigravity, shell). Use plain names without colons:
29
29
 
30
30
  | Category | Skills |
31
31
  |----------|--------|
@@ -58,12 +58,12 @@ You can mix both types: \`--skills "review,feature-dev:code-explorer,investigate
58
58
  - Never use the -e/--edit flag in automated mode \u2014 it opens an interactive editor.
59
59
  - Always specify --role when calling \`orch agent add\`.
60
60
 
61
- After creation \u2014 \`orch context set agent-<name> "<capabilities>"\`.`;function P(a="claude"){let e=a$2(a,"balanced");return [{id:"agt_creator",name:"Agent Creator",adapter:a,role:E,config:{model:e||void 0,approval_policy:"suggest",max_turns:50,timeout_ms:36e5,stall_timeout_ms:3e5,skills:a==="claude"?["document-skills:skill-creator"]:[]},status:"idle",stats:{tasks_completed:0,tasks_failed:0,total_runs:0,total_runtime_ms:0}}]}var l=promisify(execFile);async function R(a$2={}){let e=process.cwd(),o=new b(e);if(await k(o.root)){k$1("Already initialized");return}let t=a$2.adapter??await O();await Promise.all([j(o.tasksDir),j(o.agentsDir),j(o.goalsDir),j(o.runsDir),j(o.templatesDir),j(o.logsDir)]);let r=await N(e),s=structuredClone(a);s.project.name=a$2.name??T.basename(e),s.defaults.agent.adapter=t,r||(s.defaults.agent.workspace_mode="shared");let p=["# Runtime state","state.json","*.lock","","# Logs and runs","runs/","logs/","","# Agent workspaces","workspaces/"].join(`
61
+ After creation \u2014 \`orch context set agent-<name> "<capabilities>"\`.`;function P(a="claude"){let e=a$2(a,"balanced");return [{id:"agt_creator",name:"Agent Creator",adapter:a,role:E,config:{model:e||void 0,approval_policy:"suggest",max_turns:50,timeout_ms:36e5,stall_timeout_ms:3e5,skills:a==="claude"?["document-skills:skill-creator"]:[]},status:"idle",stats:{tasks_completed:0,tasks_failed:0,total_runs:0,total_runtime_ms:0}}]}var l=promisify(execFile);async function R(a$2={}){let e=process.cwd(),o=new b(e);if(await k(o.root)){k$1("Already initialized");return}let t=a$2.adapter??await O();await Promise.all([j(o.tasksDir),j(o.agentsDir),j(o.goalsDir),j(o.runsDir),j(o.templatesDir),j(o.logsDir)]);let r=await L(e),s=structuredClone(a);s.project.name=a$2.name??T.basename(e),s.defaults.agent.adapter=t,r||(s.defaults.agent.workspace_mode="shared");let p=["# Runtime state","state.json","*.lock","","# Logs and runs","runs/","logs/","","# Agent workspaces","workspaces/"].join(`
62
62
  `)+`
63
63
  `,b$1=[".orchestry","node_modules",".env",".env.*","dist","build",".next","__pycache__","*.pyc",".venv"].join(`
64
64
  `)+`
65
- `,g=P(t);await Promise.all([c(o.configPath,s),a$1(o.gitignorePath,p),a$1(o.workspaceExcludePath,b$1),a$1(o.defaultTemplatePath(),f),...g.map(c$1=>c(o.agentPath(c$1.id),c$1))]),await S(e),r&&await L(e),console.log(),j$1("initialized"),console.log(),console.log(` Created ${q(".orchestry/")}`),console.log(` ${q("\u251C\u2500\u2500")} config.yml`),console.log(` ${q("\u251C\u2500\u2500")} tasks/`),console.log(` ${q("\u251C\u2500\u2500")} agents/`);for(let c of g)console.log(` ${q("\u2502 \u2514\u2500\u2500")} ${c.id}.yml ${q(`(${c.name})`)}`);console.log(` ${q("\u251C\u2500\u2500")} templates/default.md`),console.log(` ${q("\u2514\u2500\u2500")} .gitignore`),console.log();}async function O(){let e=(await Promise.all(c$1.filter(t=>t!=="shell").map(async t=>{let r=t==="cursor"?["cursor-agent"]:[t];for(let s of r)try{let{stdout:p}=await l(s,["--version"],{timeout:5e3});return {name:t,ok:!0,version:p.trim().split(`
66
- `)[0]}}catch{}return {name:t,ok:false}}))).filter(t=>t.ok);if(e.length===0)return console.log(` ${q("No AI adapters detected \u2014 defaulting to claude")}`),"claude";if(e.length===1)return console.log(` ${q(`Detected: ${e[0].name}`)} ${q(e[0].version?`(${e[0].version})`:"")}`),e[0].name;if(!process.stdout.isTTY||!process.stdin.isTTY)return e[0].name;console.log(),console.log(" Available adapters:");for(let t=0;t<e.length;t++){let r=e[t];console.log(` ${t+1}) ${r.name} ${q(r.version??"")}`);}console.log();let o=I.createInterface({input:process.stdin,output:process.stdout});try{let t=await new Promise(s=>{o.question(` Choose default adapter [1-${e.length}]: `,s);}),r=parseInt(t,10)-1;return r>=0&&r<e.length?e[r].name:e[0].name}finally{o.close();}}async function N(a){try{return await l("git",["rev-parse","--is-inside-work-tree"],{cwd:a}),!0}catch{try{return await l("git",["init"],{cwd:a}),!0}catch{return false}}}async function L(a){try{await l("git",["rev-parse","HEAD"],{cwd:a});}catch{try{await l("git",["add","-A"],{cwd:a}),await l("git",["commit","-m","Initial commit","--allow-empty"],{cwd:a});}catch{}}}async function S(a){let e=T.join(a,".gitignore");try{let o=await _.readFile(e,"utf-8");if(o.split(`
65
+ `,g=P(t);await Promise.all([c(o.configPath,s),a$1(o.gitignorePath,p),a$1(o.workspaceExcludePath,b$1),a$1(o.defaultTemplatePath(),f),...g.map(c$1=>c(o.agentPath(c$1.id),c$1))]),await S(e),r&&await N(e),console.log(),j$1("initialized"),console.log(),console.log(` Created ${q(".orchestry/")}`),console.log(` ${q("\u251C\u2500\u2500")} config.yml`),console.log(` ${q("\u251C\u2500\u2500")} tasks/`),console.log(` ${q("\u251C\u2500\u2500")} agents/`);for(let c of g)console.log(` ${q("\u2502 \u2514\u2500\u2500")} ${c.id}.yml ${q(`(${c.name})`)}`);console.log(` ${q("\u251C\u2500\u2500")} templates/default.md`),console.log(` ${q("\u2514\u2500\u2500")} .gitignore`),console.log();}async function O(){let e=(await Promise.all(c$1.filter(t=>t!=="shell").map(async t=>{let r=t==="cursor"?["cursor-agent"]:t==="antigravity"?["agy"]:[t];for(let s of r)try{let{stdout:p}=await l(s,["--version"],{timeout:5e3});return {name:t,ok:!0,version:p.trim().split(`
66
+ `)[0]}}catch{}return {name:t,ok:false}}))).filter(t=>t.ok);if(e.length===0)return console.log(` ${q("No AI adapters detected \u2014 defaulting to claude")}`),"claude";if(e.length===1)return console.log(` ${q(`Detected: ${e[0].name}`)} ${q(e[0].version?`(${e[0].version})`:"")}`),e[0].name;if(!process.stdout.isTTY||!process.stdin.isTTY)return e[0].name;console.log(),console.log(" Available adapters:");for(let t=0;t<e.length;t++){let r=e[t];console.log(` ${t+1}) ${r.name} ${q(r.version??"")}`);}console.log();let o=I.createInterface({input:process.stdin,output:process.stdout});try{let t=await new Promise(s=>{o.question(` Choose default adapter [1-${e.length}]: `,s);}),r=parseInt(t,10)-1;return r>=0&&r<e.length?e[r].name:e[0].name}finally{o.close();}}async function L(a){try{return await l("git",["rev-parse","--is-inside-work-tree"],{cwd:a}),!0}catch{try{return await l("git",["init"],{cwd:a}),!0}catch{return false}}}async function N(a){try{await l("git",["rev-parse","HEAD"],{cwd:a});}catch{try{await l("git",["add","-A"],{cwd:a}),await l("git",["commit","-m","Initial commit","--allow-empty"],{cwd:a});}catch{}}}async function S(a){let e=T.join(a,".gitignore");try{let o=await _.readFile(e,"utf-8");if(o.split(`
67
67
  `).some(r=>r.trim()===".orchestry"))return;let t=o.endsWith(`
68
68
  `)?"":`
69
69
  `;await _.appendFile(e,`${t}
@@ -71,4 +71,4 @@ After creation \u2014 \`orch context set agent-<name> "<capabilities>"\`.`;funct
71
71
  .orchestry
72
72
  `);}catch{await a$1(e,`# Orchestry state
73
73
  .orchestry
74
- `);}}function V(a){a.command("init").description("Initialize .orchestry/ in the current directory").option("--name <name>","Project name").option("--adapter <adapter>","Default agent adapter (claude, opencode, codex, cursor, pi, shell)").action(async e=>{if(e.adapter&&!b$1(e.adapter)){i(`Unknown adapter "${e.adapter}"`,`Supported: ${c$1.join(", ")}`),process.exitCode=2;return}await R(e),console.log(` Next: ${q('orch task add "Create backend agent" --assignee agt_creator')}`),console.log();});}export{V as registerInitCommand,R as runInit};
74
+ `);}}function V(a){a.command("init").description("Initialize .orchestry/ in the current directory").option("--name <name>","Project name").option("--adapter <adapter>","Default agent adapter (claude, opencode, codex, cursor, pi, grok, antigravity, shell)").action(async e=>{if(e.adapter&&!b$1(e.adapter)){i(`Unknown adapter "${e.adapter}"`,`Supported: ${c$1.join(", ")}`),process.exitCode=2;return}await R(e),console.log(` Next: ${q('orch task add "Create backend agent" --assignee agt_creator')}`),console.log();});}export{V as registerInitCommand,R as runInit};
@@ -0,0 +1,6 @@
1
+ export { Orchestrator } from './chunk-TKGW23QJ.js';
2
+ import './chunk-XUZZJCKG.js';
3
+ import './chunk-RHFRHCN5.js';
4
+ import './chunk-IESAV453.js';
5
+ //# sourceMappingURL=orchestrator-QIRX6DKR.js.map
6
+ //# sourceMappingURL=orchestrator-QIRX6DKR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-KV3VVGZR.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"orchestrator-QIRX6DKR.js"}
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import {e,c,b,d as d$1,g,f}from'./chunk-KR7VDF23.js';import {d as d$2,e as e$2,c as c$1}from'./chunk-LY3X2UHQ.js';import {a}from'./chunk-CHRW4CLD.js';import {a as a$1}from'./chunk-P4JTJBWO.js';import {d,m,h,e as e$1,o}from'./chunk-LRYVT4D4.js';import {dirname}from'path';import E from'fs/promises';import {execFile}from'child_process';function st(u,t){if(!u?.length||!t?.length)return false;for(let e of u)for(let s of t)if(ft(e,s))return true;return false}function q(u){let t=u.split("*")[0],e=!t.endsWith("/"),s=e?dirname(t):"";return {raw:u,base:t,isFile:e,dir:s}}var O=class{entries;constructor(t){this.entries=[];for(let e of t)if(e?.length)for(let s of e)this.entries.push(q(s));}overlapsAny(t){if(!t?.length||this.entries.length===0)return false;for(let e of t){let s=q(e);for(let i of this.entries)if(pt(s,i))return true}return false}add(t){if(t?.length)for(let e of t)this.entries.push(q(e));}get size(){return this.entries.length}};function pt(u,t){return u.raw===t.raw||u.base.startsWith(t.base)||t.base.startsWith(u.base)?true:u.isFile&&t.isFile?u.dir===t.dir&&u.dir!==".":false}function ft(u,t){if(u===t)return true;let e=u.split("*")[0],s=t.split("*")[0];if(e.startsWith(s)||s.startsWith(e))return true;if(!e.endsWith("/")&&!s.endsWith("/")){let i=dirname(e),r=dirname(s);return i===r&&i!=="."}return false}var it=Promise.resolve();async function G(u){let t,e=new Promise(i=>{t=i;}),s=it;it=e,await s;try{return await mt(u)}finally{t();}}var gt=6e4;async function mt(u){let t=await at(u);if(t!==null){if(St(t)&&!await vt(u))return {acquired:false,pid:t};await E.unlink(u).catch(()=>{});}try{let e=await E.open(u,"wx");return await e.writeFile(String(process.pid),"utf-8"),await e.close(),{acquired:!0,pid:process.pid}}catch(e){if(e.code==="EEXIST")return {acquired:false,pid:await at(u)??void 0};throw e}}async function I(u){await E.unlink(u).catch(()=>{});}async function rt(u){let t=Date.now()/1e3;await E.utimes(u,t,t).catch(()=>{});}async function at(u){try{let t=await E.readFile(u,"utf-8"),e=parseInt(t.trim(),10);return isNaN(e)?null:e}catch{return null}}async function vt(u){try{let t=await E.stat(u);return Date.now()-t.mtimeMs>gt}catch{return true}}function St(u){try{return process.kill(u,0),!0}catch(t){return t.code==="EPERM"}}var B=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?`${t.status??""}:${t.goalId??""}`:"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}},M=class{constructor(t){this.inner=t;}listCache=null;nameCache=new Map;async list(){if(this.listCache)return this.listCache;let t=await this.inner.list();return this.listCache=t,t}async get(t){return this.inner.get(t)}async getByName(t){if(this.nameCache.has(t))return this.nameCache.get(t)??null;let e=await this.inner.getByName(t);return this.nameCache.set(t,e),e}async save(t){await this.inner.save(t),this.listCache=null,this.nameCache.clear();}async delete(t){await this.inner.delete(t),this.listCache=null,this.nameCache.clear();}invalidate(){this.listCache=null,this.nameCache.clear();}},$=class{constructor(t){this.inner=t;}cache=new Map;async list(t){let e=t?.status??"__all__";if(this.cache.has(e))return this.cache.get(e);let s=await this.inner.list(t);return this.cache.set(e,s),s}async get(t){return this.inner.get(t)}async save(t){await this.inner.save(t),this.cache.clear();}async delete(t){await this.inner.delete(t),this.cache.clear();}invalidate(){this.cache.clear();}};var yt={test_pass:{cmd:"npm",args:["test"]},typecheck:{cmd:"npx",args:["tsc","--noEmit"]},lint:{cmd:"npm",args:["run","lint"]}},nt=["typecheck","lint","test_pass"],P=class{cwd;timeoutMs;failFast;constructor(t){this.cwd=t.cwd,this.timeoutMs=t.timeout_ms??12e4,this.failFast=t.fail_fast??true;}async runAll(t){let e=kt(t),s=[];for(let i of e){let r=await this.runCriterion(i);if(s.push(r),this.failFast&&!r.passed)break}return s}static allPassed(t){return t.length>0&&t.every(e=>e.passed)}static formatReport(t){return t.map(s=>{let i=s.passed?"\u2713":"\u2717",r=s.output;return `${i} ${s.criterion}: ${s.passed?"PASSED":"FAILED"}
3
+ ${r}`}).join(`
4
+
5
+ `)}runCriterion(t){let{cmd:e,args:s}=yt[t];return new Promise(i=>{execFile(e,s,{cwd:this.cwd,timeout:this.timeoutMs,maxBuffer:1024*1024},(r,o,n)=>{let d=(o+`
6
+ `+n).trim();i({criterion:t,passed:!r,output:d.slice(0,2e3)});});})}};function kt(u){return [...u].sort((t,e)=>{let s=nt.indexOf(t),i=nt.indexOf(e);return (s===-1?1/0:s)-(i===-1?1/0:i)})}var _t=8192,Tt=4096,ot=class u{constructor(t){this.deps=t;this.cachedTaskStore=new B(t.taskStore),this.cachedAgentStore=new M(t.agentStore),this.cachedGoalStore=t.goalStore?new $(t.goalStore):null;}intervalId=null;shuttingDown=false;state=null;abortControllers=new Map;cachedTaskStore;cachedAgentStore;cachedGoalStore;saveStateTimer=null;saveStateDirty=false;lockAcquired=false;consecutiveTickFailures=0;maxConsecutiveTickFailures=5;maxRetryQueueSize=100;signalHandlers=[];immediateDispatchTimer=null;taskCreatedUnsub=null;tickInProgress=false;stoppedResolvers=[];activeCollectors=new Set;skipAutonomousSeeding=false;singleTaskRunIds=new Set;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.dispatchOnlyTask(t));return}await this.withTemporaryLock(()=>this.freshDispatch(()=>this.dispatchOnlyTask(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||this.singleTaskRunIds.size>0||await this.freshDispatch(()=>this.shuttingDown?Promise.resolve():this.dispatchAll());}async reconcile(){let t=this.state,e=Date.now(),s=Object.entries(t.running),[i,r]=await Promise.all([Promise.all(s.map(([c])=>this.deps.taskStore.get(c))),Promise.all(s.map(([,c])=>this.deps.agentStore.get(c.agent_id)))]);for(let c=0;c<s.length;c++){let[l,p]=s[c],k=i[c];if(!k||b(k.status)){this.abortControllers.delete(l),delete t.running[l],await this.deps.agentService.setStatus(p.agent_id,"idle").catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`reconcile setStatus idle for stale agent ${p.agent_id} (task ${l})`,fatal:false});});continue}if(this.activeCollectors.has(l))continue;if(!this.deps.processManager.isAlive(p.pid)){try{await this._handleRunFailure(l,p,"Process crashed unexpectedly");}catch{delete t.running[l],await this.deps.agentService.setStatus(p.agent_id,"idle").catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`reconcile crash fallback setStatus idle for agent ${p.agent_id} (task ${l})`,fatal:false});});}continue}let v=new Date(p.last_event_at).getTime(),m=r[c]?.config.stall_timeout_ms??this.deps.config.defaults.agent.stall_timeout_ms;if(e-v>m){this.deps.eventBus.emit({type:"orchestrator:stall_detected",runId:p.run_id}),this.abortControllers.get(l)?.abort(),await this.deps.processManager.killWithGrace(p.pid,5e3);try{await this._handleRunFailure(l,p,"Agent stalled (no events)");}catch{delete t.running[l],await this.deps.agentService.setStatus(p.agent_id,"idle").catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`reconcile stall fallback setStatus idle for agent ${p.agent_id} (task ${l})`,fatal:false});});}}}let o=new Set(Object.values(t.running).map(c=>c.agent_id)),[n,d]=await Promise.all([this.cachedAgentStore.list(),this.cachedTaskStore.list()]),g=n.filter(c=>c.status==="running"&&!o.has(c.id));g.length>0&&await Promise.all(g.map(c=>this.deps.agentService.setStatus(c.id,"idle")));let f=d.filter(c=>c.status==="in_progress"&&!t.running[c.id]);f.length>0&&await Promise.all(f.map(async c=>{try{await this.deps.taskService.updateStatus(c.id,"failed");}catch{c.status="failed",c.updated_at=new Date().toISOString(),await this.deps.taskStore.save(c).catch(l=>{this.deps.eventBus.emit({type:"orchestrator:error",error:l instanceof Error?l.message:String(l),context:`force-write orphaned task ${c.id}`,fatal:false});});}this.deps.eventBus.emit({type:"task:orphaned",taskId:c.id});}));let a=[];t.retry_queue=t.retry_queue.filter(c=>e>=new Date(c.due_at).getTime()?(a.push(c.task_id),false):true);for(let c$1 of a){let l=await this.deps.taskStore.get(c$1);!l||!c(l.status)||await this.dispatchTask(c$1,l);}await this.saveState();}async seedAutonomousTasks(){let e=(await this.cachedAgentStore.list()).filter(n=>n.autonomous&&n.status==="idle");if(e.length===0)return;let s=await this.cachedTaskStore.list(),i=this.cachedGoalStore?await this.cachedGoalStore.list({status:"active"}):[],r=false,o=new Set;for(let n of e){if(s.some(p=>p.assignee===n.id&&!b(p.status)))continue;let g=this.lastAutoSeedAt.get(n.id)??0;if(Date.now()-g<u.AUTO_SEED_COOLDOWN_MS)continue;let f=i.find(p=>p.assignee===n.id&&!o.has(p.id))??i.find(p=>!p.assignee&&!o.has(p.id));f&&o.add(f.id);let a$1=n.role??"general assistant",c=f?`[auto] ${n.name}: ${f.title.slice(0,60)}`:`[auto] ${n.name}: ${a$1.slice(0,60)}`,l=f?`## GOAL (highest priority)
7
+
8
+ ${f.description||f.title}
9
+
10
+ ---
11
+ Agent role: ${a$1}`:`Autonomous work cycle. Agent role: ${a$1}`;try{await this.deps.taskService.create({title:c,description:l,assignee:n.id,labels:[a],priority:3,goalId:f?.id}),this.lastAutoSeedAt.set(n.id,Date.now()),r=!0;}catch(p){this.deps.eventBus.emit({type:"orchestrator:error",error:p instanceof Error?p.message:String(p),context:`autonomous task for agent ${n.id}`,fatal:false});}}r&&this.cachedTaskStore.invalidate();}async dispatchAll(){let t=this.state,e$1=this.deps.config.scheduling.max_concurrent_agents,s=Object.keys(t.running).length,i=e$1-s;if(i<=0)return;let r=await this.cachedTaskStore.list(),o=new Map(r.map(a=>[a.id,a])),n=r.filter(a=>c(a.status)&&!d$1(a,o)&&!t.running[a.id]&&!t.claimed.has(a.id)).sort((a,c)=>{let l=(a.priority??3)-(c.priority??3);if(l!==0)return l;let p=(a.goalId?0:1)-(c.goalId?0:1);if(p!==0)return p;let k=c.updated_at??"",v=a.updated_at??"";return k<v?-1:k>v?1:0}).slice(0,i),d=new Set,g$1=r.filter(a=>a.status==="in_progress"&&a.scope?.length),f=new O(g$1.map(a=>a.scope));for(let a of n)if(a.scope?.length)if(f.overlapsAny(a.scope)){let c=g$1.find(l=>st(a.scope,l.scope));this.deps.eventBus.emit({type:"task:scope_overlap",taskId:a.id,overlappingTaskId:c?.id??a.id,patterns:a.scope}),d.add(a.id);}else f.add(a.scope);for(let a of n)if(!d.has(a.id))try{await this.dispatchTask(a.id);}catch(c){if(c instanceof m)try{let l=await this.deps.taskStore.get(a.id);if(l&&!b(l.status)){let p={...l,attempts:(l.attempts??0)+1,updated_at:new Date().toISOString()},k=e(p),v={...p,status:k};if(await this.deps.taskStore.save(v),k==="failed"){let y=r.map(m=>m.id===v.id?v:m);this.cachedTaskStore.invalidate(),await this.cascadeFailDependents(v.id,y,`dependency ${v.id} failed: ${c.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,c.message),await this.saveState();}}}catch{}this.deps.eventBus.emit({type:"orchestrator:error",error:c instanceof Error?c.message:String(c),context:`dispatch task ${a.id}`,fatal:false});}}async dispatchOnlyTask(t){let e=this.state,s=new Set(e.claimed),i=await this.cachedTaskStore.list();this.singleTaskRunIds.add(t);for(let r of i)r.id!==t&&c(r.status)&&e.claimed.add(r.id);try{await this.dispatchTask(t);}finally{e.claimed=s,e.running[t]||this.singleTaskRunIds.delete(t),await this.saveState();}}enqueueRetry(t,e,s,i,r){t.retry_queue.some(o=>o.task_id===e)||(t.retry_queue.length>=this.maxRetryQueueSize&&t.retry_queue.shift(),t.retry_queue.push({task_id:e,attempt:s,due_at:new Date(Date.now()+i).toISOString(),error:r}));}async cascadeFailDependents(t,e,s){let i=new Map;for(let g of e)for(let f of g.depends_on){let a=i.get(f);a||(a=[],i.set(f,a)),a.push(g);}let r=[t],o=0,n=new Set,d=false;for(;o<r.length;){let g=r[o++];if(n.has(g))continue;n.add(g);let f=i.get(g);if(!f)continue;let a=[];for(let l of f)b(l.status)||n.has(l.id)||(a.push({task:l,previousStatus:l.status}),r.push(l.id));if(a.length===0)continue;let c=new Date().toISOString();await Promise.all(a.map(({task:l})=>this.deps.taskStore.save({...l,status:"failed",updated_at:c})));for(let{task:l,previousStatus:p}of a)this.deps.eventBus.emit({type:"task:status_changed",taskId:l.id,from:p,to:"failed"}),this.deps.eventBus.emit({type:"task:cascade_failed",taskId:l.id,failedDependencyId:t,reason:s});d=true;}d&&this.cachedTaskStore.invalidate();}async dispatchTask(t,e){let s=this.state;if(s.running[t]){let r=s.running[t];throw new h(t,r.run_id,r.agent_id)}let i=e??await this.deps.taskService.get(t);if(c(i.status)){s.claimed.add(t),await this.saveState();try{let r=await this.cachedAgentStore.list(),o=await this.deps.agentService.findBestAgent(i);if(!o){if(r.length===0)throw new e$1;this.unclaim(t),await this.saveState();return}let{path:n,branch:d}=await this.deps.workspaceManager.prepare(i,o,this.deps.config),g=this.deps.config.prompt?.system_template??d$2,f=this.deps.config.prompt?.user_template??e$2,a=this.deps.config.prompt?.template,c=i.attempts+1,l;if(c>1){let w=await this.deps.runService.getLastFailedRunContext(i.id);w&&(l={previous_error:w.error,previous_output:w.output});}let p=i.goalId,[k,v,y]=await Promise.all([this.deps.contextStore?.getAll(),this.deps.messageService?this.deps.messageService.drainMailbox(o.id,i.id):[],p&&this.cachedGoalStore?this.cachedGoalStore.get(p).catch(()=>null):null]),m;if(y){let dt=(await this.cachedTaskStore.list()).filter(x=>x.goalId===p),ut=await this.deps.contextStore?.get(`${p}-progress`),ht=dt.map(x=>`[${x.status}] ${x.title}`);m={id:y.id,title:y.title,description:y.description,status:y.status,task_names:ht,progress:ut?.value};}let h=c$1(i,o,c,n,this.deps.config,{allAgents:r,retryContext:l,sharedContext:k,feedback:i.feedback,messages:v.length?v:void 0,goal:m}),S,_;if(a?S=await this.deps.templateEngine.render(a,h):(_=await this.deps.templateEngine.render(g,h),S=await this.deps.templateEngine.render(f,h)),this.deps.skillLoader&&o.config.skills?.length){let w=await this.deps.skillLoader.loadSkills(o.config.skills);w&&(_!==void 0?_=_+`
12
+
13
+ `+w:S=S+`
14
+
15
+ `+w);}let b=await this.deps.runService.create({taskId:i.id,agentId:o.id,attempt:c,prompt:S,workspacePath:n});if((i.status==="failed"||i.status==="cancelled")&&(await this.deps.taskService.retry(t),i.status="todo",i.attempts=0),await this.deps.taskService.updateStatus(t,"in_progress"),await this.deps.taskService.assign(t,o.id),await this.deps.taskService.incrementAttempts(t),d){let w=await this.deps.taskStore.get(t);w&&(w.proof={...w.proof??{files_changed:[]},branch:d},w.workspace=n,await this.deps.taskStore.save(w));}await this.deps.agentService.setStatus(o.id,"running");let T=await this.deps.agentService.get(o.id);T.current_task=t,T.last_error=void 0,await this.deps.agentStore.save(T);let lt=this.deps.adapterRegistry.require(o.adapter),N=new AbortController;this.abortControllers.set(t,N);let U=lt.execute({prompt:S,systemPrompt:_,workspace:n,env:{...o.config.env,ORCH_AGENT_ID:o.id,ORCH_AGENT_NAME:o.name,ORCH_TASK_ID:i.id},config:T.config,signal:N.signal}),W=U.pid,K=new Date().toISOString();await this.deps.runService.start(b.id,W),this.unclaim(t),s.running[t]={run_id:b.id,agent_id:o.id,task_id:t,pid:W,started_at:K,last_event_at:K},await this.saveState(),this.activeCollectors.add(t),this.collectEvents(U.events,b.id,t,o.id).catch(w=>{this.deps.eventBus.emit({type:"orchestrator:error",error:w instanceof Error?w.message:String(w),context:`adapter execution for ${t}`,fatal:!1});}).finally(()=>{this.activeCollectors.delete(t);});}catch(r){throw this.abortControllers.delete(t),this.unclaim(t),await this.saveState(),r}}}async collectEvents(t,e,s,i){let r,o,n,d,g=new Set;try{for await(let a of t){if(this.shuttingDown)break;if(a.type==="done"){if(a.tokens){let{input:h,output:S,reasoning:_,cache_read:b,cache_write:T}=a.tokens;r=a$1(h,S,{reasoning:_,cache_read:b,cache_write:T});}let m=a.data;m&&typeof m.result=="string"&&(o=m.result);}if(a.type==="output"){let m=a.data;if(m){let h=typeof m.text=="string"?m.text:typeof m.message=="string"?m.message:void 0;h?.trim()&&(n=h);}}if(a.type==="file_change"){let m=a.data;if(m&&Array.isArray(m.paths))for(let h of m.paths)typeof h=="string"&&g.add(h);else {let h=m&&typeof m.path=="string"?m.path:typeof a.data=="string"?a.data:String(a.data);g.add(h);}}let c=null;if(a.type==="tool_call"){let m=a.data;if(m){let h=m.input,S=typeof m.name=="string"?m.name:"";h&&typeof h.file_path=="string"&&/^(Write|Edit|MultiEdit|NotebookEdit)$/i.test(S)&&(c=h.file_path,g.add(c));}}let l=At(a.timestamp)?a.timestamp:new Date().toISOString(),p=a.type==="file_change"?(()=>{let m=a.data;return m&&typeof m.path=="string"?m.path:typeof a.data=="string"?a.data:String(a.data)})():null,k=ct(a.data,_t);a.data=void 0;let v={timestamp:l,type:a.type==="output"?"agent_output":a.type==="file_change"?"file_changed":a.type==="command"?"command_run":a.type==="tool_call"?"tool_call":a.type==="error"?"error":"done",data:k};await this.deps.runService.appendEvent(e,v),this.state?.running[s]&&(this.state.running[s].last_event_at=l,this.saveStateLazy());let y=ct(k,Tt);a.type==="output"||a.type==="tool_call"?(this.deps.eventBus.emit({type:"agent:output",runId:e,agentId:i,data:y}),c&&this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:c})):a.type==="file_change"?this.deps.eventBus.emit({type:"agent:file_changed",runId:e,agentId:i,path:p}):a.type==="error"&&(a.errorKind&&(d=a.errorKind),this.deps.eventBus.emit({type:"agent:error",runId:e,agentId:i,error:y,...a.errorKind?{errorKind:a.errorKind}:{}}));}let f=o??n;await this.handleRunSuccess(s,e,i,r,f,[...g]);}catch(f){let a=f instanceof Error?f.message:String(f),c=d??(f instanceof Error?f.errorKind:void 0),l=this.state?.running[s];l?await this.handleRunFailure(s,l,a,c):await this.deps.runService.finish(e,"failed",void 0,a).catch(()=>{});}finally{this.deps.runStore.closeRunEvents(e);}}async handleRunSuccess(t,e,s,i,r,o){return this.withStateLock(()=>this._handleRunSuccess(t,e,s,i,r,o))}async _handleRunSuccess(t,e,s,i,r,o){await this.flushStateLazy(),this.abortControllers.delete(t);let n=this.state;if(!n.running[t])return;let d=await this.deps.taskStore.get(t);if(!d)return;let g=o;(!g||g.length===0)&&d.proof?.branch&&(g=await this.deps.workspaceManager.getChangedFiles(d.proof.branch)),d.proof={...d.proof,agent_summary:r?.slice(0,2e3)??d.proof?.agent_summary,files_changed:g?.length?g:d.proof?.files_changed??[]},delete d.feedback,await this.deps.taskStore.save(d);let f$1=await this.deps.agentStore.get(s),c=d.labels?.includes(a)||f$1?.config.approval_policy==="auto",l=f(d,true,c);await this.deps.runService.finish(e,"succeeded",i);let p=n.running[t],k=p?Date.now()-new Date(p.started_at).getTime():0;p&&(n.stats.total_runtime_ms+=k),delete n.running[t];let v={tasks_completed:(f$1?.stats.tasks_completed??0)+1,total_runs:(f$1?.stats.total_runs??0)+1,total_runtime_ms:(f$1?.stats.total_runtime_ms??0)+k};if(i&&(v.tokens_used=(f$1?.stats.tokens_used??0)+i.total),await this.deps.agentService.updateStats(s,v).catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),context:`agent stats update for ${s}`,fatal:false});}),n.stats.total_tasks_completed++,n.stats.total_runs++,i&&(n.stats.total_tokens.input+=i.input,n.stats.total_tokens.output+=i.output,n.stats.total_tokens.reasoning+=i.reasoning,n.stats.total_tokens.cache_read+=i.cache_read,n.stats.total_tokens.cache_write+=i.cache_write,n.stats.total_tokens.total=n.stats.total_tokens.input+n.stats.total_tokens.output+n.stats.total_tokens.reasoning),d.proof?.branch)try{let h=await this.deps.workspaceManager.mergeBack(d.proof.branch);if(h.success)this.deps.eventBus.emit({type:"workspace:merge_succeeded",taskId:t,branch:d.proof.branch}),await this.deps.workspaceManager.cleanup(t,d.proof.branch).catch(S=>{this.deps.eventBus.emit({type:"orchestrator:error",error:S instanceof Error?S.message:String(S),context:`workspace cleanup for ${t}`,fatal:!1});});else {this.deps.eventBus.emit({type:"workspace:merge_conflict",taskId:t,branch:d.proof.branch,conflictInfo:h.conflictInfo}),await this.forceTaskToReview(d,s,`MERGE CONFLICT: ${h.conflictInfo}`);return}}catch(h){let S=h instanceof Error?h.message:String(h);await this.forceTaskToReview(d,s,`MERGE ERROR: ${S}`);return}try{await this.deps.taskService.updateStatus(t,l);}catch(h){let S=h instanceof Error?h.message:String(h);this.deps.eventBus.emit({type:"orchestrator:error",error:S,context:`state machine validation failed for task ${t} -> ${l}, force-writing`,fatal:false}),d.status=l,d.updated_at=new Date().toISOString(),await this.deps.taskStore.save(d).catch(_=>{this.deps.eventBus.emit({type:"orchestrator:error",error:_ instanceof Error?_.message:String(_),context:`force-write task ${t} to store failed`,fatal:false});});}await this.deps.agentService.setStatus(s,"idle").catch(h=>{this.deps.eventBus.emit({type:"orchestrator:error",error:h instanceof Error?h.message:String(h),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)),l==="review"&&d.review_criteria?.length?await this.runAutoReview(t,d.review_criteria,d.workspace??this.deps.projectRoot,c):l==="review"&&c&&await this.deps.taskService.updateStatus(t,"done"),await this.saveState(),this.singleTaskRunIds.delete(t)||this.scheduleImmediateDispatch();}async handleRunFailure(t,e,s,i){return this.withStateLock(()=>this._handleRunFailure(t,e,s,i))}async _handleRunFailure(t,e$1,s,i){await this.flushStateLazy(),this.abortControllers.delete(t);let r=this.state;if(!r.running[t])return;let o$1=await this.deps.taskStore.get(t);if(!o$1)return;await this.deps.runService.finish(e$1.run_id,"failed",void 0,s),await this.deps.agentService.setStatus(e$1.agent_id,"idle");let n=await this.deps.agentStore.get(e$1.agent_id);n&&(n.current_task=void 0,n.last_error={message:s.slice(0,500),kind:i??o(s),timestamp:new Date().toISOString()},await this.deps.agentStore.save(n));let d=Date.now()-new Date(e$1.started_at).getTime();await this.deps.agentService.updateStats(e$1.agent_id,{tasks_failed:(n?.stats.tasks_failed??0)+1,total_runs:(n?.stats.total_runs??0)+1,total_runtime_ms:(n?.stats.total_runtime_ms??0)+d});let g$1=e(o$1);if(await this.deps.taskService.updateStatus(t,g$1),g$1==="retrying"){let a=g(o$1.attempts-1,this.deps.config.scheduling.retry_base_delay_ms,this.deps.config.scheduling.retry_max_delay_ms);this.enqueueRetry(r,t,o$1.attempts+1,a,s),this.deps.eventBus.emit({type:"run:retry",runId:e$1.run_id,attempt:o$1.attempts+1,delay_ms:a});}else {r.stats.total_tasks_failed++,this.cachedTaskStore.invalidate();let a=await this.cachedTaskStore.list();await this.cascadeFailDependents(t,a,`dependency ${t} failed: ${s}`);}r.stats.total_runtime_ms+=d,o$1.proof?.branch&&await this.deps.workspaceManager.cleanup(t,o$1.proof.branch).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`workspace cleanup for ${t}`,fatal:false});}),delete r.running[t],r.stats.total_runs++,await this.saveState(),this.singleTaskRunIds.delete(t)||this.scheduleImmediateDispatch();}async runAutoReview(t,e,s,i=false){let o=await new P({cwd:s}).runAll(e),n=P.allPassed(o),d=await this.deps.taskStore.get(t);if(d&&(d.review_results=o,d.proof={...d.proof,test_results:P.formatReport(o),files_changed:d.proof?.files_changed??[]},await this.deps.taskStore.save(d),this.deps.eventBus.emit({type:"task:auto_reviewed",taskId:t,passed:n,results:o}),n||i)){n||this.deps.eventBus.emit({type:"orchestrator:error",error:`Review criteria failed for task ${t} but autoApprove is set \u2014 force-approving`,context:"auto-review-with-auto-approve",fatal:false});try{await this.deps.taskService.updateStatus(t,"done");}catch(g){let f=g instanceof Error?g.message:String(g);this.deps.eventBus.emit({type:"orchestrator:error",error:f,context:`auto-review transition failed for task ${t} -> done, force-writing`,fatal:false}),d.status="done",d.updated_at=new Date().toISOString(),await this.deps.taskStore.save(d).catch(a=>{this.deps.eventBus.emit({type:"orchestrator:error",error:a instanceof Error?a.message:String(a),context:`force-write task ${t} to store failed (auto-review)`,fatal:false});});}}}async forceTaskToReview(t,e,s){t.proof={...t.proof,agent_summary:`${s}
16
+
17
+ ${t.proof?.agent_summary??""}`.slice(0,2e3),files_changed:t.proof?.files_changed??[]},t.status="review",t.updated_at=new Date().toISOString(),await this.deps.taskStore.save(t),await this.deps.agentService.setStatus(e,"idle").catch(r=>{this.deps.eventBus.emit({type:"orchestrator:error",error:r instanceof Error?r.message:String(r),context:`forceTaskToReview setStatus idle for agent ${e}`,fatal:false});});let i=await this.deps.agentStore.get(e);i&&(i.current_task=void 0,await this.deps.agentStore.save(i)),await this.saveState();}unclaim(t){this.state.claimed.delete(t);}requireOwnership(){if(!this.lockAcquired)throw new d(0)}async loadState(){this.state=await this.deps.stateStore.read();}async cleanupStaleRunningEntries(){let t=this.state,e=Object.entries(t.running).filter(([,i])=>!this.deps.processManager.isAlive(i.pid)),s=new Set;if(e.length>0){for(let[i]of e)delete t.running[i],s.add(i);await Promise.all(e.map(async([i,r])=>{await this.deps.agentService.setStatus(r.agent_id,"idle").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: setStatus idle for agent ${r.agent_id}`,fatal:false});}),await this.forceTaskCancelled(i),await this.deps.runService.finish(r.run_id,"cancelled",void 0,"Orchestrator restarted").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: finish run ${r.run_id}`,fatal:false});});}));}if(t.claimed=new Set,s.size>0){let r=(await this.cachedTaskStore.list()).filter(n=>n.status==="in_progress"&&!t.running[n.id]);r.length>0&&await Promise.all(r.map(n=>this.forceTaskCancelled(n.id)));let o=new Set([...s,...r.map(n=>n.id)]);t.retry_queue=t.retry_queue.filter(n=>!o.has(n.task_id)),await this.saveState();}await this.cleanupOrphanedPreparingRuns();}async cleanupOrphanedPreparingRuns(){try{let e=(await this.deps.runStore.listAll()).filter(r=>r.status==="preparing");if(e.length===0)return;let s=new Set(Object.values(this.state.running).map(r=>r.run_id)),i=e.filter(r=>!s.has(r.id));if(i.length===0)return;await Promise.all(i.map(r=>this.deps.runService.finish(r.id,"cancelled",void 0,"Orphaned preparing run (orchestrator restarted)").catch(o=>{this.deps.eventBus.emit({type:"orchestrator:error",error:o instanceof Error?o.message:String(o),context:`startup cleanup: finish orphaned preparing run ${r.id}`,fatal:!1});})));}catch(t){this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"startup cleanup: cleanupOrphanedPreparingRuns",fatal:false});}}async forceTaskCancelled(t){try{await this.deps.taskService.updateStatus(t,"cancelled");}catch{let e=await this.deps.taskStore.get(t);e&&!b(e.status)&&(e.status="cancelled",e.updated_at=new Date().toISOString(),await this.deps.taskStore.save(e).catch(s=>{this.deps.eventBus.emit({type:"orchestrator:error",error:s instanceof Error?s.message:String(s),context:`startup cleanup: force-cancel task ${t}`,fatal:false});}));}}async saveState(){this.state&&await this.deps.stateStore.write(this.state);}saveStateLazy(){this.saveStateDirty=true,!this.saveStateTimer&&(this.saveStateTimer=setTimeout(()=>{this.saveStateTimer=null,this.saveStateDirty&&(this.saveStateDirty=false,this.saveState().catch(t=>{this.deps.eventBus.emit({type:"orchestrator:error",error:t instanceof Error?t.message:String(t),context:"debounced state save",fatal:false});}));},500));}async flushStateLazy(){this.saveStateTimer&&(clearTimeout(this.saveStateTimer),this.saveStateTimer=null),this.saveStateDirty&&(this.saveStateDirty=false,await this.saveState());}};function At(u){if(typeof u!="string")return false;let t=new Date(u);return !isNaN(t.getTime())&&t.toISOString()===u}function ct(u,t){let e=typeof u=="string"?u:JSON.stringify(u);return e.length>t?e.slice(0,t)+"\u2026":e}export{ot as Orchestrator};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-3YGXRXS7.js';import {b as b$1}from'./chunk-JDG6ZKIM.js';import'./chunk-4O4L3Y2U.js';import {l as l$1,q,i,j}from'./chunk-64WUDYEM.js';var l=[{key:"startup-mvp",name:"Startup MVP",description:"Ship an MVP in 48 hours",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"frontend-dev",name:"Frontend"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"pr-review-corp",name:"PR Review Corp",description:"Automated review for every PR",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"security-auditor",name:"Security"},{shop_key:"performance-engineer",name:"Performance"},{shop_key:"code-reviewer",name:"Style"},{shop_key:"qa-engineer",name:"QA"}]},{key:"migration-squad",name:"Migration Squad",description:"JS-to-TS migration over a weekend",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"fullstack-dev",name:"Migrator"},{shop_key:"fullstack-dev",name:"Migrator 2"},{shop_key:"fullstack-dev",name:"Migrator 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"security-dept",name:"Security Department",description:"Multi-layer security audit",lead_index:0,agents:[{shop_key:"security-auditor",name:"Lead Auditor"},{shop_key:"security-auditor",name:"Scanner"},{shop_key:"security-auditor",name:"Secrets Auditor"},{shop_key:"bug-hunter",name:"Hunter"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"test-factory",name:"Test Factory",description:"Coverage from 40% to 80% overnight",lead_index:0,agents:[{shop_key:"qa-engineer",name:"Coverage Lead"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"qa-engineer",name:"QA 2"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"content-agency",name:"Content Agency",description:"Content factory: plan, write, edit, optimize",lead_index:0,agents:[{shop_key:"marketer",name:"Strategist"},{shop_key:"content-creator",name:"Writer"},{shop_key:"content-creator",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"growth-hacker",name:"SEO"}]},{key:"data-lab",name:"Data Lab",description:"3 CSVs to executive report by morning",lead_index:0,agents:[{shop_key:"data-engineer",name:"Lead Analyst"},{shop_key:"data-engineer",name:"Data Engineer"}]},{key:"sales-machine",name:"Sales Machine",description:"Outbound pipeline: research, outreach, follow-up, close",lead_index:0,agents:[{shop_key:"marketer",name:"Sales Director"},{shop_key:"content-creator",name:"SDR"},{shop_key:"content-creator",name:"SDR 2"},{shop_key:"content-creator",name:"Copywriter"},{shop_key:"growth-hacker",name:"Growth Analyst"}]},{key:"bugfix-dept",name:"Bugfix Department",description:"100 issues to 0 in a week",lead_index:0,agents:[{shop_key:"architect",name:"Triager"},{shop_key:"bug-hunter",name:"Fixer"},{shop_key:"bug-hunter",name:"Fixer 2"},{shop_key:"bug-hunter",name:"Fixer 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"docs-team",name:"Docs Team",description:"Technical docs from codebase analysis",lead_index:0,agents:[{shop_key:"architect",name:"Docs Lead"},{shop_key:"tech-writer",name:"Writer"},{shop_key:"tech-writer",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"code-reviewer",name:"Reviewer"}]}];function S(g){return l.find(t=>t.key===g)}function $(g,t){let u=g.command("org").description("Pre-built AI companies \u2014 deploy a full department with one command");u.command("list").alias("ls").description("List available company templates").action(async()=>{if(t.context.json){console.log(JSON.stringify(l,null,2));return}console.log();let s=["KEY","NAME","AGENTS","DESCRIPTION"],i=l.map(e=>[e.key,e.name,String(e.agents.length),e.description]);l$1(s,i),console.log(),console.log(` ${q("Deploy:")} orch org deploy <key> --goal "Your objective"`),console.log();}),u.command("deploy <template>").description("Deploy a pre-built AI company").option("--goal <goal>","Set a goal for the team").action(async(s,i$1)=>{let e=S(s);if(!e){i(`Unknown template "${s}"`,"Run: orch org list \u2014 to see available templates"),process.exitCode=1;return}let o=[];for(let n of e.agents){let m=b(n.shop_key);if(!m){i(`Agent shop template not found: ${n.shop_key}`),process.exitCode=1;return}try{let a=t.config.defaults.agent.adapter,p=b$1(m,a),k=await t.agentService.create({...p,name:n.name});o.push(k.id);}catch(a){i(`Failed to create agent "${n.name}": ${a instanceof Error?a.message:String(a)}`,o.length>0?`${o.length} agent(s) were already created. Clean up with: orch agent list`:void 0),process.exitCode=1;return}}let y=o[e.lead_index],x=o.filter(n=>n!==y),h=await t.teamService.create({name:e.name,description:e.description,lead_agent_id:y,member_agent_ids:x}),c;if(i$1.goal&&(c=(await t.goalService.create({title:i$1.goal,assignee:y})).id),t.context.json){console.log(JSON.stringify({team:h,agentIds:o,goalId:c},null,2));return}if(t.context.quiet){console.log(h.id);return}console.log(),j(`Deployed team "${e.name}" \u2014 ${e.agents.length} agents`),console.log();for(let n=0;n<e.agents.length;n++){let m=e.agents[n],a=o[n],p=n===e.lead_index,k=p?"lead":"member";console.log(` ${p?"\u2605":"\u2022"} ${m.name} ${q(`(${a}, ${k})`)}`);}console.log(`
2
+ import {b}from'./chunk-3YGXRXS7.js';import {b as b$1}from'./chunk-SLMXPTXV.js';import'./chunk-DZK72HOZ.js';import {l as l$1,q,i,j}from'./chunk-64WUDYEM.js';var l=[{key:"startup-mvp",name:"Startup MVP",description:"Ship an MVP in 48 hours",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"frontend-dev",name:"Frontend"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"pr-review-corp",name:"PR Review Corp",description:"Automated review for every PR",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"security-auditor",name:"Security"},{shop_key:"performance-engineer",name:"Performance"},{shop_key:"code-reviewer",name:"Style"},{shop_key:"qa-engineer",name:"QA"}]},{key:"migration-squad",name:"Migration Squad",description:"JS-to-TS migration over a weekend",lead_index:0,agents:[{shop_key:"architect",name:"CTO"},{shop_key:"fullstack-dev",name:"Migrator"},{shop_key:"fullstack-dev",name:"Migrator 2"},{shop_key:"fullstack-dev",name:"Migrator 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"security-dept",name:"Security Department",description:"Multi-layer security audit",lead_index:0,agents:[{shop_key:"security-auditor",name:"Lead Auditor"},{shop_key:"security-auditor",name:"Scanner"},{shop_key:"security-auditor",name:"Secrets Auditor"},{shop_key:"bug-hunter",name:"Hunter"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"test-factory",name:"Test Factory",description:"Coverage from 40% to 80% overnight",lead_index:0,agents:[{shop_key:"qa-engineer",name:"Coverage Lead"},{shop_key:"backend-dev",name:"Backend"},{shop_key:"backend-dev",name:"Backend 2"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"qa-engineer",name:"QA 2"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"content-agency",name:"Content Agency",description:"Content factory: plan, write, edit, optimize",lead_index:0,agents:[{shop_key:"marketer",name:"Strategist"},{shop_key:"content-creator",name:"Writer"},{shop_key:"content-creator",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"growth-hacker",name:"SEO"}]},{key:"data-lab",name:"Data Lab",description:"3 CSVs to executive report by morning",lead_index:0,agents:[{shop_key:"data-engineer",name:"Lead Analyst"},{shop_key:"data-engineer",name:"Data Engineer"}]},{key:"sales-machine",name:"Sales Machine",description:"Outbound pipeline: research, outreach, follow-up, close",lead_index:0,agents:[{shop_key:"marketer",name:"Sales Director"},{shop_key:"content-creator",name:"SDR"},{shop_key:"content-creator",name:"SDR 2"},{shop_key:"content-creator",name:"Copywriter"},{shop_key:"growth-hacker",name:"Growth Analyst"}]},{key:"bugfix-dept",name:"Bugfix Department",description:"100 issues to 0 in a week",lead_index:0,agents:[{shop_key:"architect",name:"Triager"},{shop_key:"bug-hunter",name:"Fixer"},{shop_key:"bug-hunter",name:"Fixer 2"},{shop_key:"bug-hunter",name:"Fixer 3"},{shop_key:"qa-engineer",name:"QA"},{shop_key:"code-reviewer",name:"Reviewer"}]},{key:"docs-team",name:"Docs Team",description:"Technical docs from codebase analysis",lead_index:0,agents:[{shop_key:"architect",name:"Docs Lead"},{shop_key:"tech-writer",name:"Writer"},{shop_key:"tech-writer",name:"Writer 2"},{shop_key:"tech-writer",name:"Editor"},{shop_key:"code-reviewer",name:"Reviewer"}]}];function S(g){return l.find(t=>t.key===g)}function $(g,t){let u=g.command("org").description("Pre-built AI companies \u2014 deploy a full department with one command");u.command("list").alias("ls").description("List available company templates").action(async()=>{if(t.context.json){console.log(JSON.stringify(l,null,2));return}console.log();let s=["KEY","NAME","AGENTS","DESCRIPTION"],i=l.map(e=>[e.key,e.name,String(e.agents.length),e.description]);l$1(s,i),console.log(),console.log(` ${q("Deploy:")} orch org deploy <key> --goal "Your objective"`),console.log();}),u.command("deploy <template>").description("Deploy a pre-built AI company").option("--goal <goal>","Set a goal for the team").action(async(s,i$1)=>{let e=S(s);if(!e){i(`Unknown template "${s}"`,"Run: orch org list \u2014 to see available templates"),process.exitCode=1;return}let o=[];for(let n of e.agents){let m=b(n.shop_key);if(!m){i(`Agent shop template not found: ${n.shop_key}`),process.exitCode=1;return}try{let a=t.config.defaults.agent.adapter,p=b$1(m,a),k=await t.agentService.create({...p,name:n.name});o.push(k.id);}catch(a){i(`Failed to create agent "${n.name}": ${a instanceof Error?a.message:String(a)}`,o.length>0?`${o.length} agent(s) were already created. Clean up with: orch agent list`:void 0),process.exitCode=1;return}}let y=o[e.lead_index],x=o.filter(n=>n!==y),h=await t.teamService.create({name:e.name,description:e.description,lead_agent_id:y,member_agent_ids:x}),c;if(i$1.goal&&(c=(await t.goalService.create({title:i$1.goal,assignee:y})).id),t.context.json){console.log(JSON.stringify({team:h,agentIds:o,goalId:c},null,2));return}if(t.context.quiet){console.log(h.id);return}console.log(),j(`Deployed team "${e.name}" \u2014 ${e.agents.length} agents`),console.log();for(let n=0;n<e.agents.length;n++){let m=e.agents[n],a=o[n],p=n===e.lead_index,k=p?"lead":"member";console.log(` ${p?"\u2605":"\u2022"} ${m.name} ${q(`(${a}, ${k})`)}`);}console.log(`
3
3
  Team: ${q(h.id)}`),c&&console.log(` Goal: ${q(c)} \u2014 "${i$1.goal}"`),console.log(),console.log(` ${q("Next:")} orch run --all --watch`),console.log();});}export{$ as registerOrgCommand};
@@ -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:s,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,i=await s(d),r=n(i),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 s=await a.taskService.assign(e,t);j(`Assigned ${s.id} \u2192 ${s.assignee??t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:s}=await import('./container-KJNQCG2C.js');await(await s(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,i=await s(d),r=n(i),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 s=await a.taskService.assign(e,t);j(`Assigned ${s.id} \u2192 ${s.assignee??t}`);}),c.command("cancel <id>").description("Cancel a task").action(async e=>{if((await a.taskService.get(e)).status==="in_progress"){let{buildFullContainer:s}=await import('./container-TQGRDHAU.js');await(await s(a.context)).orchestrator.cancelTask(e);}else await a.taskService.cancel(e);j(`Cancelled ${e}`);}),c.command("approve <id>").description("Approve a task in review").action(async e=>{await a.taskService.updateStatus(e,"done"),j(`Approved ${e}`);}),c.command("reject <id>").description("Reject a task and send it back for rework").option("-r, --reason <reason>","Feedback for the agent explaining what to fix").action(async(e,t)=>{await a.taskService.reject(e,t.reason),j(`Rejected ${e} \u2192 todo${t.reason?` (reason: ${t.reason})`:""}`);}),c.command("retry <id>").description("Retry a failed task").action(async e=>{await a.taskService.retry(e),j(`Reset ${e} to todo`);});}export{x as registerTaskCommand};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b}from'./chunk-HYQXUJYV.js';import {c}from'./chunk-DZK72HOZ.js';function pt(d,e){d.command("tui").description("Launch interactive TUI dashboard").action(async()=>{let h=await e.taskService.list(),k=await e.agentService.list(),T=await e.stateStore.read(),{render:A}=await import('ink'),{createElement:b$1}=await import('react'),{App:R}=await import('./App-YVHDT4VD.js'),C=async t=>{await e.orchestrator.runTask(t);},E=async(t,s)=>e.taskService.create({title:t,priority:s?.priority,description:s?.description,attachments:s?.attachments}),_=async t=>{await e.orchestrator.cancelTask(t);},j=async t=>{await e.taskService.retry(t);},D=async(t,s)=>{await e.taskService.assign(t,s);},P=async()=>{await e.orchestrator.runAll();},U=async t=>{await e.agentService.disable(t);},G=async t=>{await e.agentService.enable(t);},m=t=>e.eventBus.onAny(t),L=async()=>e.taskService.list(),x=async()=>e.agentService.list(),I=async()=>e.stateStore.read(),O=async(t,s,a)=>e.agentService.create({name:t,adapter:s??e.config.defaults.agent.adapter,model:a?.model||void 0,effort:a?.effort||void 0,role:a?.role||void 0,approval_policy:a?.approval_policy||void 0,skills:a?.skills||void 0}),F=async t=>{await e.agentService.remove(t);},H=async t=>{await e.taskService.delete(t);},W=async t=>{await e.taskService.updateStatus(t,"done");},M=async(t,s)=>{await e.taskService.reject(t,s);},N=async(t,s)=>e.taskService.update(t,s),B=async(t,s)=>e.agentService.update(t,{...s,effort:s.effort,approval_policy:s.approval_policy}),V=async t=>{await e.orchestrator.forceStopAgent(t);},J=async(t,s)=>e.agentService.setAutonomous(t,s),K=async t=>{let s=await e.runService.listAll();s.sort((n,i)=>new Date(i.started_at).getTime()-new Date(n.started_at).getTime());let a=s.filter(n=>n.status==="succeeded"||n.status==="failed"),u=3,gt=10,y=a.slice(0,u),v=a.slice(u,gt),f=async n=>(await e.runService.readEventsTail(n.id,30)).map(r=>({timestamp:r.timestamp,agentId:n.agent_id,taskId:n.task_id,type:r.type,data:r.data}));if(y.length>0){let n=(await Promise.all(y.map(f))).flat();n.sort((i,r)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime()),t(n.slice(-200));}if(v.length>0){let n=(await Promise.all(v.map(f))).flat();n.sort((i,r)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime()),t(n.slice(-200));}},q=async t=>e.teamService.create(t),z=async()=>e.teamService.list(),Q=async(t,s)=>e.teamService.join(t,s),X=async(t,s)=>e.teamService.leave(t,s),Y=async t=>{await e.teamService.disband(t);},Z=async(t,s)=>e.teamService.setLead(t,s),$=async()=>e.goalService.list(),tt=async t=>e.goalService.create(t),et=async(t,s)=>e.goalService.update(t,s),st=async(t,s,a)=>e.goalService.updateStatus(t,s,a),at=async t=>{await e.goalService.delete(t);},nt=async t=>e.goalService.getProgressReport(t),rt=async()=>b(c),it=async()=>{await e.orchestrator.startWatch();},ot=async()=>{await e.orchestrator.stop();},c$1=d.version()??"0.0.0",ct=import('./update-check-R5ABF6HE.js').then(t=>t.checkForUpdateSWR(c$1)).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=a=>o.subscribe(a);}let{waitUntilExit:lt}=A(b$1(R,{projectName:e.config.project.name,tasks:h,agents:k,state:T,onRunTask:C,onCreateTask:E,onCancelTask:_,onRetryTask:j,onAssignTask:D,onRunAll:P,onDisableAgent:U,onEnableAgent:G,onSubscribeEvents:m,onRefreshTasks:L,onRefreshAgents:x,onRefreshState:I,onLoadHistory:K,onAddAgent:O,onDeleteAgent:F,onApproveTask:W,onRejectTask:M,onDeleteTask:H,onUpdateTask:N,onUpdateAgent:B,onForceStopAgent:V,onToggleAutonomous:J,onRefreshGoals:$,onCreateGoal:tt,onUpdateGoal:et,onUpdateGoalStatus:st,onDeleteGoal:at,onGetGoalProgress:nt,onCreateTeam:q,onListTeams:z,onJoinTeam:Q,onLeaveTeam:X,onDisbandTeam:Y,onSetTeamLead:Z,onStartWatch:it,onStopWatch:ot,initialWatchActive:l,observerMode:g,watchError:g?void 0:p,version:c$1,latestVersion:void 0,onCheckUpdate:async()=>{let t=await ct;if(t?.updateAvailable)return t.latest;let a=await(await import('./update-check-R5ABF6HE.js')).checkForUpdateNow(c$1);return a?.updateAvailable?a.latest:void 0},onBackgroundInstall:async t=>(await import('./update-check-R5ABF6HE.js')).backgroundInstall(t),onLoadModelCatalog:rt,initialActivityFilter:e.globalConfig.tui.activity_filter,onSaveActivityFilter:async t=>{await e.globalConfigStore.set("activity_filter",t);},initialNotifications:e.globalConfig.tui.notifications,onSaveNotifications:async t=>{await e.globalConfigStore.set("notifications",t);},initialMaxConcurrent:e.config.scheduling.max_concurrent_agents,onSaveMaxConcurrent:async t=>{await e.configStore.set("scheduling.max_concurrent_agents",t),e.config.scheduling.max_concurrent_agents=t;},onCompleteOnboarding:async()=>{let t=await e.stateStore.read();t.onboardingCompleted=true,await e.stateStore.write(t);},defaultAdapter:e.config.defaults.agent.adapter}),{incrementalRendering:true,kittyKeyboard:{mode:"auto",flags:["disambiguateEscapeCodes"]}});await lt(),l&&await e.orchestrator.stop().catch(()=>{}),o&&o.stop(),e.eventBus.clear();});}export{pt as registerTuiCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxgeneral/orch",
3
- "version": "1.0.25",
3
+ "version": "1.0.27",
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": {
@@ -53,6 +53,8 @@
53
53
  "codex",
54
54
  "cursor",
55
55
  "opencode",
56
+ "grok",
57
+ "antigravity",
56
58
  "openai",
57
59
  "llm",
58
60
  "cli-tool",
package/readme.md CHANGED
@@ -326,7 +326,7 @@ Every department gets the same superpowers: state machine governance, retry, mes
326
326
  <picture>
327
327
  <source media="(prefers-color-scheme: dark)" srcset="./assets/adapters-dark.svg">
328
328
  <source media="(prefers-color-scheme: light)" srcset="./assets/adapters-light.svg">
329
- <img alt="Adapters: Claude, OpenCode, Codex, Pi, Cursor, Shell" src="./assets/adapters-dark.svg" width="100%">
329
+ <img alt="Adapters: Claude, OpenCode, Codex, Pi, Cursor, Grok, Antigravity, Shell" src="./assets/adapters-dark.svg" width="100%">
330
330
  </picture>
331
331
 
332
332
  <br/>
@@ -604,7 +604,7 @@ src/
604
604
  ├── domain/ # Models, state machine, errors
605
605
  ├── application/ # Orchestrator engine, services, event bus
606
606
  ├── infrastructure/
607
- │ ├── adapters/ # Claude, OpenCode, Codex, Pi, Cursor, Shell
607
+ │ ├── adapters/ # Claude, OpenCode, Codex, Pi, Cursor, Grok, Antigravity, Shell
608
608
  │ ├── storage/ # File-based (YAML/JSON/JSONL)
609
609
  │ ├── process/ # PID management, graceful kill
610
610
  │ ├── template/ # LiquidJS prompt templates
@@ -706,7 +706,7 @@ ORCH is open-source (MIT license). You pay only for the AI APIs you already use
706
706
 
707
707
  <br/>
708
708
 
709
- Six adapters: **Claude Code**, **OpenCode** (Gemini, DeepSeek, any OpenRouter model), **Codex**, **Pi**, **Cursor**, and **Shell** (any CLI tool). Your API keys, your tools — ORCH coordinates them.
709
+ Eight adapters: **Claude Code**, **OpenCode** (Gemini, DeepSeek, any OpenRouter model), **Codex**, **Pi**, **Cursor**, **Grok**, **Antigravity**, and **Shell** (any CLI tool). Your API keys, your tools — ORCH coordinates them.
710
710
 
711
711
  </details>
712
712