@oxgeneral/orch 1.0.17 → 1.0.18

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 (75) hide show
  1. package/dist/App-Q7J4JGDF.js +22 -0
  2. package/dist/agent-WLKP6WOR.js +9 -0
  3. package/dist/agent-factory-HJOS7FW3.js +2 -0
  4. package/dist/{agent-shop-JHDTCWCD.js → agent-shop-XWVUC3MK.js} +1 -1
  5. package/dist/{chunk-HWEMBO36.js → chunk-3YGXRXS7.js} +3 -3
  6. package/dist/{chunk-3AXNSYCM.js → chunk-6E6DC7OE.js} +1 -1
  7. package/dist/{chunk-J7ITYXE6.js → chunk-6JQDY3PP.js} +3 -3
  8. package/dist/{chunk-J7ITYXE6.js.map → chunk-6JQDY3PP.js.map} +1 -1
  9. package/dist/chunk-C7C7Q7XO.js +4 -0
  10. package/dist/{chunk-JM2WRI46.js → chunk-DEHFYICU.js} +1 -1
  11. package/dist/chunk-EWRVHOUA.js +2 -0
  12. package/dist/{chunk-NLQAJ7TW.js → chunk-IESAV453.js} +14 -4
  13. package/dist/chunk-IESAV453.js.map +1 -0
  14. package/dist/chunk-ITMAWW3J.js +3 -0
  15. package/dist/chunk-LRYVT4D4.js +2 -0
  16. package/dist/{chunk-XJ6KTO3E.js → chunk-NNF3VEVJ.js} +3 -3
  17. package/dist/{chunk-XJ6KTO3E.js.map → chunk-NNF3VEVJ.js.map} +1 -1
  18. package/dist/{chunk-TWEMIPRN.js → chunk-RFN447MA.js} +3 -3
  19. package/dist/{chunk-TWEMIPRN.js.map → chunk-RFN447MA.js.map} +1 -1
  20. package/dist/chunk-XMKCAUEH.js +2 -0
  21. package/dist/{claude-EMBYYPW4.js → claude-KZMCTMDP.js} +4 -4
  22. package/dist/{claude-EMBYYPW4.js.map → claude-KZMCTMDP.js.map} +1 -1
  23. package/dist/claude-PH7LT3OH.js +2 -0
  24. package/dist/cli.js +1 -1
  25. package/dist/{clipboard-service-WVON5ZN4.js → clipboard-service-AJTJG2DJ.js} +1 -1
  26. package/dist/{codex-WQ3LU3MM.js → codex-UR7Q22OV.js} +4 -4
  27. package/dist/{codex-WQ3LU3MM.js.map → codex-UR7Q22OV.js.map} +1 -1
  28. package/dist/codex-URQN4JLZ.js +2 -0
  29. package/dist/container-5FLJ4QYD.js +4 -0
  30. package/dist/{cursor-M3EJ432K.js → cursor-EMX3ECDY.js} +1 -1
  31. package/dist/{cursor-TKV5FFCN.js → cursor-O6M6XOMT.js} +4 -4
  32. package/dist/{cursor-TKV5FFCN.js.map → cursor-O6M6XOMT.js.map} +1 -1
  33. package/dist/{doctor-SKIWAKHW.js → doctor-5HTCX6K7.js} +1 -1
  34. package/dist/goal-KQ4XOSRH.js +8 -0
  35. package/dist/index.d.ts +87 -2
  36. package/dist/index.js +588 -14
  37. package/dist/index.js.map +1 -1
  38. package/dist/init-GVM7EYPO.js +74 -0
  39. package/dist/{logs-CU3NC24O.js → logs-EUOQ2UZL.js} +1 -1
  40. package/dist/{opencode-YWT3M4NX.js → opencode-HOX5TCMD.js} +4 -4
  41. package/dist/{opencode-YWT3M4NX.js.map → opencode-HOX5TCMD.js.map} +1 -1
  42. package/dist/opencode-K22RCQ5C.js +2 -0
  43. package/dist/orchestrator-I3CXUOH7.js +6 -0
  44. package/dist/{orchestrator-FWROY4JD.js.map → orchestrator-I3CXUOH7.js.map} +1 -1
  45. package/dist/{orchestrator-YZHLOVJO.js → orchestrator-L34ZPKAB.js} +3 -3
  46. package/dist/org-WCEBMHLR.js +3 -0
  47. package/dist/{shell-PMLIRG3N.js → shell-C2J4AIAV.js} +4 -4
  48. package/dist/{shell-PMLIRG3N.js.map → shell-C2J4AIAV.js.map} +1 -1
  49. package/dist/shell-NPNTWDMU.js +2 -0
  50. package/dist/shop-picker-2HA2CDKS.js +5 -0
  51. package/dist/{task-2LI5CMI4.js → task-TTOAOVM7.js} +1 -1
  52. package/dist/tui-IWCCSBDD.js +2 -0
  53. package/dist/{workspace-manager-KUU7UMMC.js → workspace-manager-QH27FF55.js} +4 -4
  54. package/dist/{workspace-manager-KUU7UMMC.js.map → workspace-manager-QH27FF55.js.map} +1 -1
  55. package/dist/{workspace-manager-DG4IFFG3.js → workspace-manager-ZI5SVXJU.js} +2 -2
  56. package/package.json +1 -1
  57. package/dist/App-2CW2WICK.js +0 -22
  58. package/dist/agent-TU6OC7ZT.js +0 -9
  59. package/dist/chunk-FQ5YUP4J.js +0 -4
  60. package/dist/chunk-IKNBPOQL.js +0 -2
  61. package/dist/chunk-LOJ26OVK.js +0 -3
  62. package/dist/chunk-NLQAJ7TW.js.map +0 -1
  63. package/dist/claude-GIGROCH5.js +0 -2
  64. package/dist/codex-AZD52UPS.js +0 -2
  65. package/dist/container-RFWMXKD6.js +0 -4
  66. package/dist/goal-RNNZYMNR.js +0 -8
  67. package/dist/init-6OVZBN6B.js +0 -73
  68. package/dist/opencode-4G7VAZGY.js +0 -2
  69. package/dist/orchestrator-FWROY4JD.js +0 -6
  70. package/dist/org-KLYK6MMJ.js +0 -3
  71. package/dist/shell-JC2WDWBR.js +0 -2
  72. package/dist/shop-picker-LE3SKFOX.js +0 -5
  73. package/dist/tui-24NBO5U6.js +0 -2
  74. package/scripts/demo.sh +0 -202
  75. /package/dist/{serve-JOIPYKKG.js → serve-DE7ES7Q5.js} +0 -0
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import {c,d as d$1}from'./chunk-3AXNSYCM.js';import {j}from'./chunk-ZMLF5HI5.js';import {l}from'./chunk-IKNBPOQL.js';import n from'path';import u from'fs/promises';var d=class{constructor(t,e){this.projectRoot=t;this.processManager=e;}async mergeBack(t){return new Promise(e=>{let{process:r}=this.processManager.spawn("git",["merge","--no-ff",t,"-m",`Merge ${t}`],{cwd:this.projectRoot}),s="",o=2e3,i=a=>{s.length<o&&(s+=a.toString());};r.stdout?.on("data",i),r.stderr?.on("data",i),r.on("close",a=>{if(a===0){e({success:true});return}let c=s.slice(0,1e3);if(!(c.includes("CONFLICT")||c.includes("Merge conflict"))){e({success:false,conflictInfo:c});return}try{let{process:l}=this.processManager.spawn("git",["merge","--abort"],{cwd:this.projectRoot});l.on("close",()=>{e({success:!1,conflictInfo:c});}),l.on("error",()=>{e({success:!1,conflictInfo:c});});}catch{e({success:false,conflictInfo:c});}}),r.on("error",a=>{e({success:false,conflictInfo:a.message});});})}};var w=class{constructor(t,e,r){this.projectRoot=t;this.orchestryDir=e;this.processManager=r;this.mergeStrategy=new d(t,r);}mergeStrategy;gitRepoChecked=false;isGitRepo=false;async prepare(t,e,r){let s=this.resolveMode(t,e,r);switch(s!=="shared"&&await this.requireGitRepo(s),s){case "shared":return {path:this.projectRoot};case "worktree":return this.prepareWorktree(t);case "isolated":return {path:await this.prepareIsolated(t)};default:return {path:this.projectRoot}}}async requireGitRepo(t){if(!this.gitRepoChecked){let e=await this.spawnAndWait("git",["rev-parse","--is-inside-work-tree"]);this.isGitRepo=e===0,this.isGitRepo&&(this.gitRepoChecked=true);}if(!this.isGitRepo)throw new l(`workspace_mode "${t}" requires a git repository`,`Run: git init && git add -A && git commit -m "Initial commit"
2
+ import {c,d as d$1}from'./chunk-6E6DC7OE.js';import {j}from'./chunk-ZMLF5HI5.js';import {m}from'./chunk-LRYVT4D4.js';import n from'path';import u from'fs/promises';var d=class{constructor(t,e){this.projectRoot=t;this.processManager=e;}async mergeBack(t){return new Promise(e=>{let{process:r}=this.processManager.spawn("git",["merge","--no-ff",t,"-m",`Merge ${t}`],{cwd:this.projectRoot}),s="",o=2e3,i=a=>{s.length<o&&(s+=a.toString());};r.stdout?.on("data",i),r.stderr?.on("data",i),r.on("close",a=>{if(a===0){e({success:true});return}let c=s.slice(0,1e3);if(!(c.includes("CONFLICT")||c.includes("Merge conflict"))){e({success:false,conflictInfo:c});return}try{let{process:l}=this.processManager.spawn("git",["merge","--abort"],{cwd:this.projectRoot});l.on("close",()=>{e({success:!1,conflictInfo:c});}),l.on("error",()=>{e({success:!1,conflictInfo:c});});}catch{e({success:false,conflictInfo:c});}}),r.on("error",a=>{e({success:false,conflictInfo:a.message});});})}};var w=class{constructor(t,e,r){this.projectRoot=t;this.orchestryDir=e;this.processManager=r;this.mergeStrategy=new d(t,r);}mergeStrategy;gitRepoChecked=false;isGitRepo=false;async prepare(t,e,r){let s=this.resolveMode(t,e,r);switch(s!=="shared"&&await this.requireGitRepo(s),s){case "shared":return {path:this.projectRoot};case "worktree":return this.prepareWorktree(t);case "isolated":return {path:await this.prepareIsolated(t)};default:return {path:this.projectRoot}}}async requireGitRepo(t){if(!this.gitRepoChecked){let e=await this.spawnAndWait("git",["rev-parse","--is-inside-work-tree"]);this.isGitRepo=e===0,this.isGitRepo&&(this.gitRepoChecked=true);}if(!this.isGitRepo)throw new m(`workspace_mode "${t}" requires a git repository`,`Run: git init && git add -A && git commit -m "Initial commit"
3
3
  Or set workspace_mode: shared in .orchestry/config.yml`)}async mergeBack(t){return this.mergeStrategy.mergeBack(t)}async cleanup(t,e){let r=n.join(this.orchestryDir,"workspaces",c(t));await this.spawnAndWait("git",["worktree","remove","--force",r]);let s=e?this.spawnAndWait("git",["branch","-D",e]).then(()=>{}):Promise.resolve(),o=u.rm(r,{recursive:true,force:true}).catch(()=>{});await Promise.all([s,o]);}validate(t,e){d$1(t,e);}async getChangedFiles(t){try{let{stdout:e}=await this.spawnAndCapture("git",["merge-base","HEAD",t]),r=e.trim();if(!r)return [];let{stdout:s,code:o}=await this.spawnAndCapture("git",["diff","--name-only",`${r}...${t}`]);return o!==0||!s.trim()?[]:s.trim().split(`
4
- `).filter(Boolean)}catch{return []}}resolveMode(t,e,r){return t.workspace_mode??e.config.workspace_mode??r.defaults.agent.workspace_mode??"worktree"}async prepareWorktree(t){let e=n.join(this.orchestryDir,"workspaces",c(t.id));await j(n.dirname(e));let r=y(t.title)||c(t.id),s=`orchestry/${c(t.id)}/${r}`;try{return await u.access(e),{path:e,branch:s}}catch{}if(await this.spawnAndWait("git",["worktree","add",e,"-b",s])!==0){await this.spawnAndWait("git",["worktree","prune"]);let a=await this.spawnAndWait("git",["worktree","add",e,s]);if(a!==0)throw new l(`git worktree add failed with code ${a}`,"Run: git worktree prune && git branch | grep orchestry | xargs -r git branch -D")}let i=n.join(e,".orchestry");return await u.rm(i,{recursive:true,force:true}).catch(()=>{}),{path:e,branch:s}}async spawnAndWait(t,e){try{let{process:r}=this.processManager.spawn(t,e,{cwd:this.projectRoot});return new Promise(s=>{r.on("close",o=>s(o??1)),r.on("error",()=>s(1));})}catch{return 1}}async spawnAndCapture(t,e){try{let{process:r}=this.processManager.spawn(t,e,{cwd:this.projectRoot}),s="";r.stdout?.on("data",i=>{s+=i.toString();});let o=await new Promise(i=>{r.on("close",a=>i(a??1)),r.on("error",()=>i(1));});return {stdout:s,code:o}}catch{return {stdout:"",code:1}}}async prepareIsolated(t){let e=n.join(this.orchestryDir,"workspaces",c(t.id));await j(n.dirname(e));try{if(await this.spawnAndWait("git",["clone","--local","--no-hardlinks",this.projectRoot,e])!==0)throw new Error("git clone failed")}catch{let o=["-a",`--exclude-from=${n.join(this.orchestryDir,"workspace-exclude")}`,"./",`${e}/`],i=await this.spawnAndWait("rsync",o);if(i!==0)throw new Error(`rsync failed with code ${i}`)}let r=n.join(e,".orchestry");return await u.rm(r,{recursive:true,force:true}).catch(()=>{}),e}};function y(g){return g.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}export{w as WorkspaceManager};
4
+ `).filter(Boolean)}catch{return []}}resolveMode(t,e,r){return t.workspace_mode??e.config.workspace_mode??r.defaults.agent.workspace_mode??"worktree"}async prepareWorktree(t){let e=n.join(this.orchestryDir,"workspaces",c(t.id));await j(n.dirname(e));let r=y(t.title)||c(t.id),s=`orchestry/${c(t.id)}/${r}`;try{return await u.access(e),{path:e,branch:s}}catch{}if(await this.spawnAndWait("git",["worktree","add",e,"-b",s])!==0){await this.spawnAndWait("git",["worktree","prune"]);let a=await this.spawnAndWait("git",["worktree","add",e,s]);if(a!==0)throw new m(`git worktree add failed with code ${a}`,"Run: git worktree prune && git branch | grep orchestry | xargs -r git branch -D")}let i=n.join(e,".orchestry");return await u.rm(i,{recursive:true,force:true}).catch(()=>{}),{path:e,branch:s}}async spawnAndWait(t,e){try{let{process:r}=this.processManager.spawn(t,e,{cwd:this.projectRoot});return new Promise(s=>{r.on("close",o=>s(o??1)),r.on("error",()=>s(1));})}catch{return 1}}async spawnAndCapture(t,e){try{let{process:r}=this.processManager.spawn(t,e,{cwd:this.projectRoot}),s="";r.stdout?.on("data",i=>{s+=i.toString();});let o=await new Promise(i=>{r.on("close",a=>i(a??1)),r.on("error",()=>i(1));});return {stdout:s,code:o}}catch{return {stdout:"",code:1}}}async prepareIsolated(t){let e=n.join(this.orchestryDir,"workspaces",c(t.id));await j(n.dirname(e));try{if(await this.spawnAndWait("git",["clone","--local","--no-hardlinks",this.projectRoot,e])!==0)throw new Error("git clone failed")}catch{let o=["-a",`--exclude-from=${n.join(this.orchestryDir,"workspace-exclude")}`,"./",`${e}/`],i=await this.spawnAndWait("rsync",o);if(i!==0)throw new Error(`rsync failed with code ${i}`)}let r=n.join(e,".orchestry");return await u.rm(r,{recursive:true,force:true}).catch(()=>{}),e}};function y(g){return g.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}export{w as WorkspaceManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxgeneral/orch",
3
- "version": "1.0.17",
3
+ "version": "1.0.18",
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": {
@@ -1,22 +0,0 @@
1
- #!/usr/bin/env node
2
- import {b,a as a$2}from'./chunk-HWEMBO36.js';import {a}from'./chunk-N4OXN2HW.js';import {c,a as a$1}from'./chunk-HXOMNULD.js';import {f,h,g}from'./chunk-64WUDYEM.js';import {m}from'./chunk-IKNBPOQL.js';import ao,{useState,useMemo,useEffect,useRef,useCallback}from'react';import {Box,Text,useInput,useApp,useStdout}from'ink';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var e={amber:"#ffaf00",amberDim:"#af8700",green:"#5faf87",red:"#d75f5f",blue:"#5fafd7",yellow:"#d7af00",cyan:"#5fd7d7",purple:"#af87ff",white:"#eeeeee",silver:"#bcbcbc",gray:"#808080",dim:"#585858",ghost:"#3a3a3a",void:"#262626",errorBg:"#3d1515",warnBg:"#3d2e0a",successBg:"#0f2d1f",infoBg:"#1a1a22",toolBg:"#0f1f2d"},Ro="\u2501",Ve="\u2500",me="\xB7",Jt="\u25C8",Mr="\u2605",mn="\u27F3",Ht="\u25C6",Ao={in_progress:e.green,retrying:e.yellow,review:e.blue,todo:e.dim,done:e.green,failed:e.red,cancelled:e.dim},vs=new Map,_s=new Map;function He(t){if(t<=0)return "";let n=vs.get(t);return n||(n=Ro.repeat(t),vs.set(t,n)),n}function be(t){if(t<=0)return "";let n=_s.get(t);return n||(n=Ve.repeat(t),_s.set(t,n)),n}function rt(t,n){return t.length>n?t.slice(0,n-1)+"\u2026":t}var Za=1e4;function vr(t,n=Za){if(t)return t.length>n?t.slice(0,n)+`
3
- \u2026[truncated]`:t}var Rs={active:e.green,paused:e.dim,achieved:e.amber,abandoned:e.ghost};var el=120,$o=0,oo=null,Bo=new Set;function tl(){oo||(oo=setInterval(()=>{$o++;for(let t of Bo)t($o);},el));}function nl(){oo&&Bo.size===0&&(clearInterval(oo),oo=null);}function En(t=true){let[n,o]=useState($o);return useEffect(()=>{if(!t)return;o($o);let r=l=>o(l);return Bo.add(r),tl(),()=>{Bo.delete(r),nl();}},[t]),n}var As=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function jt({color:t}){let n=En();return jsx(Text,{color:t,children:As[n%As.length]})}var ro={in_progress:0,retrying:1,review:2,todo:3,done:4,failed:5,cancelled:6};var il="\u25CB",Bs="\u2713",Es="\u2715",al="\u21BB",ll="\u2500",cl="\u25B6",Pt={green:"#0f2d1f",blue:"#0f1f2d",yellow:"#2d2a0f",red:"#2d0f0f",neutral:"#1a1a22",amber:"#2d1f0a"},dl={in_progress:{icon:cl,label:"RUN",fg:e.green,bg:Pt.green,bold:true,spinner:true},retrying:{icon:al,label:"RETRY",fg:e.yellow,bg:Pt.yellow,spinner:true},review:{icon:Jt,label:"REVIEW",fg:e.blue,bg:Pt.blue},todo:{icon:il,label:"TODO",fg:e.dim,bg:Pt.neutral},done:{icon:Bs,label:"DONE",fg:e.green,bg:Pt.green},failed:{icon:Es,label:"FAIL",fg:e.red,bg:Pt.red,bold:true},cancelled:{icon:ll,label:"OFF",fg:e.dim,bg:Pt.neutral}},ul={1:{color:e.red,label:"!!!"},2:{color:e.yellow,label:"!!"},3:{color:e.dim,label:"!"},4:{color:e.ghost,label:me}};var ml=18,fl="#2d1f0a",Eo=ao.memo(function({task:n,selected:o,width:r,agentNameMap:l,goalMap:p}){let b=dl[n.status],T=n.status==="in_progress"||n.status==="retrying",x=ul[n.priority]??{color:e.ghost,label:me},y,C;if(n.status==="done")y=Bs,C=e.green;else if(n.status==="failed")y=Es,C=e.red;else if(T){let E=Date.now()-new Date(n.updated_at).getTime();y=f(E),C=e.cyan;}else y="\u2014",C=void 0;let M=o?"\u25B8":" ",A=n.goalId?p?.get(n.goalId):void 0,S=!!A,H=10,V=4,F=14,P=S?ml:0,j=7,O=2+H+V+F+P+j,L=r?Math.max(10,r-O):40,N=n.assignee?l?.get(n.assignee)??n.assignee:void 0;return jsxs(Box,{children:[jsxs(Text,{color:o?e.amber:void 0,children:[M," "]}),jsx(Box,{width:H,children:jsx(Text,{backgroundColor:b.bg,color:b.fg,bold:b.bold,children:b.spinner?jsxs(Fragment,{children:[" ",jsx(jt,{color:b.fg})," ",b.label," "]}):jsxs(Fragment,{children:[" ",b.icon," ",b.label," "]})})}),jsx(Box,{width:V,children:jsx(Text,{color:x.color,bold:n.priority<=2,children:x.label})}),jsxs(Box,{width:L,children:[jsx(Text,{wrap:"truncate",bold:o||T,color:o?e.white:T?e.silver:void 0,children:n.title.length>L?n.title.slice(0,L-1)+"\u2026":n.title}),(n.attachments?.length??0)>0&&jsxs(Text,{color:e.dim,children:[" ","\u{1F4CE}",n.attachments.length]})]}),S&&jsx(Box,{width:P,children:jsxs(Text,{backgroundColor:fl,color:e.amberDim,wrap:"truncate",children:[" \u2295 ",rt(A.title,13)," "]})}),jsx(Box,{width:F,children:N?jsxs(Text,{backgroundColor:Pt.green,color:e.green,wrap:"truncate",children:[" ",N.length>F-2?N.slice(0,F-3)+"\u2026":N," "]}):jsx(Text,{color:e.ghost,children:"\u2014"})}),jsx(Box,{width:j,justifyContent:"flex-end",children:jsx(Text,{color:C,dimColor:!C,children:y})})]})});var Os="\u2295";function Ls({goalTitle:t,taskCount:n,doneCount:o,width:r}){let l=n>0?Math.round(o/n*100):0,p=` ${Os} ${t.toUpperCase()} ${me} ${n} task${n!==1?"s":""} ${me} ${l}% done `,b=3,T=Math.max(0,r-b-p.length-4);return jsxs(Box,{paddingX:2,children:[jsx(Text,{color:e.ghost,children:be(b)}),jsx(Text,{backgroundColor:Pt.amber,color:e.amber,bold:true,children:p}),jsx(Text,{color:e.ghost,children:be(T)})]})}function Ps({taskCount:t,width:n}){let o=` ${Os} UNGROUPED ${me} ${t} task${t!==1?"s":""} `,r=3,l=Math.max(0,n-r-o.length-4);return jsxs(Box,{paddingX:2,children:[jsx(Text,{color:e.ghost,children:be(r)}),jsx(Text,{backgroundColor:Pt.neutral,color:e.dim,children:o}),jsx(Text,{color:e.ghost,children:be(l)})]})}var hl="\u2715",Ns="\u25CB",xl="\u25B6",bl="\u2713",On={green:"#0f2d1f",red:"#2d0f0f",neutral:"#1a1a22",amber:"#2d1f0a"},Tl={running:{icon:xl,label:"ACTIVE",fg:e.green,bg:On.green,bold:true,spinner:true},idle:{icon:Ns,label:"IDLE",fg:e.dim,bg:On.neutral},error:{icon:hl,label:"ERROR",fg:e.red,bg:On.red,bold:true},disabled:{icon:Ns,label:"OFF",fg:e.ghost,bg:On.neutral}},_r={running:0,idle:1,error:2,disabled:3},Fs=ao.memo(function({agent:n,selected:o,width:r,runningEntry:l,currentTaskTitle:p,teamName:b,isLead:T}){let x=Tl[n.status],y=n.status==="running",C,M;if(y&&l){let N=Date.now()-new Date(l.started_at).getTime();C=f(N),M=e.cyan;}else n.stats.total_runs>0?(C=`${n.stats.tasks_completed}/${n.stats.total_runs}`,M=n.stats.tasks_completed>0?e.green:e.dim):(C="\u2014",M=void 0);let A=o?"\u25B8":" ",S=11,H=8,V=b?Math.min(b.length+2,12):0,F=10,P=2+S+H+V+F,j=r?Math.max(8,r-P):20,O=n.stats.total_runs>0,L=O?Math.round(n.stats.tasks_completed/n.stats.total_runs*100):0;return jsxs(Box,{children:[jsxs(Text,{color:o?e.amber:void 0,children:[A," "]}),jsx(Box,{width:S,children:jsx(Text,{backgroundColor:x.bg,color:x.fg,bold:x.bold,children:x.spinner?jsxs(Fragment,{children:[" ",jsx(jt,{color:x.fg})," ",x.label," "]}):jsxs(Fragment,{children:[" ",x.icon," ",x.label," "]})})}),jsx(Box,{width:j,children:jsxs(Text,{wrap:"truncate",bold:o||y,color:o?e.white:y?e.green:e.silver,children:[n.autonomous&&jsxs(Text,{color:e.cyan,children:[mn," "]}),T&&jsxs(Text,{color:e.amber,children:[Mr," "]}),n.name,y&&p&&jsxs(Text,{color:e.dim,children:[" ",me," ",p]}),n.status==="error"&&n.last_error&&jsxs(Text,{color:e.red,children:[" ",me," ",rt(m[n.last_error.kind]?.message??n.last_error.message,30)]})]})}),jsx(Box,{width:H,children:jsx(Text,{color:e.dim,children:n.adapter})}),b&&jsx(Box,{width:V,children:jsx(Text,{color:e.amber,wrap:"truncate",children:b})}),jsx(Box,{width:F,justifyContent:"flex-end",children:O&&!y?jsxs(Text,{color:L>=80?e.green:L>=50?e.yellow:e.red,children:[C," ",bl]}):jsx(Text,{color:M,dimColor:!M,children:C})})]})});function Gs({teamName:t,memberCount:n,leadName:o,width:r}){let l=`${n} agent${n!==1?"s":""}`,p=o?` ${me} ${Mr} ${o}`:"",b=` ${Jt} ${t.toUpperCase()} ${me} ${l}${p} `,T=3,x=Math.max(0,r-T-b.length-4);return jsxs(Box,{paddingX:2,children:[jsx(Text,{color:e.ghost,children:be(T)}),jsx(Text,{backgroundColor:On.amber,color:e.amber,bold:true,children:b}),jsx(Text,{color:e.ghost,children:be(x)})]})}var yl="\u25C7";function Ws({memberCount:t,width:n}){let o=`${t} agent${t!==1?"s":""}`,r=` ${yl} UNASSIGNED ${me} ${o} `,l=3,p=Math.max(0,n-l-r.length-4);return jsxs(Box,{paddingX:2,children:[jsx(Text,{color:e.ghost,children:be(l)}),jsx(Text,{backgroundColor:On.neutral,color:e.dim,children:r}),jsx(Text,{color:e.ghost,children:be(p)})]})}var zs="\u2713",Vs="\u2715",Sl="\u2016",kl="\u25C9",io={green:"#0f2d1f",amber:"#2d1f0a",neutral:"#1a1a22"},Cl={active:{icon:kl,label:"ACTIVE",fg:e.green,bg:io.green,bold:true},paused:{icon:Sl,label:"PAUSED",fg:e.dim,bg:io.neutral},achieved:{icon:zs,label:"DONE",fg:e.amber,bg:io.amber,bold:true},abandoned:{icon:Vs,label:"DROP",fg:e.ghost,bg:io.neutral}},Il="\u2588",Ml="\u2591",vl=14,Hs=ao.memo(function({goal:n,selected:o,width:r,agentNameMap:l,tasksByGoal:p}){let b=Cl[n.status],T=o?"\u25B8":" ",x=p?.length??0,y=p?.filter(L=>L.status==="done").length??0,C=x>0,M=11,A=C?vl:0,S=14,H=7,V=2+M+A+S+H,F=r?Math.max(10,r-V):40,P=n.assignee?l?.get(n.assignee)??n.assignee:void 0,j,O;if(n.status==="achieved")j=zs,O=e.amber;else if(n.status==="abandoned")j=Vs,O=e.ghost;else {let L=Date.now()-new Date(n.created_at).getTime(),N=Math.floor(L/864e5);j=N>0?`${N}d`:"<1d",O=e.dim;}return jsxs(Box,{children:[jsxs(Text,{color:o?e.amber:void 0,children:[T," "]}),jsx(Box,{width:M,children:jsxs(Text,{backgroundColor:b.bg,color:b.fg,bold:b.bold,children:[" ",b.icon," ",b.label," "]})}),jsx(Box,{width:F,children:jsx(Text,{wrap:"truncate",bold:o||n.status==="active",color:o?e.white:n.status==="active"?e.silver:void 0,children:n.title.length>F?n.title.slice(0,F-1)+"\u2026":n.title})}),C&&(()=>{let N=x>0?Math.round(y/x*6):0,E=6-N;return jsxs(Box,{width:A,children:[jsx(Text,{color:e.green,children:Il.repeat(N)}),jsx(Text,{color:e.ghost,children:Ml.repeat(E)}),jsx(Text,{color:e.dim,children:` ${y}/${x}`})]})})(),jsx(Box,{width:S,children:P?jsxs(Text,{backgroundColor:io.green,color:e.green,wrap:"truncate",children:[" ",P.length>S-2?P.slice(0,S-3)+"\u2026":P," "]}):jsx(Text,{color:e.ghost,children:"\u2014"})}),jsx(Box,{width:H,justifyContent:"flex-end",children:jsx(Text,{color:O,dimColor:!O,children:j})})]})});var _l={system:"\u2666",lifecycle:"\u25B6",output:"\u2502",tool:"\u2699",result:"\u2190",error:"\u2715",file:"\u270E",info:"\u2502"};function Nn({label:t,width:n,color:o}){let r=n-4,l=` ${t} `,p=3,b=Math.max(0,r-p-l.length);return jsxs(Text,{color:o??e.ghost,children:[" ",be(p),l,be(b)]})}function js({task:t,height:n,width:o,taskLogs:r,agentNameMap:l,taskTitleMap:p}){let b=Ao[t.status]??e.dim,T=t.priority<=2?t.priority===1?e.red:e.yellow:void 0,x=24,y=!!t.description?.trim(),C=!!t.proof?.agent_summary,M=(t.proof?.files_changed?.length??0)>0,A=(r?.length??0)>0,S=(t.attachments?.length??0)>0,H=y?t.description.split(`
4
- `):[],V=C?t.proof.agent_summary.split(`
5
- `):[],F=3;S&&(F+=2+t.attachments.length),y?(F+=1,F+=Math.min(H.length,Math.max(1,Math.ceil((n-10)*.3)))):C||(F+=2),C&&(F+=2),M&&(F+=1),A&&(F+=2);let P=Math.max(0,n-F),j=0,O=0;C&&A?(j=Math.max(1,Math.floor(P*.4)),O=Math.max(1,P-j)):C?j=P:A&&(O=P);let L=y?H.slice(0,Math.max(1,Math.ceil((n-10)*.3))):[],N=V.slice(0,j);return jsxs(Box,{flexDirection:"column",paddingX:2,children:[jsxs(Box,{children:[jsxs(Box,{width:x,children:[jsx(Text,{color:e.dim,children:" status "}),jsx(Text,{color:b,children:t.status})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" assignee "}),jsx(Text,{color:t.assignee?e.green:e.dim,children:t.assignee?l?.get(t.assignee)??t.assignee:"\u2014"})]})]}),jsxs(Box,{children:[jsxs(Box,{width:x,children:[jsx(Text,{color:e.dim,children:" priority "}),jsxs(Text,{color:T,bold:t.priority<=2,children:["P",t.priority]})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" attempts "}),jsxs(Text,{children:[t.attempts,"/",t.max_attempts]})]})]}),jsxs(Box,{children:[jsxs(Box,{width:x,children:[jsx(Text,{color:e.dim,children:" labels "}),jsx(Text,{color:e.purple,children:t.labels.length>0?t.labels.join(", "):"\u2014"})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" depends "}),jsx(Text,{dimColor:true,children:t.depends_on.length>0?t.depends_on.map(E=>p?.get(E)??E).join(", "):"\u2014"})]})]}),S&&jsxs(Fragment,{children:[jsx(Text,{children:" "}),jsx(Nn,{label:`attachments (${t.attachments.length})`,width:o,color:e.dim}),t.attachments.map((E,W)=>jsxs(Text,{color:e.cyan,wrap:"truncate",children:[" ",E]},`a${W}`))]}),y&&jsxs(Fragment,{children:[jsx(Text,{children:" "}),L.map((E,W)=>jsxs(Text,{color:e.silver,wrap:"truncate",children:[" ",rt(E,o-8)]},`d${W}`))]}),!y&&!C&&jsxs(Fragment,{children:[jsx(Text,{children:" "}),jsx(Text,{color:e.dim,children:" No description."})]}),C&&jsxs(Fragment,{children:[jsx(Text,{children:" "}),jsx(Nn,{label:"result",width:o,color:e.dim}),N.map((E,W)=>jsxs(Text,{color:e.white,wrap:"truncate",children:[" ",rt(E,o-8)]},`r${W}`))]}),M&&jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" files "}),jsx(Text,{color:e.cyan,children:t.proof.files_changed.length}),jsx(Text,{color:e.dim,children:" changed"}),t.proof.branch&&jsxs(Fragment,{children:[jsxs(Text,{color:e.dim,children:[" ","\xB7"," "]}),jsx(Text,{color:e.cyan,children:t.proof.branch})]})]}),A&&jsxs(Fragment,{children:[jsx(Text,{children:" "}),jsx(Nn,{label:"activity",width:o,color:e.dim}),r.slice(-O).map((E,W)=>{let z=E.msgType??"info",X=_l[z]??"\u2502",_=E.color;z==="tool"?_=e.cyan:z==="file"?_=e.purple:z==="error"?_=e.red:z==="lifecycle"?_=e.green:z==="system"&&(_=e.dim);let ae=Math.max(10,o-12),Ee=rt(E.text,ae);return jsxs(Box,{children:[jsxs(Text,{color:e.ghost,children:[" ",E.time," "]}),jsxs(Text,{color:z==="error"?e.red:e.dim,children:[X," "]}),jsx(Text,{color:_,bold:z==="lifecycle",children:Ee})]},W)})]})]})}var Oo=[{key:"G",id:"goals",label:"GOALS"},{key:"T",id:"tasks",label:"TASKS"},{key:"A",id:"agents",label:"AGENTS"},{key:"L",id:"logs",label:"ACTIONS"}];var Us="\u25CF",Xs="\u25CB",Rl="\u2713",Al="\u2715",$l="\u2191",Bl="\u2193",El="\u03A3",Ol="\u25B6",Ll="\u21BB",Pl="\u{1F9E0}",Rr=[" ","\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],Qe={green:"#0f2d1f",blue:"#0f1f2d",yellow:"#2d2a0f",red:"#2d0f0f",neutral:"#1a1a22",amber:"#2d1f0a"};function Nl({active:t}){let n=En(t),o=!t||Math.floor(n/10)%2===0;return jsx(Text,{color:o?e.amber:e.amberDim,bold:true,children:Ht})}function Dl({width:t,active:n}){let o=Math.max(4,Math.floor(t*.08)),r=2,l=En(n),p=Math.ceil((t+o)/r),b=n?l%(p*2):0;if(!n)return jsx(Box,{paddingX:1,children:jsx(Text,{color:e.ghost,children:He(t)})});let T=b<p?b*r:(p*2-b)*r,x=Math.max(0,T-o),y=Math.min(t,T),C=x,M=Math.max(0,y-x),A=Math.max(0,t-y);return jsxs(Box,{paddingX:1,children:[jsx(Text,{color:e.ghost,children:He(C)}),jsx(Text,{color:e.amber,children:He(M)}),jsx(Text,{color:e.ghost,children:He(A)})]})}function Fl({data:t,width:n,color:o}){if(t.length===0)return null;let r=t.slice(-n),l=Math.max(...r,1),p=r.map(b=>{let T=Math.round(b/l*(Rr.length-1));return Rr[T]??Rr[0]}).join("");return jsx(Text,{color:o,children:p})}function Gl({tab:t,flashColor:n,onComplete:o,badge:r}){let l=En(),p=ao.useRef(l),b=ao.useRef(false),T=l-p.current,x=2,y=6*x;return ao.useEffect(()=>{T>=y&&!b.current&&(b.current=true,o());},[T,o]),Math.floor(T/x)%2===0&&T<y?jsxs(Text,{backgroundColor:n,color:"#0a0a0c",bold:true,children:[" ",t.key," ",t.label,r," "]}):jsxs(Box,{gap:0,children:[jsx(Text,{color:e.ghost,children:t.key}),jsxs(Text,{color:e.dim,children:[" ",t.label.toLowerCase(),r]})]})}function Wl({projectName:t,activeView:n,mode:o,stats:r,uptime:l,width:p,version:b,latestVersion:T,updateInstalled:x,taskBadge:y,flashTab:C,flashColor:M,onFlashComplete:A}){return jsxs(Box,{paddingX:1,justifyContent:"space-between",width:p,children:[jsxs(Box,{gap:0,children:[jsx(Nl,{active:r.running>0}),jsx(Text,{color:e.amber,bold:true,children:" ORCH"}),b&&jsxs(Text,{color:e.ghost,children:[" ",b]}),T&&T!==b&&(x?jsxs(Text,{backgroundColor:Qe.green,color:e.green,bold:true,children:[" v",T," INSTALLED \u2014 RESTART TO APPLY "]}):jsxs(Text,{backgroundColor:Qe.green,color:e.green,bold:true,children:[" UPDATE ",T," "]})),jsxs(Text,{color:e.ghost,children:[" ",me," "]}),jsx(Text,{color:e.silver,children:t})]}),jsx(Box,{gap:0,children:Oo.map((S,H)=>{let V=n===S.id,F=S.id==="tasks"&&y!=null&&y>0?` (${y})`:"",P=!V&&C===S.id&&M&&A;return jsxs(ao.Fragment,{children:[H>0&&jsx(Text,{children:" "}),V?jsxs(Text,{backgroundColor:e.amber,color:"#0a0a0c",bold:true,children:[" ",S.key," ",S.label,F," "]}):P?jsx(Gl,{tab:S,flashColor:M,onComplete:A,badge:F}):jsxs(Box,{gap:0,children:[jsx(Text,{color:e.ghost,children:S.key}),jsxs(Text,{color:e.dim,children:[" ",S.label.toLowerCase(),F]})]})]},S.id)})}),jsxs(Box,{gap:0,children:[o==="watching"?jsxs(Text,{backgroundColor:Qe.green,color:e.green,bold:true,children:[" ",Us," WATCHING"," "]}):o==="observing"?jsxs(Text,{backgroundColor:Qe.amber,color:e.amber,bold:true,children:[" ",Us," OBSERVING"," "]}):jsxs(Text,{backgroundColor:Qe.neutral,color:e.dim,children:[" ",Xs," IDLE"," "]}),r.running>0&&jsxs(Fragment,{children:[jsx(Text,{children:" "}),jsxs(Text,{backgroundColor:Qe.green,color:e.green,children:[" ",jsx(jt,{color:e.green})," ",r.running," active"," "]})]}),l&&jsxs(Text,{color:e.ghost,children:[" ",l]})]})]})}function zl({stats:t,tokens:n,width:o,sparklineData:r}){let p=[{icon:Ol,label:"RUN",count:t.running,fg:e.green,bg:Qe.green,bold:true,spinner:true,show:t.running>0},{icon:Ll,label:"RETRY",count:t.retrying,fg:e.yellow,bg:Qe.yellow,show:t.retrying>0},{icon:Jt,label:"REVIEW",count:t.review,fg:e.blue,bg:Qe.blue,show:t.review>0},{icon:Xs,label:"TODO",count:t.todo,fg:e.dim,bg:Qe.neutral,show:t.todo>0},{icon:Rl,label:"DONE",count:t.done,fg:e.green,bg:Qe.green,show:t.done>0},{icon:Al,label:"FAIL",count:t.failed,fg:e.red,bg:Qe.red,bold:true,show:t.failed>0},{icon:Ht,label:"TEAMS",count:t.teams,fg:e.amber,bg:Qe.amber,show:t.teams>0}].filter(x=>x.show),b=n.total>0,T=r&&r.length>0?Math.min(16,r.length):0;return jsxs(Box,{paddingX:1,justifyContent:"space-between",width:o,children:[jsxs(Box,{gap:1,children:[p.map(x=>jsx(Text,{backgroundColor:x.bg,color:x.fg,bold:x.bold,children:x.spinner?jsxs(Fragment,{children:[" ",jsx(jt,{color:x.fg})," ",x.count," ",x.label," "]}):jsxs(Fragment,{children:[" ",x.icon," ",x.count," ",x.label," "]})},x.label)),p.length===0&&jsxs(Text,{backgroundColor:Qe.neutral,color:e.dim,children:[" ","NO TASKS"," "]})]}),jsxs(Box,{gap:0,children:[T>0&&r&&jsxs(Fragment,{children:[jsx(Fl,{data:r,width:T,color:e.amberDim}),jsx(Text,{children:" "})]}),b&&jsxs(Text,{backgroundColor:Qe.amber,color:e.cyan,children:[" ",$l,h(n.input)," ",Bl,h(n.output),n.reasoning>0?` ${Pl}${h(n.reasoning)}`:""," ",me," ",El,h(n.total)," "]})]})]})}var qs=ao.memo(function(n){let o=Math.max(10,n.width-2),r=n.stats.running>0;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{height:1}),jsx(Wl,{projectName:n.projectName,activeView:n.activeView,mode:n.mode,stats:n.stats,uptime:n.uptime,width:n.width,version:n.version,latestVersion:n.latestVersion,updateInstalled:n.updateInstalled,taskBadge:n.taskBadge,flashTab:n.flashTab,flashColor:n.flashColor,onFlashComplete:n.onFlashComplete}),jsx(Box,{height:1}),jsx(zl,{stats:n.stats,tokens:n.tokens,width:n.width,sparklineData:n.sparklineData}),jsx(Dl,{width:o,active:r})]})});var lo="\u0423\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415",Dn="\u041C\u041E\u041D\u0418\u0422\u041E\u0420\u0418\u041D\u0413",Po="\u041D\u0410\u0421\u0422\u0420\u041E\u0419\u041A\u0418",fn={task:{sub:["add","list","show","cancel","retry","assign","approve","reject","delete"],help:"Manage tasks",category:lo},agent:{sub:["add","list","disable","enable","delete","autonomous","shop"],help:"Manage agents",category:lo},team:{sub:["create","list","join","leave","disband","set-lead"],help:"Manage teams",category:lo},goal:{sub:["add","list","show","status","delete"],help:"Manage goals",category:lo},run:{args:"[id]",help:"Run task (or selected)",category:Dn},"run-all":{help:"Run all todo tasks",category:Dn},watch:{help:"Start watch mode (auto-dispatch)",category:Dn},pause:{help:"Pause watch mode",category:Dn},status:{help:"Show orchestrator status",category:Dn},config:{sub:["activity-filter","max-concurrent"],help:"TUI settings",category:Po},help:{help:"List all commands",category:Po},quit:{help:"Exit the TUI",category:Po}};function Ar(t){if(!t.startsWith("/"))return null;let n=t.slice(1),o=n.indexOf(" ");if(o===-1){let T=n;if(!T)return null;let x=Object.keys(fn).find(y=>y.startsWith(T)&&y!==T);return x?x.slice(T.length):null}let r=n.slice(0,o),l=fn[r];if(!l?.sub)return null;let p=n.slice(o+1);if(!p)return null;let b=l.sub.find(T=>T.startsWith(p)&&T!==p);return b?b.slice(p.length):null}function Ks(t){if(!t.startsWith("/"))return [];let n=t.slice(1),o=n.indexOf(" ");if(o===-1){let T=n.toLowerCase(),x=[];if(!T){let y=[lo,Dn,Po];for(let C of y){x.push({cmd:"",desc:`\u2500\u2500 ${C} \u2500\u2500`});for(let[M,A]of Object.entries(fn))if(A.category===C){let S=A.args?` ${A.args}`:"";x.push({cmd:`/${M}${S}`,desc:A.help,subs:A.sub?.join(" \xB7 ")});}}return x}for(let[y,C]of Object.entries(fn))if(y.startsWith(T)){let M=C.args?` ${C.args}`:"";if(x.push({cmd:`/${y}${M}`,desc:C.help,subs:C.sub?.join(" \xB7 ")}),y===T&&C.sub)for(let A of C.sub)x.push({cmd:`/${y} ${A}`,desc:`${C.help}: ${A}`});}return x}let r=n.slice(0,o),l=fn[r];if(!l?.sub)return [];let p=n.slice(o+1).toLowerCase(),b=[];for(let T of l.sub)(!p||T.startsWith(p))&&b.push({cmd:`/${r} ${T}`,desc:`${l.help}: ${T}`});return b}var No=class{entries=[];cursor=0;push(n){n&&(this.entries[this.entries.length-1]!==n&&(this.entries.push(n),this.entries.length>100&&this.entries.shift()),this.cursor=this.entries.length);}prev(){return this.entries.length===0?null:(this.cursor>0&&this.cursor--,this.entries[this.cursor]??null)}next(){return this.cursor<this.entries.length-1?(this.cursor++,this.entries[this.cursor]??null):(this.cursor=this.entries.length,null)}reset(){this.cursor=this.entries.length;}};var Hl="\u2588",Ys=ao.memo(function({mode:n,value:o,completion:r,activeView:l,canRun:p,canNew:b,canApprove:T,canReject:x,canCancel:y,canDelete:C,canUndo:M,canEdit:A,canForceStop:S,canToggleAuto:H,autoActive:V,canPause:F,isPaused:P,canToggleShowAll:j,showAllActive:O,hasDetail:L,itemCount:N,itemLabel:E,width:W,hasSuggestions:z,onboardingCompleted:X}){if(n==="command"){let _=z?" \u2191\u2193 select Tab fill Esc \u2715":" Enter exec \u2191\u2193 history Tab complete Esc \u2715",ae=Math.max(4,W-6-_.length-(r?.length??0)-1),Ee=o.length>ae?"\u2026"+o.slice(-(ae-1)):o;return jsx(Box,{paddingX:2,justifyContent:"space-between",width:W,children:jsxs(Box,{children:[jsx(Text,{color:e.amber,children:"/ "}),jsx(Text,{color:e.white,children:Ee}),r&&jsx(Text,{color:e.ghost,children:r}),jsx(Text,{color:e.amber,children:Hl}),jsx(Text,{color:e.dim,children:_})]})})}return jsxs(Box,{paddingX:2,justifyContent:"space-between",width:W,children:[jsxs(Text,{color:e.dim,children:[jsx(Text,{bold:true,color:e.gray,children:"\u2191\u2193"})," ",jsx(Text,{bold:true,color:e.gray,children:"Tab"}),"/",jsx(Text,{bold:true,color:e.gray,children:"\u2190\u2192"})," ",jsx(Text,{bold:true,color:e.gray,children:"/"})," cmd",b&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.gray,children:"N"})," new"]}),p&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.gray,children:"R"})," run"]}),y&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.amber,children:"C"})," cancel"]}),T&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.green,children:"A"})," approve"]}),x&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.red,children:"X"})," reject"]}),A&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.cyan,children:"E"})," edit"]}),S&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.red,children:"S"})," stop"]}),F&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.amber,children:"P"}),P?" resume":" pause"]}),H&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.cyan,children:"U"}),V?" auto off":" auto on"]}),j&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.gray,children:"S"}),O?" collapse":" show all"]}),C&&!T&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.gray,children:"D"})," delete"]}),M&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.yellow,children:"Z"})," undo"]}),L&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.gray,children:"Esc"})," close"]}),!L&&(l==="tasks"||l==="agents"||l==="goals")&&jsxs(Fragment,{children:[" ",jsx(Text,{bold:true,color:e.gray,children:"Enter"})," detail"]})," ",jsx(Text,{bold:true,color:e.gray,children:"Q"})," quit"," ",jsx(Text,{bold:true,color:X===false?e.amber:e.gray,children:"?"}),jsx(Text,{color:X===false?e.amber:void 0,children:" help"})]}),N>0&&jsxs(Text,{color:e.dim,children:[N," ",E]})]})});var Do="\u2588",Br=process.platform==="darwin"?"\u2318":"Ctrl";function Xl(t,n){if(n<=0||t.length<=n)return [t];let o=[];for(let r=0;r<t.length;r+=n)o.push(t.slice(r,r+n));return o}function Fo(t,n){if(n<=0)return 0;let o=n-1;for(;o>0&&t[o-1]===" ";)o--;for(;o>0&&t[o-1]!==" ";)o--;return o}function Qs(t,n){if(n>=t.length)return t.length;let o=n;for(;o<t.length&&t[o]!==" ";)o++;for(;o<t.length&&t[o]===" ";)o++;return o}function ei({title:t,steps:n,onComplete:o,onCancel:r,width:l,height:p,onPasteImage:b,footerExtra:T,onSuggestionSelected:x}){let [y,C]=useState(0),[M,A]=useState({}),[S,H]=useState(()=>{let $=n.find(I=>!I.skip?.({}));return $?.type==="text"&&$.defaultValue?$.defaultValue:""}),[V,F]=useState(()=>{let $=n.find(I=>!I.skip?.({}));return $?.type==="text"&&$.defaultValue?$.defaultValue.length:0}),[P,j]=useState(()=>{let $=n.find(I=>!I.skip?.({}));return $?.type==="textarea"&&$.defaultValue?$.defaultValue.split(`
6
- `):[""]}),[O,L]=useState(0),[N,E]=useState(0),[W,z]=useState(()=>{let $=n.find(I=>!I.skip?.({}));if($?.type==="select"&&$.defaultValue){let k=($.getOptions?.({})??$.options??[]).findIndex(B=>B.value===$.defaultValue);return k>=0?k:0}return 0}),X=useMemo(()=>n.filter($=>!$.skip?.(M)),[n,M]),_=X[y],ae=X.length,{taLineNumWidth:Ft,taContentWidth:dt}=useMemo(()=>{let $=String(P.length).length;return {taLineNumWidth:$,taContentWidth:Math.max(1,l-$-4)}},[P.length,l]),Re=useMemo(()=>{if(!_||_.type!=="textarea")return [];let $=[];for(let I=0;I<P.length;I++){let k=Xl(P[I]??"",dt);for(let B=0;B<k.length;B++)$.push({logicalRow:I,startCol:B*dt,text:k[B],isFirst:B===0});}return $},[_?.id,_?.type,P,dt]),Ke=useMemo(()=>{for(let $=0;$<Re.length;$++){let I=Re[$];if(I.logicalRow===O&&(N>=I.startCol&&N<I.startCol+dt||N>=I.startCol&&($+1>=Re.length||Re[$+1].logicalRow!==O)))return $}return 0},[Re,O,N,dt]),[ut,pt]=useState(new Set),[De,Ye]=useState(false),[gt,Ze]=useState(0),[on,Ce]=useState(false),[ht,xt]=useState(null),[qt,mt]=useState(false),kt=useRef(null),Ue=useRef(null),go=useMemo(()=>_?_.type==="text"?S:_.type==="textarea"?P.join(`
7
- `):"":"",[_,S,P]),Wn=useCallback(($,I)=>{if(kt.current&&clearTimeout(kt.current),!I){xt(null);return}kt.current=setTimeout(()=>{xt(I($));},300);},[]);useEffect(()=>(_&&_.validate&&(_.type==="text"||_.type==="textarea")&&Wn(go,_.validate),()=>{kt.current&&clearTimeout(kt.current);}),[go,_,Wn]),useEffect(()=>()=>{Ue.current&&clearTimeout(Ue.current);},[]);let Rt=useMemo(()=>!_||_.type!=="select"&&_.type!=="multiselect"?[]:_.getOptions?.(M)??_.options??[],[_,M]),Gt=Math.min(W,Math.max(0,Rt.length-1)),Wt=useMemo(()=>{if(!_?.suggestions)return [];if(!S.trim())return _.suggestions;let $=S.toLowerCase();return _.suggestions.filter(I=>I.label.toLowerCase().includes($)||(I.hint??"").toLowerCase().includes($))},[_?.suggestions,S]),zt=Math.min(gt,Math.max(0,Wt.length-1)),rn=$=>{let I={...M,[_.id]:$};A(I),H(""),F(0),j([""]),L(0),E(0),z(0),pt(new Set),Ye(false),Ze(0),Ce(false),xt(null),mt(false),kt.current&&clearTimeout(kt.current);let k=_.id,q=n.findIndex(te=>te.id===k)+1;for(;q<n.length;){let te=n[q];if(te&&!te.skip?.(I))break;q++;}if(q>=n.length)o(I);else {let te=n[q].id,de=n.filter(Ae=>!Ae.skip?.(I)).findIndex(Ae=>Ae.id===te);C(de>=0?de:0);let K=n[q];if(K.type==="text"){let Ae=K.defaultValue??"";H(Ae),F(Ae.length);}else if(K.type==="textarea"){let Ae=K.defaultValue?K.defaultValue.split(`
8
- `):[""];j(Ae),L(Ae.length-1),E(Ae[Ae.length-1].length);}else if(K.type==="select"){let Ae=K.getOptions?.(I)??K.options??[];if(K.defaultValue){let we=Ae.findIndex(Vn=>Vn.value===K.defaultValue);z(we>=0?we:0);}else z(0);}else K.type==="multiselect"&&(z(0),K.defaultValue?pt(new Set(K.defaultValue.split(","))):pt(new Set));}},sn=()=>{if(y===0){r();return}let $=_.id,k=n.findIndex(de=>de.id===$)-1;for(;k>=0;){let de=n[k];if(de&&!de.skip?.(M))break;k--;}if(k<0){r();return}let B=n[k].id,q=X.findIndex(de=>de.id===B);C(q>=0?q:0),Ye(false),Ze(0),Ce(false),xt(null),mt(false),kt.current&&clearTimeout(kt.current);let te=n[k];if(M[te.id]&&Ce(true),te.type==="text"){let de=M[te.id]??te.defaultValue??"";H(de),F(de.length);}else if(te.type==="textarea"){let de=M[te.id]??te.defaultValue??"",K=de?de.split(`
9
- `):[""];j(K),L(K.length-1),E(K[K.length-1].length);}else if(te.type==="multiselect"){z(0);let de=M[te.id];pt(de?new Set(de.split(",")):new Set);}else {let de=te.getOptions?.(M)??te.options??[],K=M[te.id],Ae=de.findIndex(we=>we.value===K);z(Ae>=0?Ae:0);}};if(useInput(($,I)=>{if(_){if(I.escape){y===0?r():sn();return}if((I.ctrl||I.meta)&&($==="v"||$==="i")&&b&&(_.type==="text"||_.type==="textarea")){b();return}if(_.type==="text"){if(De&&Wt.length>0){if(I.upArrow){zt<=0?Ye(false):Ze(k=>k-1);return}if(I.downArrow){Ze(k=>Math.min(Wt.length-1,k+1));return}if(I.return){let k=Wt[zt];k&&x&&x(k.value);return}Ye(false);}if(I.return){let k=S.trim();if(_.required&&!k){Ce(true);return}if(ht!==null){Ce(true),mt(true),Ue.current&&clearTimeout(Ue.current),Ue.current=setTimeout(()=>mt(false),2e3);return}rn(k);return}if(I.downArrow&&_.suggestions&&Wt.length>0){Ye(true),Ze(0);return}if(I.ctrl&&$==="a"){F(0);return}if(I.ctrl&&$==="e"){F(S.length);return}if(I.ctrl&&$==="k"){Ce(true),H(k=>k.slice(0,V));return}if(I.ctrl&&$==="u"){Ce(true),H(k=>k.slice(V)),F(0);return}if(I.ctrl&&$==="w"){Ce(true);let k=Fo(S,V);H(B=>B.slice(0,k)+B.slice(V)),F(k);return}if(I.meta&&(I.leftArrow||$==="b")){F(Fo(S,V));return}if(I.meta&&(I.rightArrow||$==="f")){F(Qs(S,V));return}if(I.leftArrow){F(k=>Math.max(0,k-1));return}if(I.rightArrow){F(k=>Math.min(S.length,k+1));return}if(I.backspace||I.delete){if(V===0&&S.length===0&&y>0){sn();return}V>0&&(H(k=>k.slice(0,V-1)+k.slice(V)),F(k=>k-1));return}$&&!I.ctrl&&!I.meta&&!I.escape&&(Ce(true),Ye(false),Ze(0),H(k=>k.slice(0,V)+$+k.slice(V)),F(k=>k+$.length));return}if(_.type==="textarea"){if(I.return&&(I.ctrl||I.meta)){let k=P.join(`
10
- `).trim();if(_.required&&!k){Ce(true);return}if(ht!==null){Ce(true),mt(true),Ue.current&&clearTimeout(Ue.current),Ue.current=setTimeout(()=>mt(false),2e3);return}rn(k);return}if(I.return){Ce(true),j(k=>{let B=k[O]??"",q=B.slice(0,N),te=B.slice(N),le=[...k];return le.splice(O,1,q,te),le}),L(k=>k+1),E(0);return}if(I.ctrl&&$==="a"){E(0);return}if(I.ctrl&&$==="e"){E((P[O]??"").length);return}if(I.ctrl&&$==="k"){Ce(true),j(k=>{let B=[...k];return B[O]=(B[O]??"").slice(0,N),B});return}if(I.ctrl&&$==="u"){Ce(true),j(k=>{let B=[...k];return B[O]=(B[O]??"").slice(N),B}),E(0);return}if(I.ctrl&&$==="w"){Ce(true);let k=O,B=N;j(q=>{let te=q[k]??"",le=Fo(te,B),de=[...q];return de[k]=te.slice(0,le)+te.slice(B),E(le),de});return}if(I.meta&&(I.leftArrow||$==="b")){E(Fo(P[O]??"",N));return}if(I.meta&&(I.rightArrow||$==="f")){E(Qs(P[O]??"",N));return}if(I.upArrow){if(Ke>0){let k=Re[Ke],B=Re[Ke-1],q=N-(k?.startCol??0),te=Math.min(B.startCol+q,B.startCol+B.text.length);L(B.logicalRow),E(te);}return}if(I.downArrow){if(Ke<Re.length-1){let k=Re[Ke],B=Re[Ke+1],q=N-(k?.startCol??0),te=Math.min(B.startCol+q,B.startCol+B.text.length);L(B.logicalRow),E(te);}return}if(I.leftArrow){N>0?E(k=>k-1):O>0&&(L(k=>k-1),E((P[O-1]??"").length));return}if(I.rightArrow){let k=(P[O]??"").length;N<k?E(B=>B+1):O<P.length-1&&(L(B=>B+1),E(0));return}if(I.backspace||I.delete){if(N===0&&O===0)return;if(N>0)j(k=>{let B=[...k],q=B[O]??"";return B[O]=q.slice(0,N-1)+q.slice(N),B}),E(k=>k-1);else {let k=(P[O-1]??"").length;j(B=>{let q=[...B],te=q[O-1]??"",le=q[O]??"";return q.splice(O-1,2,te+le),q}),E(k),L(B=>B-1);}return}if($&&!I.ctrl&&!I.meta&&!I.escape){Ce(true);let k=$.split(/\r?\n/);if(k.length===1)j(B=>{let q=[...B],te=q[O]??"";return q[O]=te.slice(0,N)+$+te.slice(N),q}),E(B=>B+$.length);else {let B=O,q=N;j(te=>{let le=[...te],de=le[B]??"",K=de.slice(0,q),Ae=de.slice(q),we=k[0]??"",Vn=k[k.length-1]??"",Tn=[K+we,...k.slice(1,-1),Vn+Ae];return le.splice(B,1,...Tn),le}),L(B+k.length-1),E((k[k.length-1]??"").length);}}return}if(_.type==="select"||_.type==="multiselect"){if(I.upArrow||$==="k"){z(k=>Math.max(0,k-1));return}if(I.downArrow||$==="j"){z(k=>Math.min(Rt.length-1,k+1));return}if(I.backspace||I.delete){sn();return}if(_.type==="select"){if(I.return||I.tab){let k=Rt[Gt];if(k){if(_.validate){let B=_.validate(k.value);if(B!==null){Ce(true),xt(B),mt(true),Ue.current&&clearTimeout(Ue.current),Ue.current=setTimeout(()=>mt(false),2e3);return}}rn(k.value);}return}if($>="1"&&$<="9"){let k=parseInt($,10)-1;if(k<Rt.length){let B=Rt[k];B&&rn(B.value);}return}}else {if($===" "){let k=Rt[Gt];k&&pt(B=>{let q=new Set(B);return q.has(k.value)?q.delete(k.value):q.add(k.value),q});return}if(I.return){let k=Array.from(ut).join(",");rn(k);return}}}}}),!_)return null;let nt=on?ht:null,At=Math.max(20,l-6),xn=`${y+1}/${ae}`,zn=Math.max(2,p-4),Kt=0;Gt>=zn&&(Kt=Gt-zn+1);let bn=Rt.slice(Kt,Kt+zn);return jsxs(Box,{flexDirection:"column",paddingX:2,children:[jsxs(Box,{children:[jsx(Text,{color:e.amber,bold:true,children:t}),jsxs(Text,{color:e.ghost,children:[" ",Ve,Ve," "]}),jsxs(Text,{color:e.dim,children:["step ",xn]})]}),jsxs(Box,{children:[jsx(Text,{children:" "}),X.map(($,I)=>jsxs(Text,{color:I===y?e.amber:I<y?e.green:e.ghost,children:[I===y?"\u25CF":I<y?"\u2713":"\u25CB"," "]},$.id))]}),jsxs(Box,{marginTop:0,children:[jsxs(Text,{color:e.white,bold:true,children:[" ",_.label]}),_.required&&jsx(Text,{color:e.red,children:" *"}),!_.required&&jsxs(Text,{color:e.dim,children:[" (optional, ",_.type==="textarea"?`${Br}+Enter`:"Enter"," to skip)"]})]}),_.description&&jsx(Box,{children:jsxs(Text,{color:e.dim,children:[" ",_.description]})}),_.type==="text"&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{borderStyle:nt?"round":void 0,borderColor:nt?e.red:void 0,children:[jsxs(Text,{color:e.amber,children:[" ",">"," "]}),S.length>0?jsxs(Fragment,{children:[jsx(Text,{color:e.white,children:S.slice(0,V)}),jsx(Text,{color:e.amber,children:Do}),jsx(Text,{color:e.white,children:S.slice(V)})]}):_.placeholder?jsxs(Fragment,{children:[jsx(Text,{color:e.ghost,children:_.placeholder}),jsx(Text,{color:e.amber,children:Do})]}):jsx(Text,{color:e.amber,children:Do})]}),nt&&jsxs(Text,{color:e.red,dimColor:true,children:[" ",nt]}),qt&&jsx(Text,{color:e.red,children:" Fix the error above"})]}),_.type==="text"&&_.suggestions&&Wt.length>0&&(()=>{let $=Math.max(2,p-6),I=0;De&&zt>=$&&(I=zt-$+1);let k=Wt.slice(I,I+$);return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{color:e.ghost,children:[" ",Ve,Ve,Ve," or browse templates ",Ve.repeat(Math.max(0,At-28))]}),k.map((B,q)=>{let te=q+I,le=De&&te===zt;return jsxs(Box,{children:[jsx(Text,{color:le?e.amber:e.ghost,children:le?" \u25B8 ":" "}),jsx(Text,{color:le?e.white:e.silver,bold:le,children:B.label}),B.hint&&jsxs(Text,{color:e.dim,wrap:"truncate",children:[" ",Ve," ",B.hint.replace(/\n/g," ")]})]},B.value)})]})})(),_.type==="textarea"&&(()=>{let $=Math.max(3,p-6),I=0;Ke>=$&&(I=Ke-$+1);let k=Re.slice(I,I+$);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",borderStyle:nt?"round":void 0,borderColor:nt?e.red:void 0,children:[k.map((B,q)=>{let te=q+I,le=B.isFirst?String(B.logicalRow+1).padStart(Ft," "):"".padStart(Ft," "),de=te===Ke,K=N-B.startCol;return jsxs(Box,{children:[jsxs(Text,{color:e.dim,children:[" ",le," "]}),jsxs(Text,{color:e.ghost,children:["\u2502"," "]}),de?jsxs(Fragment,{children:[jsx(Text,{color:e.white,children:B.text.slice(0,K)}),jsx(Text,{color:e.amber,children:Do}),jsx(Text,{color:e.white,children:B.text.slice(K)})]}):jsx(Text,{color:e.silver,children:B.text||(B.isFirst?" ":"")})]},`${B.logicalRow}-${B.startCol}`)}),P.length===1&&P[0]===""&&_.placeholder&&jsx(Box,{children:jsxs(Text,{color:e.dim,children:[" ","".padStart(Ft," ")," ",_.placeholder]})})]}),nt&&jsxs(Text,{color:e.red,dimColor:true,children:[" ",nt]}),qt&&jsx(Text,{color:e.red,children:" Fix the error above"})]})})(),_.type==="select"&&jsxs(Box,{flexDirection:"column",children:[bn.map(($,I)=>{let k=I+Kt,B=k===Gt,q=String(k+1).padStart(Rt.length>=10?2:1);return jsxs(Box,{children:[jsx(Text,{color:B?e.amber:e.ghost,children:B?" \u25B8 ":` ${q} `}),jsx(Text,{color:B?e.white:e.silver,bold:B,children:$.label}),$.hint&&jsxs(Text,{color:e.dim,wrap:"truncate",children:[" ",Ve," ",$.hint.replace(/\n/g," ")]})]},$.value)}),nt&&jsxs(Text,{color:e.red,dimColor:true,children:[" ",nt]}),qt&&jsx(Text,{color:e.red,children:" Fix the error above"})]}),_.type==="multiselect"&&jsxs(Box,{flexDirection:"column",children:[bn.map(($,I)=>{let B=I+Kt===Gt,q=ut.has($.value);return jsxs(Box,{children:[jsx(Text,{color:B?e.amber:e.ghost,children:B?" \u25B8 ":" "}),jsx(Text,{color:q?e.green:e.dim,children:q?"[\u2713]":"[ ]"}),jsxs(Text,{color:B?e.white:e.silver,bold:B,children:[" ",$.label]}),$.hint&&jsxs(Text,{color:e.dim,wrap:"truncate",children:[" ",Ve," ",$.hint.replace(/\n/g," ")]})]},$.value)}),ut.size>0&&jsx(Box,{children:jsxs(Text,{color:e.dim,children:[" ","\u2514"," ",ut.size," selected"]})})]}),jsxs(Box,{marginTop:0,children:[jsxs(Text,{color:e.ghost,children:[" ",_.type==="select"?"\u2191\u2193 select Enter confirm":_.type==="multiselect"?"\u2191\u2193 move Space toggle Enter confirm":_.type==="textarea"?`Enter newline ${Br}+Enter confirm \u2190\u2191\u2192\u2193 navigate`:De?"\u2191\u2193 browse Enter select \u2191 back to input":_.suggestions?"\u2190\u2192 move Enter confirm \u2193 browse templates":"\u2190\u2192 move Enter confirm",b&&(_.type==="text"||_.type==="textarea")?` ${Br}+V paste image`:""," Esc ",y>0?"back":"cancel"]}),T&&jsxs(Text,{color:e.amber,children:[" ",T]})]})]})}var oi=ao.memo(function({agents:n,selected:o,msgCounts:r,colorMap:l,maxHeight:p,onConfirm:b,onCancel:T}){let [x,y]=useState(0),[C,M]=useState(()=>new Set(o));useMemo(()=>C.size===0||C.size===n.length,[C.size,n.length]);let S=Math.max(3,p-5),H=useMemo(()=>{if(n.length<=S)return 0;let P=Math.floor(S/2),j=n.length-S;return Math.min(j,Math.max(0,x-P))},[x,n.length,S]),V=n.slice(H,H+S);useInput((P,j)=>{if(j.upArrow){y(O=>O>0?O-1:n.length-1);return}if(j.downArrow){y(O=>O<n.length-1?O+1:0);return}if(P===" "){let O=n[x];if(!O)return;M(L=>{let N=new Set(L);return N.has(O.id)?N.delete(O.id):N.add(O.id),N});return}if(P==="a"||P==="A"){M(O=>new Set);return}if(j.return){b(new Set(C));return}if(j.escape){T();return}});let F=C.size===0?n.length:C.size;return jsxs(Box,{flexDirection:"column",borderStyle:"round",borderColor:e.amber,paddingX:1,children:[jsxs(Box,{gap:1,children:[jsx(Text,{color:e.amber,bold:true,children:" \u25C8 Agent Filter"}),jsxs(Text,{color:e.dim,children:[me," ",F,"/",n.length," selected"]})]}),jsx(Text,{color:e.ghost,children:Ve.repeat(36)}),V.map((P,j)=>{let L=j+H===x,N=C.size===0||C.has(P.id),E=l.get(P.id)??e.silver,W=r.get(P.id)??0;return jsxs(Box,{gap:0,children:[jsx(Text,{color:L?e.amber:e.ghost,children:L?" \u25B8 ":" "}),jsx(Text,{color:N?e.green:e.ghost,children:N?"[\u2713]":"[ ]"}),jsxs(Text,{color:L?E:N?e.silver:e.dim,bold:L,children:[" ",P.name]}),W>0&&jsxs(Text,{color:e.dim,children:[" ",me,W]})]},P.id)}),n.length>S&&jsxs(Text,{color:e.ghost,children:[" ",H>0?"\u2191":" "," ",H+S<n.length?"\u2193":" "," ",x+1,"/",n.length]}),jsx(Text,{color:e.ghost,children:Ve.repeat(36)}),jsxs(Text,{color:e.dim,children:[" Space toggle"," ",me," ","a all"," ",me," ","Enter confirm"," ",me," ","Esc cancel"]})]})});var Jl={system:"\u2666",lifecycle:"\u25B6",output:"\u2502",tool:"\u2699",result:"\u2190",error:"\u2715",file:"\u270E",info:"\u2502"},Ql={system:"System",lifecycle:"Lifecycle",output:"Output",tool:"Tool calls",result:"Results",error:"Errors",file:"Files",info:"Info"},ec={system:e.purple,lifecycle:e.cyan,output:e.white,tool:e.blue,result:e.green,error:e.red,file:e.purple,info:e.silver},wt=["system","lifecycle","output","tool","result","error","file","info"],ii=[{key:"1",label:"all",types:wt},{key:"2",label:"text",types:["output"]},{key:"3",label:"tools",types:["tool","result","file"]},{key:"4",label:"errors",types:["error"]},{key:"5",label:"events",types:["lifecycle","system"]}],ai=ao.memo(function({selected:n,typeCounts:o,onConfirm:r,onCancel:l}){let[p,b]=useState(0),[T,x]=useState(()=>new Set(n)),y=useMemo(()=>T.size===wt.length||wt.every(M=>T.has(M)),[T]);useInput((M,A)=>{if(A.upArrow){b(S=>S>0?S-1:wt.length-1);return}if(A.downArrow){b(S=>S<wt.length-1?S+1:0);return}if(M===" "){let S=wt[p];if(!S)return;x(H=>{let V=new Set(H);return V.has(S)?V.delete(S):V.add(S),V});return}if(M==="a"||M==="A"){x(S=>S.size===wt.length?new Set:new Set(wt));return}for(let S of ii)if(M===S.key){x(new Set(S.types));return}if(A.return){let S=T.size===0?new Set(wt):new Set(T);r(S);return}if(A.escape){l();return}});let C=y?wt.length:T.size;return jsxs(Box,{flexDirection:"column",borderStyle:"round",borderColor:e.amber,paddingX:1,children:[jsxs(Box,{gap:1,children:[jsx(Text,{color:e.amber,bold:true,children:" \u25C8 Type Filter"}),jsxs(Text,{color:e.dim,children:[me," ",C,"/",wt.length," selected"]})]}),jsx(Text,{color:e.ghost,children:Ve.repeat(36)}),wt.map((M,A)=>{let S=A===p,H=T.has(M),V=o[M]??0,F=ec[M];return jsxs(Box,{gap:0,children:[jsx(Text,{color:S?e.amber:e.ghost,children:S?" \u25B8 ":" "}),jsx(Text,{color:H?e.green:e.ghost,children:H?"[\u2713]":"[ ]"}),jsxs(Text,{color:S?F:e.dim,children:[" ",Jl[M]," "]}),jsx(Text,{color:S?F:H?e.silver:e.dim,bold:S,children:Ql[M]}),V>0&&jsxs(Text,{color:e.dim,children:[" ",me,V]})]},M)}),jsx(Text,{color:e.ghost,children:Ve.repeat(36)}),jsxs(Box,{gap:0,children:[jsx(Text,{color:e.dim,children:" "}),ii.map((M,A)=>jsxs(ao.Fragment,{children:[A>0&&jsxs(Text,{color:e.ghost,children:[" ",me," "]}),jsx(Text,{color:e.amberDim,children:M.key}),jsxs(Text,{color:e.dim,children:["=",M.label]})]},M.key))]}),jsxs(Text,{color:e.dim,children:[" Space toggle"," ",me," ","a all"," ",me," ","Enter confirm"," ",me," ","Esc cancel"]})]})});var zo="\u256D",Vo="\u256E",Ho="\u2570",jo="\u256F",Ie="\u2502";function nn({children:t,cw:n}){return jsxs(Text,{children:[jsx(Text,{color:e.ghost,children:Ie}),jsxs(Text,{children:[" ",t.padEnd(n)," "]}),jsx(Text,{color:e.ghost,children:Ie})]})}function Wo({cw:t}){return jsx(nn,{cw:t,children:""})}function li({width:t,height:n}){let o=Math.min(t-4,50),r=o-6,l=be(o-2);return jsxs(Box,{flexDirection:"column",paddingX:2,marginTop:1,children:[jsxs(Text,{color:e.ghost,children:[zo,l,Vo]}),jsx(nn,{cw:r,children:""}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.amber,children:Ht}),jsx(Text,{color:e.white,bold:true,children:" Welcome to Orch"}),jsx(Text,{children:" ".repeat(Math.max(0,r-15-2))}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsx(nn,{cw:r,children:""}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.silver,children:"Press N to create your first task".padEnd(r)}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsx(nn,{cw:r,children:""}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.amber,children:"N"}),jsx(Text,{color:e.gray,children:" new task"}),jsx(Text,{children:" ".repeat(Math.max(0,r-1-1-8))}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsx(nn,{cw:r,children:""}),jsxs(Text,{color:e.ghost,children:[Ho,l,jo]})]})}function ci({step:t,width:n}){let o=Math.min(n-4,50),r=o-6,l=be(o-2),p,b=null;if(t==="task_created")p="Press R to run task",b={key:"R",label:"run task"};else if(t==="run_started")p="Agent is running your task...";else return null;return jsxs(Box,{flexDirection:"column",paddingX:2,marginTop:1,children:[jsxs(Text,{color:e.ghost,children:[zo,l,Vo]}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.amber,children:Ht}),jsxs(Text,{color:e.silver,children:[" ",p.padEnd(b?r-2-b.key.length-1-b.label.length-2:r-2)]}),b&&jsxs(Fragment,{children:[jsxs(Text,{color:e.amber,children:[" ",b.key]}),jsxs(Text,{color:e.gray,children:[" ",b.label]})]}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsxs(Text,{color:e.ghost,children:[Ho,l,jo]})]})}function di({width:t}){let n=Math.min(t-4,50),o=n-6,r=be(n-2);return jsxs(Box,{flexDirection:"column",paddingX:2,marginTop:1,children:[jsxs(Text,{color:e.ghost,children:[zo,r,Vo]}),jsx(nn,{cw:o,children:""}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.green,bold:true,children:"First task completed!"}),jsx(Text,{children:" ".repeat(Math.max(0,o-21))}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsx(nn,{cw:o,children:""}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.silver,children:"Type / to see all commands".padEnd(o)}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsx(nn,{cw:o,children:""}),jsxs(Text,{color:e.ghost,children:[Ho,r,jo]})]})}function Uo({count:t,config:n,width:o}){if(t>=3)return null;let r=Math.min((o??44)-4,50),l=r-6,p=be(r-2),b=jsxs(Text,{color:e.ghost,children:[zo,p,Vo]}),T=jsxs(Text,{color:e.ghost,children:[Ho,p,jo]});if(t>0){let y=n.hints[0],C=y?` ${y.key} ${y.label}`:"";return jsxs(Box,{flexDirection:"column",paddingX:2,marginTop:1,children:[b,jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.amber,children:Ht}),jsxs(Text,{color:e.silver,children:[" ",n.nudge.padEnd(l-2-C.length)]}),y&&jsxs(Fragment,{children:[jsxs(Text,{color:e.amber,children:[" ",y.key]}),jsxs(Text,{color:e.gray,children:[" ",y.label]})]}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),T]})}let x=n.hints.reduce((y,C,M)=>y+C.key.length+1+C.label.length+(M>0?3:0),0);return jsxs(Box,{flexDirection:"column",paddingX:2,marginTop:1,children:[b,jsx(Wo,{cw:l}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.amber,children:Ht}),jsxs(Text,{color:e.white,bold:true,children:[" ",n.title]}),jsx(Text,{children:" ".repeat(Math.max(0,l-n.title.length-2))}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsx(Wo,{cw:l}),n.description.map((y,C)=>jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),jsx(Text,{color:e.silver,children:y.padEnd(l)}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]},C)),jsx(Wo,{cw:l}),jsxs(Text,{children:[jsxs(Text,{color:e.ghost,children:[Ie," "]}),n.hints.map((y,C)=>jsxs(ao.Fragment,{children:[C>0&&jsx(Text,{color:e.ghost,children:" "}),jsx(Text,{color:e.amber,children:y.key}),jsxs(Text,{color:e.gray,children:[" ",y.label]})]},C)),jsx(Text,{children:" ".repeat(Math.max(0,l-x))}),jsx(Text,{children:" "}),jsx(Text,{color:e.ghost,children:Ie})]}),jsx(Wo,{cw:l}),T]})}var nc=2,fi=360,oc={done:4e3,failed:8e3,review:6e3},rc={done:"\u2713",failed:"\u2715",review:Jt},sc={done:e.green,failed:e.red,review:e.blue},ic={done:e.successBg,failed:e.errorBg,review:e.infoBg};function ac(t){let n=t.agentName??"Agent";switch(t.type){case "done":return `Task completed by ${n}`;case "failed":return "Task failed \u2014 press Enter for details";case "review":return "Task ready for review \u2014 press A to approve"}}var lc=ao.memo(function({toast:n,onDismiss:o}){let[r,l]=useState(true),[p,b]=useState(false);useEffect(()=>{let S=setTimeout(()=>l(false),fi);return ()=>clearTimeout(S)},[]),useEffect(()=>{let S=oc[n.type],H=setTimeout(()=>b(true),S),V=setTimeout(()=>o(n.id),S+fi);return ()=>{clearTimeout(H),clearTimeout(V);}},[n.id,n.type,o]);let T=r||p,x=rc[n.type],y=sc[n.type],C=ic[n.type],M=ac(n),A=n.title.length>40?n.title.slice(0,39)+"\u2026":n.title;return jsx(Box,{children:jsxs(Text,{backgroundColor:C,children:[jsxs(Text,{color:T?e.dim:y,children:[" ",x," "]}),jsx(Text,{color:T?e.dim:e.white,bold:!T,children:A}),jsxs(Text,{color:T?e.dim:e.silver,children:[" ",M," "]})]})})}),xi=ao.memo(function({toasts:n,onDismiss:o}){let r=n.slice(0,nc);return r.length===0?null:jsx(Box,{flexDirection:"column",children:r.map(l=>jsx(lc,{toast:l,onDismiss:o},l.id))})});var uc="\u256D",gc="\u256E",mc="\u2570",fc="\u256F",ct="\u2502",Pr=[{key:"\u2191\u2193/j/k",label:"Navigate"},{key:"Tab/\u2190\u2192",label:"Switch tabs"},{key:"Enter",label:"Detail view"},{key:"G",label:"Goals tab"},{key:"T",label:"Tasks tab"},{key:"A",label:"Agents tab"},{key:"L",label:"Logs tab"}],Nr=[{key:"N",label:"New item"},{key:"E",label:"Edit"},{key:"D",label:"Delete"},{key:"R",label:"Run task"},{key:"S",label:"Show / Stop"},{key:"C",label:"Cancel"},{key:"A",label:"Approve"},{key:"X",label:"Reject"},{key:"U",label:"Autonomous"},{key:"Z",label:"Undo delete"}],Dr=[{key:"/",label:"Command mode"},{key:"/task add",label:"Create task"},{key:"/run",label:"Execute"},{key:"/watch",label:"Auto-dispatch"},{key:"/config",label:"Settings"},{key:"/help",label:"Help"},{key:"/quit",label:"Exit"}],Fn=10,Xt=22;function Fr(t){let n=Math.max(0,Math.floor((Xt-t.length-2)/2)),o=Math.max(0,Xt-n-t.length-2);return be(n)+" "+t+" "+be(o)}var bi=ao.memo(function({width:n,height:o}){let r=Xt*3+3+3+2,l=r+2,p=be(l-2),b="KEYBOARD SHORTCUTS",T=Math.max(0,Math.floor((r-b.length)/2)),x=Math.max(0,r-T-b.length),y="Press any key to dismiss",C=Math.max(0,Math.floor((r-y.length)/2)),M=Math.max(0,r-C-y.length),A=Math.max(Pr.length,Nr.length,Dr.length),S=A+10,H=Math.max(0,Math.floor((o-S)/2)),V=[];for(let L=0;L<A;L++){let N=L<Pr.length?Pr[L]:null,E=L<Nr.length?Nr[L]:null,W=L<Dr.length?Dr[L]:null;V.push(jsxs(Text,{children:[jsx(Text,{color:e.amber,children:ct}),jsx(Text,{children:" "}),N?jsxs(Fragment,{children:[jsx(Text,{color:e.amber,bold:true,children:N.key.padEnd(Fn)}),jsx(Text,{color:e.silver,children:N.label.padEnd(Xt-Fn)})]}):jsx(Text,{children:" ".repeat(Xt)}),jsxs(Text,{color:e.dim,children:[" ",ct," "]}),E?jsxs(Fragment,{children:[jsx(Text,{color:e.amber,bold:true,children:E.key.padEnd(Fn)}),jsx(Text,{color:e.silver,children:E.label.padEnd(Xt-Fn)})]}):jsx(Text,{children:" ".repeat(Xt)}),jsxs(Text,{color:e.dim,children:[" ",ct," "]}),W?jsxs(Fragment,{children:[jsx(Text,{color:e.amber,bold:true,children:W.key.padEnd(Fn)}),jsx(Text,{color:e.silver,children:W.label.padEnd(Xt-Fn)})]}):jsx(Text,{children:" ".repeat(Xt)}),jsx(Text,{children:" "}),jsx(Text,{color:e.amber,children:ct})]},`r${L}`));}let F=L=>jsxs(Text,{children:[jsx(Text,{color:e.amber,children:ct}),jsx(Text,{children:" ".repeat(r)}),jsx(Text,{color:e.amber,children:ct})]},L),P=Fr("NAVIGATION"),j=Fr("ACTIONS"),O=Fr("COMMANDS");return jsxs(Box,{flexDirection:"column",paddingX:Math.max(0,Math.floor((n-l)/2)),marginTop:H,children:[jsxs(Text,{color:e.amber,children:[uc,p,gc]}),F("e1"),jsxs(Text,{children:[jsx(Text,{color:e.amber,children:ct}),jsx(Text,{children:" ".repeat(T)}),jsx(Text,{color:e.amber,bold:true,children:b}),jsx(Text,{children:" ".repeat(x)}),jsx(Text,{color:e.amber,children:ct})]}),F("e2"),jsxs(Text,{children:[jsx(Text,{color:e.amber,children:ct}),jsx(Text,{children:" "}),jsx(Text,{color:e.dim,children:P}),jsxs(Text,{color:e.dim,children:[" ",ct," "]}),jsx(Text,{color:e.dim,children:j}),jsxs(Text,{color:e.dim,children:[" ",ct," "]}),jsx(Text,{color:e.dim,children:O}),jsx(Text,{children:" "}),jsx(Text,{color:e.amber,children:ct})]}),F("e3"),V,F("e4"),jsxs(Text,{children:[jsx(Text,{color:e.amber,children:ct}),jsx(Text,{children:" ".repeat(C)}),jsx(Text,{color:e.dim,children:y}),jsx(Text,{children:" ".repeat(M)}),jsx(Text,{color:e.amber,children:ct})]}),F("e5"),jsxs(Text,{color:e.amber,children:[mc,p,fc]})]})});var wi=[{value:"claude-opus-4-6",label:"Claude Opus 4.6",hint:"most capable"},{value:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",hint:"fast, balanced"},{value:"claude-haiku-4-6",label:"Claude Haiku 4.6",hint:"fastest, cheapest"},{value:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",hint:"extended thinking"},{value:"claude-haiku-4-5-20251001",label:"Claude Haiku 4.5",hint:"legacy"}],Si=[{value:"gpt-5.3-codex",label:"GPT-5.3 Codex",hint:"default, balanced"},{value:"gpt-5.4",label:"GPT-5.4",hint:"latest"},{value:"gpt-5",label:"GPT-5",hint:"capable"},{value:"gpt-5.3-codex-spark",label:"GPT-5.3 Codex Spark",hint:"fast"},{value:"o3",label:"o3",hint:"reasoning"},{value:"o4-mini",label:"o4-mini",hint:"fast reasoning"},{value:"gpt-5-mini",label:"GPT-5 Mini",hint:"light"},{value:"gpt-5-nano",label:"GPT-5 Nano",hint:"cheapest"},{value:"codex-mini-latest",label:"Codex Mini",hint:"legacy"}],ki=[{value:"auto",label:"Auto",hint:"let Cursor decide"},{value:"composer-1.5",label:"Composer 1.5",hint:"latest agent"},{value:"composer-1",label:"Composer 1",hint:"stable agent"},{value:"gpt-5.3-codex",label:"GPT-5.3 Codex",hint:"OpenAI"},{value:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",hint:"Anthropic"}],Ci=[{value:"",label:"Default",hint:"use model configured in opencode"},{value:"openrouter/anthropic/claude-sonnet-4.6",label:"Claude Sonnet 4.6",hint:"fast, balanced"},{value:"openrouter/anthropic/claude-opus-4.6",label:"Claude Opus 4.6",hint:"most capable"},{value:"openrouter/google/gemini-2.5-pro",label:"Gemini 2.5 Pro",hint:"Google"},{value:"openrouter/google/gemini-2.5-flash",label:"Gemini 2.5 Flash",hint:"Google, fast"},{value:"openrouter/deepseek/deepseek-v3.2",label:"DeepSeek V3.2",hint:"open-source"},{value:"openrouter/deepseek/deepseek-r1:free",label:"DeepSeek R1",hint:"reasoning, free"},{value:"opencode/big-pickle",label:"Big Pickle",hint:"opencode native"}],Ii=[{value:"",label:"Default",hint:"use shell adapter default"}],Mi=[{value:"",label:"Default",hint:"no override \u2014 use model default"},{value:"high",label:"High",hint:"deepest reasoning, best quality, slowest"},{value:"medium",label:"Medium",hint:"balanced speed and quality"},{value:"low",label:"Low",hint:"fastest responses, minimal reasoning"}],vi=new Set(["claude"]),pc=[{value:"claude",label:"Claude",hint:"Claude Code CLI"},{value:"opencode",label:"OpenCode",hint:"OpenCode \u2014 multi-provider"},{value:"codex",label:"Codex",hint:"OpenAI Codex CLI"},{value:"cursor",label:"Cursor",hint:"Cursor Agent CLI"},{value:"shell",label:"Shell",hint:"custom shell command"}],_i=[{value:"1",label:"P1 Critical",hint:"urgent, do first"},{value:"2",label:"P2 High",hint:"important"},{value:"3",label:"P3 Medium",hint:"default priority"},{value:"4",label:"P4 Low",hint:"nice to have"}],Ti=60;function Ri(t){return t.filter(n=>n.status!=="disabled").map(n=>{let o=(n.role??"").split(`
11
- `)[0].trim(),r=o.length>Ti?o.slice(0,Ti-1)+"\u2026":o,l=r?`[${n.adapter}] ${r}`:n.adapter;return {value:n.id,label:n.name,hint:l}})}function Ko(t,n="Auto-assign",o="orchestrator picks the best agent"){return [{value:"",label:n,hint:o},...Ri(t)]}var Wr=[{value:"",label:"Skip",hint:"no role description"},{value:"Full-stack developer",label:"Full-stack developer",hint:"general purpose"},{value:"Frontend developer",label:"Frontend developer",hint:"React, CSS, UI"},{value:"Backend developer",label:"Backend developer",hint:"APIs, databases, services"},{value:"DevOps engineer",label:"DevOps engineer",hint:"CI/CD, infra, deploys"},{value:"QA / Test engineer",label:"QA / Test engineer",hint:"testing, quality"},{value:"Code reviewer",label:"Code reviewer",hint:"review PRs, find bugs"},{value:"Technical writer",label:"Technical writer",hint:"docs, READMEs"},{value:"__custom__",label:"Custom...",hint:"type your own"}];function Ai(t){return [{value:"",label:"None",hint:"no team"},...(t??[]).filter(n=>n.status==="active").map(n=>({value:n.id,label:n.name,hint:`${n.members.length} members`}))]}function $i(){return [{id:"shop_template",label:"Agent Shop \u2014 choose a template",type:"select",options:a$2.map(t=>({value:t.key,label:t.name,hint:t.description}))}]}function zr(t,n){return t.map(o=>{switch(o.id){case "name":return {...o,defaultValue:n.name};case "adapter":return {...o,defaultValue:n.adapter};case "model":return {...o,defaultValue:n.model};case "role":return {...o,defaultValue:"__custom__"};case "role_custom":return {...o,defaultValue:n.role,skip:void 0};case "skills":return {...o,defaultValue:n.skills.join(", ")};case "approval_policy":return {...o,defaultValue:n.approval_policy};default:return o}})}function Yo(t,n){let o=Ai(n);return [{id:"name",label:"Agent name",type:"text",placeholder:"e.g. alpha, frontend-bot, reviewer",required:true,validate:r=>r.trim()?t?.some(l=>l.name===r.trim())?"Agent with this name already exists":null:"Name is required",suggestions:a$2.map(r=>({value:r.key,label:r.name,hint:r.description}))},{id:"adapter",label:"Provider",type:"select",options:pc},{id:"model",label:"Model",type:"select",getOptions:r=>r.adapter==="opencode"?Ci:r.adapter==="codex"?Si:r.adapter==="cursor"?ki:r.adapter==="shell"?Ii:wi},{id:"effort",label:"Reasoning effort",type:"select",options:Mi,skip:r=>!vi.has(r.adapter??"")},{id:"role",label:"Role / specialization",type:"select",options:Wr},{id:"role_custom",label:"Describe the role",type:"textarea",placeholder:"e.g. Specialist in React and TypeScript",skip:r=>r.role!=="__custom__"},{id:"skills",label:"Skills (comma-separated)",type:"text",placeholder:"e.g. feature-dev:feature-dev, testing-suite:generate-tests"},{id:"approval_policy",label:"Approval policy",type:"text",skip:()=>true},{id:"team",label:"Join team",type:"select",options:o,skip:()=>o.length<=1}]}function Bi(t){let n=t.role==="__custom__"?t.role_custom||void 0:t.role||void 0,o=t.skills?t.skills.split(",").map(p=>p.trim()).filter(Boolean):void 0,r=t.approval_policy||"auto",l=t.effort||void 0;return {name:t.name,adapter:t.adapter||"claude",role:n,model:t.model||void 0,effort:l,approval_policy:r,skills:o,team_id:t.team||void 0}}function Ei(t,n){let o=Ri(t);return [{id:"name",label:"Team name",type:"text",placeholder:"e.g. frontend, backend, qa",required:true,validate:r=>r.trim()?n?.some(l=>l.name===r.trim())?"Team with this name already exists":null:"Name is required"},{id:"lead",label:"Team lead",type:"select",options:o},{id:"members",label:"Team members",type:"multiselect",getOptions:r=>o.filter(l=>l.value!==r.lead),skip:r=>!o.some(l=>l.value!==r.lead)},{id:"description",label:"Description",type:"textarea",placeholder:"Optional team purpose..."}]}function Oi(t){let n=t.members?t.members.split(",").filter(Boolean):[];return {name:t.name,lead_agent_id:t.lead,member_agent_ids:n.length>0?n:void 0,description:t.description||void 0}}function Li(t){let n=Ko(t);return [{id:"title",label:"Task title",type:"text",placeholder:"What needs to be done?",required:true,validate:o=>o.trim()?null:"Title is required"},{id:"priority",label:"Priority",type:"select",options:_i,defaultValue:"3",validate:o=>{let r=Number(o);return !Number.isInteger(r)||r<1||r>4?"Priority must be 1-4":null}},{id:"assignee",label:"Assignee",type:"select",options:n,skip:()=>n.length<=1},{id:"description",label:"Description",type:"textarea",placeholder:"Optional details, context, acceptance criteria..."}]}function Pi(t){return {title:t.title,priority:t.priority?parseInt(t.priority,10):void 0,assignee:t.assignee||void 0,description:t.description||void 0}}function Ni(t,n){let o=Ko(n,"None / Auto","remove assignee");return [{id:"title",label:"Task title",type:"text",defaultValue:t.title,required:true,validate:r=>r.trim()?null:"Title is required"},{id:"priority",label:"Priority",type:"select",options:_i,defaultValue:String(t.priority),validate:r=>{let l=Number(r);return !Number.isInteger(l)||l<1||l>4?"Priority must be 1-4":null}},{id:"assignee",label:"Assignee",type:"select",options:o,defaultValue:t.assignee??"",skip:()=>o.length<=1},{id:"description",label:"Description",type:"textarea",defaultValue:t.description||"",placeholder:"Optional details..."}]}function Di(t){return {title:t.title,priority:t.priority?parseInt(t.priority,10):void 0,assignee:t.assignee||void 0,description:t.description??""}}function Fi(t,n,o){let r=Wr.find(x=>x.value===t.role),l=r?t.role:t.role?"__custom__":"",p=t.adapter==="opencode"?Ci:t.adapter==="codex"?Si:t.adapter==="cursor"?ki:t.adapter==="shell"?Ii:wi,b=Ai(o),T=o?.find(x=>x.members.some(y=>y.agent_id===t.id))?.id;return [{id:"name",label:"Agent name",type:"text",defaultValue:t.name,required:true,validate:x=>x.trim()?n?.some(y=>y.id!==t.id&&y.name===x.trim())?"Agent with this name already exists":null:"Name is required"},{id:"model",label:"Model",type:"select",options:p,defaultValue:t.config.model??""},{id:"effort",label:"Reasoning effort",type:"select",options:Mi,defaultValue:t.config.effort??"",skip:()=>!vi.has(t.adapter)},{id:"role",label:"Role / specialization",type:"select",options:Wr,defaultValue:l},{id:"role_custom",label:"Describe the role",type:"textarea",defaultValue:t.role&&!r?t.role:"",placeholder:"e.g. Specialist in React and TypeScript",skip:x=>x.role!=="__custom__"},{id:"team",label:"Team",type:"select",options:b,defaultValue:T??"",skip:()=>b.length<=1}]}var hc=[{value:"1",label:"1 agent",hint:"~0.5 GB RAM, 1 subprocess"},{value:"2",label:"2 agents",hint:"~1 GB RAM, 2 subprocesses"},{value:"3",label:"3 agents",hint:"~1.5 GB RAM, 3 subprocesses"},{value:"4",label:"4 agents",hint:"~2 GB RAM, 4 subprocesses"},{value:"6",label:"6 agents",hint:"~3 GB RAM, 6 subprocesses"},{value:"8",label:"8 agents",hint:"~4 GB RAM, 8 subprocesses"},{value:"10",label:"10 agents",hint:"~5 GB RAM, 10 subprocesses"}],xc=[{value:"all",label:"All",hint:"show everything"},{value:"text",label:"Text",hint:"agent output only"},{value:"tools",label:"Tools",hint:"tool calls, results, files"},{value:"errors",label:"Errors",hint:"errors only"},{value:"events",label:"Events",hint:"lifecycle, system events"}],yi=[{value:"true",label:"On"},{value:"false",label:"Off"}];function Gi(t,n,o){let r=o??{toast:true,bell:false};return [{id:"activity_filter",label:"Activity filter preset",type:"select",options:xc,defaultValue:t},{id:"max_concurrent",label:"Max concurrent agents",type:"select",options:hc,defaultValue:String(n)},{id:"notifications_toast",label:"Toast notifications",type:"select",options:yi,defaultValue:String(r.toast)},{id:"notifications_bell",label:"Bell on completion",type:"select",options:yi,defaultValue:String(r.bell)}]}function Wi(t){let n=t.role==="__custom__"?t.role_custom||void 0:t.role||void 0,o=t.effort||void 0;return {name:t.name,role:n,model:t.model||void 0,effort:o,team_id:t.team||void 0}}function Zo(t){let n=Ko(t,"Any agent","auto-assign to autonomous agents");return [{id:"title",label:"Goal title",type:"text",placeholder:'e.g. "Implement OAuth2 login with Google and GitHub"',description:"Be specific \u2014 agents work better with clear, measurable objectives",required:true,validate:o=>o.trim()?null:"Title is required"},{id:"assignee",label:"Assignee",type:"select",description:"Assigned agent gets autonomous mode \u2014 it will plan and execute without prompts",options:n,skip:()=>n.length<=1},{id:"description",label:"Description",type:"textarea",placeholder:"Success criteria, constraints, technical context...",description:'Context matters \u2014 include tech stack, constraints, and what "done" looks like'}]}function zi(t){return {title:t.title,assignee:t.assignee||void 0,description:t.description||void 0}}function Vi(t,n){let o=Ko(n,"Any agent","auto-assign");return [{id:"title",label:"Goal title",type:"text",defaultValue:t.title,description:"Be specific \u2014 agents work better with clear, measurable objectives",required:true,validate:r=>r.trim()?null:"Title is required"},{id:"assignee",label:"Assignee",type:"select",description:"Assigned agent gets autonomous mode \u2014 it will plan and execute without prompts",options:o,defaultValue:t.assignee??"",skip:()=>o.length<=1},{id:"description",label:"Description",type:"textarea",defaultValue:t.description||"",placeholder:"Success criteria, constraints, technical context...",description:'Context matters \u2014 include tech stack, constraints, and what "done" looks like'}]}function Hi(t){return {title:t.title,assignee:t.assignee||void 0,description:t.description??""}}var ji=10,Ui=500,nr=2048,hn=500,Xi=5,Vr=new Set(["todo","failed","cancelled"]),wc={title:"Goals",description:["Define what your team should achieve.","The orchestrator breaks goals into tasks","and assigns them to agents automatically."],hints:[{key:"N",label:"new goal"},{key:"/",label:"commands"}],nudge:"Add more goals to keep your team focused."},Sc={title:"Tasks",description:["Units of work dispatched to agents.","Create them manually or let goals","generate them automatically."],hints:[{key:"N",label:"new task"},{key:"W",label:"start orchestrator"}],nudge:"Add more tasks to keep agents busy."},kc={title:"Agents",description:["AI workers that execute your tasks.","Each agent uses an adapter (claude, codex,","cursor, shell) and has its own role."],hints:[{key:"N",label:"new agent"},{key:"W",label:"start orchestrator"}],nudge:"Add more agents to increase parallelism."},qi=5e3,Yi=0;function og(){Yi=0;}var Zi=/^\[[\w_]+\]$/;function Ji(t){return Zi.test(t)?{msgType:"lifecycle",color:e.dim}:t.startsWith("\u2699")?{msgType:"tool",color:e.dim}:t.startsWith("\u2190")?{msgType:"result",color:e.dim}:t.startsWith("\u2713")?{msgType:"lifecycle",color:e.dim}:t.startsWith("\u23F3")?{msgType:"info",color:e.silver}:{msgType:"output",color:e.silver}}var Ur=["#5faf87","#5fafd7","#af87ff","#d7af00","#5fd7d7","#d787af","#afaf5f","#d7875f"],Cc=" ".repeat(9),or={system:"\u2666",lifecycle:"\u25B6",output:"\u2502",tool:"\u2699",result:"\u2190",error:"\u2715",file:"\u270E",info:"\u2502"},er=["system","lifecycle","output","tool","result","error","file","info"],Gn=[{label:"all",types:er},{label:"text",types:["output"]},{label:"tools",types:["tool","result","file"]},{label:"errors",types:["error"]},{label:"events",types:["lifecycle","system"]}];function Hr(t){let o=(Gn.findIndex(r=>r.types.length===t.size&&r.types.every(l=>t.has(l)))+1)%Gn.length;return Gn[o]}function jr(t,n){if(t.length!==n.length)return true;for(let o=0;o<t.length;o++)if(t[o].id!==n[o].id||t[o].updated_at!==n[o].updated_at)return true;return false}function rg({projectName:t,tasks:n,agents:o=[],state:r,onRunTask:l,onCreateTask:p,onCancelTask:b$1,onRetryTask:T,onAssignTask:x,onRunAll:y,onDisableAgent:C,onEnableAgent:M,onSubscribeEvents:A,onRefreshTasks:S,onRefreshAgents:H,onRefreshState:V,onLoadHistory:F,onAddAgent:P,onDeleteAgent:j,onApproveTask:O,onRejectTask:L,onDeleteTask:N,onUpdateTask:E,onUpdateAgent:W,onForceStopAgent:z,onCreateTeam:X,onListTeams:_,onJoinTeam:ae,onLeaveTeam:Ee,onDisbandTeam:Ft,onSetTeamLead:dt,onStartWatch:Re,onStopWatch:Ke,onToggleAutonomous:ut,onRefreshGoals:pt,onCreateGoal:De,onUpdateGoal:Ye,onUpdateGoalStatus:gt,onDeleteGoal:Ze,onGetGoalProgress:on,onCompleteOnboarding:Ce,initialWatchActive:ht,observerMode:xt,watchError:qt,messageBatchMs:mt=process.env.VITEST?0:80,initialActivityFilter:kt="all",onSaveActivityFilter:Ue,initialMaxConcurrent:go=a.scheduling.max_concurrent_agents,onSaveMaxConcurrent:Wn,initialNotifications:Rt,onSaveNotifications:Gt,version:Wt,latestVersion:zt,onCheckUpdate:rn,onBackgroundInstall:sn}){let{exit:nt}=useApp(),{stdout:At}=useStdout(),[xn,zn]=useState(zt),Kt=useRef(rn);useEffect(()=>{if(zt||!Kt.current)return;let i=setTimeout(()=>{Kt.current?.().then(f=>{f&&zn(f);}).catch(()=>{});},5e3);return ()=>clearTimeout(i)},[zt]);let[bn,$]=useState(false),I=useRef(false);useEffect(()=>{!xn||!sn||I.current||bn||(I.current=true,sn(xn).then(i=>{i&&$(true);}).catch(()=>{}));},[xn,sn,bn]);let[k,B]=useState({w:At?.columns??80,h:At?.rows??24});useEffect(()=>{if(!At)return;let i=()=>B({w:At.columns,h:At.rows});return At.on("resize",i),()=>{At.off("resize",i);}},[At]);let q=k.w,te=k.h,[le,de]=useState(n),[K,Ae]=useState(o),[we,Vn]=useState(r),[Tn,rr]=useState(ht??!!r.pid),[Hn,Xr]=useState([]),[ra,qr]=useState(void 0),[Yt,mo]=useState(()=>r.onboardingCompleted||(r.stats?.total_tasks_completed??0)>0?"dismissed":Object.keys(r.running??{}).length>0?"run_started":n.length>0?"task_created":"welcome");useEffect(()=>{if(Yt!=="completed")return;let i=setTimeout(()=>{mo("dismissed"),Ce?.().catch(()=>{});},5e3);return ()=>clearTimeout(i)},[Yt,Ce]);let[R,yn]=useState("tasks"),[fo,jn]=useState(0),[sr,Kr]=useState(0),[ir,Yr]=useState(0),[$e,Un]=useState(false),[ze,Zr]=useState([]),[Fe,Oe]=useState("none"),[an,Ct]=useState(""),[bt,Je]=useState(null),[ln,Xn]=useState([]),[$t,ar]=useState(false),[Jr,sa]=useState(()=>new Set),[wn,lr]=useState(false),[qn,cr]=useState(false),[Qr,es]=useState(()=>new Set(er)),[Kn,dr]=useState(-1),[ia,Yn]=useState(0),[Sn,ur]=useState(()=>{let i=Gn.find(f=>f.label===kt);return new Set(i?.types??er)}),po=useMemo(()=>Gn.find(f=>f.types.length===Sn.size&&f.types.every(s=>Sn.has(s)))?.label??"all",[Sn]),gr=useMemo(()=>Sn.size>=er.length?ze:ze.filter(i=>Sn.has(i.msgType??"info")),[ze,Sn]),[ts,aa]=useState(go),[ho,la]=useState(Rt??{toast:true,bell:false}),[ca,ns]=useState([]),da=useRef(0),[mr,os]=useState(),rs=useRef(R);rs.current=R;let ss=useRef(le);ss.current=le;let is=useRef(K);is.current=K;let xo=useRef(ho);xo.current=ho;let bo=useCallback((i,f)=>{if(!xo.current.toast)return;let s=ss.current.find(h=>h.id===f),d=s?.title??f,g=s?.assignee?is.current.find(h=>h.id===s.assignee):void 0;ns(h=>{let u=[...h,{id:`toast_${da.current++}`,type:i,title:d,agentName:g?.name,ts:Date.now()}];return u.length>Xi?u.slice(u.length-Xi):u}),xo.current.bell&&(i==="failed"||i==="review")&&process.stdout.write("\x07");},[]),ua=useCallback(i=>{ns(f=>f.filter(s=>s.id!==i));},[]),To=ao.useRef(new No).current,[ga,kn]=useState(0),[as,ls]=useState(false),[Zn,ma]=useState(false),[fa,fr]=useState(0),[pa,pr]=useState(0),[hr,Cn]=useState(0),[yo,xr]=useState(false),[ha,Jn]=useState(0),[wo,Zt]=useState(0),[Vt,cs]=useState([]),[In,br]=useState([]),Mn=useRef(Vt);Mn.current=Vt;let ds=useRef(0),Z=useCallback(async i=>{ds.current=Date.now();let[f,s,d,g,h]=await Promise.all([S?.()??Promise.resolve(le),H?.()??Promise.resolve(K),V?.()??Promise.resolve(we),i?.includeTeams?_?.()??Promise.resolve(Mn.current):Promise.resolve(null),pt?.()??Promise.resolve(Hn)]);de(u=>jr(u,f)?f:u),Ae(u=>jr(u,s)?s:u),Vn(d),g!==null&&cs(g),Xr(u=>jr(u,h)?h:u),ht&&rr(!!d.pid);},[S,H,V,_,pt,ht]),vn=useMemo(()=>{let i=new Map;for(let f of Hn)i.set(f.id,f);return i},[Hn]),Le=useMemo(()=>{let i=[...le].sort((h,u)=>(ro[h.status]??9)-(ro[u.status]??9));if(!Zn)return i;let f=[],s=[],d=[],g=new Map;for(let h of i)h.goalId&&vn.has(h.goalId)?(g.has(h.goalId)||(d.push(h.goalId),g.set(h.goalId,[])),g.get(h.goalId).push(h)):s.push(h);for(let h of d)f.push(...g.get(h));return [...f,...s]},[le,Zn,vn]),Bt=as?Le:Le.slice(0,ji),_n=Le.length-Bt.length,U=Le[fo],Qn=useMemo(()=>{let i=new Map;for(let f of le)i.set(f.id,f.title);return i},[le]),cn=useMemo(()=>{let i=new Map;for(let f of K)i.set(f.id,f.name);return i},[K]),xa=useMemo(()=>{let i=new Map;for(let f of le)if(f.goalId){let s=i.get(f.goalId);s||(s=[],i.set(f.goalId,s)),s.push(f);}return i},[le]),So=useMemo(()=>{let i=new Map;for(let f=0;f<K.length;f++)i.set(K[f].id,Ur[f%Ur.length]);return i},[K]),us=useMemo(()=>{let i=new Map;for(let f of ze)f.agentId&&i.set(f.agentId,(i.get(f.agentId)??0)+1);return i},[ze]),ba=useMemo(()=>{let i={};for(let f of ze){let s=f.msgType??"info";i[s]=(i[s]??0)+1;}return i},[ze]),{agentTeamMap:Rn,activeTeamCount:eo,teamLeadSet:Ta}=useMemo(()=>{let i=new Map,f=new Set,s=0;for(let d of Vt)if(d.status==="active"){s++,f.add(d.lead_agent_id);for(let g of d.members)i.set(g.agent_id,d.name);}return {agentTeamMap:i,activeTeamCount:s,teamLeadSet:f}},[Vt]),Ge=useMemo(()=>{let i=[...K];return i.sort((f,s)=>{let d=Rn.get(f.id),g=Rn.get(s.id);return d&&!g?-1:!d&&g?1:d&&g&&d!==g?d.localeCompare(g):(_r[f.status]??9)-(_r[s.status]??9)}),i},[K,Rn]),Q=Ge[sr],ft=useMemo(()=>[...Hn].sort((i,f)=>(c[i.status]??9)-(c[f.status]??9)),[Hn]),oe=ft[ir],ya=useMemo(()=>oe?le.filter(i=>i.goalId===oe.id):[],[oe,le]),Tr=useRef(on);Tr.current=on,useEffect(()=>{if(!oe||!Tr.current){qr(void 0);return}let i=false;return Tr.current(oe.id).then(f=>{i||qr(f);}).catch(()=>{}),()=>{i=true;}},[oe?.id]);let dn=useRef(new Map),ko=useRef(new Map);useEffect(()=>{for(let[i,f]of Object.entries(we.running))dn.current.set(f.run_id,f.agent_id),ko.current.set(f.run_id,i);if(dn.current.size>Ui){let i=dn.current.size-Ui,f=0;for(let s of dn.current.keys()){if(f++>=i)break;dn.current.delete(s),ko.current.delete(s);}}},[we.running]);let un=useRef([]),to=useRef(null),yr=useCallback(()=>{if(to.current=null,un.current.length===0)return;let i=un.current;un.current=[],Zr(f=>{if(i.length>=hn)return i.slice(-hn);let s=hn-i.length;return (f.length>s?f.slice(-s):f).concat(i)});},[]);useEffect(()=>()=>{to.current&&clearTimeout(to.current);},[]);let a=useCallback((i,f,s)=>{let d=new Date,g=d.toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"}),h=s?.detail&&s.detail.length>nr?s.detail.slice(0,nr)+"\u2026[truncated]":s?.detail;un.current.push({text:i,color:f,time:g,ts:d.getTime(),...s,detail:h}),un.current.length>hn&&(un.current=un.current.slice(-hn)),mt===0?yr():to.current||(to.current=setTimeout(yr,mt));},[yr]);useEffect(()=>{xt?a("Observer mode: watching external orchestrator via disk polling.",e.amber):qt&&a(`Watch mode failed: ${qt}. Tasks will not auto-dispatch.`,e.red);},[]),useEffect(()=>{let i=xt?3e3:5e3,f=setInterval(()=>{Date.now()-ds.current>=i&&Z().catch(()=>{});},i);return ()=>clearInterval(f)},[xt,Z]);let An=useCallback((i,f,s,d)=>{let g={key:++Yi,entityType:i,entityId:f,entityName:s,expiresAt:Date.now()+qi,needsForceStop:d?.needsForceStop};br(h=>[...h,g]),a(`\u2717 "${s}" will be deleted in ${Math.round(qi/1e3)}s \u2014 press Z to undo`,e.yellow);},[a]),wa=useCallback(()=>{br(i=>{if(i.length===0)return i;let f=i[i.length-1];return a(`\u21B6 Undo: "${f.entityName}" restored`,e.green),i.slice(0,-1)});},[a]),gs=useCallback(async i=>{try{i.entityType==="task"&&N?await N(i.entityId):i.entityType==="agent"?(i.needsForceStop&&z&&await z(i.entityId),j&&await j(i.entityId)):i.entityType==="goal"&&Ze&&await Ze(i.entityId),a(`\u2713 Deleted "${i.entityName}"`,e.green),Z();}catch(f){a(`Failed to delete "${i.entityName}": ${f instanceof Error?f.message:String(f)}`,e.red);}},[N,j,Ze,z,a,Z]),ms=useRef(gs);ms.current=gs,useEffect(()=>{if(In.length===0)return;let i=setInterval(()=>{let f=Date.now(),s=[];br(d=>{let g=d.filter(h=>h.expiresAt<=f?(s.push(h),false):true);return s.length>0?g:d});for(let d of s)ms.current(d);},1e3);return ()=>clearInterval(i)},[In.length>0]),useEffect(()=>{if(!F)return;let i=f=>{let s=new Date(f.timestamp).toLocaleTimeString("en-US",{hour12:false,hour:"2-digit",minute:"2-digit",second:"2-digit"}),d=typeof f.data=="string"?f.data:JSON.stringify(f.data),g,h=e.silver,u="output";if(f.type==="error")g=typeof f.data=="string"?f.data:JSON.stringify(f.data),g=g.slice(0,200),h=e.red,u="error";else if(f.type==="file_changed")g=String(f.data),h=e.purple,u="file";else if(f.type==="done")g="Completed",h=e.green,u="lifecycle";else if(f.type==="tool_call")g=`\u2699 ${f.data?.name??"tool"}()`,h=e.cyan,u="tool";else {let{summary:w}=oa(d);if(!w)return null;g=w;let J=Ji(g);u=J.msgType,h=J.color;}return {text:g,color:h,time:s,ts:new Date(f.timestamp).getTime(),agentId:f.agentId,taskId:f.taskId,msgType:u}};F(f=>{if(f.length===0)return;let s=f.map(i).filter(d=>d!==null);Zr(d=>{let g=[...s,...d];return g.length>hn?g.slice(-hn):g});}).catch(f=>{process.stderr.write(`[TUI] onLoadHistory error: ${f instanceof Error?f.stack??f.message:String(f)}
12
- `);});},[]),useEffect(()=>{_?.().then(cs).catch(()=>{}),pt?.().then(Xr).catch(()=>{});},[]);let Co=useCallback(()=>{Je({title:"NEW AGENT",steps:Yo(K,Mn.current),kind:"agent"}),Oe("wizard");},[K]),fs=useCallback(()=>{Je({title:"AGENT SHOP",steps:$i(),kind:"agent_shop"}),Oe("wizard");},[]),Io=useCallback(()=>{Xn([]),Je({title:"NEW TASK",steps:Li(K),kind:"task"}),Oe("wizard");},[K]),Sa=useCallback(async()=>{try{let{detectClipboardType:i,getClipboardImage:f}=await import('./clipboard-service-WVON5ZN4.js'),s=await i();if(s!=="image")return a(s==="text"?"Clipboard has text, not image":"Clipboard is empty",e.dim),s;let d=await f();if(!d)return a("Failed to read clipboard image",e.red),"empty";let{mkdtemp:g,writeFile:h}=await import('fs/promises'),{tmpdir:u}=await import('os'),{join:w}=await import('path'),J=await g(w(u(),"orch-paste-")),Ot=w(J,`clipboard-${Date.now()}.${d.ext}`);return await h(Ot,d.data),Xn(gn=>[...gn,Ot]),a(`\u{1F4CE} Image attached (${Math.round(d.data.length/1024)}KB)`,e.green),"image"}catch{return a("Clipboard paste failed",e.red),"empty"}},[a]),ka=useCallback(i=>{Je({title:"EDIT TASK",steps:Ni(i,K),kind:"edit_task",targetId:i.id}),Oe("wizard");},[K]),ps=useCallback(()=>{Je({title:"NEW TEAM",steps:Ei(K,Vt),kind:"team"}),Oe("wizard");},[K]),Ca=useCallback(i=>{Je({title:"EDIT AGENT",steps:Fi(i,K,Vt),kind:"edit_agent",targetId:i.id}),Oe("wizard");},[Vt]),hs=useCallback(()=>{Je({title:"SETTINGS",steps:Gi(po,ts,ho),kind:"config"}),Oe("wizard");},[po,ts]),Ia=useCallback(i=>{Oe("none");let f=bt?.kind,s=bt?.targetId;if(Je(null),f==="agent_shop"){let d=i.shop_template,g=d?b(d):void 0;if(g){let h=Yo(K,Mn.current),u=zr(h,g);Je({title:`NEW AGENT \u2014 ${g.name}`,steps:u,kind:"agent_from_shop"}),Oe("wizard");}else a("No template selected",e.yellow);return}if((f==="agent"||f==="agent_from_shop")&&P){let d=Bi(i);a(`Creating agent "${d.name}"...`,e.amber),P(d.name,d.adapter,{model:d.model,effort:d.effort,role:d.role,approval_policy:d.approval_policy,skills:d.skills}).then(g=>{a(`\u2713 Created agent "${g.name}" (${g.id}, ${g.adapter})`,e.green),d.team_id&&ae?ae(d.team_id,g.id).then(h=>{a(`\u2713 Joined team "${h.name}"`,e.green),Z({includeTeams:true});},h=>a(`Failed to join team: ${h instanceof Error?h.message:String(h)}`,e.red)):Z();},g=>a(`Failed: ${g instanceof Error?g.message:String(g)}`,e.red));}else if(f==="team"&&X){let d=Oi(i);a(`Creating team "${d.name}"...`,e.amber),X(d).then(g=>{a(`\u2713 Created team "${g.name}" (${g.id}, ${g.members.length} members)`,e.green),Z({includeTeams:true});},g=>a(`Failed: ${g instanceof Error?g.message:String(g)}`,e.red));}else if(f==="task"&&p){let d=Pi(i),g=ln.length>0?[...ln]:void 0;Xn([]),a(`Creating "${d.title}"...`,e.amber),p(d.title,{priority:d.priority,description:d.description,attachments:g}).then(h=>{a(`\u2713 Created "${h.title}" (${h.id})${g?` \u{1F4CE}${g.length}`:""}`,e.green),d.assignee&&x&&x(h.id,d.assignee).catch(()=>{}),Z();},h=>a(`Failed: ${h instanceof Error?h.message:String(h)}`,e.red));}else if(f==="edit_task"&&s&&E){let d=Di(i),g=ln.length>0?[...ln]:void 0;Xn([]),a("Updating task...",e.amber),E(s,{...d,attachments:g}).then(h=>{a(`\u2713 Updated "${h.title}"${g?` \u{1F4CE}${g.length}`:""}`,e.green),d.assignee&&x&&x(s,d.assignee).catch(()=>{}),Z();},h=>a(`Failed: ${h instanceof Error?h.message:String(h)}`,e.red));}else if(f==="edit_agent"&&s&&W){let d=Wi(i),g=d.team_id??"",h=Vt.find(u=>u.members.some(w=>w.agent_id===s))?.id??"";a("Updating agent...",e.amber),W(s,{name:d.name,role:d.role,model:d.model,effort:d.effort}).then(u=>{a(`\u2713 Updated agent "${u.name}"`,e.green);let w=[];h&&h!==g&&Ee&&w.push(Ee(h,s).then(J=>a(`\u2713 Left team "${J.name}"`,e.green),J=>a(`Failed to leave team: ${J instanceof Error?J.message:String(J)}`,e.red))),g&&g!==h&&ae&&w.push(ae(g,s).then(J=>a(`\u2713 Joined team "${J.name}"`,e.green),J=>a(`Failed to join team: ${J instanceof Error?J.message:String(J)}`,e.red))),Promise.all(w).then(()=>Z({includeTeams:w.length>0}));},u=>a(`Failed: ${u instanceof Error?u.message:String(u)}`,e.red));}else if(f==="config"){if(i.activity_filter){let u=Gn.find(w=>w.label===i.activity_filter);u&&(ur(new Set(u.types)),Ue?.(u.label));}if(i.max_concurrent){let u=parseInt(i.max_concurrent,10);u>0&&(aa(u),Wn?.(u));}let d=i.notifications_toast==="true",g=i.notifications_bell==="true",h={toast:d,bell:g};la(h),Gt?.(h),a("Settings saved",e.green);}else if(f==="goal"&&De){let d=zi(i);a(`Creating goal "${d.title}"...`,e.amber),De(d).then(g=>{a(`\u2713 Created goal "${g.title}" (${g.id})`,e.green),Z();},g=>a(`Failed: ${g instanceof Error?g.message:String(g)}`,e.red));}else if(f==="edit_goal"&&s&&Ye){let d=Hi(i);a("Updating goal...",e.amber),Ye(s,d).then(g=>{a(`\u2713 Updated goal "${g.title}"`,e.green),Z();},g=>a(`Failed: ${g instanceof Error?g.message:String(g)}`,e.red));}},[bt,P,p,X,ae,Ee,x,E,W,ut,De,Ye,a,Z,Ue,Wn,ho,Gt,Vt,ln]),Ma=useCallback(()=>{Oe("none"),Je(null),Xn([]);},[]),va=useCallback(i=>{let f=b(i);if(!f)return;let s=Yo(K,Mn.current),d=zr(s,f);Je({title:`NEW AGENT \u2014 ${f.name}`,steps:d,kind:"agent_from_shop"}),Oe("wizard");},[]);useEffect(()=>{if(!A)return;let i=null,f=()=>{i||(i=setTimeout(()=>{i=null,Z().catch(()=>{});},150));},s=A(d=>{if(d.type==="agent:started"&&(dn.current.set(d.runId,d.agentId),ko.current.set(d.runId,d.taskId)),Vc(d,a,dn.current,ko.current),d.type==="task:created"?mo(g=>g==="welcome"?"task_created":g):d.type==="agent:started"?mo(g=>g==="task_created"?"run_started":g):d.type==="task:status_changed"&&d.to==="done"&&mo(g=>g==="run_started"?"completed":g),d.type==="task:status_changed"&&(d.to==="done"?bo("done",d.taskId):d.to==="failed"?bo("failed",d.taskId):d.to==="review"&&bo("review",d.taskId),xo.current.toast&&rs.current!=="tasks")){let g=d.to==="done"?e.green:d.to==="failed"?e.red:d.to==="review"?e.blue:void 0;g&&os({tab:"tasks",color:g});}(d.type==="task:status_changed"||d.type==="task:created"||d.type==="task:assigned"||d.type==="agent:started"||d.type==="agent:completed"||d.type==="run:retry"||d.type==="goal:created"||d.type==="goal:status_changed"||d.type==="goal:updated"||d.type==="goal:deleted")&&f();});return ()=>{s(),i&&clearTimeout(i);}},[A,a,Z,bo]);let wr=xt?"observing":Tn?"watching":"idle",_a=we.started_at?g(we.started_at):void 0,xs=we.stats.total_tokens.total,bs=useMemo(()=>{let i={running:0,retrying:0,review:0,todo:0,done:0,failed:0,cancelled:0};for(let f of le)f.status==="in_progress"?i.running++:f.status==="retrying"?i.retrying++:f.status==="review"?i.review++:f.status==="todo"?i.todo++:f.status==="done"?i.done++:f.status==="failed"?i.failed++:f.status==="cancelled"&&i.cancelled++;return {...i,teams:eo}},[le,eo]);bs.running;let Ra=useMemo(()=>({input:we.stats.total_tokens.input??0,output:we.stats.total_tokens.output??0,reasoning:we.stats.total_tokens.reasoning??0,total:xs,cache_read:we.stats.total_tokens.cache_read??0,cache_write:we.stats.total_tokens.cache_write??0}),[we.stats.total_tokens,xs]),It=Math.max(4,te-9),Aa=Rn.size,$a=K.length>Aa,Ba=eo>0?eo+($a?1:0):0,Ea=useMemo(()=>{if(!Zn||vn.size===0)return 0;let i=0,f=new Set,s=false;for(let d of Bt)d.goalId&&vn.has(d.goalId)?f.has(d.goalId)||(f.add(d.goalId),i++):s=true;return s&&i++,i},[Zn,vn,Bt]),Oa=R==="goals"?ft.length+1:R==="tasks"?Bt.length+1+(_n>0?1:0)+Ea:R==="agents"?K.length+1+Ba:0,La=Math.min(Oa+1,Math.ceil(It*.5)),Pa=R==="logs"?It:Math.max(2,Math.min(La,It-4)),Se,Et;if(R==="logs")Se=It,Et=0;else if(yo)Se=0,Et=Math.max(1,It);else {let i=Math.max(3,Math.min(Pa+hr,It-4));Se=i,Et=Math.max(1,It-i);}let ve=Math.max(10,q-2),Mt=useMemo(()=>Fe==="command"?Ks(an):[],[Fe,an]),$n=It-4-3;useEffect(()=>{hr>$n&&Cn($n),hr<-$n&&Cn(-$n);},[It]),useEffect(()=>{kn(i=>Math.min(i,Math.max(0,Bt.length-Se)));},[Bt.length,Se]),useEffect(()=>{fr(i=>Math.min(i,Math.max(0,Ge.length-Se)));},[Ge.length,Se]),useEffect(()=>{pr(i=>Math.min(i,Math.max(0,ft.length-Se)));},[ft.length,Se]);let Na=useCallback(i=>{let s=i.trim().replace(/^\//,"").split(/\s+/),d=s[0]?.toLowerCase();if(!d)return;let g=h=>h instanceof Error?h.message:String(h);switch(d){case "cancel":{if(!U){a("No task selected",e.yellow);return}if(!b$1)return;a(`Cancelling "${U.title}"...`,e.amber),b$1(U.id).then(()=>{a(`\u2713 Cancelled "${U.title}"`,e.green),Z();},h=>a(`Failed: ${g(h)}`,e.red));return}case "retry":{if(!U){a("No task selected",e.yellow);return}if(!T)return;a(`Retrying "${U.title}"...`,e.amber),T(U.id).then(()=>{a(`\u2713 Retried "${U.title}"`,e.green),Z();},h=>a(`Failed: ${g(h)}`,e.red));return}case "assign":{if(!U){a("No task selected",e.yellow);return}if(!x||!s[1]){a("Usage: assign <agent>",e.yellow);return}a(`Assigning "${U.title}" to ${s[1]}...`,e.amber),x(U.id,s[1]).then(()=>{a(`\u2713 Assigned "${U.title}" to ${s[1]}`,e.green),Z();},h=>a(`Failed: ${g(h)}`,e.red));return}case "task":{let h=s[1]?.toLowerCase();if(h==="add"){let u=s.slice(2).join(" ");if(!u){Io();return}if(!p){a("Create not available",e.yellow);return}a(`Creating "${u}"...`,e.amber),p(u).then(w=>{a(`\u2713 Created "${w.title}" (${w.id})`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="list"){let u=Le.map(w=>` ${w.id} ${w.status.padEnd(11)} ${w.title}`);if(u.length===0)a("No tasks",e.dim);else for(let w of u)a(w,e.cyan);}else if(h==="show"){let u=s[2]?Le.find(w=>w.id===s[2]):U;if(!u){a("No task selected or id given",e.yellow);return}a(`${u.id} ${u.status} P${u.priority} "${u.title}"`,e.cyan),u.assignee&&a(` agent: ${u.assignee}`,e.dim),u.description&&a(` ${u.description.slice(0,100)}`,e.dim);}else if(h==="cancel"){let u=s[2]?Le.find(w=>w.id===s[2]):U;if(!u){a("No task selected or id given",e.yellow);return}if(!b$1)return;a(`Cancelling "${u.title}"...`,e.amber),b$1(u.id).then(()=>{a(`\u2713 Cancelled "${u.title}"`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="retry"){let u=s[2]?Le.find(w=>w.id===s[2]):U;if(!u){a("No task selected or id given",e.yellow);return}if(!T)return;a(`Retrying "${u.title}"...`,e.amber),T(u.id).then(()=>{a(`\u2713 Retried "${u.title}"`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="assign"){let u=s[2]?Le.find(Ot=>Ot.id===s[2]):void 0,w=u??U,J=u?s[3]:s[2];if(!w){a("No task selected or id given",e.yellow);return}if(!J){a("Usage: /task assign [id] <agent>",e.yellow);return}if(!x)return;a(`Assigning "${w.title}" to ${J}...`,e.amber),x(w.id,J).then(()=>{a(`\u2713 Assigned "${w.title}" to ${J}`,e.green),Z();},Ot=>a(`Failed: ${g(Ot)}`,e.red));}else if(h==="approve"){let u=s[2]?Le.find(w=>w.id===s[2]):U;if(!u){a("No task selected or id given",e.yellow);return}if(u.status!=="review"){a(`Cannot approve \u2014 status is ${u.status}`,e.yellow);return}if(!O)return;a(`Approving "${u.title}"...`,e.amber),O(u.id).then(()=>{a(`\u2713 Approved "${u.title}"`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="reject"){let u=s[2]?Le.find(J=>J.id===s[2]):U;if(!u){a("No task selected or id given",e.yellow);return}if(u.status!=="review"){a(`Cannot reject \u2014 status is ${u.status}`,e.yellow);return}if(!L)return;let w=s.slice(s[2]&&Le.find(J=>J.id===s[2])?3:2).join(" ").trim()||void 0;a(`Rejecting "${u.title}"${w?" with feedback":""}...`,e.amber),L(u.id,w).then(()=>{a(`\u2713 Rejected "${u.title}" \u2192 todo`,e.green),Z();},J=>a(`Failed: ${g(J)}`,e.red));}else if(h==="delete"){let u=s[2]?Le.find(w=>w.id===s[2]):U;if(!u){a("No task selected or id given",e.yellow);return}if(u.status==="in_progress"){a("Cannot delete \u2014 task is running",e.yellow);return}if(!N)return;An("task",u.id,u.title);}else a("Usage: /task add|list|show|cancel|retry|assign|approve|reject|delete",e.yellow);return}case "agent":{let h=s[1]?.toLowerCase();if(h==="add"){let u=s[2];if(!u){Co();return}if(!P){a("Agent creation not available",e.yellow);return}let w=s[3];a(`Creating agent "${u}"...`,e.amber),P(u,w).then(J=>{a(`\u2713 Created agent "${J.name}" (${J.id}, ${J.adapter})`,e.green),Z();},J=>a(`Failed: ${g(J)}`,e.red));}else if(h==="list"){let u=Ge.map(w=>` ${w.id} ${w.status.padEnd(8)} ${w.name} (${w.adapter})`);if(u.length===0)a("No agents",e.dim);else for(let w of u)a(w,e.cyan);}else if(h==="disable"){let u=s[2]?Ge.find(w=>w.id===s[2]||w.name===s[2]):Q;if(!u){a("No agent selected or id given",e.yellow);return}if(!C)return;a(`Disabling ${u.name}...`,e.amber),C(u.id).then(()=>{a(`\u2713 Disabled ${u.name}`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="enable"){let u=s[2]?Ge.find(w=>w.id===s[2]||w.name===s[2]):Q;if(!u){a("No agent selected or id given",e.yellow);return}if(!M)return;a(`Enabling ${u.name}...`,e.amber),M(u.id).then(()=>{a(`\u2713 Enabled ${u.name}`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="delete"||h==="remove"){let u=s[2]?Ge.find(w=>w.id===s[2]||w.name===s[2]):Q;if(!u){a("No agent selected or id given",e.yellow);return}if(u.status==="running"){a("Cannot delete \u2014 agent is running",e.yellow);return}if(!j){a("Agent deletion not available",e.yellow);return}An("agent",u.id,u.name);}else if(h==="autonomous"||h==="auto"){let u=s[2]?Ge.find(w=>w.id===s[2]||w.name===s[2]):Q;if(!u){a("No agent selected or id given",e.yellow);return}if(!ut){a("Autonomous toggle not available",e.yellow);return}u.autonomous?(a(`Disabling autonomous mode for "${u.name}"...`,e.amber),ut(u.id,false).then(()=>{a(`${mn} ${u.name} autonomous OFF`,e.cyan),Z();},w=>a(`Failed: ${g(w)}`,e.red))):(a(`Enabling autonomous mode for "${u.name}"...`,e.amber),ut(u.id,true).then(()=>{a(`${mn} ${u.name} autonomous ON`,e.cyan),Z();},w=>a(`Failed: ${g(w)}`,e.red)));}else h==="shop"?fs():a("Usage: /agent add|list|disable|enable|delete|autonomous|shop",e.yellow);return}case "team":{let h=s[1]?.toLowerCase();if(h==="create"||h==="add")ps();else if(h==="list"){let u=Mn.current;if(u.length===0)a("No teams",e.dim);else for(let w of u)a(` ${w.id} ${w.status.padEnd(8)} ${w.name} (${w.members.length} members)`,e.cyan);}else if(h==="join"){if(!ae){a("Join not available",e.yellow);return}let u=s[2],w=s[3]??Q?.id;if(!u||!w){a("Usage: /team join <teamId> [agentId]",e.yellow);return}a(`Joining team ${u}...`,e.amber),ae(u,w).then(J=>{a(`\u2713 Agent joined team "${J.name}"`,e.green),Z({includeTeams:true});},J=>a(`Failed: ${g(J)}`,e.red));}else if(h==="leave"){if(!Ee){a("Leave not available",e.yellow);return}let u=s[2],w=s[3]??Q?.id;if(!u||!w){a("Usage: /team leave <teamId> [agentId]",e.yellow);return}a(`Leaving team ${u}...`,e.amber),Ee(u,w).then(J=>{a(`\u2713 Agent left team "${J.name}"`,e.green),Z({includeTeams:true});},J=>a(`Failed: ${g(J)}`,e.red));}else if(h==="disband"){if(!Ft){a("Disband not available",e.yellow);return}let u=s[2];if(!u){a("Usage: /team disband <teamId>",e.yellow);return}a(`Disbanding team ${u}...`,e.amber),Ft(u).then(()=>{a("\u2713 Team disbanded",e.green),Z({includeTeams:true});},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="set-lead"){if(!dt){a("Set-lead not available",e.yellow);return}let u=s[2],w=s[3];if(!u||!w){a("Usage: /team set-lead <teamId> <agentId>",e.yellow);return}a(`Setting lead for team ${u}...`,e.amber),dt(u,w).then(J=>{a(`\u2713 New lead for team "${J.name}"`,e.green),Z({includeTeams:true});},J=>a(`Failed: ${g(J)}`,e.red));}else a("Usage: /team create|list|join|leave|disband|set-lead",e.yellow);return}case "goal":{let h=s[1]?.toLowerCase();if(h==="add"||h==="create"){let u=s.slice(2).join(" ").trim();if(!u){let w=Zo(K);Je({title:"New Goal",steps:w,kind:"goal"}),Oe("wizard");return}if(!De){a("Goal creation not available",e.yellow);return}a(`Creating goal "${u}"...`,e.amber),De({title:u}).then(w=>{a(`\u2713 Created goal "${w.title}" (${w.id})`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));}else if(h==="list"){let u=ft.map(w=>` ${w.id} ${w.status.padEnd(8)} ${w.title}`);if(u.length===0)a("No goals",e.dim);else for(let w of u)a(w,e.cyan);}else if(h==="show"){let u=s[2]?ft.find(w=>w.id===s[2]):oe;if(!u){a("No goal selected or id given",e.yellow);return}a(`${u.id} ${u.status} "${u.title}"`,e.cyan),u.description&&a(` ${u.description.slice(0,100)}`,e.dim);}else if(h==="status"){let u=s[2]?ft.find(gn=>gn.id===s[2]):void 0,w=u??oe;if(!w){a("No goal selected or id given",e.yellow);return}let J=s[u?3:2];if(!J||!a$1.includes(J)){a("Usage: /goal status [id] <active|paused|achieved|abandoned>",e.yellow);return}let Ot=J;if(!gt){a("Status update not available",e.yellow);return}a(`Updating goal status to ${Ot}...`,e.amber),gt(w.id,Ot).then(gn=>{a(`\u2713 Goal "${gn.title}" \u2192 ${Ot}`,e.green),Z();},gn=>a(`Failed: ${g(gn)}`,e.red));}else if(h==="delete"){let u=s[2]?ft.find(w=>w.id===s[2]):oe;if(!u){a("No goal selected or id given",e.yellow);return}if(!Ze){a("Goal deletion not available",e.yellow);return}An("goal",u.id,u.title);}else a("Usage: /goal add|list|show|status|delete",e.yellow);return}case "run":{let h=s[1]??U?.id;if(!h){a("No task selected or id given",e.yellow);return}if(!l){a("Run not available",e.yellow);return}let u=Le.find(w=>w.id===h);if(u&&!Vr.has(u.status)){a(`Cannot run \u2014 status is ${u.status}`,e.yellow);return}a(`Running ${h}...`,e.amber),l(h).then(()=>{a(`\u2713 Dispatched ${h}`,e.green),Z();},w=>a(`Failed: ${g(w)}`,e.red));return}case "run-all":{if(!y){a("Run-all not available",e.yellow);return}a("Running all todo tasks...",e.amber),y().then(()=>{a("\u2713 Dispatched all todo tasks",e.green),Z();},h=>a(`Failed: ${g(h)}`,e.red));return}case "watch":{if(Tn){a("Watch mode already active",e.yellow);return}if(!Re){a("Watch not available",e.yellow);return}a("Starting watch mode...",e.amber),Re().then(()=>{rr(true),a("\u2713 Watch mode started",e.green);},h=>a(`Failed: ${g(h)}`,e.red));return}case "pause":{if(!Tn){a("Watch mode not active",e.yellow);return}if(!Ke){a("Pause not available",e.yellow);return}a("Pausing watch mode...",e.amber),Ke().then(()=>{rr(false),a("\u2713 Watch mode paused",e.green);},h=>a(`Failed: ${g(h)}`,e.red));return}case "config":{s[1]?.toLowerCase()==="activity-filter"?ur(u=>{let w=Hr(u);return Ue?.(w.label),a(`Activity filter: ${w.label}`,e.amber),new Set(w.types)}):hs();return}case "status":{let h=le.filter(u=>u.status==="in_progress").length;a(`${wr} ${h} running ${le.length} tasks ${Ge.length} agents`,e.cyan);return}case "help":{for(let[h,u]of Object.entries(fn)){let w=u.sub?" "+u.sub.join("|"):u.args?" "+u.args:"";a(` /${h}${w} \u2014 ${u.help}`,e.silver);}return}case "quit":{nt();return}case "disable":{if(!Q){a("No agent selected",e.yellow);return}if(!C)return;a(`Disabling ${Q.name}...`,e.amber),C(Q.id).then(()=>{a(`\u2713 Disabled ${Q.name}`,e.green),Z();},h=>a(`Failed: ${g(h)}`,e.red));return}case "enable":{if(!Q){a("No agent selected",e.yellow);return}if(!M)return;a(`Enabling ${Q.name}...`,e.amber),M(Q.id).then(()=>{a(`\u2713 Enabled ${Q.name}`,e.green),Z();},h=>a(`Failed: ${g(h)}`,e.red));return}default:a(`Unknown: ${d}. Type /help for commands`,e.yellow);}},[U,Q,Le,Ge,le,wr,Tn,b$1,T,x,y,l,p,C,M,P,O,L,N,ae,Ee,Ft,dt,Re,Ke,a,nt,Z,Io,Co,ps,hs]);useInput((i,f)=>{if(!($t&&(ar(false),i==="?"||f.escape||i==="\x1BOP"))&&!wn){if((f.ctrl||f.meta)&&i==="s"&&Fe==="wizard"&&bt?.kind==="agent"){fs();return}if(Fe!=="none"){if(f.escape){Oe("none"),Ct(""),To.reset();return}if(f.return){let s=an.trim();if(!s)return;if(Fe==="new_task"){if(!p)return;Oe("none"),Ct(""),a(`Creating "${s}"...`,e.amber),p(s).then(d=>{a(`\u2713 Created "${d.title}" (${d.id})`,e.green),Z();},d=>a(`Failed to create: ${d instanceof Error?d.message:String(d)}`,e.red));}else if(Fe==="command"){let d=s;if(Mt.length>0&&Mt[wo]){let g=Mt[wo],h=g.cmd.replace(/\s+\[.*\]$/,"");if((h.startsWith(s)||s==="/")&&(d=h),g.subs&&!h.includes(" ")){Ct(h+" "),Zt(0);return}}Oe("none"),Ct(""),Zt(0),To.push(d),Na(d);}return}if(f.tab&&Fe==="command"){if(Mt.length>0){let s=Mt[wo];if(s){let d=s.cmd.replace(/\s+\[.*\]$/,"");Ct(d+(s.subs?" ":"")),Zt(0);}}else {let s=Ar(an);s&&Ct(d=>d+s);}return}if(f.upArrow&&Fe==="command"){if(Mt.length>0)Zt(s=>Math.max(0,s-1));else {let s=To.prev();s!==null&&Ct(s);}return}if(f.downArrow&&Fe==="command"){if(Mt.length>0)Zt(s=>Math.min(Mt.length-1,s+1));else {let s=To.next();Ct(s??"");}return}if(f.backspace||f.delete){Ct(s=>s.slice(0,-1)),Zt(0);return}i&&!f.ctrl&&!f.meta&&(Ct(s=>s+i),Zt(0));return}if(i.toLowerCase()==="q"){nt();return}if(f.escape){if($e){Un(false),Jn(0);return}if(R==="logs"&&Kn>=0){dr(-1),Yn(0);return}return}if((i==="+"||i==="=")&&R!=="logs"){yo?(xr(false),Cn(-Math.floor(It/2))):Cn(s=>Math.max(-$n,s-3));return}if(i==="-"&&R!=="logs"){yo?(xr(false),Cn(Math.floor(It/2))):Cn(s=>Math.min($n,s+3));return}if(i==="M"&&R!=="logs"){xr(s=>!s);return}if(i==="?"){ar(true);return}if(i==="\x1BOP"){ar(true);return}if(i==="/"&&!$e){Oe("command"),Ct("/"),Zt(0);return}if((i==="a"||i==="A")&&R==="logs"&&!$e&&!wn&&!qn){lr(true);return}if(i==="f"&&R==="logs"&&!$e&&!wn&&!qn){cr(true);return}if(i==="F"&&R==="logs"&&!$e&&!wn&&!qn){es(s=>new Set(Hr(s).types));return}if((i==="z"||i==="Z")&&In.length>0){wa();return}if((i==="f"||i==="F")&&(R==="tasks"||R==="agents"||R==="goals")&&!$e){ur(s=>{let d=Hr(s);return Ue?.(d.label),new Set(d.types)});return}if((i==="n"||i==="N")&&R==="tasks"&&!$e&&p){Io();return}if((i==="n"||i==="N")&&R==="agents"&&!$e&&P){Co();return}if((i==="n"||i==="N")&&R==="goals"&&!$e&&De){let s=Zo(K);Je({title:"New Goal",steps:s,kind:"goal"}),Oe("wizard");return}if((i==="e"||i==="E")&&R==="goals"&&oe&&Ye){let s=Vi(oe,K);Je({title:`Edit Goal: ${oe.title}`,steps:s,kind:"edit_goal",targetId:oe.id}),Oe("wizard");return}if((i==="d"||i==="D")&&R==="goals"&&oe&&Ze){An("goal",oe.id,oe.title);return}if((i==="c"||i==="C")&&R==="goals"&&oe&&gt){(oe.status==="active"||oe.status==="paused")&&(a(`Marking goal "${oe.title}" as achieved...`,e.amber),gt(oe.id,"achieved").then(()=>{a(`\u2713 Goal "${oe.title}" achieved`,e.green),Z();},s=>a(`Failed: ${s instanceof Error?s.message:String(s)}`,e.red)));return}if((i==="x"||i==="X")&&R==="goals"&&oe&&gt){(oe.status==="active"||oe.status==="paused")&&(a(`Abandoning goal "${oe.title}"...`,e.amber),gt(oe.id,"abandoned").then(()=>{a(`\u2713 Goal "${oe.title}" abandoned`,e.dim),Z();},s=>a(`Failed: ${s instanceof Error?s.message:String(s)}`,e.red)));return}if((i==="p"||i==="P")&&R==="goals"&&oe&&gt){let s=oe.status==="paused"?"active":"paused";(oe.status==="active"||oe.status==="paused")&&gt(oe.id,s).then(()=>{a(`Goal "${oe.title}" ${s}`,e.cyan),Z();},d=>a(`Failed: ${d instanceof Error?d.message:String(d)}`,e.red));return}if((i==="a"||i==="A")&&R==="tasks"&&U?.status==="review"&&O){a(`Approving "${U.title}"...`,e.amber),O(U.id).then(()=>{a(`\u2713 Approved "${U.title}"`,e.green),Z();},s=>a(`Failed: ${s instanceof Error?s.message:String(s)}`,e.red));return}if((i==="x"||i==="X")&&R==="tasks"&&U?.status==="review"&&L){a(`Rejecting "${U.title}"...`,e.amber),L(U.id).then(()=>{a(`\u2713 Rejected "${U.title}" \u2192 todo`,e.green),Z();},s=>a(`Failed: ${s instanceof Error?s.message:String(s)}`,e.red));return}if((i==="c"||i==="C")&&R==="tasks"&&U&&b$1){if(U.status==="done"||U.status==="failed"||U.status==="cancelled"){a(`Cannot cancel \u2014 status is ${U.status}`,e.yellow);return}a(`Cancelling "${U.title}"...`,e.amber),b$1(U.id).then(()=>{a(`\u2713 Cancelled "${U.title}"`,e.green),Z();},s=>a(`Failed: ${s instanceof Error?s.message:String(s)}`,e.red));return}if((i==="e"||i==="E")&&R==="tasks"&&U&&E){ka(U);return}if((i==="e"||i==="E")&&R==="agents"&&Q&&W){Ca(Q);return}if((i==="s"||i==="S")&&R==="tasks"){ls(s=>!s),jn(0),kn(0);return}if((i==="g"||i==="G")&&R==="tasks"&&!$e){ma(s=>!s),jn(0),kn(0);return}if((i==="s"||i==="S")&&R==="agents"&&Q&&z){if(!Object.values(we.running).some(d=>d.agent_id===Q.id)&&Q.status!=="running"){a(`Agent "${Q.name}" is not running`,e.yellow);return}a(`Force-stopping agent "${Q.name}"...`,e.amber),z(Q.id).then(()=>{a(`\u2713 Stopped agent "${Q.name}"`,e.green),Z();},d=>a(`Failed: ${d instanceof Error?d.message:String(d)}`,e.red));return}if((i==="d"||i==="D")&&R==="tasks"&&U&&U.status!=="in_progress"&&N){An("task",U.id,U.title);return}if((i==="d"||i==="D")&&R==="agents"&&Q&&j){let s=Object.values(we.running).some(d=>d.agent_id===Q.id);if(s&&!z){a(`Cannot delete \u2014 agent "${Q.name}" is running. Press S to stop first.`,e.yellow);return}An("agent",Q.id,Q.name,{needsForceStop:s});return}if((i==="u"||i==="U")&&R==="agents"&&Q&&ut){let s=!Q.autonomous;a(`${s?"Enabling":"Disabling"} autonomous mode for "${Q.name}"...`,e.amber),ut(Q.id,s).then(()=>{a(`${mn} ${Q.name} autonomous ${s?"ON":"OFF"}`,e.cyan),Z();},d=>a(`Failed: ${d instanceof Error?d.message:String(d)}`,e.red));return}if(!$e){if(i==="g"||i==="G"){yn("goals");return}if(i==="t"||i==="T"){yn("tasks");return}if(i==="a"||i==="A"){yn("agents");return}if(i==="l"||i==="L"){yn("logs");return}}if(!$e){let s=Oo.map(g=>g.id),d=s.indexOf(R);if(f.tab||f.rightArrow){yn(s[(d+1)%s.length]);return}if(f.leftArrow){yn(s[(d+s.length-1)%s.length]);return}}if(f.return){let s=_n>0?Bt.length:-1;if(R==="tasks"&&fo===s){ls(g=>!g),jn(0),kn(0);return}let d=Bt.length+(_n>0?1:0);if(R==="tasks"&&fo===d&&p){Io();return}if(R==="goals"&&ir===ft.length&&De){let g=Zo(K);Je({title:"New Goal",steps:g,kind:"goal"}),Oe("wizard");return}if(R==="agents"&&sr===Ge.length&&P){Co();return}if(R==="goals"&&oe){Un(g=>!g),Jn(0);return}if(R==="tasks"&&U){Un(g=>!g);return}if(R==="agents"&&Q){Un(g=>!g);return}if(R==="logs"&&Kn>=0){Un(g=>!g);return}}if((i==="r"||i==="R")&&R==="tasks"&&U&&l){if(!Vr.has(U.status)){a(`Cannot run "${U.title}" \u2014 status is ${U.status}`,e.yellow);return}a(`Running "${U.title}"...`,e.green),l(U.id).then(()=>{a(`Dispatched "${U.title}"`,e.green),Z();},s=>a(`Failed to run: ${s instanceof Error?s.message:String(s)}`,e.red));return}if(f.upArrow||i==="k"){if(R==="goals"&&$e){Jn(s=>Math.max(0,s-1));return}R==="goals"?Yr(s=>{let d=Math.max(0,s-1);return pr(g=>d<g?d:g),d}):R==="tasks"?jn(s=>{let d=Math.max(0,s-1);return kn(g=>d<g?d:g),d}):R==="agents"?Kr(s=>{let d=Math.max(0,s-1);return fr(g=>d<g?d:g),d}):R==="logs"&&dr(s=>{if(s===-1){let g=ze.length-1;return Yn(Math.max(0,g-Se+2)),Math.max(0,g)}let d=Math.max(0,s-1);return Yn(g=>d<g?d:g),d});}if(f.downArrow||i==="j"){if(R==="goals"&&$e){Jn(s=>s+1);return}if(R==="goals"){let s=ft.length+(De?1:0)-1;Yr(d=>{let g=Math.min(Math.max(0,s),d+1);return pr(h=>g>=h+Se?g-Se+1:h),g});}else if(R==="tasks"){let s=Bt.length+(p?1:0)+(_n>0?1:0)-1;jn(d=>{let g=Math.min(Math.max(0,s),d+1);return kn(h=>g>=h+Se?g-Se+1:h),g});}else if(R==="agents"){let s=Ge.length+(P?1:0)-1;Kr(d=>{let g=Math.min(Math.max(0,s),d+1);return fr(h=>g>=h+Se?g-Se+1:h),g});}else R==="logs"&&dr(s=>{if(s===-1)return -1;let d=ze.length-1;if(s>=d)return Yn(0),-1;let g=s+1;return Yn(h=>g>=h+Se-1?g-Se+2:h),g});}}});let ot=Fe!=="none",Ts=Kn>=0?ze[Kn]:void 0,Mo=yo?"+/- exit max":"+/- resize \u2502 M max",ys=!ot&&$e&&R==="tasks"&&U,ws=!ot&&$e&&R==="agents"&&Q,Ss=!ot&&$e&&R==="goals"&&oe,Da=!ot&&$e&&R==="logs"&&Ts,Sr=U?.id,Fa=useMemo(()=>Sr?ze.filter(i=>i.taskId===Sr):[],[ze,Sr]),Ga=!ot&&R==="tasks"&&U&&Vr.has(U.status)&&!!l,Wa=!ot&&!$e&&(R==="goals"&&!!De||R==="tasks"&&!!p||R==="agents"&&!!P),za=!ot&&R==="tasks"&&U?.status==="review"&&!!O,Va=!ot&&R==="tasks"&&U?.status==="review"&&!!L,Ha=Q?Object.values(we.running).some(i=>i.agent_id===Q.id):false,ja=!ot&&(R==="goals"&&oe&&!!Ze||R==="tasks"&&U&&U.status!=="in_progress"&&!!N||R==="agents"&&Q&&!!j),Ua=!ot&&!$e&&(R==="goals"&&!!oe&&!!Ye||R==="tasks"&&!!U&&!!E||R==="agents"&&!!Q&&!!W),Xa=!ot&&R==="agents"&&Q&&(Ha||Q.status==="running")&&!!z,qa=!ot&&R==="agents"&&!!Q&&!!ut,Ka=!ot&&R==="goals"&&!!oe&&(oe.status==="active"||oe.status==="paused")&&!!gt,Ya=!ot&&In.length>0,ks=Fe==="command"&&Mt.length>0,Cs=bt?.kind==="task"||bt?.kind==="edit_task";return jsxs(Box,{flexDirection:"column",width:q,height:te,children:[jsx(qs,{projectName:t,activeView:R,mode:wr,stats:bs,tokens:Ra,uptime:_a,width:q,version:Wt,latestVersion:xn,updateInstalled:bn,taskBadge:_n>0?Le.length:void 0,flashTab:mr?.tab,flashColor:mr?.color,onFlashComplete:mr?()=>os(void 0):void 0}),jsx(Box,{height:1}),$t&&jsx(bi,{width:q,height:te-7}),!$t&&Yt==="welcome"&&R==="tasks"&&jsx(li,{width:q,height:te}),!$t&&R==="goals"&&jsx(vc,{goals:ft,selectedIndex:ir,scrollOffset:pa,height:Se,width:ve,showAddRow:!!De,agentNameMap:cn,tasksByGoalMap:xa}),!$t&&Yt!=="welcome"&&R==="tasks"&&jsx(Rc,{tasks:Bt,selectedIndex:fo,scrollOffset:ga,height:Se,width:ve,showAddRow:!!p,agentNameMap:cn,hiddenCount:_n,goalMap:vn,groupByGoal:Zn}),!$t&&R==="tasks"&&(Yt==="task_created"||Yt==="run_started")&&jsx(ci,{step:Yt,width:q}),!$t&&R==="tasks"&&Yt==="completed"&&jsx(di,{width:q}),!$t&&R==="agents"&&jsx(Ac,{agents:Ge,selectedIndex:sr,scrollOffset:fa,height:Se,width:ve,state:we,taskTitleMap:Qn,showAddRow:!!P,agentTeamMap:Rn,teamLeadSet:Ta,activeTeamCount:eo}),!$t&&R==="logs"&&jsxs(Fragment,{children:[jsx(Bc,{messages:ze,height:wn||qn?Math.max(3,Se-16):Se,agents:Ge,logAgentFilter:Jr,logTypeFilter:Qr,selectedIndex:Kn,scrollOffset:ia,agentNameMap:cn,agentColorMap:So,agentMsgCounts:us,taskTitleMap:Qn,width:ve}),wn&&jsx(Box,{paddingX:2,children:jsx(oi,{agents:Ge,selected:Jr,msgCounts:us,colorMap:So,maxHeight:Math.min(Se-4,18),onConfirm:i=>{sa(i),lr(false);},onCancel:()=>lr(false)})}),qn&&jsx(Box,{paddingX:2,children:jsx(ai,{selected:Qr,typeCounts:ba,onConfirm:i=>{es(i),cr(false);},onCancel:()=>cr(false)})})]}),jsx(Box,{height:1}),$t?null:Fe==="wizard"&&bt?jsx(ei,{title:bt.title,steps:bt.steps,onComplete:Ia,onCancel:Ma,width:ve,height:Et,onPasteImage:Cs?Sa:void 0,onSuggestionSelected:bt.kind==="agent"?va:void 0,footerExtra:ln.length>0&&Cs?`\u{1F4CE}${ln.length}`:void 0},`${bt.kind}-${bt.title}`):ks?jsxs(Fragment,{children:[jsx(Jo,{label:"COMMANDS",width:ve}),jsx(Mc,{suggestions:Mt,selectedIndex:wo,height:Math.min(Mt.length,Et),width:ve})]}):Fe==="new_task"?jsxs(Fragment,{children:[jsx(Gc,{mode:Fe,width:ve}),jsx(Wc,{mode:Fe,value:an,width:ve})]}):ys?jsxs(Fragment,{children:[jsx(Lc,{task:U,width:ve,resizeHint:Mo}),jsx(js,{task:U,height:Et,width:ve,taskLogs:Fa,agentNameMap:cn,taskTitleMap:Qn})]}):Ss?jsxs(Fragment,{children:[jsx(Jo,{label:`GOAL: ${oe.title}`,width:ve,suffixLen:Mo.length+2,suffix:jsxs(Text,{color:e.dim,children:[" ",Mo," "]})}),jsx(_c,{goal:oe,height:Et,width:ve,agentNameMap:cn,tasks:ya,progressReport:ra,scrollOffset:ha,onClampScroll:Jn})]}):ws?jsxs(Fragment,{children:[jsx(Pc,{agent:Q,width:ve,resizeHint:Mo}),jsx(Nc,{agent:Q,height:Et,state:we,taskTitleMap:Qn,teamName:Rn.get(Q.id)})]}):Da?jsxs(Fragment,{children:[jsx(Jo,{label:"LOG",width:ve}),jsx(Oc,{message:Ts,height:Et,width:ve,agents:Ge,agentNameMap:cn,agentColorMap:So,taskTitleMap:Qn})]}):ze.length>0&&R!=="logs"?jsxs(Fragment,{children:[(()=>{let i=` F:${po.toUpperCase()} \u2502 ${gr.length}/${ze.length}`;return jsx(Jo,{label:"ACTIVITY",width:ve,suffixLen:i.length,suffix:jsxs(Fragment,{children:[jsx(Text,{color:e.dim,children:" F:"}),jsx(Text,{color:e.amber,children:po.toUpperCase()}),jsxs(Text,{color:e.ghost,children:[" ","\u2502"," ",gr.length,"/",ze.length]})]})})})(),jsx(Ec,{messages:gr,height:Math.max(1,Et-1),width:ve,agents:Ge,agentNameMap:cn,agentColorMap:So})]}):R==="goals"?jsx(Uo,{count:ft.length,config:wc,width:ve}):R==="tasks"?jsx(Uo,{count:Le.length,config:Sc,width:ve}):R==="agents"?jsx(Uo,{count:Ge.length,config:kc,width:ve}):null,jsx(Box,{flexGrow:1}),jsx(xi,{toasts:ca,onDismiss:ua}),In.length>0&&jsx(Ic,{deletions:In,width:q}),jsx(Ys,{mode:Fe==="command"?"command":"navigate",value:Fe==="command"?an:"",completion:Fe==="command"?Ar(an):null,activeView:R,canRun:!!Ga,canNew:!!Wa,canApprove:!!za,canReject:!!Va,canCancel:R==="tasks"&&!!U&&U.status==="in_progress"&&!!b$1,canDelete:!!ja,canUndo:!!Ya,canEdit:!!Ua,canForceStop:!!Xa,canToggleAuto:!!qa,autoActive:Q?.autonomous,canPause:!!Ka,isPaused:oe?.status==="paused",canToggleShowAll:R==="tasks"&&Le.length>ji,showAllActive:as,hasDetail:!!(ys||ws||Ss),itemCount:R==="goals"?ft.length:R==="tasks"?Le.length:R==="agents"?K.length:ze.length,itemLabel:R==="goals"?"goals":R==="tasks"?"tasks":R==="agents"?"agents":"events",width:q,hasSuggestions:ks,onboardingCompleted:r.onboardingCompleted})]})}var Ic=ao.memo(function({deletions:n,width:o}){let[,r]=useState(0);useEffect(()=>{let p=setInterval(()=>r(b=>b+1),1e3);return ()=>clearInterval(p)},[]);let l=Date.now();return jsx(Box,{flexDirection:"column",width:o,children:n.map(p=>{let b=Math.max(0,Math.ceil((p.expiresAt-l)/1e3)),T=Math.max(0,o-4),x=p.entityType==="task"?"Task":p.entityType==="agent"?"Agent":"Goal",y=Math.max(10,T-x.length-30),C=p.entityName.length>y?p.entityName.slice(0,y-1)+"\u2026":p.entityName;return jsx(Box,{paddingX:2,children:jsxs(Text,{color:e.yellow,children:["\u2717 ",jsx(Text,{bold:true,children:x}),` "${C}" \u2014 `,jsxs(Text,{color:e.amber,bold:true,children:[b,"s"]}),jsx(Text,{color:e.dim,children:" \u2502 "}),jsx(Text,{color:e.gray,bold:true,children:"Z"}),jsx(Text,{color:e.dim,children:" undo"})]})},p.key)})})});function Mc({suggestions:t,selectedIndex:n,height:o,width:r}){let l=o,p=0;n>=l&&(p=n-l+1);let b=t.slice(p,p+l);return jsx(Box,{flexDirection:"column",paddingX:2,children:b.map((T,x)=>{let y=x+p,C=y===n,M=C?"\u25B6":" ",A=Math.min(20,Math.max(14,...t.map(P=>P.cmd.length+1))),S=T.cmd.padEnd(A),H=T.subs?` ${T.subs}`:"",V=Math.max(4,r-A-H.length-8),F=T.desc.length>V?T.desc.slice(0,V-1)+"\u2026":T.desc;return jsxs(Text,{wrap:"truncate",children:[jsx(Text,{color:C?e.amber:e.ghost,children:` ${M} `}),jsx(Text,{color:C?e.white:e.silver,bold:C,children:S}),jsx(Text,{color:e.dim,children:F}),H&&jsx(Text,{color:e.ghost,children:H})]},y)})})}function vc({goals:t,selectedIndex:n,scrollOffset:o=0,height:r,width:l,showAddRow:p,agentNameMap:b,tasksByGoalMap:T}){let x=t.length,y=t.slice(o,o+r),C=p&&x>=o&&x<o+r;return jsxs(Box,{flexDirection:"column",height:r,children:[y.map((M,A)=>jsx(Box,{paddingX:2,children:jsx(Hs,{goal:M,selected:A+o===n,width:l-2,agentNameMap:b,tasksByGoal:T?.get(M.id)})},M.id)),C&&jsx(Box,{paddingX:2,children:jsxs(Text,{color:n===x?e.amber:e.ghost,children:[n===x?" \u25B8 ":" ",jsx(Text,{color:n===x?e.amber:e.dim,children:"+ add goal..."})]})},"__add__")]})}function _c({goal:t,height:n,width:o,agentNameMap:r,tasks:l,progressReport:p,scrollOffset:b=0,onClampScroll:T}){let y=ao.useMemo(()=>{let V=l??[],F=t.assignee?r?.get(t.assignee)??t.assignee:"\u2014",P=Math.max(20,o-6),j=(z,X)=>{if(z.length<=X)return [z];let _=[];for(let ae=0;ae<z.length;ae+=X)_.push(z.slice(ae,ae+X));return _},O=vr(p)?.split(`
13
- `).flatMap(z=>j(z,P))??[],L=vr(t.description)?.split(`
14
- `).flatMap(z=>j(z,P))??[],N=Rs[t.status]??e.dim,E=new Map;for(let z of V)E.set(z.status,(E.get(z.status)??0)+1);let W=[];if(W.push({key:"row-status",node:jsxs(Box,{children:[jsxs(Box,{width:24,children:[jsx(Text,{color:e.dim,children:" status "}),jsx(Text,{color:N,bold:true,children:t.status})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" assignee "}),jsx(Text,{color:t.assignee?e.green:e.dim,children:F})]})]})}),W.push({key:"row-id",node:jsxs(Box,{children:[jsxs(Box,{width:24,children:[jsx(Text,{color:e.dim,children:" id "}),jsx(Text,{color:e.dim,children:t.id})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" created "}),jsx(Text,{children:t.created_at.slice(0,10)})]})]})}),t.updated_at&&t.updated_at!==t.created_at&&W.push({key:"row-updated",node:jsxs(Box,{children:[jsx(Box,{width:24,children:jsxs(Text,{color:e.dim,children:[" "," "]})}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" Updated "}),jsx(Text,{children:t.updated_at.slice(0,10)})]})]})}),V.length>0){let z=[];for(let[X,_]of E)z.push(`${_} ${X}`);W.push({key:"row-tasks-summary",node:jsxs(Box,{children:[jsxs(Box,{width:24,children:[jsx(Text,{color:e.dim,children:" tasks "}),jsx(Text,{color:e.cyan,children:V.length})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" "}),jsx(Text,{color:e.dim,children:z.join(" \xB7 ")})]})]})});}if(L.length>0){W.push({key:"desc-gap",node:jsx(Text,{children:" "})});for(let z=0;z<L.length;z++)W.push({key:`desc-${z}`,node:jsxs(Text,{color:e.silver,wrap:"truncate",children:[" ",L[z]]})});}else W.push({key:"desc-gap",node:jsx(Text,{children:" "})}),W.push({key:"desc-empty",node:jsx(Text,{color:e.dim,children:" No description."})});if(O.length>0){W.push({key:"prog-gap",node:jsx(Text,{children:" "})}),W.push({key:"prog-div",node:jsx(Nn,{label:"progress",width:o})});for(let z=0;z<O.length;z++)W.push({key:`prog-${z}`,node:jsxs(Text,{color:e.white,wrap:"truncate",children:[" ",O[z]]})});}if(V.length>0){W.push({key:"tasks-gap",node:jsx(Text,{children:" "})}),W.push({key:"tasks-div",node:jsx(Nn,{label:`tasks (${V.length})`,width:o})});for(let z of V){let X=Ao[z.status]??e.dim;W.push({key:`task-${z.id}`,node:jsxs(Text,{color:e.silver,wrap:"truncate",children:[" ",jsx(Text,{color:X,children:z.status.padEnd(12)}),z.title.slice(0,Math.max(10,o-22))]})});}}return W},[t,l,p,o,r]),C=Math.max(0,y.length-n),M=Math.min(b,C);ao.useEffect(()=>{T&&M!==b&&T(M);},[M,b,T]);let A=y.length>n&&M<C,S=A?n-1:n,H=y.slice(M,M+S);return jsxs(Box,{flexDirection:"column",height:n,paddingX:2,children:[H.map(V=>jsx(Box,{children:V.node},V.key)),A&&jsxs(Text,{color:e.ghost,children:[" ","\u2193"," ",y.length-M-S," more ","\u2014"," ","\u2191","\u2193"," to scroll"]})]})}function Rc({tasks:t,selectedIndex:n,scrollOffset:o=0,height:r,width:l,showAddRow:p,agentNameMap:b,hiddenCount:T=0,goalMap:x,groupByGoal:y=false}){let C=T>0,M=C?t.length:-1,A=t.length+(C?1:0),S=t.slice(o,o+r),H=C&&M>=o&&M<o+r,V=p&&A>=o&&A<o+r,F=useMemo(()=>{if(!y||!x||x.size===0)return null;let N=new Map;for(let E of t)if(E.goalId&&x.has(E.goalId)){let W=N.get(E.goalId)??{total:0,done:0};W.total++,E.status==="done"&&W.done++,N.set(E.goalId,W);}return N},[t,y,x]),P=y&&x?t.filter(N=>!N.goalId||!x.has(N.goalId)).length:0,j=y&&x&&x.size>0&&F&&F.size>0,O=[],L=o>0?t[o-1]?.goalId??null:void 0;for(let N=0;N<S.length&&O.length<r;N++){let E=S[N],W=E.goalId&&x?.has(E.goalId)?E.goalId:null;if(j){if(W&&W!==L){let z=x.get(W),X=F.get(W)??{total:0,done:0};if(O.push(jsx(Ls,{goalTitle:z.title,taskCount:X.total,doneCount:X.done,width:l},`gh_${W}`)),O.length>=r)break}if(!W&&L!==null&&L!==void 0&&(O.push(jsx(Ps,{taskCount:P,width:l},"__ungrouped__")),O.length>=r))break}L=W,O.push(jsx(Box,{paddingX:2,children:jsx(Eo,{task:E,selected:N+o===n,width:l-2,agentNameMap:b,goalMap:x})},E.id));}return H&&O.length<r&&O.push(jsx(Box,{paddingX:2,children:jsxs(Text,{color:n===M?e.amber:e.ghost,children:[n===M?" \u25B8 ":" ",jsxs(Text,{color:n===M?e.amber:e.dim,children:["\u25BC"," Show all (",T," more) \u2014 press ",jsx(Text,{bold:true,color:e.gray,children:"S"})]})]})},"__show_all__")),V&&O.length<r&&O.push(jsx(Box,{paddingX:2,children:jsxs(Text,{color:n===A?e.amber:e.ghost,children:[n===A?" \u25B8 ":" ",jsx(Text,{color:n===A?e.amber:e.dim,children:"+ add task..."})]})},"__add__")),jsx(Box,{flexDirection:"column",height:r,children:O})}function Ac({agents:t,selectedIndex:n,scrollOffset:o=0,height:r,width:l,state:p,taskTitleMap:b,showAddRow:T,agentTeamMap:x,teamLeadSet:y,activeTeamCount:C}){let M=new Map;for(let E of Object.values(p.running))M.set(E.agent_id,E);let A=new Map;if(C&&C>0)for(let E of t){let W=x?.get(E.id);W&&A.set(W,(A.get(W)??0)+1);}let S=t.length,H=t.slice(o,o+r),V=T&&S>=o&&S<o+r,F=C!=null&&C>0,P=new Map;if(F&&y&&x){for(let E of t)if(y.has(E.id)){let W=x.get(E.id);W&&P.set(W,E.name);}}let j=0;for(let E of A.values())j+=E;let O=t.length-j,L=[],N=o>0?x?.get(t[o-1]?.id??""):void 0;for(let E=0;E<H.length&&L.length<r;E++){let W=H[E],z=x?.get(W.id);if(F&&z&&z!==N&&(L.push(jsx(Gs,{teamName:z,memberCount:A.get(z)??0,leadName:P.get(z),width:l},`ts-${z}`)),L.length>=r)||F&&!z&&N&&(L.push(jsx(Ws,{memberCount:O,width:l},"ts-unassigned")),L.length>=r))break;N=z,L.push(jsx(Box,{paddingX:2,children:jsx(Fs,{agent:W,selected:E+o===n,width:l-2,runningEntry:M.get(W.id),currentTaskTitle:W.current_task?b.get(W.current_task):void 0,teamName:z,isLead:y?.has(W.id)})},W.id));}return V&&L.length<r&&L.push(jsx(Box,{paddingX:2,children:jsxs(Text,{color:n===S?e.amber:e.ghost,children:[n===S?" \u25B8 ":" ",jsx(Text,{color:n===S?e.amber:e.dim,children:"+ add agent..."})]})},"__add__")),jsx(Box,{flexDirection:"column",height:r,children:L})}function Qi(t=5e3){let[n,o]=useState(Date.now());return useEffect(()=>{let r=setInterval(()=>o(Date.now()),t);return ()=>clearInterval(r)},[t]),n}function ea(t,n){let o=Math.max(0,n-t);return o<3e3?"now":o<6e4?`${Math.floor(o/1e3)}s`:o<36e5?`${Math.floor(o/6e4)}m`:`${Math.floor(o/36e5)}h`}function $c(t){if(t==="error")return e.errorBg}function ta(t,n){switch(t){case "output":return e.white;case "tool":return e.dim;case "result":return e.dim;case "file":return e.gray;case "error":return e.red;case "lifecycle":return e.dim;case "system":return e.dim;default:return n}}function Bc({messages:t,height:n,agents:o,logAgentFilter:r,logTypeFilter:l,selectedIndex:p,scrollOffset:b,agentNameMap:T,agentColorMap:x,agentMsgCounts:y,taskTitleMap:C,width:M}){let A=Qi(),S=useMemo(()=>t.filter(X=>{if(r.size>0&&X.agentId&&!r.has(X.agentId))return false;let _=X.msgType??"info";return l.has(_)}),[t,r,l]);useMemo(()=>{let X={};for(let _ of t){let ae=_.msgType??"info";X[ae]=(X[ae]??0)+1;}return X},[t]);let V=l.size>=8?"all":l.size===1&&l.has("output")?"text":l.size===1&&l.has("error")?"errors":l.has("tool")&&!l.has("output")?"tools":l.has("lifecycle")&&!l.has("output")?"events":`${l.size} types`,F=r.size>0,P=n-2,j=p===-1?S.slice(-P):S.slice(b,b+P),O=p===-1?-1:p-b,L=Math.min(10,Math.max(6,...o.map(X=>X.name.length))),N=11+L,E=X=>{if(X===0)return true;let _=j[X],ae=j[X-1];return _.agentId!==ae.agentId?true:_.agentId?_.ts-ae.ts>3e4:false},W=Math.max(4,Math.floor((M-20)/Math.max(1,o.length))-1),z=Math.min(W,10);return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Box,{gap:0,justifyContent:"space-between",width:M,children:[jsxs(Box,{gap:0,children:[p===-1?jsxs(Box,{gap:0,children:[jsx(Text,{backgroundColor:e.successBg,color:e.green,children:" "}),jsx(Text,{backgroundColor:e.successBg,color:e.green,children:jsx(jt,{color:e.green})}),jsx(Text,{backgroundColor:e.successBg,color:e.green,children:" LIVE "})]}):jsxs(Text,{backgroundColor:e.warnBg,color:e.amber,children:[" \u2191\u2193 ",p+1,"/",S.length," "]}),jsxs(Text,{color:e.dim,children:[" ",S.length," events"]}),V!=="all"&&jsxs(Text,{color:e.amber,children:[" f:",V]}),F&&jsxs(Text,{color:e.cyan,children:[" ",r.size,"/",o.length," agents"]})]}),jsxs(Box,{gap:0,children:[jsx(Text,{color:e.amber,bold:true,children:"a"}),jsx(Text,{color:e.dim,children:" filter "}),jsx(Text,{color:e.amber,bold:true,children:"f"}),jsx(Text,{color:e.dim,children:" type "}),jsx(Text,{color:e.amber,bold:true,children:"F"}),jsx(Text,{color:e.dim,children:" cycle"})]})]}),jsx(Box,{gap:0,children:o.map(X=>{let _=x.get(X.id)??Ur[0],ae=r.size===0||r.has(X.id),Ee=X.name.length>z?X.name.slice(0,z-1)+"\u2026":X.name;return jsxs(Text,{color:ae?_:e.ghost,bold:ae,children:[" ",Ee]},X.id)})}),j.length===0?jsxs(Box,{flexDirection:"column",paddingX:2,paddingTop:1,children:[jsx(Text,{color:e.dim,children:t.length===0?" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E":"No events for current filter."}),t.length===0&&jsxs(Fragment,{children:[jsx(Text,{color:e.dim,children:" \u2502 \u2502"}),jsxs(Text,{color:e.dim,children:[" \u2502 ",jsx(Text,{color:e.ghost,children:"\u25C7"}),jsx(Text,{color:e.gray,children:" Waiting for activity "}),"\u2502"]}),jsxs(Text,{color:e.dim,children:[" \u2502 ",jsx(Text,{color:e.ghost,children:"\u2502"}),jsx(Text,{color:e.dim,children:" Run tasks or start "}),"\u2502"]}),jsxs(Text,{color:e.dim,children:[" \u2502 ",jsx(Text,{color:e.ghost,children:"\u2502"}),jsx(Text,{color:e.dim,children:" the orchestrator "}),"\u2502"]}),jsxs(Text,{color:e.dim,children:[" \u2502 ",jsx(Text,{color:e.ghost,children:"\u25C7"}),jsx(Text,{color:e.dim,children:" "}),"\u2502"]}),jsx(Text,{color:e.dim,children:" \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"})]})]}):j.map((X,_)=>{let ae=_===O,Ee=X.msgType??"info",Ft=or[Ee]??"\u2502",dt=X.agentId?T.get(X.agentId)??X.agentId.slice(0,8):void 0,Re=X.agentId?x.get(X.agentId):void 0,Ke=E(_),pt=(_>0?j[_-1]:void 0)?.agentId===X.agentId&&!!X.agentId,De=!pt&&!!dt,Ye=pt&&!!dt,gt=ta(Ee,X.color),Ze=ae?e.infoBg:Ee==="error"?e.errorBg:void 0,on=X.taskId?C.get(X.taskId):void 0,Ce=ea(X.ts,A),ht=on&&M>80?`#${on.slice(0,20)}`:"",xt=ht?ht.length+3:0,qt=Math.max(10,M-2-N-xt),mt=rt(X.text,qt);return jsxs(Box,{backgroundColor:Ze,children:[jsx(Text,{color:Re??e.ghost,children:Ke&&De?"\u250C":Ye?"\u2502":" "}),jsx(Text,{color:ae?e.amber:void 0,children:ae?"\u25B8":" "}),jsx(Box,{width:5,children:jsx(Text,{color:Ce==="now"?e.green:ae?e.silver:e.ghost,children:Ce.padStart(4)})}),jsx(Box,{width:L+1,children:De?jsxs(Text,{color:Re,bold:true,children:[" ",dt.slice(0,L).padEnd(L)]}):Ye?jsxs(Text,{color:Re??e.ghost,children:[" ","\xB7".padEnd(L)]}):jsxs(Text,{color:e.ghost,children:[" "," ".padEnd(L)]})}),jsxs(Text,{color:Ee==="error"?e.red:Re??e.dim,children:[" ",Ft," "]}),jsx(Text,{color:ae?e.white:gt,bold:ae||Ee==="lifecycle",children:mt}),ht&&jsxs(Text,{color:e.ghost,children:[" ",jsx(Text,{color:e.dim,backgroundColor:e.void,children:` ${ht} `})]})]},_)})]})}function Ec({messages:t,height:n,width:o,agents:r,agentNameMap:l,agentColorMap:p}){let b=Qi(),T=t.slice(-n),x=Math.max(10,o-2-17),y=Math.max(0,n-T.length),C=0,M=[];for(let A=0;A<T.length;A++)A>0&&T[A].agentId!==T[A-1].agentId&&C++,M.push(C);return jsxs(Box,{flexDirection:"column",paddingX:1,children:[y>0&&jsx(Box,{height:y}),T.map((A,S)=>{let H=A.agentId?l.get(A.agentId)??A.agentId.slice(0,8):void 0,V=A.agentId?p.get(A.agentId):void 0,F=A.msgType??"info",P=or[F]??"\u2502",j=ta(F,A.color),L=(S>0?T[S-1]:void 0)?.agentId===A.agentId&&!!A.agentId,N=(M[S]&1)===1,E=$c(F)??(N?"#1a1a1a":void 0),W=ea(A.ts,b),z=rt(A.text,x);return jsxs(Box,{backgroundColor:E,children:[jsx(Text,{color:V??e.ghost,children:!L&&H?"\u258D":L?"\u258F":" "}),jsx(Box,{width:5,children:jsx(Text,{color:L?e.ghost:W==="now"?e.green:e.dim,children:L?" ":W.padStart(4)})}),jsx(Box,{width:9,children:H&&!L?jsxs(Text,{color:V,bold:true,children:[" ",H.slice(0,8)]}):jsx(Text,{color:e.ghost,children:Cc})}),jsxs(Text,{color:F==="error"?e.red:L?e.ghost:V??e.dim,children:[P," "]}),jsx(Text,{color:j,children:z})]},S)})]})}function Oc({message:t,height:n,width:o,agents:r,agentNameMap:l,agentColorMap:p,taskTitleMap:b}){let T=t.detail??t.text,x=t.msgType??"info",y=t.agentId?l.get(t.agentId)??t.agentId.slice(0,8):void 0,C=t.agentId?p.get(t.agentId):e.dim,M=t.taskId?b.get(t.taskId):void 0,A,S=false;try{let P=JSON.parse(T);A=JSON.stringify(P,null,2),S=!0;}catch{A=T;}let H=Math.max(4,o-6),V=Math.max(1,n-4),F=A.split(`
15
- `).slice(0,V);return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{children:jsxs(Text,{color:e.ghost,children:["\u256D",be(H+2),"\u256E"]})}),jsxs(Box,{children:[jsx(Text,{color:e.ghost,children:"\u2502 "}),jsx(Text,{color:e.dim,children:t.time}),jsx(Text,{color:e.ghost,children:" \u2502 "}),y&&jsx(Text,{color:C,bold:true,children:y}),y&&jsx(Text,{color:e.ghost,children:" \u2502 "}),jsxs(Text,{color:or[x]?x==="error"?e.red:e.dim:e.dim,children:[or[x]??"\u2502"," ",x]}),M&&jsxs(Fragment,{children:[jsx(Text,{color:e.ghost,children:" \u2502 "}),jsxs(Text,{color:e.dim,children:["#",M.slice(0,30)]})]})]}),jsxs(Box,{children:[jsx(Text,{color:e.ghost,children:"\u2502 "}),jsx(Text,{color:t.color,bold:true,wrap:"truncate",children:t.text.slice(0,H)})]}),jsx(Box,{children:jsxs(Text,{color:e.ghost,children:["\u251C",be(H+2),"\u2524"]})}),F.map((P,j)=>jsxs(Box,{children:[jsx(Text,{color:e.ghost,children:"\u2502 "}),S&&jsxs(Text,{color:e.ghost,children:[String(j+1).padStart(3)," "]}),jsx(Text,{wrap:"truncate",color:S&&P.includes('"')?e.cyan:S&&/^\s*[}\]]/.test(P)?e.ghost:P.startsWith("error")||P.startsWith("Error")?e.red:e.silver,children:P.slice(0,S?H-4:H)})]},j)),jsx(Box,{children:jsxs(Text,{color:e.ghost,children:["\u2570",be(H+2),"\u256F"]})})]})}function Jo({label:t,width:n,suffix:o,suffixLen:r=0}){let l=` ${t} `,p=3,b=p+l.length+2;if(!o){let y=Math.max(0,n-b);return jsxs(Box,{paddingX:1,children:[jsx(Text,{color:e.ghost,children:He(p)}),jsx(Text,{backgroundColor:"#1a1a22",color:e.dim,bold:true,children:l}),jsx(Text,{color:e.ghost,children:He(y)})]})}let T=2,x=Math.max(0,n-b-T-r);return jsxs(Box,{paddingX:1,children:[jsx(Text,{color:e.ghost,children:He(p)}),jsx(Text,{backgroundColor:"#1a1a22",color:e.dim,bold:true,children:l}),jsx(Text,{color:e.ghost,children:He(T)}),o,jsx(Text,{color:e.ghost,children:He(x)})]})}function Lc({task:t,width:n,resizeHint:o}){let r=" DETAIL ",l=o?` ${o} `:"",p=n-r.length-l.length-10,b=t.title.length>p?t.title.slice(0,p-3)+"...":t.title,T=Math.max(0,n-3-r.length-b.length-l.length-4);return jsxs(Box,{paddingX:1,children:[jsx(Text,{color:e.ghost,children:He(3)}),jsx(Text,{backgroundColor:"#2d1f0a",color:e.amber,bold:true,children:r}),jsxs(Text,{color:e.ghost,children:[Ro," "]}),jsx(Text,{color:e.white,bold:true,children:b}),jsxs(Text,{color:e.ghost,children:[" ",He(Math.max(0,T))]}),l?jsx(Text,{color:e.dim,children:l}):null]})}function Pc({agent:t,width:n,resizeHint:o}){let r=" AGENT ",l=o?` ${o} `:"",p=n-r.length-l.length-10,b=t.name.length>p?t.name.slice(0,p-3)+"...":t.name,T=Math.max(0,n-3-r.length-b.length-l.length-4);return jsxs(Box,{paddingX:1,children:[jsx(Text,{color:e.ghost,children:He(3)}),jsx(Text,{backgroundColor:"#0f2d1f",color:e.green,bold:true,children:r}),jsxs(Text,{color:e.ghost,children:[Ro," "]}),jsx(Text,{color:e.green,bold:true,children:b}),jsxs(Text,{color:e.ghost,children:[" ",He(Math.max(0,T))]}),l?jsx(Text,{color:e.dim,children:l}):null]})}function Nc({agent:t,height:n,state:o,taskTitleMap:r,teamName:l}){let p=Dc[t.status]??e.dim;Object.values(o.running).find(y=>y.agent_id===t.id);let T=t.current_task?r.get(t.current_task):void 0,x=24;return jsxs(Box,{flexDirection:"column",paddingX:2,children:[jsxs(Box,{children:[jsxs(Box,{width:x,children:[jsx(Text,{color:e.dim,children:" status "}),jsx(Text,{color:p,children:t.status})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" adapter "}),jsx(Text,{color:e.cyan,children:t.adapter})]})]}),jsxs(Box,{children:[jsxs(Box,{width:x,children:[jsx(Text,{color:e.dim,children:" model "}),jsx(Text,{children:t.config.model??"\u2014"})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" task "}),jsx(Text,{color:T?e.white:e.dim,children:T??"\u2014"})]})]}),jsxs(Box,{children:[jsxs(Box,{width:x,children:[jsx(Text,{color:e.dim,children:" runs "}),jsx(Text,{children:t.stats.total_runs}),jsx(Text,{color:e.dim,children:" ("}),jsx(Text,{color:e.green,children:t.stats.tasks_completed}),jsx(Text,{color:e.dim,children:"/"}),jsx(Text,{color:t.stats.tasks_failed>0?e.red:e.dim,children:t.stats.tasks_failed}),jsx(Text,{color:e.dim,children:")"})]}),jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" team "}),jsx(Text,{color:l?e.amber:e.dim,children:l??"\u2014"})]})]}),t.autonomous&&jsx(Box,{children:jsxs(Box,{width:x,children:[jsx(Text,{color:e.dim,children:" auto "}),jsxs(Text,{color:e.cyan,children:[mn," ON"]})]})}),t.config.skills&&t.config.skills.length>0&&jsxs(Box,{children:[jsx(Text,{color:e.dim,children:" skills "}),jsx(Text,{color:e.cyan,wrap:"truncate",children:rt(t.config.skills.join(", "),500)})]}),t.last_error&&(()=>{let y=t.last_error.kind,C=m[y],M=!C||y==="unknown",A=t.last_error.timestamp,S=A?g(A)+" ago":"";return jsxs(Fragment,{children:[jsx(Text,{children:" "}),jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:e.red,paddingX:1,children:[jsxs(Text,{color:e.red,bold:true,children:["\u26A0"," \u041E\u0448\u0438\u0431\u043A\u0430"]}),C&&jsx(Text,{color:e.white,children:C.message}),C&&jsx(Text,{color:e.cyan,children:C.fix}),C?.doctorHint&&jsx(Text,{color:e.yellow,children:"\u0414\u0438\u0430\u0433\u043D\u043E\u0441\u0442\u0438\u043A\u0430: orch doctor"}),M&&t.last_error.message&&jsx(Text,{color:e.dim,children:rt(t.last_error.message,120)}),S&&jsx(Text,{color:e.dim,children:S})]})]})})(),jsx(Text,{children:" "}),t.role?t.role.split(`
16
- `).slice(0,Math.max(1,n-(t.last_error?10:4))).map((y,C)=>jsxs(Text,{color:e.silver,wrap:"truncate",children:[" ",rt(y,500)]},C)):jsx(Text,{color:e.dim,children:" No role description."})]})}var Dc={idle:e.dim,running:e.green,error:e.red,disabled:e.ghost},Fc="\u2588";function Gc({mode:t,width:n}){let r=` ${t==="command"?"COMMAND":"NEW TASK"} `,l=Math.max(0,n-3-r.length-2);return jsxs(Box,{paddingX:1,children:[jsx(Text,{color:e.ghost,children:He(3)}),jsx(Text,{backgroundColor:"#2d1f0a",color:e.amber,bold:true,children:r}),jsx(Text,{color:e.ghost,children:He(l)})]})}function Wc({mode:t,value:n,width:o}){let r=t==="command"?"/":"\u25B8",l=Math.max(10,o-8),p=n.length>l?n.slice(-l):n;return jsxs(Box,{paddingX:2,children:[jsxs(Text,{color:e.amber,children:[r," "]}),jsx(Text,{color:e.white,children:p}),jsx(Text,{color:e.amber,children:Fc})]})}function na(t,n){if(!n||typeof n!="object")return "";let o=n;if(o.file_path&&typeof o.file_path=="string")return o.file_path.split("/").slice(-2).join("/");if(o.command&&typeof o.command=="string")return o.command.slice(0,60);if(o.pattern&&typeof o.pattern=="string")return `"${o.pattern.slice(0,40)}"`;if(o.glob&&typeof o.glob=="string")return o.glob.slice(0,40);let r=JSON.stringify(o);return r.length>80?r.slice(0,77)+"...":r}function Qo(t,n=200){if(typeof t=="string")return t.slice(0,n);if(!Array.isArray(t))return null;let o=[],r=0;for(let l of t){if(r>=n)break;if(l?.type==="text"&&typeof l.text=="string"){let p=l.text.split(`
17
- `).find(b=>b.trim().length>0)??"";o.push(p.slice(0,n-r)),r+=p.length;}else if(l?.type==="tool_use"){let p=na(l.name??"tool",l.input),b=`\u2699 ${l.name??"tool"}(${p})`;o.push(b),r+=b.length;}else if(l?.type==="tool_result")o.push("\u2190 (result)"),r+=10;else if(l?.type==="thinking"&&typeof l.thinking=="string"){let p=l.thinking.slice(0,60).split(`
18
- `)[0]??"";o.push(`\u{1F4AD} ${p}`),r+=p.length+3;}}return o.length>0?o.join(" "):null}function Ki(t){if(typeof t=="string"){let o=t.split(`
19
- `).length,r=t.split(`
20
- `).find(l=>l.trim().length>0)??"";return o>3?`${r.slice(0,80)}... (${o} lines)`:r.slice(0,120)}if(!Array.isArray(t))return "(result)";let n=[];for(let o of t)if(o?.type==="tool_result"){o.tool_use_id?o.tool_use_id.slice(0,8):"";let l=o.is_error,p=typeof o.content=="string"?o.content:"",b=p.split(`
21
- `).length;l?n.push(`\u2715 error: ${p.slice(0,60)}`):b>3?n.push(`\u2713 ${b} lines`):n.push(`\u2713 ${p.slice(0,80)}`);}else o?.type==="text"&&typeof o.text=="string"&&n.push(o.text.split(`
22
- `)[0]?.slice(0,80)??"");return n.join(" ")||"(result)"}function oa(t){let n=()=>t.length>nr?t.slice(0,nr)+"\u2026":t;if(Zi.test(t.trim()))return {summary:t.trim(),detail:n()};try{let o=JSON.parse(t);if(o.type==="message"&&o.role==="assistant"){let r=Qo(o.content);return r?{summary:r.slice(0,200),detail:n()}:{summary:null,detail:""}}if(o.type==="assistant"||o.role==="assistant"){let r=o.message?.content??o.content,l=Qo(r);return l?{summary:l.slice(0,200),detail:n()}:{summary:null,detail:""}}if(o.type==="user"||o.role==="user"){let r=o.message?.content??o.content;return {summary:`\u2190 ${Ki(r).slice(0,180)}`,detail:n()}}if(o.type==="tool_use"||typeof o.name=="string"&&"input"in o){let r=o.name??"tool",l=na(r,o.input);return {summary:`\u2699 ${r}(${l})`,detail:n()}}if(o.type==="tool_result")return {summary:`\u2190 ${Ki(o.content).slice(0,180)}`,detail:n()};if(o.type==="result"){let r=typeof o.result=="string"?o.result:null;return {summary:r?`\u2713 ${r.slice(0,180)}`:"\u2713 Agent finished",detail:n()}}if(o.type==="rate_limit_event")return {summary:`\u23F3 Rate limited (${o.rate_limit_info?.rateLimitType??"unknown"})`,detail:n()};if(o.subtype){if(o.message){let r=o.message.content??o.message,l=Qo(r);if(l)return {summary:l.slice(0,200),detail:n()}}return {summary:`[${o.subtype}]`,detail:n()}}if(o.content){let r=Qo(o.content);if(r)return {summary:r.slice(0,200),detail:n()}}return o.type?{summary:`[${o.type}]`,detail:n()}:{summary:t.slice(0,150),detail:n()}}catch{return {summary:zc(t),detail:n()}}}function zc(t){let n=t.match(/"subtype"\s*:\s*"([^"]+)"/);if(n)return `[${n[1]}]`;let o=t.match(/"type"\s*:\s*"([^"]+)"/),r=t.match(/"role"\s*:\s*"([^"]+)"/),l=o?.[1],p=r?.[1];if(!l&&!p)return t.slice(0,200);if(l==="assistant"||l==="message"||p==="assistant"){let b=t.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(b)try{return JSON.parse(`"${b[1]}"`).slice(0,200)}catch{}return "\u{1F4AC} (assistant)"}if(l==="user"||l==="tool_result"||p==="user")return "\u2190 (tool result)";if(l==="tool_use")return `\u2699 ${t.match(/"name"\s*:\s*"([^"]+)"/)?.[1]??"tool"}()`;if(l==="result"){let b=t.match(/"result"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(b)try{return `\u2713 ${JSON.parse(`"${b[1]}"`).slice(0,180)}`}catch{}return "\u2713 Agent finished"}return l==="rate_limit_event"?"\u23F3 Rate limited":`[${l??p}]`}function Vc(t,n,o,r){let l=p=>r?.get(p);switch(t.type){case "agent:started":n("Started task",e.green,{agentId:t.agentId,taskId:t.taskId,msgType:"lifecycle"});break;case "agent:output":{let{summary:p,detail:b}=oa(t.data);if(p){let T=Ji(p);n(p,T.color,{agentId:t.agentId,taskId:l(t.runId),detail:b,msgType:T.msgType});}break}case "agent:file_changed":n(`${t.path}`,e.purple,{agentId:t.agentId,taskId:l(t.runId),msgType:"file"});break;case "agent:completed":n(t.success?"Completed successfully":"Failed",t.success?e.green:e.red,{agentId:t.agentId,taskId:l(t.runId),msgType:"lifecycle"});break;case "agent:error":n(`${t.error.slice(0,150)}`,e.red,{agentId:t.agentId,taskId:l(t.runId),detail:t.error,msgType:"error"});break;case "task:status_changed":n(`${t.from} \u2192 ${t.to}`,e.cyan,{taskId:t.taskId,msgType:"system"});break;case "task:assigned":n(`Assigned \u2192 ${t.agentId}`,e.cyan,{taskId:t.taskId,msgType:"system"});break;case "task:created":n(`Created: ${t.task.title}`,e.amber,{taskId:t.task.id,msgType:"system"});break;case "run:retry":n(`Retry #${t.attempt} (${Math.round(t.delay_ms/1e3)}s delay)`,e.yellow,{agentId:o?.get(t.runId),taskId:l(t.runId),msgType:"lifecycle"});break;case "orchestrator:tick":(t.running>0||t.queued>0)&&n(`${t.running} running \xB7 ${t.queued} queued`,e.ghost,{msgType:"system"});break;case "orchestrator:stall_detected":n("Stall detected",e.yellow,{agentId:o?.get(t.runId),taskId:l(t.runId),msgType:"error"});break;case "task:cascade_failed":n(`Cascade failed (dep: ${t.failedDependencyId})`,e.red,{taskId:t.taskId,detail:t.reason,msgType:"error"});break}}export{rg as App,og as _resetPendingDeletionSeq};
@@ -1,9 +0,0 @@
1
- #!/usr/bin/env node
2
- import {j,o,l,q,d,h,m}from'./chunk-64WUDYEM.js';function T(y,n){let l$1=y.command("agent").description("Manage agents");l$1.command("add <name>").description("Add a new agent").requiredOption("--adapter <adapter>","Adapter type: claude, opencode, codex, cursor, shell").option("--role <role>","Agent role description").option("--command <cmd>","Shell command (for shell adapter)").option("--model <model>","Model name (for AI adapters)").option("--effort <level>","Reasoning effort: low, medium, high").option("--max-turns <n>","Max turns per run").option("--timeout <ms>","Timeout in ms").option("--approval-policy <policy>","suggest|auto|manual").option("--workspace-mode <mode>","shared|worktree|isolated").option("--skills <skills>","Comma-separated list of agent skills").option("-e, --edit","Open $EDITOR to write the role description").action(async(o$1,e)=>{let i=e.role;if(e.edit){let{openInEditor:t,agentToEditorContent:s,agentFromEditorContent:u}=await import('./editor-7IFRWVTL.js'),g=s({name:o$1,model:e.model,role:i}),d=await t(g),c=u(d);c.name&&(o$1=c.name),c.model&&(e.model=c.model),c.role&&(i=c.role);}let a=await n.agentService.create({name:o$1,adapter:e.adapter,role:i,command:e.command,model:e.model,effort:e.effort,max_turns:e.maxTurns?parseInt(e.maxTurns,10):void 0,timeout_ms:e.timeout?parseInt(e.timeout,10):void 0,approval_policy:e.approvalPolicy,workspace_mode:e.workspaceMode,skills:e.skills?e.skills.split(",").map(t=>t.trim()):void 0});n.context.json?console.log(JSON.stringify(a,null,2)):n.context.quiet?console.log(a.id):j(`Added agent ${o(a.name)} (${a.adapter}) \u2192 ${a.id}`);}),l$1.command("shop").description("Browse and install pre-built agent templates").option("--list","Print all templates (non-interactive)").action(async o$1=>{let{AGENT_SHOP_TEMPLATES:e}=await import('./agent-shop-JHDTCWCD.js');if(o$1.list||!process.stdout.isTTY){l(["Key","Name","Adapter","Model","Skills"],e.map(s=>[s.key,s.name,s.adapter,s.model.replace("claude-",""),s.skills.slice(0,2).join(", ")]));return}let{pickFromShop:i}=await import('./shop-picker-LE3SKFOX.js'),a=await i(e);if(!a){console.log(" Cancelled.");return}let t=await n.agentService.create({name:a.name,adapter:a.adapter,model:a.model,role:a.role,skills:a.skills,approval_policy:a.approval_policy});j(`Added agent ${o(t.name)} (${t.adapter}) \u2192 ${t.id}`);}),l$1.command("list").description("List all agents").action(async()=>{let o$1=await n.agentService.list();if(n.context.json){console.log(JSON.stringify(o$1,null,2));return}if(n.context.quiet){o$1.forEach(t=>console.log(t.id));return}if(o$1.length===0){console.log(`
3
- No agents. Add one: ${q("orch agent add <name> --adapter claude")}
4
- `);return}let e=["STATUS","AGENT","ADAPTER","TASK","TIME"],i=o$1.map(t=>[`${d(t.status)} ${t.status}`,o(t.name),t.adapter,t.current_task??q("\u2014"),q("\u2014")]);console.log(),l(e,i);let a=o$1.filter(t=>t.status==="running").length;console.log(`
5
- ${o$1.length} agents \xB7 ${a} running \xB7 ${h(o$1.reduce((t,s)=>t+(s.stats.tokens_used??0),0))} tokens total
6
- `);}),l$1.command("status <id>").description("Show agent details").action(async o=>{let e=await n.agentService.get(o);if(n.context.json){console.log(JSON.stringify(e,null,2));return}console.log(`
7
- ${e.name}`),console.log(` ${"\u2550".repeat(42)}`),console.log();let i=[["Adapter",`${e.adapter}${e.config.model?` (${e.config.model})`:""}`],["Status",`${d(e.status)} ${e.status}`],["Effort",e.config.effort??"default"],["Policy",e.config.approval_policy??"auto"]];e.current_task&&i.push(["Task",e.current_task]),e.role&&i.push(["Role",e.role]),e.config.skills?.length&&i.push(["Skills",e.config.skills.join(", ")]),m(i),console.log(`
8
- Stats
9
- ${"\u2500".repeat(42)}`),m([["Tasks completed",String(e.stats.tasks_completed)],["Tasks failed",String(e.stats.tasks_failed)],["Total runs",String(e.stats.total_runs)],["Tokens used",h(e.stats.tokens_used??0)]]),console.log();}),l$1.command("edit <id>").description("Edit an agent in $EDITOR").action(async o$1=>{let e=await n.agentService.get(o$1),{openInEditor:i,agentToEditorContent:a,agentFromEditorContent:t}=await import('./editor-7IFRWVTL.js'),s=a({name:e.name,model:e.config.model,role:e.role}),u=await i(s),g=t(u),d=await n.agentService.update(o$1,{name:g.name,role:g.role,model:g.model});n.context.json?console.log(JSON.stringify(d,null,2)):n.context.quiet?console.log(d.id):j(`Updated agent ${o(d.name)} (${d.id})`);}),l$1.command("remove <id>").description("Remove an agent").action(async o=>{await n.agentService.remove(o),j(`Removed agent ${o}`);}),l$1.command("disable <id>").description("Disable an agent").action(async o=>{await n.agentService.disable(o),j(`Disabled agent ${o}`);}),l$1.command("enable <id>").description("Enable an agent").action(async o=>{await n.agentService.enable(o),j(`Enabled agent ${o}`);}),l$1.command("autonomous <id>").description("Toggle autonomous mode for an agent").option("--on","Enable autonomous mode").option("--off","Disable autonomous mode").action(async(o$1,e)=>{let i=await n.agentService.get(o$1),a=e.on?true:e.off?false:!i.autonomous,t=await n.agentService.setAutonomous(o$1,a);n.context.json?console.log(JSON.stringify(t,null,2)):n.context.quiet?console.log(t.id):j(`Autonomous mode ${a?"enabled":"disabled"} for agent ${o(t.name)} (${t.id})`);});}export{T as registerAgentCommand};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a}from'./chunk-P4JTJBWO.js';import {n}from'./chunk-IKNBPOQL.js';import {b as b$1}from'./chunk-6MJ7V6VY.js';function b(n,s){return n?n+`
3
-
4
- `+s:s}function y(n,s){let e=n.usage;if(!e&&s?.statsFallback&&(e=n.stats?.usage),e&&typeof e.input_tokens=="number"){let i=e.input_tokens,u=typeof e.output_tokens=="number"?e.output_tokens:0,a$1=typeof e.reasoning_tokens=="number"?e.reasoning_tokens:0,o=typeof e.cache_read_input_tokens=="number"?e.cache_read_input_tokens:0,c=typeof e.cache_creation_input_tokens=="number"?e.cache_creation_input_tokens:0;return a(i,u,{reasoning:a$1,cache_read:o,cache_write:c})}}function w(n$1,s,e,i){async function*u(){let a=false,o=null,c=null,g=new Promise(r=>{n$1.on("close",t=>{o=t,r();}),n$1.on("error",t=>{c=t,r();});});if(n$1.stdout)try{for await(let r of b$1(n$1.stdout)){if(i?.aborted)break;let t=s(r);t&&(t.type==="done"&&(a=!0),yield t);}}finally{n$1.stdout.destroy();}if(await g,c&&!i?.aborted&&!a){let r=c,t=n(r.message,o??void 0);throw Object.assign(new Error(r.message),{errorKind:t})}if(o!==0&&o!==null&&!i?.aborted&&!a){let r=`${e} process exited with code ${o}`,t=n(r,o);throw Object.assign(new Error(r),{errorKind:t})}}return u()}export{b as a,y as b,w as c};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- var n=class extends Error{constructor(r,s,x){super(r);this.exitCode=s;this.hint=x;this.name="OrchestryError";}},o=class extends n{constructor(){super("Not initialized",3,"Run: orch init"),this.name="NotInitializedError";}},i=class extends n{constructor(e){super(e,2),this.name="InvalidArgumentsError";}},a=class extends n{constructor(e){super(`Orchestrator already running (PID: ${e})`,4,"Use: orch status"),this.name="LockConflictError";}};var u=class extends n{constructor(){super("No agents configured",1,"Run: orch agent add <name> --adapter claude"),this.name="NoAgentsError";}},c=class extends n{constructor(e){super(`Task not found: ${e}`,1),this.name="TaskNotFoundError";}},d=class extends n{constructor(e){super(`Agent not found: ${e}`,1),this.name="AgentNotFoundError";}},l=class extends n{constructor(e,r,s){super(`Task ${e} is already running (run: ${r}, agent: ${s})`,1,`Use: orch logs --task ${e} --follow`),this.name="TaskAlreadyRunningError";}},p=class extends n{constructor(e,r,s){super(`Invalid transition for ${e}: ${r} \u2192 ${s}`,1),this.name="InvalidTransitionError";}},g=class extends n{constructor(e){super(`Goal not found: ${e}`,1),this.name="GoalNotFoundError";}},A=class extends n{constructor(e){super(`Team not found: ${e}`,1),this.name="TeamNotFoundError";}};var m=class extends n{constructor(e,r){super(e,6,r),this.name="WorkspaceError";}};var f={adapter_not_found:{message:"CLI \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D.",fix:"\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435: npm i -g @anthropic-ai/claude-code",doctorHint:true},auth_failed:{message:"API \u043A\u043B\u044E\u0447 \u043D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D.",fix:"\u041F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435: claude auth status"},timeout:{message:"\u0410\u0433\u0435\u043D\u0442 \u043F\u0440\u0435\u0432\u044B\u0441\u0438\u043B \u043B\u0438\u043C\u0438\u0442 \u0432\u0440\u0435\u043C\u0435\u043D\u0438.",fix:"\u0423\u0432\u0435\u043B\u0438\u0447\u044C\u0442\u0435 \u0447\u0435\u0440\u0435\u0437: orch config set agent_timeout <ms>"},rate_limit:{message:"\u0414\u043E\u0441\u0442\u0438\u0433\u043D\u0443\u0442 \u043B\u0438\u043C\u0438\u0442 API.",fix:"\u041F\u043E\u0434\u043E\u0436\u0434\u0438\u0442\u0435 \u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0435: orch task retry <id>"},process_crash:{message:"\u041F\u0440\u043E\u0446\u0435\u0441\u0441 \u0430\u0433\u0435\u043D\u0442\u0430 \u0443\u043F\u0430\u043B.",fix:"\u041F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435: orch task retry <id>"},spawn_failed:{message:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u043F\u0440\u043E\u0446\u0435\u0441\u0441.",fix:"\u041F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 PATH \u0438 \u043F\u0440\u0430\u0432\u0430 \u0434\u043E\u0441\u0442\u0443\u043F\u0430"},unknown:{message:"\u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430.",fix:"\u0417\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435: orch doctor",doctorHint:true}};function h(t,e){let r=t.toLowerCase();return r.includes("enoent")||r.includes("spawn failed")?"spawn_failed":r.includes("not found")||r.includes("command not found")||r.includes("no such file")?"adapter_not_found":r.includes("auth")||r.includes("unauthorized")||r.includes("401")||r.includes("invalid api key")||r.includes("authentication")?"auth_failed":r.includes("timeout")||r.includes("timed out")||r.includes("etimedout")?"timeout":r.includes("rate limit")||r.includes("429")||r.includes("too many requests")?"rate_limit":e!==void 0&&e!==0?"process_crash":"unknown"}export{n as a,o as b,i as c,a as d,u as e,c as f,d as g,l as h,p as i,g as j,A as k,m as l,f as m,h as n};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a}from'./chunk-FQ5YUP4J.js';import {n}from'./chunk-IKNBPOQL.js';import {b}from'./chunk-6MJ7V6VY.js';import {execFile}from'child_process';import {promisify}from'util';function m(){let n;return {promise:new Promise(t=>{n=t;}),resolve:n}}var o=class{buf;head=0;tail=0;count=0;capacity;dataReady=null;spaceReady=null;closed=false;constructor(e=1024){this.capacity=e,this.buf=new Array(e);}get size(){return this.count}get isFull(){return this.count>=this.capacity}async push(e){for(;this.isFull&&!this.closed;)this.spaceReady||(this.spaceReady=m()),await this.spaceReady.promise;if(!this.closed&&(this.buf[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.count++,this.dataReady)){let t=this.dataReady;this.dataReady=null,t.resolve();}}async take(){for(;this.count===0;){if(this.closed)return;this.dataReady||(this.dataReady=m()),await this.dataReady.promise;}let e=this.buf[this.head];if(this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.count--,this.spaceReady){let t=this.spaceReady;this.spaceReady=null,t.resolve();}return e}close(){if(this.closed=true,this.dataReady){let e=this.dataReady;this.dataReady=null,e.resolve();}if(this.spaceReady){let e=this.spaceReady;this.spaceReady=null,e.resolve();}}get isClosed(){return this.closed}async*[Symbol.asyncIterator](){for(;;){let e=await this.take();if(e===void 0)return;yield e;}}};var E=promisify(execFile),y=class{constructor(e){this.processManager=e;}kind="shell";async test(){try{let{stdout:e}=await E("bash",["--version"]);return {ok:!0,version:e.split(`
3
- `)[0]?.trim()??"unknown"}}catch{return {ok:false,error:"bash not found",errorKind:n("bash not found")}}}execute(e){let t=e.config.command;if(!t){async function*i(){yield {type:"error",timestamp:new Date().toISOString(),data:"Shell adapter requires a command in agent config",errorKind:"spawn_failed"};}return {pid:0,events:i()}}let{process:s,pid:u}=this.processManager.spawn("bash",["-lc",t],{cwd:e.workspace,env:{...process.env,...e.env,ORCHESTRY_TASK_PROMPT:a(e.systemPrompt,e.prompt)},signal:e.signal}),r=e.signal,v=this.processManager;async function*g(){let i=new o,d=()=>{v.killWithGrace(u,5e3).catch(()=>{});};r&&(r.aborted?d():r.addEventListener("abort",d,{once:true}));let A=(async()=>{if(s.stdout)for await(let a of b(s.stdout)){if(r?.aborted)break;await i.push({type:"output",timestamp:new Date().toISOString(),data:a});}})(),b$1=(async()=>{if(s.stderr)for await(let a of b(s.stderr)){if(r?.aborted)break;await i.push({type:"error",timestamp:new Date().toISOString(),data:a,errorKind:n(a)});}})();Promise.all([A,b$1]).then(()=>i.close(),()=>i.close()),yield*i,r&&!r.aborted&&r.removeEventListener("abort",d),await new Promise((a,p)=>{if(s.exitCode!==null||s.killed){a();return}s.on("close",h=>{h===0||r?.aborted?a():p(new Error(`Shell command exited with code ${h}`));}),s.on("error",p);});}return {pid:u,events:g()}}async stop(e){await this.processManager.killWithGrace(e);}};export{y as a};
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/domain/errors.ts"],"names":["AdapterErrorKind"],"mappings":";AAeO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EACxC,WAAA,CACE,OAAA,EACgB,QAAA,EACA,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AAAA,EACd;AACF;AAEO,IAAM,mBAAA,GAAN,cAAkC,cAAA,CAAe;AAAA,EACtD,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM,iBAAA,EAAmB,GAAG,gBAAgB,CAAA;AAC5C,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAEO,IAAM,qBAAA,GAAN,cAAoC,cAAA,CAAe;AAAA,EACxD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,SAAS,CAAC,CAAA;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF;AAEO,IAAM,iBAAA,GAAN,cAAgC,cAAA,CAAe;AAAA,EACpD,YAAY,GAAA,EAAa;AACvB,IAAA,KAAA,CAAM,CAAA,mCAAA,EAAsC,GAAG,CAAA,CAAA,CAAA,EAAK,CAAA,EAAG,kBAAkB,CAAA;AACzE,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AAAA,EACd;AACF;AASO,IAAM,aAAA,GAAN,cAA4B,cAAA,CAAe;AAAA,EAChD,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM,sBAAA,EAAwB,GAAG,6CAA6C,CAAA;AAC9E,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF;AAEO,IAAM,iBAAA,GAAN,cAAgC,cAAA,CAAe;AAAA,EACpD,YAAY,MAAA,EAAgB;AAC1B,IAAA,KAAA,CAAM,CAAA,gBAAA,EAAmB,MAAM,CAAA,CAAA,EAAI,CAAC,CAAA;AACpC,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AAAA,EACd;AACF;AAEO,IAAM,kBAAA,GAAN,cAAiC,cAAA,CAAe;AAAA,EACrD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,CAAA,iBAAA,EAAoB,OAAO,CAAA,CAAA,EAAI,CAAC,CAAA;AACtC,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF;AAEO,IAAM,uBAAA,GAAN,cAAsC,cAAA,CAAe;AAAA,EAC1D,WAAA,CAAY,MAAA,EAAgB,KAAA,EAAe,SAAA,EAAmB;AAC5D,IAAA,KAAA;AAAA,MACE,CAAA,KAAA,EAAQ,MAAM,CAAA,0BAAA,EAA6B,KAAK,YAAY,SAAS,CAAA,CAAA,CAAA;AAAA,MACrE,CAAA;AAAA,MACA,yBAAyB,MAAM,CAAA,SAAA;AAAA,KACjC;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF;AAEO,IAAM,sBAAA,GAAN,cAAqC,cAAA,CAAe;AAAA,EACzD,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAc,EAAA,EAAY;AACpD,IAAA,KAAA,CAAM,0BAA0B,MAAM,CAAA,EAAA,EAAK,IAAI,CAAA,QAAA,EAAM,EAAE,IAAI,CAAC,CAAA;AAC5D,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AAEO,IAAM,iBAAA,GAAN,cAAgC,cAAA,CAAe;AAAA,EACpD,YAAY,MAAA,EAAgB;AAC1B,IAAA,KAAA,CAAM,CAAA,gBAAA,EAAmB,MAAM,CAAA,CAAA,EAAI,CAAC,CAAA;AACpC,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AAAA,EACd;AACF;AAEO,IAAM,iBAAA,GAAN,cAAgC,cAAA,CAAe;AAAA,EACpD,YAAY,MAAA,EAAgB;AAC1B,IAAA,KAAA,CAAM,CAAA,gBAAA,EAAmB,MAAM,CAAA,CAAA,EAAI,CAAC,CAAA;AACpC,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AAAA,EACd;AACF;AASO,IAAM,cAAA,GAAN,cAA6B,cAAA,CAAe;AAAA,EACjD,WAAA,CAAY,SAAiB,IAAA,EAAe;AAC1C,IAAA,KAAA,CAAM,OAAA,EAAS,GAAG,IAAI,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AAAA,EACd;AACF;AAIO,IAAK,gBAAA,qBAAAA,iBAAAA,KAAL;AACL,EAAAA,kBAAA,mBAAA,CAAA,GAAoB,mBAAA;AACpB,EAAAA,kBAAA,aAAA,CAAA,GAAc,aAAA;AACd,EAAAA,kBAAA,SAAA,CAAA,GAAU,SAAA;AACV,EAAAA,kBAAA,YAAA,CAAA,GAAa,YAAA;AACb,EAAAA,kBAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,EAAAA,kBAAA,cAAA,CAAA,GAAe,cAAA;AACf,EAAAA,kBAAA,SAAA,CAAA,GAAU,SAAA;AAPA,EAAA,OAAAA,iBAAAA;AAAA,CAAA,EAAA,gBAAA,IAAA,EAAA;AAgBL,IAAM,WAAA,GAA0D;AAAA,EACrE,CAAC,8CAAqC;AAAA,IACpC,OAAA,EAAS,gFAAA;AAAA,IACT,GAAA,EAAK,kGAAA;AAAA,IACL,UAAA,EAAY;AAAA,GACd;AAAA,EACA,CAAC,kCAA+B;AAAA,IAC9B,OAAA,EAAS,sFAAA;AAAA,IACT,GAAA,EAAK;AAAA,GACP;AAAA,EACA,CAAC,0BAA2B;AAAA,IAC1B,OAAA,EAAS,4JAAA;AAAA,IACT,GAAA,EAAK;AAAA,GACP;AAAA,EACA,CAAC,gCAA8B;AAAA,IAC7B,OAAA,EAAS,4FAAA;AAAA,IACT,GAAA,EAAK;AAAA,GACP;AAAA,EACA,CAAC,sCAAiC;AAAA,IAChC,OAAA,EAAS,2GAAA;AAAA,IACT,GAAA,EAAK;AAAA,GACP;AAAA,EACA,CAAC,oCAAgC;AAAA,IAC/B,OAAA,EAAS,4JAAA;AAAA,IACT,GAAA,EAAK;AAAA,GACP;AAAA,EACA,CAAC,0BAA2B;AAAA,IAC1B,OAAA,EAAS,0GAAA;AAAA,IACT,GAAA,EAAK,qEAAA;AAAA,IACL,UAAA,EAAY;AAAA;AAEhB;AAEO,SAAS,oBAAA,CAAqB,OAAe,QAAA,EAAqC;AACvF,EAAA,MAAM,KAAA,GAAQ,MAAM,WAAA,EAAY;AAEhC,EAAA,IAAI,MAAM,QAAA,CAAS,QAAQ,KAAK,KAAA,CAAM,QAAA,CAAS,cAAc,CAAA,EAAG;AAC9D,IAAA,OAAO,cAAA;AAAA,EACT;AACA,EAAA,IAAI,KAAA,CAAM,QAAA,CAAS,WAAW,CAAA,IAAK,KAAA,CAAM,QAAA,CAAS,mBAAmB,CAAA,IAAK,KAAA,CAAM,QAAA,CAAS,cAAc,CAAA,EAAG;AACxG,IAAA,OAAO,mBAAA;AAAA,EACT;AACA,EAAA,IAAI,MAAM,QAAA,CAAS,MAAM,KAAK,KAAA,CAAM,QAAA,CAAS,cAAc,CAAA,IAAK,KAAA,CAAM,SAAS,KAAK,CAAA,IAAK,MAAM,QAAA,CAAS,iBAAiB,KAAK,KAAA,CAAM,QAAA,CAAS,gBAAgB,CAAA,EAAG;AAC9J,IAAA,OAAO,aAAA;AAAA,EACT;AACA,EAAA,IAAI,KAAA,CAAM,QAAA,CAAS,SAAS,CAAA,IAAK,KAAA,CAAM,QAAA,CAAS,WAAW,CAAA,IAAK,KAAA,CAAM,QAAA,CAAS,WAAW,CAAA,EAAG;AAC3F,IAAA,OAAO,SAAA;AAAA,EACT;AACA,EAAA,IAAI,KAAA,CAAM,QAAA,CAAS,YAAY,CAAA,IAAK,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,CAAS,mBAAmB,CAAA,EAAG;AAChG,IAAA,OAAO,YAAA;AAAA,EACT;AACA,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,QAAA,KAAa,CAAA,EAAG;AAC5C,IAAA,OAAO,eAAA;AAAA,EACT;AAEA,EAAA,OAAO,SAAA;AACT","file":"chunk-NLQAJ7TW.js","sourcesContent":["/**\n * Typed error hierarchy for the orchestrator.\n *\n * Every error carries an exit code (matching CLI_UI_DESIGN.md §11)\n * and an optional hint for the user.\n *\n * Exit codes:\n * 0 - Success\n * 1 - General error\n * 2 - Invalid arguments\n * 3 - Not initialized (.orchestry/ not found)\n * 4 - Lock conflict (orchestrator already running)\n * 5 - Agent error (adapter test failed)\n */\n\nexport class OrchestryError extends Error {\n constructor(\n message: string,\n public readonly exitCode: number,\n public readonly hint?: string,\n ) {\n super(message);\n this.name = 'OrchestryError';\n }\n}\n\nexport class NotInitializedError extends OrchestryError {\n constructor() {\n super('Not initialized', 3, 'Run: orch init');\n this.name = 'NotInitializedError';\n }\n}\n\nexport class InvalidArgumentsError extends OrchestryError {\n constructor(message: string) {\n super(message, 2);\n this.name = 'InvalidArgumentsError';\n }\n}\n\nexport class LockConflictError extends OrchestryError {\n constructor(pid: number) {\n super(`Orchestrator already running (PID: ${pid})`, 4, 'Use: orch status');\n this.name = 'LockConflictError';\n }\n}\n\nexport class AgentAdapterError extends OrchestryError {\n constructor(adapter: string, detail: string) {\n super(`Agent adapter \"${adapter}\" not available`, 5, detail);\n this.name = 'AgentAdapterError';\n }\n}\n\nexport class NoAgentsError extends OrchestryError {\n constructor() {\n super('No agents configured', 1, 'Run: orch agent add <name> --adapter claude');\n this.name = 'NoAgentsError';\n }\n}\n\nexport class TaskNotFoundError extends OrchestryError {\n constructor(taskId: string) {\n super(`Task not found: ${taskId}`, 1);\n this.name = 'TaskNotFoundError';\n }\n}\n\nexport class AgentNotFoundError extends OrchestryError {\n constructor(agentId: string) {\n super(`Agent not found: ${agentId}`, 1);\n this.name = 'AgentNotFoundError';\n }\n}\n\nexport class TaskAlreadyRunningError extends OrchestryError {\n constructor(taskId: string, runId: string, agentName: string) {\n super(\n `Task ${taskId} is already running (run: ${runId}, agent: ${agentName})`,\n 1,\n `Use: orch logs --task ${taskId} --follow`,\n );\n this.name = 'TaskAlreadyRunningError';\n }\n}\n\nexport class InvalidTransitionError extends OrchestryError {\n constructor(taskId: string, from: string, to: string) {\n super(`Invalid transition for ${taskId}: ${from} → ${to}`, 1);\n this.name = 'InvalidTransitionError';\n }\n}\n\nexport class GoalNotFoundError extends OrchestryError {\n constructor(goalId: string) {\n super(`Goal not found: ${goalId}`, 1);\n this.name = 'GoalNotFoundError';\n }\n}\n\nexport class TeamNotFoundError extends OrchestryError {\n constructor(teamId: string) {\n super(`Team not found: ${teamId}`, 1);\n this.name = 'TeamNotFoundError';\n }\n}\n\nexport class MessageNotFoundError extends OrchestryError {\n constructor(messageId: string) {\n super(`Message not found: ${messageId}`, 1);\n this.name = 'MessageNotFoundError';\n }\n}\n\nexport class WorkspaceError extends OrchestryError {\n constructor(message: string, hint?: string) {\n super(message, 6, hint);\n this.name = 'WorkspaceError';\n }\n}\n\n// ── Adapter Error Classification ──────────────────────────────────\n\nexport enum AdapterErrorKind {\n ADAPTER_NOT_FOUND = 'adapter_not_found',\n AUTH_FAILED = 'auth_failed',\n TIMEOUT = 'timeout',\n RATE_LIMIT = 'rate_limit',\n PROCESS_CRASH = 'process_crash',\n SPAWN_FAILED = 'spawn_failed',\n UNKNOWN = 'unknown',\n}\n\nexport interface AdapterErrorHint {\n message: string;\n fix: string;\n doctorHint?: boolean;\n}\n\nexport const ERROR_HINTS: Record<AdapterErrorKind, AdapterErrorHint> = {\n [AdapterErrorKind.ADAPTER_NOT_FOUND]: {\n message: 'CLI не установлен.',\n fix: 'Установите: npm i -g @anthropic-ai/claude-code',\n doctorHint: true,\n },\n [AdapterErrorKind.AUTH_FAILED]: {\n message: 'API ключ невалиден.',\n fix: 'Проверьте: claude auth status',\n },\n [AdapterErrorKind.TIMEOUT]: {\n message: 'Агент превысил лимит времени.',\n fix: 'Увеличьте через: orch config set agent_timeout <ms>',\n },\n [AdapterErrorKind.RATE_LIMIT]: {\n message: 'Достигнут лимит API.',\n fix: 'Подождите и повторите: orch task retry <id>',\n },\n [AdapterErrorKind.PROCESS_CRASH]: {\n message: 'Процесс агента упал.',\n fix: 'Попробуйте: orch task retry <id>',\n },\n [AdapterErrorKind.SPAWN_FAILED]: {\n message: 'Не удалось запустить процесс.',\n fix: 'Проверьте PATH и права доступа',\n },\n [AdapterErrorKind.UNKNOWN]: {\n message: 'Неизвестная ошибка.',\n fix: 'Запустите: orch doctor',\n doctorHint: true,\n },\n};\n\nexport function classifyAdapterError(error: string, exitCode?: number): AdapterErrorKind {\n const lower = error.toLowerCase();\n\n if (lower.includes('enoent') || lower.includes('spawn failed')) {\n return AdapterErrorKind.SPAWN_FAILED;\n }\n if (lower.includes('not found') || lower.includes('command not found') || lower.includes('no such file')) {\n return AdapterErrorKind.ADAPTER_NOT_FOUND;\n }\n if (lower.includes('auth') || lower.includes('unauthorized') || lower.includes('401') || lower.includes('invalid api key') || lower.includes('authentication')) {\n return AdapterErrorKind.AUTH_FAILED;\n }\n if (lower.includes('timeout') || lower.includes('timed out') || lower.includes('etimedout')) {\n return AdapterErrorKind.TIMEOUT;\n }\n if (lower.includes('rate limit') || lower.includes('429') || lower.includes('too many requests')) {\n return AdapterErrorKind.RATE_LIMIT;\n }\n if (exitCode !== undefined && exitCode !== 0) {\n return AdapterErrorKind.PROCESS_CRASH;\n }\n\n return AdapterErrorKind.UNKNOWN;\n}\n"]}
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{a as ClaudeAdapter}from'./chunk-JM2WRI46.js';import'./chunk-FQ5YUP4J.js';import'./chunk-P4JTJBWO.js';import'./chunk-IKNBPOQL.js';import'./chunk-6MJ7V6VY.js';
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a,c,b}from'./chunk-FQ5YUP4J.js';import'./chunk-P4JTJBWO.js';import {n}from'./chunk-IKNBPOQL.js';import'./chunk-6MJ7V6VY.js';import {execFile}from'child_process';import {promisify}from'util';var f=promisify(execFile),g=class{constructor(e){this.processManager=e;}kind="codex";async test(){try{let{stdout:e}=await f("codex",["--version"]);return {ok:!0,version:e.trim()}}catch(e){let r=e instanceof Error?e.message:String(e);return {ok:false,error:"Codex CLI not found. Install: npm i -g @openai/codex",errorKind:n(r)}}}execute(e){let r=["exec","--json","--sandbox","danger-full-access"];e.config.model&&r.push("--model",e.config.model),r.push("-");let{process:s,pid:t}=this.processManager.spawn("codex",r,{cwd:e.workspace,env:{...process.env,...e.env},signal:e.signal,stdio:["pipe","pipe","pipe"]});s.stdin&&(s.stdin.write(a(e.systemPrompt,e.prompt)),s.stdin.end());let n=c(s,h,"Codex",e.signal);return {pid:t,events:n}}async stop(e){await this.processManager.killWithGrace(e);}};function h(a){if(!a.trim())return null;try{let e=JSON.parse(a),r=new Date().toISOString();switch(e.type??""){case "thread.started":return {type:"output",timestamp:r,data:e};case "turn.started":return {type:"output",timestamp:r,data:e};case "turn.completed":{let t=b(e);return {type:"done",timestamp:r,data:e,tokens:t}}case "turn.failed":{let t=b(e),n$1=typeof e.error=="string"?e.error:JSON.stringify(e);return {type:"error",timestamp:r,data:e,tokens:t,errorKind:n(n$1)}}case "item.started":case "item.completed":{let t=e.item??{},n$1=t.type??"";if(n$1==="agent_message")return {type:"output",timestamp:r,data:t};if(n$1==="reasoning")return {type:"output",timestamp:r,data:t};if(n$1==="command_execution")return {type:"command",timestamp:r,data:t};if(n$1==="file_change"){let m=(Array.isArray(t.changes)?t.changes:[]).map(p=>typeof p.path=="string"?p.path:"").filter(Boolean);return {type:"file_change",timestamp:r,data:{paths:m,raw:t}}}if(n$1==="tool_use")return {type:"tool_call",timestamp:r,data:t};if(n$1==="tool_result")return {type:"output",timestamp:r,data:t};if(n$1==="error"){let c=typeof t.message=="string"?t.message:JSON.stringify(t);return {type:"error",timestamp:r,data:t,errorKind:n(c)}}return {type:"output",timestamp:r,data:t}}case "error":{let t=e.error??e,n$1=typeof t=="string"?t:JSON.stringify(t);return {type:"error",timestamp:r,data:t,errorKind:n(n$1)}}default:return {type:"output",timestamp:r,data:e}}}catch{return {type:"output",timestamp:new Date().toISOString(),data:a}}}export{g as CodexAdapter};