@stackone/cli 1.44.2 → 1.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,33 +1,33 @@
1
- import{n as e}from"./fileNames-DzZBY06N.mjs";import{C as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,u as ee,v,w as y,x as b,y as x}from"./agentConfig-BWQWMYKQ.mjs";import{r as S,t as C}from"./setupMigration-C1ShGzOu.mjs";import{r as te}from"./agentApiKey-CWXxJgCO.mjs";import{createRequire as w}from"node:module";import T from"chalk";import{Argument as E,Command as ne}from"commander";import{BuildOrchestrator as D,checkCommandSafety as re,createAgentSession as ie,createDefaultVisualizationRegistry as ae,createSkillTracker as O,executeAgent as oe,extractBuildIntent as se,getAvailableSkillNames as k,getBundledSkillsPath as A,getSkillsForMode as j,initAgentTelemetry as ce}from"@stackone/agent-harness";import*as M from"node:fs";import{cpSync as le,existsSync as N,mkdirSync as ue,readFileSync as de,readdirSync as P,rmSync as fe,statSync as pe,writeFileSync as me}from"node:fs";import*as F from"node:os";import{homedir as I,platform as he}from"node:os";import*as L from"node:path";import{dirname as ge,join as R,resolve as _e,sep as ve}from"node:path";import{Box as z,Text as B,render as ye,useApp as be,useInput as xe}from"ink";import V,{useCallback as Se,useEffect as H,useMemo as Ce,useRef as U,useState as W}from"react";import{exec as we,execFile as Te,execFileSync as Ee,execSync as De}from"node:child_process";import Oe from"ink-spinner";import G,{readFileSync as ke,readdirSync as Ae,statSync as K,writeFileSync as je}from"fs";import Me,{basename as Ne,dirname as Pe,join as Fe,resolve as Ie}from"path";import{fileURLToPath as Le}from"url";import q from"ora";import{access as Re}from"node:fs/promises";import ze from"inquirer";import{stdin as Be,stdout as Ve}from"node:process";import{createInterface as He}from"node:readline";import{isMissing as J,isObject as Ue,notMissing as Y,z as X}from"@stackone/utils";import{cancel as We,confirm as Ge,intro as Ke,isCancel as qe,outro as Je,password as Ye,select as Xe,text as Ze}from"@clack/prompts";import{loadConnector as Qe,parseYamlConnector as $e,runAction as et,validateYamlConnector as tt}from"@stackone/connect-sdk";import{diffLines as nt}from"diff";import{createInterface as rt}from"readline";import{ChangelogLabels as it}from"@stackone/core";import at from"semver";import{HttpClient as ot}from"@stackone/transport";import{promisify as st}from"node:util";import{readdir as ct,stat as lt}from"fs/promises";var ut=w(import.meta.url);const Z={primary:`#00AF66`,success:`green`,warning:`yellow`,error:`red`,text:`white`,dim:`gray`},dt={defaultTerminalWidth:80,boxWidth:44,maxToolNameWidth:64,maxInputSummaryWidth:60,maxSeparatorWidth:60,maxConversationTitleLength:36,maxExampleLength:38,maxCollapsedTools:5,maxToolOutputLines:15},ft=e=>{let t=e.replace(/^claude-/,``).replace(/-\d{8,}$/,``),n=t.match(/^(\w+)-(\d+)(?:-(\d+))?$/);if(n){let e=n[3]?`.${n[3]}`:``;return`${n[1]}-${n[2]}${e}`}return t||e},pt={cellsPerFrame:3,pixelFrameMs:18,holdFrames:25,fadeSteps:5,fadeStepMs:80,timerIntervalMs:1e3};function mt(e){return e.replace(/\*\*\*(.+?)\*\*\*/g,`$1`).replace(/\*\*(.+?)\*\*/g,`$1`).replace(/\*(.+?)\*/g,`$1`).replace(/^#{1,6}\s+/gm,``).replace(/```([\s\S]*?)```/g,`$1`).replace(/`(.+?)`/g,`$1`).replace(/!\[([^\]]{0,500})\]\([^)]{1,2000}\)/g,`$1`).replace(/\[([^\]]{1,500})\]\([^)]{1,2000}\)/g,`$1`).replace(/^(?!_+$)[-*_]{3,}$/gm,``).replace(/^>\s+/gm,``).trim()}const ht=e=>{let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},gt=e=>{let t=(e.status===`complete`||e.status===`warning`||e.status===`error`)&&e.durationMs!=null?` ${ht(e.durationMs)}`:``,n=e.model?V.createElement(B,{dimColor:!0},` (`,ft(e.model),`)`):null;switch(e.status){case`complete`:return V.createElement(B,{color:`green`},e.name,n,` ✓`,t);case`warning`:return V.createElement(B,{color:`yellow`},e.name,n,` ⚠`,t);case`running`:return V.createElement(B,{color:`cyan`},e.name,n,` `,V.createElement(Oe,{type:`dots`}));case`error`:return V.createElement(B,{color:`red`},e.name,n,` ✗`,t);case`skipped`:return V.createElement(B,{dimColor:!0},e.name,` ⊘`);case`pending`:default:return V.createElement(B,{dimColor:!0},e.name,` ○`)}},_t=({phases:e})=>e.length===0?null:V.createElement(z,{marginBottom:1},V.createElement(B,{bold:!0},`Build: `),e.map((t,n)=>V.createElement(z,{key:t.name},V.createElement(B,null,`[`),gt(t),V.createElement(B,null,`]`),n<e.length-1&&V.createElement(B,null,` `)))),vt=[`\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;14;147;94m▀\x1B[0m\x1B[38;2;8;125;77m\x1B[48;2;29;115;84m▀\x1B[0m\x1B[38;2;16;108;72m\x1B[48;2;23;128;88m▀\x1B[0m\x1B[38;2;14;112;73m\x1B[48;2;17;140;91m▀\x1B[0m\x1B[38;2;9;122;76m\x1B[48;2;11;152;95m▀\x1B[0m\x1B[38;2;4;132;79m\x1B[48;2;5;165;99m▀\x1B[0m\x1B[38;2;0;55;33m\x1B[48;2;0;69;41m▀\x1B[0m`,`\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;2;170;100m\x1B[48;2;11;153;95m▀\x1B[0m\x1B[38;2;34;106;81m\x1B[48;2;35;103;80m▀\x1B[0m\x1B[38;2;29;115;84m\x1B[48;2;29;115;84m▀\x1B[0m\x1B[38;2;23;127;88m\x1B[48;2;23;127;88m▀\x1B[0m\x1B[38;2;17;140;92m\x1B[48;2;17;140;92m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;11;152;95m▀\x1B[0m\x1B[38;2;5;165;99m\x1B[48;2;5;165;99m▀\x1B[0m\x1B[38;2;0;69;41m\x1B[48;2;0;69;41m▀\x1B[0m`,`\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;1;125;74m\x1B[48;2;0;123;71m▀\x1B[0m \x1B[38;2;0;128;75m\x1B[48;2;0;123;71m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m`,`\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;123;71m\x1B[48;2;0;128;75m▀\x1B[0m \x1B[38;2;0;123;71m\x1B[48;2;1;125;74m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m`,` \x1B[38;2;0;69;41m\x1B[48;2;0;69;41m▀\x1B[0m\x1B[38;2;5;165;99m\x1B[48;2;5;165;99m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;11;152;95m▀\x1B[0m\x1B[38;2;17;140;91m\x1B[48;2;17;140;91m▀\x1B[0m\x1B[38;2;23;127;88m\x1B[48;2;23;127;88m▀\x1B[0m\x1B[38;2;29;115;84m\x1B[48;2;29;115;84m▀\x1B[0m\x1B[38;2;35;102;80m\x1B[48;2;34;105;81m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;3;169;100m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m`,` \x1B[38;2;0;69;40m\x1B[48;2;0;62;37m▀\x1B[0m\x1B[38;2;5;165;99m\x1B[48;2;5;148;89m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;10;137;86m▀\x1B[0m\x1B[38;2;17;140;91m\x1B[48;2;15;126;82m▀\x1B[0m\x1B[38;2;23;127;88m\x1B[48;2;17;122;81m▀\x1B[0m\x1B[38;2;29;115;84m\x1B[48;2;9;139;86m▀\x1B[0m\x1B[38;2;16;143;92m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m`],yt=[` ▄▖▗ ▌ ▄▖`,` ▚ ▜▘▀▌▛▘▙▘▌▌▛▌█▌`,` ▄▌▐▖█▌▙▖▛▖▙▌▌▌▙▖`,``,``,``],bt=vt.map((e,t)=>e+yt[t]),xt=vt.map(e=>{let t=[],n=0;for(;n<e.length;)if(e[n]===`\x1B`){let r=``;for(;n<e.length;)if(e[n]===`\x1B`){let t=e.indexOf(`m`,n);if(r+=e.substring(n,t+1),n=t+1,r.endsWith(`\x1B[0m`)&&/[▀▄█]/.test(r))break}else r+=e[n],n++;t.push(r)}else e[n]===` `&&t.push(null),n++;return t}),St=[];for(let e=0;e<xt.length;e++)for(let t=0;t<xt[e].length;t++){let n=xt[e][t];n&&St.push({row:e,col:t,cell:n})}const Ct=Math.max(...xt.map(e=>e.length)),wt=({wordmark:e})=>V.createElement(B,null,(e?bt:vt).join(`
2
- `)),Tt=e=>{let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t},Et=({ready:e,onComplete:t})=>{let[n,r]=W(0),i=U(Tt(St.map((e,t)=>t))),a=U(Tt(St.map((e,t)=>t))),o=U(!1),s=Math.ceil(St.length/pt.cellsPerFrame),c=s;H(()=>{let e=setInterval(()=>{r(e=>{let t=e+1;return t>=s+pt.holdFrames+s+pt.holdFrames?(i.current=Tt(St.map((e,t)=>t)),a.current=Tt(St.map((e,t)=>t)),0):t})},pt.pixelFrameMs);return()=>clearInterval(e)},[s]),H(()=>{e&&n>=c&&!o.current&&(o.current=!0,t?.())},[e,n,c,t]);let l=new Set;if(n<s){let e=Math.min((n+1)*pt.cellsPerFrame,St.length);for(let t=0;t<e;t++)l.add(i.current[t])}else if(n<s+pt.holdFrames)for(let e=0;e<St.length;e++)l.add(e);else if(e)for(let e=0;e<St.length;e++)l.add(e);else if(n<s*2+pt.holdFrames){let e=n-s-pt.holdFrames,t=Math.min((e+1)*pt.cellsPerFrame,St.length);for(let e=0;e<St.length;e++)l.add(e);for(let e=0;e<t;e++)l.delete(a.current[e])}let u=new Map;for(let e of l){let t=St[e];u.set(`${t.row},${t.col}`,t.cell)}let d=[];for(let e=0;e<xt.length;e++){let t=``;for(let n=0;n<Ct;n++){let r=u.get(`${e},${n}`);t+=r??` `}d.push(t)}return V.createElement(B,null,d.join(`
3
- `))},Dt=(e,t)=>{if(t)return t;let n=dt.maxToolNameWidth;return(e.length>n?`${e.slice(0,n-1)}…`:e).padEnd(n)},Ot=(e,t)=>{let n=e.split(`
1
+ import{n as e}from"./fileNames-DzZBY06N.mjs";import{C as t,S as n,T as r,_ as i,a,b as o,c as s,d as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,u as ee,v,w as y,x as b,y as x}from"./agentConfig-BWQWMYKQ.mjs";import{r as S,t as C}from"./setupMigration-C1ShGzOu.mjs";import{r as te}from"./agentApiKey-CWXxJgCO.mjs";import{createRequire as w}from"node:module";import T from"chalk";import{Argument as E,Command as ne}from"commander";import{BuildOrchestrator as D,checkCommandSafety as re,createAgentSession as ie,createDefaultVisualizationRegistry as O,createSkillTracker as k,executeAgent as ae,extractBuildIntent as oe,getAvailableSkillNames as se,getBundledSkillsPath as A,getSkillsForMode as j,initAgentTelemetry as ce}from"@stackone/agent-harness";import*as M from"node:fs";import{cpSync as le,existsSync as N,mkdirSync as ue,readFileSync as de,readdirSync as P,rmSync as fe,statSync as pe,writeFileSync as me}from"node:fs";import*as F from"node:os";import{homedir as I,platform as he}from"node:os";import*as L from"node:path";import{dirname as ge,join as R,resolve as _e,sep as ve}from"node:path";import{Box as z,Text as B,render as ye,useApp as be,useInput as xe}from"ink";import V,{useCallback as Se,useEffect as H,useMemo as Ce,useRef as U,useState as W}from"react";import{exec as we,execFile as Te,execFileSync as Ee,execSync as De}from"node:child_process";import Oe from"ink-spinner";import G,{readFileSync as ke,readdirSync as Ae,statSync as K,writeFileSync as je}from"fs";import Me,{basename as Ne,dirname as Pe,join as Fe,resolve as Ie}from"path";import{fileURLToPath as Le}from"url";import q from"ora";import{access as Re}from"node:fs/promises";import ze from"inquirer";import{stdin as Be,stdout as Ve}from"node:process";import{createInterface as He}from"node:readline";import{getContentHash as Ue,isMissing as J,isObject as We,notMissing as Y,z as X}from"@stackone/utils";import{cancel as Ge,confirm as Ke,intro as qe,isCancel as Je,outro as Ye,password as Xe,select as Ze,text as Qe}from"@clack/prompts";import{createIncrementalStrategy as $e,createPaginator as et,extractItems as tt,loadConnector as nt,parseYamlConnector as rt,runAction as it,validateYamlConnector as at}from"@stackone/connect-sdk";import{diffLines as ot}from"diff";import{createInterface as st}from"readline";import{ChangelogLabels as ct,computeDataSyncFingerprint as lt,getIteratorLocation as ut}from"@stackone/core";import dt from"semver";import{HttpClient as ft}from"@stackone/transport";import{promisify as pt}from"node:util";import{readdir as mt,stat as ht}from"fs/promises";var gt=w(import.meta.url);const Z={primary:`#00AF66`,success:`green`,warning:`yellow`,error:`red`,text:`white`,dim:`gray`},_t={defaultTerminalWidth:80,boxWidth:44,maxToolNameWidth:64,maxInputSummaryWidth:60,maxSeparatorWidth:60,maxConversationTitleLength:36,maxExampleLength:38,maxCollapsedTools:5,maxToolOutputLines:15},vt=e=>{let t=e.replace(/^claude-/,``).replace(/-\d{8,}$/,``),n=t.match(/^(\w+)-(\d+)(?:-(\d+))?$/);if(n){let e=n[3]?`.${n[3]}`:``;return`${n[1]}-${n[2]}${e}`}return t||e},yt={cellsPerFrame:3,pixelFrameMs:18,holdFrames:25,fadeSteps:5,fadeStepMs:80,timerIntervalMs:1e3};function bt(e){return e.replace(/\*\*\*(.+?)\*\*\*/g,`$1`).replace(/\*\*(.+?)\*\*/g,`$1`).replace(/\*(.+?)\*/g,`$1`).replace(/^#{1,6}\s+/gm,``).replace(/```([\s\S]*?)```/g,`$1`).replace(/`(.+?)`/g,`$1`).replace(/!\[([^\]]{0,500})\]\([^)]{1,2000}\)/g,`$1`).replace(/\[([^\]]{1,500})\]\([^)]{1,2000}\)/g,`$1`).replace(/^(?!_+$)[-*_]{3,}$/gm,``).replace(/^>\s+/gm,``).trim()}const xt=e=>{let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},St=e=>{let t=(e.status===`complete`||e.status===`warning`||e.status===`error`)&&e.durationMs!=null?` ${xt(e.durationMs)}`:``,n=e.model?V.createElement(B,{dimColor:!0},` (`,vt(e.model),`)`):null;switch(e.status){case`complete`:return V.createElement(B,{color:`green`},e.name,n,` ✓`,t);case`warning`:return V.createElement(B,{color:`yellow`},e.name,n,` ⚠`,t);case`running`:return V.createElement(B,{color:`cyan`},e.name,n,` `,V.createElement(Oe,{type:`dots`}));case`error`:return V.createElement(B,{color:`red`},e.name,n,` ✗`,t);case`skipped`:return V.createElement(B,{dimColor:!0},e.name,` ⊘`);case`pending`:default:return V.createElement(B,{dimColor:!0},e.name,` ○`)}},Ct=({phases:e})=>e.length===0?null:V.createElement(z,{marginBottom:1},V.createElement(B,{bold:!0},`Build: `),e.map((t,n)=>V.createElement(z,{key:t.name},V.createElement(B,null,`[`),St(t),V.createElement(B,null,`]`),n<e.length-1&&V.createElement(B,null,` `)))),wt=[`\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;140;82m\x1B[48;2;14;147;94m▀\x1B[0m\x1B[38;2;8;125;77m\x1B[48;2;29;115;84m▀\x1B[0m\x1B[38;2;16;108;72m\x1B[48;2;23;128;88m▀\x1B[0m\x1B[38;2;14;112;73m\x1B[48;2;17;140;91m▀\x1B[0m\x1B[38;2;9;122;76m\x1B[48;2;11;152;95m▀\x1B[0m\x1B[38;2;4;132;79m\x1B[48;2;5;165;99m▀\x1B[0m\x1B[38;2;0;55;33m\x1B[48;2;0;69;41m▀\x1B[0m`,`\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;2;170;100m\x1B[48;2;11;153;95m▀\x1B[0m\x1B[38;2;34;106;81m\x1B[48;2;35;103;80m▀\x1B[0m\x1B[38;2;29;115;84m\x1B[48;2;29;115;84m▀\x1B[0m\x1B[38;2;23;127;88m\x1B[48;2;23;127;88m▀\x1B[0m\x1B[38;2;17;140;92m\x1B[48;2;17;140;92m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;11;152;95m▀\x1B[0m\x1B[38;2;5;165;99m\x1B[48;2;5;165;99m▀\x1B[0m\x1B[38;2;0;69;41m\x1B[48;2;0;69;41m▀\x1B[0m`,`\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;1;125;74m\x1B[48;2;0;123;71m▀\x1B[0m \x1B[38;2;0;128;75m\x1B[48;2;0;123;71m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m`,`\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;123;71m\x1B[48;2;0;128;75m▀\x1B[0m \x1B[38;2;0;123;71m\x1B[48;2;1;125;74m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m`,` \x1B[38;2;0;69;41m\x1B[48;2;0;69;41m▀\x1B[0m\x1B[38;2;5;165;99m\x1B[48;2;5;165;99m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;11;152;95m▀\x1B[0m\x1B[38;2;17;140;91m\x1B[48;2;17;140;91m▀\x1B[0m\x1B[38;2;23;127;88m\x1B[48;2;23;127;88m▀\x1B[0m\x1B[38;2;29;115;84m\x1B[48;2;29;115;84m▀\x1B[0m\x1B[38;2;35;102;80m\x1B[48;2;34;105;81m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;3;169;100m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;175;102m▀\x1B[0m`,` \x1B[38;2;0;69;40m\x1B[48;2;0;62;37m▀\x1B[0m\x1B[38;2;5;165;99m\x1B[48;2;5;148;89m▀\x1B[0m\x1B[38;2;11;152;95m\x1B[48;2;10;137;86m▀\x1B[0m\x1B[38;2;17;140;91m\x1B[48;2;15;126;82m▀\x1B[0m\x1B[38;2;23;127;88m\x1B[48;2;17;122;81m▀\x1B[0m\x1B[38;2;29;115;84m\x1B[48;2;9;139;86m▀\x1B[0m\x1B[38;2;16;143;92m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m\x1B[38;2;0;175;102m\x1B[48;2;0;158;92m▀\x1B[0m`],Tt=[` ▄▖▗ ▌ ▄▖`,` ▚ ▜▘▀▌▛▘▙▘▌▌▛▌█▌`,` ▄▌▐▖█▌▙▖▛▖▙▌▌▌▙▖`,``,``,``],Et=wt.map((e,t)=>e+Tt[t]),Dt=wt.map(e=>{let t=[],n=0;for(;n<e.length;)if(e[n]===`\x1B`){let r=``;for(;n<e.length;)if(e[n]===`\x1B`){let t=e.indexOf(`m`,n);if(r+=e.substring(n,t+1),n=t+1,r.endsWith(`\x1B[0m`)&&/[▀▄█]/.test(r))break}else r+=e[n],n++;t.push(r)}else e[n]===` `&&t.push(null),n++;return t}),Ot=[];for(let e=0;e<Dt.length;e++)for(let t=0;t<Dt[e].length;t++){let n=Dt[e][t];n&&Ot.push({row:e,col:t,cell:n})}const kt=Math.max(...Dt.map(e=>e.length)),At=({wordmark:e})=>V.createElement(B,null,(e?Et:wt).join(`
2
+ `)),jt=e=>{let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t},Mt=({ready:e,onComplete:t})=>{let[n,r]=W(0),i=U(jt(Ot.map((e,t)=>t))),a=U(jt(Ot.map((e,t)=>t))),o=U(!1),s=Math.ceil(Ot.length/yt.cellsPerFrame),c=s;H(()=>{let e=setInterval(()=>{r(e=>{let t=e+1;return t>=s+yt.holdFrames+s+yt.holdFrames?(i.current=jt(Ot.map((e,t)=>t)),a.current=jt(Ot.map((e,t)=>t)),0):t})},yt.pixelFrameMs);return()=>clearInterval(e)},[s]),H(()=>{e&&n>=c&&!o.current&&(o.current=!0,t?.())},[e,n,c,t]);let l=new Set;if(n<s){let e=Math.min((n+1)*yt.cellsPerFrame,Ot.length);for(let t=0;t<e;t++)l.add(i.current[t])}else if(n<s+yt.holdFrames)for(let e=0;e<Ot.length;e++)l.add(e);else if(e)for(let e=0;e<Ot.length;e++)l.add(e);else if(n<s*2+yt.holdFrames){let e=n-s-yt.holdFrames,t=Math.min((e+1)*yt.cellsPerFrame,Ot.length);for(let e=0;e<Ot.length;e++)l.add(e);for(let e=0;e<t;e++)l.delete(a.current[e])}let u=new Map;for(let e of l){let t=Ot[e];u.set(`${t.row},${t.col}`,t.cell)}let d=[];for(let e=0;e<Dt.length;e++){let t=``;for(let n=0;n<kt;n++){let r=u.get(`${e},${n}`);t+=r??` `}d.push(t)}return V.createElement(B,null,d.join(`
3
+ `))},Nt=(e,t)=>{if(t)return t;let n=_t.maxToolNameWidth;return(e.length>n?`${e.slice(0,n-1)}…`:e).padEnd(n)},Pt=(e,t)=>{let n=e.split(`
4
4
  `);return n.length<=t?{text:e,truncated:!1}:{text:n.slice(0,t).join(`
5
- `),truncated:!0}},kt=({tools:e,expanded:t=!1,maxCollapsed:n=dt.maxCollapsedTools,title:r})=>{if(e.length===0)return null;let i=e.some(e=>e.status===`running`),a=r||(i?`Working...`:`Tools (${e.length})`),o=t?e:e.slice(0,n),s=e.length-o.length;return V.createElement(z,{flexDirection:`column`,borderStyle:`round`,borderColor:Z.primary,borderDimColor:!0,paddingX:1},V.createElement(B,{dimColor:!0,bold:!0},a),o.map((e,n)=>V.createElement(z,{key:`tool-${n}`,flexDirection:`column`},V.createElement(z,null,e.status===`running`?V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})):e.status===`failed`?V.createElement(B,{color:Z.error},`✗`):V.createElement(B,{color:Z.primary},`✓`),V.createElement(B,{bold:!0},` `,Dt(e.name,e.skillName)),e.inputSummary&&V.createElement(B,{dimColor:!0,italic:!0},` `,e.inputSummary.length>dt.maxInputSummaryWidth?`${e.inputSummary.slice(0,dt.maxInputSummaryWidth-1)}…`:e.inputSummary)),t&&e.output&&V.createElement(z,{paddingLeft:2,flexDirection:`column`},(()=>{let{text:t,truncated:n}=Ot(e.output,dt.maxToolOutputLines);return V.createElement(V.Fragment,null,V.createElement(B,{dimColor:!0,italic:!0,wrap:`wrap`},t),n&&V.createElement(B,{dimColor:!0,italic:!0},`... (truncated)`))})()))),s>0&&V.createElement(B,{dimColor:!0},`... and `,s,` more (Ctrl+O to show all)`))};let At=``;try{let e=ut.resolve(`@stackone/agent-harness`),t=L.dirname(e);for(;t!==L.dirname(t);){let e=L.join(t,`package.json`);if(M.existsSync(e)){let t=JSON.parse(M.readFileSync(e,`utf-8`));if(t.name===`@stackone/agent-harness`){At=t.version||``;break}}t=L.dirname(t)}}catch{}const jt=({startTime:e})=>{let[,t]=W(0);H(()=>{let e=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(e)},[]);let n=Date.now()-e.getTime(),r=Math.floor(n/1e3),i=r>=60?`${Math.floor(r/60)}m${r%60}s`:`${r}s`;return V.createElement(B,{dimColor:!0},i)},Mt=({children:e})=>{let[t,n]=W(0);return H(()=>{if(t>=pt.fadeSteps)return;let e=setTimeout(()=>n(e=>e+1),pt.fadeStepMs);return()=>clearTimeout(e)},[t]),V.createElement(V.Fragment,null,e(Math.min(t/pt.fadeSteps,1)))},Nt=e=>{try{return De(process.platform===`darwin`?`pbcopy`:process.platform===`win32`?`clip`:`xclip -selection clipboard`,{input:e,stdio:[`pipe`,`ignore`,`ignore`]}),!0}catch{return!1}};function Pt(e){return e===` `||e===` `||e===`
6
- `||e===`\r`}function Ft(e,t){let n=t-1;for(;n>=0&&Pt(e[n]);)n--;for(;n>=0&&!Pt(e[n]);)n--;return n+1}function It(e,t){let n=t;for(;n<e.length&&Pt(e[n]);)n++;for(;n<e.length&&!Pt(e[n]);)n++;return n}function Lt(e){return e.filter(e=>!(e.role===`system`&&e.content.startsWith(`TOOL_START:`)))}const Rt=e=>{let t=[],n={userMessage:null,toolMessages:[],assistantMessages:[],systemMessages:[]};for(let r of e)r.role===`user`?((n.userMessage||n.toolMessages.length>0||n.assistantMessages.length>0||n.systemMessages.length>0)&&t.push(n),n={userMessage:r,toolMessages:[],assistantMessages:[],systemMessages:[]}):r.role===`system`&&r.content.startsWith(`TOOL:`)?n.toolMessages.push(r):r.role===`assistant`?n.assistantMessages.push(r):n.systemMessages.push(r);return(n.userMessage||n.toolMessages.length>0||n.assistantMessages.length>0||n.systemMessages.length>0)&&t.push(n),t},zt=e=>{let t=e.split(`|||`);return{name:t[0].replace(`TOOL:`,``),inputSummary:t.length>=3&&t[1]||``,output:t.length>=3?t.slice(2).join(`|||`):t[1]||``}},Bt=({title:e,mode:t,connector:n,action:r,onSubmit:i,onExit:a,onStop:o,messages:s,currentToolCalls:c=[],isThinking:l=!1,isComplete:u=!1,error:d,isInterrupted:f=!1,commandHistory:p=[],streamingText:m=``,usage:h,detailViewData:g=null,onCloseDetailView:_,onResumeConversation:ee,onToggleTrust:v,onRewindTo:y,spawnedSubagentActive:b=!1,spawnedSubagentName:x=`Subagent`,spawnedSubagentComplete:S=!1,queuedMessages:C=[],isProcessingQueue:te=!1,initInfo:w,pendingDeleteConfirmation:T=null,onConfirmDelete:E,slashCommands:ne=[],welcomeContext:D,buildPhases:re,currentBuildPhase:ie})=>{let{exit:ae}=be(),[O,oe]=W(null),[se,k]=W(``),[,A]=W(0),j=U(0),[ce,M]=W(!0),le=U(s),[N,ue]=W(-1),de=U(p),P=U(``),[fe,pe]=W([]),[me,F]=W(0),[I,he]=W(0),[L,ge]=W(!1),[R,_e]=W(!1),[ve,ye]=W(!1),[we,Te]=W(!1),Ee=U(``),[De,G]=W(1),[ke,Ae]=W(null),[K,je]=W(1),Me=Ce(()=>ne.map(e=>`/${e.name}`),[ne]);H(()=>{le.current=s},[s]),H(()=>{de.current=p},[p]),H(()=>{se.startsWith(`/`)?(pe(Me.filter(e=>e.startsWith(se.toLowerCase()))),F(0)):(pe([]),F(0))},[se]),H(()=>{if(g?.items){let e=Math.max(0,g.items.length-1);he(t=>Math.min(t,e))}},[g?.items?.length]),xe(Se((e,t)=>{let n=P.current,r=N;if(t.escape&&(l||m||c.length>0)&&!g){o?.(),k(``),P.current=``,j.current=0,A(0),ue(-1);return}if(t.escape&&b&&R&&!g){_e(!1);return}if(t.escape&&ve&&!b&&!g){ye(!1);return}if(T&&E){if(t.escape||e.toLowerCase()===`n`){G(1),E(!1);return}if(e.toLowerCase()===`y`){G(0),E(!0);return}if(t.upArrow||t.downArrow){G(e=>e===0?1:0);return}if(t.return){E(De===0);return}return}if(g){if(ke){if(t.escape||t.ctrl&&e===`c`){Ae(null);return}if(t.leftArrow||t.rightArrow){je(e=>e===0?1:0);return}if(e.toLowerCase()===`y`){v&&v(ke.path),Ae(null);return}if(e.toLowerCase()===`n`){Ae(null);return}if(t.return){K===0&&v&&v(ke.path),Ae(null);return}return}if(t.escape||t.ctrl&&e===`c`)if(L){ge(!1);return}else{_?.(),he(0);return}if(t.upArrow&&!L){he(e=>e>0?e-1:g.items.length-1);return}if(t.downArrow&&!L){he(e=>e<g.items.length-1?e+1:0);return}if(t.ctrl&&e===`o`&&g.type===`trust`&&!ke&&!L){let e=g.items[I];e?.path&&(Ae({path:e.path,name:e.name}),je(1));return}if(t.return){if(L)return;if(g.type===`resume`){let e=g.items[I];e.messages&&ee&&(ee(e.messages),_?.(),he(0));return}if(g.type===`rewind`){let e=g.items[I];e.index!==void 0&&y&&(y(e.index),_?.(),he(0));return}ge(!0);return}return}if(t.ctrl&&e===`o`){b?_e(e=>!e):ye(e=>!e);return}if(t.ctrl&&e===`u`){k(``),P.current=``,j.current=0,A(0),ue(-1);return}if(t.ctrl&&e===`y`){let e=[...s].reverse().find(e=>e.role===`assistant`);e&&Nt(e.content)&&(Te(!0),setTimeout(()=>Te(!1),2e3));return}if(t.ctrl&&e===`c`||e===``)if(n.trim()){k(``),P.current=``,j.current=0,A(0),ue(-1);return}else{a(),ae();return}if(t.shift&&t.return){let e=j.current,t=P.current,n=t.slice(0,e)+`
7
- `+t.slice(e);P.current=n,k(n);let r=e+1;j.current=r,A(r);return}if(t.ctrl&&e===`a`){j.current=0,A(0);return}if(t.ctrl&&e===`e`){j.current=n.length,A(n.length);return}let u=e===`\x1Bb`||e===`b`&&t.meta||e===`\x1B\x1B[D`||e===`\x1B[1;3D`||e===`\x1B[1;9D`||t.meta&&t.leftArrow&&!t.ctrl&&!t.shift,d=e===`\x1Bf`||e===`f`&&t.meta||e===`\x1B\x1B[C`||e===`\x1B[1;3C`||e===`\x1B[1;9C`||t.meta&&t.rightArrow&&!t.ctrl&&!t.shift;if(u){let e=Ft(n,j.current);j.current=e,A(e);return}if(d){let e=It(n,j.current);j.current=e,A(e);return}if(t.home||e===`\x1B[H`||e===`\x1BOH`){j.current=0,A(0);return}if(t.end||e===`\x1B[F`||e===`\x1BOF`){j.current=n.length,A(n.length);return}if(process.platform===`darwin`&&t.meta&&t.leftArrow){j.current=0,A(0);return}if(process.platform===`darwin`&&t.meta&&t.rightArrow){j.current=n.length,A(n.length);return}if(process.platform===`darwin`&&t.meta&&t.upArrow){j.current=0,A(0);return}if(process.platform===`darwin`&&t.meta&&t.downArrow){j.current=n.length,A(n.length);return}if(t.ctrl&&t.leftArrow&&process.platform!==`darwin`){let e=Ft(n,j.current);j.current=e,A(e);return}if(t.ctrl&&t.rightArrow&&process.platform!==`darwin`){let e=It(n,j.current);j.current=e,A(e);return}let f=()=>{let e=process.stdout?.columns||80,t=Math.max(20,e-6),r=[],i=0;n.split(`
8
- `).forEach((e,n)=>{let a=i,o=n===0?t-2:t;if(e.length===0)r.push({start:a,end:a});else{let n=0;for(;n<e.length;){let i=n===0?o:t;r.push({start:a+n,end:a+Math.min(n+i,e.length)}),n+=i}}i=a+e.length+1});let a=j.current,o=r.findIndex(e=>a>=e.start&&a<e.end);return o===-1&&r.length>0&&(o=r.findIndex(e=>a===e.end)),{rows:r,currentRow:Math.max(0,o)}};if(t.upArrow){if(fe.length>0){F(e=>e>0?e-1:fe.length-1);return}let e=de.current;if(r>=0&&e.length>0){ue(t=>{let n=Math.max(0,t-1),r=e[n]||``;return k(r),P.current=r,j.current=r.length,A(r.length),n});return}let{rows:t,currentRow:n}=f();if(n>0){let e=j.current-t[n].start,r=t[n-1],i=r.start+Math.min(e,r.end-r.start);j.current=i,A(i);return}if(e.length>0){ue(t=>{let n=t<0?e.length-1:Math.max(0,t-1),r=e[n]||``;return k(r),P.current=r,j.current=r.length,A(r.length),n});return}return}if(t.downArrow){if(fe.length>0){F(e=>e<fe.length-1?e+1:0);return}let e=de.current;if(r>=0&&e.length>0){ue(t=>{let n=t>=e.length-1?-1:t+1,r=n<0?``:e[n]||``;return k(r),P.current=r,j.current=r.length,A(r.length),n});return}let{rows:t,currentRow:n}=f();if(n<t.length-1){let e=j.current-t[n].start,r=t[n+1],i=r.start+Math.min(e,r.end-r.start);j.current=i,A(i);return}return}if(t.return){if(fe.length>0){let e=fe[me];pe([]),F(0),k(``),P.current=``,j.current=0,A(0),Ee.current=e,i(e);return}if(n.trim()){let e=n.trim();Ee.current=e,i(e),k(``),P.current=``,j.current=0,A(0),ue(-1)}return}if((t.backspace||t.delete)&&j.current>0){let e=j.current,t=P.current,n=t.slice(0,e-1)+t.slice(e);P.current=n,k(n);let r=Math.max(0,e-1);j.current=r,A(r),ue(-1);return}if(t.leftArrow&&!t.meta&&!t.ctrl){let e=Math.max(0,j.current-1);j.current=e,A(e);return}if(t.rightArrow&&!t.meta&&!t.ctrl){let e=Math.min(n.length,j.current+1);j.current=e,A(e);return}if(t.tab&&n.startsWith(`/`)){let e=Me.filter(e=>e.startsWith(n.toLowerCase()));if(e.length===1){let t=e[0].length;k(e[0]),P.current=e[0],j.current=t,A(t)}return}if(e){if(t.meta||t.ctrl||!e.split(``).every(e=>{let t=e.charCodeAt(0);return t>=32&&t!==127||t===10||t===9}))return;let n=j.current,r=P.current,i=r.slice(0,n)+e+r.slice(n);P.current=i,k(i);let a=n+e.length;j.current=a,A(a),ue(-1)}},[i,a,ae,N,Me,fe,me,g,L,_,b,R,ee,I,l,m,c,o,y,T,E,De,ve,s])),H(()=>{u&&M(!1)},[u]);let Ne=l||m!==``||c.length>0;H(()=>{Ne&&!O?oe(new Date):!Ne&&O&&oe(null)},[Ne,O]);let Pe=`\x1B[2m`,Fe=`\x1B[0m`,Ie=[...bt.slice(0,4),`${vt[4]} ${Pe}sessions monitored${Fe}`,`${vt[5]} ${Pe}preview${At?` v${At}`:``}${Fe}`].join(`
9
- `),Le=Lt(s),q=Ce(()=>Rt(Le),[Le]),Re=!!w,ze=Ce(()=>{let e=[`${t.charAt(0).toUpperCase()+t.slice(1)} mode`];if(D?.credentialEmail){let t=D.credentialTimeRemaining?` (${D.credentialTimeRemaining.days}d ${D.credentialTimeRemaining.hours}h)`:``;e.push(`${D.credentialEmail}${t}`)}w&&w.mcpServers.length>0&&e.push(`${w.mcpServers.reduce((e,t)=>e+t.count,0)} tools`),w&&w.claudeSkills.count>0&&e.push(`${w.claudeSkills.count} skills`);let r=[{text:`✓ ${e.join(` · `)}`,color:Z.primary}],i=n||D?.detectedConnector;if(i&&r.push({text:`📂 Detected connector: ${i}`}),w)for(let e of w.errors)r.push({text:`⚠ ${e}`,color:`yellow`});return r},[w,D,t,n]),Be=Ce(()=>{let e=[],t=D?.recentConversations;if(t&&t.length>0){e.push({text:`Recent sessions:`});for(let n of t){let t=n.trim(),r=t.length>36?`${t.slice(0,35)}…`:t;e.push({text:` "${r}"`})}e.push({text:``}),e.push({text:`/resume to continue`})}return e},[n,D]),Ve=Ce(()=>{let e=n||D?.detectedConnector,r={build:[e?`"Add a new action to ${e}"`:`"Add a new action to Slack"`,e?`"Show current actions for ${e}"`:`"Show actions for Datadog"`,`"Create a connector for a new provider"`,`"Validate and fix connector issues"`,`"Add OAuth authentication support"`,`"Map response fields to StackOne schema"`,`"Add pagination to the list endpoint"`,`"Generate test credentials for sandbox"`,`"Add rate limiting configuration"`,`"Improve descriptions for all actions"`],test:[e?`"Test all actions for ${e}"`:`"Test all actions for Slack"`,`"Run a specific action and show response"`,`"Debug why list_users is returning errors"`,`"Test with a different account"`,`"Compare response against StackOne schema"`,`"Test pagination across all list actions"`,`"Validate error handling for 401 responses"`,`"Run actions with verbose output"`,`"Test the OAuth flow end to end"`,`"Check rate limiting behavior"`],research:[e?`"${e} API endpoints?"`:`"Workday API endpoints?"`,`"Compare pagination for Greenhouse vs Lever"`,`"Auth methods for this provider?"`,`"What versioning strategy does the API use?"`,`"Find the rate limits documentation"`,`"What webhook events are available?"`,`"How does the provider handle deleted records?"`,`"What scopes are needed for user data?"`,`"Does the API support filtering or search?"`,`"What date format does the API use?"`]},i=[...r[t]||r.build];for(let e=i.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[i[e],i[t]]=[i[t],i[e]]}let a=i.slice(0,3),o=[{text:`Try:`}];for(let e of a){let t=e.length>38?`${e.slice(0,36)}…"`:e;o.push({text:` ${t}`})}return o},[t,n]),[He,J]=W(!1),Ue=Se(()=>J(!0),[]),Y=Re&&He,X=Se((e,t)=>{if(!e||t>=1)return e;let n=e.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let r=Math.round(Number.parseInt(n[1],16)*t),i=Math.round(Number.parseInt(n[2],16)*t),a=Math.round(Number.parseInt(n[3],16)*t);return`#${r.toString(16).padStart(2,`0`)}${i.toString(16).padStart(2,`0`)}${a.toString(16).padStart(2,`0`)}`},[]);return V.createElement(z,{flexDirection:`column`,padding:1},!Y&&V.createElement(Et,{ready:!!Re,onComplete:Ue}),Y&&V.createElement(z,{flexDirection:`row`,marginBottom:1},V.createElement(z,{flexDirection:`column`,flexShrink:0},V.createElement(B,null,Ie)),V.createElement(z,{flexDirection:`column`,marginLeft:3,marginTop:1},V.createElement(Mt,null,e=>V.createElement(V.Fragment,null,ze.map((t,n)=>V.createElement(B,{key:`hero-${n}`,color:X(t.color,e),dimColor:!t.color},t.text)),V.createElement(z,{flexDirection:`row`,marginTop:1},Be.length>0&&V.createElement(z,{flexDirection:`column`,marginRight:2,borderStyle:`round`,borderColor:Z.primary,borderDimColor:!0,paddingX:1,width:44},Be.map((e,t)=>V.createElement(B,{key:`ctx-${t}`,dimColor:!0},e.text))),V.createElement(z,{flexDirection:`column`,borderStyle:`round`,borderColor:Z.primary,borderDimColor:!0,paddingX:1,width:44},Ve.map((e,t)=>V.createElement(B,{key:`ex-${t}`,dimColor:!0},e.text)))))))),V.createElement(z,{flexDirection:`column`,marginBottom:1},q.map((e,t)=>{let n=process.stdout?.columns||80,r=Math.max(0,Math.min(n-4,60)),i=[...e.assistantMessages,...e.toolMessages,...e.systemMessages],a=i.length>0?i.reduce((e,t)=>t.timestamp>e.timestamp?t:e):null,o=e.userMessage&&a?a.timestamp.getTime()-e.userMessage.timestamp.getTime():0,s=o>0?o>=6e4?`${Math.floor(o/6e4)}m${Math.round(o%6e4/1e3)}s`:`${Math.round(o/1e3)}s`:``,c=e.toolMessages.map(e=>{let t=zt(e.content);return{name:t.name,inputSummary:t.inputSummary,output:t.output,status:`completed`}});return V.createElement(z,{key:`turn-${t}`,flexDirection:`column`},t>0&&V.createElement(z,{marginBottom:1},V.createElement(B,{dimColor:!0},`─`.repeat(r))),e.userMessage&&V.createElement(z,{marginBottom:1,flexDirection:`column`},V.createElement(B,{bold:!0,color:`white`},`❯ You`,V.createElement(B,{color:`gray`},` `,`• `,e.userMessage.timestamp.toLocaleTimeString())),V.createElement(z,{paddingLeft:2},V.createElement(B,{color:`white`,wrap:`wrap`},e.userMessage.content))),(c.length>0||e.assistantMessages.length>0)&&V.createElement(z,{flexDirection:`column`,marginBottom:1},V.createElement(B,{bold:!0,color:Z.primary},`◆ StackOne Agent`),c.length>0&&V.createElement(z,{paddingLeft:2,marginTop:0,marginBottom:1},V.createElement(kt,{tools:c,expanded:ve})),e.assistantMessages.map((n,r)=>{let i=r===e.assistantMessages.length-1;return V.createElement(z,{key:`asst-${t}-${r}`,paddingLeft:2,flexDirection:`column`,marginBottom:i?0:1},n.isSubagent&&V.createElement(B,{color:Z.primary,dimColor:!0},`⚡ Subagent`),V.createElement(B,{wrap:`wrap`,dimColor:!i},mt(n.content)))}),s&&V.createElement(z,{paddingLeft:2,marginTop:1},V.createElement(B,{dimColor:!0},`✓ `,s))),e.systemMessages.map((e,n)=>V.createElement(z,{key:`sys-${t}-${n}`,marginBottom:1},V.createElement(B,{color:`gray`},`ℹ System • `,e.timestamp.toLocaleTimeString()),V.createElement(z,{paddingLeft:2},V.createElement(B,{dimColor:!0,wrap:`wrap`},e.content)))))})),V.createElement(z,{flexDirection:`column`,marginBottom:1},V.createElement(V.Fragment,null,(b||S)&&V.createElement(z,{marginBottom:0,marginTop:0,borderStyle:`single`,borderColor:Z.primary,paddingX:2,paddingY:1,flexDirection:`column`,height:R?`100%`:void 0},V.createElement(B,{bold:!0,color:Z.primary},S?`✓`:`⚡`,` Subprocess:`,` `,x,` `,S?`(Complete)`:``,` `,R?`(Expanded)`:``),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},S?R?`Press Ctrl+O or ESC to collapse`:`Press Ctrl+O to expand`:R?`Running... Press Ctrl+O or ESC to collapse`:`Running... Press Ctrl+O to expand`)),R?V.createElement(V.Fragment,null,s.filter(e=>e.isSubagent&&!e.content.startsWith(`TOOL_START:`)).map((e,t)=>{let n=e.role===`system`&&e.content.startsWith(`TOOL:`),r=e.role===`assistant`?`⚡ Subagent`:`ℹ System`,i=e.content;if(n){let t=zt(e.content);r=`🔧 Tool • ${t.name}`,i=t.output.slice(0,500),t.output.length>500&&(i+=`
10
- ... (truncated)`)}return V.createElement(z,{key:`${e.timestamp.getTime()}-${t}-${e.role}-subagent`,marginTop:1,flexDirection:`column`},V.createElement(B,{bold:!0,color:Z.primary},r,V.createElement(B,{color:`gray`},` `,`•`,` `,e.timestamp.toLocaleTimeString())),V.createElement(z,{paddingLeft:2},V.createElement(B,{color:n?`gray`:Z.primary,dimColor:n,wrap:`wrap`},mt(i))))}),!S&&!f&&l&&c.length===0&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{dimColor:!0},` Thinking...`)),!S&&!f&&c.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},c.map((e,t)=>V.createElement(z,{key:t,marginBottom:1},e.status===`running`&&V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{color:Z.primary},` `,e.skillName?V.createElement(V.Fragment,null,`✨ Skill •`,` `,e.skillName):V.createElement(V.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`)))),!S&&m&&!f&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},mt(m)))):V.createElement(V.Fragment,null,s.filter(e=>e.isSubagent&&!e.content.startsWith(`TOOL_START:`)&&e.role!==`system`||e.content.startsWith(`TOOL:`)).slice(-2).map((e,t)=>{let n=e.role===`system`&&e.content.startsWith(`TOOL:`),r=e.content;if(n){let t=zt(e.content);r=`🔧 ${t.name}: ${t.output.slice(0,100)}${t.output.length>100?`...`:``}`}let i=r.split(`
5
+ `),truncated:!0}},Ft=({tools:e,expanded:t=!1,maxCollapsed:n=_t.maxCollapsedTools,title:r})=>{if(e.length===0)return null;let i=e.some(e=>e.status===`running`),a=r||(i?`Working...`:`Tools (${e.length})`),o=t?e:e.slice(0,n),s=e.length-o.length;return V.createElement(z,{flexDirection:`column`,borderStyle:`round`,borderColor:Z.primary,borderDimColor:!0,paddingX:1},V.createElement(B,{dimColor:!0,bold:!0},a),o.map((e,n)=>V.createElement(z,{key:`tool-${n}`,flexDirection:`column`},V.createElement(z,null,e.status===`running`?V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})):e.status===`failed`?V.createElement(B,{color:Z.error},`✗`):V.createElement(B,{color:Z.primary},`✓`),V.createElement(B,{bold:!0},` `,Nt(e.name,e.skillName)),e.inputSummary&&V.createElement(B,{dimColor:!0,italic:!0},` `,e.inputSummary.length>_t.maxInputSummaryWidth?`${e.inputSummary.slice(0,_t.maxInputSummaryWidth-1)}…`:e.inputSummary)),t&&e.output&&V.createElement(z,{paddingLeft:2,flexDirection:`column`},(()=>{let{text:t,truncated:n}=Pt(e.output,_t.maxToolOutputLines);return V.createElement(V.Fragment,null,V.createElement(B,{dimColor:!0,italic:!0,wrap:`wrap`},t),n&&V.createElement(B,{dimColor:!0,italic:!0},`... (truncated)`))})()))),s>0&&V.createElement(B,{dimColor:!0},`... and `,s,` more (Ctrl+O to show all)`))};let It=``;try{let e=gt.resolve(`@stackone/agent-harness`),t=L.dirname(e);for(;t!==L.dirname(t);){let e=L.join(t,`package.json`);if(M.existsSync(e)){let t=JSON.parse(M.readFileSync(e,`utf-8`));if(t.name===`@stackone/agent-harness`){It=t.version||``;break}}t=L.dirname(t)}}catch{}const Lt=({startTime:e})=>{let[,t]=W(0);H(()=>{let e=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(e)},[]);let n=Date.now()-e.getTime(),r=Math.floor(n/1e3),i=r>=60?`${Math.floor(r/60)}m${r%60}s`:`${r}s`;return V.createElement(B,{dimColor:!0},i)},Rt=({children:e})=>{let[t,n]=W(0);return H(()=>{if(t>=yt.fadeSteps)return;let e=setTimeout(()=>n(e=>e+1),yt.fadeStepMs);return()=>clearTimeout(e)},[t]),V.createElement(V.Fragment,null,e(Math.min(t/yt.fadeSteps,1)))},zt=e=>{try{return De(process.platform===`darwin`?`pbcopy`:process.platform===`win32`?`clip`:`xclip -selection clipboard`,{input:e,stdio:[`pipe`,`ignore`,`ignore`]}),!0}catch{return!1}};function Bt(e){return e===` `||e===` `||e===`
6
+ `||e===`\r`}function Vt(e,t){let n=t-1;for(;n>=0&&Bt(e[n]);)n--;for(;n>=0&&!Bt(e[n]);)n--;return n+1}function Ht(e,t){let n=t;for(;n<e.length&&Bt(e[n]);)n++;for(;n<e.length&&!Bt(e[n]);)n++;return n}function Ut(e){return e.filter(e=>!(e.role===`system`&&e.content.startsWith(`TOOL_START:`)))}const Wt=e=>{let t=[],n={userMessage:null,toolMessages:[],assistantMessages:[],systemMessages:[]};for(let r of e)r.role===`user`?((n.userMessage||n.toolMessages.length>0||n.assistantMessages.length>0||n.systemMessages.length>0)&&t.push(n),n={userMessage:r,toolMessages:[],assistantMessages:[],systemMessages:[]}):r.role===`system`&&r.content.startsWith(`TOOL:`)?n.toolMessages.push(r):r.role===`assistant`?n.assistantMessages.push(r):n.systemMessages.push(r);return(n.userMessage||n.toolMessages.length>0||n.assistantMessages.length>0||n.systemMessages.length>0)&&t.push(n),t},Gt=e=>{let t=e.split(`|||`);return{name:t[0].replace(`TOOL:`,``),inputSummary:t.length>=3&&t[1]||``,output:t.length>=3?t.slice(2).join(`|||`):t[1]||``}},Kt=({title:e,mode:t,connector:n,action:r,onSubmit:i,onExit:a,onStop:o,messages:s,currentToolCalls:c=[],isThinking:l=!1,isComplete:u=!1,error:d,isInterrupted:f=!1,commandHistory:p=[],streamingText:m=``,usage:h,detailViewData:g=null,onCloseDetailView:_,onResumeConversation:ee,onToggleTrust:v,onRewindTo:y,spawnedSubagentActive:b=!1,spawnedSubagentName:x=`Subagent`,spawnedSubagentComplete:S=!1,queuedMessages:C=[],isProcessingQueue:te=!1,initInfo:w,pendingDeleteConfirmation:T=null,onConfirmDelete:E,slashCommands:ne=[],welcomeContext:D,buildPhases:re,currentBuildPhase:ie})=>{let{exit:O}=be(),[k,ae]=W(null),[oe,se]=W(``),[,A]=W(0),j=U(0),[ce,M]=W(!0),le=U(s),[N,ue]=W(-1),de=U(p),P=U(``),[fe,pe]=W([]),[me,F]=W(0),[I,he]=W(0),[L,ge]=W(!1),[R,_e]=W(!1),[ve,ye]=W(!1),[we,Te]=W(!1),Ee=U(``),[De,G]=W(1),[ke,Ae]=W(null),[K,je]=W(1),Me=Ce(()=>ne.map(e=>`/${e.name}`),[ne]);H(()=>{le.current=s},[s]),H(()=>{de.current=p},[p]),H(()=>{oe.startsWith(`/`)?(pe(Me.filter(e=>e.startsWith(oe.toLowerCase()))),F(0)):(pe([]),F(0))},[oe]),H(()=>{if(g?.items){let e=Math.max(0,g.items.length-1);he(t=>Math.min(t,e))}},[g?.items?.length]),xe(Se((e,t)=>{let n=P.current,r=N;if(t.escape&&(l||m||c.length>0)&&!g){o?.(),se(``),P.current=``,j.current=0,A(0),ue(-1);return}if(t.escape&&b&&R&&!g){_e(!1);return}if(t.escape&&ve&&!b&&!g){ye(!1);return}if(T&&E){if(t.escape||e.toLowerCase()===`n`){G(1),E(!1);return}if(e.toLowerCase()===`y`){G(0),E(!0);return}if(t.upArrow||t.downArrow){G(e=>e===0?1:0);return}if(t.return){E(De===0);return}return}if(g){if(ke){if(t.escape||t.ctrl&&e===`c`){Ae(null);return}if(t.leftArrow||t.rightArrow){je(e=>e===0?1:0);return}if(e.toLowerCase()===`y`){v&&v(ke.path),Ae(null);return}if(e.toLowerCase()===`n`){Ae(null);return}if(t.return){K===0&&v&&v(ke.path),Ae(null);return}return}if(t.escape||t.ctrl&&e===`c`)if(L){ge(!1);return}else{_?.(),he(0);return}if(t.upArrow&&!L){he(e=>e>0?e-1:g.items.length-1);return}if(t.downArrow&&!L){he(e=>e<g.items.length-1?e+1:0);return}if(t.ctrl&&e===`o`&&g.type===`trust`&&!ke&&!L){let e=g.items[I];e?.path&&(Ae({path:e.path,name:e.name}),je(1));return}if(t.return){if(L)return;if(g.type===`resume`){let e=g.items[I];e.messages&&ee&&(ee(e.messages),_?.(),he(0));return}if(g.type===`rewind`){let e=g.items[I];e.index!==void 0&&y&&(y(e.index),_?.(),he(0));return}ge(!0);return}return}if(t.ctrl&&e===`o`){b?_e(e=>!e):ye(e=>!e);return}if(t.ctrl&&e===`u`){se(``),P.current=``,j.current=0,A(0),ue(-1);return}if(t.ctrl&&e===`y`){let e=[...s].reverse().find(e=>e.role===`assistant`);e&&zt(e.content)&&(Te(!0),setTimeout(()=>Te(!1),2e3));return}if(t.ctrl&&e===`c`||e===``)if(n.trim()){se(``),P.current=``,j.current=0,A(0),ue(-1);return}else{a(),O();return}if(t.shift&&t.return){let e=j.current,t=P.current,n=t.slice(0,e)+`
7
+ `+t.slice(e);P.current=n,se(n);let r=e+1;j.current=r,A(r);return}if(t.ctrl&&e===`a`){j.current=0,A(0);return}if(t.ctrl&&e===`e`){j.current=n.length,A(n.length);return}let u=e===`\x1Bb`||e===`b`&&t.meta||e===`\x1B\x1B[D`||e===`\x1B[1;3D`||e===`\x1B[1;9D`||t.meta&&t.leftArrow&&!t.ctrl&&!t.shift,d=e===`\x1Bf`||e===`f`&&t.meta||e===`\x1B\x1B[C`||e===`\x1B[1;3C`||e===`\x1B[1;9C`||t.meta&&t.rightArrow&&!t.ctrl&&!t.shift;if(u){let e=Vt(n,j.current);j.current=e,A(e);return}if(d){let e=Ht(n,j.current);j.current=e,A(e);return}if(t.home||e===`\x1B[H`||e===`\x1BOH`){j.current=0,A(0);return}if(t.end||e===`\x1B[F`||e===`\x1BOF`){j.current=n.length,A(n.length);return}if(process.platform===`darwin`&&t.meta&&t.leftArrow){j.current=0,A(0);return}if(process.platform===`darwin`&&t.meta&&t.rightArrow){j.current=n.length,A(n.length);return}if(process.platform===`darwin`&&t.meta&&t.upArrow){j.current=0,A(0);return}if(process.platform===`darwin`&&t.meta&&t.downArrow){j.current=n.length,A(n.length);return}if(t.ctrl&&t.leftArrow&&process.platform!==`darwin`){let e=Vt(n,j.current);j.current=e,A(e);return}if(t.ctrl&&t.rightArrow&&process.platform!==`darwin`){let e=Ht(n,j.current);j.current=e,A(e);return}let f=()=>{let e=process.stdout?.columns||80,t=Math.max(20,e-6),r=[],i=0;n.split(`
8
+ `).forEach((e,n)=>{let a=i,o=n===0?t-2:t;if(e.length===0)r.push({start:a,end:a});else{let n=0;for(;n<e.length;){let i=n===0?o:t;r.push({start:a+n,end:a+Math.min(n+i,e.length)}),n+=i}}i=a+e.length+1});let a=j.current,o=r.findIndex(e=>a>=e.start&&a<e.end);return o===-1&&r.length>0&&(o=r.findIndex(e=>a===e.end)),{rows:r,currentRow:Math.max(0,o)}};if(t.upArrow){if(fe.length>0){F(e=>e>0?e-1:fe.length-1);return}let e=de.current;if(r>=0&&e.length>0){ue(t=>{let n=Math.max(0,t-1),r=e[n]||``;return se(r),P.current=r,j.current=r.length,A(r.length),n});return}let{rows:t,currentRow:n}=f();if(n>0){let e=j.current-t[n].start,r=t[n-1],i=r.start+Math.min(e,r.end-r.start);j.current=i,A(i);return}if(e.length>0){ue(t=>{let n=t<0?e.length-1:Math.max(0,t-1),r=e[n]||``;return se(r),P.current=r,j.current=r.length,A(r.length),n});return}return}if(t.downArrow){if(fe.length>0){F(e=>e<fe.length-1?e+1:0);return}let e=de.current;if(r>=0&&e.length>0){ue(t=>{let n=t>=e.length-1?-1:t+1,r=n<0?``:e[n]||``;return se(r),P.current=r,j.current=r.length,A(r.length),n});return}let{rows:t,currentRow:n}=f();if(n<t.length-1){let e=j.current-t[n].start,r=t[n+1],i=r.start+Math.min(e,r.end-r.start);j.current=i,A(i);return}return}if(t.return){if(fe.length>0){let e=fe[me];pe([]),F(0),se(``),P.current=``,j.current=0,A(0),Ee.current=e,i(e);return}if(n.trim()){let e=n.trim();Ee.current=e,i(e),se(``),P.current=``,j.current=0,A(0),ue(-1)}return}if((t.backspace||t.delete)&&j.current>0){let e=j.current,t=P.current,n=t.slice(0,e-1)+t.slice(e);P.current=n,se(n);let r=Math.max(0,e-1);j.current=r,A(r),ue(-1);return}if(t.leftArrow&&!t.meta&&!t.ctrl){let e=Math.max(0,j.current-1);j.current=e,A(e);return}if(t.rightArrow&&!t.meta&&!t.ctrl){let e=Math.min(n.length,j.current+1);j.current=e,A(e);return}if(t.tab&&n.startsWith(`/`)){let e=Me.filter(e=>e.startsWith(n.toLowerCase()));if(e.length===1){let t=e[0].length;se(e[0]),P.current=e[0],j.current=t,A(t)}return}if(e){if(t.meta||t.ctrl||!e.split(``).every(e=>{let t=e.charCodeAt(0);return t>=32&&t!==127||t===10||t===9}))return;let n=j.current,r=P.current,i=r.slice(0,n)+e+r.slice(n);P.current=i,se(i);let a=n+e.length;j.current=a,A(a),ue(-1)}},[i,a,O,N,Me,fe,me,g,L,_,b,R,ee,I,l,m,c,o,y,T,E,De,ve,s])),H(()=>{u&&M(!1)},[u]);let Ne=l||m!==``||c.length>0;H(()=>{Ne&&!k?ae(new Date):!Ne&&k&&ae(null)},[Ne,k]);let Pe=`\x1B[2m`,Fe=`\x1B[0m`,Ie=[...Et.slice(0,4),`${wt[4]} ${Pe}sessions monitored${Fe}`,`${wt[5]} ${Pe}preview${It?` v${It}`:``}${Fe}`].join(`
9
+ `),Le=Ut(s),q=Ce(()=>Wt(Le),[Le]),Re=!!w,ze=Ce(()=>{let e=[`${t.charAt(0).toUpperCase()+t.slice(1)} mode`];if(D?.credentialEmail){let t=D.credentialTimeRemaining?` (${D.credentialTimeRemaining.days}d ${D.credentialTimeRemaining.hours}h)`:``;e.push(`${D.credentialEmail}${t}`)}w&&w.mcpServers.length>0&&e.push(`${w.mcpServers.reduce((e,t)=>e+t.count,0)} tools`),w&&w.claudeSkills.count>0&&e.push(`${w.claudeSkills.count} skills`);let r=[{text:`✓ ${e.join(` · `)}`,color:Z.primary}],i=n||D?.detectedConnector;if(i&&r.push({text:`📂 Detected connector: ${i}`}),w)for(let e of w.errors)r.push({text:`⚠ ${e}`,color:`yellow`});return r},[w,D,t,n]),Be=Ce(()=>{let e=[],t=D?.recentConversations;if(t&&t.length>0){e.push({text:`Recent sessions:`});for(let n of t){let t=n.trim(),r=t.length>36?`${t.slice(0,35)}…`:t;e.push({text:` "${r}"`})}e.push({text:``}),e.push({text:`/resume to continue`})}return e},[n,D]),Ve=Ce(()=>{let e=n||D?.detectedConnector,r={build:[e?`"Add a new action to ${e}"`:`"Add a new action to Slack"`,e?`"Show current actions for ${e}"`:`"Show actions for Datadog"`,`"Create a connector for a new provider"`,`"Validate and fix connector issues"`,`"Add OAuth authentication support"`,`"Map response fields to StackOne schema"`,`"Add pagination to the list endpoint"`,`"Generate test credentials for sandbox"`,`"Add rate limiting configuration"`,`"Improve descriptions for all actions"`],test:[e?`"Test all actions for ${e}"`:`"Test all actions for Slack"`,`"Run a specific action and show response"`,`"Debug why list_users is returning errors"`,`"Test with a different account"`,`"Compare response against StackOne schema"`,`"Test pagination across all list actions"`,`"Validate error handling for 401 responses"`,`"Run actions with verbose output"`,`"Test the OAuth flow end to end"`,`"Check rate limiting behavior"`],research:[e?`"${e} API endpoints?"`:`"Workday API endpoints?"`,`"Compare pagination for Greenhouse vs Lever"`,`"Auth methods for this provider?"`,`"What versioning strategy does the API use?"`,`"Find the rate limits documentation"`,`"What webhook events are available?"`,`"How does the provider handle deleted records?"`,`"What scopes are needed for user data?"`,`"Does the API support filtering or search?"`,`"What date format does the API use?"`]},i=[...r[t]||r.build];for(let e=i.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[i[e],i[t]]=[i[t],i[e]]}let a=i.slice(0,3),o=[{text:`Try:`}];for(let e of a){let t=e.length>38?`${e.slice(0,36)}…"`:e;o.push({text:` ${t}`})}return o},[t,n]),[He,Ue]=W(!1),J=Se(()=>Ue(!0),[]),We=Re&&He,Y=Se((e,t)=>{if(!e||t>=1)return e;let n=e.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let r=Math.round(Number.parseInt(n[1],16)*t),i=Math.round(Number.parseInt(n[2],16)*t),a=Math.round(Number.parseInt(n[3],16)*t);return`#${r.toString(16).padStart(2,`0`)}${i.toString(16).padStart(2,`0`)}${a.toString(16).padStart(2,`0`)}`},[]);return V.createElement(z,{flexDirection:`column`,padding:1},!We&&V.createElement(Mt,{ready:!!Re,onComplete:J}),We&&V.createElement(z,{flexDirection:`row`,marginBottom:1},V.createElement(z,{flexDirection:`column`,flexShrink:0},V.createElement(B,null,Ie)),V.createElement(z,{flexDirection:`column`,marginLeft:3,marginTop:1},V.createElement(Rt,null,e=>V.createElement(V.Fragment,null,ze.map((t,n)=>V.createElement(B,{key:`hero-${n}`,color:Y(t.color,e),dimColor:!t.color},t.text)),V.createElement(z,{flexDirection:`row`,marginTop:1},Be.length>0&&V.createElement(z,{flexDirection:`column`,marginRight:2,borderStyle:`round`,borderColor:Z.primary,borderDimColor:!0,paddingX:1,width:44},Be.map((e,t)=>V.createElement(B,{key:`ctx-${t}`,dimColor:!0},e.text))),V.createElement(z,{flexDirection:`column`,borderStyle:`round`,borderColor:Z.primary,borderDimColor:!0,paddingX:1,width:44},Ve.map((e,t)=>V.createElement(B,{key:`ex-${t}`,dimColor:!0},e.text)))))))),V.createElement(z,{flexDirection:`column`,marginBottom:1},q.map((e,t)=>{let n=process.stdout?.columns||80,r=Math.max(0,Math.min(n-4,60)),i=[...e.assistantMessages,...e.toolMessages,...e.systemMessages],a=i.length>0?i.reduce((e,t)=>t.timestamp>e.timestamp?t:e):null,o=e.userMessage&&a?a.timestamp.getTime()-e.userMessage.timestamp.getTime():0,s=o>0?o>=6e4?`${Math.floor(o/6e4)}m${Math.round(o%6e4/1e3)}s`:`${Math.round(o/1e3)}s`:``,c=e.toolMessages.map(e=>{let t=Gt(e.content);return{name:t.name,inputSummary:t.inputSummary,output:t.output,status:`completed`}});return V.createElement(z,{key:`turn-${t}`,flexDirection:`column`},t>0&&V.createElement(z,{marginBottom:1},V.createElement(B,{dimColor:!0},`─`.repeat(r))),e.userMessage&&V.createElement(z,{marginBottom:1,flexDirection:`column`},V.createElement(B,{bold:!0,color:`white`},`❯ You`,V.createElement(B,{color:`gray`},` `,`• `,e.userMessage.timestamp.toLocaleTimeString())),V.createElement(z,{paddingLeft:2},V.createElement(B,{color:`white`,wrap:`wrap`},e.userMessage.content))),(c.length>0||e.assistantMessages.length>0)&&V.createElement(z,{flexDirection:`column`,marginBottom:1},V.createElement(B,{bold:!0,color:Z.primary},`◆ StackOne Agent`),c.length>0&&V.createElement(z,{paddingLeft:2,marginTop:0,marginBottom:1},V.createElement(Ft,{tools:c,expanded:ve})),e.assistantMessages.map((n,r)=>{let i=r===e.assistantMessages.length-1;return V.createElement(z,{key:`asst-${t}-${r}`,paddingLeft:2,flexDirection:`column`,marginBottom:i?0:1},n.isSubagent&&V.createElement(B,{color:Z.primary,dimColor:!0},`⚡ Subagent`),V.createElement(B,{wrap:`wrap`,dimColor:!i},bt(n.content)))}),s&&V.createElement(z,{paddingLeft:2,marginTop:1},V.createElement(B,{dimColor:!0},`✓ `,s))),e.systemMessages.map((e,n)=>V.createElement(z,{key:`sys-${t}-${n}`,marginBottom:1},V.createElement(B,{color:`gray`},`ℹ System • `,e.timestamp.toLocaleTimeString()),V.createElement(z,{paddingLeft:2},V.createElement(B,{dimColor:!0,wrap:`wrap`},e.content)))))})),V.createElement(z,{flexDirection:`column`,marginBottom:1},V.createElement(V.Fragment,null,(b||S)&&V.createElement(z,{marginBottom:0,marginTop:0,borderStyle:`single`,borderColor:Z.primary,paddingX:2,paddingY:1,flexDirection:`column`,height:R?`100%`:void 0},V.createElement(B,{bold:!0,color:Z.primary},S?`✓`:`⚡`,` Subprocess:`,` `,x,` `,S?`(Complete)`:``,` `,R?`(Expanded)`:``),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},S?R?`Press Ctrl+O or ESC to collapse`:`Press Ctrl+O to expand`:R?`Running... Press Ctrl+O or ESC to collapse`:`Running... Press Ctrl+O to expand`)),R?V.createElement(V.Fragment,null,s.filter(e=>e.isSubagent&&!e.content.startsWith(`TOOL_START:`)).map((e,t)=>{let n=e.role===`system`&&e.content.startsWith(`TOOL:`),r=e.role===`assistant`?`⚡ Subagent`:`ℹ System`,i=e.content;if(n){let t=Gt(e.content);r=`🔧 Tool • ${t.name}`,i=t.output.slice(0,500),t.output.length>500&&(i+=`
10
+ ... (truncated)`)}return V.createElement(z,{key:`${e.timestamp.getTime()}-${t}-${e.role}-subagent`,marginTop:1,flexDirection:`column`},V.createElement(B,{bold:!0,color:Z.primary},r,V.createElement(B,{color:`gray`},` `,`•`,` `,e.timestamp.toLocaleTimeString())),V.createElement(z,{paddingLeft:2},V.createElement(B,{color:n?`gray`:Z.primary,dimColor:n,wrap:`wrap`},bt(i))))}),!S&&!f&&l&&c.length===0&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{dimColor:!0},` Thinking...`)),!S&&!f&&c.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},c.map((e,t)=>V.createElement(z,{key:t,marginBottom:1},e.status===`running`&&V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{color:Z.primary},` `,e.skillName?V.createElement(V.Fragment,null,`✨ Skill •`,` `,e.skillName):V.createElement(V.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`)))),!S&&m&&!f&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},bt(m)))):V.createElement(V.Fragment,null,s.filter(e=>e.isSubagent&&!e.content.startsWith(`TOOL_START:`)&&e.role!==`system`||e.content.startsWith(`TOOL:`)).slice(-2).map((e,t)=>{let n=e.role===`system`&&e.content.startsWith(`TOOL:`),r=e.content;if(n){let t=Gt(e.content);r=`🔧 ${t.name}: ${t.output.slice(0,100)}${t.output.length>100?`...`:``}`}let i=r.split(`
11
11
  `).slice(0,2).join(`
12
- `);return V.createElement(z,{key:t,marginTop:1},V.createElement(B,{color:Z.primary,dimColor:n},mt(i),r.split(`
13
- `).length>2&&`...`))}),!S&&!f&&l&&c.length===0&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{dimColor:!0},` Thinking...`)),!S&&!f&&c.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},c.slice(-2).map((e,t)=>V.createElement(z,{key:t,marginBottom:1},e.status===`running`&&V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{color:Z.primary},` `,e.skillName?V.createElement(V.Fragment,null,`✨ Skill •`,` `,e.skillName):V.createElement(V.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`))),c.length>2&&V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`... and`,` `,c.length-2,` `,`more (Ctrl+O to expand)`))),!S&&m&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},mt(m).split(`
12
+ `);return V.createElement(z,{key:t,marginTop:1},V.createElement(B,{color:Z.primary,dimColor:n},bt(i),r.split(`
13
+ `).length>2&&`...`))}),!S&&!f&&l&&c.length===0&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{dimColor:!0},` Thinking...`)),!S&&!f&&c.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},c.slice(-2).map((e,t)=>V.createElement(z,{key:t,marginBottom:1},e.status===`running`&&V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{color:Z.primary},` `,e.skillName?V.createElement(V.Fragment,null,`✨ Skill •`,` `,e.skillName):V.createElement(V.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`))),c.length>2&&V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`... and`,` `,c.length-2,` `,`more (Ctrl+O to expand)`))),!S&&m&&V.createElement(z,{marginTop:1},V.createElement(B,{color:Z.primary},bt(m).split(`
14
14
  `).slice(0,2).join(`
15
- `),mt(m).split(`
15
+ `),bt(m).split(`
16
16
  `).length>2&&`
17
- ...`))))),m&&!b&&!f&&V.createElement(z,{marginBottom:1,flexDirection:`column`},V.createElement(B,{bold:!0,color:Z.primary},`◆ StackOne Agent`,V.createElement(B,{color:`gray`},` • `,new Date().toLocaleTimeString())),V.createElement(z,{paddingLeft:2},V.createElement(B,{wrap:`wrap`},mt(m)))),!b&&!f&&c.length>0&&V.createElement(z,{marginBottom:1,paddingLeft:2},V.createElement(kt,{tools:c.map(e=>({name:e.name,inputSummary:e.inputSummary||``,output:``,status:e.status===`failed`?`failed`:e.status,skillName:e.skillName}))}))),re&&re.length>0&&V.createElement(_t,{phases:re,currentPhase:ie}),!b&&!f&&l&&c.length===0&&V.createElement(z,{marginBottom:1},V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{dimColor:!0},` Thinking...`),O&&V.createElement(B,{dimColor:!0},` `,V.createElement(jt,{startTime:O}))),f&&V.createElement(z,{marginTop:1},V.createElement(B,{color:`red`},`⏺ Interrupted · What should the StackOne Agent do instead?`)),d&&V.createElement(z,{marginBottom:1,borderStyle:`single`,borderColor:`red`,paddingX:2,paddingY:1,flexDirection:`column`},V.createElement(B,{color:`red`},`✗ `,d),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Press Enter to try again or Ctrl+C to exit`))),u&&V.createElement(z,{marginBottom:1,borderStyle:`single`,borderColor:Z.primary,paddingX:2},V.createElement(B,{color:Z.primary},`✓ Complete`)),g&&V.createElement(z,{marginBottom:1,borderStyle:`single`,borderColor:Z.primary,paddingX:2,paddingY:1,flexDirection:`column`},L?V.createElement(V.Fragment,null,V.createElement(B,{bold:!0,color:Z.primary},g.items[I].name),g.type!==`trust`&&V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},g.items[I].description)),g.type===`skills`&&V.createElement(z,{flexDirection:`column`},g.items[I].version?V.createElement(B,{dimColor:!0},`Version:`,` `,String(g.items[I].version)):null,g.items[I].author?V.createElement(B,{dimColor:!0},`Author:`,` `,String(g.items[I].author)):null,g.items[I].tags&&Array.isArray(g.items[I].tags)?V.createElement(B,{dimColor:!0},`Tags:`,` `,g.items[I].tags.join(`, `)):null,g.items[I].content?V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{bold:!0},`Skill Content:`),V.createElement(z,{marginTop:1},V.createElement(B,{wrap:`wrap`},String(g.items[I].content).slice(0,2e3),String(g.items[I].content).length>2e3?`
17
+ ...`))))),m&&!b&&!f&&V.createElement(z,{marginBottom:1,flexDirection:`column`},V.createElement(B,{bold:!0,color:Z.primary},`◆ StackOne Agent`,V.createElement(B,{color:`gray`},` • `,new Date().toLocaleTimeString())),V.createElement(z,{paddingLeft:2},V.createElement(B,{wrap:`wrap`},bt(m)))),!b&&!f&&c.length>0&&V.createElement(z,{marginBottom:1,paddingLeft:2},V.createElement(Ft,{tools:c.map(e=>({name:e.name,inputSummary:e.inputSummary||``,output:``,status:e.status===`failed`?`failed`:e.status,skillName:e.skillName}))}))),re&&re.length>0&&V.createElement(Ct,{phases:re,currentPhase:ie}),!b&&!f&&l&&c.length===0&&V.createElement(z,{marginBottom:1},V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),V.createElement(B,{dimColor:!0},` Thinking...`),k&&V.createElement(B,{dimColor:!0},` `,V.createElement(Lt,{startTime:k}))),f&&V.createElement(z,{marginTop:1},V.createElement(B,{color:`red`},`⏺ Interrupted · What should the StackOne Agent do instead?`)),d&&V.createElement(z,{marginBottom:1,borderStyle:`single`,borderColor:`red`,paddingX:2,paddingY:1,flexDirection:`column`},V.createElement(B,{color:`red`},`✗ `,d),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Press Enter to try again or Ctrl+C to exit`))),u&&V.createElement(z,{marginBottom:1,borderStyle:`single`,borderColor:Z.primary,paddingX:2},V.createElement(B,{color:Z.primary},`✓ Complete`)),g&&V.createElement(z,{marginBottom:1,borderStyle:`single`,borderColor:Z.primary,paddingX:2,paddingY:1,flexDirection:`column`},L?V.createElement(V.Fragment,null,V.createElement(B,{bold:!0,color:Z.primary},g.items[I].name),g.type!==`trust`&&V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},g.items[I].description)),g.type===`skills`&&V.createElement(z,{flexDirection:`column`},g.items[I].version?V.createElement(B,{dimColor:!0},`Version:`,` `,String(g.items[I].version)):null,g.items[I].author?V.createElement(B,{dimColor:!0},`Author:`,` `,String(g.items[I].author)):null,g.items[I].tags&&Array.isArray(g.items[I].tags)?V.createElement(B,{dimColor:!0},`Tags:`,` `,g.items[I].tags.join(`, `)):null,g.items[I].content?V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{bold:!0},`Skill Content:`),V.createElement(z,{marginTop:1},V.createElement(B,{wrap:`wrap`},String(g.items[I].content).slice(0,2e3),String(g.items[I].content).length>2e3?`
18
18
 
19
19
  ... (content truncated)`:``))):V.createElement(B,{dimColor:!0},`No content available`)),g.type===`tools`&&V.createElement(z,{flexDirection:`column`},V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Category:`,` `,String(g.items[I].category))),V.createElement(z,{marginTop:1},V.createElement(B,{bold:!0},`Input Parameters:`)),g.items[I].inputSchema?V.createElement(z,{marginTop:1,paddingLeft:2,flexDirection:`column`},(()=>{let e=g.items[I].inputSchema,t=e.properties||{},n=e.required||[];return Object.entries(t).map(([e,t])=>V.createElement(z,{key:e,flexDirection:`column`,marginBottom:1},V.createElement(B,null,e,n.includes(e)?` *`:``,V.createElement(B,{dimColor:!0},` `,`(`,t.type?String(t.type):`any`,`)`)),t.description?V.createElement(z,{paddingLeft:2},V.createElement(B,{dimColor:!0},String(t.description))):null))})(),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`* = required parameter`))):V.createElement(z,{marginTop:1,paddingLeft:2},V.createElement(B,{dimColor:!0},`No parameters`)),V.createElement(z,{marginTop:1},V.createElement(B,{bold:!0},`Output:`)),V.createElement(z,{marginTop:1,paddingLeft:2},V.createElement(B,{dimColor:!0},`Returns JSON with tool execution results`))),g.type===`trust`&&V.createElement(z,{flexDirection:`column`,marginTop:1},V.createElement(B,null,V.createElement(B,{dimColor:!0},`Path: `),V.createElement(B,null,String(g.items[I].path))),V.createElement(B,null,V.createElement(B,{dimColor:!0},`Trusted at: `),V.createElement(B,null,g.items[I].trustedAt?new Date(g.items[I].trustedAt).toLocaleString():`N/A`))),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Press Esc to go back`))):ke?V.createElement(V.Fragment,null,V.createElement(B,{bold:!0,color:`yellow`},`⚠️ Remove Trust`),V.createElement(z,{flexDirection:`column`,marginTop:1},V.createElement(B,{color:`white`},`Are you sure you want to remove trust from:`),V.createElement(B,{color:`cyan`,bold:!0},ke.path)),V.createElement(z,{flexDirection:`column`,marginTop:1},V.createElement(B,{color:`yellow`},`⚠️ This action is permanent. To trust this folder again,`),V.createElement(B,{color:`yellow`},`you must open a new chat session in that directory.`)),V.createElement(z,{marginTop:1},V.createElement(B,{color:K===0?`green`:`gray`,bold:K===0},K===0?`❯ [Y]es`:` Yes`),V.createElement(B,null,` `),V.createElement(B,{color:K===1?`green`:`gray`,bold:K===1},K===1?`❯ [N]o`:` No`)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`←→ to select • Enter to confirm • Esc to cancel`))):V.createElement(V.Fragment,null,V.createElement(B,{bold:!0,color:Z.primary},g.type===`skills`?`📚 Skills (${g.items.length})`:g.type===`tools`?`🔧 Tools (${g.items.length})`:g.type===`mcp`?`📡 MCP Servers (${g.items.filter(e=>e.connected).length}/${g.items.length} connected)`:g.type===`trust`?`📁 Trusted Folders (${g.items.length})`:g.type===`rewind`?`⏮️ Command History (${g.items.length})`:`💬 Recent Conversations (${g.items.length})`),V.createElement(z,{flexDirection:`column`,marginTop:1},g.items.map((e,t)=>{let n=t===I?`❯ `:` `,r=process.stdout.columns||80,i=Math.min(r-10,120),a=(e.name||``).replace(/\n/g,` ⏎ `),o=``;if(g.type===`mcp`?o=e.connected?`● `:`○ `:g.type===`trust`&&(o=e.trusted?`● `:`○ `),g.type===`skills`)return V.createElement(B,{key:t,color:t===I?Z.primary:`gray`},n,a);let s=e.tokens?` (~${e.tokens.toLocaleString()} tokens)`:``,c=i-(n.length+o.length+a.length+s.length)-5,l=``;if(e.description&&c>10){let t=String(e.description).replace(/\n/g,` ⏎ `);l=t.length>c?` - ${t.slice(0,c)}...`:` - ${t}`}let u=`${n}${o}${a}${s}${l}`,d=u.slice(0,i);return V.createElement(B,{key:t,color:t===I?Z.primary:`gray`},d,u.length>i?`...`:``)})),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},g.type===`skills`?`↑↓ Navigate • Enter for details • Esc to close`:g.type===`trust`?`↑↓ Navigate • Ctrl+O to remove trust • Enter for details • Esc to close`:g.type===`resume`?`↑↓ Navigate • Enter to resume • Esc to close`:g.type===`rewind`?`↑↓ Navigate • Enter to rewind to • Esc to close`:`↑↓ Navigate • Enter for details • Esc to close`)))),C.length>0&&V.createElement(z,{flexDirection:`column`,marginBottom:1},C.map((e,t)=>V.createElement(z,{key:t,marginBottom:t<C.length-1?1:0},V.createElement(B,{dimColor:!0},`📬 `),V.createElement(B,null,e.content))),te&&V.createElement(B,{dimColor:!0,italic:!0},`Processing...`)),T&&V.createElement(z,{marginBottom:1},V.createElement(B,{color:`yellow`},`Delete `),V.createElement(B,{color:`red`},T.isDirectory&&T.directoryContents?`${T.files.map(e=>e.split(`/`).pop()).join(`, `)}/ (${T.directoryContents.length} files)`:T.files.map(e=>e.split(`/`).pop()).join(`, `)),V.createElement(B,{color:`yellow`},`? `),V.createElement(B,{color:De===0?`green`:`gray`},De===0?`[Y]es`:`y`),V.createElement(B,null,`/`),V.createElement(B,{color:De===1?`green`:`gray`},De===1?`[N]o`:`n`)),ce&&!u&&!g&&!T&&V.createElement(V.Fragment,null,V.createElement(z,{borderStyle:`round`,borderColor:Z.primary,borderDimColor:!0,paddingX:2,flexDirection:`column`},(()=>{let e=process.stdout.columns||80,t=Math.max(20,e-6),n=P.current.split(`
20
- `),r=j.current,i=0,a=[];return n.forEach((e,o)=>{let s=i,c=s+e.length;i=c+1;let l=o===0,u=l?t-2:t,d=[];if(e.length===0)d.push(``);else{let n=e,r=!0;for(;n.length>0;){let e=r?u:t;d.push(n.slice(0,e)),n=n.slice(e),r=!1}}let f=0;d.forEach((e,t)=>{let i=s+f,u=i+e.length,p=l&&t===0,m=r>=i&&r<u,h=r===c&&o<n.length-1&&t===d.length-1,g=r===u&&t===d.length-1&&o===n.length-1,_=`${o}-${t}`;if(m||h||g){let t=r-i,n=e.slice(0,t),o=h?` `:e.charAt(t)||` `,s=h?``:e.slice(t+1);a.push(V.createElement(z,{key:_},p&&V.createElement(B,{color:Z.primary},`❯ `),V.createElement(B,{color:`white`},n),V.createElement(B,{backgroundColor:`white`,color:`black`,bold:!0},o),V.createElement(B,{color:`white`},s)))}else a.push(V.createElement(z,{key:_},p&&V.createElement(B,{color:Z.primary},`❯ `),V.createElement(B,{color:`white`},e||` `)));f+=e.length})}),a})()),fe.length>0&&V.createElement(z,{marginTop:1,paddingLeft:2,flexDirection:`column`},fe.map((e,t)=>V.createElement(z,{key:e},V.createElement(B,{color:t===me?Z.primary:`gray`},t===me?`❯ `:` `,e))))),h&&(()=>{let e=100-(h.input_tokens+h.output_tokens)/1e6*100,t=e>50?`green`:e>20?`yellow`:`red`,n=e<10;return V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{dimColor:!0},`📊 Model: Sonnet 4.5 • 🧠 Context left:`,` `,V.createElement(B,{color:t},e.toFixed(1),`%`)),n&&V.createElement(B,{color:`red`},`⚠️ Context low (`,e.toFixed(1),`% remaining)`))})(),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},ce?`Type message and press Enter • Shift+Enter for new line • `:``,(l||m||c.length>0)&&`ESC to stop • `,we?`Copied to clipboard! • `:`Ctrl+Y to copy last response • `,b?`Ctrl+O to expand subprocess • `:`Ctrl+O to show/hide full tool results • `,`Ctrl+C to clear/exit`)))},Vt=({timeRemaining:e,onRunSetup:t,onIgnore:n})=>{let{exit:r}=be(),[i,a]=W(0);xe((e,o)=>{if(e===`1`){t(),r();return}if(e===`2`){n(),r();return}o.upArrow?a(0):o.downArrow?a(1):o.return?i===0?(t(),r()):(n(),r()):o.escape&&(n(),r())});let o=`\x1B[38;2;0;175;102m`,{hours:s,minutes:c}=e,l=s>0?`${s} hour${s===1?``:`s`} and ${c} minute${c===1?``:`s`}`:`${c} minute${c===1?``:`s`}`;return V.createElement(z,{flexDirection:`column`,padding:2},V.createElement(z,{borderStyle:`round`,borderColor:`yellow`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0,color:`yellow`},`⚠️ Credential Warning`),V.createElement(B,null),V.createElement(B,null,`Your StackOne credentials expire in `,l,` (last day of 7-day validity).`),V.createElement(B,null),V.createElement(B,null,"To avoid interruption, run `stackone agent setup` to reauthenticate."),V.createElement(B,null),V.createElement(B,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Run stackone agent setup`),V.createElement(B,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. Ignore and continue`)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to continue`)))},Ht=({directory:e,onConfirm:t,onCancel:n})=>{let{exit:r}=be(),[i,a]=W(0);xe((e,o)=>{o.upArrow?a(0):o.downArrow?a(1):o.return?i===0?(t(),r()):(n(),r()):o.escape&&(n(),r())});let o=`\x1B[38;2;0;175;102m`;return V.createElement(z,{flexDirection:`column`,padding:2},V.createElement(z,{borderStyle:`round`,borderColor:`#00AF66`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0},`Do you trust the files in this folder?`),V.createElement(B,null),V.createElement(B,{dimColor:!0},e),V.createElement(B,null),V.createElement(B,null,`StackOne Agent may read, write, or execute files contained in this directory.`),V.createElement(B,null,`This can pose security risks, so only use files and commands from trusted sources.`),V.createElement(B,null),V.createElement(B,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Yes, proceed`),V.createElement(B,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. No, exit`)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to exit`)))},Ut=`claude-sonnet-4-6`;async function*Wt(e){let{provider:t,category:n,apiKey:r,mcpServers:i,verbose:a,workDir:o=`./connectors/${t}`,abortSignal:s}=e,c=new D({provider:t,category:n,workDir:o,baseOptions:{mode:`build`,model:Ut,apiKey:r,mcpServers:i,verbose:a,origin:`cli`,abortSignal:s,mcpCache:{enabled:!0},contextPreservation:{enabled:!0,provider:t,workDir:o}}});for await(let e of c.run())yield e}const Gt=()=>{try{let e=R(ge(w(import.meta.url).resolve(`@stackone/agent-harness`)),`mcp-servers`),t=P(e).filter(e=>e.endsWith(`.json`)),n=[];for(let r of t){let t=de(R(e,r),`utf-8`),i=JSON.parse(t);for(let[e,t]of Object.entries(i.mcpServers)){let r=`stdio`;if(t.type)r=t.type;else if(t.transport?.type){let n=t.transport.type;if(n!==`http`&&n!==`stdio`&&n!==`sse`){y.warn(`⚠️ Skipping MCP server "${e}": Invalid transport type "${n}". Must be "http", "stdio", or "sse"`);continue}r=n===`sse`?`http`:n}else t.url&&(r=`http`);let i={},a=t.transport?.headers||t.headers;if(a)for(let[t,n]of Object.entries(a))i[t]=n.replace(/\$\{([^}]+)\}/g,(n,r)=>{let i=process.env[r];return i===void 0?(y.warn(`[MCP] Warning: Environment variable '${r}' referenced in header '${t}' for server '${e}' is not set. Substituting empty string.`),``):i});if(t.auth?.type===`bearer`&&(i.Authorization=`Bearer ${t.auth.token.replace(/\$\{([^}]+)\}/g,(t,n)=>{let r=process.env[n];return r===void 0?(y.warn(`[MCP] Warning: Environment variable '${n}' for auth token in server '${e}' is not set`),``):r})}`),r===`http`&&!t.url){y.warn(`⚠️ Skipping MCP server "${e}": HTTP transport requires a URL`);continue}if(r===`stdio`){y.debug(`Skipping MCP server "${e}": stdio transport is not supported for bundled servers`);continue}n.push({name:e,transport:r,url:t?.url??``,headers:i})}}return n}catch(e){if(e.code===`ENOENT`)return y.log(`[MCP] No bundled MCP server configurations found in agent-harness package`),[];throw e}};let Kt;const qt=()=>{if(Kt!==void 0)return Kt;try{let e=Fe(Pe(Le(import.meta.url)),`..`,`package.json`);Kt=JSON.parse(ke(e,`utf8`)).version}catch{Kt=`unknown`}return Kt??`unknown`},Jt=(e,t)=>{try{if(t.existed&&t.content!==null){let n=L.dirname(e);return M.existsSync(n)||M.mkdirSync(n,{recursive:!0}),M.writeFileSync(e,t.content,`utf-8`),{success:!0,action:`restored`}}else return M.existsSync(e)?(M.unlinkSync(e),{success:!0,action:`deleted`}):{success:!0,action:`restored`}}catch(e){return{success:!1,action:`error`,error:e instanceof Error?e.message:String(e)}}},Yt=/<![^>]*>[\s\S]*<\/HTML>/gi,Xt=/API Error:\s*\d{3}.*?(?=API Error:|$)/gi,Zt=e=>e.replace(Yt,``).replace(Xt,``).trim(),Qt=e=>{let t=/<TITLE>([^<]*)<\/TITLE>/i.exec(e),n=/<H1>\s*(\d{3}[^<]*)<\/H1>/i.exec(e);if(t||n)return`HTTP ${n?.[1]?.trim()||``} from ${/cloudfront/i.test(e)?`CloudFront`:/nginx/i.test(e)?`Nginx`:`upstream`}`.trim();let r=/API Error:\s*\d{3}.*?(?=API Error:|$)/i.exec(e);return r?r[0].trim():/Failed to authenticate/i.test(e)?`Authentication failed`:null},$t=(e,t,n)=>{let r=[...new Set(e)],i=t.length,a=n.length,o=[];i>0?o.push(`Build failed — ${i}/${a} phases errored\n`):o.push(`Build failed
20
+ `),r=j.current,i=0,a=[];return n.forEach((e,o)=>{let s=i,c=s+e.length;i=c+1;let l=o===0,u=l?t-2:t,d=[];if(e.length===0)d.push(``);else{let n=e,r=!0;for(;n.length>0;){let e=r?u:t;d.push(n.slice(0,e)),n=n.slice(e),r=!1}}let f=0;d.forEach((e,t)=>{let i=s+f,u=i+e.length,p=l&&t===0,m=r>=i&&r<u,h=r===c&&o<n.length-1&&t===d.length-1,g=r===u&&t===d.length-1&&o===n.length-1,_=`${o}-${t}`;if(m||h||g){let t=r-i,n=e.slice(0,t),o=h?` `:e.charAt(t)||` `,s=h?``:e.slice(t+1);a.push(V.createElement(z,{key:_},p&&V.createElement(B,{color:Z.primary},`❯ `),V.createElement(B,{color:`white`},n),V.createElement(B,{backgroundColor:`white`,color:`black`,bold:!0},o),V.createElement(B,{color:`white`},s)))}else a.push(V.createElement(z,{key:_},p&&V.createElement(B,{color:Z.primary},`❯ `),V.createElement(B,{color:`white`},e||` `)));f+=e.length})}),a})()),fe.length>0&&V.createElement(z,{marginTop:1,paddingLeft:2,flexDirection:`column`},fe.map((e,t)=>V.createElement(z,{key:e},V.createElement(B,{color:t===me?Z.primary:`gray`},t===me?`❯ `:` `,e))))),h&&(()=>{let e=100-(h.input_tokens+h.output_tokens)/1e6*100,t=e>50?`green`:e>20?`yellow`:`red`,n=e<10;return V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{dimColor:!0},`📊 Model: Sonnet 4.5 • 🧠 Context left:`,` `,V.createElement(B,{color:t},e.toFixed(1),`%`)),n&&V.createElement(B,{color:`red`},`⚠️ Context low (`,e.toFixed(1),`% remaining)`))})(),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},ce?`Type message and press Enter • Shift+Enter for new line • `:``,(l||m||c.length>0)&&`ESC to stop • `,we?`Copied to clipboard! • `:`Ctrl+Y to copy last response • `,b?`Ctrl+O to expand subprocess • `:`Ctrl+O to show/hide full tool results • `,`Ctrl+C to clear/exit`)))},qt=({timeRemaining:e,onRunSetup:t,onIgnore:n})=>{let{exit:r}=be(),[i,a]=W(0);xe((e,o)=>{if(e===`1`){t(),r();return}if(e===`2`){n(),r();return}o.upArrow?a(0):o.downArrow?a(1):o.return?i===0?(t(),r()):(n(),r()):o.escape&&(n(),r())});let o=`\x1B[38;2;0;175;102m`,{hours:s,minutes:c}=e,l=s>0?`${s} hour${s===1?``:`s`} and ${c} minute${c===1?``:`s`}`:`${c} minute${c===1?``:`s`}`;return V.createElement(z,{flexDirection:`column`,padding:2},V.createElement(z,{borderStyle:`round`,borderColor:`yellow`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0,color:`yellow`},`⚠️ Credential Warning`),V.createElement(B,null),V.createElement(B,null,`Your StackOne credentials expire in `,l,` (last day of 7-day validity).`),V.createElement(B,null),V.createElement(B,null,"To avoid interruption, run `stackone agent setup` to reauthenticate."),V.createElement(B,null),V.createElement(B,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Run stackone agent setup`),V.createElement(B,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. Ignore and continue`)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to continue`)))},Jt=({directory:e,onConfirm:t,onCancel:n})=>{let{exit:r}=be(),[i,a]=W(0);xe((e,o)=>{o.upArrow?a(0):o.downArrow?a(1):o.return?i===0?(t(),r()):(n(),r()):o.escape&&(n(),r())});let o=`\x1B[38;2;0;175;102m`;return V.createElement(z,{flexDirection:`column`,padding:2},V.createElement(z,{borderStyle:`round`,borderColor:`#00AF66`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0},`Do you trust the files in this folder?`),V.createElement(B,null),V.createElement(B,{dimColor:!0},e),V.createElement(B,null),V.createElement(B,null,`StackOne Agent may read, write, or execute files contained in this directory.`),V.createElement(B,null,`This can pose security risks, so only use files and commands from trusted sources.`),V.createElement(B,null),V.createElement(B,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Yes, proceed`),V.createElement(B,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. No, exit`)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to exit`)))},Yt=`claude-sonnet-4-6`;async function*Xt(e){let{provider:t,category:n,apiKey:r,mcpServers:i,verbose:a,workDir:o=`./connectors/${t}`,abortSignal:s}=e,c=new D({provider:t,category:n,workDir:o,baseOptions:{mode:`build`,model:Yt,apiKey:r,mcpServers:i,verbose:a,origin:`cli`,abortSignal:s,mcpCache:{enabled:!0},contextPreservation:{enabled:!0,provider:t,workDir:o}}});for await(let e of c.run())yield e}const Zt=()=>{try{let e=R(ge(w(import.meta.url).resolve(`@stackone/agent-harness`)),`mcp-servers`),t=P(e).filter(e=>e.endsWith(`.json`)),n=[];for(let r of t){let t=de(R(e,r),`utf-8`),i=JSON.parse(t);for(let[e,t]of Object.entries(i.mcpServers)){let r=`stdio`;if(t.type)r=t.type;else if(t.transport?.type){let n=t.transport.type;if(n!==`http`&&n!==`stdio`&&n!==`sse`){y.warn(`⚠️ Skipping MCP server "${e}": Invalid transport type "${n}". Must be "http", "stdio", or "sse"`);continue}r=n===`sse`?`http`:n}else t.url&&(r=`http`);let i={},a=t.transport?.headers||t.headers;if(a)for(let[t,n]of Object.entries(a))i[t]=n.replace(/\$\{([^}]+)\}/g,(n,r)=>{let i=process.env[r];return i===void 0?(y.warn(`[MCP] Warning: Environment variable '${r}' referenced in header '${t}' for server '${e}' is not set. Substituting empty string.`),``):i});if(t.auth?.type===`bearer`&&(i.Authorization=`Bearer ${t.auth.token.replace(/\$\{([^}]+)\}/g,(t,n)=>{let r=process.env[n];return r===void 0?(y.warn(`[MCP] Warning: Environment variable '${n}' for auth token in server '${e}' is not set`),``):r})}`),r===`http`&&!t.url){y.warn(`⚠️ Skipping MCP server "${e}": HTTP transport requires a URL`);continue}if(r===`stdio`){y.debug(`Skipping MCP server "${e}": stdio transport is not supported for bundled servers`);continue}n.push({name:e,transport:r,url:t?.url??``,headers:i})}}return n}catch(e){if(e.code===`ENOENT`)return y.log(`[MCP] No bundled MCP server configurations found in agent-harness package`),[];throw e}};let Qt;const $t=()=>{if(Qt!==void 0)return Qt;try{let e=Fe(Pe(Le(import.meta.url)),`..`,`package.json`);Qt=JSON.parse(ke(e,`utf8`)).version}catch{Qt=`unknown`}return Qt??`unknown`},en=(e,t)=>{try{if(t.existed&&t.content!==null){let n=L.dirname(e);return M.existsSync(n)||M.mkdirSync(n,{recursive:!0}),M.writeFileSync(e,t.content,`utf-8`),{success:!0,action:`restored`}}else return M.existsSync(e)?(M.unlinkSync(e),{success:!0,action:`deleted`}):{success:!0,action:`restored`}}catch(e){return{success:!1,action:`error`,error:e instanceof Error?e.message:String(e)}}},tn=/<![^>]*>[\s\S]*<\/HTML>/gi,nn=/API Error:\s*\d{3}.*?(?=API Error:|$)/gi,rn=e=>e.replace(tn,``).replace(nn,``).trim(),an=e=>{let t=/<TITLE>([^<]*)<\/TITLE>/i.exec(e),n=/<H1>\s*(\d{3}[^<]*)<\/H1>/i.exec(e);if(t||n)return`HTTP ${n?.[1]?.trim()||``} from ${/cloudfront/i.test(e)?`CloudFront`:/nginx/i.test(e)?`Nginx`:`upstream`}`.trim();let r=/API Error:\s*\d{3}.*?(?=API Error:|$)/i.exec(e);return r?r[0].trim():/Failed to authenticate/i.test(e)?`Authentication failed`:null},on=(e,t,n)=>{let r=[...new Set(e)],i=t.length,a=n.length,o=[];i>0?o.push(`Build failed — ${i}/${a} phases errored\n`):o.push(`Build failed
21
21
  `);for(let e of r)o.push(` ${e}`);let s=r.join(` `);return/400|Bad Request/i.test(s)?o.push(`
22
22
  This usually means the model is not supported or the request was malformed.`,`Check that your STACKONE_AGENT_TOKEN is valid and the model is available.`):/401|Unauthorized|403|Forbidden/i.test(s)?o.push(`
23
23
  Your API key may be invalid or expired.`,`Check your STACKONE_AGENT_TOKEN configuration.`):/429|rate limit/i.test(s)?o.push(`
24
24
  Rate limit hit. Wait a moment and try again.`):/5\d{2}|Internal Server Error|Service Unavailable/i.test(s)&&o.push(`
25
25
  The API is experiencing issues. Try again shortly.`),o.join(`
26
- `)},en=[{name:`commands`,description:`Show all available commands`,argumentHint:``,source:`cli`},{name:`skills`,description:`View and toggle skills (max 8)`,argumentHint:``,source:`cli`},{name:`tools`,description:`View available tools`,argumentHint:``,source:`cli`},{name:`mcp`,description:`List configured MCP servers`,argumentHint:``,source:`cli`},{name:`trust`,description:`View and manage trusted folders`,argumentHint:``,source:`cli`},{name:`compact`,description:`Summarize conversation to free up context`,argumentHint:``,source:`cli`},{name:`exit`,description:`Exit the agent (or use Ctrl+C)`,argumentHint:``,source:`cli`}],tn=new Set([`heapdump`]);function nn(e,t){let n=new Map(t.map(e=>[e.name,e]));for(let t of e)!n.has(t.name)&&!tn.has(t.name)&&n.set(t.name,{...t,source:`harness`});return Array.from(n.values())}const rn=({mode:e,connector:t,action:n,goal:r,verbose:i,temperature:a,apiKey:o})=>{let[s,l]=W([]),d=U([]);d.current=s;let[f,p]=W(new Map),[m,h]=W(!1),[g,_]=W(),[ee,v]=W(!1),[b,x]=W(!0),[S,C]=W([]),[te,w]=W([]),[T,E]=W(``),[ne]=W(),[D,j]=W(!1),[ce,le]=W(null),N=U(ae()),ue=U(O()),[de]=W(new Date),[P,fe]=W(0),[pe,me]=W(!1),I=U(!1),[he,ge]=W(``),[R,_e]=W(!1),[ve,z]=W([]),[B,ye]=W(!1),[be,xe]=W(!1),we=U(!1),[Te,Ee]=W(),[De,Oe]=W(),G=U({shouldStop:!1,requestId:0,controller:null}),[ke,Ae]=W([]),K=U(null),[je,Me]=W([]),Ne=U(null),Pe=U([]),Fe=U(0),[Ie,Le]=W({claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]}),[q,Re]=W(en),ze=U(new Map),Be=U(-1),[Ve,He]=W(null),J=U(null),Ue=U({operation:``,phase:`idle`}),Y=(e,t=!1)=>{let n=Ue.current,r=e;n.operation&&(r=`${r}\n\nContext: ${n.operation}`);let i={idle:`Agent was idle`,thinking:`Agent was processing your request`,tool_execution:n.toolName?`Agent was executing tool: ${n.toolName}`:`Agent was executing a tool`,streaming:`Agent was generating a response`};if(n.phase!==`idle`&&(r=`${r}\nPhase: ${i[n.phase]}`),t&&n.toolName&&n.toolInput)try{let e=typeof n.toolInput==`string`?n.toolInput:JSON.stringify(n.toolInput,null,2),t=e.length>500?e.slice(0,500)+`...`:e;r=`${r}\nTool input: ${t}`}catch{}return r},X=Ce(()=>{let e={};try{let t=c();t?.email&&(e.credentialEmail=t.email);let n=u(t);n.status===`valid`&&(e.credentialTimeRemaining=n.timeRemaining)}catch{}if(!t)try{let t=process.cwd(),n=M.readdirSync(t).find(e=>e.endsWith(`.connector.s1.yaml`));if(n)e.detectedConnector=n.replace(`.connector.s1.yaml`,``);else{let n=L.join(t,`src`,`configs`);if(M.existsSync(n)&&M.statSync(n).isDirectory()){let t=M.readdirSync(n);if(t.length===1){let r=L.join(n,t[0],`${t[0]}.connector.s1.yaml`);M.existsSync(r)&&(e.detectedConnector=t[0])}}}}catch{}try{let t=L.join(F.homedir(),`.stackone`,`conversations`);if(M.existsSync(t)){let n=M.readdirSync(t).filter(e=>e.endsWith(`.json`)).sort().reverse(),r=[];for(let e of n.slice(0,3)){let t=e.match(/^\d+-(.+)\.json$/);t&&r.push(t[1].replace(/-/g,` `))}r.length>0&&(e.recentConversations=r)}}catch{}return e},[t]);H(()=>{let e=L.join(F.homedir(),`.stackone`,`agent_history`);try{if(M.existsSync(e)){let t=M.readFileSync(e,`utf-8`),n;try{let e=JSON.parse(t);n=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()):t.split(`
26
+ `)},sn=[{name:`commands`,description:`Show all available commands`,argumentHint:``,source:`cli`},{name:`skills`,description:`View and toggle skills (max 8)`,argumentHint:``,source:`cli`},{name:`tools`,description:`View available tools`,argumentHint:``,source:`cli`},{name:`mcp`,description:`List configured MCP servers`,argumentHint:``,source:`cli`},{name:`trust`,description:`View and manage trusted folders`,argumentHint:``,source:`cli`},{name:`compact`,description:`Summarize conversation to free up context`,argumentHint:``,source:`cli`},{name:`exit`,description:`Exit the agent (or use Ctrl+C)`,argumentHint:``,source:`cli`}],cn=new Set([`heapdump`]);function ln(e,t){let n=new Map(t.map(e=>[e.name,e]));for(let t of e)!n.has(t.name)&&!cn.has(t.name)&&n.set(t.name,{...t,source:`harness`});return Array.from(n.values())}const un=({mode:e,connector:t,action:n,goal:r,verbose:i,temperature:a,apiKey:o})=>{let[s,l]=W([]),d=U([]);d.current=s;let[f,p]=W(new Map),[m,h]=W(!1),[g,_]=W(),[ee,v]=W(!1),[b,x]=W(!0),[S,C]=W([]),[te,w]=W([]),[T,E]=W(``),[ne]=W(),[D,j]=W(!1),[ce,le]=W(null),N=U(O()),ue=U(k()),[de]=W(new Date),[P,fe]=W(0),[pe,me]=W(!1),I=U(!1),[he,ge]=W(``),[R,_e]=W(!1),[ve,z]=W([]),[B,ye]=W(!1),[be,xe]=W(!1),we=U(!1),[Te,Ee]=W(),[De,Oe]=W(),G=U({shouldStop:!1,requestId:0,controller:null}),[ke,Ae]=W([]),K=U(null),[je,Me]=W([]),Ne=U(null),Pe=U([]),Fe=U(0),[Ie,Le]=W({claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]}),[q,Re]=W(sn),ze=U(new Map),Be=U(-1),[Ve,He]=W(null),Ue=U(null),J=U({operation:``,phase:`idle`}),We=(e,t=!1)=>{let n=J.current,r=e;n.operation&&(r=`${r}\n\nContext: ${n.operation}`);let i={idle:`Agent was idle`,thinking:`Agent was processing your request`,tool_execution:n.toolName?`Agent was executing tool: ${n.toolName}`:`Agent was executing a tool`,streaming:`Agent was generating a response`};if(n.phase!==`idle`&&(r=`${r}\nPhase: ${i[n.phase]}`),t&&n.toolName&&n.toolInput)try{let e=typeof n.toolInput==`string`?n.toolInput:JSON.stringify(n.toolInput,null,2),t=e.length>500?e.slice(0,500)+`...`:e;r=`${r}\nTool input: ${t}`}catch{}return r},Y=Ce(()=>{let e={};try{let t=c();t?.email&&(e.credentialEmail=t.email);let n=u(t);n.status===`valid`&&(e.credentialTimeRemaining=n.timeRemaining)}catch{}if(!t)try{let t=process.cwd(),n=M.readdirSync(t).find(e=>e.endsWith(`.connector.s1.yaml`));if(n)e.detectedConnector=n.replace(`.connector.s1.yaml`,``);else{let n=L.join(t,`src`,`configs`);if(M.existsSync(n)&&M.statSync(n).isDirectory()){let t=M.readdirSync(n);if(t.length===1){let r=L.join(n,t[0],`${t[0]}.connector.s1.yaml`);M.existsSync(r)&&(e.detectedConnector=t[0])}}}}catch{}try{let t=L.join(F.homedir(),`.stackone`,`conversations`);if(M.existsSync(t)){let n=M.readdirSync(t).filter(e=>e.endsWith(`.json`)).sort().reverse(),r=[];for(let e of n.slice(0,3)){let t=e.match(/^\d+-(.+)\.json$/);t&&r.push(t[1].replace(/-/g,` `))}r.length>0&&(e.recentConversations=r)}}catch{}return e},[t]);H(()=>{let e=L.join(F.homedir(),`.stackone`,`agent_history`);try{if(M.existsSync(e)){let t=M.readFileSync(e,`utf-8`),n;try{let e=JSON.parse(t);n=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()):t.split(`
27
27
  `).filter(e=>e.trim())}catch{n=t.split(`
28
- `).filter(e=>e.trim())}w(n)}}catch(e){i&&y.error(`[History] Failed to load command history:`,e)}},[i]);let We=U([]);H(()=>{(async()=>{let t={claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]};try{try{let e=k(),n=A();C(e.map(e=>{let t=L.join(n,e,`SKILL.md`),r,i;try{if(M.existsSync(t)){let e=M.readFileSync(t,`utf-8`);i=e;let n=e.match(/^---\n([\s\S]*?)\n---/);if(n){let e=n[1].match(/description:\s*\|?\s*\n?([\s\S]*?)(?=\n\w+:|$)/);e&&(r=e[1].trim().split(`
29
- `)[0].trim())}}}catch{}return{name:e,description:r,content:i}})),t.claudeSkills={count:e.length,names:e,totalSize:0}}catch(e){y.error(`[Skills] Failed to load skills:`,e),t.errors.push(`Failed to load skills`)}try{let e=Gt();We.current=e;for(let n of e)t.mcpServers.push({name:n.name,count:0});let n=`fetch.extract_html_text.web_search.vector_search.get_external_integrations.analyze_external_integration.analyze_external_integrations.get_external_repos.scan_external_repo.search_external_repo.get_provider_coverage.get_providers.map_provider_key.get_stackone_actions.meta_feedback.get_stackone_categories.get_docs.get_stackone_expressions.extract_oas_actions.get_provider_actions.scramble_credentials.improve_descriptions.discover_actions.get_improve_descriptions_task_status.get_discover_actions_task_status.test_actions.get_test_actions_task_status.analyze_versioning.get_analyze_versioning_task_status.falcon_workflow.falcon_research.falcon_build.falcon_oauth.falcon_test.falcon_security`.split(`.`);t.mcpServers.push({name:`stackone`,count:n.length}),t.toolCounts.mcpByServer.stackone=n}catch(e){t.errors.push(`MCP: ${e instanceof Error?e.message:String(e)}`)}t.toolCounts.builtin=[`Read`,`Write`,`Edit`,`Glob`,`Grep`,`Bash`,`WebSearch`,`WebFetch`],t.toolCounts.total=t.toolCounts.builtin.length;try{Re(nn(await(await ie({prompt:``,mode:e,apiKey:o})).supportedCommands(),en))}catch(e){i&&y.warn(`[Commands] Failed to fetch harness commands:`,e)}Le(t)}catch(e){y.error(`[Init] Failed to initialize runtime:`,e)}finally{x(!1)}})()},[o,e,i]),H(()=>{we.current=be},[be]),H(()=>{if(ne&&!D){let e=ne.input_tokens+ne.output_tokens,t=(1e6-e)/1e6*100;if(t<10){let n={role:`system`,content:`⚠️ Context Warning\n\nYou have ${t.toFixed(1)}% context remaining (${(1e6-e).toLocaleString()} tokens).\n\nConsider using /compact to summarize the conversation and free up context.`,timestamp:new Date};l(e=>[...e,n]),j(!0)}}},[ne,D]);let Ge=Se(async r=>{try{let i=d.current,a=i.filter(e=>e.role===`user`||e.role===`assistant`);if(a.length<2)return;let o=r.trim().slice(0,50)||a.find(e=>e.role===`user`)?.content?.slice(0,50)||`conversation`;await M.promises.mkdir(L.join(F.homedir(),`.stackone`,`conversations`),{recursive:!0});let s=Date.now(),c=`${s}-${o.replace(/[^a-zA-Z0-9]/g,`-`).toLowerCase().slice(0,50)}.json`,l=L.join(F.homedir(),`.stackone`,`conversations`,c);await M.promises.writeFile(l,JSON.stringify({title:o,timestamp:s,goal:r,messages:i.filter(e=>e.role!==`system`),mode:e,connector:t,action:n},null,2))}catch(e){y.error(`Failed to save conversation:`,e)}},[e,t,n]),Ke=async(e,t,n,r)=>{let a=[`research`,`discover-actions`,`build-and-validate`];Ee(a.map(e=>({name:e,status:`pending`})));let s=new Map,c=L.join(F.homedir(),`.stackone`),u=L.join(c,`build-debug.log`);M.existsSync(c)||M.mkdirSync(c,{recursive:!0});let d=M.createWriteStream(u,{flags:`w`}),f=e=>{d.write(`${JSON.stringify({ts:new Date().toISOString(),...e})}\n`)};d.on(`error`,()=>{f=()=>{}}),f({event:`build_start`,provider:e,category:t,model:Ut,mcpServerCount:We.current.length});let m=console.log,g=console.error;console.log=(...e)=>{f({event:`console_log`,args:e.map(String)})},console.error=(...e)=>{f({event:`console_error`,args:e.map(String)})};try{for await(let c of Wt({provider:e,category:t,apiKey:o,mcpServers:We.current,verbose:i||!1,abortSignal:r})){if(!n())return;if(c.type===`agent_message`){let e=c.message;f({event:`agent_message`,phase:c.phase,msgType:e.type,...e.type===`text`&&{content:e.content},...e.type===`error`&&{error:e.error},...e.type===`tool_call`&&{toolName:e.toolName}})}else f({...c,timestamp:void 0});switch(c.type){case`phase_start`:Oe(c.phase),Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:`running`,model:c.model}:e));break;case`phase_complete`:{let e=c.result.warnings&&c.result.warnings.length>0,t=s.get(c.phase),n=t&&t.length>0,r=!c.result.success||n,i=r?`error`:e?`warning`:`complete`;Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:i,durationMs:c.result.durationMs}:e)),r?_($t(t&&t.length>0?t:[c.result.error||`Unknown error`],[c.phase],a)):e&&l(e=>[...e,{role:`system`,content:`⚠️ Phase "${c.phase}" completed with warnings:\n${c.result.warnings?.join(`
30
- `)}`,timestamp:new Date}]);break}case`phase_error`:Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:`error`,durationMs:c.result?.durationMs}:e)),_($t([c.error||`Unknown error`],[c.phase],a));break;case`phase_skipped`:Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:`skipped`}:e));break;case`agent_message`:{let e=c.message;if(e.type===`text`){let t=e.content??``,n=Qt(t);if(n){let e=s.get(c.phase)??[];e.includes(n)||e.push(n),s.set(c.phase,e)}let r=Zt(t);E(e=>e+(r||``))}else if(e.type===`tool_call`){let t=`tc-${++Fe.current}`;Pe.current.push(t),E(e=>(e&&l(t=>[...t,{role:`assistant`,content:e,timestamp:new Date}]),``)),p(n=>{let r=new Map(n);return r.set(t,{name:e.toolName??``,status:`running`}),r})}else if(e.type===`tool_result`){let e=Pe.current.shift();e&&p(t=>{let n=new Map(t);return n.delete(e),n})}else e.type===`error`&&_(e.error??`Unknown error`);break}}}if(E(e=>{if(e){let t=Qt(e);if(t){let e=s.get(`_unattributed`)??[];e.includes(t)||e.push(t),s.set(`_unattributed`,e)}let n=Zt(e);n&&l(e=>[...e,{role:`assistant`,content:n,timestamp:new Date}])}return``}),s.size>0){let e=[...new Set([...s.values()].flat())],t=[...s.keys()].filter(e=>e!==`_unattributed`);Ee(e=>(e||[]).map(e=>s.has(e.name)&&e.status===`complete`?{...e,status:`error`}:e)),_($t(e,t,a))}Oe(void 0)}catch(e){let t=e instanceof Error?e.message:String(e);f({event:`build_error`,error:t}),_(t)}finally{f({event:`build_end`,phaseErrors:Object.fromEntries(s)}),console.log=m,console.error=g,d.end(),Ee(e=>(e||[]).map(e=>e.status===`pending`||e.status===`running`?{...e,status:`skipped`}:e)),h(!1),xe(!1),we.current=!1,p(new Map)}},qe=Se(async(r,a=!1)=>{if((b||we.current)&&!a){z(e=>[...e,{content:r,timestamp:new Date}]),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{Ye()},3e4);return}if(_(void 0),v(!1),r===`/skills`){if(S.length===0){let e={role:`system`,content:`📚 No skills loaded. Skills will be loaded on startup.`,timestamp:new Date};l(t=>[...t,e]);return}le({type:`skills`,items:S.map(e=>({name:e.name,description:e.description,content:e.content}))});return}if(r===`/tools`){let e=[];for(let t of Ie.mcpServers){let n=Ie.toolCounts.mcpByServer[t.name]||[];for(let r of n)e.push({name:r,description:`MCP tool (${t.name})`,category:`MCP:${t.name}`})}let t=[...Ie.toolCounts.builtin.map(e=>({name:e,description:`Built-in (from agent harness)`,category:`Built-in`})),...e,...Ie.mcpServers.filter(e=>!Ie.toolCounts.mcpByServer[e.name]?.length).map(e=>({name:e.name,description:e.name===`stackone`?`MCP server (${e.count} tools) - from agent harness`:`MCP server (${e.count} tools)`,category:`MCP`}))];le({type:`tools`,items:t.length>0?t:[{name:`—`,description:`Tools provided by harness (built-in + skills + MCP)`,category:``}]});return}if(r===`/commands`){let e=`📋 Available Commands:
28
+ `).filter(e=>e.trim())}w(n)}}catch(e){i&&y.error(`[History] Failed to load command history:`,e)}},[i]);let X=U([]);H(()=>{(async()=>{let t={claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]};try{try{let e=se(),n=A();C(e.map(e=>{let t=L.join(n,e,`SKILL.md`),r,i;try{if(M.existsSync(t)){let e=M.readFileSync(t,`utf-8`);i=e;let n=e.match(/^---\n([\s\S]*?)\n---/);if(n){let e=n[1].match(/description:\s*\|?\s*\n?([\s\S]*?)(?=\n\w+:|$)/);e&&(r=e[1].trim().split(`
29
+ `)[0].trim())}}}catch{}return{name:e,description:r,content:i}})),t.claudeSkills={count:e.length,names:e,totalSize:0}}catch(e){y.error(`[Skills] Failed to load skills:`,e),t.errors.push(`Failed to load skills`)}try{let e=Zt();X.current=e;for(let n of e)t.mcpServers.push({name:n.name,count:0});let n=`fetch.extract_html_text.web_search.vector_search.get_external_integrations.analyze_external_integration.analyze_external_integrations.get_external_repos.scan_external_repo.search_external_repo.get_provider_coverage.get_providers.map_provider_key.get_stackone_actions.meta_feedback.get_stackone_categories.get_docs.get_stackone_expressions.extract_oas_actions.get_provider_actions.scramble_credentials.improve_descriptions.discover_actions.get_improve_descriptions_task_status.get_discover_actions_task_status.test_actions.get_test_actions_task_status.analyze_versioning.get_analyze_versioning_task_status.falcon_workflow.falcon_research.falcon_build.falcon_oauth.falcon_test.falcon_security`.split(`.`);t.mcpServers.push({name:`stackone`,count:n.length}),t.toolCounts.mcpByServer.stackone=n}catch(e){t.errors.push(`MCP: ${e instanceof Error?e.message:String(e)}`)}t.toolCounts.builtin=[`Read`,`Write`,`Edit`,`Glob`,`Grep`,`Bash`,`WebSearch`,`WebFetch`],t.toolCounts.total=t.toolCounts.builtin.length;try{Re(ln(await(await ie({prompt:``,mode:e,apiKey:o})).supportedCommands(),sn))}catch(e){i&&y.warn(`[Commands] Failed to fetch harness commands:`,e)}Le(t)}catch(e){y.error(`[Init] Failed to initialize runtime:`,e)}finally{x(!1)}})()},[o,e,i]),H(()=>{we.current=be},[be]),H(()=>{if(ne&&!D){let e=ne.input_tokens+ne.output_tokens,t=(1e6-e)/1e6*100;if(t<10){let n={role:`system`,content:`⚠️ Context Warning\n\nYou have ${t.toFixed(1)}% context remaining (${(1e6-e).toLocaleString()} tokens).\n\nConsider using /compact to summarize the conversation and free up context.`,timestamp:new Date};l(e=>[...e,n]),j(!0)}}},[ne,D]);let Ge=Se(async r=>{try{let i=d.current,a=i.filter(e=>e.role===`user`||e.role===`assistant`);if(a.length<2)return;let o=r.trim().slice(0,50)||a.find(e=>e.role===`user`)?.content?.slice(0,50)||`conversation`;await M.promises.mkdir(L.join(F.homedir(),`.stackone`,`conversations`),{recursive:!0});let s=Date.now(),c=`${s}-${o.replace(/[^a-zA-Z0-9]/g,`-`).toLowerCase().slice(0,50)}.json`,l=L.join(F.homedir(),`.stackone`,`conversations`,c);await M.promises.writeFile(l,JSON.stringify({title:o,timestamp:s,goal:r,messages:i.filter(e=>e.role!==`system`),mode:e,connector:t,action:n},null,2))}catch(e){y.error(`Failed to save conversation:`,e)}},[e,t,n]),Ke=async(e,t,n,r)=>{let a=[`research`,`discover-actions`,`build-and-validate`];Ee(a.map(e=>({name:e,status:`pending`})));let s=new Map,c=L.join(F.homedir(),`.stackone`),u=L.join(c,`build-debug.log`);M.existsSync(c)||M.mkdirSync(c,{recursive:!0});let d=M.createWriteStream(u,{flags:`w`}),f=e=>{d.write(`${JSON.stringify({ts:new Date().toISOString(),...e})}\n`)};d.on(`error`,()=>{f=()=>{}}),f({event:`build_start`,provider:e,category:t,model:Yt,mcpServerCount:X.current.length});let m=console.log,g=console.error;console.log=(...e)=>{f({event:`console_log`,args:e.map(String)})},console.error=(...e)=>{f({event:`console_error`,args:e.map(String)})};try{for await(let c of Xt({provider:e,category:t,apiKey:o,mcpServers:X.current,verbose:i||!1,abortSignal:r})){if(!n())return;if(c.type===`agent_message`){let e=c.message;f({event:`agent_message`,phase:c.phase,msgType:e.type,...e.type===`text`&&{content:e.content},...e.type===`error`&&{error:e.error},...e.type===`tool_call`&&{toolName:e.toolName}})}else f({...c,timestamp:void 0});switch(c.type){case`phase_start`:Oe(c.phase),Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:`running`,model:c.model}:e));break;case`phase_complete`:{let e=c.result.warnings&&c.result.warnings.length>0,t=s.get(c.phase),n=t&&t.length>0,r=!c.result.success||n,i=r?`error`:e?`warning`:`complete`;Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:i,durationMs:c.result.durationMs}:e)),r?_(on(t&&t.length>0?t:[c.result.error||`Unknown error`],[c.phase],a)):e&&l(e=>[...e,{role:`system`,content:`⚠️ Phase "${c.phase}" completed with warnings:\n${c.result.warnings?.join(`
30
+ `)}`,timestamp:new Date}]);break}case`phase_error`:Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:`error`,durationMs:c.result?.durationMs}:e)),_(on([c.error||`Unknown error`],[c.phase],a));break;case`phase_skipped`:Ee(e=>(e||[]).map(e=>e.name===c.phase?{...e,status:`skipped`}:e));break;case`agent_message`:{let e=c.message;if(e.type===`text`){let t=e.content??``,n=an(t);if(n){let e=s.get(c.phase)??[];e.includes(n)||e.push(n),s.set(c.phase,e)}let r=rn(t);E(e=>e+(r||``))}else if(e.type===`tool_call`){let t=`tc-${++Fe.current}`;Pe.current.push(t),E(e=>(e&&l(t=>[...t,{role:`assistant`,content:e,timestamp:new Date}]),``)),p(n=>{let r=new Map(n);return r.set(t,{name:e.toolName??``,status:`running`}),r})}else if(e.type===`tool_result`){let e=Pe.current.shift();e&&p(t=>{let n=new Map(t);return n.delete(e),n})}else e.type===`error`&&_(e.error??`Unknown error`);break}}}if(E(e=>{if(e){let t=an(e);if(t){let e=s.get(`_unattributed`)??[];e.includes(t)||e.push(t),s.set(`_unattributed`,e)}let n=rn(e);n&&l(e=>[...e,{role:`assistant`,content:n,timestamp:new Date}])}return``}),s.size>0){let e=[...new Set([...s.values()].flat())],t=[...s.keys()].filter(e=>e!==`_unattributed`);Ee(e=>(e||[]).map(e=>s.has(e.name)&&e.status===`complete`?{...e,status:`error`}:e)),_(on(e,t,a))}Oe(void 0)}catch(e){let t=e instanceof Error?e.message:String(e);f({event:`build_error`,error:t}),_(t)}finally{f({event:`build_end`,phaseErrors:Object.fromEntries(s)}),console.log=m,console.error=g,d.end(),Ee(e=>(e||[]).map(e=>e.status===`pending`||e.status===`running`?{...e,status:`skipped`}:e)),h(!1),xe(!1),we.current=!1,p(new Map)}},qe=Se(async(r,a=!1)=>{if((b||we.current)&&!a){z(e=>[...e,{content:r,timestamp:new Date}]),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{Ye()},3e4);return}if(_(void 0),v(!1),r===`/skills`){if(S.length===0){let e={role:`system`,content:`📚 No skills loaded. Skills will be loaded on startup.`,timestamp:new Date};l(t=>[...t,e]);return}le({type:`skills`,items:S.map(e=>({name:e.name,description:e.description,content:e.content}))});return}if(r===`/tools`){let e=[];for(let t of Ie.mcpServers){let n=Ie.toolCounts.mcpByServer[t.name]||[];for(let r of n)e.push({name:r,description:`MCP tool (${t.name})`,category:`MCP:${t.name}`})}let t=[...Ie.toolCounts.builtin.map(e=>({name:e,description:`Built-in (from agent harness)`,category:`Built-in`})),...e,...Ie.mcpServers.filter(e=>!Ie.toolCounts.mcpByServer[e.name]?.length).map(e=>({name:e.name,description:e.name===`stackone`?`MCP server (${e.count} tools) - from agent harness`:`MCP server (${e.count} tools)`,category:`MCP`}))];le({type:`tools`,items:t.length>0?t:[{name:`—`,description:`Tools provided by harness (built-in + skills + MCP)`,category:``}]});return}if(r===`/commands`){let e=`📋 Available Commands:
31
31
 
32
32
  `;for(let t of q){let n=t.argumentHint?` ${t.argumentHint}`:``;e+=` /${t.name}${n} - ${t.description}\n`}let t={role:`system`,content:e,timestamp:new Date};l(e=>[...e,t]);return}if(r===`/exit`&&process.exit(0),r===`/instructions`){let r=[`📜 Active Instructions
33
33
  `];if(S.length>0){r.push(`Skills Loaded (${S.length}):`);for(let e of S)r.push(` • ${e.name}${e.description?` - ${e.description}`:``}`);r.push(``)}r.push(`Session Context:`),r.push(` • Mode: ${e}`),t&&r.push(` • Connector: ${t}`),n&&r.push(` • Action: ${n}`),r.push(` • Turn Count: ${P}`),r.push(``);let i={instructions:`Mode: ${e}\nSkills: ${S.map(e=>e.name).join(`, `)||`none`}\nConnector: ${t||`none`}`,skills:S.map(e=>({name:e.name,description:e.description,enabled:!0})),session:{id:`current`,startedAt:de,mode:e,turnCount:P}},a=N.current.render(`instructions`,i);a?.content&&r.push(a.content);let o={role:`system`,content:r.join(`
@@ -48,9 +48,9 @@ Folders are automatically trusted when you open a chat session in them.`,timesta
48
48
  `),t=e.length>2e3?e.slice(0,2e3)+`
49
49
 
50
50
  [... truncated for context]`:e;h(!1);let n={role:`system`,content:`🗜️ Compact mode activated - recent context:\n\n${t}`,timestamp:new Date};l(e=>[e[e.length-1],n])}catch(e){h(!1),_(e instanceof Error?e.message:`Failed to summarize conversation`)}return}w(e=>{let t=r.trim();if(!t)return e;let n=[...e,t],a=n.length-1;Be.current=a,ze.current.has(a)||ze.current.set(a,{commandIndex:a,command:t,timestamp:Date.now(),files:new Map});let o=L.join(F.homedir(),`.stackone`,`agent_history`);try{let e=L.dirname(o);M.existsSync(e)||M.mkdirSync(e,{recursive:!0});let t=n.slice(-1e3);M.writeFileSync(o,JSON.stringify(t),`utf-8`)}catch(e){i&&y.error(`[History] Failed to save command history:`,e)}return n});let d={role:`user`,content:r,timestamp:new Date};l(e=>[...e,d]),h(!0),xe(!0),fe(e=>e+1),G.current.requestId+=1,G.current.shouldStop=!1,G.current.controller=new AbortController;let f=G.current.requestId,m=G.current.controller.signal;Ne.current&&=(clearTimeout(Ne.current),null),Me([]);let g=()=>!G.current.shouldStop&&G.current.requestId===f;try{let a=s.filter(e=>(e.role===`user`||e.role===`assistant`)&&!e.isSubagent).map(e=>({role:e.role,content:e.content})).slice(-20).map(e=>`${e.role}: ${e.content.slice(0,500)}`).join(`
51
- `);Pe.current=[],Fe.current=0;let c=se(r);if(e===`build`&&c.isConnectorBuild&&c.provider){await Ke(c.provider,c.category,g,m);return}try{i&&(y.log(`
52
- [AGENT:CONFIG] ═══════════════════════════════════════`),y.log(`[AGENT:CONFIG] Prompt: "${r.slice(0,100)}..."`),y.log(`[AGENT:CONFIG] Mode: ${e}`),y.log(`[AGENT:CONFIG] MCP Servers: ${We.current.map(e=>e.name).join(`, `)||`none`}`),y.log(`[AGENT:CONFIG] API Key: ${o?`${o.slice(0,15)}...`:`MISSING`}`),y.log(`[AGENT:CONFIG] Context keys: ${Object.keys({connector:t,action:n}).filter(e=>({connector:t,action:n})[e]).join(`, `)||`none`}`),y.log(`[AGENT:CONFIG] Max turns: 1000`),y.log(`[AGENT:CONFIG] ═══════════════════════════════════════
53
- `));let s=0,c=Date.now();for await(let u of oe({prompt:r,mode:e,mcpServers:We.current,apiKey:o,context:{connector:t,action:n,conversationSummary:a||void 0},maxTurns:1e3,verbose:i||!1,streaming:!1,origin:`cli`,abortSignal:m,cliVersion:qt()})){s++;let e=Date.now()-c;if(i){let t=u.type===`text`?` content="${(u.content||``).slice(0,30)}..."`:u.type===`error`?` error="${u.error}"`:u.type===`tool_call`?` tool="${u.toolName}"`:``;y.log(`[AGENT:MSG #${s}] type=${u.type}${t} (${e}ms)`)}if(!g())return;if(u.type===`text`){Ue.current.phase=`streaming`,E(e=>e+(u.content??``)),Je();continue}if(u.type===`skill_invocation`){let e=`skill-${++Fe.current}`;p(t=>{let n=new Map(t);return n.set(e,{name:`Skill`,status:`running`,skillName:u.skillName,inputSummary:u.skillArgs}),n}),setTimeout(()=>{p(t=>{let n=new Map(t);return n.delete(e),n})},2e3);continue}if(u.type===`tool_call`){Ue.current={operation:`Processing: "${r.slice(0,100)}${r.length>100?`...`:``}"`,phase:`tool_execution`,toolName:u.toolName,toolInput:u.toolInput};let e=`tc-${++Fe.current}`;if(Pe.current.push(e),Ae(t=>[...t,{id:e,name:u.toolName??``,input:u.toolInput,output:void 0}]),u.toolName===`spawn_subagent`&&u.toolInput){let e=u.toolInput,t=e.description??e.goal??e.name??`Subagent`;if(typeof t==`string`&&t.length>50){let e=String(t).split(/[.!?]/)[0];t=e.length>50?e.slice(0,47)+`...`:e}ge(String(t)),I.current=!0,setTimeout(()=>me(!0),10)}let t=u.toolInput,n=``;t&&typeof t==`object`&&(t.command?n=String(t.command).slice(0,100):t.file_path?n=String(t.file_path):t.pattern?n=String(t.pattern):t.url?n=String(t.url):t.query&&(n=String(t.query))),E(e=>(e&&l(t=>[...t,{role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current}]),``)),p(t=>{let r=new Map(t);return r.set(e,{name:u.toolName??``,status:`running`,inputSummary:n}),r});continue}if(u.type===`tool_result`){Ue.current={...Ue.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=Pe.current.shift();if(e){Ae(t=>t.map(t=>t.id===e?{...t,output:u.toolResult}:t));let t=``;p(n=>{let r=n.get(e);r?.inputSummary&&(t=r.inputSummary);let i=new Map(n);return i.delete(e),i});let n=typeof u.toolResult==`string`?u.toolResult:JSON.stringify(u.toolResult,null,2),r={role:`system`,content:`TOOL:${u.toolName}|||${t}|||${n}`,timestamp:new Date,isSubagent:I.current};l(e=>[...e,r])}continue}if(u.type===`tool_progress`){let e=u.progress;u.toolName&&p(t=>{let n=new Map(t);for(let[t,r]of n)if(r.name===u.toolName){n.set(t,{...r,inputSummary:e?.operation||r.inputSummary});break}return n});continue}if(u.type===`tool_error`){Ue.current={...Ue.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=Pe.current.shift();e&&(Ae(t=>t.map(t=>t.id===e?{...t,output:`Error: ${u.error}`}:t)),p(t=>{let n=new Map(t);return n.delete(e),n}));continue}if(u.type===`error`){let e=u.error??`Unknown error`,t=e;if(i){y.log(`
51
+ `);Pe.current=[],Fe.current=0;let c=oe(r);if(e===`build`&&c.isConnectorBuild&&c.provider){await Ke(c.provider,c.category,g,m);return}try{i&&(y.log(`
52
+ [AGENT:CONFIG] ═══════════════════════════════════════`),y.log(`[AGENT:CONFIG] Prompt: "${r.slice(0,100)}..."`),y.log(`[AGENT:CONFIG] Mode: ${e}`),y.log(`[AGENT:CONFIG] MCP Servers: ${X.current.map(e=>e.name).join(`, `)||`none`}`),y.log(`[AGENT:CONFIG] API Key: ${o?`${o.slice(0,15)}...`:`MISSING`}`),y.log(`[AGENT:CONFIG] Context keys: ${Object.keys({connector:t,action:n}).filter(e=>({connector:t,action:n})[e]).join(`, `)||`none`}`),y.log(`[AGENT:CONFIG] Max turns: 1000`),y.log(`[AGENT:CONFIG] ═══════════════════════════════════════
53
+ `));let s=0,c=Date.now();for await(let u of ae({prompt:r,mode:e,mcpServers:X.current,apiKey:o,context:{connector:t,action:n,conversationSummary:a||void 0},maxTurns:1e3,verbose:i||!1,streaming:!1,origin:`cli`,abortSignal:m,cliVersion:$t()})){s++;let e=Date.now()-c;if(i){let t=u.type===`text`?` content="${(u.content||``).slice(0,30)}..."`:u.type===`error`?` error="${u.error}"`:u.type===`tool_call`?` tool="${u.toolName}"`:``;y.log(`[AGENT:MSG #${s}] type=${u.type}${t} (${e}ms)`)}if(!g())return;if(u.type===`text`){J.current.phase=`streaming`,E(e=>e+(u.content??``)),Je();continue}if(u.type===`skill_invocation`){let e=`skill-${++Fe.current}`;p(t=>{let n=new Map(t);return n.set(e,{name:`Skill`,status:`running`,skillName:u.skillName,inputSummary:u.skillArgs}),n}),setTimeout(()=>{p(t=>{let n=new Map(t);return n.delete(e),n})},2e3);continue}if(u.type===`tool_call`){J.current={operation:`Processing: "${r.slice(0,100)}${r.length>100?`...`:``}"`,phase:`tool_execution`,toolName:u.toolName,toolInput:u.toolInput};let e=`tc-${++Fe.current}`;if(Pe.current.push(e),Ae(t=>[...t,{id:e,name:u.toolName??``,input:u.toolInput,output:void 0}]),u.toolName===`spawn_subagent`&&u.toolInput){let e=u.toolInput,t=e.description??e.goal??e.name??`Subagent`;if(typeof t==`string`&&t.length>50){let e=String(t).split(/[.!?]/)[0];t=e.length>50?e.slice(0,47)+`...`:e}ge(String(t)),I.current=!0,setTimeout(()=>me(!0),10)}let t=u.toolInput,n=``;t&&typeof t==`object`&&(t.command?n=String(t.command).slice(0,100):t.file_path?n=String(t.file_path):t.pattern?n=String(t.pattern):t.url?n=String(t.url):t.query&&(n=String(t.query))),E(e=>(e&&l(t=>[...t,{role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current}]),``)),p(t=>{let r=new Map(t);return r.set(e,{name:u.toolName??``,status:`running`,inputSummary:n}),r});continue}if(u.type===`tool_result`){J.current={...J.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=Pe.current.shift();if(e){Ae(t=>t.map(t=>t.id===e?{...t,output:u.toolResult}:t));let t=``;p(n=>{let r=n.get(e);r?.inputSummary&&(t=r.inputSummary);let i=new Map(n);return i.delete(e),i});let n=typeof u.toolResult==`string`?u.toolResult:JSON.stringify(u.toolResult,null,2),r={role:`system`,content:`TOOL:${u.toolName}|||${t}|||${n}`,timestamp:new Date,isSubagent:I.current};l(e=>[...e,r])}continue}if(u.type===`tool_progress`){let e=u.progress;u.toolName&&p(t=>{let n=new Map(t);for(let[t,r]of n)if(r.name===u.toolName){n.set(t,{...r,inputSummary:e?.operation||r.inputSummary});break}return n});continue}if(u.type===`tool_error`){J.current={...J.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=Pe.current.shift();e&&(Ae(t=>t.map(t=>t.id===e?{...t,output:`Error: ${u.error}`}:t)),p(t=>{let n=new Map(t);return n.delete(e),n}));continue}if(u.type===`error`){let e=u.error??`Unknown error`,t=e;if(i){y.log(`
54
54
  [AGENT:ERROR] ═══════════════════════════════════════`),y.log(`[AGENT:ERROR] Message: ${e}`),y.log(`[AGENT:ERROR] Full message object:`);try{y.log(JSON.stringify(u,null,2))}catch{y.log(`[AGENT:ERROR] (could not stringify message)`)}y.log(`[AGENT:ERROR] Messages received before error: ${s}`),y.log(`[AGENT:ERROR] Time elapsed: ${Date.now()-c}ms`),y.log(`[AGENT:ERROR] ═══════════════════════════════════════
55
55
  `)}e.includes(`exited with code 1`)?t=`Agent subprocess failed (exit code 1).
56
56
 
@@ -71,11 +71,11 @@ Run 'stackone agent setup' to refresh your credentials.
71
71
 
72
72
  Original error: ${e}`:(e.includes(`ENOTFOUND`)||e.includes(`ECONNREFUSED`)||e.includes(`network`))&&(t=`Network error. Check your internet connection.
73
73
 
74
- Original error: ${e}`),_(t),Ue.current={operation:``,phase:`idle`};continue}if(u.type===`done`){if(i){let e=Date.now()-c;y.log(`
74
+ Original error: ${e}`),_(t),J.current={operation:``,phase:`idle`};continue}if(u.type===`done`){if(i){let e=Date.now()-c;y.log(`
75
75
  [AGENT:DONE] ═══════════════════════════════════════`),y.log(`[AGENT:DONE] Total messages received: ${s}`),y.log(`[AGENT:DONE] Total time: ${e}ms`),y.log(`[AGENT:DONE] Status: ${u.status||`unknown`}`),s<=2&&y.log(`[AGENT:DONE] ⚠️ WARNING: Very few messages - agent may have failed early`),y.log(`[AGENT:DONE] ═══════════════════════════════════════
76
- `)}Ue.current={operation:``,phase:`idle`},h(!1),p(new Map),Ae([]);let e=I.current;E(t=>(t&&l(n=>[...n,{role:`assistant`,content:t,timestamp:new Date,isSubagent:e}]),``)),e?(I.current=!1,setTimeout(()=>{l(e=>{let t=e.filter(e=>e.isSubagent&&e.role===`assistant`).map(e=>e.content).join(`
76
+ `)}J.current={operation:``,phase:`idle`},h(!1),p(new Map),Ae([]);let e=I.current;E(t=>(t&&l(n=>[...n,{role:`assistant`,content:t,timestamp:new Date,isSubagent:e}]),``)),e?(I.current=!1,setTimeout(()=>{l(e=>{let t=e.filter(e=>e.isSubagent&&e.role===`assistant`).map(e=>e.content).join(`
77
77
 
78
- `);return t?.trim()?setTimeout(()=>{_e(!1),me(!1),setTimeout(()=>{try{qe(t,!0)}catch(e){y.error(`[SUBAGENT] Error:`,e),xe(!1)}},100)},300):(_e(!1),me(!1),xe(!1)),e})},100)):xe(!1),await Ge(r)}}}catch(e){if(!g())return;h(!1),p(new Map),_(Y(e instanceof Error?e.message:String(e),i||!1)),Ue.current={operation:``,phase:`idle`}}g()&&(h(!1),p(new Map),xe(!1),Ae([]),Ue.current={operation:``,phase:`idle`})}catch(e){if(!g()){i&&y.log(`[STREAM] Ignoring error from interrupted request:`,e instanceof Error?e.message:String(e));return}h(!1),p(new Map),xe(!1),Ae([]);let t=e instanceof Error?e.message:String(e);t.toLowerCase().includes(`cloudfront`)||t.includes(`403`)&&t.includes(`Request blocked`)?_(`⚠️ Request temporarily blocked by CloudFront
78
+ `);return t?.trim()?setTimeout(()=>{_e(!1),me(!1),setTimeout(()=>{try{qe(t,!0)}catch(e){y.error(`[SUBAGENT] Error:`,e),xe(!1)}},100)},300):(_e(!1),me(!1),xe(!1)),e})},100)):xe(!1),await Ge(r)}}}catch(e){if(!g())return;h(!1),p(new Map),_(We(e instanceof Error?e.message:String(e),i||!1)),J.current={operation:``,phase:`idle`}}g()&&(h(!1),p(new Map),xe(!1),Ae([]),J.current={operation:``,phase:`idle`})}catch(e){if(!g()){i&&y.log(`[STREAM] Ignoring error from interrupted request:`,e instanceof Error?e.message:String(e));return}h(!1),p(new Map),xe(!1),Ae([]);let t=e instanceof Error?e.message:String(e);t.toLowerCase().includes(`cloudfront`)||t.includes(`403`)&&t.includes(`Request blocked`)?_(`⚠️ Request temporarily blocked by CloudFront
79
79
 
80
80
  The API server's firewall blocked this request. This usually happens due to:
81
81
  • Rate limiting (too many requests in a short time)
@@ -96,19 +96,19 @@ To fix this:
96
96
 
97
97
  Original error: ${t}`):t.includes(`API key`)||t.includes(`Invalid API Key`)?(y.error(`
98
98
  ❌ Critical error:`,t),y.error(`Please check your configuration and try again.
99
- `),process.exit(1)):_(Y(t,i||!1)),Ue.current={operation:``,phase:`idle`},xe(!1),h(!1),p(new Map)}},[b,s,r,e,t,n,ne,D,o,pe,Ge]);H(()=>{b||r&&qe(r)},[b,r,e,Ie]);let Je=()=>{z(e=>(e.length===0||p(e=>(!(e.size>0)&&we.current&&(K.current&&=(clearTimeout(K.current),null),setTimeout(()=>Ye(),100)),e)),e))},Ye=()=>{z(e=>{if(e.length===0)return e;ye(!0),E(e=>{if(e){let t={role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current};l(e=>[...e,t])}return``});let t=e.map(e=>({role:`user`,content:e.content,timestamp:new Date}));l(e=>[...e,...t]);let n=e.map(e=>e.content).join(`
99
+ `),process.exit(1)):_(We(t,i||!1)),J.current={operation:``,phase:`idle`},xe(!1),h(!1),p(new Map)}},[b,s,r,e,t,n,ne,D,o,pe,Ge]);H(()=>{b||r&&qe(r)},[b,r,e,Ie]);let Je=()=>{z(e=>(e.length===0||p(e=>(!(e.size>0)&&we.current&&(K.current&&=(clearTimeout(K.current),null),setTimeout(()=>Ye(),100)),e)),e))},Ye=()=>{z(e=>{if(e.length===0)return e;ye(!0),E(e=>{if(e){let t={role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current};l(e=>[...e,t])}return``});let t=e.map(e=>({role:`user`,content:e.content,timestamp:new Date}));l(e=>[...e,...t]);let n=e.map(e=>e.content).join(`
100
100
 
101
101
  ---
102
102
 
103
- `);return ye(!1),xe(!1),Ae([]),K.current&&=(clearTimeout(K.current),null),setTimeout(()=>{qe(n,!0)},100),[]})},Xe=Se(async e=>{let{removeTrustedFolder:t,getTrustedFoldersForDisplay:n}=await import(`./trustedFolders-6UfkywNe.mjs`);t(e);let r=n();r.length===0?le(null):le({type:`trust`,items:r.map(e=>({name:e.name,description:e.path,path:e.path,trusted:e.trusted,trustedAt:e.trustedAt}))})},[le]);H(()=>{let e=S.map(e=>e.name);ue.current.setActiveSkills(e)},[S]),H(()=>{if(!b&&ve.length>0){let e=setTimeout(()=>{Je()},100);return()=>clearTimeout(e)}},[b,ve.length]);let Ze=()=>{},Qe=Se(()=>{G.current.shouldStop=!0,G.current.controller?.abort(),v(!0),E(e=>{if(e){let t=I.current,n={role:`assistant`,content:e,timestamp:new Date,isSubagent:t};l(e=>[...e,n])}return``}),h(!1),xe(!1),we.current=!1,p(new Map),Ae([]),l(e=>e.map(e=>{if(e.content.startsWith(`TOOL_START:`)){let t=e.content.split(`|||`)[1]||`unknown`;return{...e,content:`TOOL:${t}|||[Interrupted]|||`}}return e})),z([]),Me([]),ye(!1),Ne.current&&=(clearTimeout(Ne.current),null)},[]),$e=Se(e=>{J.current&&=(J.current.resolve(e),null),He(null)},[]);return b?V.createElement(Bt,{title:`Agent ${e.charAt(0).toUpperCase()+e.slice(1)} Mode`,mode:e,connector:t,action:n,messages:[],currentToolCalls:[],isThinking:!1,isComplete:!1,error:void 0,isInterrupted:!1,onSubmit:()=>{},onExit:Ze,onStop:Qe,slashCommands:q,welcomeContext:X}):V.createElement(Bt,{title:`Agent ${e.charAt(0).toUpperCase()+e.slice(1)} Mode`,mode:e,connector:t,action:n,messages:s,currentToolCalls:Array.from(f.values()),isThinking:m,isComplete:!1,error:g,isInterrupted:ee,onSubmit:qe,onExit:Ze,onStop:Qe,commandHistory:te,streamingText:T,usage:ne,detailViewData:ce,onCloseDetailView:()=>le(null),onToggleTrust:Xe,slashCommands:q,buildPhases:Te,currentBuildPhase:De,onRewindTo:e=>{try{let t=L.join(F.homedir(),`.stackone`,`agent_history`),n=M.readFileSync(t,`utf-8`),r;try{let e=JSON.parse(n);r=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()):n.split(`
103
+ `);return ye(!1),xe(!1),Ae([]),K.current&&=(clearTimeout(K.current),null),setTimeout(()=>{qe(n,!0)},100),[]})},Xe=Se(async e=>{let{removeTrustedFolder:t,getTrustedFoldersForDisplay:n}=await import(`./trustedFolders-6UfkywNe.mjs`);t(e);let r=n();r.length===0?le(null):le({type:`trust`,items:r.map(e=>({name:e.name,description:e.path,path:e.path,trusted:e.trusted,trustedAt:e.trustedAt}))})},[le]);H(()=>{let e=S.map(e=>e.name);ue.current.setActiveSkills(e)},[S]),H(()=>{if(!b&&ve.length>0){let e=setTimeout(()=>{Je()},100);return()=>clearTimeout(e)}},[b,ve.length]);let Ze=()=>{},Qe=Se(()=>{G.current.shouldStop=!0,G.current.controller?.abort(),v(!0),E(e=>{if(e){let t=I.current,n={role:`assistant`,content:e,timestamp:new Date,isSubagent:t};l(e=>[...e,n])}return``}),h(!1),xe(!1),we.current=!1,p(new Map),Ae([]),l(e=>e.map(e=>{if(e.content.startsWith(`TOOL_START:`)){let t=e.content.split(`|||`)[1]||`unknown`;return{...e,content:`TOOL:${t}|||[Interrupted]|||`}}return e})),z([]),Me([]),ye(!1),Ne.current&&=(clearTimeout(Ne.current),null)},[]),$e=Se(e=>{Ue.current&&=(Ue.current.resolve(e),null),He(null)},[]);return b?V.createElement(Kt,{title:`Agent ${e.charAt(0).toUpperCase()+e.slice(1)} Mode`,mode:e,connector:t,action:n,messages:[],currentToolCalls:[],isThinking:!1,isComplete:!1,error:void 0,isInterrupted:!1,onSubmit:()=>{},onExit:Ze,onStop:Qe,slashCommands:q,welcomeContext:Y}):V.createElement(Kt,{title:`Agent ${e.charAt(0).toUpperCase()+e.slice(1)} Mode`,mode:e,connector:t,action:n,messages:s,currentToolCalls:Array.from(f.values()),isThinking:m,isComplete:!1,error:g,isInterrupted:ee,onSubmit:qe,onExit:Ze,onStop:Qe,commandHistory:te,streamingText:T,usage:ne,detailViewData:ce,onCloseDetailView:()=>le(null),onToggleTrust:Xe,slashCommands:q,buildPhases:Te,currentBuildPhase:De,onRewindTo:e=>{try{let t=L.join(F.homedir(),`.stackone`,`agent_history`),n=M.readFileSync(t,`utf-8`),r;try{let e=JSON.parse(n);r=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()):n.split(`
104
104
  `).filter(e=>e.trim())}catch{r=n.split(`
105
- `).filter(e=>e.trim())}let i=new Map,a=[],o=[],s=[],c=Array.from(ze.current.keys()).filter(t=>t>e).sort((e,t)=>e-t);for(let e of c){let t=ze.current.get(e);if(t)for(let[e,n]of t.files)i.has(e)||i.set(e,n)}for(let[e,t]of i){let n=Jt(e,t);n.success?n.action===`deleted`?o.push(e):a.push(e):s.push(`${e}: ${n.error}`)}for(let e of c)ze.current.delete(e);Be.current=e;let u=r.slice(0,e+1);M.writeFileSync(t,JSON.stringify(u),`utf-8`);let d=`⏮️ Rewound to command: "${r[e]}"`;if(a.length>0||o.length>0){if(d+=`
105
+ `).filter(e=>e.trim())}let i=new Map,a=[],o=[],s=[],c=Array.from(ze.current.keys()).filter(t=>t>e).sort((e,t)=>e-t);for(let e of c){let t=ze.current.get(e);if(t)for(let[e,n]of t.files)i.has(e)||i.set(e,n)}for(let[e,t]of i){let n=en(e,t);n.success?n.action===`deleted`?o.push(e):a.push(e):s.push(`${e}: ${n.error}`)}for(let e of c)ze.current.delete(e);Be.current=e;let u=r.slice(0,e+1);M.writeFileSync(t,JSON.stringify(u),`utf-8`);let d=`⏮️ Rewound to command: "${r[e]}"`;if(a.length>0||o.length>0){if(d+=`
106
106
 
107
107
  📁 File changes:`,a.length>0){d+=`\n Restored (${a.length}):`;for(let e of a.slice(0,10))d+=`\n • ${L.basename(e)}`;a.length>10&&(d+=`\n ... and ${a.length-10} more`)}if(o.length>0){d+=`\n Deleted (${o.length}):`;for(let e of o.slice(0,10))d+=`\n • ${L.basename(e)}`;o.length>10&&(d+=`\n ... and ${o.length-10} more`)}}else d+=`
108
108
 
109
- 📁 No file changes to restore.`;if(s.length>0){d+=`\n\n⚠️ Errors (${s.length}):`;for(let e of s.slice(0,5))d+=`\n • ${e}`}let f={role:`system`,content:d,timestamp:new Date};l(e=>[...e,f]),w(u)}catch(e){let t={role:`system`,content:`❌ Error rewinding: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};l(e=>[...e,t])}},onResumeConversation:e=>{l(e.map(e=>({...e,timestamp:new Date(e.timestamp)})))},spawnedSubagentActive:pe,spawnedSubagentName:he,spawnedSubagentComplete:R,queuedMessages:ve,isProcessingQueue:B,initInfo:Ie,welcomeContext:X,pendingDeleteConfirmation:Ve,onConfirmDelete:$e})};var an=class{async execute(e){if(!process.execArgv.some(e=>e.startsWith(`--max-old-space-size`))){let{spawn:e}=await import(`child_process`);e(process.execPath,[`--max-old-space-size=8192`,...process.argv.slice(1)],{stdio:`inherit`,env:process.env}).on(`exit`,e=>{process.exit(e||0)});return}process.stdout.write(`\x1Bc`);let{getAgentApiKey:t,getAgentCredentialStatus:n,CredentialExpiredError:r,CredentialMissingError:i}=await import(`./agentApiKey-BoYyBKnD.mjs`),{hasOldSetupFiles:a,migrateFromLocalSetup:o,displayMigrationMessage:s}=await import(`./setupMigration-D_zUtD_W.mjs`);try{let r=process.cwd(),i=t();a(r)&&s(await o(r,i));let c=n(),l=c.status===`expiring_soon`?c.timeRemaining:void 0;process.env.STACKONE_AGENT_TOKEN||(process.env.STACKONE_AGENT_TOKEN=i);let u=L.join(F.homedir(),`.stackone`,`trusted_directories`),d=[];try{M.existsSync(u)&&(d=M.readFileSync(u,`utf-8`).split(`
110
- `).filter(e=>e.trim()))}catch(e){y.error(`[Trust] Failed to load trusted directories:`,e)}if(!d.includes(r)){let e=!1,{addTrustedFolder:t}=await import(`./trustedFolders-6UfkywNe.mjs`),{waitUntilExit:n}=ye(V.createElement(Ht,{directory:r,onConfirm:()=>{e=!0,t(r)},onCancel:()=>{e=!1}}));await n(),e||(y.log(`
111
- Exiting...`),process.exit(0)),process.stdout.write(`\x1Bc`)}let f=i;if(l){let e={current:`ignore`},{waitUntilExit:n}=ye(V.createElement(Vt,{timeRemaining:l,onRunSetup:()=>{e.current=`setup`},onIgnore:()=>{e.current=`ignore`}}));if(await n(),e.current===`setup`){process.stdout.write(`\x1Bc`);let{spawnSync:e}=await import(`node:child_process`),n=e(process.execPath,[process.argv[1],`agent`,`setup`],{stdio:`inherit`});n.status!==0&&process.exit(n.status??1);let r=t();process.env.STACKONE_AGENT_TOKEN=r,f=r}process.stdout.write(`\x1Bc`)}let{waitUntilExit:p}=ye(V.createElement(rn,{...e,apiKey:f}),{exitOnCtrlC:!1});await p()}catch(e){e instanceof r&&(y.error(`
109
+ 📁 No file changes to restore.`;if(s.length>0){d+=`\n\n⚠️ Errors (${s.length}):`;for(let e of s.slice(0,5))d+=`\n • ${e}`}let f={role:`system`,content:d,timestamp:new Date};l(e=>[...e,f]),w(u)}catch(e){let t={role:`system`,content:`❌ Error rewinding: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};l(e=>[...e,t])}},onResumeConversation:e=>{l(e.map(e=>({...e,timestamp:new Date(e.timestamp)})))},spawnedSubagentActive:pe,spawnedSubagentName:he,spawnedSubagentComplete:R,queuedMessages:ve,isProcessingQueue:B,initInfo:Ie,welcomeContext:Y,pendingDeleteConfirmation:Ve,onConfirmDelete:$e})};var dn=class{async execute(e){if(!process.execArgv.some(e=>e.startsWith(`--max-old-space-size`))){let{spawn:e}=await import(`child_process`);e(process.execPath,[`--max-old-space-size=8192`,...process.argv.slice(1)],{stdio:`inherit`,env:process.env}).on(`exit`,e=>{process.exit(e||0)});return}process.stdout.write(`\x1Bc`);let{getAgentApiKey:t,getAgentCredentialStatus:n,CredentialExpiredError:r,CredentialMissingError:i}=await import(`./agentApiKey-BoYyBKnD.mjs`),{hasOldSetupFiles:a,migrateFromLocalSetup:o,displayMigrationMessage:s}=await import(`./setupMigration-D_zUtD_W.mjs`);try{let r=process.cwd(),i=t();a(r)&&s(await o(r,i));let c=n(),l=c.status===`expiring_soon`?c.timeRemaining:void 0;process.env.STACKONE_AGENT_TOKEN||(process.env.STACKONE_AGENT_TOKEN=i);let u=L.join(F.homedir(),`.stackone`,`trusted_directories`),d=[];try{M.existsSync(u)&&(d=M.readFileSync(u,`utf-8`).split(`
110
+ `).filter(e=>e.trim()))}catch(e){y.error(`[Trust] Failed to load trusted directories:`,e)}if(!d.includes(r)){let e=!1,{addTrustedFolder:t}=await import(`./trustedFolders-6UfkywNe.mjs`),{waitUntilExit:n}=ye(V.createElement(Jt,{directory:r,onConfirm:()=>{e=!0,t(r)},onCancel:()=>{e=!1}}));await n(),e||(y.log(`
111
+ Exiting...`),process.exit(0)),process.stdout.write(`\x1Bc`)}let f=i;if(l){let e={current:`ignore`},{waitUntilExit:n}=ye(V.createElement(qt,{timeRemaining:l,onRunSetup:()=>{e.current=`setup`},onIgnore:()=>{e.current=`ignore`}}));if(await n(),e.current===`setup`){process.stdout.write(`\x1Bc`);let{spawnSync:e}=await import(`node:child_process`),n=e(process.execPath,[process.argv[1],`agent`,`setup`],{stdio:`inherit`});n.status!==0&&process.exit(n.status??1);let r=t();process.env.STACKONE_AGENT_TOKEN=r,f=r}process.stdout.write(`\x1Bc`)}let{waitUntilExit:p}=ye(V.createElement(un,{...e,apiKey:f}),{exitOnCtrlC:!1});await p()}catch(e){e instanceof r&&(y.error(`
112
112
  ❌ Credentials Expired
113
113
  `),y.log(T.white(`Your StackOne credentials have expired.
114
114
  `)),y.log(T.white("To continue using the agent, run `stackone agent setup` to reauthenticate.\n")),y.log(T.dim(`Credentials are valid for 7 days after authentication.
@@ -120,40 +120,40 @@ Exiting...`),process.exit(0)),process.stdout.write(`\x1Bc`)}let f=i;if(l){let e=
120
120
  `)),process.exit(1));let t=e instanceof Error?e.message:String(e);y.error(`
121
121
  ❌ Error:`,t),y.log(T.dim(`
122
122
  If you continue to see this error, try running:`)),y.log(T.cyan(` stackone agent setup
123
- `)),process.exit(1)}}},on=class{async execute(){y.log(T.blue.bold(`🧹 StackOne Agent Cleanup
123
+ `)),process.exit(1)}}},fn=class{async execute(){y.log(T.blue.bold(`🧹 StackOne Agent Cleanup
124
124
  `));try{let e=q(`Removing stored configuration...`).start();await p(),e.succeed(`Removed ~/.stackone/agent-config.json`);let t=q(`Removing MCP servers from Claude...`).start(),n=0;h(a(),_())&&n++,h(m(process.cwd()),s())&&n++,n>0?t.succeed(`Removed ${n} MCP server(s) from Claude`):t.warn(`No MCP servers found in Claude (already removed or not configured)`),y.success(`Cleanup complete!`),y.log(T.white(`
125
125
  What was removed:`)),y.log(T.cyan(` • ~/.stackone/agent-config.json`)),n>0&&y.log(T.cyan(` • MCP server entries from Claude configuration`)),y.log(T.dim(`
126
- To authenticate again:`)),y.log(T.cyan(` stackone agent setup`),T.dim(`(for global setup)`)),y.log(T.cyan(` stackone agent setup --local`),T.dim(`(for local project setup)`)),y.log(``),process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}};const sn=(e,t)=>e?!!(t?.email||t?.password||t?.passwordFromStdin||process.env.STACKONE_EMAIL?.trim()||process.env.STACKONE_PASSWORD?.trim()):!1,cn=`stackone-cli`,ln=async e=>{let t=`HTTP ${e.status}: ${e.statusText}`;try{let n=await e.text(),r=JSON.parse(n);return r.error_description||r.error||t}catch{return t}};var un=class{constructor(e){this.baseUrl=e||process.env.AUTH_SERVER_URL||`https://idp-api.stackone.com`}async login(e,t){try{let n=await fetch(`${this.baseUrl}/auth/sign-in/mcp`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({email:e,password:t})});if(!n.ok)return{success:!1,error:await ln(n)};let r=await n.json();return r.apiKey?{success:!0,apiKey:r.apiKey}:{success:!1,error:`Invalid response format`}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Network error occurred`}}}async validateKey(e){try{let t=await fetch(`${this.baseUrl}/api-key/verify`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({key:e})});return t.ok?await t.json():{valid:!1,error:await ln(t)}}catch(e){return{valid:!1,error:e instanceof Error?e.message:`Network error occurred`}}}async requestDeviceCode(){let e=await fetch(`${this.baseUrl}/api/auth/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_id:cn})});if(!e.ok)throw Error(await ln(e));return await e.json()}async pollDeviceToken(e){try{let t=await fetch(`${this.baseUrl}/api/auth/device/token`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({grant_type:`urn:ietf:params:oauth:grant-type:device_code`,device_code:e,client_id:cn})});if(t.ok)return{token:await t.json()};try{let e=await t.json();if(e.error)return{error:e}}catch{}return{error:{error:`server_error`,error_description:`HTTP ${t.status}: ${t.statusText}`}}}catch(e){return{error:{error:`network_error`,error_description:e instanceof Error?e.message:`Network error`}}}}async createApiKey(e){let t=10080*60,n=await fetch(`${this.baseUrl}/api/auth/api-key/create`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e}`},body:JSON.stringify({prefix:`falcon_key_`,expiresIn:t,name:`CLI Auth Key`})});if(!n.ok)throw Error(await ln(n));let r=await n.json(),i=new Date(Date.now()+t*1e3).toISOString();return{key:r.key,expiresAt:i}}};const dn=e=>new Promise(t=>{let n=he(),r,i;n===`darwin`?(r=`open`,i=[e]):n===`win32`?(r=`rundll32`,i=[`url.dll,FileProtocolHandler`,e]):(r=`xdg-open`,i=[e]),Te(r,i,e=>{t(!e)})}),fn=async(e,t)=>{let n=await e.requestDeviceCode(),r=await dn(n.verification_uri_complete),i=`Confirmation code: ${n.user_code}`;t(r?`Browser opened. ${i}\nWaiting for authentication...`:`Could not open browser. Please visit:\n ${n.verification_uri_complete}\n\n${i}`);let a=n.interval*1e3,o=0,s=Date.now()+n.expires_in*1e3;for(;Date.now()<s;){await new Promise(e=>setTimeout(e,a));let r=await e.pollDeviceToken(n.device_code);if(`token`in r){t(`Authenticated. Creating API key...`);let n=await e.createApiKey(r.token.access_token),i=await e.validateKey(n.key);return{success:!0,apiKey:n.key,email:i.email,userId:i.userId,expiresAt:n.expiresAt}}let i=r.error.error;if(i===`authorization_pending`){o=0;continue}if(i===`slow_down`){o=0,await new Promise(e=>setTimeout(e,a));continue}if(i===`expired_token`)return{success:!1,error:`Authentication session expired`};if(i===`access_denied`)return{success:!1,error:`Access denied by user`};if(o++,o>=5)return{success:!1,error:`Polling failed: ${r.error.error_description??`unknown error`}`}}return{success:!1,error:`Authentication timed out`}},pn=new un,mn=async()=>{let e=He({input:Be,output:Ve}),t=await new Promise(t=>{e.question(T.white(`Email: `),e=>{t(e.trim())})});return e.close(),t||(y.error(`Email is required`),process.exit(1)),t},hn=async()=>{process.stdin.isTTY&&(y.error(`--password-stdin was set but no input was piped to stdin`),process.exit(1));let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`).replace(/[\r\n]+$/,``)},gn=async e=>{let t=e.email?.trim()||process.env.STACKONE_EMAIL?.trim()||void 0,n;return e.passwordFromStdin?n=await hn():e.password?n=e.password:process.env.STACKONE_PASSWORD&&(n=process.env.STACKONE_PASSWORD),{email:t,password:n||void 0}},_n=async e=>{let t=await gn(e),n=t.email;if(!n){let e=await ee();if(e?.email){y.log(T.dim(`Last used email: ${e.email}\n`));let{useExisting:t}=await ze.prompt([{type:`confirm`,name:`useExisting`,message:`Sign in with this email?`,default:!0}]);n=t?e.email:await mn()}else n=await mn()}let r=t.password;r||=(e.passwordFromStdin&&(y.error(`Password is required`),process.exit(1)),(await ze.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}])).password),r||(y.error(`Password is required`),process.exit(1)),y.log(``);let i=q(`Authenticating...`).start(),a=await pn.login(n,r);(!a.success||!a.apiKey)&&(i.fail(`Authentication failed`),y.error(`${a.error||`Invalid credentials`}`),y.log(T.dim(`Please check your email and password and try again.
127
- `)),process.exit(1)),i.succeed(`Login successful!`);let o=new Date(Date.now()+10080*60*1e3).toISOString();return{apiKey:a.apiKey,email:n,expiresAt:o}},vn=async()=>{let e=q(`Starting browser authentication...`).start(),t;try{t=await fn(pn,t=>{e.text=t})}catch(t){e.fail(`Authentication failed`),y.error(t instanceof Error?t.message:`Unknown error`),process.exit(1)}(!t.success||!t.apiKey)&&(e.fail(`Authentication failed`),y.error(t.error||`Unknown error`),process.exit(1)),e.succeed(`Login successful!`);let n=t.expiresAt||new Date(Date.now()+10080*60*1e3).toISOString();return{apiKey:t.apiKey,email:t.email??``,userId:t.userId,expiresAt:n}},yn=async e=>{let t=await fn(pn,e);if(!t.success||!t.apiKey)throw Error(t.error||`Authentication failed`);let n=t.expiresAt||new Date(Date.now()+10080*60*1e3).toISOString(),r={apiKey:t.apiKey,userId:t.userId??t.email??``,email:t.email??``,expiresAt:n,serverUrl:g()};return await f(r),r},bn=async(e,t={})=>{let{apiKey:n,email:r,userId:i,expiresAt:a}=e?await _n(t):await vn(),o={apiKey:n,userId:i??r,email:r,expiresAt:a,serverUrl:g()};return await f(o),o},xn=e=>{let t=new Date(e),n=new Date,r=t.getTime()-n.getTime(),i=Math.floor(r/(1440*60*1e3)),a=Math.floor(r%(1440*60*1e3)/(3600*1e3)),o=t.toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`,hour12:!0});return`${t.toLocaleDateString(`en-US`,{weekday:`short`,month:`short`,day:`numeric`})} at ${o} (${i>0?`${i} days, ${a} hours`:`${a} hours`} from now)`};var Sn=class{async execute(e){y.log(T.blue.bold(`🤖 StackOne Agent Setup - Global Configuration
128
- `));try{let t=process.cwd(),n=await Re(`${t}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await Re(`${t}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r)if(y.warn(`Existing local setup detected:`),n&&y.log(T.dim(` • CLAUDE.md found in current directory`)),r&&y.log(T.dim(` • .mcp.json found in current directory`)),y.log(``),sn(!!e?.legacy,e?.credentials))y.log(T.dim(`Non-interactive credentials detected; proceeding without confirmation.
126
+ To authenticate again:`)),y.log(T.cyan(` stackone agent setup`),T.dim(`(for global setup)`)),y.log(T.cyan(` stackone agent setup --local`),T.dim(`(for local project setup)`)),y.log(``),process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}};const pn=(e,t)=>e?!!(t?.email||t?.password||t?.passwordFromStdin||process.env.STACKONE_EMAIL?.trim()||process.env.STACKONE_PASSWORD?.trim()):!1,mn=`stackone-cli`,hn=async e=>{let t=`HTTP ${e.status}: ${e.statusText}`;try{let n=await e.text(),r=JSON.parse(n);return r.error_description||r.error||t}catch{return t}};var gn=class{constructor(e){this.baseUrl=e||process.env.AUTH_SERVER_URL||`https://idp-api.stackone.com`}async login(e,t){try{let n=await fetch(`${this.baseUrl}/auth/sign-in/mcp`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({email:e,password:t})});if(!n.ok)return{success:!1,error:await hn(n)};let r=await n.json();return r.apiKey?{success:!0,apiKey:r.apiKey}:{success:!1,error:`Invalid response format`}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Network error occurred`}}}async validateKey(e){try{let t=await fetch(`${this.baseUrl}/api-key/verify`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({key:e})});return t.ok?await t.json():{valid:!1,error:await hn(t)}}catch(e){return{valid:!1,error:e instanceof Error?e.message:`Network error occurred`}}}async requestDeviceCode(){let e=await fetch(`${this.baseUrl}/api/auth/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({client_id:mn})});if(!e.ok)throw Error(await hn(e));return await e.json()}async pollDeviceToken(e){try{let t=await fetch(`${this.baseUrl}/api/auth/device/token`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({grant_type:`urn:ietf:params:oauth:grant-type:device_code`,device_code:e,client_id:mn})});if(t.ok)return{token:await t.json()};try{let e=await t.json();if(e.error)return{error:e}}catch{}return{error:{error:`server_error`,error_description:`HTTP ${t.status}: ${t.statusText}`}}}catch(e){return{error:{error:`network_error`,error_description:e instanceof Error?e.message:`Network error`}}}}async createApiKey(e){let t=10080*60,n=await fetch(`${this.baseUrl}/api/auth/api-key/create`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e}`},body:JSON.stringify({prefix:`falcon_key_`,expiresIn:t,name:`CLI Auth Key`})});if(!n.ok)throw Error(await hn(n));let r=await n.json(),i=new Date(Date.now()+t*1e3).toISOString();return{key:r.key,expiresAt:i}}};const _n=e=>new Promise(t=>{let n=he(),r,i;n===`darwin`?(r=`open`,i=[e]):n===`win32`?(r=`rundll32`,i=[`url.dll,FileProtocolHandler`,e]):(r=`xdg-open`,i=[e]),Te(r,i,e=>{t(!e)})}),vn=async(e,t)=>{let n=await e.requestDeviceCode(),r=await _n(n.verification_uri_complete),i=`Confirmation code: ${n.user_code}`;t(r?`Browser opened. ${i}\nWaiting for authentication...`:`Could not open browser. Please visit:\n ${n.verification_uri_complete}\n\n${i}`);let a=n.interval*1e3,o=0,s=Date.now()+n.expires_in*1e3;for(;Date.now()<s;){await new Promise(e=>setTimeout(e,a));let r=await e.pollDeviceToken(n.device_code);if(`token`in r){t(`Authenticated. Creating API key...`);let n=await e.createApiKey(r.token.access_token),i=await e.validateKey(n.key);return{success:!0,apiKey:n.key,email:i.email,userId:i.userId,expiresAt:n.expiresAt}}let i=r.error.error;if(i===`authorization_pending`){o=0;continue}if(i===`slow_down`){o=0,await new Promise(e=>setTimeout(e,a));continue}if(i===`expired_token`)return{success:!1,error:`Authentication session expired`};if(i===`access_denied`)return{success:!1,error:`Access denied by user`};if(o++,o>=5)return{success:!1,error:`Polling failed: ${r.error.error_description??`unknown error`}`}}return{success:!1,error:`Authentication timed out`}},yn=new gn,bn=async()=>{let e=He({input:Be,output:Ve}),t=await new Promise(t=>{e.question(T.white(`Email: `),e=>{t(e.trim())})});return e.close(),t||(y.error(`Email is required`),process.exit(1)),t},xn=async()=>{process.stdin.isTTY&&(y.error(`--password-stdin was set but no input was piped to stdin`),process.exit(1));let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`).replace(/[\r\n]+$/,``)},Sn=async e=>{let t=e.email?.trim()||process.env.STACKONE_EMAIL?.trim()||void 0,n;return e.passwordFromStdin?n=await xn():e.password?n=e.password:process.env.STACKONE_PASSWORD&&(n=process.env.STACKONE_PASSWORD),{email:t,password:n||void 0}},Cn=async e=>{let t=await Sn(e),n=t.email;if(!n){let e=await ee();if(e?.email){y.log(T.dim(`Last used email: ${e.email}\n`));let{useExisting:t}=await ze.prompt([{type:`confirm`,name:`useExisting`,message:`Sign in with this email?`,default:!0}]);n=t?e.email:await bn()}else n=await bn()}let r=t.password;r||=(e.passwordFromStdin&&(y.error(`Password is required`),process.exit(1)),(await ze.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}])).password),r||(y.error(`Password is required`),process.exit(1)),y.log(``);let i=q(`Authenticating...`).start(),a=await yn.login(n,r);(!a.success||!a.apiKey)&&(i.fail(`Authentication failed`),y.error(`${a.error||`Invalid credentials`}`),y.log(T.dim(`Please check your email and password and try again.
127
+ `)),process.exit(1)),i.succeed(`Login successful!`);let o=new Date(Date.now()+10080*60*1e3).toISOString();return{apiKey:a.apiKey,email:n,expiresAt:o}},wn=async()=>{let e=q(`Starting browser authentication...`).start(),t;try{t=await vn(yn,t=>{e.text=t})}catch(t){e.fail(`Authentication failed`),y.error(t instanceof Error?t.message:`Unknown error`),process.exit(1)}(!t.success||!t.apiKey)&&(e.fail(`Authentication failed`),y.error(t.error||`Unknown error`),process.exit(1)),e.succeed(`Login successful!`);let n=t.expiresAt||new Date(Date.now()+10080*60*1e3).toISOString();return{apiKey:t.apiKey,email:t.email??``,userId:t.userId,expiresAt:n}},Tn=async e=>{let t=await vn(yn,e);if(!t.success||!t.apiKey)throw Error(t.error||`Authentication failed`);let n=t.expiresAt||new Date(Date.now()+10080*60*1e3).toISOString(),r={apiKey:t.apiKey,userId:t.userId??t.email??``,email:t.email??``,expiresAt:n,serverUrl:g()};return await f(r),r},En=async(e,t={})=>{let{apiKey:n,email:r,userId:i,expiresAt:a}=e?await Cn(t):await wn(),o={apiKey:n,userId:i??r,email:r,expiresAt:a,serverUrl:g()};return await f(o),o},Dn=e=>{let t=new Date(e),n=new Date,r=t.getTime()-n.getTime(),i=Math.floor(r/(1440*60*1e3)),a=Math.floor(r%(1440*60*1e3)/(3600*1e3)),o=t.toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`,hour12:!0});return`${t.toLocaleDateString(`en-US`,{weekday:`short`,month:`short`,day:`numeric`})} at ${o} (${i>0?`${i} days, ${a} hours`:`${a} hours`} from now)`};var On=class{async execute(e){y.log(T.blue.bold(`🤖 StackOne Agent Setup - Global Configuration
128
+ `));try{let t=process.cwd(),n=await Re(`${t}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await Re(`${t}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r)if(y.warn(`Existing local setup detected:`),n&&y.log(T.dim(` • CLAUDE.md found in current directory`)),r&&y.log(T.dim(` • .mcp.json found in current directory`)),y.log(``),pn(!!e?.legacy,e?.credentials))y.log(T.dim(`Non-interactive credentials detected; proceeding without confirmation.
129
129
  `));else{let{proceed:e}=await ze.prompt([{type:`confirm`,name:`proceed`,message:`Re-authenticate globally despite existing local setup?`,default:!0}]);e||(y.log(T.dim(`
130
- Setup cancelled.`)),process.exit(0)),y.log(``)}let i=await bn(!!e?.legacy,e?.credentials);y.success(`API key saved to ~/.stackone/agent-config.json`),y.log(T.white(`✓ Key expires at`),T.cyan(xn(i.expiresAt))),C(await S(process.cwd(),i.apiKey));let o=q(`Setting up global MCP configuration...`).start();try{l(a(),_(),i.apiKey),o.succeed(`Installed to Claude (global)`),y.success(`Global setup complete!`),y.log(T.white(`Config location:`),T.cyan(`~/.claude.json`)),y.log(T.dim(`Token stored securely in Claude MCP server config.`)),y.log(T.blue(`
130
+ Setup cancelled.`)),process.exit(0)),y.log(``)}let i=await En(!!e?.legacy,e?.credentials);y.success(`API key saved to ~/.stackone/agent-config.json`),y.log(T.white(`✓ Key expires at`),T.cyan(Dn(i.expiresAt))),C(await S(process.cwd(),i.apiKey));let o=q(`Setting up global MCP configuration...`).start();try{l(a(),_(),i.apiKey),o.succeed(`Installed to Claude (global)`),y.success(`Global setup complete!`),y.log(T.white(`Config location:`),T.cyan(`~/.claude.json`)),y.log(T.dim(`Token stored securely in Claude MCP server config.`)),y.log(T.blue(`
131
131
  Verify:`),T.cyan(`claude mcp list`)),y.log(T.dim(`
132
132
  💡 Tip: Run Claude without permission prompts:`),T.cyan(`claude --dangerously-skip-permissions`)),y.log(T.dim(`
133
- To setup for a specific project, run:`),T.cyan(`stackone agent setup --local`)),y.log(``)}catch(e){o.fail(`Installation to Claude failed`),e instanceof Error&&y.error(e.message)}process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}};const Cn={research:`Researching API...`,"discover-actions":`Discovering available actions...`,"build-and-validate":`Building and validating connector...`};var wn=class{async execute(e){let{prompt:t,mode:n=`build`,maxTurns:r=25,verbose:i=!1}=e;t.trim()||(y.error(`A prompt is required.`),process.exit(1));let a;try{a=te()}catch(e){e instanceof Error&&e.name===`CredentialMissingError`?(y.error(`
133
+ To setup for a specific project, run:`),T.cyan(`stackone agent setup --local`)),y.log(``)}catch(e){o.fail(`Installation to Claude failed`),e instanceof Error&&y.error(e.message)}process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}};const kn={research:`Researching API...`,"discover-actions":`Discovering available actions...`,"build-and-validate":`Building and validating connector...`};var An=class{async execute(e){let{prompt:t,mode:n=`build`,maxTurns:r=25,verbose:i=!1}=e;t.trim()||(y.error(`A prompt is required.`),process.exit(1));let a;try{a=te()}catch(e){e instanceof Error&&e.name===`CredentialMissingError`?(y.error(`
134
134
  ❌ Authentication Required
135
- `),y.log(T.white("Run `stackone agent setup` to authenticate, then try again.\n"))):y.error(e instanceof Error?e.message:String(e)),process.exit(1)}let o=Gt(),s=se(t.trim());if(n===`build`&&s.isConnectorBuild&&s.provider)return this.executeOrchestratedBuild({provider:s.provider,category:s.category,apiKey:a,mcpServers:o,verbose:i});i&&(y.log(T.dim(`Mode: ${n}\n`)),o.length>0&&y.log(T.dim(`MCP Servers: ${o.map(e=>e.name).join(`, `)}\n`)));let c=null;try{for await(let e of oe({prompt:t.trim(),mode:n,apiKey:a,maxTurns:r,verbose:i,mcpServers:o,origin:`cli`,cliVersion:qt()}))En(e,e=>{c&&c.stop(),c=e})}catch(e){c?.fail(),y.error(T.red(`
135
+ `),y.log(T.white("Run `stackone agent setup` to authenticate, then try again.\n"))):y.error(e instanceof Error?e.message:String(e)),process.exit(1)}let o=Zt(),s=oe(t.trim());if(n===`build`&&s.isConnectorBuild&&s.provider)return this.executeOrchestratedBuild({provider:s.provider,category:s.category,apiKey:a,mcpServers:o,verbose:i});i&&(y.log(T.dim(`Mode: ${n}\n`)),o.length>0&&y.log(T.dim(`MCP Servers: ${o.map(e=>e.name).join(`, `)}\n`)));let c=null;try{for await(let e of ae({prompt:t.trim(),mode:n,apiKey:a,maxTurns:r,verbose:i,mcpServers:o,origin:`cli`,cliVersion:$t()}))Mn(e,e=>{c&&c.stop(),c=e})}catch(e){c?.fail(),y.error(T.red(`
136
136
  Error: `+(e instanceof Error?e.message:String(e)))),process.exit(1)}c?.stop(),y.log(T.green(`
137
137
  ✓ Done
138
- `))}async executeOrchestratedBuild(e){let{provider:t,category:n,verbose:r}=e,i=n?` (${n})`:``;y.log(T.bold(`\nOrchestrated build: ${t}${i}\n`));let a=null,o=new Map;try{for await(let t of Wt(e))switch(t.type){case`phase_start`:{let e=Cn[t.phase]||`${t.phase}...`,n=t.model?T.dim(` (${ft(t.model)})`):``;a?.stop(),a=q(T.cyan(`[${t.phase}]${n} ${e}`)).start(),o.set(t.phase,Date.now());break}case`phase_complete`:{let e=o.get(t.phase),n=e===void 0?0:Math.round((Date.now()-e)/1e3);a?.succeed(T.green(`[${t.phase}] Done (${n}s)`)),a=null;break}case`phase_error`:a?.fail(T.red(`[${t.phase}] ${t.error}`)),a=null;break;case`agent_message`:Tn(t,a,r);break}}catch(e){a?.fail(),y.error(T.red(`
138
+ `))}async executeOrchestratedBuild(e){let{provider:t,category:n,verbose:r}=e,i=n?` (${n})`:``;y.log(T.bold(`\nOrchestrated build: ${t}${i}\n`));let a=null,o=new Map;try{for await(let t of Xt(e))switch(t.type){case`phase_start`:{let e=kn[t.phase]||`${t.phase}...`,n=t.model?T.dim(` (${vt(t.model)})`):``;a?.stop(),a=q(T.cyan(`[${t.phase}]${n} ${e}`)).start(),o.set(t.phase,Date.now());break}case`phase_complete`:{let e=o.get(t.phase),n=e===void 0?0:Math.round((Date.now()-e)/1e3);a?.succeed(T.green(`[${t.phase}] Done (${n}s)`)),a=null;break}case`phase_error`:a?.fail(T.red(`[${t.phase}] ${t.error}`)),a=null;break;case`agent_message`:jn(t,a,r);break}}catch(e){a?.fail(),y.error(T.red(`
139
139
  Error: `+(e instanceof Error?e.message:String(e)))),process.exit(1)}a?.stop(),y.log(T.green(`
140
140
  ✓ Build complete
141
- `))}};const Tn=(e,t,n)=>{let r=e.message;switch(r.type){case`text`:n&&process.stdout.write(r.content??``);break;case`tool_call`:{let n=r.toolName??`unknown tool`;t&&(t.text=T.cyan(`[${e.phase}] Tool: ${n}`));break}case`tool_error`:y.error(T.red(`\n[${e.phase}] Tool error (${r.toolName}): ${r.error??`Unknown error`}`));break;case`error`:y.error(T.red(`\n[${e.phase}] ${r.error??`Unknown error`}`));break;default:break}};function En(e,t){switch(e.type){case`text`:t(null),process.stdout.write(e.content??``);break;case`tool_call`:{let n=e.toolName??`unknown tool`;t(q(T.cyan(`Tool: ${n}`)).start());break}case`tool_result`:t(null);break;case`tool_progress`:{let n=e.progress?.operation||e.toolName||`Working...`;t(q(T.cyan(`Tool: ${n}`)).start());break}case`tool_error`:t(null),y.error(T.red(`\nTool error (${e.toolName}): ${e.error??`Unknown error`}`));break;case`error`:t(null),y.error(T.red(`\n${e.error??`Unknown error`}`));break;case`done`:t(null);break;default:process.env.VERBOSE&&console.warn(`[AgentRun] Unknown message type:`,e.type);break}}const Dn=e=>{let t=e.trim();return t===`~`?I():t.startsWith(`~/`)?R(I(),t.slice(2)):t},On=(e,t,n)=>e?`global`:t?`local`:n?null:`global`,kn=(e,t)=>e?.trim()||(t?null:process.cwd()),An=e=>e.existingConfig?`overwrite`:jn(e),jn=e=>e.mode===`local`&&e.alreadyAuthed?`work`:`auth`,Mn=(e,t)=>{switch(e){case`mode`:return t.mode===`local`?t.hasGit?`repo-confirm`:`path-input`:An(t);case`repo-confirm`:return t.repoAccepted?An(t):`path-input`;case`path-input`:return An(t);case`overwrite`:return jn(t);case`auth`:return`work`;default:return`done`}},Nn=(e,t)=>Ee(`git`,[`-C`,e,...t],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim(),Pn=e=>{try{let t=Nn(e,[`rev-parse`,`--show-toplevel`]);if(!t)return null;let n;try{n=Nn(e,[`remote`,`get-url`,`origin`])||void 0}catch{}return{root:t,remoteUrl:n}}catch{return null}},Fn=`connector-guide.md`,In=`<!-- BEGIN stackone-connector-guide -->`,Ln=`<!-- END stackone-connector-guide -->`,Rn=/^[a-z0-9][a-z0-9_-]*$/,zn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Bn=e=>`<!-- Generated by \`stackone agent sync\` from @stackone/agent-harness@${e}. Edit upstream, not here. -->`,Vn=e=>{if(e.includes(`..`)||!Rn.test(e))throw Error(`Refusing unsafe path segment: ${JSON.stringify(e)}`)},Q=(e,...t)=>{let n=_e(e),r=_e(n,...t);if(r!==n&&!r.startsWith(n+ve))throw Error(`Refusing path outside ${n}: ${r}`);return r},Hn=(e,...t)=>de(Q(e,...t),`utf-8`),Un=(e,...t)=>de(Q(e,...t)),Wn=()=>{let e=w(import.meta.url).resolve(`@stackone/agent-harness`),t=ge(e);for(let e=0;e<6;e++){if(N(R(t,`package.json`))&&N(R(t,`plugin`)))return t;let e=ge(t);if(e===t)break;t=e}return ge(ge(e))},Gn=()=>R(Wn(),`plugin`),Kn=e=>{try{let t=e?_e(e,`..`):Wn();return JSON.parse(Hn(t,`package.json`)).version??`unknown`}catch{return`unknown`}},qn=e=>{let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^---\n[\s\S]*?\n---\n?/);return n&&(t=t.slice(n[0].length)),t=t.replace(/^\s*<!--[\s\S]*?-->\s*/,``),t.trim()},Jn=(e,t,n)=>{let r=[In,Bn(n),``,t,``,Ln].join(`
142
- `);if(e.includes(In)&&e.includes(Ln)){let t=RegExp(`${zn(In)}[\\s\\S]*?${zn(Ln)}`);return e.replace(t,r)}let i=e.replace(/\s*$/,``);return i.length>0?`${i}\n\n${r}\n`:`${r}\n`},Yn=e=>{let t=[];for(let n of P(e,{withFileTypes:!0}))if(n.isDirectory()){let r=Yn(Q(e,n.name));t.push(...r.map(e=>R(n.name,e)))}else t.push(n.name);return t},Xn=(e,t)=>{if(!N(t))return!1;let n=Yn(e).sort(),r=Yn(t).sort();return n.length!==r.length||n.some((e,t)=>e!==r[t])?!1:n.every(n=>Un(e,n).equals(Un(t,n)))},Zn=(e,t)=>{fe(t,{recursive:!0,force:!0}),ue(ge(t),{recursive:!0}),le(e,t,{recursive:!0})},Qn=e=>P(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory())return!1;let n=Q(e,t.name);return N(Q(n,`SKILL.md`))||Qn(n)}),$n=e=>{if(!N(e))return[];let t=[],n=[];for(let r of P(e,{withFileTypes:!0})){if(!r.isDirectory()||!Rn.test(r.name))continue;let i=Q(e,r.name);N(Q(i,`SKILL.md`))?t.push(r.name):Qn(i)&&n.push(r.name)}return n.length>0&&console.warn(`Skipped ${n.length} grouped skill director${n.length===1?`y`:`ies`} (${n.join(`, `)}): skills must be one level down (skills/<name>/SKILL.md). Claude Code reads plugin skills one level deep too, so grouped skills are not reachable by any route — flatten them to make them usable.`),t.sort()},er=()=>({changed:[],unchanged:[],missing:[]}),tr=(e,t,n,r)=>{let i=er();for(let a of e){Vn(a);let e=Q(t,a);if(!N(e)||!pe(e).isDirectory()){i.missing.push(a);continue}let o=Q(n,a);if(Xn(e,o)){i.unchanged.push(a);continue}i.changed.push(a),r||Zn(e,o)}return i},nr=(e,t,n)=>{if(!N(e)||!pe(e).isDirectory())return{status:`missing-source`,fileCount:0};let r=Yn(e).length;return r===0?{status:`missing-source`,fileCount:0}:Xn(e,t)?{status:`unchanged`,fileCount:r}:(n||Zn(e,t),{status:`changed`,fileCount:r})},rr=(e,t,n,r)=>{if(!N(Q(e,Fn)))return`missing-source`;let i=qn(Hn(e,Fn)),a=Q(t,`CLAUDE.md`),o=N(a)?Hn(t,`CLAUDE.md`):``,s=Jn(o,i,n);return s===o?`unchanged`:(r||me(a,s),`changed`)},ir=e=>{let t=_e(e.pluginDir??Gn()),n=_e(e.cwd),r=e.version??Kn(t),i=e.check??!1,a=Q(n,`.claude`),o=Q(t,`skills`),s=tr($n(o),o,Q(a,`skills`),i),c=nr(Q(t,`commands`),Q(a,`commands`),i),l=nr(Q(t,`agents`),Q(a,`agents`),i),u=rr(t,n,r,i),d=s.changed.length>0||c.status===`changed`||l.status===`changed`||u===`changed`,f=u!==`missing-source`||c.status!==`missing-source`||l.status!==`missing-source`||s.changed.length+s.unchanged.length>0;if(!i&&f){ue(a,{recursive:!0});let e={harnessVersion:r,skills:s.changed.concat(s.unchanged).sort(),commands:c.fileCount,agents:l.fileCount,guide:u!==`missing-source`};me(Q(a,`.stackone-connector-env.json`),`${JSON.stringify(e,null,2)}\n`)}return{skills:s,commands:c,agents:l,guide:u,hasChanges:d}},ar=e=>{try{let t=e??Gn();return pe(t).isDirectory()?e?JSON.parse(Hn(_e(t,`..`),`package.json`)).name===`@stackone/agent-harness`:!0:!1}catch{return!1}},or=({message:e,choices:t,initialIndex:n=0,onSelect:r,onCancel:i})=>{let[a,o]=W(()=>t.length?Math.min(Math.max(n,0),t.length-1):0);return xe((e,n)=>{if(t.length===0){n.escape&&i?.();return}n.upArrow?o(e=>(e-1+t.length)%t.length):n.downArrow?o(e=>(e+1)%t.length):n.return?r(t[a].value):n.escape&&i?.()}),t.length===0?null:V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(z,{borderStyle:`round`,borderColor:`cyan`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{flexDirection:`column`,marginTop:1},t.map((e,t)=>V.createElement(B,{key:e.value,color:t===a?`#00af66`:`white`},t===a?`❯ `:` `,e.label)))),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to select`)))},sr=({message:e,initialValue:t=``,validate:n,onSubmit:r,onCancel:i})=>{let[a,o]=W(t),[s,c]=W(null);return xe((e,t)=>{if(t.return){let e=n?n(a):!0;e===!0?r(a):c(e);return}if(t.escape){i?.();return}if(t.backspace||t.delete){o(e=>e.slice(0,-1)),c(null);return}e&&!t.ctrl&&!t.meta&&!t.tab&&!t.upArrow&&!t.downArrow&&(o(t=>t+e),c(null))}),V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{marginTop:1},V.createElement(B,null,`> `),V.createElement(B,null,a),V.createElement(B,{inverse:!0},` `)),s&&V.createElement(z,{marginTop:1},V.createElement(B,{color:`red`},s)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Enter to submit • Esc to cancel`)))},cr=e=>N(`${e}/CLAUDE.md`)||N(`${e}/.mcp.json`),lr=e=>{try{return pe(e).isDirectory()}catch{return!1}},ur=({initialMode:e,pathFlag:t,startDir:n,onExit:r})=>{let[i,o]=W(`mode`),[c,u]=W(null),[f,p]=W(!1),[h,g]=W([]),[v,y]=W(``),[b,x]=W(e),[C,te]=W(``),[w,T]=W(``),[E,ne]=W(!1),[D,re]=W(null),ie=U(0),ae=Se(e=>{ie.current+=1;let t=ie.current;g(n=>[...n,{...e,id:t}])},[]),O=Se(e=>{u(e)},[]),oe=Se(async e=>{let t=_e(Dn(e));if(!lr(t)){O({status:`error`,message:N(t)?`Target path is not a directory: ${t}`:`Target path does not exist: ${t}`});return}te(t);let n=cr(t),r=d(await ee());ne(r),o(Mn(`path-input`,{mode:`local`,hasGit:!1,repoAccepted:!1,existingConfig:n,alreadyAuthed:r}))},[O]),se=Se(e=>{if(x(e),e===`local`){let e=t?.trim();if(e){oe(e);return}let r=Pn(n);r&&(T(`Install the connector setup into this repo? ${r.remoteUrl?`${r.remoteUrl} (${r.root})`:r.root}`),te(r.root)),o(Mn(`mode`,{mode:`local`,hasGit:!!r,repoAccepted:!1,existingConfig:!1,alreadyAuthed:!1}));return}o(Mn(`mode`,{mode:`global`,hasGit:!1,repoAccepted:!1,existingConfig:cr(n),alreadyAuthed:!1}))},[t,n,oe]);H(()=>{e&&se(e)},[]);let k=Se(e=>{e?oe(C):o(`path-input`)},[oe,C]),A=Se(e=>{if(!e){O({status:`cancelled`});return}o(Mn(`overwrite`,{mode:b??`global`,hasGit:!1,repoAccepted:!1,existingConfig:!0,alreadyAuthed:E}))},[b,E,O]);return H(()=>{if(i!==`auth`)return;let e=!1;return y(`Starting browser authentication…`),yn(t=>{e||y(t)}).then(t=>{e||(re(t),ae({icon:`✓`,text:t.email?`Authenticated as ${t.email}`:`Authenticated`,color:Z.success}),o(`work`))}).catch(t=>{e||O({status:`error`,message:t instanceof Error?t.message:`Authentication failed`})}),()=>{e=!0}},[i,ae,O]),H(()=>{if(i!==`work`)return;let e=!1;return(async()=>{try{let t=D??await ee();if(!t)throw Error(`Not authenticated — no API key found`);let r=await S(b===`local`?C:n,t.apiKey);if(r.migrated&&ae({icon:`✓`,text:`Migrated ${r.actions.length} item(s) from a previous setup`,color:Z.success}),b===`local`){y(`Creating .mcp.json…`),l(m(C),s(),t.apiKey),ae({icon:`✓`,text:`Created .mcp.json`,color:Z.success}),y(`Syncing connector-building skills + guide…`);let e=ir({cwd:C});ae({icon:`✓`,text:`Connector environment ready (${e.skills.changed.length+e.skills.unchanged.length} skills in .claude/, ${e.guide===`missing-source`?`guide unavailable in this version`:`guide in CLAUDE.md`})`,color:Z.success})}else y(`Installing global MCP configuration…`),l(a(),_(),t.apiKey),ae({icon:`✓`,text:`Installed to Claude (global)`,color:Z.success});if(e)return;y(``),O({status:`done`})}catch(t){if(e)return;O({status:`error`,message:t instanceof Error?t.message:`Setup failed`})}})(),()=>{e=!0}},[i,D,b,C,n,ae,O]),H(()=>{if(!c)return;let e=setTimeout(()=>r(c),60);return()=>clearTimeout(e)},[c,r]),V.createElement(z,{flexDirection:`column`,padding:1},f?V.createElement(wt,{wordmark:!0}):V.createElement(Et,{ready:!0,onComplete:()=>p(!0)}),h.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},h.map(e=>V.createElement(B,{key:e.id,color:e.color},e.icon?`${e.icon} `:``,e.text))),V.createElement(z,{marginTop:1},(()=>{if(c)return c.status===`error`?V.createElement(B,{color:Z.error},`✗ `,c.message??`Setup failed`):c.status===`cancelled`?V.createElement(B,{color:Z.dim},`Setup cancelled.`):V.createElement(z,{flexDirection:`column`},V.createElement(B,{color:Z.success},`✓ Setup complete!`),V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{color:Z.dim},`Verify with `,V.createElement(B,{color:Z.primary},`claude mcp list`)),V.createElement(B,{color:Z.dim},`Tip: run`,` `,V.createElement(B,{color:Z.primary},`claude --dangerously-skip-permissions`),` `,`to skip permission prompts`),b===`local`&&V.createElement(B,{color:Z.dim},`Refresh skills anytime with`,` `,V.createElement(B,{color:Z.primary},`stackone agent sync`))));switch(i){case`mode`:return e?null:V.createElement(or,{message:`How do you want to set up the StackOne agent?`,initialIndex:0,choices:[{label:`Local — this project: auth + .mcp.json + connector skills (.claude/) + guide (CLAUDE.md)`,value:`local`},{label:`Global — any repo: auth + global MCP only (no connector skills/guide)`,value:`global`}],onSelect:e=>se(e),onCancel:()=>O({status:`cancelled`})});case`repo-confirm`:return V.createElement(or,{message:w,initialIndex:0,choices:[{label:`Yes`,value:`yes`},{label:`No, let me choose a path`,value:`no`}],onSelect:e=>k(e===`yes`),onCancel:()=>O({status:`cancelled`})});case`path-input`:return V.createElement(sr,{message:`Path to install the connector setup into:`,initialValue:n,validate:e=>{let t=Dn(e)||n;return N(t)?lr(t)?!0:`Path is not a directory: ${t}`:`Path does not exist: ${t}`},onSubmit:e=>void oe(e.trim()||n),onCancel:()=>O({status:`cancelled`})});case`overwrite`:{let e=b===`local`;return V.createElement(or,{message:e?`Existing setup found in ${C}. Overwrite it?`:`Local setup detected in ${n} (it won't be modified). Set up the agent globally anyway?`,initialIndex:e?1:0,choices:[{label:e?`Yes, overwrite`:`Yes, set up globally`,value:`yes`},{label:`No, cancel`,value:`no`}],onSelect:e=>A(e===`yes`),onCancel:()=>O({status:`cancelled`})})}case`auth`:case`work`:return V.createElement(B,null,V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),` `,v);default:return null}})()))},dr=e=>new Promise(t=>{let{unmount:n}=ye(e(e=>{n(),t(e)}))}),fr=()=>dr(e=>V.createElement(or,{message:`How do you want to set up the StackOne agent?`,initialIndex:0,choices:[{label:`Local — this project: auth + .mcp.json + connector skills (.claude/) + guide (CLAUDE.md)`,value:`local`},{label:`Global — any repo: auth + global MCP only (no connector skills/guide)`,value:`global`}],onSelect:t=>e(t)})),pr=(e,t=!0)=>dr(n=>V.createElement(or,{message:e,initialIndex:t?0:1,choices:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}],onSelect:e=>n(e===`yes`),onCancel:()=>n(!1)})),mr=async e=>{let t=Pn(e);return t&&await pr(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`,!0)?t.root:dr(n=>V.createElement(sr,{message:t?`Path to install into:`:`Current directory is not a git repo. Path to install into:`,initialValue:e,validate:t=>{let n=Dn(t)||e;return N(n)?!0:`Path does not exist: ${n}`},onSubmit:t=>n(Dn(t)||e)}))},hr=e=>new Promise(t=>{let{unmount:n}=ye(V.createElement(ur,{initialMode:e.initialMode,pathFlag:e.pathFlag,startDir:e.startDir??process.cwd(),onExit:e=>{n(),t(e)}}))});var gr=class{async execute(e){y.log(T.blue.bold(`🤖 StackOne Agent Setup - Local Project
143
- `));try{let t=_e(Dn(e?.targetPath??process.cwd()));await Re(t).then(()=>!0).catch(()=>!1)||(y.error(`Target path does not exist: ${t}`),process.exit(1)),e?.targetPath&&y.log(T.dim(`Installing into ${t}\n`));let n=await Re(`${t}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await Re(`${t}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){y.warn(`Existing local setup detected:`),n&&y.log(T.dim(` • CLAUDE.md found`)),r&&y.log(T.dim(` • .mcp.json found`)),y.log(``);let t=sn(!!e?.legacy,e?.credentials),i=!!process.stdin.isTTY;t||!i?y.log(T.dim(t?`Non-interactive credentials detected; proceeding without confirmation.
141
+ `))}};const jn=(e,t,n)=>{let r=e.message;switch(r.type){case`text`:n&&process.stdout.write(r.content??``);break;case`tool_call`:{let n=r.toolName??`unknown tool`;t&&(t.text=T.cyan(`[${e.phase}] Tool: ${n}`));break}case`tool_error`:y.error(T.red(`\n[${e.phase}] Tool error (${r.toolName}): ${r.error??`Unknown error`}`));break;case`error`:y.error(T.red(`\n[${e.phase}] ${r.error??`Unknown error`}`));break;default:break}};function Mn(e,t){switch(e.type){case`text`:t(null),process.stdout.write(e.content??``);break;case`tool_call`:{let n=e.toolName??`unknown tool`;t(q(T.cyan(`Tool: ${n}`)).start());break}case`tool_result`:t(null);break;case`tool_progress`:{let n=e.progress?.operation||e.toolName||`Working...`;t(q(T.cyan(`Tool: ${n}`)).start());break}case`tool_error`:t(null),y.error(T.red(`\nTool error (${e.toolName}): ${e.error??`Unknown error`}`));break;case`error`:t(null),y.error(T.red(`\n${e.error??`Unknown error`}`));break;case`done`:t(null);break;default:process.env.VERBOSE&&console.warn(`[AgentRun] Unknown message type:`,e.type);break}}const Nn=e=>{let t=e.trim();return t===`~`?I():t.startsWith(`~/`)?R(I(),t.slice(2)):t},Pn=(e,t,n)=>e?`global`:t?`local`:n?null:`global`,Fn=(e,t)=>e?.trim()||(t?null:process.cwd()),In=e=>e.existingConfig?`overwrite`:Ln(e),Ln=e=>e.mode===`local`&&e.alreadyAuthed?`work`:`auth`,Rn=(e,t)=>{switch(e){case`mode`:return t.mode===`local`?t.hasGit?`repo-confirm`:`path-input`:In(t);case`repo-confirm`:return t.repoAccepted?In(t):`path-input`;case`path-input`:return In(t);case`overwrite`:return Ln(t);case`auth`:return`work`;default:return`done`}},zn=(e,t)=>Ee(`git`,[`-C`,e,...t],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim(),Bn=e=>{try{let t=zn(e,[`rev-parse`,`--show-toplevel`]);if(!t)return null;let n;try{n=zn(e,[`remote`,`get-url`,`origin`])||void 0}catch{}return{root:t,remoteUrl:n}}catch{return null}},Vn=`connector-guide.md`,Hn=`<!-- BEGIN stackone-connector-guide -->`,Un=`<!-- END stackone-connector-guide -->`,Wn=/^[a-z0-9][a-z0-9_-]*$/,Gn=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Kn=e=>`<!-- Generated by \`stackone agent sync\` from @stackone/agent-harness@${e}. Edit upstream, not here. -->`,qn=e=>{if(e.includes(`..`)||!Wn.test(e))throw Error(`Refusing unsafe path segment: ${JSON.stringify(e)}`)},Q=(e,...t)=>{let n=_e(e),r=_e(n,...t);if(r!==n&&!r.startsWith(n+ve))throw Error(`Refusing path outside ${n}: ${r}`);return r},Jn=(e,...t)=>de(Q(e,...t),`utf-8`),Yn=(e,...t)=>de(Q(e,...t)),Xn=()=>{let e=w(import.meta.url).resolve(`@stackone/agent-harness`),t=ge(e);for(let e=0;e<6;e++){if(N(R(t,`package.json`))&&N(R(t,`plugin`)))return t;let e=ge(t);if(e===t)break;t=e}return ge(ge(e))},Zn=()=>R(Xn(),`plugin`),Qn=e=>{try{let t=e?_e(e,`..`):Xn();return JSON.parse(Jn(t,`package.json`)).version??`unknown`}catch{return`unknown`}},$n=e=>{let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^---\n[\s\S]*?\n---\n?/);return n&&(t=t.slice(n[0].length)),t=t.replace(/^\s*<!--[\s\S]*?-->\s*/,``),t.trim()},er=(e,t,n)=>{let r=[Hn,Kn(n),``,t,``,Un].join(`
142
+ `);if(e.includes(Hn)&&e.includes(Un)){let t=RegExp(`${Gn(Hn)}[\\s\\S]*?${Gn(Un)}`);return e.replace(t,r)}let i=e.replace(/\s*$/,``);return i.length>0?`${i}\n\n${r}\n`:`${r}\n`},tr=e=>{let t=[];for(let n of P(e,{withFileTypes:!0}))if(n.isDirectory()){let r=tr(Q(e,n.name));t.push(...r.map(e=>R(n.name,e)))}else t.push(n.name);return t},nr=(e,t)=>{if(!N(t))return!1;let n=tr(e).sort(),r=tr(t).sort();return n.length!==r.length||n.some((e,t)=>e!==r[t])?!1:n.every(n=>Yn(e,n).equals(Yn(t,n)))},rr=(e,t)=>{fe(t,{recursive:!0,force:!0}),ue(ge(t),{recursive:!0}),le(e,t,{recursive:!0})},ir=e=>P(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory())return!1;let n=Q(e,t.name);return N(Q(n,`SKILL.md`))||ir(n)}),ar=e=>{if(!N(e))return[];let t=[],n=[];for(let r of P(e,{withFileTypes:!0})){if(!r.isDirectory()||!Wn.test(r.name))continue;let i=Q(e,r.name);N(Q(i,`SKILL.md`))?t.push(r.name):ir(i)&&n.push(r.name)}return n.length>0&&console.warn(`Skipped ${n.length} grouped skill director${n.length===1?`y`:`ies`} (${n.join(`, `)}): skills must be one level down (skills/<name>/SKILL.md). Claude Code reads plugin skills one level deep too, so grouped skills are not reachable by any route — flatten them to make them usable.`),t.sort()},or=()=>({changed:[],unchanged:[],missing:[]}),sr=(e,t,n,r)=>{let i=or();for(let a of e){qn(a);let e=Q(t,a);if(!N(e)||!pe(e).isDirectory()){i.missing.push(a);continue}let o=Q(n,a);if(nr(e,o)){i.unchanged.push(a);continue}i.changed.push(a),r||rr(e,o)}return i},cr=(e,t,n)=>{if(!N(e)||!pe(e).isDirectory())return{status:`missing-source`,fileCount:0};let r=tr(e).length;return r===0?{status:`missing-source`,fileCount:0}:nr(e,t)?{status:`unchanged`,fileCount:r}:(n||rr(e,t),{status:`changed`,fileCount:r})},lr=(e,t,n,r)=>{if(!N(Q(e,Vn)))return`missing-source`;let i=$n(Jn(e,Vn)),a=Q(t,`CLAUDE.md`),o=N(a)?Jn(t,`CLAUDE.md`):``,s=er(o,i,n);return s===o?`unchanged`:(r||me(a,s),`changed`)},ur=e=>{let t=_e(e.pluginDir??Zn()),n=_e(e.cwd),r=e.version??Qn(t),i=e.check??!1,a=Q(n,`.claude`),o=Q(t,`skills`),s=sr(ar(o),o,Q(a,`skills`),i),c=cr(Q(t,`commands`),Q(a,`commands`),i),l=cr(Q(t,`agents`),Q(a,`agents`),i),u=lr(t,n,r,i),d=s.changed.length>0||c.status===`changed`||l.status===`changed`||u===`changed`,f=u!==`missing-source`||c.status!==`missing-source`||l.status!==`missing-source`||s.changed.length+s.unchanged.length>0;if(!i&&f){ue(a,{recursive:!0});let e={harnessVersion:r,skills:s.changed.concat(s.unchanged).sort(),commands:c.fileCount,agents:l.fileCount,guide:u!==`missing-source`};me(Q(a,`.stackone-connector-env.json`),`${JSON.stringify(e,null,2)}\n`)}return{skills:s,commands:c,agents:l,guide:u,hasChanges:d}},dr=e=>{try{let t=e??Zn();return pe(t).isDirectory()?e?JSON.parse(Jn(_e(t,`..`),`package.json`)).name===`@stackone/agent-harness`:!0:!1}catch{return!1}},fr=({message:e,choices:t,initialIndex:n=0,onSelect:r,onCancel:i})=>{let[a,o]=W(()=>t.length?Math.min(Math.max(n,0),t.length-1):0);return xe((e,n)=>{if(t.length===0){n.escape&&i?.();return}n.upArrow?o(e=>(e-1+t.length)%t.length):n.downArrow?o(e=>(e+1)%t.length):n.return?r(t[a].value):n.escape&&i?.()}),t.length===0?null:V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(z,{borderStyle:`round`,borderColor:`cyan`,flexDirection:`column`,paddingX:2,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{flexDirection:`column`,marginTop:1},t.map((e,t)=>V.createElement(B,{key:e.value,color:t===a?`#00af66`:`white`},t===a?`❯ `:` `,e.label)))),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`↑↓ to navigate • Enter to select`)))},pr=({message:e,initialValue:t=``,validate:n,onSubmit:r,onCancel:i})=>{let[a,o]=W(t),[s,c]=W(null);return xe((e,t)=>{if(t.return){let e=n?n(a):!0;e===!0?r(a):c(e);return}if(t.escape){i?.();return}if(t.backspace||t.delete){o(e=>e.slice(0,-1)),c(null);return}e&&!t.ctrl&&!t.meta&&!t.tab&&!t.upArrow&&!t.downArrow&&(o(t=>t+e),c(null))}),V.createElement(z,{flexDirection:`column`,paddingY:1},V.createElement(B,{bold:!0},e),V.createElement(z,{marginTop:1},V.createElement(B,null,`> `),V.createElement(B,null,a),V.createElement(B,{inverse:!0},` `)),s&&V.createElement(z,{marginTop:1},V.createElement(B,{color:`red`},s)),V.createElement(z,{marginTop:1},V.createElement(B,{dimColor:!0},`Enter to submit • Esc to cancel`)))},mr=e=>N(`${e}/CLAUDE.md`)||N(`${e}/.mcp.json`),hr=e=>{try{return pe(e).isDirectory()}catch{return!1}},gr=({initialMode:e,pathFlag:t,startDir:n,onExit:r})=>{let[i,o]=W(`mode`),[c,u]=W(null),[f,p]=W(!1),[h,g]=W([]),[v,y]=W(``),[b,x]=W(e),[C,te]=W(``),[w,T]=W(``),[E,ne]=W(!1),[D,re]=W(null),ie=U(0),O=Se(e=>{ie.current+=1;let t=ie.current;g(n=>[...n,{...e,id:t}])},[]),k=Se(e=>{u(e)},[]),ae=Se(async e=>{let t=_e(Nn(e));if(!hr(t)){k({status:`error`,message:N(t)?`Target path is not a directory: ${t}`:`Target path does not exist: ${t}`});return}te(t);let n=mr(t),r=d(await ee());ne(r),o(Rn(`path-input`,{mode:`local`,hasGit:!1,repoAccepted:!1,existingConfig:n,alreadyAuthed:r}))},[k]),oe=Se(e=>{if(x(e),e===`local`){let e=t?.trim();if(e){ae(e);return}let r=Bn(n);r&&(T(`Install the connector setup into this repo? ${r.remoteUrl?`${r.remoteUrl} (${r.root})`:r.root}`),te(r.root)),o(Rn(`mode`,{mode:`local`,hasGit:!!r,repoAccepted:!1,existingConfig:!1,alreadyAuthed:!1}));return}o(Rn(`mode`,{mode:`global`,hasGit:!1,repoAccepted:!1,existingConfig:mr(n),alreadyAuthed:!1}))},[t,n,ae]);H(()=>{e&&oe(e)},[]);let se=Se(e=>{e?ae(C):o(`path-input`)},[ae,C]),A=Se(e=>{if(!e){k({status:`cancelled`});return}o(Rn(`overwrite`,{mode:b??`global`,hasGit:!1,repoAccepted:!1,existingConfig:!0,alreadyAuthed:E}))},[b,E,k]);return H(()=>{if(i!==`auth`)return;let e=!1;return y(`Starting browser authentication…`),Tn(t=>{e||y(t)}).then(t=>{e||(re(t),O({icon:`✓`,text:t.email?`Authenticated as ${t.email}`:`Authenticated`,color:Z.success}),o(`work`))}).catch(t=>{e||k({status:`error`,message:t instanceof Error?t.message:`Authentication failed`})}),()=>{e=!0}},[i,O,k]),H(()=>{if(i!==`work`)return;let e=!1;return(async()=>{try{let t=D??await ee();if(!t)throw Error(`Not authenticated — no API key found`);let r=await S(b===`local`?C:n,t.apiKey);if(r.migrated&&O({icon:`✓`,text:`Migrated ${r.actions.length} item(s) from a previous setup`,color:Z.success}),b===`local`){y(`Creating .mcp.json…`),l(m(C),s(),t.apiKey),O({icon:`✓`,text:`Created .mcp.json`,color:Z.success}),y(`Syncing connector-building skills + guide…`);let e=ur({cwd:C});O({icon:`✓`,text:`Connector environment ready (${e.skills.changed.length+e.skills.unchanged.length} skills in .claude/, ${e.guide===`missing-source`?`guide unavailable in this version`:`guide in CLAUDE.md`})`,color:Z.success})}else y(`Installing global MCP configuration…`),l(a(),_(),t.apiKey),O({icon:`✓`,text:`Installed to Claude (global)`,color:Z.success});if(e)return;y(``),k({status:`done`})}catch(t){if(e)return;k({status:`error`,message:t instanceof Error?t.message:`Setup failed`})}})(),()=>{e=!0}},[i,D,b,C,n,O,k]),H(()=>{if(!c)return;let e=setTimeout(()=>r(c),60);return()=>clearTimeout(e)},[c,r]),V.createElement(z,{flexDirection:`column`,padding:1},f?V.createElement(At,{wordmark:!0}):V.createElement(Mt,{ready:!0,onComplete:()=>p(!0)}),h.length>0&&V.createElement(z,{flexDirection:`column`,marginTop:1},h.map(e=>V.createElement(B,{key:e.id,color:e.color},e.icon?`${e.icon} `:``,e.text))),V.createElement(z,{marginTop:1},(()=>{if(c)return c.status===`error`?V.createElement(B,{color:Z.error},`✗ `,c.message??`Setup failed`):c.status===`cancelled`?V.createElement(B,{color:Z.dim},`Setup cancelled.`):V.createElement(z,{flexDirection:`column`},V.createElement(B,{color:Z.success},`✓ Setup complete!`),V.createElement(z,{marginTop:1,flexDirection:`column`},V.createElement(B,{color:Z.dim},`Verify with `,V.createElement(B,{color:Z.primary},`claude mcp list`)),V.createElement(B,{color:Z.dim},`Tip: run`,` `,V.createElement(B,{color:Z.primary},`claude --dangerously-skip-permissions`),` `,`to skip permission prompts`),b===`local`&&V.createElement(B,{color:Z.dim},`Refresh skills anytime with`,` `,V.createElement(B,{color:Z.primary},`stackone agent sync`))));switch(i){case`mode`:return e?null:V.createElement(fr,{message:`How do you want to set up the StackOne agent?`,initialIndex:0,choices:[{label:`Local — this project: auth + .mcp.json + connector skills (.claude/) + guide (CLAUDE.md)`,value:`local`},{label:`Global — any repo: auth + global MCP only (no connector skills/guide)`,value:`global`}],onSelect:e=>oe(e),onCancel:()=>k({status:`cancelled`})});case`repo-confirm`:return V.createElement(fr,{message:w,initialIndex:0,choices:[{label:`Yes`,value:`yes`},{label:`No, let me choose a path`,value:`no`}],onSelect:e=>se(e===`yes`),onCancel:()=>k({status:`cancelled`})});case`path-input`:return V.createElement(pr,{message:`Path to install the connector setup into:`,initialValue:n,validate:e=>{let t=Nn(e)||n;return N(t)?hr(t)?!0:`Path is not a directory: ${t}`:`Path does not exist: ${t}`},onSubmit:e=>void ae(e.trim()||n),onCancel:()=>k({status:`cancelled`})});case`overwrite`:{let e=b===`local`;return V.createElement(fr,{message:e?`Existing setup found in ${C}. Overwrite it?`:`Local setup detected in ${n} (it won't be modified). Set up the agent globally anyway?`,initialIndex:e?1:0,choices:[{label:e?`Yes, overwrite`:`Yes, set up globally`,value:`yes`},{label:`No, cancel`,value:`no`}],onSelect:e=>A(e===`yes`),onCancel:()=>k({status:`cancelled`})})}case`auth`:case`work`:return V.createElement(B,null,V.createElement(B,{color:Z.primary},V.createElement(Oe,{type:`dots`})),` `,v);default:return null}})()))},_r=e=>new Promise(t=>{let{unmount:n}=ye(e(e=>{n(),t(e)}))}),vr=()=>_r(e=>V.createElement(fr,{message:`How do you want to set up the StackOne agent?`,initialIndex:0,choices:[{label:`Local — this project: auth + .mcp.json + connector skills (.claude/) + guide (CLAUDE.md)`,value:`local`},{label:`Global — any repo: auth + global MCP only (no connector skills/guide)`,value:`global`}],onSelect:t=>e(t)})),yr=(e,t=!0)=>_r(n=>V.createElement(fr,{message:e,initialIndex:t?0:1,choices:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}],onSelect:e=>n(e===`yes`),onCancel:()=>n(!1)})),br=async e=>{let t=Bn(e);return t&&await yr(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`,!0)?t.root:_r(n=>V.createElement(pr,{message:t?`Path to install into:`:`Current directory is not a git repo. Path to install into:`,initialValue:e,validate:t=>{let n=Nn(t)||e;return N(n)?!0:`Path does not exist: ${n}`},onSubmit:t=>n(Nn(t)||e)}))},xr=e=>new Promise(t=>{let{unmount:n}=ye(V.createElement(gr,{initialMode:e.initialMode,pathFlag:e.pathFlag,startDir:e.startDir??process.cwd(),onExit:e=>{n(),t(e)}}))});var Sr=class{async execute(e){y.log(T.blue.bold(`🤖 StackOne Agent Setup - Local Project
143
+ `));try{let t=_e(Nn(e?.targetPath??process.cwd()));await Re(t).then(()=>!0).catch(()=>!1)||(y.error(`Target path does not exist: ${t}`),process.exit(1)),e?.targetPath&&y.log(T.dim(`Installing into ${t}\n`));let n=await Re(`${t}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await Re(`${t}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){y.warn(`Existing local setup detected:`),n&&y.log(T.dim(` • CLAUDE.md found`)),r&&y.log(T.dim(` • .mcp.json found`)),y.log(``);let t=pn(!!e?.legacy,e?.credentials),i=!!process.stdin.isTTY;t||!i?y.log(T.dim(t?`Non-interactive credentials detected; proceeding without confirmation.
144
144
  `:`No interactive terminal detected; proceeding without overwrite confirmation.
145
- `)):(await pr(`Overwrite existing local configuration?`,!1)||(y.log(T.dim(`
145
+ `)):(await yr(`Overwrite existing local configuration?`,!1)||(y.log(T.dim(`
146
146
  Setup cancelled.`)),process.exit(0)),y.log(``))}let i=await ee();(!i||!d(i))&&(y.warn(`Not authenticated globally.`),y.log(T.white(`Let's authenticate now...
147
- `)),i=await bn(!!e?.legacy,e?.credentials),y.log(``)),C(await S(t,i.apiKey));let a=q(`Creating .mcp.json...`).start();try{l(m(t),s(),i.apiKey),a.succeed(`Created .mcp.json`),y.success(`Local setup complete!`),y.log(T.white(`Files created:`)),y.log(T.cyan(` • .mcp.json`)),y.log(T.dim(`Token stored securely in Claude MCP server config.`)),y.log(T.dim(`
147
+ `)),i=await En(!!e?.legacy,e?.credentials),y.log(``)),C(await S(t,i.apiKey));let a=q(`Creating .mcp.json...`).start();try{l(m(t),s(),i.apiKey),a.succeed(`Created .mcp.json`),y.success(`Local setup complete!`),y.log(T.white(`Files created:`)),y.log(T.cyan(` • .mcp.json`)),y.log(T.dim(`Token stored securely in Claude MCP server config.`)),y.log(T.dim(`
148
148
  💡 The stackone-agent-local MCP server is now available in this project`)),y.log(T.dim(`
149
149
  💡 Tip: Run Claude without permission prompts:`),T.cyan(`claude --dangerously-skip-permissions`)),y.log(T.blue(`
150
- Verify:`),T.cyan(`claude mcp list`)),y.log(``)}catch(e){a.fail(`Failed to create .mcp.json`),e instanceof Error&&y.error(e.message)}let o=q(`Syncing connector-building skills + guide...`).start();try{let e=ir({cwd:t}),n=e.skills.changed.length+e.skills.unchanged.length,r=e.guide===`missing-source`?`unavailable in this version`:`in CLAUDE.md`;o.succeed(`Connector-building environment ready (${n} skills in .claude/, guide ${r})`),y.log(T.dim(` Refresh anytime with`),T.cyan(`stackone agent sync`))}catch(e){o.fail(`Failed to sync connector-building environment`),e instanceof Error&&y.error(e.message)}process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}},_r=class{async execute(e){let t=k(),n=e?.mode;if(y.log(T.bold(`
150
+ Verify:`),T.cyan(`claude mcp list`)),y.log(``)}catch(e){a.fail(`Failed to create .mcp.json`),e instanceof Error&&y.error(e.message)}let o=q(`Syncing connector-building skills + guide...`).start();try{let e=ur({cwd:t}),n=e.skills.changed.length+e.skills.unchanged.length,r=e.guide===`missing-source`?`unavailable in this version`:`in CLAUDE.md`;o.succeed(`Connector-building environment ready (${n} skills in .claude/, guide ${r})`),y.log(T.dim(` Refresh anytime with`),T.cyan(`stackone agent sync`))}catch(e){o.fail(`Failed to sync connector-building environment`),e instanceof Error&&y.error(e.message)}process.exit(0)}catch(e){e instanceof Error?y.error(e.message):y.error(`Unknown error occurred`),process.exit(1)}}},Cr=class{async execute(e){let t=se(),n=e?.mode;if(y.log(T.bold(`
151
151
  Available skills
152
152
  `)),t.length===0){y.log(T.dim(` No bundled skills found.
153
- `));return}for(let e of t)y.log(` • ${e}`);if(n){let e=j(n);if(e.length>0){y.log(T.bold(`\nRecommended for mode "${n}":\n`));for(let n of e){let e=t.includes(n);y.log(` • ${n}${e?``:T.dim(` (not found)`)}`)}}}y.log(``)}};const vr=(e,t,n)=>{let r=n?`stale`:`synced`;t.changed.length>0&&y.log(T.cyan(` • ${e} ${r}: ${t.changed.join(`, `)}`)),t.missing.length>0&&y.log(T.dim(` • ${e} not in this harness version: ${t.missing.join(`, `)}`))},yr=(e,t,n)=>{if(t.status===`missing-source`)return;let r=t.status===`changed`?n?`stale`:`synced`:`up to date`;y.log(T.cyan(` • ${e} ${r}: ${t.fileCount} file(s)`))},br=(e,t)=>{e===`missing-source`?y.log(T.dim(` • connector-guide.md not in this harness version — skipped CLAUDE.md`)):e===`changed`&&y.log(T.cyan(` • CLAUDE.md guide block ${t?`stale`:`updated`}`))};var xr=class{async execute(e){let t=!!e?.check,n=e?.pluginDir;ar(n)||(y.error(n?`--plugin-dir is not a valid @stackone/agent-harness plugin dir: ${n}`:`Could not locate the bundled @stackone/agent-harness plugin. Reinstall the CLI and try again.`),process.exit(1));let r=Kn(n);y.log(T.blue.bold(`🧩 ${t?`Checking`:`Syncing`} connector-building environment`)+T.dim(` (agent-harness@${r}${n?` [--plugin-dir]`:``})\n`));try{let e=ir({cwd:process.cwd(),check:t,pluginDir:n});vr(`skills`,e.skills,t),yr(`commands`,e.commands,t),yr(`agents`,e.agents,t),br(e.guide,t),t&&(e.hasChanges&&(y.log(``),y.error("Connector-building environment is out of date. Run `stackone agent sync` to update."),process.exit(1)),y.success(`Connector-building environment is up to date.`),process.exit(0)),e.hasChanges?(y.success(`Connector-building environment synced into .claude/ and CLAUDE.md.`),y.log(T.dim(`
154
- 💡 Skills and the connector guide are managed by the CLI — `),T.dim("re-run `stackone agent sync` after a CLI update."))):y.success(`Already up to date — nothing to sync.`),process.exit(0)}catch(e){y.error(e instanceof Error?e.message:`Unknown error during sync`),process.exit(1)}}};const Sr={profiles:{}},Cr=()=>{let t=i.readConfigFile(e);if(!t)return Sr;try{return JSON.parse(t)}catch{return Sr}},wr=e=>Cr().profiles[e],Tr=e=>!!Cr().profiles[e],Er=(t,n)=>{let r=Cr();r.profiles[t]=n,i.writeConfigFile(e,JSON.stringify(r,null,2))},Dr=()=>{let e=Cr();return Object.keys(e.profiles)},Or=`https://api.stackone.com`;var kr=class{async execute({profile:e,connector:r,apiUrl:i,apiKey:a}={}){if(!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Tr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Dr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?wr(e):{apiUrl:i??Or,apiKey:a};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),r||(y.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let s=r.split(`@`);(s.length!==2||!s[0]||!s[1])&&(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)}`),process.exit(1));let c=o.apiUrl??Or,l=await this.dropConnector(r,c,o.apiKey);process.exit(l?0:1)}async dropConnector(e,n,i){let a=q(`🗑️ Dropping connector ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/registry/connectors/${e}`,{method:`DELETE`,headers:{Authorization:`Basic ${r}`}});return a.stop(),o.status===204?(y.success(`Successfully dropped connector ${t(e)} from the registry`),!0):o.status===404?(y.error(`Connector ${t(e)} not found in the registry`),!1):o.status===401||o.status===403?(y.error(`You do not have permission to drop this connector`),!1):o.status===409?(y.error(`Connector ${t(e)} has associated configs and cannot be dropped`),y.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(o.ok||await b(o,`Failed to drop connector ${t(e)} from the registry`),!1)}catch(i){return a.stop(),y.error(`Failed to drop connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}};const Ar=`stackone`;async function jr(e,n){n.length===0&&(y.error(`Multiple versions of connector ${t(e)} were found but no owner information was returned`),process.exit(1));let r=n.map(e=>({value:e,label:e===Ar?`StackOne`:`Custom`,hint:e===Ar?`Official StackOne connector`:`Custom connector version created by your organization`}));y.warn(`Multiple versions of connector ${t(e)} were found. Please select which version to use.`);let i=await Xe({message:`Which version would you like to use?`,options:r});return qe(i)&&(y.error(`Operation cancelled.`),process.exit(1)),i}const Mr=`https://api.stackone.com`;var Nr=class{async execute({profile:e,connector:r,accountId:i,format:a,outputFile:s,apiUrl:c,apiKey:l,owner:u}={}){if(!e&&!l&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&l&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&c&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Tr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Dr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let d=e?wr(e):{apiUrl:c??Mr,apiKey:l};d?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),J(r)&&J(i)&&(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1)),Y(r)&&Y(i)&&(y.error(`Please provide either ${t(`--connector`)} or ${t(`--account-id`)}, not both.`),process.exit(1)),Y(a)&&a!==`yaml`&&a!==`json`&&(y.error(`Format must be either ${t(`yaml`)} or ${t(`json`)}.`),process.exit(1));let f=d.apiUrl??Mr,p;if(Y(r)){this.#t(r)||(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),process.exit(1));let e=this.#n(r);p=await this.#r(e,f,d.apiKey,a,u)}else Y(i)?p=await this.#i(i,f,d.apiKey,a):(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1));if(Y(s))try{G.writeFileSync(s,p,`utf-8`),y.success(`Connector written to file: ${t(s)}`)}catch(e){y.error(`Failed to write connector to file ${t(s)}: ${e.message}`),process.exit(1)}else if(y.log(`\n${T.blue.inverse(` CONNECTOR CONTENT `)}\n`),!a||a===`yaml`)y.log(this.#e(p));else if(a===`json`)try{o(JSON.parse(p))}catch{y.log(p)}else y.log(p);process.exit(0)}#e(e){return e.split(`
153
+ `));return}for(let e of t)y.log(` • ${e}`);if(n){let e=j(n);if(e.length>0){y.log(T.bold(`\nRecommended for mode "${n}":\n`));for(let n of e){let e=t.includes(n);y.log(` • ${n}${e?``:T.dim(` (not found)`)}`)}}}y.log(``)}};const wr=(e,t,n)=>{let r=n?`stale`:`synced`;t.changed.length>0&&y.log(T.cyan(` • ${e} ${r}: ${t.changed.join(`, `)}`)),t.missing.length>0&&y.log(T.dim(` • ${e} not in this harness version: ${t.missing.join(`, `)}`))},Tr=(e,t,n)=>{if(t.status===`missing-source`)return;let r=t.status===`changed`?n?`stale`:`synced`:`up to date`;y.log(T.cyan(` • ${e} ${r}: ${t.fileCount} file(s)`))},Er=(e,t)=>{e===`missing-source`?y.log(T.dim(` • connector-guide.md not in this harness version — skipped CLAUDE.md`)):e===`changed`&&y.log(T.cyan(` • CLAUDE.md guide block ${t?`stale`:`updated`}`))};var Dr=class{async execute(e){let t=!!e?.check,n=e?.pluginDir;dr(n)||(y.error(n?`--plugin-dir is not a valid @stackone/agent-harness plugin dir: ${n}`:`Could not locate the bundled @stackone/agent-harness plugin. Reinstall the CLI and try again.`),process.exit(1));let r=Qn(n);y.log(T.blue.bold(`🧩 ${t?`Checking`:`Syncing`} connector-building environment`)+T.dim(` (agent-harness@${r}${n?` [--plugin-dir]`:``})\n`));try{let e=ur({cwd:process.cwd(),check:t,pluginDir:n});wr(`skills`,e.skills,t),Tr(`commands`,e.commands,t),Tr(`agents`,e.agents,t),Er(e.guide,t),t&&(e.hasChanges&&(y.log(``),y.error("Connector-building environment is out of date. Run `stackone agent sync` to update."),process.exit(1)),y.success(`Connector-building environment is up to date.`),process.exit(0)),e.hasChanges?(y.success(`Connector-building environment synced into .claude/ and CLAUDE.md.`),y.log(T.dim(`
154
+ 💡 Skills and the connector guide are managed by the CLI — `),T.dim("re-run `stackone agent sync` after a CLI update."))):y.success(`Already up to date — nothing to sync.`),process.exit(0)}catch(e){y.error(e instanceof Error?e.message:`Unknown error during sync`),process.exit(1)}}};const Or={profiles:{}},kr=()=>{let t=i.readConfigFile(e);if(!t)return Or;try{return JSON.parse(t)}catch{return Or}},Ar=e=>kr().profiles[e],jr=e=>!!kr().profiles[e],Mr=(t,n)=>{let r=kr();r.profiles[t]=n,i.writeConfigFile(e,JSON.stringify(r,null,2))},Nr=()=>{let e=kr();return Object.keys(e.profiles)},Pr=`https://api.stackone.com`;var Fr=class{async execute({profile:e,connector:r,apiUrl:i,apiKey:a}={}){if(!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?Ar(e):{apiUrl:i??Pr,apiKey:a};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),r||(y.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let s=r.split(`@`);(s.length!==2||!s[0]||!s[1])&&(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)}`),process.exit(1));let c=o.apiUrl??Pr,l=await this.dropConnector(r,c,o.apiKey);process.exit(l?0:1)}async dropConnector(e,n,i){let a=q(`🗑️ Dropping connector ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/registry/connectors/${e}`,{method:`DELETE`,headers:{Authorization:`Basic ${r}`}});return a.stop(),o.status===204?(y.success(`Successfully dropped connector ${t(e)} from the registry`),!0):o.status===404?(y.error(`Connector ${t(e)} not found in the registry`),!1):o.status===401||o.status===403?(y.error(`You do not have permission to drop this connector`),!1):o.status===409?(y.error(`Connector ${t(e)} has associated configs and cannot be dropped`),y.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(o.ok||await b(o,`Failed to drop connector ${t(e)} from the registry`),!1)}catch(i){return a.stop(),y.error(`Failed to drop connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}};const Ir=`stackone`;async function Lr(e,n){n.length===0&&(y.error(`Multiple versions of connector ${t(e)} were found but no owner information was returned`),process.exit(1));let r=n.map(e=>({value:e,label:e===Ir?`StackOne`:`Custom`,hint:e===Ir?`Official StackOne connector`:`Custom connector version created by your organization`}));y.warn(`Multiple versions of connector ${t(e)} were found. Please select which version to use.`);let i=await Ze({message:`Which version would you like to use?`,options:r});return Je(i)&&(y.error(`Operation cancelled.`),process.exit(1)),i}const Rr=`https://api.stackone.com`;var zr=class{async execute({profile:e,connector:r,accountId:i,format:a,outputFile:s,apiUrl:c,apiKey:l,owner:u}={}){if(!e&&!l&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&l&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&c&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let d=e?Ar(e):{apiUrl:c??Rr,apiKey:l};d?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),J(r)&&J(i)&&(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1)),Y(r)&&Y(i)&&(y.error(`Please provide either ${t(`--connector`)} or ${t(`--account-id`)}, not both.`),process.exit(1)),Y(a)&&a!==`yaml`&&a!==`json`&&(y.error(`Format must be either ${t(`yaml`)} or ${t(`json`)}.`),process.exit(1));let f=d.apiUrl??Rr,p;if(Y(r)){this.#t(r)||(y.error(`Invalid connector format ${n(r)}. Expected format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),process.exit(1));let e=this.#n(r);p=await this.#r(e,f,d.apiKey,a,u)}else Y(i)?p=await this.#i(i,f,d.apiKey,a):(y.error(`Either ${t(`--connector`)} or ${t(`--account-id`)} must be provided`),process.exit(1));if(Y(s))try{G.writeFileSync(s,p,`utf-8`),y.success(`Connector written to file: ${t(s)}`)}catch(e){y.error(`Failed to write connector to file ${t(s)}: ${e.message}`),process.exit(1)}else if(y.log(`\n${T.blue.inverse(` CONNECTOR CONTENT `)}\n`),!a||a===`yaml`)y.log(this.#e(p));else if(a===`json`)try{o(JSON.parse(p))}catch{y.log(p)}else y.log(p);process.exit(0)}#e(e){return e.split(`
155
155
  `).map(e=>{if(e.trim().startsWith(`#`))return T.gray(e);if(e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t+1),r=e.substring(t+1),i=r,a=r.trim();return a===`true`||a===`false`?i=r.replace(a,T.cyan(a)):a===`null`||a===`~`?i=r.replace(a,T.gray(a)):/^-?\d+(\.\d+)?$/.test(a)?i=r.replace(a,T.green(a)):(a.startsWith(`"`)&&a.endsWith(`"`)||a.startsWith(`'`)&&a.endsWith(`'`)||a&&!a.startsWith(`-`))&&(i=r.replace(a,T.yellow(a))),T.red(n)+i}return e.trim().startsWith(`-`)?e.replace(`-`,T.gray(`-`)):e}).join(`
156
- `)}#t=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#n=e=>e.includes(`@`)?e:`${e}@latest`;async#r(e,n,i,a,o){let s=q(`Getting connector ${t(e)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=a?`?format=${a}`:``,l=o?`${c?`&`:`?`}owner=${encodeURIComponent(o)}`:``,u=await fetch(`${n}/registry/connectors/${e}${c}${l}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),u.status===409){o&&(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1));let i=await jr(e,(await u.json()).availableOwners??[]),a=`${n}/registry/connectors/${e}${c}${c?`&`:`?`}owner=${encodeURIComponent(i)}`;s.text=`Getting connector ${t(e)} from registry...`,s.start();let l=await fetch(a,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),l.ok||(await b(l,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await l.text()}return u.ok||(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await u.text()}catch(i){s.stop(),y.error(`Failed to get connector ${t(e)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}async#i(e,n,i,a){let o=q(`Getting connector from account ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),s=a?`?format=${a}`:``,c=await fetch(`${n}/accounts/${e}/connector${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return o.stop(),c.ok||(await b(c,`Failed to get connector from account ${t(e)}`),process.exit(1)),await c.text()}catch(i){o.stop(),y.error(`Failed to get connector from account ${t(e)}: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}};const Pr=`http://localhost:4000`;var Fr=class{async execute({environment:e}={}){let n=e?.toLowerCase()??`production`;try{Ke(`${T.inverse(` Initialize profile `)}`);let e=await Ze({message:`Profile label`,validate:e=>{if(!e||e.trim().length===0)return`The profile label is required`;if(e.includes(` `))return`The profile label cannot contain spaces`}});if(qe(e))return We(`Configuration profile initialization cancelled`),process.exit(0);if(Tr(e)){let n=await Ge({message:`Configuration profile with name ${t(e)} already exists. Do you want to overwrite it?`});if(qe(n)||!n)return We(`Configuration profile initialization cancelled`),process.exit(0)}let r;if(n===`production`)r=`https://api.stackone.com`;else if(n===`staging`)r=`https://api.stackone-dev.com`;else{let e=await Ze({message:`API URL`,placeholder:Pr,initialValue:Pr,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{new URL(e)}catch{return`Please enter a valid URL`}}});if(qe(e))return We(`Configuration profile initialization cancelled`),process.exit(0);r=e}let i=await Ye({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if(qe(i))return We(`Configuration profile initialization cancelled`),process.exit(0);Er(e,{label:e,environment:n,apiUrl:r,apiKey:i}),Je(`${T.green(`✔`)} Configuration profile ${t(e)} initialized successfully!`),process.exit(0)}catch(e){e?.isTtyError?y.error(`Prompt couldn't be rendered in the current environment`):y.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const $={pending:`○`,acceptRemote:`●`,acceptLocal:`◐`,acceptBoth:`◑`,current:`◉`,arrow:`→`,check:`✓`,cross:`✗`,warning:`⚠`};var Ir=class{constructor(e,t,n,r){this.conflicts=[],this.currentIndex=0,this.totalConflicts=0,this.currentCleanup=null,this.connectorId=t,this.localVersion=n,this.remoteVersion=r,this.conflicts=e.map(e=>({conflict:e,choice:e.type===`unchanged`?`remote`:`pending`})),this.totalConflicts=e.filter(e=>e.type===`conflict`).length}resetForReResolution(){this.currentIndex=0}async resolve(){return this.totalConflicts===0?{cancelled:!1,states:this.conflicts}:(this.moveToNextConflict(),new Promise(e=>{let t=rt({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),this.render();let n=n=>{let r=n.toString();if(r===``){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r===`\x1B`&&n.length===1){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r.startsWith(`\x1B[`)){switch(r.slice(2)){case`D`:this.moveToPrevConflict(),this.render();break;case`C`:this.moveToNextConflict(),this.render();break}return}switch(r){case`r`:case`R`:this.setCurrentChoice(`remote`),this.advanceAfterChoice(t);break;case`l`:case`L`:this.setCurrentChoice(`local`),this.advanceAfterChoice(t);break;case`b`:case`B`:this.setCurrentChoice(`both`),this.advanceAfterChoice(t);break;case`\r`:case`
156
+ `)}#t=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#n=e=>e.includes(`@`)?e:`${e}@latest`;async#r(e,n,i,a,o){let s=q(`Getting connector ${t(e)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=a?`?format=${a}`:``,l=o?`${c?`&`:`?`}owner=${encodeURIComponent(o)}`:``,u=await fetch(`${n}/registry/connectors/${e}${c}${l}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),u.status===409){o&&(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1));let i=await Lr(e,(await u.json()).availableOwners??[]),a=`${n}/registry/connectors/${e}${c}${c?`&`:`?`}owner=${encodeURIComponent(i)}`;s.text=`Getting connector ${t(e)} from registry...`,s.start();let l=await fetch(a,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),l.ok||(await b(l,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await l.text()}return u.ok||(await b(u,`Failed to get connector ${t(e)} from the registry`),process.exit(1)),await u.text()}catch(i){s.stop(),y.error(`Failed to get connector ${t(e)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}async#i(e,n,i,a){let o=q(`Getting connector from account ${t(e)}...`).start();try{let r=Buffer.from(i).toString(`base64`),s=a?`?format=${a}`:``,c=await fetch(`${n}/accounts/${e}/connector${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return o.stop(),c.ok||(await b(c,`Failed to get connector from account ${t(e)}`),process.exit(1)),await c.text()}catch(i){o.stop(),y.error(`Failed to get connector from account ${t(e)}: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}}};const Br=`http://localhost:4000`;var Vr=class{async execute({environment:e}={}){let n=e?.toLowerCase()??`production`;try{qe(`${T.inverse(` Initialize profile `)}`);let e=await Qe({message:`Profile label`,validate:e=>{if(!e||e.trim().length===0)return`The profile label is required`;if(e.includes(` `))return`The profile label cannot contain spaces`}});if(Je(e))return Ge(`Configuration profile initialization cancelled`),process.exit(0);if(jr(e)){let n=await Ke({message:`Configuration profile with name ${t(e)} already exists. Do you want to overwrite it?`});if(Je(n)||!n)return Ge(`Configuration profile initialization cancelled`),process.exit(0)}let r;if(n===`production`)r=`https://api.stackone.com`;else if(n===`staging`)r=`https://api.stackone-dev.com`;else{let e=await Qe({message:`API URL`,placeholder:Br,initialValue:Br,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{new URL(e)}catch{return`Please enter a valid URL`}}});if(Je(e))return Ge(`Configuration profile initialization cancelled`),process.exit(0);r=e}let i=await Xe({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if(Je(i))return Ge(`Configuration profile initialization cancelled`),process.exit(0);Mr(e,{label:e,environment:n,apiUrl:r,apiKey:i}),Ye(`${T.green(`✔`)} Configuration profile ${t(e)} initialized successfully!`),process.exit(0)}catch(e){e?.isTtyError?y.error(`Prompt couldn't be rendered in the current environment`):y.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const $={pending:`○`,acceptRemote:`●`,acceptLocal:`◐`,acceptBoth:`◑`,current:`◉`,arrow:`→`,check:`✓`,cross:`✗`,warning:`⚠`};var Hr=class{constructor(e,t,n,r){this.conflicts=[],this.currentIndex=0,this.totalConflicts=0,this.currentCleanup=null,this.connectorId=t,this.localVersion=n,this.remoteVersion=r,this.conflicts=e.map(e=>({conflict:e,choice:e.type===`unchanged`?`remote`:`pending`})),this.totalConflicts=e.filter(e=>e.type===`conflict`).length}resetForReResolution(){this.currentIndex=0}async resolve(){return this.totalConflicts===0?{cancelled:!1,states:this.conflicts}:(this.moveToNextConflict(),new Promise(e=>{let t=st({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),this.render();let n=n=>{let r=n.toString();if(r===``){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r===`\x1B`&&n.length===1){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r.startsWith(`\x1B[`)){switch(r.slice(2)){case`D`:this.moveToPrevConflict(),this.render();break;case`C`:this.moveToNextConflict(),this.render();break}return}switch(r){case`r`:case`R`:this.setCurrentChoice(`remote`),this.advanceAfterChoice(t);break;case`l`:case`L`:this.setCurrentChoice(`local`),this.advanceAfterChoice(t);break;case`b`:case`B`:this.setCurrentChoice(`both`),this.advanceAfterChoice(t);break;case`\r`:case`
157
157
  `:this.allResolved()?(this.cleanup(t),e({cancelled:!1,states:this.conflicts})):(this.moveToNextUnresolved(),this.render());break;case`q`:case`Q`:this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});break;case`a`:case`A`:this.acceptAllRemaining(`remote`),this.render();break;case`u`:case`U`:this.setCurrentChoice(`pending`),this.render();break}};process.stdin.on(`data`,n),this.currentCleanup=()=>{process.stdin.removeListener(`data`,n),process.stdin.isTTY&&process.stdin.setRawMode(!1),t.close()}}))}cleanup(e){this.currentCleanup?(this.currentCleanup(),this.currentCleanup=null):(process.stdin.isTTY&&process.stdin.setRawMode(!1),e.close())}advanceAfterChoice(e){this.allResolved()||this.moveToNextUnresolved(),this.render()}render(){v();let e=process.stdout.columns||80;this.renderHeader(e),this.renderProgressBar(e),this.renderCurrentConflict(e),this.renderControls(e)}renderHeader(e){let t=this.connectorId,n=`${this.localVersion} ${$.arrow} ${this.remoteVersion}`,r=Math.max(0,e-17),i=Math.floor(r/2),a=r-i,o=` `.repeat(i)+`CONFLICT RESOLVER`+` `.repeat(a);y.log(``),y.log(T.bgBlue.white.bold(o)),y.log(T.gray(this.centerText(t,e))),y.log(T.gray(this.centerText(n,e))),y.log(``)}renderProgressBar(e){let t=this.conflicts.filter(e=>e.conflict.type===`conflict`),n=this.getCurrentConflictIndex(),r=t.map((e,t)=>{let r=t===n,i,a;switch(e.choice){case`remote`:i=r?$.current:$.acceptRemote,a=T.green;break;case`local`:i=r?$.current:$.acceptLocal,a=T.yellow;break;case`both`:i=r?$.current:$.acceptBoth,a=T.cyan;break;default:i=r?$.current:$.pending,a=r?T.white:T.gray}return a(i)}),i=t.filter(e=>e.choice!==`pending`).length,a=` Conflict ${n+1} of ${this.totalConflicts} • ${i}/${this.totalConflicts} resolved `;y.log(T.gray(this.centerText(a,e))),y.log(this.centerText(r.join(` `),e)),y.log(``)}renderCurrentConflict(e){let t=this.conflicts[this.currentIndex];if(!t||t.conflict.type!==`conflict`)return;let n=t.conflict;if(y.log(T.gray(`_`.repeat(e))),y.log(`
158
158
 
159
159
  `),n.local){let e=t.choice===`local`||t.choice===`both`?T.yellow.bold(`${$.check} LOCAL (keeping)`):T.red.bold(`${$.cross} LOCAL (removing)`),r=n.local.split(`
@@ -167,9 +167,9 @@ Available skills
167
167
  `),s=r.length>20?`\n${T.gray(`... and ${r.length-20} more lines`)}`:``;y.log(`${e}\n\n${o}${s}`)}y.log(`
168
168
 
169
169
  `),y.log(T.gray(`_`.repeat(e))),y.log(``)}renderControls(e){let t=[T.green(`[R] Accept Remote`),T.yellow(`[L] Keep Local`),T.cyan(`[B] Keep Both`),T.gray(`[U] Undo`)],n=[T.gray(`[←/→] Navigate`),T.gray(`[A] Accept all remaining`)],r=this.allResolved()?[T.green.bold(`[Enter] Apply Changes`),T.gray(`[Esc] Cancel`)]:[T.gray(`[Enter] Next Unresolved`),T.gray(`[Esc] Cancel`)];y.log(this.centerText(t.join(` `),e)),y.log(``),y.log(this.centerText(n.join(` `),e)),y.log(``),y.log(this.centerText(r.join(` `),e)),this.allResolved()&&(y.log(``),y.log(T.green.bold(this.centerText(`✓ All conflicts resolved!`,e))))}renderFinalSummary(){v();let e=this.conflicts.filter(e=>e.conflict.type===`conflict`),t=0,n=0,r=0;for(let i of e)switch(i.choice){case`remote`:t++;break;case`local`:n++;break;case`both`:r++;break}let i=[T.green.bold(`Conflict resolution complete`),``,`${T.bold(this.totalConflicts)} conflicts resolved:`,``,`${T.green($.acceptRemote)} Accepted remote: ${t}`,`${T.yellow($.acceptLocal)} Kept local: ${n}`,`${T.cyan($.acceptBoth)} Kept both: ${r}`];y.box(i.join(`
170
- `))}renderCancelled(){v(),y.log(T.yellow(`Conflict resolution cancelled`)),y.log(``),y.log(`No changes were made to your local connector file.`)}getCurrentConflictIndex(){let e=-1;for(let t=0;t<=this.currentIndex&&t<this.conflicts.length;t++)this.conflicts[t].conflict.type===`conflict`&&e++;return e}moveToNextConflict(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToPrevConflict(){for(let e=this.currentIndex-1;e>=0;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=this.conflicts.length-1;e>this.currentIndex;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToNextUnresolved(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}}setCurrentChoice(e){this.conflicts[this.currentIndex]?.conflict.type===`conflict`&&(this.conflicts[this.currentIndex].choice=e)}allResolved(){return this.conflicts.filter(e=>e.conflict.type===`conflict`).every(e=>e.choice!==`pending`)}acceptAllRemaining(e){for(let t of this.conflicts)t.conflict.type===`conflict`&&t.choice===`pending`&&(t.choice=e)}centerText(e,t){let n=this.stripAnsi(e),r=Math.max(0,Math.floor((t-n.length)/2));return` `.repeat(r)+e}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}getResolvedContent(){let e=[];for(let t of this.conflicts)if(t.conflict.type===`unchanged`)e.push(t.conflict.content||``);else if(t.conflict.type===`conflict`)switch(t.choice){case`remote`:t.conflict.remote&&e.push(t.conflict.remote);break;case`local`:t.conflict.local&&e.push(t.conflict.local);break;case`both`:t.conflict.local&&e.push(t.conflict.local),t.conflict.remote&&e.push(t.conflict.remote);break;case`pending`:t.conflict.remote&&e.push(t.conflict.remote);break}return e.join(``)}};const Lr=`https://api.stackone.com`;var Rr=class{async execute({profile:e,connector:n,outputPath:r,apiUrl:i,apiKey:a,owner:o}={}){if(J(n)&&(y.error(`Connector identifier is required`),y.log(`Please provide a connector identifier using the ${t(`--connector`)} option in the format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),y.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Tr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Dr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let s=e?wr(e):{apiUrl:i??Lr,apiKey:a};s?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1));let c=s.apiUrl??Lr,[l,u]=n.split(`@`),d=await this.#f(l,c,s.apiKey,u??`latest`,o),f=this.#e(d),p=f.version??`unknown`,m=this.#t(r,f.key,p),h=this.#r(m),g=h===null,_=d;if(!g){let e=this.#i(h,m);e&&(y.warn(e.message),e.errors.length>0&&x(e.errors,!1),y.log(``));let t=e?void 0:this.#e(h);if(this.#o(h,d)){this.#a(h,d,m);let e=t?.version??`unknown`,r=await this.#s(h,d,n,e,p);r.action===`cancel`&&(We(`Pull cancelled`),process.exit(0)),r.action===`keep-local`&&(y.log(``),y.info(`Keeping local version. No changes made.`),process.exit(0)),r.action===`interactive-cancel`&&process.exit(0),r.action===`interactive`&&(_=r.resolvedContent)}else y.info(`No changes detected in connector configuration.`),process.exit(0)}let ee=tt(_).connector,v=ee?.key??f.key,b=ee?.version??p,S=this.#t(r,v,b),C=S;if(S!==m){let e=await this.#n(S);y.log(``),e!==void 0&&(C=e)}await this.#d(C,_),g?y.success(`Connector ${t(v)}@${t(b)} pulled successfully (new connector)`):y.success(`Connector ${t(v)}@${t(b)} updated successfully`);let te=v===f.key?t(v):`${t(f.key)} ${T.whiteBright(`→`)} ${t(v)}`,w=b===p?t(b):`${t(p)} ${T.whiteBright(`→`)} ${t(b)}`,E=C===m?t(C):`${t(m)}\n ${T.whiteBright(`→`)} ${t(C)}`;y.log(`\n${T.blue.inverse(` CONNECTOR DETAILS `)}\n`),y.log(` Provider: ${te}`),y.log(` Version: ${w}`),y.log(` Output file: ${E}`),process.exit(0)}#e(e){let n=tt(e),r=n?.errors??[];if(n.success)return n.connector;y.error(`Connector pulled from the registry is not valid`),y.log(`Please make sure you are using the latest version of the StackOne CLI by running ${t(`stackone update`)}`),r.length>0&&x(r,!0),process.exit(1)}#t(e,n,r){let i=`${n}_v${r.replaceAll(`.`,`-`)}.s1.yaml`;return e?(G.existsSync(e)&&(G.statSync(e).isDirectory()||(y.error(`Output path ${t(e)} is not a directory`),y.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),Me.resolve(e,n,i)):Me.resolve(process.cwd(),`connectors`,n,i)}async#n(e){if(!G.existsSync(e))return;let n=Me.basename(e),r=Me.dirname(e);y.warn(`File ${t(n)} already exists at ${t(r)}`);let i=await Xe({message:`How would you like to proceed?`,options:[{value:`override`,label:`Override existing file`,hint:`Replace the existing file with the new content`},{value:`rename`,label:`Save with a different name`,hint:`Provide a new filename for the connector`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if((qe(i)||i===`cancel`)&&(We(`Operation cancelled. No local changes were made.`),process.exit(0)),i===`override`)return;let a=await Ze({message:`Enter the new filename:`,placeholder:n,validate:e=>{if(!e||e.trim()===``)return`Filename cannot be empty`;if(!e.endsWith(`.s1.yaml`))return`Filename must end with .s1.yaml`;let t=Me.join(r,e.trim());if(G.existsSync(t))return`File ${e} already exists`}});return qe(a)&&(We(`Operation cancelled. No local changes were made.`),process.exit(0)),Me.join(r,a.trim())}#r(e){if(!G.existsSync(e))return null;try{return G.readFileSync(e,`utf-8`)}catch{return null}}#i(e,n){try{let r=tt(e);if(!r.success){let e=r.errors??[];return{message:`Local connector ${t(Me.basename(n))} has validation errors:`,errors:e}}}catch(e){return{message:`Local connector ${t(Me.basename(n))} could not be validated: ${e.message}`,errors:[]}}return null}#a(e,t,n){let r=nt(e,t);if(!r.some(e=>e.added||e.removed)){y.info(`No changes detected in connector configuration.`);return}y.log(`${T.blue.inverse(` CHANGES `)}\n`),y.log(T.gray(`--- local: ${n}`)),y.log(T.gray(`+++ remote: StackOne Registry`)),y.log(``);let i=0,a=0;for(let e of r){let t=e.value.split(`
171
- `).filter(e=>e!==``);if(e.added){i+=t.length;for(let e of t)y.log(T.green(`+ ${e}`))}else if(e.removed){a+=t.length;for(let e of t)y.log(T.red(`- ${e}`))}else if(t.length<=6)for(let e of t)y.log(T.gray(` ${e}`));else{for(let e=0;e<3;e++)y.log(T.gray(` ${t[e]}`));y.log(T.gray(` ... (${t.length-6} unchanged lines)`));for(let e=t.length-3;e<t.length;e++)y.log(T.gray(` ${t[e]}`))}}y.log(``),y.log(T.gray(`Summary: ${T.green(`+${i}`)} additions, ${T.red(`-${a}`)} deletions`))}#o(e,t){return nt(e,t).some(e=>e.added||e.removed)}async#s(e,t,n,r,i){y.log(``);let a=await Xe({message:`How would you like to resolve the differences?`,options:[{value:`override`,label:`Override local with remote`,hint:`Replace your local file with the StackOne version`},{value:`keep-local`,label:`Keep local version`,hint:`Cancel the pull and keep your current file`},{value:`interactive`,label:`Resolve conflicts interactively`,hint:`Choose which changes to accept one by one`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if(qe(a))return{action:`cancel`};if(a===`override`)return{action:`override`};if(a===`keep-local`)return{action:`keep-local`};if(a===`interactive`){let a=await this.#c(e,t,n,r,i);return a===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:a}}return{action:`cancel`}}async#c(e,t,n,r,i){let a=nt(e,t),o=this.#u(a);if(o.length===0)return y.info(`No conflicts to resolve.`),t;let s=new Ir(o,n,r,i);for(;;){if((await s.resolve()).cancelled)return null;let e=s.getResolvedContent(),t=tt(e);if(t.success)return s.renderFinalSummary(),e;let n=await this.#l(t.errors);if(n===`cancel`)return v(),y.info(`Operation cancelled. No changes were made to the local connector.`),null;if(n===`save`)return v(),y.warn(`The connector was saved but it is invalid`),e;s.resetForReResolution()}}async#l(e){let{createInterface:t}=await import(`readline`);return new Promise(n=>{v();let r=(e||[{message:`Unknown validation error`}]).map(e=>` • ${e.message}`).join(`
172
- `);y.box({title:`⚠️ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${r}`,style:{borderColor:`yellow`,padding:1}}),y.log(``),y.log(T.bold(` Choose an action:`)),y.log(``),y.log(T.cyan(` [B]`)+` ← Go back to conflict resolution`),y.log(T.dim(` Modify your choices to fix the validation errors`)),y.log(``),y.log(T.yellow(` [S]`)+` 💾 Save anyway`),y.log(T.dim(` Save the invalid configuration (not recommended)`)),y.log(``),y.log(T.red(` [C]`)+` ✖ Cancel`),y.log(T.dim(` Discard all changes`)),y.log(``);let i=t({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let a=e=>{let t=e.toString().toLowerCase(),r=()=>{process.stdin.removeListener(`data`,a),process.stdin.isTTY&&process.stdin.setRawMode(!1),i.close()};if(t===``||t===`\x1B`){r(),n(`cancel`);return}switch(t){case`b`:r(),n(`back`);break;case`s`:r(),n(`save`);break;case`c`:case`q`:r(),n(`cancel`);break}};process.stdin.on(`data`,a)})}#u(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r.added&&!r.removed)t.push({type:`unchanged`,content:r.value}),n++;else if(r.removed){let i=e[n+1];i?.added?(t.push({type:`conflict`,local:r.value,remote:i.value}),n+=2):(t.push({type:`conflict`,local:r.value,remote:void 0}),n++)}else r.added&&t.push({type:`conflict`,local:void 0,remote:r.value}),n++}return t}async#d(e,n){let r=Me.dirname(e);G.existsSync(r)||G.mkdirSync(r,{recursive:!0});try{G.writeFileSync(e,n,`utf-8`)}catch(n){y.error(`Failed to write connector to file ${t(e)}: ${n.message}`),process.exit(1)}}async#f(e,n,i,a,o){let s=q(`Pulling connector ${t(e)}@${t(a)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=`${n}/registry/connectors/${e}@${a}${o?`?owner=${encodeURIComponent(o)}`:``}`,l=await fetch(c,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),l.status===409){o&&(await this.#p(l,e,a),process.exit(1));let i=(await l.json()).availableOwners??[],c=await jr(`${e}@${a}`,i);s.text=`Pulling connector ${t(e)}@${t(a)} from registry...`,s.start();let u=`${n}/registry/connectors/${e}@${a}`,d=await fetch(`${u}?owner=${encodeURIComponent(c)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),d.ok||(await this.#p(d,e,a),process.exit(1)),await d.text()}return l.ok||(await this.#p(l,e,a),process.exit(1)),await l.text()}catch(i){s.stop(),y.error(`Failed to pull connector ${t(e)}@${t(a)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid.`),process.exit(1)}}async#p(e,n,r){switch(e.status){case 401:case 403:y.error(`Access denied`),y.log(`Please ensure that your API key is valid and has the ${t(`connectors:read`)} scope required to pull connectors.`);break;case 404:y.error(`Connector ${t(n)}@${t(r)} was not found in the registry`),await this.#m(n);break;case 429:y.error(`Rate limit exceeded`),y.log(`Too many requests. Please wait a moment before trying again.`);break;default:await b(e,`Failed to pull connector ${t(n)}`)}}async#m(e){y.info(`To see available versions, check the connector documentation or contact support.`)}};const zr=`https://api.stackone.com`;var Br=class{async execute({profile:e,fileOrDir:n,apiUrl:r,apiKey:i,force:a}={}){if(!e&&!i&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&i&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&r&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Tr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Dr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?wr(e):{apiUrl:r??zr,apiKey:i};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),n||(y.error(`File or directory is required.`),process.exit(1));try{K(n)}catch{y.error(`File or directory not found: ${T.red(n)}`),process.exit(1)}let s=K(n),c=o.apiUrl??zr;if(s.isDirectory()){let e=qr(n),t=0;e.length===0?(y.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(y.start(`Found ${e.length} connector(s) file(s). Pushing to registry...`),y.log(``));for(let n of e)await this.uploadFile(n,c,o.apiKey,a)&&t++;t===0?y.error(`Error while pushing connectors: no files were uploaded`):(y.log(``),y.info(`Upload completed: ${T.green(t)} of ${T.blue(e.length)} file(s) uploaded successfully.`)),process.exit(t>0?0:1)}else n.endsWith(`.s1.yaml`)||(y.error(`Only ${t(`.s1.yaml`)} files are supported for upload`),process.exit(1));let l=await this.uploadFile(n,c,o.apiKey,a);process.exit(l?0:1)}async uploadFile(e,n,i,a){let o=q(`📤 Pushing connector in ${Ne(e)}...`).start();try{let r=Kr(e);if(!r)return!1;let s=Ne(e),c=new FormData,l=new Blob([r],{type:`application/x-yaml`});c.append(`file`,l,s),a&&c.append(`force`,`true`);let u=Buffer.from(i).toString(`base64`),d=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${u}`},body:c});if(o.stop(),!d.ok)return d.status===409||d.status===422?await this.handleVersionConflict(d,e,n,i,a):(await b(d,`Failed to push connector in ${t(s)} to the registry`),!1);let f=await d.json();return y.success(`Successfully uploaded ${t(s)} with connector ${t(f.provider)}@${t(f.version)}`),!0}catch(i){return o.stop(),y.error(`Failed to upload file ${t(e)}: ${i}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}async handleVersionConflict(e,n,r,i,a){let o=Vr(e.status,a);o&&y.warn(o);let s=await e.text(),c;try{c=JSON.parse(s)}catch{}let l=at.valid(c?.latestVersion);if(!l)return await b(new Response(s,{status:e.status,statusText:e.statusText}),`Failed to push connector in ${t(Ne(n))} to the registry`),!1;let u=ke(n,`utf-8`),d=Hr(u),f=d?`${t(d)}`:``,p=e.status===409?`Version ${f} already exists in the registry. Latest version: ${t(l)}`:`Version ${f} is lower than the latest version in the registry. Latest version: ${t(l)}`;y.error(p);let m=at.inc(l,`patch`)??l,h=at.inc(l,`minor`)??l,g=at.inc(l,`major`)??l,_=await Xe({message:`How would you like to proceed?`,options:[{value:m,label:`Bump patch version (${m})`},{value:h,label:`Bump minor version (${h})`},{value:g,label:`Bump major version (${g})`},{value:`cancel`,label:`Cancel push`}]});return qe(_)||_===`cancel`?(We(`Push cancelled`),!1):(je(n,Ur(u,_),`utf-8`),y.info(`Updated version to ${t(_)} in ${Ne(n)}`),this.uploadFile(n,r,i,a))}};const Vr=(e,n)=>!n||e!==409?null:`${t(`--force`)} was ignored because Immutable Versioning is enabled for this project, so a published connector version cannot be overwritten. Push a new version, or turn Immutable Versioning off in the project settings.`,Hr=e=>e.match(/^\s*version: (\S+)/m)?.[1],Ur=(e,t)=>e.replace(/^(\s*version: )\S+/m,`$1${t}`),Wr=e=>{try{let t=$e(e);return t.changelog?.summary?.trim()?null:`has no changelog entry for version ${t.version}`}catch{return null}},Gr=()=>{y.log(`Every published version must record what changed. Add an ${t(`info.changelog`)} block:`),y.log(``),y.log(T.gray(` info:`)),y.log(T.gray(` changelog:`)),y.log(T.gray(` summary: What changed in this version.`)),y.log(T.gray(` labels: [new-actions] # optional, one of: ${it.join(`, `)}`)),y.log(``)},Kr=e=>{let t=Qe(e),r=tt(t),i=r?.errors??[];if(r.success){let r=Wr(t);if(r){y.error(`Connector in ${n(e)} ${r}`),Gr();return}return t}else i.length>0?(y.error(`Connector in ${n(e)} is not valid`),x(i,!0)):y.error(`Connector in ${n(e)} is not valid. Please check the file for errors.`)},qr=e=>{let t=[],n=Ae(e,{withFileTypes:!0});for(let r of n){let n=Fe(e,r.name);r.isDirectory()?t.push(...qr(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},Jr=X.object({provider_key:X.string().optional(),provider_version:X.string().optional(),auth_config_key:X.string(),environment:X.string().default(`production`),organization_id:X.string().default(`cli-organization-id`),account_id:X.string().default(`cli-account-secure-id`),project_id:X.string().default(`cli-project-secure-id`),credentials:X.record(X.string(),X.any()).default({})}),Yr=X.record(X.string(),X.any()),Xr=X.object({path:X.record(X.string(),X.any()).default({}),queryParams:X.record(X.string(),X.any()).default({}),header:X.record(X.string(),X.any()).default({}),body:X.record(X.string(),X.any()).default({})}),Zr=`https://api.stackone.com`;var Qr=class{async execute({connector:e,action:n,actionId:r,account:i,accountId:a,params:s,credentials:c,profile:l,outputFile:u,debug:d,apiUrl:f,apiKey:p,owner:m}={}){if(!l&&!p&&a&&(y.error(`Profile or API key is required when providing an account ID`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),l&&p&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),l&&f&&y.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),l&&!Tr(l)){y.error(`Configuration profile ${t(l)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let e=Dr();e.length>0&&(y.info(`Available configuration profiles:`),e.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let h=l?wr(l):{apiUrl:f??Zr,apiKey:p};J(i)&&J(a)&&(y.error(`A valid account or account ID is required to run an action`),process.exit(1));let g;if(Y(e))if(this.#a(e)){!l&&!p&&(y.error(`Profile or API key is required when using a connector identifier`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.`),process.exit(1));let n=this.#o(e);g=await this.#s(n,h?.apiUrl??Zr,h?.apiKey,m)}else g=this.#e(e);else Y(a)&&(g=await this.#c(a,h?.apiUrl??Zr,h?.apiKey));let _=Y(n)?this.#r(n,e):g;J(_)&&(y.error(`A valid connector is required to run an action.`),process.exit(1));let ee=Y(_?.actions)?Object.keys(_?.actions).length:0,v=Y(_?.actions)?Object.keys(_.actions)[ee-1]:void 0,b=Y(v)?_?.actions?.[v]?.id:void 0,x=(Y(r)&&!r?.startsWith(`${_.key}_`)?`${_.key}_${r}`:r)??b;J(x)&&(y.error(`A valid action ID is required to run an action`),process.exit(1));let S=Y(a)?await this.#l(a,h?.apiUrl??Zr,h?.apiKey):{},C=Y(i)?this.#i(i,_.key??`unknown`,_.version??`unknown`):void 0,te=Y(c)?this.#u(c):{},w={...S,...C,credentials:{...S.credentials??{},...te}};J(w)&&(y.error(`A valid account data is required to run an action.`),process.exit(1));let E=_.actions?.[x];J(E)&&(y.error(`Action ID ${t(x)} not found in the connector ${t(_.key)}@${t(_.version)}.`),process.exit(1));let ne=Y(s)?this.#d(s,x):{path:{},queryParams:{},header:{},body:{}},D=Date.now(),re=await this.#f({connector:_,actionId:x,account:w,queryParams:{...ne.queryParams,...d?{debug:`true`}:{}},pathParams:ne.path,body:ne.body,headers:ne.header}),ie=Date.now()-D;if(Y(u))try{G.writeFileSync(u,JSON.stringify(re.output,null,2),`utf-8`),y.info(`Output written to file: ${u}`)}catch(e){y.error(`Failed to write output to file ${u}: ${e.message}`),process.exit(1)}else y.log(`\n${T.blue.inverse(` ACTION OUTPUT `)}`),o(re.output);y.log(``),y.info(`Action ${t(x)} from connector ${t(_?.key)}@${t(_?.version)} finished in ${T.yellowBright((ie/1e3).toFixed(2))} seconds.`),process.exit(0)}#e=e=>{let t=e;try{t=Qe(e)}catch{}return t?this.#n(t):void 0};#t=e=>{try{return Qe(e)}catch(n){y.error(`Failed to load connector file from ${t(e)}: ${n.message}`),process.exit(1)}};#n=e=>{let t=tt(e),n=t?.errors??[];if(t.success)return t.connector||(y.error(`Failed to load connector.`),process.exit(1)),t.connector;n.length>0?(y.error(`Connector is not valid`),x(n,!0),process.exit(1)):(y.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#r=(e,t)=>{let n=e;try{n=G.readFileSync(e,`utf-8`)}catch{}J(t)&&(y.error(`A valid connector is required to load an action.`),process.exit(1));let r=`${this.#t(t)} - ${n.split(`
170
+ `))}renderCancelled(){v(),y.log(T.yellow(`Conflict resolution cancelled`)),y.log(``),y.log(`No changes were made to your local connector file.`)}getCurrentConflictIndex(){let e=-1;for(let t=0;t<=this.currentIndex&&t<this.conflicts.length;t++)this.conflicts[t].conflict.type===`conflict`&&e++;return e}moveToNextConflict(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToPrevConflict(){for(let e=this.currentIndex-1;e>=0;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=this.conflicts.length-1;e>this.currentIndex;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToNextUnresolved(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}}setCurrentChoice(e){this.conflicts[this.currentIndex]?.conflict.type===`conflict`&&(this.conflicts[this.currentIndex].choice=e)}allResolved(){return this.conflicts.filter(e=>e.conflict.type===`conflict`).every(e=>e.choice!==`pending`)}acceptAllRemaining(e){for(let t of this.conflicts)t.conflict.type===`conflict`&&t.choice===`pending`&&(t.choice=e)}centerText(e,t){let n=this.stripAnsi(e),r=Math.max(0,Math.floor((t-n.length)/2));return` `.repeat(r)+e}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}getResolvedContent(){let e=[];for(let t of this.conflicts)if(t.conflict.type===`unchanged`)e.push(t.conflict.content||``);else if(t.conflict.type===`conflict`)switch(t.choice){case`remote`:t.conflict.remote&&e.push(t.conflict.remote);break;case`local`:t.conflict.local&&e.push(t.conflict.local);break;case`both`:t.conflict.local&&e.push(t.conflict.local),t.conflict.remote&&e.push(t.conflict.remote);break;case`pending`:t.conflict.remote&&e.push(t.conflict.remote);break}return e.join(``)}};const Ur=`https://api.stackone.com`;var Wr=class{async execute({profile:e,connector:n,outputPath:r,apiUrl:i,apiKey:a,owner:o}={}){if(J(n)&&(y.error(`Connector identifier is required`),y.log(`Please provide a connector identifier using the ${t(`--connector`)} option in the format: ${t(`provider_key@version`)} or ${t(`provider_key`)}`),y.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!e&&!a&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&a&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let s=e?Ar(e):{apiUrl:i??Ur,apiKey:a};s?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1));let c=s.apiUrl??Ur,[l,u]=n.split(`@`),d=await this.#f(l,c,s.apiKey,u??`latest`,o),f=this.#e(d),p=f.version??`unknown`,m=this.#t(r,f.key,p),h=this.#r(m),g=h===null,_=d;if(!g){let e=this.#i(h,m);e&&(y.warn(e.message),e.errors.length>0&&x(e.errors,!1),y.log(``));let t=e?void 0:this.#e(h);if(this.#o(h,d)){this.#a(h,d,m);let e=t?.version??`unknown`,r=await this.#s(h,d,n,e,p);r.action===`cancel`&&(Ge(`Pull cancelled`),process.exit(0)),r.action===`keep-local`&&(y.log(``),y.info(`Keeping local version. No changes made.`),process.exit(0)),r.action===`interactive-cancel`&&process.exit(0),r.action===`interactive`&&(_=r.resolvedContent)}else y.info(`No changes detected in connector configuration.`),process.exit(0)}let ee=at(_).connector,v=ee?.key??f.key,b=ee?.version??p,S=this.#t(r,v,b),C=S;if(S!==m){let e=await this.#n(S);y.log(``),e!==void 0&&(C=e)}await this.#d(C,_),g?y.success(`Connector ${t(v)}@${t(b)} pulled successfully (new connector)`):y.success(`Connector ${t(v)}@${t(b)} updated successfully`);let te=v===f.key?t(v):`${t(f.key)} ${T.whiteBright(`→`)} ${t(v)}`,w=b===p?t(b):`${t(p)} ${T.whiteBright(`→`)} ${t(b)}`,E=C===m?t(C):`${t(m)}\n ${T.whiteBright(`→`)} ${t(C)}`;y.log(`\n${T.blue.inverse(` CONNECTOR DETAILS `)}\n`),y.log(` Provider: ${te}`),y.log(` Version: ${w}`),y.log(` Output file: ${E}`),process.exit(0)}#e(e){let n=at(e),r=n?.errors??[];if(n.success)return n.connector;y.error(`Connector pulled from the registry is not valid`),y.log(`Please make sure you are using the latest version of the StackOne CLI by running ${t(`stackone update`)}`),r.length>0&&x(r,!0),process.exit(1)}#t(e,n,r){let i=`${n}_v${r.replaceAll(`.`,`-`)}.s1.yaml`;return e?(G.existsSync(e)&&(G.statSync(e).isDirectory()||(y.error(`Output path ${t(e)} is not a directory`),y.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),Me.resolve(e,n,i)):Me.resolve(process.cwd(),`connectors`,n,i)}async#n(e){if(!G.existsSync(e))return;let n=Me.basename(e),r=Me.dirname(e);y.warn(`File ${t(n)} already exists at ${t(r)}`);let i=await Ze({message:`How would you like to proceed?`,options:[{value:`override`,label:`Override existing file`,hint:`Replace the existing file with the new content`},{value:`rename`,label:`Save with a different name`,hint:`Provide a new filename for the connector`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if((Je(i)||i===`cancel`)&&(Ge(`Operation cancelled. No local changes were made.`),process.exit(0)),i===`override`)return;let a=await Qe({message:`Enter the new filename:`,placeholder:n,validate:e=>{if(!e||e.trim()===``)return`Filename cannot be empty`;if(!e.endsWith(`.s1.yaml`))return`Filename must end with .s1.yaml`;let t=Me.join(r,e.trim());if(G.existsSync(t))return`File ${e} already exists`}});return Je(a)&&(Ge(`Operation cancelled. No local changes were made.`),process.exit(0)),Me.join(r,a.trim())}#r(e){if(!G.existsSync(e))return null;try{return G.readFileSync(e,`utf-8`)}catch{return null}}#i(e,n){try{let r=at(e);if(!r.success){let e=r.errors??[];return{message:`Local connector ${t(Me.basename(n))} has validation errors:`,errors:e}}}catch(e){return{message:`Local connector ${t(Me.basename(n))} could not be validated: ${e.message}`,errors:[]}}return null}#a(e,t,n){let r=ot(e,t);if(!r.some(e=>e.added||e.removed)){y.info(`No changes detected in connector configuration.`);return}y.log(`${T.blue.inverse(` CHANGES `)}\n`),y.log(T.gray(`--- local: ${n}`)),y.log(T.gray(`+++ remote: StackOne Registry`)),y.log(``);let i=0,a=0;for(let e of r){let t=e.value.split(`
171
+ `).filter(e=>e!==``);if(e.added){i+=t.length;for(let e of t)y.log(T.green(`+ ${e}`))}else if(e.removed){a+=t.length;for(let e of t)y.log(T.red(`- ${e}`))}else if(t.length<=6)for(let e of t)y.log(T.gray(` ${e}`));else{for(let e=0;e<3;e++)y.log(T.gray(` ${t[e]}`));y.log(T.gray(` ... (${t.length-6} unchanged lines)`));for(let e=t.length-3;e<t.length;e++)y.log(T.gray(` ${t[e]}`))}}y.log(``),y.log(T.gray(`Summary: ${T.green(`+${i}`)} additions, ${T.red(`-${a}`)} deletions`))}#o(e,t){return ot(e,t).some(e=>e.added||e.removed)}async#s(e,t,n,r,i){y.log(``);let a=await Ze({message:`How would you like to resolve the differences?`,options:[{value:`override`,label:`Override local with remote`,hint:`Replace your local file with the StackOne version`},{value:`keep-local`,label:`Keep local version`,hint:`Cancel the pull and keep your current file`},{value:`interactive`,label:`Resolve conflicts interactively`,hint:`Choose which changes to accept one by one`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if(Je(a))return{action:`cancel`};if(a===`override`)return{action:`override`};if(a===`keep-local`)return{action:`keep-local`};if(a===`interactive`){let a=await this.#c(e,t,n,r,i);return a===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:a}}return{action:`cancel`}}async#c(e,t,n,r,i){let a=ot(e,t),o=this.#u(a);if(o.length===0)return y.info(`No conflicts to resolve.`),t;let s=new Hr(o,n,r,i);for(;;){if((await s.resolve()).cancelled)return null;let e=s.getResolvedContent(),t=at(e);if(t.success)return s.renderFinalSummary(),e;let n=await this.#l(t.errors);if(n===`cancel`)return v(),y.info(`Operation cancelled. No changes were made to the local connector.`),null;if(n===`save`)return v(),y.warn(`The connector was saved but it is invalid`),e;s.resetForReResolution()}}async#l(e){let{createInterface:t}=await import(`readline`);return new Promise(n=>{v();let r=(e||[{message:`Unknown validation error`}]).map(e=>` • ${e.message}`).join(`
172
+ `);y.box({title:`⚠️ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${r}`,style:{borderColor:`yellow`,padding:1}}),y.log(``),y.log(T.bold(` Choose an action:`)),y.log(``),y.log(T.cyan(` [B]`)+` ← Go back to conflict resolution`),y.log(T.dim(` Modify your choices to fix the validation errors`)),y.log(``),y.log(T.yellow(` [S]`)+` 💾 Save anyway`),y.log(T.dim(` Save the invalid configuration (not recommended)`)),y.log(``),y.log(T.red(` [C]`)+` ✖ Cancel`),y.log(T.dim(` Discard all changes`)),y.log(``);let i=t({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let a=e=>{let t=e.toString().toLowerCase(),r=()=>{process.stdin.removeListener(`data`,a),process.stdin.isTTY&&process.stdin.setRawMode(!1),i.close()};if(t===``||t===`\x1B`){r(),n(`cancel`);return}switch(t){case`b`:r(),n(`back`);break;case`s`:r(),n(`save`);break;case`c`:case`q`:r(),n(`cancel`);break}};process.stdin.on(`data`,a)})}#u(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r.added&&!r.removed)t.push({type:`unchanged`,content:r.value}),n++;else if(r.removed){let i=e[n+1];i?.added?(t.push({type:`conflict`,local:r.value,remote:i.value}),n+=2):(t.push({type:`conflict`,local:r.value,remote:void 0}),n++)}else r.added&&t.push({type:`conflict`,local:void 0,remote:r.value}),n++}return t}async#d(e,n){let r=Me.dirname(e);G.existsSync(r)||G.mkdirSync(r,{recursive:!0});try{G.writeFileSync(e,n,`utf-8`)}catch(n){y.error(`Failed to write connector to file ${t(e)}: ${n.message}`),process.exit(1)}}async#f(e,n,i,a,o){let s=q(`Pulling connector ${t(e)}@${t(a)} from registry...`).start();try{let r=Buffer.from(i).toString(`base64`),c=`${n}/registry/connectors/${e}@${a}${o?`?owner=${encodeURIComponent(o)}`:``}`,l=await fetch(c,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(s.stop(),l.status===409){o&&(await this.#p(l,e,a),process.exit(1));let i=(await l.json()).availableOwners??[],c=await Lr(`${e}@${a}`,i);s.text=`Pulling connector ${t(e)}@${t(a)} from registry...`,s.start();let u=`${n}/registry/connectors/${e}@${a}`,d=await fetch(`${u}?owner=${encodeURIComponent(c)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});return s.stop(),d.ok||(await this.#p(d,e,a),process.exit(1)),await d.text()}return l.ok||(await this.#p(l,e,a),process.exit(1)),await l.text()}catch(i){s.stop(),y.error(`Failed to pull connector ${t(e)}@${t(a)} from the registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid.`),process.exit(1)}}async#p(e,n,r){switch(e.status){case 401:case 403:y.error(`Access denied`),y.log(`Please ensure that your API key is valid and has the ${t(`connectors:read`)} scope required to pull connectors.`);break;case 404:y.error(`Connector ${t(n)}@${t(r)} was not found in the registry`),await this.#m(n);break;case 429:y.error(`Rate limit exceeded`),y.log(`Too many requests. Please wait a moment before trying again.`);break;default:await b(e,`Failed to pull connector ${t(n)}`)}}async#m(e){y.info(`To see available versions, check the connector documentation or contact support.`)}};const Gr=`https://api.stackone.com`;var Kr=class{async execute({profile:e,fileOrDir:n,apiUrl:r,apiKey:i,force:a}={}){if(!e&&!i&&(y.error(`Profile or API key is required`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),e&&i&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&r&&y.warn(`Specifying ${t(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!jr(e)){y.error(`Configuration profile ${t(e)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let n=Nr();n.length>0&&(y.info(`Available configuration profiles:`),n.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let o=e?Ar(e):{apiUrl:r??Gr,apiKey:i};o?.apiKey||(y.error(`API key is missing`),y.log(`Please provide a valid API key in the profile or via the ${t(`--api-key`)} option.`),process.exit(1)),n||(y.error(`File or directory is required.`),process.exit(1));try{K(n)}catch{y.error(`File or directory not found: ${T.red(n)}`),process.exit(1)}let s=K(n),c=o.apiUrl??Gr;if(s.isDirectory()){let e=$r(n),t=0;e.length===0?(y.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(y.start(`Found ${e.length} connector(s) file(s). Pushing to registry...`),y.log(``));for(let n of e)await this.uploadFile(n,c,o.apiKey,a)&&t++;t===0?y.error(`Error while pushing connectors: no files were uploaded`):(y.log(``),y.info(`Upload completed: ${T.green(t)} of ${T.blue(e.length)} file(s) uploaded successfully.`)),process.exit(t>0?0:1)}else n.endsWith(`.s1.yaml`)||(y.error(`Only ${t(`.s1.yaml`)} files are supported for upload`),process.exit(1));let l=await this.uploadFile(n,c,o.apiKey,a);process.exit(l?0:1)}async uploadFile(e,n,i,a){let o=q(`📤 Pushing connector in ${Ne(e)}...`).start();try{let r=Qr(e);if(!r)return!1;let s=Ne(e),c=new FormData,l=new Blob([r],{type:`application/x-yaml`});c.append(`file`,l,s),a&&c.append(`force`,`true`);let u=Buffer.from(i).toString(`base64`),d=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${u}`},body:c});if(o.stop(),!d.ok)return d.status===409||d.status===422?await this.handleVersionConflict(d,e,n,i,a):(await b(d,`Failed to push connector in ${t(s)} to the registry`),!1);let f=await d.json();return y.success(`Successfully uploaded ${t(s)} with connector ${t(f.provider)}@${t(f.version)}`),!0}catch(i){return o.stop(),y.error(`Failed to upload file ${t(e)}: ${i}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),!1}}async handleVersionConflict(e,n,r,i,a){let o=qr(e.status,a);o&&y.warn(o);let s=await e.text(),c;try{c=JSON.parse(s)}catch{}let l=dt.valid(c?.latestVersion);if(!l)return await b(new Response(s,{status:e.status,statusText:e.statusText}),`Failed to push connector in ${t(Ne(n))} to the registry`),!1;let u=ke(n,`utf-8`),d=Jr(u),f=d?`${t(d)}`:``,p=e.status===409?`Version ${f} already exists in the registry. Latest version: ${t(l)}`:`Version ${f} is lower than the latest version in the registry. Latest version: ${t(l)}`;y.error(p);let m=dt.inc(l,`patch`)??l,h=dt.inc(l,`minor`)??l,g=dt.inc(l,`major`)??l,_=await Ze({message:`How would you like to proceed?`,options:[{value:m,label:`Bump patch version (${m})`},{value:h,label:`Bump minor version (${h})`},{value:g,label:`Bump major version (${g})`},{value:`cancel`,label:`Cancel push`}]});return Je(_)||_===`cancel`?(Ge(`Push cancelled`),!1):(je(n,Yr(u,_),`utf-8`),y.info(`Updated version to ${t(_)} in ${Ne(n)}`),this.uploadFile(n,r,i,a))}};const qr=(e,n)=>!n||e!==409?null:`${t(`--force`)} was ignored because Immutable Versioning is enabled for this project, so a published connector version cannot be overwritten. Push a new version, or turn Immutable Versioning off in the project settings.`,Jr=e=>e.match(/^\s*version: (\S+)/m)?.[1],Yr=(e,t)=>e.replace(/^(\s*version: )\S+/m,`$1${t}`),Xr=e=>{try{let t=rt(e);return t.changelog?.summary?.trim()?null:`has no changelog entry for version ${t.version}`}catch{return null}},Zr=()=>{y.log(`Every published version must record what changed. Add an ${t(`info.changelog`)} block:`),y.log(``),y.log(T.gray(` info:`)),y.log(T.gray(` changelog:`)),y.log(T.gray(` summary: What changed in this version.`)),y.log(T.gray(` labels: [new-actions] # optional, one of: ${ct.join(`, `)}`)),y.log(``)},Qr=e=>{let t=nt(e),r=at(t),i=r?.errors??[];if(r.success){let r=Xr(t);if(r){y.error(`Connector in ${n(e)} ${r}`),Zr();return}return t}else i.length>0?(y.error(`Connector in ${n(e)} is not valid`),x(i,!0)):y.error(`Connector in ${n(e)} is not valid. Please check the file for errors.`)},$r=e=>{let t=[],n=Ae(e,{withFileTypes:!0});for(let r of n){let n=Fe(e,r.name);r.isDirectory()?t.push(...$r(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},ei=(e,t)=>{if(!e)return{ok:!1,reason:`Action has no pagination config, so there is no page size to override.`};switch(e.type){case`page`:return e.iterator.pageSizeKey?{ok:!0,pagination:{...e,iterator:{...e.iterator,defaultPageSize:t}}}:{ok:!1,reason:`Pagination declares no pageSizeKey, so the provider's page size cannot be set. Add dataSync.pagination.iterator.pageSizeKey, or use --params if the provider takes its page size as a regular action input.`};case`offset`:return{ok:!0,pagination:{...e,iterator:{...e.iterator,defaultLimit:t}}};case`cursor`:return{ok:!1,reason:`Cursor pagination has no page size key to override — the strategy only ever sets the cursor. If the provider takes a page size (GraphQL "first", for example), it is an ordinary action input: pass it with --params, which the paginator preserves across pages.`}}},ti=e=>({path:e.path,query:e.queryParams,headers:e.header,body:e.body}),ni=e=>({pathParams:e.path??{},queryParams:e.query??{},headers:e.headers??{},body:e.body??{}}),ri=(e,t)=>{switch(e.type){case`time_filter`:return{kind:`timestamp`,value:t};case`delta_token`:return{kind:`cursor`,value:t}}},ii=(e,t,n)=>{let{in:r,key:i}=e.iterator;return ai(n[r])[i]===t.value},ai=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},oi=2e3;var si=class extends Error{constructor(e){super(`Action failed on page ${e.iteration}: ${e.statusCode??`unknown`} ${e.providerMessage??`no response`}`.trim()),this.name=`SyncPageError`,this.iteration=e.iteration,this.statusCode=e.statusCode,this.providerMessage=e.providerMessage,this.providerData=e.providerData,this.inputs=e.inputs,this.pagesCompleted=e.pagesCompleted,this.recordsCollected=e.recordsCollected}};const ci=async({dataSyncConfig:e,baseInputs:t,checkpointIn:n,callAction:r,maxPages:i,runStartTime:a,onPage:o})=>{let s=e.incremental?$e(e.incremental):null,c=s?s.applyToInputs({baseInputs:t,checkpoint:n}):t,l=e.incremental&&n?ii(e.incremental,n,c):null,u=e.pagination?et(e.pagination,{baseInputs:c}):null,d=Math.min(i,oi),f=[],p=[],m=[],h=null,g=0,_=null,ee=e=>({items:f,pages:p,pagesRetrieved:g,stoppedBy:e,extractedCheckpoints:m,checkpointOut:e===`exhausted`&&s?s.finalizeCheckpoint({runStartTime:a,extractedCheckpoints:m}):null,checkpointApplied:l});for(;;){if(g>=d)return ee(`maxIterations`);let t=h??u?.computeNextInputs({previousResponse:void 0,currentIteration:g})??c,n=await r(t);if(g++,n.response?.successful!==!0)throw new si({iteration:g,statusCode:n.response?.statusCode,providerMessage:n.response?.message,providerData:n.response?.data,inputs:t,pagesCompleted:g-1,recordsCollected:f.length});let i=tt(n,e),a=Ue(i),l=u?u.isExhausted(n,g):!0,v=s?.extractFromPage({block:n,items:i,isFinalPage:l})??null,y={iteration:g,inputs:t,itemCount:i.length,statusCode:n.response?.statusCode,exhausted:l,extractedCheckpoint:v};if(p.push(y),o?.(y),v){let e=m.findIndex(e=>e.kind===v.kind&&e.value===v.value);e!==-1&&m.splice(e,1),m.push(v)}if(_!==null&&a===_)return ee(`duplicatePage`);if(f.push(...i),_=a,l)return ee(`exhausted`);h=u?.computeNextInputs({previousResponse:n,currentIteration:g})}},li=(e,t)=>{let n=e.dataSync;return n?n.allowed===!0?t===`incremental`&&!n.incremental?{ok:!1,reason:`Action does not support incremental syncs: no dataSync.incremental block`}:{ok:!0,dataSyncConfig:n}:{ok:!1,reason:`Action data sync is not enabled: dataSync.allowed is false`}:{ok:!1,reason:`Action does not support data sync: no dataSync block`}},ui=(e,t)=>Math.min(t??e.maxPages??oi,oi),di=async({dataSyncConfig:e,mode:t,checkpointValue:n,baseInputs:r,callAction:i,maxPages:a,now:o,onPage:s})=>{let c=async(t,n)=>({mode:t,checkpointIn:n,...await ci({dataSyncConfig:e,baseInputs:r,checkpointIn:n,callAction:i,maxPages:a,runStartTime:o(),onPage:s&&(e=>s(e,t))})});if(t===`full`)return{phases:[await c(`full`,null)]};if(n!==void 0&&e.incremental)return{phases:[await c(`incremental`,ri(e.incremental,n))]};let l=await c(`full`,null);return l.checkpointOut?{phases:[l,await c(`incremental`,l.checkpointOut)]}:{phases:[l],skipped:`no checkpoint produced by the full phase`}},fi=({actionId:e,connector:t,dataSyncConfig:n,result:r,warnings:i,includePages:a})=>{let o=r.phases.find(e=>e.items.length>0)?.items[0];return{actionId:e,connector:t,dataSyncConfigFingerprint:lt(n),phases:r.phases.map(e=>({mode:e.mode,pagesRetrieved:e.pagesRetrieved,records:e.items.length,stoppedBy:e.stoppedBy,checkpointIn:e.checkpointIn,checkpointOut:e.checkpointOut,checkpointApplied:e.checkpointApplied,...a?{pages:e.pages.map(e=>({iteration:e.iteration,inputs:e.inputs,itemCount:e.itemCount,statusCode:e.statusCode,exhausted:e.exhausted}))}:{}})),...r.skipped?{incrementalPhaseSkipped:r.skipped}:{},...o?{sampleRecord:o}:{},warnings:i}},pi=(e,t)=>{let n=[],{incremental:r}=t;for(let r of e.phases)n.push(...mi(r,t));let i=e.phases.some(e=>e.stoppedBy===`exhausted`&&e.checkpointOut===null);r?.type===`delta_token`&&i&&n.push(`The run reached the end of the data but produced no delta token, so production would abandon every following incremental fire ("no checkpoint to resume from"). Check dataSync.incremental.response.path (${r.response.path})${r.response.onlyOnFinalPage?` — it is only read on the final page`:``}.`);let a=e.phases.find(e=>e.mode===`full`),o=e.phases.find(e=>e.mode===`incremental`);return a&&o&&o.checkpointApplied===!0&&o.items.length>=a.items.length&&n.push(`The incremental phase did not narrow the result set (${a.items.length} records full vs ${o.items.length} incremental). Verify the provider honours ${gi(t)}; every sync will refetch the whole dataset if it does not.`),n},mi=(e,t)=>{let n=[],{incremental:r}=t;return e.checkpointApplied===!1&&n.push(`The ${e.mode} phase checkpoint (kind "${e.checkpointIn?.kind}") was ignored by the ${r?.type} strategy, so this run fetched an unfiltered dataset. It reports success but proves nothing about incremental behaviour.`),e.stoppedBy===`maxIterations`&&n.push(`The ${e.mode} phase was truncated at the ${e.pagesRetrieved}-page cap before exhausting the provider, so no checkpoint was produced. Production withholds a truncated run's checkpoint for the same reason.`),e.stoppedBy===`duplicatePage`&&n.push(`The ${e.mode} phase stopped after two identical consecutive pages, which means the iterator is not reaching the provider. A declared input alone is not enough — the request step must forward it via args (value: $.inputs.${t.pagination?hi(t):`cursor`}). Connector validation cannot catch this.`),r?.type===`time_filter`&&r.response?.updatedAtPath&&e.items.length>0&&e.extractedCheckpoints.length===0&&n.push(`dataSync.incremental.response.updatedAtPath (${r.response.updatedAtPath}) resolved on no record in the ${e.mode} phase, so the watermark fell back to this machine's clock minus ${r.safetyBufferSeconds??60}s. Records changed during the run can be missed.`),n},hi=e=>{let t=e.pagination;if(!t)return`cursor`;switch(t.type){case`cursor`:return t.iterator.key;case`offset`:return t.iterator.offsetKey;case`page`:return t.iterator.pageKey}},gi=e=>{let{incremental:t}=e;return t?`${t.iterator.key} in ${t.iterator.in}`:`the incremental iterator`},_i=X.object({provider_key:X.string().optional(),provider_version:X.string().optional(),auth_config_key:X.string(),environment:X.string().default(`production`),organization_id:X.string().default(`cli-organization-id`),account_id:X.string().default(`cli-account-secure-id`),project_id:X.string().default(`cli-project-secure-id`),credentials:X.record(X.string(),X.any()).default({})}),vi=X.record(X.string(),X.any()),yi=X.object({path:X.record(X.string(),X.any()).default({}),queryParams:X.record(X.string(),X.any()).default({}),header:X.record(X.string(),X.any()).default({}),body:X.record(X.string(),X.any()).default({})}),bi=`https://api.stackone.com`;var xi=class{async execute({connector:e,action:n,actionId:r,account:i,accountId:a,params:s,credentials:c,profile:l,outputFile:u,debug:d,apiUrl:f,apiKey:p,owner:m,syncFull:h,syncIncremental:g,syncMaxPages:_,syncPageSize:ee}={}){if(!l&&!p&&a&&(y.error(`Profile or API key is required when providing an account ID`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`To create a profile, run ${t(`stackone init`)}.`),process.exit(1)),l&&p&&(y.error(`Please provide either a profile or an API key, not both`),process.exit(1)),l&&f&&y.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),l&&!jr(l)){y.error(`Configuration profile ${t(l)} not found`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.\n`);let e=Nr();e.length>0&&(y.info(`Available configuration profiles:`),e.forEach(e=>{y.log(` - ${T.blue(e)}`)})),process.exit(1)}let v=l?Ar(l):{apiUrl:f??bi,apiKey:p};J(i)&&J(a)&&(y.error(`A valid account or account ID is required to run an action`),process.exit(1));let b;if(Y(e))if(this.#s(e)){!l&&!p&&(y.error(`Profile or API key is required when using a connector identifier`),y.log(`Please provide a profile using the ${t(`--profile`)} option or an API key using the ${t(`--api-key`)} option.`),y.log(`Run ${t(`stackone init`)} to create a new configuration profile.`),process.exit(1));let n=this.#c(e);b=await this.#l(n,v?.apiUrl??bi,v?.apiKey,m)}else b=this.#n(e);else Y(a)&&(b=await this.#u(a,v?.apiUrl??bi,v?.apiKey));let x=Y(n)?this.#a(n,e):b;J(x)&&(y.error(`A valid connector is required to run an action.`),process.exit(1));let S=Y(x?.actions)?Object.keys(x?.actions).length:0,C=Y(x?.actions)?Object.keys(x.actions)[S-1]:void 0,te=Y(C)?x?.actions?.[C]?.id:void 0,w=(Y(r)&&!r?.startsWith(`${x.key}_`)?`${x.key}_${r}`:r)??te;J(w)&&(y.error(`A valid action ID is required to run an action`),process.exit(1));let E=Y(a)?await this.#d(a,v?.apiUrl??bi,v?.apiKey):{},ne=Y(i)?this.#o(i,x.key??`unknown`,x.version??`unknown`):void 0,D=Y(c)?this.#f(c):{},re={...E,...ne,credentials:{...E.credentials??{},...D}};J(re)&&(y.error(`A valid account data is required to run an action.`),process.exit(1));let ie=x.actions?.[w];J(ie)&&(y.error(`Action ID ${t(w)} not found in the connector ${t(x.key)}@${t(x.version)}.`),process.exit(1));let O=Y(s)?this.#p(s,w):{path:{},queryParams:{},header:{},body:{}};if(h||g!==void 0)return this.#e({connector:x,actionId:w,action:ie,account:re,baseInputs:ti(O),mode:h?`full`:`incremental`,checkpointValue:typeof g==`string`&&g!==``?g:void 0,maxPagesOverride:_,pageSizeOverride:ee,outputFile:u,debug:d});let k=Date.now(),ae=await this.#m({connector:x,actionId:w,account:re,queryParams:{...O.queryParams,...d?{debug:`true`}:{}},pathParams:O.path,body:O.body,headers:O.header}),oe=Date.now()-k;if(Y(u))try{G.writeFileSync(u,JSON.stringify(ae.output,null,2),`utf-8`),y.info(`Output written to file: ${u}`)}catch(e){y.error(`Failed to write output to file ${u}: ${e.message}`),process.exit(1)}else y.log(`\n${T.blue.inverse(` ACTION OUTPUT `)}`),o(ae.output);y.log(``),y.info(`Action ${t(w)} from connector ${t(x?.key)}@${t(x?.version)} finished in ${T.yellowBright((oe/1e3).toFixed(2))} seconds.`),process.exit(0)}async#e({connector:e,actionId:n,action:r,account:i,baseInputs:a,mode:s,checkpointValue:c,maxPagesOverride:l,pageSizeOverride:u,outputFile:d,debug:f}){let p=li(r,s);p.ok||(y.error(p.reason),process.exit(1));let{dataSyncConfig:m}=p;if(Y(u)){let e=ei(m.pagination,u);e.ok||(y.error(`Cannot override the page size: ${e.reason}`),process.exit(1)),m={...m,pagination:e.pagination}}let h=ui(m,l);y.info(`Data sync ${t(s)} run of ${t(n)} — pagination ${t(m.pagination?.type??`none`)}${Y(u)?` (page size ${t(String(u))})`:``}, incremental ${t(m.incremental?.type??`none`)}, page cap ${t(String(h))}`);let g=Date.now(),_,ee=new ft;try{_=await di({dataSyncConfig:m,mode:s,checkpointValue:c,baseInputs:a,maxPages:h,now:()=>new Date,callAction:async t=>it({mode:`action_id`,actionId:n,account:i,connector:e,...ni(t),getHttpClient:async()=>ee}),onPage:(e,t)=>{y.log(` ${T.gray(t)} page ${T.yellowBright(e.iteration)} — ${T.green(e.itemCount)} records${e.exhausted?T.gray(` (last)`):``}`)}})}catch(e){e instanceof si&&this.#t(e,m),this.#g(e)}let v=(Date.now()-g)/1e3,b=pi(_,m),x={actionId:n,connector:`${e.key}@${e.version}`,dataSyncConfig:m,result:_,warnings:b};if(y.log(`\n${T.blue.inverse(` DATA SYNC SUMMARY `)}`),o(fi({...x,includePages:f===!0})),Y(d))try{G.writeFileSync(d,JSON.stringify({...fi({...x,includePages:!0}),records:_.phases.map(e=>e.items)},null,2),`utf-8`),y.info(`Records and summary written to file: ${d}`)}catch(e){y.error(`Failed to write output to file ${d}: ${e.message}`),process.exit(1)}b.length>0&&(y.log(`${T.yellow.inverse(` WARNINGS `)}`),b.forEach(e=>y.warn(e))),y.log(``),y.info(`Data sync ${t(s)} run finished in ${T.yellowBright(v.toFixed(2))} seconds. Nothing was indexed.`);let S=_.phases.some(e=>e.checkpointApplied===!1)||_.phases.some(e=>e.stoppedBy===`duplicatePage`);process.exit(S?1:0)}#t(e,n){if(y.error(`Data sync failed on page ${t(String(e.iteration))} — ${r(String(e.statusCode??`unknown`))} ${e.providerMessage??``}`.trim()),y.log(`${e.pagesCompleted} page(s) and ${e.recordsCollected} record(s) succeeded before this one.\n`),Y(e.providerData)&&(y.log(`${T.red.inverse(` PROVIDER ERROR `)}`),o(e.providerData),y.log(``)),y.log(`${T.yellow.inverse(` REQUEST THAT FAILED `)}`),o(e.inputs),e.iteration>1&&Y(n.pagination)){let{pagination:r}=n;y.log(``),y.info(`Page 1 succeeded and page ${e.iteration} did not, so the ${t(r.type)} iterator is the first thing to check: the value above under ${t(ut(r)??`query`)} is what the provider rejected. A provider that requires a page-size argument alongside the cursor needs it supplied via ${t(`--params`)}, since the iterator only sets the cursor itself.`)}process.exit(1)}#n=e=>{let t=e;try{t=nt(e)}catch{}return t?this.#i(t):void 0};#r=e=>{try{return nt(e)}catch(n){y.error(`Failed to load connector file from ${t(e)}: ${n.message}`),process.exit(1)}};#i=e=>{let t=at(e),n=t?.errors??[];if(t.success)return t.connector||(y.error(`Failed to load connector.`),process.exit(1)),t.connector;n.length>0?(y.error(`Connector is not valid`),x(n,!0),process.exit(1)):(y.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#a=(e,t)=>{let n=e;try{n=G.readFileSync(e,`utf-8`)}catch{}J(t)&&(y.error(`A valid connector is required to load an action.`),process.exit(1));let r=`${this.#r(t)} - ${n.split(`
173
173
  `).map((e,t)=>t===0?e:` ${e}`).join(`
174
- `)}`;return this.#n(r)};#i=(e,t,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{let e=Jr.parse(JSON.parse(r));return{providerKey:t,providerVersion:n,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse account information`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#a=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#o=e=>e.includes(`@`)?e:`${e}@latest`;#s=async(e,n,i,a)=>{(J(e)||J(n)||J(i))&&(y.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let o=q();try{o.text=`Fetching connector ${t(e)} from registry...`,o.start();let r=Buffer.from(i).toString(`base64`),s=a?`?owner=${encodeURIComponent(a)}`:``,c=await fetch(`${n}/registry/connectors/${e}${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(o.stop(),c.status===409){a&&(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let i=await jr(e,(await c.json()).availableOwners??[]);o.text=`Fetching connector ${t(e)} from registry...`,o.start();let s=await fetch(`${n}/registry/connectors/${e}?owner=${encodeURIComponent(i)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});o.stop(),s.ok||(await b(s,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await s.text(),u=this.#n(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}c.ok||(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await c.text(),u=this.#n(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}catch(i){o.stop(),y.error(`Failed to fetch connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#c=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let a=q();try{a.text=`Fetching connector for account ${t(e)} from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/connector`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch connector`),process.exit(1));let s=await o.text(),c=this.#n(s);return y.success(`Fetched connector ${t(c.key)}@${t(c.version)} for account ${t(e)}`),c}catch(e){a.stop(),y.error(`Failed to fetch connector: ${e.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#l=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let a=q();try{a.text=`Fetching account ${t(e)} information from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch account ${t(e)} information`),process.exit(1));let s=await o.json();return y.success(`Fetched account ${t(e)} information from project ${t(s.project_id)}`),{providerKey:s.provider_key,providerVersion:s.provider_version,authConfigKey:s.auth_config_key,environment:s.environment,organizationId:s.organization_id,secureId:s.account_id,projectSecureId:s.project_id,credentials:s.credentials}}catch(i){a.stop(),y.error(`Failed to fetch account ${t(e)} information: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#u=e=>{let t=e;try{t=G.readFileSync(e,`utf-8`)}catch{}try{return Yr.parse(JSON.parse(t))}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse credentials`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#d=(e,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{return Xr.parse(JSON.parse(r))}catch(e){let r=[];try{r=JSON.parse(e.message)}catch{}y.error(`Invalid parameters for action ${t(n)}.`),x(r,!1),r.length===0&&y.log(e.message),process.exit(1)}};async#f({connector:e,actionId:n,account:r,pathParams:i={},queryParams:a={},body:s={},headers:c={}}){try{let l=await et({mode:`action_id`,actionId:n,account:r,connector:e,pathParams:i,queryParams:a,body:s,headers:c,getHttpClient:async()=>new ot});if(l.response?.successful){let e={...this.#p(a,l.steps),...Ue(l.outputs)?l.outputs:{data:l.outputs}};return{statusCode:l.response?.statusCode,output:e}}else{let r=l.response?.message??`An error occurred while processing the request`;y.error(`Action ID ${t(n)} from connector ${t(e.key)}@${t(e.version)} failed with status ${l.response?.statusCode}: ${r}`);let i={...this.#p(a,l.steps)};Object.keys(i).length>0&&(y.log(`${T.yellow.inverse(` EXECUTION DETAILS `)}`),o(i)),process.exit(1)}}catch(e){this.#m(e)}}#p(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#m(e){let t=e;switch(J(t.errorType)&&(y.error(`An unknown error occurred`),y.log(`${e instanceof Error?e.message:String(e)}`),process.exit(1)),t.errorType){case`MISSING_ACTION_ERROR`:y.error(`The specified action was not found: ${t.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let e=t;y.error(`Invalid action inputs`),x(e.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:y.error(`Invalid cursor: ${t.message}`);break;default:y.error(`An error occurred: ${t.message}`)}process.exit(1)}};const $r=st(we);var ei=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=q(),this.currentVersion=qt()}async execute(e={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let t=await this.getLatestVersion();this.spinner.stop(),t||(y.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(t,this.currentVersion)?(y.box(`New version available: ${T.yellow(this.currentVersion)} → ${T.green(t)}`),await this.performUpdate(t)):e.force?(y.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(t)):y.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(e){this.spinner.stop(),y.error(`Error while trying to update StackOne CLI: ${e?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await $r(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return at.gt(e,t)}async performUpdate(e){this.spinner.text=`Updating to latest version (${t(e)})...`,this.spinner.start();let n=`npm install -g ${this.packageName}@latest`;try{await $r(n,{encoding:`utf-8`}),this.spinner.stop(),y.success(`StackOne CLI updated successfully to latest version (${t(e)})`)}catch{throw this.spinner.stop(),Error(`Failed to install update. Please try manually: ${n}`)}}};const ti=e=>e===null?!0:Object.values(e).some(e=>e!==null),ni=()=>{y.log(`${T.gray.inverse(` CONNECTORS VALIDATION `)} ${T.yellow.inverse(` WATCH MODE `)}\n`)};var ri=class{async execute(e){let{watchMode:t,fileOrDir:n}=e,r=q(`Watching for file changes... ${T.gray(`(press "q" to quit)`)}`);if(!n)return;let i=Ie(n);try{await lt(i)}catch{y.error(`The specified path does not exist: ${i}\n`),process.exit(1)}if(t){v();let e={},{watch:t}=await import(`chokidar`),n=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let a=()=>{s.close(),r.stop(),n.close(),y.log(T.grey(`
175
- Exiting watch mode...`)),process.exit(0)};ni(),y.start(`Validating connectors...`);let o=await si(i);e=ii(e,o||{}),ai(e,i),r.start();let s=t(i,{persistent:!0,ignoreInitial:!0}),c=async t=>{if(!t.endsWith(`.s1.yaml`)&&!t.endsWith(`s1.partial.yaml`))return;let n=t.endsWith(`s1.partial.yaml`)?await li(t):[t];if(!(!n||n.length===0)){v(),r.stop(),ni(),y.log(T.gray(`File change detected: ${t}`)),y.start(`Validating connectors...`);for(let t of n){let n=await si(t);e=ii(e,n||{})}ai(e,i),r.start()}};s.on(`change`,async e=>await c(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&a()}),process.on(`SIGINT`,()=>{a()})}else{let e=await si(i,y);process.exit(ti(e)?1:0)}}};const ii=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},ai=(e,n)=>{v(),ni();let r=0,i=0;for(let[n,a]of Object.entries(e))a===null?r++:(y?.error(`Connector ${t(n)} is not valid`),x(a,!0),i++);y.log(``),y.log(T.blue.inverse(` Validation Summary `)),y.log(`Connectors path: ${t(n)}`),y.log(`${r===0?T.red(`0`):T.green(r)} valid, ${i===0?T.green(`0`):T.red(i)} invalid connectors\n`)},oi=async e=>{let t=[],n=await ct(e);for(let r of n){let n=Fe(e,r),i=await lt(n);i.isDirectory()?t.push(...await oi(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},si=async(e,r)=>{let i=await lt(e),a={};if(i.isDirectory()){let i=await oi(e);if(i.length===0)return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null;let o=0,s=0;for(let e of i){let t=await ci(e,r);t===null?o++:(r?.log(``),s++),a[e]=t}return r?.log(``),r?.log(T.blue.inverse(` Validation Summary `)),r?.log(`${o===0?T.red(`0`):T.green(o)} valid, ${s===0?T.green(`0`):T.red(s)} invalid connectors`),a}else if(i.isFile()&&e.endsWith(`s1.yaml`))return a[e]=await ci(e,r),a;else if(i.isFile()&&e.endsWith(`partial.yaml`)){r?.error(`Partial connector files cannot be validated directly`),r?.log(`The file ${n(e)} is a partial connector file.`);let i=await li(e);return i&&i?.length>0&&r?.log(`Did you mean ${t(i[0])}?`),null}else return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null},ci=async(e,n)=>{let r=tt(Qe(e)),i=r?.errors??[];if(r.success){let r=e.split(`/`).pop()||e;return n?.success(`Connector ${t(r)} is valid!`),null}else if(i.length>0)return n?.error(`Connector ${t(e)} is not valid`),n&&x(i,!0),i;else return n?.error(`Connector ${t(e)} is not valid. Please check the file for errors`),[]},li=async e=>{let t=Pe(e);try{return(await ct(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>Fe(t,e))}catch{}};function ui(e){if(!e)return!1;try{let{hostname:t}=new URL(e);return t===`stackone-dev.com`||t.endsWith(`.stackone-dev.com`)}catch{return!1}}function di(){return process.env.AI_TELEMETRY_URL?process.env.AI_TELEMETRY_URL:[process.env.AUTH_SERVER_URL,process.env.STACKONE_API_URL].some(ui)?`https://ai-telemetry.stackone-dev.com`:`https://ai-telemetry.stackone.com`}function fi(){let e=process.env.STACKONE_AGENT_TOKEN,t=process.env.LANGSMITH_PROJECT||`stackone-agent-cli`;if(process.env.AI_TELEMETRY_URL=di(),e)try{ce({apiKey:e,projectName:t}),process.env.VERBOSE&&console.log(`[Telemetry] Initialized for project:`,t)}catch(e){process.env.VERBOSE&&console.error(`[Telemetry] Failed to initialize:`,e)}}const pi=R(I(),`.stackone`),mi=R(pi,`version-check.json`),hi=(e=!1)=>{let t=yi(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=gi();e&&_i(e)&&vi(e),bi({lastCheckTime:n})}},gi=()=>{try{return De(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},_i=e=>{try{let t=qt();return at.gt(e,t)}catch{return!1}},vi=e=>{let t=qt(),n=`Update available: ${T.dim(t)} → ${T.green(e)}`,r=`\n\nRun ${T.cyan(`stackone update`)} to update`;y.box(n,r)},yi=()=>{try{if(!N(mi))return null;let e=de(mi,`utf-8`);return JSON.parse(e)}catch{return null}},bi=e=>{try{N(pi)||ue(pi,{recursive:!0}),me(mi,JSON.stringify(e,null,2),`utf-8`)}catch{}};var xi=class{constructor(e=new ne,t=qt()){this.program=e,this.version=t,fi(),this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let e=new Fr,t=new Br,n=new Rr,r=new kr,i=new Nr,a=new ri,o=new Sn,s=new gr,c=new on,l=new an,u=new wn,d=new _r,f=new xr,p=new Qr,m=new ei;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(T.red(e))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(t=>{e.execute({environment:t.env})}),this.program.command(`push`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`--force`,`Force push the connector, bypassing version conflict checks`).addArgument(new E(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,n)=>{t.execute({profile:n.profile,fileOrDir:e,apiUrl:n.apiUrl,apiKey:n.apiKey,force:n.force})}),this.program.command(`drop`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new E(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{r.execute({profile:t.profile,connector:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`get`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key (defaults to latest)`).option(`--account-id <account-id>`,`Account ID to fetch connector from`).option(`-f, --format <format>`,`Output format: yaml or json (default: yaml)`,`yaml`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Get a connector from the StackOne registry`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),i.execute({profile:e.profile,connector:e.connector,accountId:e.accountId,format:e.format,outputFile:e.outputFile,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`pull`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output <path>`,`Output directory for the connectors files (default: ./connectors)`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Pull a connector configuration from StackOne registry to local filesystem`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),n.execute({profile:e.profile,connector:e.connector,outputPath:e.output,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new E(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{a.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`run`).option(`--connector <connector>`,`Connector file, inline YAML, or identifier (provider_key@version or provider_key for latest)`).option(`--action <action>`,`Action to execute on the connector (path to file or inline string action code)`).option(`--action-id <action-id>`,`Action ID to execute on the connector`).option(`--account <account>`,`Account details to use for running the connector (path to file or inline string account data)`).option(`--account-id <account-id>`,`Account ID to use for running the connector against (fetches connector from API if --connector not provided)`).option(`--params <params>`,`Action parameters (path to file or inline string with JSON parameters)`).option(`--credentials <credentials>`,`Credentials to use (path to file or inline string with JSON credentials)`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`-d, --debug`,`Enables debug mode to include more details in the action execution output`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Run a connector action`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),p.execute({connector:e.connector,action:e.action,actionId:e.actionId,account:e.account,accountId:e.accountId,params:e.params,credentials:e.credentials,profile:e.profile,outputFile:e.outputFile,debug:e.debug,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})});let h=this.program.command(`agent`).description(`StackOne agent commands`);h.command(`setup`).option(`-g, --global`,`Global only: auth + MCP server (no connector skills/guide)`).option(`-l, --local`,`Local: auth + .mcp.json + connector skills (.claude/) and guide (CLAUDE.md)`).option(`--path <dir>`,`Target project path for local setup (defaults to the current directory)`).option(`--legacy`,`Use email/password login instead of browser-based auth`).option(`--email <email>`,`Email for legacy login (or set STACKONE_EMAIL); requires --legacy`).option(`--password <password>`,`Password for legacy login (or set STACKONE_PASSWORD); requires --legacy. Prefer --password-stdin`).option(`--password-stdin`,`Read password for legacy login from stdin; requires --legacy`).description(`Set up the StackOne agent — prompts for global vs local when neither flag is given`).action(async e=>{e.global&&e.local&&(y.error(`--global and --local are mutually exclusive. Please provide only one.`),process.exit(1));let t=e.email!==void 0,n=e.password!==void 0,r=e.passwordStdin===!0;n&&r&&(y.error(`--password and --password-stdin are mutually exclusive. Please provide only one.`),process.exit(1));let i=t||n||r;i&&!e.legacy&&(y.error(`--email, --password, and --password-stdin require --legacy.`),process.exit(1)),t&&e.email.trim()===``&&(y.error(`--email cannot be empty.`),process.exit(1)),n&&e.password===``&&(y.error(`--password cannot be empty.`),process.exit(1)),r&&(t||process.env.STACKONE_EMAIL?.trim()||(y.error(`--password-stdin requires --email or STACKONE_EMAIL (stdin is consumed for the password, so email cannot be prompted).`),process.exit(1)));let a={email:e.email,password:e.password,passwordFromStdin:r},c=!!process.stdin.isTTY;if(c&&!e.legacy&&!i){let t=await hr({initialMode:e.global?`global`:e.local?`local`:null,pathFlag:e.path});process.exit(t.status===`error`?1:0)}let l=c&&!i;!e.global&&!e.local&&!l&&y.log(T.dim(`No interactive terminal detected — defaulting to global setup. Run in a terminal for the prompt, or pass --local (with --path) / --global.`));let u=On(e.global,e.local,l);if(u===null&&(u=await fr()),u===`local`){let t=kn(e.path,l);t===null&&(t=await mr(process.cwd())),await s.execute({legacy:!!e.legacy,credentials:a,targetPath:t})}else await o.execute({legacy:!!e.legacy,credentials:a})}),h.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{c.execute()}),h.command(`run`).description(`Run the agent once with a prompt (non-interactive)`).argument(`<prompt>`,`What to do`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`--max-turns <n>`,`Max agent turns`,`25`).option(`-v, --verbose`,`Verbose output`).action(async(e,t)=>{let n=[`build`,`test`,`research`],r=t.mode??`build`;n.includes(r)||(y.error(`${T.red(`Invalid mode:`)} ${T.white(r)}. Valid modes are: ${n.join(`, `)}.`),process.exit(1));let i=t.maxTurns?parseInt(String(t.maxTurns),10):void 0;await u.execute({prompt:String(e),mode:r,maxTurns:i!==void 0&&!isNaN(i)?i:void 0,verbose:t.verbose})}),h.command(`skills`).description(`List available agent skills and optional recommendations by mode`).option(`-m, --mode <mode>`,`Show skills recommended for this mode`).action(async e=>{await d.execute({mode:e.mode})}),h.command(`sync`).description(`Sync the connector-building skills + guide into this project (.claude/ + CLAUDE.md)`).option(`--check`,`Report drift and exit non-zero instead of writing (CI guard)`).option(`--plugin-dir <path>`,`Override the agent-harness plugin dir (e.g. point at a checkout in CI/benchmarks)`).action(async e=>{await f.execute({check:!!e.check,pluginDir:e.pluginDir})}),h.command(`chat`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`-c, --connector <name>`,`Connector name`).option(`-a, --action <name>`,`Action name`).option(`-g, --goal <goal>`,`Initial goal/message`).option(`-t, --temperature <number>`,`Temperature (0-1, default: 0.5)`,parseFloat).option(`-v, --verbose`,`Enable verbose logging`).description(`Start an interactive chat session with the agent (use /commands in chat)`).action(async e=>{let t=[`build`,`test`,`research`];e.mode&&!t.includes(e.mode)&&(y.error(`❌ Error: Invalid mode "${e.mode}". Must be one of: ${t.join(`, `)}`),process.exit(1)),e.temperature!==void 0&&(isNaN(e.temperature)&&(y.error(`❌ Error: Temperature must be a valid number`),process.exit(1)),(e.temperature<0||e.temperature>1)&&(y.error(`❌ Error: Temperature must be between 0 and 1`),process.exit(1))),l.execute({mode:e.mode,connector:e.connector,action:e.action,goal:e.goal,temperature:e.temperature,verbose:e.verbose})}),this.program.command(`update`).option(`-f, --force`,`Force reinstall even if already on latest version`).description(`Update the CLI to the latest version`).action(e=>{m.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{y.log(`${T.inverse.greenBright(`StackOne`)} ${T.grey(`CLI`)} ${T.whiteBright(this.version)}`),hi(!0),process.exit(0)})}run(){process.argv.includes(`version`)||hi(),this.program.parse(process.argv)}};export{xi as t};
174
+ `)}`;return this.#i(r)};#o=(e,t,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{let e=_i.parse(JSON.parse(r));return{providerKey:t,providerVersion:n,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse account information`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#s=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#c=e=>e.includes(`@`)?e:`${e}@latest`;#l=async(e,n,i,a)=>{(J(e)||J(n)||J(i))&&(y.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let o=q();try{o.text=`Fetching connector ${t(e)} from registry...`,o.start();let r=Buffer.from(i).toString(`base64`),s=a?`?owner=${encodeURIComponent(a)}`:``,c=await fetch(`${n}/registry/connectors/${e}${s}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});if(o.stop(),c.status===409){a&&(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let i=await Lr(e,(await c.json()).availableOwners??[]);o.text=`Fetching connector ${t(e)} from registry...`,o.start();let s=await fetch(`${n}/registry/connectors/${e}?owner=${encodeURIComponent(i)}`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});o.stop(),s.ok||(await b(s,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await s.text(),u=this.#i(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}c.ok||(await b(c,`Failed to fetch connector ${t(e)} from registry`),process.exit(1));let l=await c.text(),u=this.#i(l);return y.success(`Fetched connector ${t(u.key)}@${t(u.version)} from registry`),u}catch(i){o.stop(),y.error(`Failed to fetch connector ${t(e)} from registry: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#u=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let a=q();try{a.text=`Fetching connector for account ${t(e)} from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/connector`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch connector`),process.exit(1));let s=await o.text(),c=this.#i(s);return y.success(`Fetched connector ${t(c.key)}@${t(c.version)} for account ${t(e)}`),c}catch(e){a.stop(),y.error(`Failed to fetch connector: ${e.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#d=async(e,n,i)=>{(J(e)||J(n)||J(i))&&(y.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let a=q();try{a.text=`Fetching account ${t(e)} information from API...`,a.start();let r=Buffer.from(i).toString(`base64`),o=await fetch(`${n}/accounts/${e}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${r}`}});a.stop(),o.ok||(await b(o,`Failed to fetch account ${t(e)} information`),process.exit(1));let s=await o.json();return y.success(`Fetched account ${t(e)} information from project ${t(s.project_id)}`),{providerKey:s.provider_key,providerVersion:s.provider_version,authConfigKey:s.auth_config_key,environment:s.environment,organizationId:s.organization_id,secureId:s.account_id,projectSecureId:s.project_id,credentials:s.credentials}}catch(i){a.stop(),y.error(`Failed to fetch account ${t(e)} information: ${i.message}`),y.log(`Please ensure that the API at ${r(n)} is reachable and the API key is valid`),process.exit(1)}};#f=e=>{let t=e;try{t=G.readFileSync(e,`utf-8`)}catch{}try{return vi.parse(JSON.parse(t))}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}y.error(`Failed to parse credentials`),x(t,!1),t.length===0&&y.log(e.message),process.exit(1)}};#p=(e,n)=>{let r=e;try{r=G.readFileSync(e,`utf-8`)}catch{}try{return yi.parse(JSON.parse(r))}catch(e){let r=[];try{r=JSON.parse(e.message)}catch{}y.error(`Invalid parameters for action ${t(n)}.`),x(r,!1),r.length===0&&y.log(e.message),process.exit(1)}};async#m({connector:e,actionId:n,account:r,pathParams:i={},queryParams:a={},body:s={},headers:c={}}){try{let l=await it({mode:`action_id`,actionId:n,account:r,connector:e,pathParams:i,queryParams:a,body:s,headers:c,getHttpClient:async()=>new ft});if(l.response?.successful){let e={...this.#h(a,l.steps),...We(l.outputs)?l.outputs:{data:l.outputs}};return{statusCode:l.response?.statusCode,output:e}}else{let r=l.response?.message??`An error occurred while processing the request`;y.error(`Action ID ${t(n)} from connector ${t(e.key)}@${t(e.version)} failed with status ${l.response?.statusCode}: ${r}`);let i={...this.#h(a,l.steps)};Object.keys(i).length>0&&(y.log(`${T.yellow.inverse(` EXECUTION DETAILS `)}`),o(i)),process.exit(1)}}catch(e){this.#g(e)}}#h(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#g(e){let t=e;switch(J(t.errorType)&&(y.error(`An unknown error occurred`),y.log(`${e instanceof Error?e.message:String(e)}`),process.exit(1)),t.errorType){case`MISSING_ACTION_ERROR`:y.error(`The specified action was not found: ${t.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let e=t;y.error(`Invalid action inputs`),x(e.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:y.error(`Invalid cursor: ${t.message}`);break;default:y.error(`An error occurred: ${t.message}`)}process.exit(1)}};const Si=pt(we);var Ci=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=q(),this.currentVersion=$t()}async execute(e={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let t=await this.getLatestVersion();this.spinner.stop(),t||(y.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(t,this.currentVersion)?(y.box(`New version available: ${T.yellow(this.currentVersion)} → ${T.green(t)}`),await this.performUpdate(t)):e.force?(y.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(t)):y.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(e){this.spinner.stop(),y.error(`Error while trying to update StackOne CLI: ${e?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await Si(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return dt.gt(e,t)}async performUpdate(e){this.spinner.text=`Updating to latest version (${t(e)})...`,this.spinner.start();let n=`npm install -g ${this.packageName}@latest`;try{await Si(n,{encoding:`utf-8`}),this.spinner.stop(),y.success(`StackOne CLI updated successfully to latest version (${t(e)})`)}catch{throw this.spinner.stop(),Error(`Failed to install update. Please try manually: ${n}`)}}};const wi=e=>e===null?!0:Object.values(e).some(e=>e!==null),Ti=()=>{y.log(`${T.gray.inverse(` CONNECTORS VALIDATION `)} ${T.yellow.inverse(` WATCH MODE `)}\n`)};var Ei=class{async execute(e){let{watchMode:t,fileOrDir:n}=e,r=q(`Watching for file changes... ${T.gray(`(press "q" to quit)`)}`);if(!n)return;let i=Ie(n);try{await ht(i)}catch{y.error(`The specified path does not exist: ${i}\n`),process.exit(1)}if(t){v();let e={},{watch:t}=await import(`chokidar`),n=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let a=()=>{s.close(),r.stop(),n.close(),y.log(T.grey(`
175
+ Exiting watch mode...`)),process.exit(0)};Ti(),y.start(`Validating connectors...`);let o=await Ai(i);e=Di(e,o||{}),Oi(e,i),r.start();let s=t(i,{persistent:!0,ignoreInitial:!0}),c=async t=>{if(!t.endsWith(`.s1.yaml`)&&!t.endsWith(`s1.partial.yaml`))return;let n=t.endsWith(`s1.partial.yaml`)?await Mi(t):[t];if(!(!n||n.length===0)){v(),r.stop(),Ti(),y.log(T.gray(`File change detected: ${t}`)),y.start(`Validating connectors...`);for(let t of n){let n=await Ai(t);e=Di(e,n||{})}Oi(e,i),r.start()}};s.on(`change`,async e=>await c(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&a()}),process.on(`SIGINT`,()=>{a()})}else{let e=await Ai(i,y);process.exit(wi(e)?1:0)}}};const Di=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},Oi=(e,n)=>{v(),Ti();let r=0,i=0;for(let[n,a]of Object.entries(e))a===null?r++:(y?.error(`Connector ${t(n)} is not valid`),x(a,!0),i++);y.log(``),y.log(T.blue.inverse(` Validation Summary `)),y.log(`Connectors path: ${t(n)}`),y.log(`${r===0?T.red(`0`):T.green(r)} valid, ${i===0?T.green(`0`):T.red(i)} invalid connectors\n`)},ki=async e=>{let t=[],n=await mt(e);for(let r of n){let n=Fe(e,r),i=await ht(n);i.isDirectory()?t.push(...await ki(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},Ai=async(e,r)=>{let i=await ht(e),a={};if(i.isDirectory()){let i=await ki(e);if(i.length===0)return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null;let o=0,s=0;for(let e of i){let t=await ji(e,r);t===null?o++:(r?.log(``),s++),a[e]=t}return r?.log(``),r?.log(T.blue.inverse(` Validation Summary `)),r?.log(`${o===0?T.red(`0`):T.green(o)} valid, ${s===0?T.green(`0`):T.red(s)} invalid connectors`),a}else if(i.isFile()&&e.endsWith(`s1.yaml`))return a[e]=await ji(e,r),a;else if(i.isFile()&&e.endsWith(`partial.yaml`)){r?.error(`Partial connector files cannot be validated directly`),r?.log(`The file ${n(e)} is a partial connector file.`);let i=await Mi(e);return i&&i?.length>0&&r?.log(`Did you mean ${t(i[0])}?`),null}else return r?.error(`No StackOne connector found in ${n(e)}`),r?.log(`Connector files need to have the extension ${t(`*.s1.yaml`)}`),null},ji=async(e,n)=>{let r=at(nt(e)),i=r?.errors??[];if(r.success){let r=e.split(`/`).pop()||e;return n?.success(`Connector ${t(r)} is valid!`),null}else if(i.length>0)return n?.error(`Connector ${t(e)} is not valid`),n&&x(i,!0),i;else return n?.error(`Connector ${t(e)} is not valid. Please check the file for errors`),[]},Mi=async e=>{let t=Pe(e);try{return(await mt(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>Fe(t,e))}catch{}};function Ni(e){if(!e)return!1;try{let{hostname:t}=new URL(e);return t===`stackone-dev.com`||t.endsWith(`.stackone-dev.com`)}catch{return!1}}function Pi(){return process.env.AI_TELEMETRY_URL?process.env.AI_TELEMETRY_URL:[process.env.AUTH_SERVER_URL,process.env.STACKONE_API_URL].some(Ni)?`https://ai-telemetry.stackone-dev.com`:`https://ai-telemetry.stackone.com`}function Fi(){let e=process.env.STACKONE_AGENT_TOKEN,t=process.env.LANGSMITH_PROJECT||`stackone-agent-cli`;if(process.env.AI_TELEMETRY_URL=Pi(),e)try{ce({apiKey:e,projectName:t}),process.env.VERBOSE&&console.log(`[Telemetry] Initialized for project:`,t)}catch(e){process.env.VERBOSE&&console.error(`[Telemetry] Failed to initialize:`,e)}}const Ii=e=>{let t=e.trim();return/^\d+$/.test(t)?Number(t):NaN},Li=R(I(),`.stackone`),Ri=R(Li,`version-check.json`),zi=(e=!1)=>{let t=Ui(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=Bi();e&&Vi(e)&&Hi(e),Wi({lastCheckTime:n})}},Bi=()=>{try{return De(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},Vi=e=>{try{let t=$t();return dt.gt(e,t)}catch{return!1}},Hi=e=>{let t=$t(),n=`Update available: ${T.dim(t)} → ${T.green(e)}`,r=`\n\nRun ${T.cyan(`stackone update`)} to update`;y.box(n,r)},Ui=()=>{try{if(!N(Ri))return null;let e=de(Ri,`utf-8`);return JSON.parse(e)}catch{return null}},Wi=e=>{try{N(Li)||ue(Li,{recursive:!0}),me(Ri,JSON.stringify(e,null,2),`utf-8`)}catch{}};var Gi=class{constructor(e=new ne,t=$t()){this.program=e,this.version=t,Fi(),this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let e=new Vr,t=new Kr,n=new Wr,r=new Fr,i=new zr,a=new Ei,o=new On,s=new Sr,c=new fn,l=new dn,u=new An,d=new Cr,f=new Dr,p=new xi,m=new Ci;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(T.red(e))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(t=>{e.execute({environment:t.env})}),this.program.command(`push`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`--force`,`Force push the connector, bypassing version conflict checks`).addArgument(new E(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,n)=>{t.execute({profile:n.profile,fileOrDir:e,apiUrl:n.apiUrl,apiKey:n.apiKey,force:n.force})}),this.program.command(`drop`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new E(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{r.execute({profile:t.profile,connector:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`get`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key (defaults to latest)`).option(`--account-id <account-id>`,`Account ID to fetch connector from`).option(`-f, --format <format>`,`Output format: yaml or json (default: yaml)`,`yaml`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Get a connector from the StackOne registry`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),i.execute({profile:e.profile,connector:e.connector,accountId:e.accountId,format:e.format,outputFile:e.outputFile,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`pull`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output <path>`,`Output directory for the connectors files (default: ./connectors)`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).description(`Pull a connector configuration from StackOne registry to local filesystem`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),n.execute({profile:e.profile,connector:e.connector,outputPath:e.output,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new E(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{a.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`run`).option(`--connector <connector>`,`Connector file, inline YAML, or identifier (provider_key@version or provider_key for latest)`).option(`--action <action>`,`Action to execute on the connector (path to file or inline string action code)`).option(`--action-id <action-id>`,`Action ID to execute on the connector`).option(`--account <account>`,`Account details to use for running the connector (path to file or inline string account data)`).option(`--account-id <account-id>`,`Account ID to use for running the connector against (fetches connector from API if --connector not provided)`).option(`--params <params>`,`Action parameters (path to file or inline string with JSON parameters)`).option(`--credentials <credentials>`,`Credentials to use (path to file or inline string with JSON credentials)`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`-d, --debug`,`Enables debug mode to include more details in the action execution output`).option(`--builtin`,`Use the builtin (StackOne) version of the connector`).option(`--custom`,`Use the custom (organization) version of the connector`).option(`--owner <owner>`,`Owner to use for disambiguating connector versions`).option(`--sync-full`,`Walk the action's dataSync config to exhaustion, as a full sync would (reads only, indexes nothing)`).option(`--sync-incremental [checkpoint]`,`Test incremental sync. With a checkpoint value, resumes from it; without one, runs a full pass first and resumes from the checkpoint it produces`).option(`--sync-max-pages <pages>`,`Cap pages for a sync run (clamped to the production limit of 2000)`,Ii).option(`--sync-page-size <size>`,`Override the provider page size for a sync run, so a small sample account still produces multiple pages (page and offset strategies only)`,Ii).description(`Run a connector action`).action(e=>{[e.builtin,e.custom,e.owner].filter(Boolean).length>1&&(y.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),e.syncFull&&e.syncIncremental!==void 0&&(y.error(`--sync-full and --sync-incremental are mutually exclusive. Please provide only one.`),process.exit(1)),e.syncIncremental===``&&(y.error(`--sync-incremental was given an empty checkpoint value. Omit the value to derive one from a full pass, or pass a real checkpoint.`),process.exit(1)),e.syncMaxPages!==void 0&&(Number.isNaN(e.syncMaxPages)||e.syncMaxPages<1)&&(y.error(`--sync-max-pages must be a positive integer.`),process.exit(1)),e.syncPageSize!==void 0&&(Number.isNaN(e.syncPageSize)||e.syncPageSize<1)&&(y.error(`--sync-page-size must be a positive integer.`),process.exit(1)),e.syncPageSize!==void 0&&!e.syncFull&&!e.syncIncremental&&(y.error(`--sync-page-size only applies to --sync-full or --sync-incremental.`),process.exit(1)),p.execute({connector:e.connector,action:e.action,actionId:e.actionId,account:e.account,accountId:e.accountId,params:e.params,credentials:e.credentials,profile:e.profile,outputFile:e.outputFile,debug:e.debug,apiUrl:e.apiUrl,apiKey:e.apiKey,owner:e.builtin?`builtin`:e.custom?`custom`:e.owner,syncFull:e.syncFull,syncIncremental:e.syncIncremental,syncMaxPages:e.syncMaxPages,syncPageSize:e.syncPageSize})});let h=this.program.command(`agent`).description(`StackOne agent commands`);h.command(`setup`).option(`-g, --global`,`Global only: auth + MCP server (no connector skills/guide)`).option(`-l, --local`,`Local: auth + .mcp.json + connector skills (.claude/) and guide (CLAUDE.md)`).option(`--path <dir>`,`Target project path for local setup (defaults to the current directory)`).option(`--legacy`,`Use email/password login instead of browser-based auth`).option(`--email <email>`,`Email for legacy login (or set STACKONE_EMAIL); requires --legacy`).option(`--password <password>`,`Password for legacy login (or set STACKONE_PASSWORD); requires --legacy. Prefer --password-stdin`).option(`--password-stdin`,`Read password for legacy login from stdin; requires --legacy`).description(`Set up the StackOne agent — prompts for global vs local when neither flag is given`).action(async e=>{e.global&&e.local&&(y.error(`--global and --local are mutually exclusive. Please provide only one.`),process.exit(1));let t=e.email!==void 0,n=e.password!==void 0,r=e.passwordStdin===!0;n&&r&&(y.error(`--password and --password-stdin are mutually exclusive. Please provide only one.`),process.exit(1));let i=t||n||r;i&&!e.legacy&&(y.error(`--email, --password, and --password-stdin require --legacy.`),process.exit(1)),t&&e.email.trim()===``&&(y.error(`--email cannot be empty.`),process.exit(1)),n&&e.password===``&&(y.error(`--password cannot be empty.`),process.exit(1)),r&&(t||process.env.STACKONE_EMAIL?.trim()||(y.error(`--password-stdin requires --email or STACKONE_EMAIL (stdin is consumed for the password, so email cannot be prompted).`),process.exit(1)));let a={email:e.email,password:e.password,passwordFromStdin:r},c=!!process.stdin.isTTY;if(c&&!e.legacy&&!i){let t=await xr({initialMode:e.global?`global`:e.local?`local`:null,pathFlag:e.path});process.exit(t.status===`error`?1:0)}let l=c&&!i;!e.global&&!e.local&&!l&&y.log(T.dim(`No interactive terminal detected — defaulting to global setup. Run in a terminal for the prompt, or pass --local (with --path) / --global.`));let u=Pn(e.global,e.local,l);if(u===null&&(u=await vr()),u===`local`){let t=Fn(e.path,l);t===null&&(t=await br(process.cwd())),await s.execute({legacy:!!e.legacy,credentials:a,targetPath:t})}else await o.execute({legacy:!!e.legacy,credentials:a})}),h.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{c.execute()}),h.command(`run`).description(`Run the agent once with a prompt (non-interactive)`).argument(`<prompt>`,`What to do`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`--max-turns <n>`,`Max agent turns`,`25`).option(`-v, --verbose`,`Verbose output`).action(async(e,t)=>{let n=[`build`,`test`,`research`],r=t.mode??`build`;n.includes(r)||(y.error(`${T.red(`Invalid mode:`)} ${T.white(r)}. Valid modes are: ${n.join(`, `)}.`),process.exit(1));let i=t.maxTurns?parseInt(String(t.maxTurns),10):void 0;await u.execute({prompt:String(e),mode:r,maxTurns:i!==void 0&&!isNaN(i)?i:void 0,verbose:t.verbose})}),h.command(`skills`).description(`List available agent skills and optional recommendations by mode`).option(`-m, --mode <mode>`,`Show skills recommended for this mode`).action(async e=>{await d.execute({mode:e.mode})}),h.command(`sync`).description(`Sync the connector-building skills + guide into this project (.claude/ + CLAUDE.md)`).option(`--check`,`Report drift and exit non-zero instead of writing (CI guard)`).option(`--plugin-dir <path>`,`Override the agent-harness plugin dir (e.g. point at a checkout in CI/benchmarks)`).action(async e=>{await f.execute({check:!!e.check,pluginDir:e.pluginDir})}),h.command(`chat`).option(`-m, --mode <mode>`,`Mode: build, test, or research`,`build`).option(`-c, --connector <name>`,`Connector name`).option(`-a, --action <name>`,`Action name`).option(`-g, --goal <goal>`,`Initial goal/message`).option(`-t, --temperature <number>`,`Temperature (0-1, default: 0.5)`,parseFloat).option(`-v, --verbose`,`Enable verbose logging`).description(`Start an interactive chat session with the agent (use /commands in chat)`).action(async e=>{let t=[`build`,`test`,`research`];e.mode&&!t.includes(e.mode)&&(y.error(`❌ Error: Invalid mode "${e.mode}". Must be one of: ${t.join(`, `)}`),process.exit(1)),e.temperature!==void 0&&(isNaN(e.temperature)&&(y.error(`❌ Error: Temperature must be a valid number`),process.exit(1)),(e.temperature<0||e.temperature>1)&&(y.error(`❌ Error: Temperature must be between 0 and 1`),process.exit(1))),l.execute({mode:e.mode,connector:e.connector,action:e.action,goal:e.goal,temperature:e.temperature,verbose:e.verbose})}),this.program.command(`update`).option(`-f, --force`,`Force reinstall even if already on latest version`).description(`Update the CLI to the latest version`).action(e=>{m.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{y.log(`${T.inverse.greenBright(`StackOne`)} ${T.grey(`CLI`)} ${T.whiteBright(this.version)}`),zi(!0),process.exit(0)})}run(){process.argv.includes(`version`)||zi(),this.program.parse(process.argv)}};export{Gi as t};