@stackone/cli 1.44.2 → 1.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{cliCore-DSgrBC4x.mjs → cliCore-BharJXXM.mjs} +52 -52
- package/dist/{cliCore-DUvOvrms.cjs → cliCore-BqpUU92Z.cjs} +37 -37
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
const e=require(`./agentConfig-KBkYYmMr.cjs`),t=require(`./fileNames-Booqk8P6.cjs`),n=require(`./setupMigration-rqPZ8MV6.cjs`),r=require(`./agentApiKey-BDp7EFMI.cjs`);let i=require(`chalk`);i=e.E(i);let a=require(`commander`),o=require(`@stackone/agent-harness`),s=require(`node:fs`);s=e.E(s);let c=require(`node:os`);c=e.E(c);let l=require(`node:path`);l=e.E(l);let u=require(`ink`),d=require(`react`);d=e.E(d);let f=require(`node:child_process`),p=require(`ink-spinner`);p=e.E(p);let m=require(`fs`);m=e.E(m);let h=require(`path`);h=e.E(h);let g=require(`node:module`),_=require(`url`),v=require(`ora`);v=e.E(v);let y=require(`node:fs/promises`),b=require(`inquirer`);b=e.E(b);let x=require(`node:process`),S=require(`node:readline`),C=require(`@stackone/utils`),w=require(`@clack/prompts`),T=require(`@stackone/connect-sdk`),E=require(`diff`),
|
|
2
|
-
`)),
|
|
3
|
-
`))},
|
|
1
|
+
const e=require(`./agentConfig-KBkYYmMr.cjs`),t=require(`./fileNames-Booqk8P6.cjs`),n=require(`./setupMigration-rqPZ8MV6.cjs`),r=require(`./agentApiKey-BDp7EFMI.cjs`);let i=require(`chalk`);i=e.E(i);let a=require(`commander`),o=require(`@stackone/agent-harness`),s=require(`node:fs`);s=e.E(s);let c=require(`node:os`);c=e.E(c);let l=require(`node:path`);l=e.E(l);let u=require(`ink`),d=require(`react`);d=e.E(d);let f=require(`node:child_process`),p=require(`ink-spinner`);p=e.E(p);let m=require(`fs`);m=e.E(m);let h=require(`path`);h=e.E(h);let g=require(`node:module`),_=require(`url`),v=require(`ora`);v=e.E(v);let y=require(`node:fs/promises`),b=require(`inquirer`);b=e.E(b);let x=require(`node:process`),S=require(`node:readline`),C=require(`@stackone/utils`),w=require(`@clack/prompts`),T=require(`@stackone/connect-sdk`),E=require(`diff`),D=require(`readline`),ee=require(`@stackone/core`),O=require(`semver`);O=e.E(O);let k=require(`@stackone/transport`),A=require(`node:util`),j=require(`fs/promises`);const M={primary:`#00AF66`,success:`green`,warning:`yellow`,error:`red`,text:`white`,dim:`gray`},N={defaultTerminalWidth:80,boxWidth:44,maxToolNameWidth:64,maxInputSummaryWidth:60,maxSeparatorWidth:60,maxConversationTitleLength:36,maxExampleLength:38,maxCollapsedTools:5,maxToolOutputLines:15},P=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},F={cellsPerFrame:3,pixelFrameMs:18,holdFrames:25,fadeSteps:5,fadeStepMs:80,timerIntervalMs:1e3};function te(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 ne=e=>{let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},re=e=>{let t=(e.status===`complete`||e.status===`warning`||e.status===`error`)&&e.durationMs!=null?` ${ne(e.durationMs)}`:``,n=e.model?d.default.createElement(u.Text,{dimColor:!0},` (`,P(e.model),`)`):null;switch(e.status){case`complete`:return d.default.createElement(u.Text,{color:`green`},e.name,n,` ✓`,t);case`warning`:return d.default.createElement(u.Text,{color:`yellow`},e.name,n,` ⚠`,t);case`running`:return d.default.createElement(u.Text,{color:`cyan`},e.name,n,` `,d.default.createElement(p.default,{type:`dots`}));case`error`:return d.default.createElement(u.Text,{color:`red`},e.name,n,` ✗`,t);case`skipped`:return d.default.createElement(u.Text,{dimColor:!0},e.name,` ⊘`);case`pending`:default:return d.default.createElement(u.Text,{dimColor:!0},e.name,` ○`)}},ie=({phases:e})=>e.length===0?null:d.default.createElement(u.Box,{marginBottom:1},d.default.createElement(u.Text,{bold:!0},`Build: `),e.map((t,n)=>d.default.createElement(u.Box,{key:t.name},d.default.createElement(u.Text,null,`[`),re(t),d.default.createElement(u.Text,null,`]`),n<e.length-1&&d.default.createElement(u.Text,null,` `)))),ae=[`\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`],oe=[` ▄▖▗ ▌ ▄▖`,` ▚ ▜▘▀▌▛▘▙▘▌▌▛▌█▌`,` ▄▌▐▖█▌▙▖▛▖▙▌▌▌▙▖`,``,``,``],se=ae.map((e,t)=>e+oe[t]),I=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},L=ae.map(I),R=[];for(let e=0;e<L.length;e++)for(let t=0;t<L[e].length;t++){let n=L[e][t];n&&R.push({row:e,col:t,cell:n})}const z=Math.max(...L.map(e=>e.length)),ce=({wordmark:e})=>d.default.createElement(u.Text,null,(e?se:ae).join(`
|
|
2
|
+
`)),le=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},ue=({ready:e,onComplete:t})=>{let[n,r]=(0,d.useState)(0),i=(0,d.useRef)(le(R.map((e,t)=>t))),a=(0,d.useRef)(le(R.map((e,t)=>t))),o=(0,d.useRef)(!1),s=Math.ceil(R.length/F.cellsPerFrame),c=s;(0,d.useEffect)(()=>{let e=setInterval(()=>{r(e=>{let t=e+1;return t>=s+F.holdFrames+s+F.holdFrames?(i.current=le(R.map((e,t)=>t)),a.current=le(R.map((e,t)=>t)),0):t})},F.pixelFrameMs);return()=>clearInterval(e)},[s]),(0,d.useEffect)(()=>{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)*F.cellsPerFrame,R.length);for(let t=0;t<e;t++)l.add(i.current[t])}else if(n<s+F.holdFrames)for(let e=0;e<R.length;e++)l.add(e);else if(e)for(let e=0;e<R.length;e++)l.add(e);else if(n<s*2+F.holdFrames){let e=n-s-F.holdFrames,t=Math.min((e+1)*F.cellsPerFrame,R.length);for(let e=0;e<R.length;e++)l.add(e);for(let e=0;e<t;e++)l.delete(a.current[e])}let f=new Map;for(let e of l){let t=R[e];f.set(`${t.row},${t.col}`,t.cell)}let p=[];for(let e=0;e<L.length;e++){let t=``;for(let n=0;n<z;n++){let r=f.get(`${e},${n}`);t+=r??` `}p.push(t)}return d.default.createElement(u.Text,null,p.join(`
|
|
3
|
+
`))},de=(e,t)=>{if(t)return t;let n=N.maxToolNameWidth;return(e.length>n?`${e.slice(0,n-1)}…`:e).padEnd(n)},fe=(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}},
|
|
6
|
-
`||e===`\r`}function
|
|
7
|
-
`+t.slice(e);U.current=n,
|
|
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=
|
|
9
|
-
`),Be=
|
|
10
|
-
... (truncated)`)}return d.default.createElement(u.Box,{key:`${e.timestamp.getTime()}-${t}-${e.role}-subagent`,marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:
|
|
5
|
+
`),truncated:!0}},pe=({tools:e,expanded:t=!1,maxCollapsed:n=N.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 d.default.createElement(u.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:M.primary,borderDimColor:!0,paddingX:1},d.default.createElement(u.Text,{dimColor:!0,bold:!0},a),o.map((e,n)=>d.default.createElement(u.Box,{key:`tool-${n}`,flexDirection:`column`},d.default.createElement(u.Box,null,e.status===`running`?d.default.createElement(u.Text,{color:M.primary},d.default.createElement(p.default,{type:`dots`})):e.status===`failed`?d.default.createElement(u.Text,{color:M.error},`✗`):d.default.createElement(u.Text,{color:M.primary},`✓`),d.default.createElement(u.Text,{bold:!0},` `,de(e.name,e.skillName)),e.inputSummary&&d.default.createElement(u.Text,{dimColor:!0,italic:!0},` `,e.inputSummary.length>N.maxInputSummaryWidth?`${e.inputSummary.slice(0,N.maxInputSummaryWidth-1)}…`:e.inputSummary)),t&&e.output&&d.default.createElement(u.Box,{paddingLeft:2,flexDirection:`column`},(()=>{let{text:t,truncated:n}=fe(e.output,N.maxToolOutputLines);return d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{dimColor:!0,italic:!0,wrap:`wrap`},t),n&&d.default.createElement(u.Text,{dimColor:!0,italic:!0},`... (truncated)`))})()))),s>0&&d.default.createElement(u.Text,{dimColor:!0},`... and `,s,` more (Ctrl+O to show all)`))};let B=``;try{let e=require.resolve(`@stackone/agent-harness`),t=l.dirname(e);for(;t!==l.dirname(t);){let e=l.join(t,`package.json`);if(s.existsSync(e)){let t=JSON.parse(s.readFileSync(e,`utf-8`));if(t.name===`@stackone/agent-harness`){B=t.version||``;break}}t=l.dirname(t)}}catch{}const me=({startTime:e})=>{let[,t]=(0,d.useState)(0);(0,d.useEffect)(()=>{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 d.default.createElement(u.Text,{dimColor:!0},i)},he=({children:e})=>{let[t,n]=(0,d.useState)(0);return(0,d.useEffect)(()=>{if(t>=F.fadeSteps)return;let e=setTimeout(()=>n(e=>e+1),F.fadeStepMs);return()=>clearTimeout(e)},[t]),d.default.createElement(d.default.Fragment,null,e(Math.min(t/F.fadeSteps,1)))},ge=e=>{try{return(0,f.execSync)(process.platform===`darwin`?`pbcopy`:process.platform===`win32`?`clip`:`xclip -selection clipboard`,{input:e,stdio:[`pipe`,`ignore`,`ignore`]}),!0}catch{return!1}};function V(e){return e===` `||e===` `||e===`
|
|
6
|
+
`||e===`\r`}function _e(e,t){let n=t-1;for(;n>=0&&V(e[n]);)n--;for(;n>=0&&!V(e[n]);)n--;return n+1}function H(e,t){let n=t;for(;n<e.length&&V(e[n]);)n++;for(;n<e.length&&!V(e[n]);)n++;return n}function ve(e){return e.filter(e=>!(e.role===`system`&&e.content.startsWith(`TOOL_START:`)))}const ye=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},be=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]||``}},xe=({title:e,mode:t,connector:n,action:r,onSubmit:i,onExit:a,onStop:o,messages:s,currentToolCalls:c=[],isThinking:l=!1,isComplete:f=!1,error:m,isInterrupted:h=!1,commandHistory:g=[],streamingText:_=``,usage:v,detailViewData:y=null,onCloseDetailView:b,onResumeConversation:x,onToggleTrust:S,onRewindTo:C,spawnedSubagentActive:w=!1,spawnedSubagentName:T=`Subagent`,spawnedSubagentComplete:E=!1,queuedMessages:D=[],isProcessingQueue:ee=!1,initInfo:O,pendingDeleteConfirmation:k=null,onConfirmDelete:A,slashCommands:j=[],welcomeContext:N,buildPhases:P,currentBuildPhase:F})=>{let{exit:ne}=(0,u.useApp)(),[re,oe]=(0,d.useState)(null),[I,L]=(0,d.useState)(``),[,R]=(0,d.useState)(0),z=(0,d.useRef)(0),[ce,le]=(0,d.useState)(!0),de=(0,d.useRef)(s),[fe,V]=(0,d.useState)(-1),xe=(0,d.useRef)(g),U=(0,d.useRef)(``),[W,Se]=(0,d.useState)([]),[Ce,we]=(0,d.useState)(0),[G,K]=(0,d.useState)(0),[Te,Ee]=(0,d.useState)(!1),[q,De]=(0,d.useState)(!1),[Oe,ke]=(0,d.useState)(!1),[Ae,J]=(0,d.useState)(!1),je=(0,d.useRef)(``),[Me,Ne]=(0,d.useState)(1),[Pe,Y]=(0,d.useState)(null),[X,Fe]=(0,d.useState)(1),Ie=(0,d.useMemo)(()=>j.map(e=>`/${e.name}`),[j]);(0,d.useEffect)(()=>{de.current=s},[s]),(0,d.useEffect)(()=>{xe.current=g},[g]),(0,d.useEffect)(()=>{I.startsWith(`/`)?(Se(Ie.filter(e=>e.startsWith(I.toLowerCase()))),we(0)):(Se([]),we(0))},[I]),(0,d.useEffect)(()=>{if(y?.items){let e=Math.max(0,y.items.length-1);K(t=>Math.min(t,e))}},[y?.items?.length]),(0,u.useInput)((0,d.useCallback)((e,t)=>{let n=U.current,r=fe;if(t.escape&&(l||_||c.length>0)&&!y){o?.(),L(``),U.current=``,z.current=0,R(0),V(-1);return}if(t.escape&&w&&q&&!y){De(!1);return}if(t.escape&&Oe&&!w&&!y){ke(!1);return}if(k&&A){if(t.escape||e.toLowerCase()===`n`){Ne(1),A(!1);return}if(e.toLowerCase()===`y`){Ne(0),A(!0);return}if(t.upArrow||t.downArrow){Ne(e=>e===0?1:0);return}if(t.return){A(Me===0);return}return}if(y){if(Pe){if(t.escape||t.ctrl&&e===`c`){Y(null);return}if(t.leftArrow||t.rightArrow){Fe(e=>e===0?1:0);return}if(e.toLowerCase()===`y`){S&&S(Pe.path),Y(null);return}if(e.toLowerCase()===`n`){Y(null);return}if(t.return){X===0&&S&&S(Pe.path),Y(null);return}return}if(t.escape||t.ctrl&&e===`c`)if(Te){Ee(!1);return}else{b?.(),K(0);return}if(t.upArrow&&!Te){K(e=>e>0?e-1:y.items.length-1);return}if(t.downArrow&&!Te){K(e=>e<y.items.length-1?e+1:0);return}if(t.ctrl&&e===`o`&&y.type===`trust`&&!Pe&&!Te){let e=y.items[G];e?.path&&(Y({path:e.path,name:e.name}),Fe(1));return}if(t.return){if(Te)return;if(y.type===`resume`){let e=y.items[G];e.messages&&x&&(x(e.messages),b?.(),K(0));return}if(y.type===`rewind`){let e=y.items[G];e.index!==void 0&&C&&(C(e.index),b?.(),K(0));return}Ee(!0);return}return}if(t.ctrl&&e===`o`){w?De(e=>!e):ke(e=>!e);return}if(t.ctrl&&e===`u`){L(``),U.current=``,z.current=0,R(0),V(-1);return}if(t.ctrl&&e===`y`){let e=[...s].reverse().find(e=>e.role===`assistant`);e&&ge(e.content)&&(J(!0),setTimeout(()=>J(!1),2e3));return}if(t.ctrl&&e===`c`||e===``)if(n.trim()){L(``),U.current=``,z.current=0,R(0),V(-1);return}else{a(),ne();return}if(t.shift&&t.return){let e=z.current,t=U.current,n=t.slice(0,e)+`
|
|
7
|
+
`+t.slice(e);U.current=n,L(n);let r=e+1;z.current=r,R(r);return}if(t.ctrl&&e===`a`){z.current=0,R(0);return}if(t.ctrl&&e===`e`){z.current=n.length,R(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=_e(n,z.current);z.current=e,R(e);return}if(d){let e=H(n,z.current);z.current=e,R(e);return}if(t.home||e===`\x1B[H`||e===`\x1BOH`){z.current=0,R(0);return}if(t.end||e===`\x1B[F`||e===`\x1BOF`){z.current=n.length,R(n.length);return}if(process.platform===`darwin`&&t.meta&&t.leftArrow){z.current=0,R(0);return}if(process.platform===`darwin`&&t.meta&&t.rightArrow){z.current=n.length,R(n.length);return}if(process.platform===`darwin`&&t.meta&&t.upArrow){z.current=0,R(0);return}if(process.platform===`darwin`&&t.meta&&t.downArrow){z.current=n.length,R(n.length);return}if(t.ctrl&&t.leftArrow&&process.platform!==`darwin`){let e=_e(n,z.current);z.current=e,R(e);return}if(t.ctrl&&t.rightArrow&&process.platform!==`darwin`){let e=H(n,z.current);z.current=e,R(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=z.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(W.length>0){we(e=>e>0?e-1:W.length-1);return}let e=xe.current;if(r>=0&&e.length>0){V(t=>{let n=Math.max(0,t-1),r=e[n]||``;return L(r),U.current=r,z.current=r.length,R(r.length),n});return}let{rows:t,currentRow:n}=f();if(n>0){let e=z.current-t[n].start,r=t[n-1],i=r.start+Math.min(e,r.end-r.start);z.current=i,R(i);return}if(e.length>0){V(t=>{let n=t<0?e.length-1:Math.max(0,t-1),r=e[n]||``;return L(r),U.current=r,z.current=r.length,R(r.length),n});return}return}if(t.downArrow){if(W.length>0){we(e=>e<W.length-1?e+1:0);return}let e=xe.current;if(r>=0&&e.length>0){V(t=>{let n=t>=e.length-1?-1:t+1,r=n<0?``:e[n]||``;return L(r),U.current=r,z.current=r.length,R(r.length),n});return}let{rows:t,currentRow:n}=f();if(n<t.length-1){let e=z.current-t[n].start,r=t[n+1],i=r.start+Math.min(e,r.end-r.start);z.current=i,R(i);return}return}if(t.return){if(W.length>0){let e=W[Ce];Se([]),we(0),L(``),U.current=``,z.current=0,R(0),je.current=e,i(e);return}if(n.trim()){let e=n.trim();je.current=e,i(e),L(``),U.current=``,z.current=0,R(0),V(-1)}return}if((t.backspace||t.delete)&&z.current>0){let e=z.current,t=U.current,n=t.slice(0,e-1)+t.slice(e);U.current=n,L(n);let r=Math.max(0,e-1);z.current=r,R(r),V(-1);return}if(t.leftArrow&&!t.meta&&!t.ctrl){let e=Math.max(0,z.current-1);z.current=e,R(e);return}if(t.rightArrow&&!t.meta&&!t.ctrl){let e=Math.min(n.length,z.current+1);z.current=e,R(e);return}if(t.tab&&n.startsWith(`/`)){let e=Ie.filter(e=>e.startsWith(n.toLowerCase()));if(e.length===1){let t=e[0].length;L(e[0]),U.current=e[0],z.current=t,R(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=z.current,r=U.current,i=r.slice(0,n)+e+r.slice(n);U.current=i,L(i);let a=n+e.length;z.current=a,R(a),V(-1)}},[i,a,ne,fe,Ie,W,Ce,y,Te,b,w,q,x,G,l,_,c,o,C,k,A,Me,Oe,s])),(0,d.useEffect)(()=>{f&&le(!1)},[f]);let Le=l||_!==``||c.length>0;(0,d.useEffect)(()=>{Le&&!re?oe(new Date):!Le&&re&&oe(null)},[Le,re]);let Z=`\x1B[2m`,Re=`\x1B[0m`,ze=[...se.slice(0,4),`${ae[4]} ${Z}sessions monitored${Re}`,`${ae[5]} ${Z}preview${B?` v${B}`:``}${Re}`].join(`
|
|
9
|
+
`),Be=ve(s),Ve=(0,d.useMemo)(()=>ye(Be),[Be]),He=!!O,Ue=(0,d.useMemo)(()=>{let e=[`${t.charAt(0).toUpperCase()+t.slice(1)} mode`];if(N?.credentialEmail){let t=N.credentialTimeRemaining?` (${N.credentialTimeRemaining.days}d ${N.credentialTimeRemaining.hours}h)`:``;e.push(`${N.credentialEmail}${t}`)}O&&O.mcpServers.length>0&&e.push(`${O.mcpServers.reduce((e,t)=>e+t.count,0)} tools`),O&&O.claudeSkills.count>0&&e.push(`${O.claudeSkills.count} skills`);let r=[{text:`✓ ${e.join(` · `)}`,color:M.primary}],i=n||N?.detectedConnector;if(i&&r.push({text:`📂 Detected connector: ${i}`}),O)for(let e of O.errors)r.push({text:`⚠ ${e}`,color:`yellow`});return r},[O,N,t,n]),We=(0,d.useMemo)(()=>{let e=[],t=N?.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,N]),Ge=(0,d.useMemo)(()=>{let e=n||N?.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]),[Ke,qe]=(0,d.useState)(!1),Je=(0,d.useCallback)(()=>qe(!0),[]),Ye=He&&Ke,Xe=(0,d.useCallback)((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 d.default.createElement(u.Box,{flexDirection:`column`,padding:1},!Ye&&d.default.createElement(ue,{ready:!!He,onComplete:Je}),Ye&&d.default.createElement(u.Box,{flexDirection:`row`,marginBottom:1},d.default.createElement(u.Box,{flexDirection:`column`,flexShrink:0},d.default.createElement(u.Text,null,ze)),d.default.createElement(u.Box,{flexDirection:`column`,marginLeft:3,marginTop:1},d.default.createElement(he,null,e=>d.default.createElement(d.default.Fragment,null,Ue.map((t,n)=>d.default.createElement(u.Text,{key:`hero-${n}`,color:Xe(t.color,e),dimColor:!t.color},t.text)),d.default.createElement(u.Box,{flexDirection:`row`,marginTop:1},We.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginRight:2,borderStyle:`round`,borderColor:M.primary,borderDimColor:!0,paddingX:1,width:44},We.map((e,t)=>d.default.createElement(u.Text,{key:`ctx-${t}`,dimColor:!0},e.text))),d.default.createElement(u.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:M.primary,borderDimColor:!0,paddingX:1,width:44},Ge.map((e,t)=>d.default.createElement(u.Text,{key:`ex-${t}`,dimColor:!0},e.text)))))))),d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},Ve.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=be(e.content);return{name:t.name,inputSummary:t.inputSummary,output:t.output,status:`completed`}});return d.default.createElement(u.Box,{key:`turn-${t}`,flexDirection:`column`},t>0&&d.default.createElement(u.Box,{marginBottom:1},d.default.createElement(u.Text,{dimColor:!0},`─`.repeat(r))),e.userMessage&&d.default.createElement(u.Box,{marginBottom:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:`white`},`❯ You`,d.default.createElement(u.Text,{color:`gray`},` `,`• `,e.userMessage.timestamp.toLocaleTimeString())),d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{color:`white`,wrap:`wrap`},e.userMessage.content))),(c.length>0||e.assistantMessages.length>0)&&d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},d.default.createElement(u.Text,{bold:!0,color:M.primary},`◆ StackOne Agent`),c.length>0&&d.default.createElement(u.Box,{paddingLeft:2,marginTop:0,marginBottom:1},d.default.createElement(pe,{tools:c,expanded:Oe})),e.assistantMessages.map((n,r)=>{let i=r===e.assistantMessages.length-1;return d.default.createElement(u.Box,{key:`asst-${t}-${r}`,paddingLeft:2,flexDirection:`column`,marginBottom:i?0:1},n.isSubagent&&d.default.createElement(u.Text,{color:M.primary,dimColor:!0},`⚡ Subagent`),d.default.createElement(u.Text,{wrap:`wrap`,dimColor:!i},te(n.content)))}),s&&d.default.createElement(u.Box,{paddingLeft:2,marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`✓ `,s))),e.systemMessages.map((e,n)=>d.default.createElement(u.Box,{key:`sys-${t}-${n}`,marginBottom:1},d.default.createElement(u.Text,{color:`gray`},`ℹ System • `,e.timestamp.toLocaleTimeString()),d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0,wrap:`wrap`},e.content)))))})),d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},d.default.createElement(d.default.Fragment,null,(w||E)&&d.default.createElement(u.Box,{marginBottom:0,marginTop:0,borderStyle:`single`,borderColor:M.primary,paddingX:2,paddingY:1,flexDirection:`column`,height:q?`100%`:void 0},d.default.createElement(u.Text,{bold:!0,color:M.primary},E?`✓`:`⚡`,` Subprocess:`,` `,T,` `,E?`(Complete)`:``,` `,q?`(Expanded)`:``),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},E?q?`Press Ctrl+O or ESC to collapse`:`Press Ctrl+O to expand`:q?`Running... Press Ctrl+O or ESC to collapse`:`Running... Press Ctrl+O to expand`)),q?d.default.createElement(d.default.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=be(e.content);r=`🔧 Tool • ${t.name}`,i=t.output.slice(0,500),t.output.length>500&&(i+=`
|
|
10
|
+
... (truncated)`)}return d.default.createElement(u.Box,{key:`${e.timestamp.getTime()}-${t}-${e.role}-subagent`,marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:M.primary},r,d.default.createElement(u.Text,{color:`gray`},` `,`•`,` `,e.timestamp.toLocaleTimeString())),d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{color:n?`gray`:M.primary,dimColor:n,wrap:`wrap`},te(i))))}),!E&&!h&&l&&c.length===0&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:M.primary},d.default.createElement(p.default,{type:`dots`})),d.default.createElement(u.Text,{dimColor:!0},` Thinking...`)),!E&&!h&&c.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},c.map((e,t)=>d.default.createElement(u.Box,{key:t,marginBottom:1},e.status===`running`&&d.default.createElement(u.Text,{color:M.primary},d.default.createElement(p.default,{type:`dots`})),d.default.createElement(u.Text,{color:M.primary},` `,e.skillName?d.default.createElement(d.default.Fragment,null,`✨ Skill •`,` `,e.skillName):d.default.createElement(d.default.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`)))),!E&&_&&!h&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:M.primary},te(_)))):d.default.createElement(d.default.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=be(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 d.default.createElement(u.Box,{key:t,marginTop:1},d.default.createElement(u.Text,{color:
|
|
13
|
-
`).length>2&&`...`))}),!E&&!h&&l&&c.length===0&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:
|
|
12
|
+
`);return d.default.createElement(u.Box,{key:t,marginTop:1},d.default.createElement(u.Text,{color:M.primary,dimColor:n},te(i),r.split(`
|
|
13
|
+
`).length>2&&`...`))}),!E&&!h&&l&&c.length===0&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:M.primary},d.default.createElement(p.default,{type:`dots`})),d.default.createElement(u.Text,{dimColor:!0},` Thinking...`)),!E&&!h&&c.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},c.slice(-2).map((e,t)=>d.default.createElement(u.Box,{key:t,marginBottom:1},e.status===`running`&&d.default.createElement(u.Text,{color:M.primary},d.default.createElement(p.default,{type:`dots`})),d.default.createElement(u.Text,{color:M.primary},` `,e.skillName?d.default.createElement(d.default.Fragment,null,`✨ Skill •`,` `,e.skillName):d.default.createElement(d.default.Fragment,null,`🔧 `,e.name),e.status===`running`&&`...`,e.status===`completed`&&` ✓`))),c.length>2&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`... and`,` `,c.length-2,` `,`more (Ctrl+O to expand)`))),!E&&_&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:M.primary},te(_).split(`
|
|
14
14
|
`).slice(0,2).join(`
|
|
15
|
-
`),
|
|
15
|
+
`),te(_).split(`
|
|
16
16
|
`).length>2&&`
|
|
17
|
-
...`))))),_&&!w&&!h&&d.default.createElement(u.Box,{marginBottom:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:
|
|
17
|
+
...`))))),_&&!w&&!h&&d.default.createElement(u.Box,{marginBottom:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0,color:M.primary},`◆ StackOne Agent`,d.default.createElement(u.Text,{color:`gray`},` • `,new Date().toLocaleTimeString())),d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{wrap:`wrap`},te(_)))),!w&&!h&&c.length>0&&d.default.createElement(u.Box,{marginBottom:1,paddingLeft:2},d.default.createElement(pe,{tools:c.map(e=>({name:e.name,inputSummary:e.inputSummary||``,output:``,status:e.status===`failed`?`failed`:e.status,skillName:e.skillName}))}))),P&&P.length>0&&d.default.createElement(ie,{phases:P,currentPhase:F}),!w&&!h&&l&&c.length===0&&d.default.createElement(u.Box,{marginBottom:1},d.default.createElement(u.Text,{color:M.primary},d.default.createElement(p.default,{type:`dots`})),d.default.createElement(u.Text,{dimColor:!0},` Thinking...`),re&&d.default.createElement(u.Text,{dimColor:!0},` `,d.default.createElement(me,{startTime:re}))),h&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`red`},`⏺ Interrupted · What should the StackOne Agent do instead?`)),m&&d.default.createElement(u.Box,{marginBottom:1,borderStyle:`single`,borderColor:`red`,paddingX:2,paddingY:1,flexDirection:`column`},d.default.createElement(u.Text,{color:`red`},`✗ `,m),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Press Enter to try again or Ctrl+C to exit`))),f&&d.default.createElement(u.Box,{marginBottom:1,borderStyle:`single`,borderColor:M.primary,paddingX:2},d.default.createElement(u.Text,{color:M.primary},`✓ Complete`)),y&&d.default.createElement(u.Box,{marginBottom:1,borderStyle:`single`,borderColor:M.primary,paddingX:2,paddingY:1,flexDirection:`column`},Te?d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:M.primary},y.items[G].name),y.type!==`trust`&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},y.items[G].description)),y.type===`skills`&&d.default.createElement(u.Box,{flexDirection:`column`},y.items[G].version?d.default.createElement(u.Text,{dimColor:!0},`Version:`,` `,String(y.items[G].version)):null,y.items[G].author?d.default.createElement(u.Text,{dimColor:!0},`Author:`,` `,String(y.items[G].author)):null,y.items[G].tags&&Array.isArray(y.items[G].tags)?d.default.createElement(u.Text,{dimColor:!0},`Tags:`,` `,y.items[G].tags.join(`, `)):null,y.items[G].content?d.default.createElement(u.Box,{marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{bold:!0},`Skill Content:`),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{wrap:`wrap`},String(y.items[G].content).slice(0,2e3),String(y.items[G].content).length>2e3?`
|
|
18
18
|
|
|
19
|
-
... (content truncated)`:``))):d.default.createElement(u.Text,{dimColor:!0},`No content available`)),y.type===`tools`&&d.default.createElement(u.Box,{flexDirection:`column`},d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Category:`,` `,String(y.items[G].category))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{bold:!0},`Input Parameters:`)),y.items[G].inputSchema?d.default.createElement(u.Box,{marginTop:1,paddingLeft:2,flexDirection:`column`},(()=>{let e=y.items[G].inputSchema,t=e.properties||{},n=e.required||[];return Object.entries(t).map(([e,t])=>d.default.createElement(u.Box,{key:e,flexDirection:`column`,marginBottom:1},d.default.createElement(u.Text,null,e,n.includes(e)?` *`:``,d.default.createElement(u.Text,{dimColor:!0},` `,`(`,t.type?String(t.type):`any`,`)`)),t.description?d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},String(t.description))):null))})(),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`* = required parameter`))):d.default.createElement(u.Box,{marginTop:1,paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},`No parameters`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{bold:!0},`Output:`)),d.default.createElement(u.Box,{marginTop:1,paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},`Returns JSON with tool execution results`))),y.type===`trust`&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,null,d.default.createElement(u.Text,{dimColor:!0},`Path: `),d.default.createElement(u.Text,null,String(y.items[G].path))),d.default.createElement(u.Text,null,d.default.createElement(u.Text,{dimColor:!0},`Trusted at: `),d.default.createElement(u.Text,null,y.items[G].trustedAt?new Date(y.items[G].trustedAt).toLocaleString():`N/A`))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Press Esc to go back`))):Pe?d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:`yellow`},`⚠️ Remove Trust`),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,{color:`white`},`Are you sure you want to remove trust from:`),d.default.createElement(u.Text,{color:`cyan`,bold:!0},Pe.path)),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,{color:`yellow`},`⚠️ This action is permanent. To trust this folder again,`),d.default.createElement(u.Text,{color:`yellow`},`you must open a new chat session in that directory.`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:X===0?`green`:`gray`,bold:X===0},X===0?`❯ [Y]es`:` Yes`),d.default.createElement(u.Text,null,` `),d.default.createElement(u.Text,{color:X===1?`green`:`gray`,bold:X===1},X===1?`❯ [N]o`:` No`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`←→ to select • Enter to confirm • Esc to cancel`))):d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:
|
|
20
|
-
`),r=
|
|
19
|
+
... (content truncated)`:``))):d.default.createElement(u.Text,{dimColor:!0},`No content available`)),y.type===`tools`&&d.default.createElement(u.Box,{flexDirection:`column`},d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Category:`,` `,String(y.items[G].category))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{bold:!0},`Input Parameters:`)),y.items[G].inputSchema?d.default.createElement(u.Box,{marginTop:1,paddingLeft:2,flexDirection:`column`},(()=>{let e=y.items[G].inputSchema,t=e.properties||{},n=e.required||[];return Object.entries(t).map(([e,t])=>d.default.createElement(u.Box,{key:e,flexDirection:`column`,marginBottom:1},d.default.createElement(u.Text,null,e,n.includes(e)?` *`:``,d.default.createElement(u.Text,{dimColor:!0},` `,`(`,t.type?String(t.type):`any`,`)`)),t.description?d.default.createElement(u.Box,{paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},String(t.description))):null))})(),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`* = required parameter`))):d.default.createElement(u.Box,{marginTop:1,paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},`No parameters`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{bold:!0},`Output:`)),d.default.createElement(u.Box,{marginTop:1,paddingLeft:2},d.default.createElement(u.Text,{dimColor:!0},`Returns JSON with tool execution results`))),y.type===`trust`&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,null,d.default.createElement(u.Text,{dimColor:!0},`Path: `),d.default.createElement(u.Text,null,String(y.items[G].path))),d.default.createElement(u.Text,null,d.default.createElement(u.Text,{dimColor:!0},`Trusted at: `),d.default.createElement(u.Text,null,y.items[G].trustedAt?new Date(y.items[G].trustedAt).toLocaleString():`N/A`))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Press Esc to go back`))):Pe?d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:`yellow`},`⚠️ Remove Trust`),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,{color:`white`},`Are you sure you want to remove trust from:`),d.default.createElement(u.Text,{color:`cyan`,bold:!0},Pe.path)),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},d.default.createElement(u.Text,{color:`yellow`},`⚠️ This action is permanent. To trust this folder again,`),d.default.createElement(u.Text,{color:`yellow`},`you must open a new chat session in that directory.`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:X===0?`green`:`gray`,bold:X===0},X===0?`❯ [Y]es`:` Yes`),d.default.createElement(u.Text,null,` `),d.default.createElement(u.Text,{color:X===1?`green`:`gray`,bold:X===1},X===1?`❯ [N]o`:` No`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`←→ to select • Enter to confirm • Esc to cancel`))):d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Text,{bold:!0,color:M.primary},y.type===`skills`?`📚 Skills (${y.items.length})`:y.type===`tools`?`🔧 Tools (${y.items.length})`:y.type===`mcp`?`📡 MCP Servers (${y.items.filter(e=>e.connected).length}/${y.items.length} connected)`:y.type===`trust`?`📁 Trusted Folders (${y.items.length})`:y.type===`rewind`?`⏮️ Command History (${y.items.length})`:`💬 Recent Conversations (${y.items.length})`),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},y.items.map((e,t)=>{let n=t===G?`❯ `:` `,r=process.stdout.columns||80,i=Math.min(r-10,120),a=(e.name||``).replace(/\n/g,` ⏎ `),o=``;if(y.type===`mcp`?o=e.connected?`● `:`○ `:y.type===`trust`&&(o=e.trusted?`● `:`○ `),y.type===`skills`)return d.default.createElement(u.Text,{key:t,color:t===G?M.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 f=`${n}${o}${a}${s}${l}`,p=f.slice(0,i);return d.default.createElement(u.Text,{key:t,color:t===G?M.primary:`gray`},p,f.length>i?`...`:``)})),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},y.type===`skills`?`↑↓ Navigate • Enter for details • Esc to close`:y.type===`trust`?`↑↓ Navigate • Ctrl+O to remove trust • Enter for details • Esc to close`:y.type===`resume`?`↑↓ Navigate • Enter to resume • Esc to close`:y.type===`rewind`?`↑↓ Navigate • Enter to rewind to • Esc to close`:`↑↓ Navigate • Enter for details • Esc to close`)))),D.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginBottom:1},D.map((e,t)=>d.default.createElement(u.Box,{key:t,marginBottom:t<D.length-1?1:0},d.default.createElement(u.Text,{dimColor:!0},`📬 `),d.default.createElement(u.Text,null,e.content))),ee&&d.default.createElement(u.Text,{dimColor:!0,italic:!0},`Processing...`)),k&&d.default.createElement(u.Box,{marginBottom:1},d.default.createElement(u.Text,{color:`yellow`},`Delete `),d.default.createElement(u.Text,{color:`red`},k.isDirectory&&k.directoryContents?`${k.files.map(e=>e.split(`/`).pop()).join(`, `)}/ (${k.directoryContents.length} files)`:k.files.map(e=>e.split(`/`).pop()).join(`, `)),d.default.createElement(u.Text,{color:`yellow`},`? `),d.default.createElement(u.Text,{color:Me===0?`green`:`gray`},Me===0?`[Y]es`:`y`),d.default.createElement(u.Text,null,`/`),d.default.createElement(u.Text,{color:Me===1?`green`:`gray`},Me===1?`[N]o`:`n`)),ce&&!f&&!y&&!k&&d.default.createElement(d.default.Fragment,null,d.default.createElement(u.Box,{borderStyle:`round`,borderColor:M.primary,borderDimColor:!0,paddingX:2,flexDirection:`column`},(()=>{let e=process.stdout.columns||80,t=Math.max(20,e-6),n=U.current.split(`
|
|
20
|
+
`),r=z.current,i=0,a=[];return n.forEach((e,o)=>{let s=i,c=s+e.length;i=c+1;let l=o===0,f=l?t-2:t,p=[];if(e.length===0)p.push(``);else{let n=e,r=!0;for(;n.length>0;){let e=r?f:t;p.push(n.slice(0,e)),n=n.slice(e),r=!1}}let m=0;p.forEach((e,t)=>{let i=s+m,f=i+e.length,h=l&&t===0,g=r>=i&&r<f,_=r===c&&o<n.length-1&&t===p.length-1,v=r===f&&t===p.length-1&&o===n.length-1,y=`${o}-${t}`;if(g||_||v){let t=r-i,n=e.slice(0,t),o=_?` `:e.charAt(t)||` `,s=_?``:e.slice(t+1);a.push(d.default.createElement(u.Box,{key:y},h&&d.default.createElement(u.Text,{color:M.primary},`❯ `),d.default.createElement(u.Text,{color:`white`},n),d.default.createElement(u.Text,{backgroundColor:`white`,color:`black`,bold:!0},o),d.default.createElement(u.Text,{color:`white`},s)))}else a.push(d.default.createElement(u.Box,{key:y},h&&d.default.createElement(u.Text,{color:M.primary},`❯ `),d.default.createElement(u.Text,{color:`white`},e||` `)));m+=e.length})}),a})()),W.length>0&&d.default.createElement(u.Box,{marginTop:1,paddingLeft:2,flexDirection:`column`},W.map((e,t)=>d.default.createElement(u.Box,{key:e},d.default.createElement(u.Text,{color:t===Ce?M.primary:`gray`},t===Ce?`❯ `:` `,e))))),v&&(()=>{let e=100-(v.input_tokens+v.output_tokens)/1e6*100,t=e>50?`green`:e>20?`yellow`:`red`,n=e<10;return d.default.createElement(u.Box,{marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{dimColor:!0},`📊 Model: Sonnet 4.5 • 🧠 Context left:`,` `,d.default.createElement(u.Text,{color:t},e.toFixed(1),`%`)),n&&d.default.createElement(u.Text,{color:`red`},`⚠️ Context low (`,e.toFixed(1),`% remaining)`))})(),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},ce?`Type message and press Enter • Shift+Enter for new line • `:``,(l||_||c.length>0)&&`ESC to stop • `,Ae?`Copied to clipboard! • `:`Ctrl+Y to copy last response • `,w?`Ctrl+O to expand subprocess • `:`Ctrl+O to show/hide full tool results • `,`Ctrl+C to clear/exit`)))},U=({timeRemaining:e,onRunSetup:t,onIgnore:n})=>{let{exit:r}=(0,u.useApp)(),[i,a]=(0,d.useState)(0);(0,u.useInput)((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 d.default.createElement(u.Box,{flexDirection:`column`,padding:2},d.default.createElement(u.Box,{borderStyle:`round`,borderColor:`yellow`,flexDirection:`column`,paddingX:2,paddingY:1},d.default.createElement(u.Text,{bold:!0,color:`yellow`},`⚠️ Credential Warning`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,null,`Your StackOne credentials expire in `,l,` (last day of 7-day validity).`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,null,"To avoid interruption, run `stackone agent setup` to reauthenticate."),d.default.createElement(u.Text,null),d.default.createElement(u.Text,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Run stackone agent setup`),d.default.createElement(u.Text,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. Ignore and continue`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to continue`)))},W=({directory:e,onConfirm:t,onCancel:n})=>{let{exit:r}=(0,u.useApp)(),[i,a]=(0,d.useState)(0);(0,u.useInput)((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 d.default.createElement(u.Box,{flexDirection:`column`,padding:2},d.default.createElement(u.Box,{borderStyle:`round`,borderColor:`#00AF66`,flexDirection:`column`,paddingX:2,paddingY:1},d.default.createElement(u.Text,{bold:!0},`Do you trust the files in this folder?`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,{dimColor:!0},e),d.default.createElement(u.Text,null),d.default.createElement(u.Text,null,`StackOne Agent may read, write, or execute files contained in this directory.`),d.default.createElement(u.Text,null,`This can pose security risks, so only use files and commands from trusted sources.`),d.default.createElement(u.Text,null),d.default.createElement(u.Text,{color:i===0?o:`white`},i===0?`❯ `:` `,`1. Yes, proceed`),d.default.createElement(u.Text,{color:i===1?o:`white`},i===1?`❯ `:` `,`2. No, exit`)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`↑↓ to navigate • Enter to confirm • Esc to exit`)))},Se=`claude-sonnet-4-6`;async function*Ce(e){let{provider:t,category:n,apiKey:r,mcpServers:i,verbose:a,workDir:s=`./connectors/${t}`,abortSignal:c}=e,l=new o.BuildOrchestrator({provider:t,category:n,workDir:s,baseOptions:{mode:`build`,model:Se,apiKey:r,mcpServers:i,verbose:a,origin:`cli`,abortSignal:c,mcpCache:{enabled:!0},contextPreservation:{enabled:!0,provider:t,workDir:s}}});for await(let e of l.run())yield e}const we=()=>{try{let t=(0,l.join)((0,l.dirname)((0,g.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve(`@stackone/agent-harness`)),`mcp-servers`),n=(0,s.readdirSync)(t).filter(e=>e.endsWith(`.json`)),r=[];for(let i of n){let n=(0,s.readFileSync)((0,l.join)(t,i),`utf-8`),a=JSON.parse(n);for(let[t,n]of Object.entries(a.mcpServers)){let i=`stdio`;if(n.type)i=n.type;else if(n.transport?.type){let r=n.transport.type;if(r!==`http`&&r!==`stdio`&&r!==`sse`){e.w.warn(`⚠️ Skipping MCP server "${t}": Invalid transport type "${r}". Must be "http", "stdio", or "sse"`);continue}i=r===`sse`?`http`:r}else n.url&&(i=`http`);let a={},o=n.transport?.headers||n.headers;if(o)for(let[n,r]of Object.entries(o))a[n]=r.replace(/\$\{([^}]+)\}/g,(r,i)=>{let a=process.env[i];return a===void 0?(e.w.warn(`[MCP] Warning: Environment variable '${i}' referenced in header '${n}' for server '${t}' is not set. Substituting empty string.`),``):a});if(n.auth?.type===`bearer`&&(a.Authorization=`Bearer ${n.auth.token.replace(/\$\{([^}]+)\}/g,(n,r)=>{let i=process.env[r];return i===void 0?(e.w.warn(`[MCP] Warning: Environment variable '${r}' for auth token in server '${t}' is not set`),``):i})}`),i===`http`&&!n.url){e.w.warn(`⚠️ Skipping MCP server "${t}": HTTP transport requires a URL`);continue}if(i===`stdio`){e.w.debug(`Skipping MCP server "${t}": stdio transport is not supported for bundled servers`);continue}r.push({name:t,transport:i,url:n?.url??``,headers:a})}}return r}catch(t){if(t.code===`ENOENT`)return e.w.log(`[MCP] No bundled MCP server configurations found in agent-harness package`),[];throw t}};let G;const K=()=>{if(G!==void 0)return G;try{let e=(0,h.join)((0,h.dirname)((0,_.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),`..`,`package.json`);G=JSON.parse((0,m.readFileSync)(e,`utf8`)).version}catch{G=`unknown`}return G??`unknown`},Te=(e,t)=>{try{if(t.existed&&t.content!==null){let n=l.dirname(e);return s.existsSync(n)||s.mkdirSync(n,{recursive:!0}),s.writeFileSync(e,t.content,`utf-8`),{success:!0,action:`restored`}}else return s.existsSync(e)?(s.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)}}},Ee=/<![^>]*>[\s\S]*<\/HTML>/gi,q=/API Error:\s*\d{3}.*?(?=API Error:|$)/gi,De=e=>e.replace(Ee,``).replace(q,``).trim(),Oe=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},ke=(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
|
-
`)},Ae=[{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`}],J=new Set([`heapdump`]);function je(e,t){let n=new Map(t.map(e=>[e.name,e]));for(let t of e)!n.has(t.name)&&!J.has(t.name)&&n.set(t.name,{...t,source:`harness`});return Array.from(n.values())}const Me=({mode:t,connector:n,action:r,goal:i,verbose:a,temperature:u,apiKey:f})=>{let[p,m]=(0,d.useState)([]),h=(0,d.useRef)([]);h.current=p;let[g,_]=(0,d.useState)(new Map),[v,y]=(0,d.useState)(!1),[b,x]=(0,d.useState)(),[S,C]=(0,d.useState)(!1),[w,T]=(0,d.useState)(!0),[E,
|
|
26
|
+
`)},Ae=[{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`}],J=new Set([`heapdump`]);function je(e,t){let n=new Map(t.map(e=>[e.name,e]));for(let t of e)!n.has(t.name)&&!J.has(t.name)&&n.set(t.name,{...t,source:`harness`});return Array.from(n.values())}const Me=({mode:t,connector:n,action:r,goal:i,verbose:a,temperature:u,apiKey:f})=>{let[p,m]=(0,d.useState)([]),h=(0,d.useRef)([]);h.current=p;let[g,_]=(0,d.useState)(new Map),[v,y]=(0,d.useState)(!1),[b,x]=(0,d.useState)(),[S,C]=(0,d.useState)(!1),[w,T]=(0,d.useState)(!0),[E,D]=(0,d.useState)([]),[ee,O]=(0,d.useState)([]),[k,A]=(0,d.useState)(``),[j]=(0,d.useState)(),[M,N]=(0,d.useState)(!1),[P,F]=(0,d.useState)(null),te=(0,d.useRef)((0,o.createDefaultVisualizationRegistry)()),ne=(0,d.useRef)((0,o.createSkillTracker)()),[re]=(0,d.useState)(new Date),[ie,ae]=(0,d.useState)(0),[oe,se]=(0,d.useState)(!1),I=(0,d.useRef)(!1),[L,R]=(0,d.useState)(``),[z,ce]=(0,d.useState)(!1),[le,ue]=(0,d.useState)([]),[de,fe]=(0,d.useState)(!1),[pe,B]=(0,d.useState)(!1),me=(0,d.useRef)(!1),[he,ge]=(0,d.useState)(),[V,_e]=(0,d.useState)(),H=(0,d.useRef)({shouldStop:!1,requestId:0,controller:null}),[ve,ye]=(0,d.useState)([]),be=(0,d.useRef)(null),[U,W]=(0,d.useState)([]),G=(0,d.useRef)(null),Ee=(0,d.useRef)([]),q=(0,d.useRef)(0),[J,Me]=(0,d.useState)({claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]}),[Ne,Pe]=(0,d.useState)(Ae),Y=(0,d.useRef)(new Map),X=(0,d.useRef)(-1),[Fe,Ie]=(0,d.useState)(null),Le=(0,d.useRef)(null),Z=(0,d.useRef)({operation:``,phase:`idle`}),Re=(e,t=!1)=>{let n=Z.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},ze=(0,d.useMemo)(()=>{let t={};try{let n=e.d();n?.email&&(t.credentialEmail=n.email);let r=e.i(n);r.status===`valid`&&(t.credentialTimeRemaining=r.timeRemaining)}catch{}if(!n)try{let e=process.cwd(),n=s.readdirSync(e).find(e=>e.endsWith(`.connector.s1.yaml`));if(n)t.detectedConnector=n.replace(`.connector.s1.yaml`,``);else{let n=l.join(e,`src`,`configs`);if(s.existsSync(n)&&s.statSync(n).isDirectory()){let e=s.readdirSync(n);if(e.length===1){let r=l.join(n,e[0],`${e[0]}.connector.s1.yaml`);s.existsSync(r)&&(t.detectedConnector=e[0])}}}}catch{}try{let e=l.join(c.homedir(),`.stackone`,`conversations`);if(s.existsSync(e)){let n=s.readdirSync(e).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&&(t.recentConversations=r)}}catch{}return t},[n]);(0,d.useEffect)(()=>{let t=l.join(c.homedir(),`.stackone`,`agent_history`);try{if(s.existsSync(t)){let e=s.readFileSync(t,`utf-8`),n;try{let t=JSON.parse(e);n=Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim()):e.split(`
|
|
27
27
|
`).filter(e=>e.trim())}catch{n=e.split(`
|
|
28
|
-
`).filter(e=>e.trim())}
|
|
29
|
-
`)[0].trim())}}}catch{}return{name:e,description:r,content:i}})),n.claudeSkills={count:e.length,names:e,totalSize:0}}catch(t){e.w.error(`[Skills] Failed to load skills:`,t),n.errors.push(`Failed to load skills`)}try{let e=we();Be.current=e;for(let t of e)n.mcpServers.push({name:t.name,count:0});let t=`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(`.`);n.mcpServers.push({name:`stackone`,count:t.length}),n.toolCounts.mcpByServer.stackone=t}catch(e){n.errors.push(`MCP: ${e instanceof Error?e.message:String(e)}`)}n.toolCounts.builtin=[`Read`,`Write`,`Edit`,`Glob`,`Grep`,`Bash`,`WebSearch`,`WebFetch`],n.toolCounts.total=n.toolCounts.builtin.length;try{Pe(je(await(await(0,o.createAgentSession)({prompt:``,mode:t,apiKey:f})).supportedCommands(),Ae))}catch(t){a&&e.w.warn(`[Commands] Failed to fetch harness commands:`,t)}Me(n)}catch(t){e.w.error(`[Init] Failed to initialize runtime:`,t)}finally{T(!1)}})()},[f,t,a]),(0,d.useEffect)(()=>{
|
|
30
|
-
`)}`,timestamp:new Date}]);break}case`phase_error`:
|
|
28
|
+
`).filter(e=>e.trim())}O(n)}}catch(t){a&&e.w.error(`[History] Failed to load command history:`,t)}},[a]);let Be=(0,d.useRef)([]);(0,d.useEffect)(()=>{(async()=>{let n={claudeSkills:{count:0,names:[],totalSize:0},mcpServers:[],toolCounts:{total:0,builtin:[],mcpByServer:{}},errors:[]};try{try{let e=(0,o.getAvailableSkillNames)(),t=(0,o.getBundledSkillsPath)();D(e.map(e=>{let n=l.join(t,e,`SKILL.md`),r,i;try{if(s.existsSync(n)){let e=s.readFileSync(n,`utf-8`);i=e;let t=e.match(/^---\n([\s\S]*?)\n---/);if(t){let e=t[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}})),n.claudeSkills={count:e.length,names:e,totalSize:0}}catch(t){e.w.error(`[Skills] Failed to load skills:`,t),n.errors.push(`Failed to load skills`)}try{let e=we();Be.current=e;for(let t of e)n.mcpServers.push({name:t.name,count:0});let t=`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(`.`);n.mcpServers.push({name:`stackone`,count:t.length}),n.toolCounts.mcpByServer.stackone=t}catch(e){n.errors.push(`MCP: ${e instanceof Error?e.message:String(e)}`)}n.toolCounts.builtin=[`Read`,`Write`,`Edit`,`Glob`,`Grep`,`Bash`,`WebSearch`,`WebFetch`],n.toolCounts.total=n.toolCounts.builtin.length;try{Pe(je(await(await(0,o.createAgentSession)({prompt:``,mode:t,apiKey:f})).supportedCommands(),Ae))}catch(t){a&&e.w.warn(`[Commands] Failed to fetch harness commands:`,t)}Me(n)}catch(t){e.w.error(`[Init] Failed to initialize runtime:`,t)}finally{T(!1)}})()},[f,t,a]),(0,d.useEffect)(()=>{me.current=pe},[pe]),(0,d.useEffect)(()=>{if(j&&!M){let e=j.input_tokens+j.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};m(e=>[...e,n]),N(!0)}}},[j,M]);let Ve=(0,d.useCallback)(async i=>{try{let e=h.current,a=e.filter(e=>e.role===`user`||e.role===`assistant`);if(a.length<2)return;let o=i.trim().slice(0,50)||a.find(e=>e.role===`user`)?.content?.slice(0,50)||`conversation`;await s.promises.mkdir(l.join(c.homedir(),`.stackone`,`conversations`),{recursive:!0});let u=Date.now(),d=`${u}-${o.replace(/[^a-zA-Z0-9]/g,`-`).toLowerCase().slice(0,50)}.json`,f=l.join(c.homedir(),`.stackone`,`conversations`,d);await s.promises.writeFile(f,JSON.stringify({title:o,timestamp:u,goal:i,messages:e.filter(e=>e.role!==`system`),mode:t,connector:n,action:r},null,2))}catch(t){e.w.error(`Failed to save conversation:`,t)}},[t,n,r]),He=async(e,t,n,r)=>{let i=[`research`,`discover-actions`,`build-and-validate`];ge(i.map(e=>({name:e,status:`pending`})));let o=new Map,u=l.join(c.homedir(),`.stackone`),d=l.join(u,`build-debug.log`);s.existsSync(u)||s.mkdirSync(u,{recursive:!0});let p=s.createWriteStream(d,{flags:`w`}),h=e=>{p.write(`${JSON.stringify({ts:new Date().toISOString(),...e})}\n`)};p.on(`error`,()=>{h=()=>{}}),h({event:`build_start`,provider:e,category:t,model:Se,mcpServerCount:Be.current.length});let g=console.log,v=console.error;console.log=(...e)=>{h({event:`console_log`,args:e.map(String)})},console.error=(...e)=>{h({event:`console_error`,args:e.map(String)})};try{for await(let s of Ce({provider:e,category:t,apiKey:f,mcpServers:Be.current,verbose:a||!1,abortSignal:r})){if(!n())return;if(s.type===`agent_message`){let e=s.message;h({event:`agent_message`,phase:s.phase,msgType:e.type,...e.type===`text`&&{content:e.content},...e.type===`error`&&{error:e.error},...e.type===`tool_call`&&{toolName:e.toolName}})}else h({...s,timestamp:void 0});switch(s.type){case`phase_start`:_e(s.phase),ge(e=>(e||[]).map(e=>e.name===s.phase?{...e,status:`running`,model:s.model}:e));break;case`phase_complete`:{let e=s.result.warnings&&s.result.warnings.length>0,t=o.get(s.phase),n=t&&t.length>0,r=!s.result.success||n,a=r?`error`:e?`warning`:`complete`;ge(e=>(e||[]).map(e=>e.name===s.phase?{...e,status:a,durationMs:s.result.durationMs}:e)),r?x(ke(t&&t.length>0?t:[s.result.error||`Unknown error`],[s.phase],i)):e&&m(e=>[...e,{role:`system`,content:`⚠️ Phase "${s.phase}" completed with warnings:\n${s.result.warnings?.join(`
|
|
30
|
+
`)}`,timestamp:new Date}]);break}case`phase_error`:ge(e=>(e||[]).map(e=>e.name===s.phase?{...e,status:`error`,durationMs:s.result?.durationMs}:e)),x(ke([s.error||`Unknown error`],[s.phase],i));break;case`phase_skipped`:ge(e=>(e||[]).map(e=>e.name===s.phase?{...e,status:`skipped`}:e));break;case`agent_message`:{let e=s.message;if(e.type===`text`){let t=e.content??``,n=Oe(t);if(n){let e=o.get(s.phase)??[];e.includes(n)||e.push(n),o.set(s.phase,e)}let r=De(t);A(e=>e+(r||``))}else if(e.type===`tool_call`){let t=`tc-${++q.current}`;Ee.current.push(t),A(e=>(e&&m(t=>[...t,{role:`assistant`,content:e,timestamp:new Date}]),``)),_(n=>{let r=new Map(n);return r.set(t,{name:e.toolName??``,status:`running`}),r})}else if(e.type===`tool_result`){let e=Ee.current.shift();e&&_(t=>{let n=new Map(t);return n.delete(e),n})}else e.type===`error`&&x(e.error??`Unknown error`);break}}}if(A(e=>{if(e){let t=Oe(e);if(t){let e=o.get(`_unattributed`)??[];e.includes(t)||e.push(t),o.set(`_unattributed`,e)}let n=De(e);n&&m(e=>[...e,{role:`assistant`,content:n,timestamp:new Date}])}return``}),o.size>0){let e=[...new Set([...o.values()].flat())],t=[...o.keys()].filter(e=>e!==`_unattributed`);ge(e=>(e||[]).map(e=>o.has(e.name)&&e.status===`complete`?{...e,status:`error`}:e)),x(ke(e,t,i))}_e(void 0)}catch(e){let t=e instanceof Error?e.message:String(e);h({event:`build_error`,error:t}),x(t)}finally{h({event:`build_end`,phaseErrors:Object.fromEntries(o)}),console.log=g,console.error=v,p.end(),ge(e=>(e||[]).map(e=>e.status===`pending`||e.status===`running`?{...e,status:`skipped`}:e)),y(!1),B(!1),me.current=!1,_(new Map)}},Ue=(0,d.useCallback)(async(i,u=!1)=>{if((w||me.current)&&!u){ue(e=>[...e,{content:i,timestamp:new Date}]),be.current&&clearTimeout(be.current),be.current=setTimeout(()=>{Ge()},3e4);return}if(x(void 0),C(!1),i===`/skills`){if(E.length===0){let e={role:`system`,content:`📚 No skills loaded. Skills will be loaded on startup.`,timestamp:new Date};m(t=>[...t,e]);return}F({type:`skills`,items:E.map(e=>({name:e.name,description:e.description,content:e.content}))});return}if(i===`/tools`){let e=[];for(let t of J.mcpServers){let n=J.toolCounts.mcpByServer[t.name]||[];for(let r of n)e.push({name:r,description:`MCP tool (${t.name})`,category:`MCP:${t.name}`})}let t=[...J.toolCounts.builtin.map(e=>({name:e,description:`Built-in (from agent harness)`,category:`Built-in`})),...e,...J.mcpServers.filter(e=>!J.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`}))];F({type:`tools`,items:t.length>0?t:[{name:`—`,description:`Tools provided by harness (built-in + skills + MCP)`,category:``}]});return}if(i===`/commands`){let e=`📋 Available Commands:
|
|
31
31
|
|
|
32
32
|
`;for(let t of Ne){let n=t.argumentHint?` ${t.argumentHint}`:``;e+=` /${t.name}${n} - ${t.description}\n`}let t={role:`system`,content:e,timestamp:new Date};m(e=>[...e,t]);return}if(i===`/exit`&&process.exit(0),i===`/instructions`){let e=[`📜 Active Instructions
|
|
33
|
-
`];if(E.length>0){e.push(`Skills Loaded (${E.length}):`);for(let t of E)e.push(` • ${t.name}${t.description?` - ${t.description}`:``}`);e.push(``)}e.push(`Session Context:`),e.push(` • Mode: ${t}`),n&&e.push(` • Connector: ${n}`),r&&e.push(` • Action: ${r}`),e.push(` • Turn Count: ${
|
|
33
|
+
`];if(E.length>0){e.push(`Skills Loaded (${E.length}):`);for(let t of E)e.push(` • ${t.name}${t.description?` - ${t.description}`:``}`);e.push(``)}e.push(`Session Context:`),e.push(` • Mode: ${t}`),n&&e.push(` • Connector: ${n}`),r&&e.push(` • Action: ${r}`),e.push(` • Turn Count: ${ie}`),e.push(``);let i={instructions:`Mode: ${t}\nSkills: ${E.map(e=>e.name).join(`, `)||`none`}\nConnector: ${n||`none`}`,skills:E.map(e=>({name:e.name,description:e.description,enabled:!0})),session:{id:`current`,startedAt:re,mode:t,turnCount:ie}},a=te.current.render(`instructions`,i);a?.content&&e.push(a.content);let o={role:`system`,content:e.join(`
|
|
34
34
|
`),timestamp:new Date};m(e=>[...e,o]);return}if(i===`/safety`){let e=`🛡️ Safety Rules
|
|
35
35
|
|
|
36
36
|
`;e+=`Command execution is protected by safety checks implemented in the agent harness.
|
|
@@ -40,17 +40,17 @@ The API is experiencing issues. Try again shortly.`),o.join(`
|
|
|
40
40
|
`,e+=`The exact safety rules and heuristics are maintained by the runtime and may change over time.
|
|
41
41
|
`;try{(0,o.checkCommandSafety)(`ls -la`),e+=`
|
|
42
42
|
✓ Safety hook is active and working`}catch{e+=`
|
|
43
|
-
⚠ Safety hook check failed`}let t={role:`system`,content:e,timestamp:new Date};m(e=>[...e,t]);return}if(i===`/mcp`){if(J.mcpServers.length===0){let e={role:`system`,content:`📡 No MCP servers configured`,timestamp:new Date};m(t=>[...t,e]);return}
|
|
43
|
+
⚠ Safety hook check failed`}let t={role:`system`,content:e,timestamp:new Date};m(e=>[...e,t]);return}if(i===`/mcp`){if(J.mcpServers.length===0){let e={role:`system`,content:`📡 No MCP servers configured`,timestamp:new Date};m(t=>[...t,e]);return}F({type:`mcp`,items:J.mcpServers.map(e=>{let t=J.toolCounts.mcpByServer[e.name]||[];return{name:e.name,description:`${t.length} tools`,tools:t,connected:t.length>0}})});return}if(i===`/trust`){let{getTrustedFoldersForDisplay:e}=await Promise.resolve().then(()=>require(`./trustedFolders-C3hB4Qg3.cjs`)),t=e();if(t.length===0){let e={role:`system`,content:`📁 No trusted folders found.
|
|
44
44
|
|
|
45
|
-
Folders are automatically trusted when you open a chat session in them.`,timestamp:new Date};m(t=>[...t,e]);return}
|
|
46
|
-
`).filter(e=>e.trim());if(t.length===0){let e={role:`system`,content:`⏮️ Command history is empty.`,timestamp:new Date};m(t=>[...t,e]);return}
|
|
45
|
+
Folders are automatically trusted when you open a chat session in them.`,timestamp:new Date};m(t=>[...t,e]);return}F({type:`trust`,items:t.map(e=>({name:e.name,description:e.path,path:e.path,trusted:e.trusted,trustedAt:e.trustedAt}))});return}if(i===`/rewind`){try{let e=l.join(c.homedir(),`.stackone`,`agent_history`);if(!s.existsSync(e)){let e={role:`system`,content:`⏮️ No command history found.`,timestamp:new Date};m(t=>[...t,e]);return}let t=s.readFileSync(e,`utf-8`).split(`
|
|
46
|
+
`).filter(e=>e.trim());if(t.length===0){let e={role:`system`,content:`⏮️ Command history is empty.`,timestamp:new Date};m(t=>[...t,e]);return}F({type:`rewind`,items:t.reverse().slice(0,10).map((e,n)=>({name:e,description:`${t.length-n} messages ago`,index:t.length-n-1}))})}catch(e){let t={role:`system`,content:`❌ Error loading history: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};m(e=>[...e,t])}return}if(i===`/resume`){try{let e=l.join(c.homedir(),`.stackone`,`conversations`);if(!s.existsSync(e)){let e={role:`system`,content:`▶️ No conversation history found. Start a new conversation first!`,timestamp:new Date};m(t=>[...t,e]);return}let t=s.readdirSync(e).filter(e=>e.endsWith(`.json`)).sort((e,t)=>{let n=parseInt(e.split(`-`)[0])||0;return(parseInt(t.split(`-`)[0])||0)-n}).slice(0,10);if(t.length===0){let e={role:`system`,content:`▶️ No conversations found.`,timestamp:new Date};m(t=>[...t,e]);return}let n=t.map(t=>{try{let n=s.readFileSync(l.join(e,t),`utf-8`),r=JSON.parse(n);return{file:t,title:r.title||`Untitled conversation`,timestamp:r.timestamp,messages:r.messages,goal:r.goal}}catch{return null}}).filter(Boolean);if(n.length===0){let e={role:`system`,content:`▶️ No valid conversations found.`,timestamp:new Date};m(t=>[...t,e]);return}F({type:`resume`,items:n.map(e=>({name:e?.title,description:new Date(e?.timestamp).toLocaleString(),goal:e?.goal,file:e?.file,messages:e?.messages}))})}catch(e){let t={role:`system`,content:`❌ Error loading conversations: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};m(e=>[...e,t])}return}let d=Ne.map(e=>`/${e.name}`),h=i.split(` `)[0];if(i.startsWith(`/`)&&h!==`/`&&!d.includes(h)){let e={role:`system`,content:`❌ Unknown command: ${i}\n\nType /commands to see available commands.`,timestamp:new Date};m(t=>[...t,e]);return}if(i===`/compact`){let e={role:`user`,content:i,timestamp:new Date};m(t=>[...t,e]),y(!0);try{let e=p.filter(e=>e.role===`user`||e.role===`assistant`).map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`).join(`
|
|
47
47
|
|
|
48
48
|
`),t=e.length>2e3?e.slice(0,2e3)+`
|
|
49
49
|
|
|
50
|
-
[... truncated for context]`:e;y(!1);let n={role:`system`,content:`🗜️ Compact mode activated - recent context:\n\n${t}`,timestamp:new Date};m(e=>[e[e.length-1],n])}catch(e){y(!1),x(e instanceof Error?e.message:`Failed to summarize conversation`)}return}
|
|
50
|
+
[... truncated for context]`:e;y(!1);let n={role:`system`,content:`🗜️ Compact mode activated - recent context:\n\n${t}`,timestamp:new Date};m(e=>[e[e.length-1],n])}catch(e){y(!1),x(e instanceof Error?e.message:`Failed to summarize conversation`)}return}O(t=>{let n=i.trim();if(!n)return t;let r=[...t,n],o=r.length-1;X.current=o,Y.current.has(o)||Y.current.set(o,{commandIndex:o,command:n,timestamp:Date.now(),files:new Map});let u=l.join(c.homedir(),`.stackone`,`agent_history`);try{let e=l.dirname(u);s.existsSync(e)||s.mkdirSync(e,{recursive:!0});let t=r.slice(-1e3);s.writeFileSync(u,JSON.stringify(t),`utf-8`)}catch(t){a&&e.w.error(`[History] Failed to save command history:`,t)}return r});let g={role:`user`,content:i,timestamp:new Date};m(e=>[...e,g]),y(!0),B(!0),ae(e=>e+1),H.current.requestId+=1,H.current.shouldStop=!1,H.current.controller=new AbortController;let v=H.current.requestId,b=H.current.controller.signal;G.current&&=(clearTimeout(G.current),null),W([]);let S=()=>!H.current.shouldStop&&H.current.requestId===v;try{let s=p.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
51
|
`);Ee.current=[],q.current=0;let c=(0,o.extractBuildIntent)(i);if(t===`build`&&c.isConnectorBuild&&c.provider){await He(c.provider,c.category,S,b);return}try{a&&(e.w.log(`
|
|
52
52
|
[AGENT:CONFIG] ═══════════════════════════════════════`),e.w.log(`[AGENT:CONFIG] Prompt: "${i.slice(0,100)}..."`),e.w.log(`[AGENT:CONFIG] Mode: ${t}`),e.w.log(`[AGENT:CONFIG] MCP Servers: ${Be.current.map(e=>e.name).join(`, `)||`none`}`),e.w.log(`[AGENT:CONFIG] API Key: ${f?`${f.slice(0,15)}...`:`MISSING`}`),e.w.log(`[AGENT:CONFIG] Context keys: ${Object.keys({connector:n,action:r}).filter(e=>({connector:n,action:r})[e]).join(`, `)||`none`}`),e.w.log(`[AGENT:CONFIG] Max turns: 1000`),e.w.log(`[AGENT:CONFIG] ═══════════════════════════════════════
|
|
53
|
-
`));let c=0,l=Date.now();for await(let u of(0,o.executeAgent)({prompt:i,mode:t,mcpServers:Be.current,apiKey:f,context:{connector:n,action:r,conversationSummary:s||void 0},maxTurns:1e3,verbose:a||!1,streaming:!1,origin:`cli`,abortSignal:b,cliVersion:K()})){c++;let t=Date.now()-l;if(a){let n=u.type===`text`?` content="${(u.content||``).slice(0,30)}..."`:u.type===`error`?` error="${u.error}"`:u.type===`tool_call`?` tool="${u.toolName}"`:``;e.w.log(`[AGENT:MSG #${c}] type=${u.type}${n} (${t}ms)`)}if(!S())return;if(u.type===`text`){Z.current.phase=`streaming`,
|
|
53
|
+
`));let c=0,l=Date.now();for await(let u of(0,o.executeAgent)({prompt:i,mode:t,mcpServers:Be.current,apiKey:f,context:{connector:n,action:r,conversationSummary:s||void 0},maxTurns:1e3,verbose:a||!1,streaming:!1,origin:`cli`,abortSignal:b,cliVersion:K()})){c++;let t=Date.now()-l;if(a){let n=u.type===`text`?` content="${(u.content||``).slice(0,30)}..."`:u.type===`error`?` error="${u.error}"`:u.type===`tool_call`?` tool="${u.toolName}"`:``;e.w.log(`[AGENT:MSG #${c}] type=${u.type}${n} (${t}ms)`)}if(!S())return;if(u.type===`text`){Z.current.phase=`streaming`,A(e=>e+(u.content??``)),We();continue}if(u.type===`skill_invocation`){let e=`skill-${++q.current}`;_(t=>{let n=new Map(t);return n.set(e,{name:`Skill`,status:`running`,skillName:u.skillName,inputSummary:u.skillArgs}),n}),setTimeout(()=>{_(t=>{let n=new Map(t);return n.delete(e),n})},2e3);continue}if(u.type===`tool_call`){Z.current={operation:`Processing: "${i.slice(0,100)}${i.length>100?`...`:``}"`,phase:`tool_execution`,toolName:u.toolName,toolInput:u.toolInput};let e=`tc-${++q.current}`;if(Ee.current.push(e),ye(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}R(String(t)),I.current=!0,setTimeout(()=>se(!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))),A(e=>(e&&m(t=>[...t,{role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current}]),``)),_(t=>{let r=new Map(t);return r.set(e,{name:u.toolName??``,status:`running`,inputSummary:n}),r});continue}if(u.type===`tool_result`){Z.current={...Z.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=Ee.current.shift();if(e){ye(t=>t.map(t=>t.id===e?{...t,output:u.toolResult}:t));let t=``;_(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};m(e=>[...e,r])}continue}if(u.type===`tool_progress`){let e=u.progress;u.toolName&&_(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`){Z.current={...Z.current,phase:`streaming`,toolName:void 0,toolInput:void 0};let e=Ee.current.shift();e&&(ye(t=>t.map(t=>t.id===e?{...t,output:`Error: ${u.error}`}:t)),_(t=>{let n=new Map(t);return n.delete(e),n}));continue}if(u.type===`error`){let t=u.error??`Unknown error`,n=t;if(a){e.w.log(`
|
|
54
54
|
[AGENT:ERROR] ═══════════════════════════════════════`),e.w.log(`[AGENT:ERROR] Message: ${t}`),e.w.log(`[AGENT:ERROR] Full message object:`);try{e.w.log(JSON.stringify(u,null,2))}catch{e.w.log(`[AGENT:ERROR] (could not stringify message)`)}e.w.log(`[AGENT:ERROR] Messages received before error: ${c}`),e.w.log(`[AGENT:ERROR] Time elapsed: ${Date.now()-l}ms`),e.w.log(`[AGENT:ERROR] ═══════════════════════════════════════
|
|
55
55
|
`)}t.includes(`exited with code 1`)?n=`Agent subprocess failed (exit code 1).
|
|
56
56
|
|
|
@@ -73,9 +73,9 @@ Original error: ${t}`:(t.includes(`ENOTFOUND`)||t.includes(`ECONNREFUSED`)||t.in
|
|
|
73
73
|
|
|
74
74
|
Original error: ${t}`),x(n),Z.current={operation:``,phase:`idle`};continue}if(u.type===`done`){if(a){let t=Date.now()-l;e.w.log(`
|
|
75
75
|
[AGENT:DONE] ═══════════════════════════════════════`),e.w.log(`[AGENT:DONE] Total messages received: ${c}`),e.w.log(`[AGENT:DONE] Total time: ${t}ms`),e.w.log(`[AGENT:DONE] Status: ${u.status||`unknown`}`),c<=2&&e.w.log(`[AGENT:DONE] ⚠️ WARNING: Very few messages - agent may have failed early`),e.w.log(`[AGENT:DONE] ═══════════════════════════════════════
|
|
76
|
-
`)}Z.current={operation:``,phase:`idle`},y(!1),_(new Map),
|
|
76
|
+
`)}Z.current={operation:``,phase:`idle`},y(!1),_(new Map),ye([]);let t=I.current;A(e=>(e&&m(n=>[...n,{role:`assistant`,content:e,timestamp:new Date,isSubagent:t}]),``)),t?(I.current=!1,setTimeout(()=>{m(t=>{let n=t.filter(e=>e.isSubagent&&e.role===`assistant`).map(e=>e.content).join(`
|
|
77
77
|
|
|
78
|
-
`);return n?.trim()?setTimeout(()=>{
|
|
78
|
+
`);return n?.trim()?setTimeout(()=>{ce(!1),se(!1),setTimeout(()=>{try{Ue(n,!0)}catch(t){e.w.error(`[SUBAGENT] Error:`,t),B(!1)}},100)},300):(ce(!1),se(!1),B(!1)),t})},100)):B(!1),await Ve(i)}}}catch(e){if(!S())return;y(!1),_(new Map),x(Re(e instanceof Error?e.message:String(e),a||!1)),Z.current={operation:``,phase:`idle`}}S()&&(y(!1),_(new Map),B(!1),ye([]),Z.current={operation:``,phase:`idle`})}catch(t){if(!S()){a&&e.w.log(`[STREAM] Ignoring error from interrupted request:`,t instanceof Error?t.message:String(t));return}y(!1),_(new Map),B(!1),ye([]);let n=t instanceof Error?t.message:String(t);n.toLowerCase().includes(`cloudfront`)||n.includes(`403`)&&n.includes(`Request blocked`)?x(`⚠️ 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,17 +96,17 @@ To fix this:
|
|
|
96
96
|
|
|
97
97
|
Original error: ${n}`):n.includes(`API key`)||n.includes(`Invalid API Key`)?(e.w.error(`
|
|
98
98
|
❌ Critical error:`,n),e.w.error(`Please check your configuration and try again.
|
|
99
|
-
`),process.exit(1)):x(Re(n,a||!1)),Z.current={operation:``,phase:`idle`},
|
|
99
|
+
`),process.exit(1)):x(Re(n,a||!1)),Z.current={operation:``,phase:`idle`},B(!1),y(!1),_(new Map)}},[w,p,i,t,n,r,j,M,f,oe,Ve]);(0,d.useEffect)(()=>{w||i&&Ue(i)},[w,i,t,J]);let We=()=>{ue(e=>(e.length===0||_(e=>(!(e.size>0)&&me.current&&(be.current&&=(clearTimeout(be.current),null),setTimeout(()=>Ge(),100)),e)),e))},Ge=()=>{ue(e=>{if(e.length===0)return e;fe(!0),A(e=>{if(e){let t={role:`assistant`,content:e,timestamp:new Date,isSubagent:I.current};m(e=>[...e,t])}return``});let t=e.map(e=>({role:`user`,content:e.content,timestamp:new Date}));m(e=>[...e,...t]);let n=e.map(e=>e.content).join(`
|
|
100
100
|
|
|
101
101
|
---
|
|
102
102
|
|
|
103
|
-
`);return
|
|
103
|
+
`);return fe(!1),B(!1),ye([]),be.current&&=(clearTimeout(be.current),null),setTimeout(()=>{Ue(n,!0)},100),[]})},Ke=(0,d.useCallback)(async e=>{let{removeTrustedFolder:t,getTrustedFoldersForDisplay:n}=await Promise.resolve().then(()=>require(`./trustedFolders-C3hB4Qg3.cjs`));t(e);let r=n();r.length===0?F(null):F({type:`trust`,items:r.map(e=>({name:e.name,description:e.path,path:e.path,trusted:e.trusted,trustedAt:e.trustedAt}))})},[F]);(0,d.useEffect)(()=>{let e=E.map(e=>e.name);ne.current.setActiveSkills(e)},[E]),(0,d.useEffect)(()=>{if(!w&&le.length>0){let e=setTimeout(()=>{We()},100);return()=>clearTimeout(e)}},[w,le.length]);let qe=()=>{},Je=(0,d.useCallback)(()=>{H.current.shouldStop=!0,H.current.controller?.abort(),C(!0),A(e=>{if(e){let t=I.current,n={role:`assistant`,content:e,timestamp:new Date,isSubagent:t};m(e=>[...e,n])}return``}),y(!1),B(!1),me.current=!1,_(new Map),ye([]),m(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})),ue([]),W([]),fe(!1),G.current&&=(clearTimeout(G.current),null)},[]),Ye=(0,d.useCallback)(e=>{Le.current&&=(Le.current.resolve(e),null),Ie(null)},[]);return w?d.default.createElement(xe,{title:`Agent ${t.charAt(0).toUpperCase()+t.slice(1)} Mode`,mode:t,connector:n,action:r,messages:[],currentToolCalls:[],isThinking:!1,isComplete:!1,error:void 0,isInterrupted:!1,onSubmit:()=>{},onExit:qe,onStop:Je,slashCommands:Ne,welcomeContext:ze}):d.default.createElement(xe,{title:`Agent ${t.charAt(0).toUpperCase()+t.slice(1)} Mode`,mode:t,connector:n,action:r,messages:p,currentToolCalls:Array.from(g.values()),isThinking:v,isComplete:!1,error:b,isInterrupted:S,onSubmit:Ue,onExit:qe,onStop:Je,commandHistory:ee,streamingText:k,usage:j,detailViewData:P,onCloseDetailView:()=>F(null),onToggleTrust:Ke,slashCommands:Ne,buildPhases:he,currentBuildPhase:V,onRewindTo:e=>{try{let t=l.join(c.homedir(),`.stackone`,`agent_history`),n=s.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
105
|
`).filter(e=>e.trim())}let i=new Map,a=[],o=[],u=[],d=Array.from(Y.current.keys()).filter(t=>t>e).sort((e,t)=>e-t);for(let e of d){let t=Y.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=Te(e,t);n.success?n.action===`deleted`?o.push(e):a.push(e):u.push(`${e}: ${n.error}`)}for(let e of d)Y.current.delete(e);X.current=e;let f=r.slice(0,e+1);s.writeFileSync(t,JSON.stringify(f),`utf-8`);let p=`⏮️ Rewound to command: "${r[e]}"`;if(a.length>0||o.length>0){if(p+=`
|
|
106
106
|
|
|
107
107
|
📁 File changes:`,a.length>0){p+=`\n Restored (${a.length}):`;for(let e of a.slice(0,10))p+=`\n • ${l.basename(e)}`;a.length>10&&(p+=`\n ... and ${a.length-10} more`)}if(o.length>0){p+=`\n Deleted (${o.length}):`;for(let e of o.slice(0,10))p+=`\n • ${l.basename(e)}`;o.length>10&&(p+=`\n ... and ${o.length-10} more`)}}else p+=`
|
|
108
108
|
|
|
109
|
-
📁 No file changes to restore.`;if(u.length>0){p+=`\n\n⚠️ Errors (${u.length}):`;for(let e of u.slice(0,5))p+=`\n • ${e}`}let h={role:`system`,content:p,timestamp:new Date};m(e=>[...e,h]),
|
|
109
|
+
📁 No file changes to restore.`;if(u.length>0){p+=`\n\n⚠️ Errors (${u.length}):`;for(let e of u.slice(0,5))p+=`\n • ${e}`}let h={role:`system`,content:p,timestamp:new Date};m(e=>[...e,h]),O(f)}catch(e){let t={role:`system`,content:`❌ Error rewinding: ${e instanceof Error?e.message:String(e)}`,timestamp:new Date};m(e=>[...e,t])}},onResumeConversation:e=>{m(e.map(e=>({...e,timestamp:new Date(e.timestamp)})))},spawnedSubagentActive:oe,spawnedSubagentName:L,spawnedSubagentComplete:z,queuedMessages:le,isProcessingQueue:de,initInfo:J,welcomeContext:ze,pendingDeleteConfirmation:Fe,onConfirmDelete:Ye})};var Ne=class{async execute(t){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:n,getAgentCredentialStatus:r,CredentialExpiredError:a,CredentialMissingError:o}=await Promise.resolve().then(()=>require(`./agentApiKey-BhO6uR40.cjs`)),{hasOldSetupFiles:f,migrateFromLocalSetup:p,displayMigrationMessage:m}=await Promise.resolve().then(()=>require(`./setupMigration-BAPr-YQq.cjs`));try{let i=process.cwd(),a=n();f(i)&&m(await p(i,a));let o=r(),h=o.status===`expiring_soon`?o.timeRemaining:void 0;process.env.STACKONE_AGENT_TOKEN||(process.env.STACKONE_AGENT_TOKEN=a);let g=l.join(c.homedir(),`.stackone`,`trusted_directories`),_=[];try{s.existsSync(g)&&(_=s.readFileSync(g,`utf-8`).split(`
|
|
110
110
|
`).filter(e=>e.trim()))}catch(t){e.w.error(`[Trust] Failed to load trusted directories:`,t)}if(!_.includes(i)){let t=!1,{addTrustedFolder:n}=await Promise.resolve().then(()=>require(`./trustedFolders-C3hB4Qg3.cjs`)),{waitUntilExit:r}=(0,u.render)(d.default.createElement(W,{directory:i,onConfirm:()=>{t=!0,n(i)},onCancel:()=>{t=!1}}));await r(),t||(e.w.log(`
|
|
111
111
|
Exiting...`),process.exit(0)),process.stdout.write(`\x1Bc`)}let v=a;if(h){let e={current:`ignore`},{waitUntilExit:t}=(0,u.render)(d.default.createElement(U,{timeRemaining:h,onRunSetup:()=>{e.current=`setup`},onIgnore:()=>{e.current=`ignore`}}));if(await t(),e.current===`setup`){process.stdout.write(`\x1Bc`);let{spawnSync:e}=await import(`node:child_process`),t=e(process.execPath,[process.argv[1],`agent`,`setup`],{stdio:`inherit`});t.status!==0&&process.exit(t.status??1);let r=n();process.env.STACKONE_AGENT_TOKEN=r,v=r}process.stdout.write(`\x1Bc`)}let{waitUntilExit:y}=(0,u.render)(d.default.createElement(Me,{...t,apiKey:v}),{exitOnCtrlC:!1});await y()}catch(t){t instanceof a&&(e.w.error(`
|
|
112
112
|
❌ Credentials Expired
|
|
@@ -135,11 +135,11 @@ To setup for a specific project, run:`),i.default.cyan(`stackone agent setup --l
|
|
|
135
135
|
`),e.w.log(i.default.white("Run `stackone agent setup` to authenticate, then try again.\n"))):e.w.error(t instanceof Error?t.message:String(t)),process.exit(1)}let u=we(),d=(0,o.extractBuildIntent)(n.trim());if(a===`build`&&d.isConnectorBuild&&d.provider)return this.executeOrchestratedBuild({provider:d.provider,category:d.category,apiKey:l,mcpServers:u,verbose:c});c&&(e.w.log(i.default.dim(`Mode: ${a}\n`)),u.length>0&&e.w.log(i.default.dim(`MCP Servers: ${u.map(e=>e.name).join(`, `)}\n`)));let f=null;try{for await(let e of(0,o.executeAgent)({prompt:n.trim(),mode:a,apiKey:l,maxTurns:s,verbose:c,mcpServers:u,origin:`cli`,cliVersion:K()}))$e(e,e=>{f&&f.stop(),f=e})}catch(t){f?.fail(),e.w.error(i.default.red(`
|
|
136
136
|
Error: `+(t instanceof Error?t.message:String(t)))),process.exit(1)}f?.stop(),e.w.log(i.default.green(`
|
|
137
137
|
✓ Done
|
|
138
|
-
`))}async executeOrchestratedBuild(t){let{provider:n,category:r,verbose:a}=t,o=r?` (${r})`:``;e.w.log(i.default.bold(`\nOrchestrated build: ${n}${o}\n`));let s=null,c=new Map;try{for await(let e of Ce(t))switch(e.type){case`phase_start`:{let t=Xe[e.phase]||`${e.phase}...`,n=e.model?i.default.dim(` (${
|
|
138
|
+
`))}async executeOrchestratedBuild(t){let{provider:n,category:r,verbose:a}=t,o=r?` (${r})`:``;e.w.log(i.default.bold(`\nOrchestrated build: ${n}${o}\n`));let s=null,c=new Map;try{for await(let e of Ce(t))switch(e.type){case`phase_start`:{let t=Xe[e.phase]||`${e.phase}...`,n=e.model?i.default.dim(` (${P(e.model)})`):``;s?.stop(),s=(0,v.default)(i.default.cyan(`[${e.phase}]${n} ${t}`)).start(),c.set(e.phase,Date.now());break}case`phase_complete`:{let t=c.get(e.phase),n=t===void 0?0:Math.round((Date.now()-t)/1e3);s?.succeed(i.default.green(`[${e.phase}] Done (${n}s)`)),s=null;break}case`phase_error`:s?.fail(i.default.red(`[${e.phase}] ${e.error}`)),s=null;break;case`agent_message`:Qe(e,s,a);break}}catch(t){s?.fail(),e.w.error(i.default.red(`
|
|
139
139
|
Error: `+(t instanceof Error?t.message:String(t)))),process.exit(1)}s?.stop(),e.w.log(i.default.green(`
|
|
140
140
|
✓ Build complete
|
|
141
141
|
`))}};const Qe=(t,n,r)=>{let a=t.message;switch(a.type){case`text`:r&&process.stdout.write(a.content??``);break;case`tool_call`:{let e=a.toolName??`unknown tool`;n&&(n.text=i.default.cyan(`[${t.phase}] Tool: ${e}`));break}case`tool_error`:e.w.error(i.default.red(`\n[${t.phase}] Tool error (${a.toolName}): ${a.error??`Unknown error`}`));break;case`error`:e.w.error(i.default.red(`\n[${t.phase}] ${a.error??`Unknown error`}`));break;default:break}};function $e(t,n){switch(t.type){case`text`:n(null),process.stdout.write(t.content??``);break;case`tool_call`:{let e=t.toolName??`unknown tool`;n((0,v.default)(i.default.cyan(`Tool: ${e}`)).start());break}case`tool_result`:n(null);break;case`tool_progress`:{let e=t.progress?.operation||t.toolName||`Working...`;n((0,v.default)(i.default.cyan(`Tool: ${e}`)).start());break}case`tool_error`:n(null),e.w.error(i.default.red(`\nTool error (${t.toolName}): ${t.error??`Unknown error`}`));break;case`error`:n(null),e.w.error(i.default.red(`\n${t.error??`Unknown error`}`));break;case`done`:n(null);break;default:process.env.VERBOSE&&console.warn(`[AgentRun] Unknown message type:`,t.type);break}}const et=e=>{let t=e.trim();return t===`~`?(0,c.homedir)():t.startsWith(`~/`)?(0,l.join)((0,c.homedir)(),t.slice(2)):t},tt=(e,t,n)=>e?`global`:t?`local`:n?null:`global`,nt=(e,t)=>e?.trim()||(t?null:process.cwd()),rt=e=>e.existingConfig?`overwrite`:it(e),it=e=>e.mode===`local`&&e.alreadyAuthed?`work`:`auth`,at=(e,t)=>{switch(e){case`mode`:return t.mode===`local`?t.hasGit?`repo-confirm`:`path-input`:rt(t);case`repo-confirm`:return t.repoAccepted?rt(t):`path-input`;case`path-input`:return rt(t);case`overwrite`:return it(t);case`auth`:return`work`;default:return`done`}},ot=(e,t)=>(0,f.execFileSync)(`git`,[`-C`,e,...t],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim(),st=e=>{try{let t=ot(e,[`rev-parse`,`--show-toplevel`]);if(!t)return null;let n;try{n=ot(e,[`remote`,`get-url`,`origin`])||void 0}catch{}return{root:t,remoteUrl:n}}catch{return null}},ct=`connector-guide.md`,lt=`<!-- BEGIN stackone-connector-guide -->`,ut=`<!-- END stackone-connector-guide -->`,dt=`.stackone-connector-env.json`,ft=/^[a-z0-9][a-z0-9_-]*$/,pt=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),mt=e=>`<!-- Generated by \`stackone agent sync\` from @stackone/agent-harness@${e}. Edit upstream, not here. -->`,ht=e=>{if(e.includes(`..`)||!ft.test(e))throw Error(`Refusing unsafe path segment: ${JSON.stringify(e)}`)},Q=(e,...t)=>{let n=(0,l.resolve)(e),r=(0,l.resolve)(n,...t);if(r!==n&&!r.startsWith(n+l.sep))throw Error(`Refusing path outside ${n}: ${r}`);return r},gt=(e,...t)=>(0,s.readFileSync)(Q(e,...t),`utf-8`),_t=(e,...t)=>(0,s.readFileSync)(Q(e,...t)),vt=`@stackone/agent-harness`,yt=()=>{let e=(0,g.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve(`@stackone/agent-harness`),t=(0,l.dirname)(e);for(let e=0;e<6;e++){if((0,s.existsSync)((0,l.join)(t,`package.json`))&&(0,s.existsSync)((0,l.join)(t,`plugin`)))return t;let e=(0,l.dirname)(t);if(e===t)break;t=e}return(0,l.dirname)((0,l.dirname)(e))},bt=()=>(0,l.join)(yt(),`plugin`),xt=e=>{try{let t=e?(0,l.resolve)(e,`..`):yt();return JSON.parse(gt(t,`package.json`)).version??`unknown`}catch{return`unknown`}},St=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()},Ct=(e,t,n)=>{let r=[lt,mt(n),``,t,``,ut].join(`
|
|
142
|
-
`);if(e.includes(lt)&&e.includes(ut)){let t=RegExp(`${pt(lt)}[\\s\\S]*?${pt(ut)}`);return e.replace(t,r)}let i=e.replace(/\s*$/,``);return i.length>0?`${i}\n\n${r}\n`:`${r}\n`},wt=e=>{let t=[];for(let n of(0,s.readdirSync)(e,{withFileTypes:!0}))if(n.isDirectory()){let r=wt(Q(e,n.name));t.push(...r.map(e=>(0,l.join)(n.name,e)))}else t.push(n.name);return t},Tt=(e,t)=>{if(!(0,s.existsSync)(t))return!1;let n=wt(e).sort(),r=wt(t).sort();return n.length!==r.length||n.some((e,t)=>e!==r[t])?!1:n.every(n=>_t(e,n).equals(_t(t,n)))},Et=(e,t)=>{(0,s.rmSync)(t,{recursive:!0,force:!0}),(0,s.mkdirSync)((0,l.dirname)(t),{recursive:!0}),(0,s.cpSync)(e,t,{recursive:!0})},Dt=e=>(0,s.readdirSync)(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory())return!1;let n=Q(e,t.name);return(0,s.existsSync)(Q(n,`SKILL.md`))||Dt(n)}),Ot=e=>{if(!(0,s.existsSync)(e))return[];let t=[],n=[];for(let r of(0,s.readdirSync)(e,{withFileTypes:!0})){if(!r.isDirectory()||!ft.test(r.name))continue;let i=Q(e,r.name);(0,s.existsSync)(Q(i,`SKILL.md`))?t.push(r.name):Dt(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()},kt=()=>({changed:[],unchanged:[],missing:[]}),At=(e,t,n,r)=>{let i=kt();for(let a of e){ht(a);let e=Q(t,a);if(!(0,s.existsSync)(e)||!(0,s.statSync)(e).isDirectory()){i.missing.push(a);continue}let o=Q(n,a);if(Tt(e,o)){i.unchanged.push(a);continue}i.changed.push(a),r||Et(e,o)}return i},jt=(e,t,n)=>{if(!(0,s.existsSync)(e)||!(0,s.statSync)(e).isDirectory())return{status:`missing-source`,fileCount:0};let r=wt(e).length;return r===0?{status:`missing-source`,fileCount:0}:Tt(e,t)?{status:`unchanged`,fileCount:r}:(n||Et(e,t),{status:`changed`,fileCount:r})},Mt=(e,t,n,r)=>{if(!(0,s.existsSync)(Q(e,ct)))return`missing-source`;let i=St(gt(e,ct)),a=Q(t,`CLAUDE.md`),o=(0,s.existsSync)(a)?gt(t,`CLAUDE.md`):``,c=Ct(o,i,n);return c===o?`unchanged`:(r||(0,s.writeFileSync)(a,c),`changed`)},Nt=e=>{let t=(0,l.resolve)(e.pluginDir??bt()),n=(0,l.resolve)(e.cwd),r=e.version??xt(t),i=e.check??!1,a=Q(n,`.claude`),o=Q(t,`skills`),c=At(Ot(o),o,Q(a,`skills`),i),u=jt(Q(t,`commands`),Q(a,`commands`),i),d=jt(Q(t,`agents`),Q(a,`agents`),i),f=Mt(t,n,r,i),p=c.changed.length>0||u.status===`changed`||d.status===`changed`||f===`changed`,m=f!==`missing-source`||u.status!==`missing-source`||d.status!==`missing-source`||c.changed.length+c.unchanged.length>0;if(!i&&m){(0,s.mkdirSync)(a,{recursive:!0});let e={harnessVersion:r,skills:c.changed.concat(c.unchanged).sort(),commands:u.fileCount,agents:d.fileCount,guide:f!==`missing-source`};(0,s.writeFileSync)(Q(a,`.stackone-connector-env.json`),`${JSON.stringify(e,null,2)}\n`)}return{skills:c,commands:u,agents:d,guide:f,hasChanges:p}},Pt=e=>{try{let t=e??bt();return(0,s.statSync)(t).isDirectory()?e?JSON.parse(gt((0,l.resolve)(t,`..`),`package.json`)).name===`@stackone/agent-harness`:!0:!1}catch{return!1}},Ft=`#00af66`,It=({message:e,choices:t,initialIndex:n=0,onSelect:r,onCancel:i})=>{let[a,o]=(0,d.useState)(()=>t.length?Math.min(Math.max(n,0),t.length-1):0);return(0,u.useInput)((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:d.default.createElement(u.Box,{flexDirection:`column`,paddingY:1},d.default.createElement(u.Box,{borderStyle:`round`,borderColor:`cyan`,flexDirection:`column`,paddingX:2,paddingY:1},d.default.createElement(u.Text,{bold:!0},e),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},t.map((e,t)=>d.default.createElement(u.Text,{key:e.value,color:t===a?`#00af66`:`white`},t===a?`❯ `:` `,e.label)))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`↑↓ to navigate • Enter to select`)))},Lt=({message:e,initialValue:t=``,validate:n,onSubmit:r,onCancel:i})=>{let[a,o]=(0,d.useState)(t),[s,c]=(0,d.useState)(null);return(0,u.useInput)((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))}),d.default.createElement(u.Box,{flexDirection:`column`,paddingY:1},d.default.createElement(u.Text,{bold:!0},e),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,null,`> `),d.default.createElement(u.Text,null,a),d.default.createElement(u.Text,{inverse:!0},` `)),s&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`red`},s)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Enter to submit • Esc to cancel`)))},Rt=e=>(0,s.existsSync)(`${e}/CLAUDE.md`)||(0,s.existsSync)(`${e}/.mcp.json`),zt=e=>{try{return(0,s.statSync)(e).isDirectory()}catch{return!1}},Bt=({initialMode:t,pathFlag:r,startDir:i,onExit:a})=>{let[o,c]=(0,d.useState)(`mode`),[f,m]=(0,d.useState)(null),[h,g]=(0,d.useState)(!1),[_,v]=(0,d.useState)([]),[y,b]=(0,d.useState)(``),[x,S]=(0,d.useState)(t),[C,w]=(0,d.useState)(``),[T,E]=(0,d.useState)(``),[ee,te]=(0,d.useState)(!1),[D,O]=(0,d.useState)(null),k=(0,d.useRef)(0),A=(0,d.useCallback)(e=>{k.current+=1;let t=k.current;v(n=>[...n,{...e,id:t}])},[]),M=(0,d.useCallback)(e=>{m(e)},[]),N=(0,d.useCallback)(async t=>{let n=(0,l.resolve)(et(t));if(!zt(n)){M({status:`error`,message:(0,s.existsSync)(n)?`Target path is not a directory: ${n}`:`Target path does not exist: ${n}`});return}w(n);let r=Rt(n),i=e.l(await e.u());te(i),c(at(`path-input`,{mode:`local`,hasGit:!1,repoAccepted:!1,existingConfig:r,alreadyAuthed:i}))},[M]),P=(0,d.useCallback)(e=>{if(S(e),e===`local`){let e=r?.trim();if(e){N(e);return}let t=st(i);t&&(E(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`),w(t.root)),c(at(`mode`,{mode:`local`,hasGit:!!t,repoAccepted:!1,existingConfig:!1,alreadyAuthed:!1}));return}c(at(`mode`,{mode:`global`,hasGit:!1,repoAccepted:!1,existingConfig:Rt(i),alreadyAuthed:!1}))},[r,i,N]);(0,d.useEffect)(()=>{t&&P(t)},[]);let ne=(0,d.useCallback)(e=>{e?N(C):c(`path-input`)},[N,C]),re=(0,d.useCallback)(e=>{if(!e){M({status:`cancelled`});return}c(at(`overwrite`,{mode:x??`global`,hasGit:!1,repoAccepted:!1,existingConfig:!0,alreadyAuthed:ee}))},[x,ee,M]);return(0,d.useEffect)(()=>{if(o!==`auth`)return;let e=!1;return b(`Starting browser authentication…`),Ke(t=>{e||b(t)}).then(t=>{e||(O(t),A({icon:`✓`,text:t.email?`Authenticated as ${t.email}`:`Authenticated`,color:j.success}),c(`work`))}).catch(t=>{e||M({status:`error`,message:t instanceof Error?t.message:`Authentication failed`})}),()=>{e=!0}},[o,A,M]),(0,d.useEffect)(()=>{if(o!==`work`)return;let t=!1;return(async()=>{try{let r=D??await e.u();if(!r)throw Error(`Not authenticated — no API key found`);let a=await n.r(x===`local`?C:i,r.apiKey);if(a.migrated&&A({icon:`✓`,text:`Migrated ${a.actions.length} item(s) from a previous setup`,color:j.success}),x===`local`){b(`Creating .mcp.json…`),e.h(e.o(C),e.c(),r.apiKey),A({icon:`✓`,text:`Created .mcp.json`,color:j.success}),b(`Syncing connector-building skills + guide…`);let t=Nt({cwd:C});A({icon:`✓`,text:`Connector environment ready (${t.skills.changed.length+t.skills.unchanged.length} skills in .claude/, ${t.guide===`missing-source`?`guide unavailable in this version`:`guide in CLAUDE.md`})`,color:j.success})}else b(`Installing global MCP configuration…`),e.h(e.a(),e.s(),r.apiKey),A({icon:`✓`,text:`Installed to Claude (global)`,color:j.success});if(t)return;b(``),M({status:`done`})}catch(e){if(t)return;M({status:`error`,message:e instanceof Error?e.message:`Setup failed`})}})(),()=>{t=!0}},[o,D,x,C,i,A,M]),(0,d.useEffect)(()=>{if(!f)return;let e=setTimeout(()=>a(f),60);return()=>clearTimeout(e)},[f,a]),d.default.createElement(u.Box,{flexDirection:`column`,padding:1},h?d.default.createElement(le,{wordmark:!0}):d.default.createElement(de,{ready:!0,onComplete:()=>g(!0)}),_.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},_.map(e=>d.default.createElement(u.Text,{key:e.id,color:e.color},e.icon?`${e.icon} `:``,e.text))),d.default.createElement(u.Box,{marginTop:1},(()=>{if(f)return f.status===`error`?d.default.createElement(u.Text,{color:j.error},`✗ `,f.message??`Setup failed`):f.status===`cancelled`?d.default.createElement(u.Text,{color:j.dim},`Setup cancelled.`):d.default.createElement(u.Box,{flexDirection:`column`},d.default.createElement(u.Text,{color:j.success},`✓ Setup complete!`),d.default.createElement(u.Box,{marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{color:j.dim},`Verify with `,d.default.createElement(u.Text,{color:j.primary},`claude mcp list`)),d.default.createElement(u.Text,{color:j.dim},`Tip: run`,` `,d.default.createElement(u.Text,{color:j.primary},`claude --dangerously-skip-permissions`),` `,`to skip permission prompts`),x===`local`&&d.default.createElement(u.Text,{color:j.dim},`Refresh skills anytime with`,` `,d.default.createElement(u.Text,{color:j.primary},`stackone agent sync`))));switch(o){case`mode`:return t?null:d.default.createElement(It,{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=>P(e),onCancel:()=>M({status:`cancelled`})});case`repo-confirm`:return d.default.createElement(It,{message:T,initialIndex:0,choices:[{label:`Yes`,value:`yes`},{label:`No, let me choose a path`,value:`no`}],onSelect:e=>ne(e===`yes`),onCancel:()=>M({status:`cancelled`})});case`path-input`:return d.default.createElement(Lt,{message:`Path to install the connector setup into:`,initialValue:i,validate:e=>{let t=et(e)||i;return(0,s.existsSync)(t)?zt(t)?!0:`Path is not a directory: ${t}`:`Path does not exist: ${t}`},onSubmit:e=>void N(e.trim()||i),onCancel:()=>M({status:`cancelled`})});case`overwrite`:{let e=x===`local`;return d.default.createElement(It,{message:e?`Existing setup found in ${C}. Overwrite it?`:`Local setup detected in ${i} (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=>re(e===`yes`),onCancel:()=>M({status:`cancelled`})})}case`auth`:case`work`:return d.default.createElement(u.Text,null,d.default.createElement(u.Text,{color:j.primary},d.default.createElement(p.default,{type:`dots`})),` `,y);default:return null}})()))},Vt=e=>new Promise(t=>{let{unmount:n}=(0,u.render)(e(e=>{n(),t(e)}))}),Ht=()=>Vt(e=>d.default.createElement(It,{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)})),Ut=(e,t=!0)=>Vt(n=>d.default.createElement(It,{message:e,initialIndex:t?0:1,choices:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}],onSelect:e=>n(e===`yes`),onCancel:()=>n(!1)})),Wt=async e=>{let t=st(e);return t&&await Ut(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`,!0)?t.root:Vt(n=>d.default.createElement(Lt,{message:t?`Path to install into:`:`Current directory is not a git repo. Path to install into:`,initialValue:e,validate:t=>{let n=et(t)||e;return(0,s.existsSync)(n)?!0:`Path does not exist: ${n}`},onSubmit:t=>n(et(t)||e)}))},Gt=e=>new Promise(t=>{let{unmount:n}=(0,u.render)(d.default.createElement(Bt,{initialMode:e.initialMode,pathFlag:e.pathFlag,startDir:e.startDir??process.cwd(),onExit:e=>{n(),t(e)}}))});var Kt=class{async execute(t){e.w.log(i.default.blue.bold(`🤖 StackOne Agent Setup - Local Project
|
|
142
|
+
`);if(e.includes(lt)&&e.includes(ut)){let t=RegExp(`${pt(lt)}[\\s\\S]*?${pt(ut)}`);return e.replace(t,r)}let i=e.replace(/\s*$/,``);return i.length>0?`${i}\n\n${r}\n`:`${r}\n`},wt=e=>{let t=[];for(let n of(0,s.readdirSync)(e,{withFileTypes:!0}))if(n.isDirectory()){let r=wt(Q(e,n.name));t.push(...r.map(e=>(0,l.join)(n.name,e)))}else t.push(n.name);return t},Tt=(e,t)=>{if(!(0,s.existsSync)(t))return!1;let n=wt(e).sort(),r=wt(t).sort();return n.length!==r.length||n.some((e,t)=>e!==r[t])?!1:n.every(n=>_t(e,n).equals(_t(t,n)))},Et=(e,t)=>{(0,s.rmSync)(t,{recursive:!0,force:!0}),(0,s.mkdirSync)((0,l.dirname)(t),{recursive:!0}),(0,s.cpSync)(e,t,{recursive:!0})},Dt=e=>(0,s.readdirSync)(e,{withFileTypes:!0}).some(t=>{if(!t.isDirectory())return!1;let n=Q(e,t.name);return(0,s.existsSync)(Q(n,`SKILL.md`))||Dt(n)}),Ot=e=>{if(!(0,s.existsSync)(e))return[];let t=[],n=[];for(let r of(0,s.readdirSync)(e,{withFileTypes:!0})){if(!r.isDirectory()||!ft.test(r.name))continue;let i=Q(e,r.name);(0,s.existsSync)(Q(i,`SKILL.md`))?t.push(r.name):Dt(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()},kt=()=>({changed:[],unchanged:[],missing:[]}),At=(e,t,n,r)=>{let i=kt();for(let a of e){ht(a);let e=Q(t,a);if(!(0,s.existsSync)(e)||!(0,s.statSync)(e).isDirectory()){i.missing.push(a);continue}let o=Q(n,a);if(Tt(e,o)){i.unchanged.push(a);continue}i.changed.push(a),r||Et(e,o)}return i},jt=(e,t,n)=>{if(!(0,s.existsSync)(e)||!(0,s.statSync)(e).isDirectory())return{status:`missing-source`,fileCount:0};let r=wt(e).length;return r===0?{status:`missing-source`,fileCount:0}:Tt(e,t)?{status:`unchanged`,fileCount:r}:(n||Et(e,t),{status:`changed`,fileCount:r})},Mt=(e,t,n,r)=>{if(!(0,s.existsSync)(Q(e,ct)))return`missing-source`;let i=St(gt(e,ct)),a=Q(t,`CLAUDE.md`),o=(0,s.existsSync)(a)?gt(t,`CLAUDE.md`):``,c=Ct(o,i,n);return c===o?`unchanged`:(r||(0,s.writeFileSync)(a,c),`changed`)},Nt=e=>{let t=(0,l.resolve)(e.pluginDir??bt()),n=(0,l.resolve)(e.cwd),r=e.version??xt(t),i=e.check??!1,a=Q(n,`.claude`),o=Q(t,`skills`),c=At(Ot(o),o,Q(a,`skills`),i),u=jt(Q(t,`commands`),Q(a,`commands`),i),d=jt(Q(t,`agents`),Q(a,`agents`),i),f=Mt(t,n,r,i),p=c.changed.length>0||u.status===`changed`||d.status===`changed`||f===`changed`,m=f!==`missing-source`||u.status!==`missing-source`||d.status!==`missing-source`||c.changed.length+c.unchanged.length>0;if(!i&&m){(0,s.mkdirSync)(a,{recursive:!0});let e={harnessVersion:r,skills:c.changed.concat(c.unchanged).sort(),commands:u.fileCount,agents:d.fileCount,guide:f!==`missing-source`};(0,s.writeFileSync)(Q(a,`.stackone-connector-env.json`),`${JSON.stringify(e,null,2)}\n`)}return{skills:c,commands:u,agents:d,guide:f,hasChanges:p}},Pt=e=>{try{let t=e??bt();return(0,s.statSync)(t).isDirectory()?e?JSON.parse(gt((0,l.resolve)(t,`..`),`package.json`)).name===`@stackone/agent-harness`:!0:!1}catch{return!1}},Ft=`#00af66`,It=({message:e,choices:t,initialIndex:n=0,onSelect:r,onCancel:i})=>{let[a,o]=(0,d.useState)(()=>t.length?Math.min(Math.max(n,0),t.length-1):0);return(0,u.useInput)((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:d.default.createElement(u.Box,{flexDirection:`column`,paddingY:1},d.default.createElement(u.Box,{borderStyle:`round`,borderColor:`cyan`,flexDirection:`column`,paddingX:2,paddingY:1},d.default.createElement(u.Text,{bold:!0},e),d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},t.map((e,t)=>d.default.createElement(u.Text,{key:e.value,color:t===a?`#00af66`:`white`},t===a?`❯ `:` `,e.label)))),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`↑↓ to navigate • Enter to select`)))},Lt=({message:e,initialValue:t=``,validate:n,onSubmit:r,onCancel:i})=>{let[a,o]=(0,d.useState)(t),[s,c]=(0,d.useState)(null);return(0,u.useInput)((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))}),d.default.createElement(u.Box,{flexDirection:`column`,paddingY:1},d.default.createElement(u.Text,{bold:!0},e),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,null,`> `),d.default.createElement(u.Text,null,a),d.default.createElement(u.Text,{inverse:!0},` `)),s&&d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{color:`red`},s)),d.default.createElement(u.Box,{marginTop:1},d.default.createElement(u.Text,{dimColor:!0},`Enter to submit • Esc to cancel`)))},Rt=e=>(0,s.existsSync)(`${e}/CLAUDE.md`)||(0,s.existsSync)(`${e}/.mcp.json`),zt=e=>{try{return(0,s.statSync)(e).isDirectory()}catch{return!1}},Bt=({initialMode:t,pathFlag:r,startDir:i,onExit:a})=>{let[o,c]=(0,d.useState)(`mode`),[f,m]=(0,d.useState)(null),[h,g]=(0,d.useState)(!1),[_,v]=(0,d.useState)([]),[y,b]=(0,d.useState)(``),[x,S]=(0,d.useState)(t),[C,w]=(0,d.useState)(``),[T,E]=(0,d.useState)(``),[D,ee]=(0,d.useState)(!1),[O,k]=(0,d.useState)(null),A=(0,d.useRef)(0),j=(0,d.useCallback)(e=>{A.current+=1;let t=A.current;v(n=>[...n,{...e,id:t}])},[]),N=(0,d.useCallback)(e=>{m(e)},[]),P=(0,d.useCallback)(async t=>{let n=(0,l.resolve)(et(t));if(!zt(n)){N({status:`error`,message:(0,s.existsSync)(n)?`Target path is not a directory: ${n}`:`Target path does not exist: ${n}`});return}w(n);let r=Rt(n),i=e.l(await e.u());ee(i),c(at(`path-input`,{mode:`local`,hasGit:!1,repoAccepted:!1,existingConfig:r,alreadyAuthed:i}))},[N]),F=(0,d.useCallback)(e=>{if(S(e),e===`local`){let e=r?.trim();if(e){P(e);return}let t=st(i);t&&(E(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`),w(t.root)),c(at(`mode`,{mode:`local`,hasGit:!!t,repoAccepted:!1,existingConfig:!1,alreadyAuthed:!1}));return}c(at(`mode`,{mode:`global`,hasGit:!1,repoAccepted:!1,existingConfig:Rt(i),alreadyAuthed:!1}))},[r,i,P]);(0,d.useEffect)(()=>{t&&F(t)},[]);let te=(0,d.useCallback)(e=>{e?P(C):c(`path-input`)},[P,C]),ne=(0,d.useCallback)(e=>{if(!e){N({status:`cancelled`});return}c(at(`overwrite`,{mode:x??`global`,hasGit:!1,repoAccepted:!1,existingConfig:!0,alreadyAuthed:D}))},[x,D,N]);return(0,d.useEffect)(()=>{if(o!==`auth`)return;let e=!1;return b(`Starting browser authentication…`),Ke(t=>{e||b(t)}).then(t=>{e||(k(t),j({icon:`✓`,text:t.email?`Authenticated as ${t.email}`:`Authenticated`,color:M.success}),c(`work`))}).catch(t=>{e||N({status:`error`,message:t instanceof Error?t.message:`Authentication failed`})}),()=>{e=!0}},[o,j,N]),(0,d.useEffect)(()=>{if(o!==`work`)return;let t=!1;return(async()=>{try{let r=O??await e.u();if(!r)throw Error(`Not authenticated — no API key found`);let a=await n.r(x===`local`?C:i,r.apiKey);if(a.migrated&&j({icon:`✓`,text:`Migrated ${a.actions.length} item(s) from a previous setup`,color:M.success}),x===`local`){b(`Creating .mcp.json…`),e.h(e.o(C),e.c(),r.apiKey),j({icon:`✓`,text:`Created .mcp.json`,color:M.success}),b(`Syncing connector-building skills + guide…`);let t=Nt({cwd:C});j({icon:`✓`,text:`Connector environment ready (${t.skills.changed.length+t.skills.unchanged.length} skills in .claude/, ${t.guide===`missing-source`?`guide unavailable in this version`:`guide in CLAUDE.md`})`,color:M.success})}else b(`Installing global MCP configuration…`),e.h(e.a(),e.s(),r.apiKey),j({icon:`✓`,text:`Installed to Claude (global)`,color:M.success});if(t)return;b(``),N({status:`done`})}catch(e){if(t)return;N({status:`error`,message:e instanceof Error?e.message:`Setup failed`})}})(),()=>{t=!0}},[o,O,x,C,i,j,N]),(0,d.useEffect)(()=>{if(!f)return;let e=setTimeout(()=>a(f),60);return()=>clearTimeout(e)},[f,a]),d.default.createElement(u.Box,{flexDirection:`column`,padding:1},h?d.default.createElement(ce,{wordmark:!0}):d.default.createElement(ue,{ready:!0,onComplete:()=>g(!0)}),_.length>0&&d.default.createElement(u.Box,{flexDirection:`column`,marginTop:1},_.map(e=>d.default.createElement(u.Text,{key:e.id,color:e.color},e.icon?`${e.icon} `:``,e.text))),d.default.createElement(u.Box,{marginTop:1},(()=>{if(f)return f.status===`error`?d.default.createElement(u.Text,{color:M.error},`✗ `,f.message??`Setup failed`):f.status===`cancelled`?d.default.createElement(u.Text,{color:M.dim},`Setup cancelled.`):d.default.createElement(u.Box,{flexDirection:`column`},d.default.createElement(u.Text,{color:M.success},`✓ Setup complete!`),d.default.createElement(u.Box,{marginTop:1,flexDirection:`column`},d.default.createElement(u.Text,{color:M.dim},`Verify with `,d.default.createElement(u.Text,{color:M.primary},`claude mcp list`)),d.default.createElement(u.Text,{color:M.dim},`Tip: run`,` `,d.default.createElement(u.Text,{color:M.primary},`claude --dangerously-skip-permissions`),` `,`to skip permission prompts`),x===`local`&&d.default.createElement(u.Text,{color:M.dim},`Refresh skills anytime with`,` `,d.default.createElement(u.Text,{color:M.primary},`stackone agent sync`))));switch(o){case`mode`:return t?null:d.default.createElement(It,{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=>F(e),onCancel:()=>N({status:`cancelled`})});case`repo-confirm`:return d.default.createElement(It,{message:T,initialIndex:0,choices:[{label:`Yes`,value:`yes`},{label:`No, let me choose a path`,value:`no`}],onSelect:e=>te(e===`yes`),onCancel:()=>N({status:`cancelled`})});case`path-input`:return d.default.createElement(Lt,{message:`Path to install the connector setup into:`,initialValue:i,validate:e=>{let t=et(e)||i;return(0,s.existsSync)(t)?zt(t)?!0:`Path is not a directory: ${t}`:`Path does not exist: ${t}`},onSubmit:e=>void P(e.trim()||i),onCancel:()=>N({status:`cancelled`})});case`overwrite`:{let e=x===`local`;return d.default.createElement(It,{message:e?`Existing setup found in ${C}. Overwrite it?`:`Local setup detected in ${i} (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=>ne(e===`yes`),onCancel:()=>N({status:`cancelled`})})}case`auth`:case`work`:return d.default.createElement(u.Text,null,d.default.createElement(u.Text,{color:M.primary},d.default.createElement(p.default,{type:`dots`})),` `,y);default:return null}})()))},Vt=e=>new Promise(t=>{let{unmount:n}=(0,u.render)(e(e=>{n(),t(e)}))}),Ht=()=>Vt(e=>d.default.createElement(It,{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)})),Ut=(e,t=!0)=>Vt(n=>d.default.createElement(It,{message:e,initialIndex:t?0:1,choices:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}],onSelect:e=>n(e===`yes`),onCancel:()=>n(!1)})),Wt=async e=>{let t=st(e);return t&&await Ut(`Install the connector setup into this repo? ${t.remoteUrl?`${t.remoteUrl} (${t.root})`:t.root}`,!0)?t.root:Vt(n=>d.default.createElement(Lt,{message:t?`Path to install into:`:`Current directory is not a git repo. Path to install into:`,initialValue:e,validate:t=>{let n=et(t)||e;return(0,s.existsSync)(n)?!0:`Path does not exist: ${n}`},onSubmit:t=>n(et(t)||e)}))},Gt=e=>new Promise(t=>{let{unmount:n}=(0,u.render)(d.default.createElement(Bt,{initialMode:e.initialMode,pathFlag:e.pathFlag,startDir:e.startDir??process.cwd(),onExit:e=>{n(),t(e)}}))});var Kt=class{async execute(t){e.w.log(i.default.blue.bold(`🤖 StackOne Agent Setup - Local Project
|
|
143
143
|
`));try{let r=(0,l.resolve)(et(t?.targetPath??process.cwd()));await(0,y.access)(r).then(()=>!0).catch(()=>!1)||(e.w.error(`Target path does not exist: ${r}`),process.exit(1)),t?.targetPath&&e.w.log(i.default.dim(`Installing into ${r}\n`));let a=await(0,y.access)(`${r}/CLAUDE.md`).then(()=>!0).catch(()=>!1),o=await(0,y.access)(`${r}/.mcp.json`).then(()=>!0).catch(()=>!1);if(a||o){e.w.warn(`Existing local setup detected:`),a&&e.w.log(i.default.dim(` • CLAUDE.md found`)),o&&e.w.log(i.default.dim(` • .mcp.json found`)),e.w.log(``);let n=Y(!!t?.legacy,t?.credentials),r=!!process.stdin.isTTY;n||!r?e.w.log(i.default.dim(n?`Non-interactive credentials detected; proceeding without confirmation.
|
|
144
144
|
`:`No interactive terminal detected; proceeding without overwrite confirmation.
|
|
145
145
|
`)):(await Ut(`Overwrite existing local configuration?`,!1)||(e.w.log(i.default.dim(`
|
|
@@ -153,7 +153,7 @@ Available skills
|
|
|
153
153
|
`));return}for(let t of n)e.w.log(` • ${t}`);if(r){let t=(0,o.getSkillsForMode)(r);if(t.length>0){e.w.log(i.default.bold(`\nRecommended for mode "${r}":\n`));for(let r of t){let t=n.includes(r);e.w.log(` • ${r}${t?``:i.default.dim(` (not found)`)}`)}}}e.w.log(``)}};const Jt=(t,n,r)=>{let a=r?`stale`:`synced`;n.changed.length>0&&e.w.log(i.default.cyan(` • ${t} ${a}: ${n.changed.join(`, `)}`)),n.missing.length>0&&e.w.log(i.default.dim(` • ${t} not in this harness version: ${n.missing.join(`, `)}`))},Yt=(t,n,r)=>{if(n.status===`missing-source`)return;let a=n.status===`changed`?r?`stale`:`synced`:`up to date`;e.w.log(i.default.cyan(` • ${t} ${a}: ${n.fileCount} file(s)`))},Xt=(t,n)=>{t===`missing-source`?e.w.log(i.default.dim(` • connector-guide.md not in this harness version — skipped CLAUDE.md`)):t===`changed`&&e.w.log(i.default.cyan(` • CLAUDE.md guide block ${n?`stale`:`updated`}`))};var Zt=class{async execute(t){let n=!!t?.check,r=t?.pluginDir;Pt(r)||(e.w.error(r?`--plugin-dir is not a valid @stackone/agent-harness plugin dir: ${r}`:`Could not locate the bundled @stackone/agent-harness plugin. Reinstall the CLI and try again.`),process.exit(1));let a=xt(r);e.w.log(i.default.blue.bold(`🧩 ${n?`Checking`:`Syncing`} connector-building environment`)+i.default.dim(` (agent-harness@${a}${r?` [--plugin-dir]`:``})\n`));try{let t=Nt({cwd:process.cwd(),check:n,pluginDir:r});Jt(`skills`,t.skills,n),Yt(`commands`,t.commands,n),Yt(`agents`,t.agents,n),Xt(t.guide,n),n&&(t.hasChanges&&(e.w.log(``),e.w.error("Connector-building environment is out of date. Run `stackone agent sync` to update."),process.exit(1)),e.w.success(`Connector-building environment is up to date.`),process.exit(0)),t.hasChanges?(e.w.success(`Connector-building environment synced into .claude/ and CLAUDE.md.`),e.w.log(i.default.dim(`
|
|
154
154
|
💡 Skills and the connector guide are managed by the CLI — `),i.default.dim("re-run `stackone agent sync` after a CLI update."))):e.w.success(`Already up to date — nothing to sync.`),process.exit(0)}catch(t){e.w.error(t instanceof Error?t.message:`Unknown error during sync`),process.exit(1)}}};const Qt={profiles:{}},$t=()=>{let n=e._.readConfigFile(t.n);if(!n)return Qt;try{return JSON.parse(n)}catch{return Qt}},en=e=>$t().profiles[e],tn=e=>!!$t().profiles[e],nn=(n,r)=>{let i=$t();i.profiles[n]=r,e._.writeConfigFile(t.n,JSON.stringify(i,null,2))},rn=()=>{let e=$t();return Object.keys(e.profiles)},an=`https://api.stackone.com`;var on=class{async execute({profile:t,connector:n,apiUrl:r,apiKey:a}={}){if(!t&&!a&&(e.w.error(`Profile or API key is required`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),t&&a&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&r&&e.w.warn(`Specifying ${e.C(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!tn(t)){e.w.error(`Configuration profile ${e.C(t)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let n=rn();n.length>0&&(e.w.info(`Available configuration profiles:`),n.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let o=t?en(t):{apiUrl:r??an,apiKey:a};o?.apiKey||(e.w.error(`API key is missing`),e.w.log(`Please provide a valid API key in the profile or via the ${e.C(`--api-key`)} option.`),process.exit(1)),n||(e.w.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let s=n.split(`@`);(s.length!==2||!s[0]||!s[1])&&(e.w.error(`Invalid connector format ${e.S(n)}. Expected format: ${e.C(`provider_key@version`)}`),process.exit(1));let c=o.apiUrl??an,l=await this.dropConnector(n,c,o.apiKey);process.exit(l?0:1)}async dropConnector(t,n,r){let i=(0,v.default)(`🗑️ Dropping connector ${e.C(t)}...`).start();try{let a=Buffer.from(r).toString(`base64`),o=await fetch(`${n}/registry/connectors/${t}`,{method:`DELETE`,headers:{Authorization:`Basic ${a}`}});return i.stop(),o.status===204?(e.w.success(`Successfully dropped connector ${e.C(t)} from the registry`),!0):o.status===404?(e.w.error(`Connector ${e.C(t)} not found in the registry`),!1):o.status===401||o.status===403?(e.w.error(`You do not have permission to drop this connector`),!1):o.status===409?(e.w.error(`Connector ${e.C(t)} has associated configs and cannot be dropped`),e.w.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(o.ok||await e.x(o,`Failed to drop connector ${e.C(t)} from the registry`),!1)}catch(r){return i.stop(),e.w.error(`Failed to drop connector ${e.C(t)} from registry: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),!1}}};const sn=`stackone`;async function cn(t,n){n.length===0&&(e.w.error(`Multiple versions of connector ${e.C(t)} were found but no owner information was returned`),process.exit(1));let r=n.map(e=>({value:e,label:e===sn?`StackOne`:`Custom`,hint:e===sn?`Official StackOne connector`:`Custom connector version created by your organization`}));e.w.warn(`Multiple versions of connector ${e.C(t)} were found. Please select which version to use.`);let i=await(0,w.select)({message:`Which version would you like to use?`,options:r});return(0,w.isCancel)(i)&&(e.w.error(`Operation cancelled.`),process.exit(1)),i}const ln=`https://api.stackone.com`;var un=class{async execute({profile:t,connector:n,accountId:r,format:a,outputFile:o,apiUrl:s,apiKey:c,owner:l}={}){if(!t&&!c&&(e.w.error(`Profile or API key is required`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),t&&c&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&s&&e.w.warn(`Specifying ${e.C(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!tn(t)){e.w.error(`Configuration profile ${e.C(t)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let n=rn();n.length>0&&(e.w.info(`Available configuration profiles:`),n.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let u=t?en(t):{apiUrl:s??ln,apiKey:c};u?.apiKey||(e.w.error(`API key is missing`),e.w.log(`Please provide a valid API key in the profile or via the ${e.C(`--api-key`)} option.`),process.exit(1)),(0,C.isMissing)(n)&&(0,C.isMissing)(r)&&(e.w.error(`Either ${e.C(`--connector`)} or ${e.C(`--account-id`)} must be provided`),process.exit(1)),(0,C.notMissing)(n)&&(0,C.notMissing)(r)&&(e.w.error(`Please provide either ${e.C(`--connector`)} or ${e.C(`--account-id`)}, not both.`),process.exit(1)),(0,C.notMissing)(a)&&a!==`yaml`&&a!==`json`&&(e.w.error(`Format must be either ${e.C(`yaml`)} or ${e.C(`json`)}.`),process.exit(1));let d=u.apiUrl??ln,f;if((0,C.notMissing)(n)){this.#t(n)||(e.w.error(`Invalid connector format ${e.S(n)}. Expected format: ${e.C(`provider_key@version`)} or ${e.C(`provider_key`)}`),process.exit(1));let t=this.#n(n);f=await this.#r(t,d,u.apiKey,a,l)}else (0,C.notMissing)(r)?f=await this.#i(r,d,u.apiKey,a):(e.w.error(`Either ${e.C(`--connector`)} or ${e.C(`--account-id`)} must be provided`),process.exit(1));if((0,C.notMissing)(o))try{m.default.writeFileSync(o,f,`utf-8`),e.w.success(`Connector written to file: ${e.C(o)}`)}catch(t){e.w.error(`Failed to write connector to file ${e.C(o)}: ${t.message}`),process.exit(1)}else if(e.w.log(`\n${i.default.blue.inverse(` CONNECTOR CONTENT `)}\n`),!a||a===`yaml`)e.w.log(this.#e(f));else if(a===`json`)try{e.b(JSON.parse(f))}catch{e.w.log(f)}else e.w.log(f);process.exit(0)}#e(e){return e.split(`
|
|
155
155
|
`).map(e=>{if(e.trim().startsWith(`#`))return i.default.gray(e);if(e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t+1),r=e.substring(t+1),a=r,o=r.trim();return o===`true`||o===`false`?a=r.replace(o,i.default.cyan(o)):o===`null`||o===`~`?a=r.replace(o,i.default.gray(o)):/^-?\d+(\.\d+)?$/.test(o)?a=r.replace(o,i.default.green(o)):(o.startsWith(`"`)&&o.endsWith(`"`)||o.startsWith(`'`)&&o.endsWith(`'`)||o&&!o.startsWith(`-`))&&(a=r.replace(o,i.default.yellow(o))),i.default.red(n)+a}return e.trim().startsWith(`-`)?e.replace(`-`,i.default.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(t,n,r,i,a){let o=(0,v.default)(`Getting connector ${e.C(t)} from registry...`).start();try{let s=Buffer.from(r).toString(`base64`),c=i?`?format=${i}`:``,l=a?`${c?`&`:`?`}owner=${encodeURIComponent(a)}`:``,u=await fetch(`${n}/registry/connectors/${t}${c}${l}`,{method:`GET`,headers:{Authorization:`Basic ${s}`}});if(o.stop(),u.status===409){a&&(await e.x(u,`Failed to get connector ${e.C(t)} from the registry`),process.exit(1));let r=await cn(t,(await u.json()).availableOwners??[]),i=`${n}/registry/connectors/${t}${c}${c?`&`:`?`}owner=${encodeURIComponent(r)}`;o.text=`Getting connector ${e.C(t)} from registry...`,o.start();let l=await fetch(i,{method:`GET`,headers:{Authorization:`Basic ${s}`}});return o.stop(),l.ok||(await e.x(l,`Failed to get connector ${e.C(t)} from the registry`),process.exit(1)),await l.text()}return u.ok||(await e.x(u,`Failed to get connector ${e.C(t)} from the registry`),process.exit(1)),await u.text()}catch(r){o.stop(),e.w.error(`Failed to get connector ${e.C(t)} from the registry: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),process.exit(1)}}async#i(t,n,r,i){let a=(0,v.default)(`Getting connector from account ${e.C(t)}...`).start();try{let o=Buffer.from(r).toString(`base64`),s=i?`?format=${i}`:``,c=await fetch(`${n}/accounts/${t}/connector${s}`,{method:`GET`,headers:{Authorization:`Basic ${o}`}});return a.stop(),c.ok||(await e.x(c,`Failed to get connector from account ${e.C(t)}`),process.exit(1)),await c.text()}catch(r){a.stop(),e.w.error(`Failed to get connector from account ${e.C(t)}: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),process.exit(1)}}};const dn=`https://api.stackone.com`,fn=`https://api.stackone-dev.com`,pn=`http://localhost:4000`;var mn=class{async execute({environment:t}={}){let n=t?.toLowerCase()??`production`;try{(0,w.intro)(`${i.default.inverse(` Initialize profile `)}`);let t=await(0,w.text)({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((0,w.isCancel)(t))return(0,w.cancel)(`Configuration profile initialization cancelled`),process.exit(0);if(tn(t)){let n=await(0,w.confirm)({message:`Configuration profile with name ${e.C(t)} already exists. Do you want to overwrite it?`});if((0,w.isCancel)(n)||!n)return(0,w.cancel)(`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(0,w.text)({message:`API URL`,placeholder:pn,initialValue:pn,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((0,w.isCancel)(e))return(0,w.cancel)(`Configuration profile initialization cancelled`),process.exit(0);r=e}let a=await(0,w.password)({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if((0,w.isCancel)(a))return(0,w.cancel)(`Configuration profile initialization cancelled`),process.exit(0);nn(t,{label:t,environment:n,apiUrl:r,apiKey:a}),(0,w.outro)(`${i.default.green(`✔`)} Configuration profile ${e.C(t)} initialized successfully!`),process.exit(0)}catch(t){t?.isTtyError?e.w.error(`Prompt couldn't be rendered in the current environment`):e.w.error(`Failed to initialize configuration profile: ${t}`),process.exit(1)}}};const hn=20,$={pending:`○`,acceptRemote:`●`,acceptLocal:`◐`,acceptBoth:`◑`,current:`◉`,arrow:`→`,check:`✓`,cross:`✗`,warning:`⚠`};var gn=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=(0,
|
|
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(t,n,r,i,a){let o=(0,v.default)(`Getting connector ${e.C(t)} from registry...`).start();try{let s=Buffer.from(r).toString(`base64`),c=i?`?format=${i}`:``,l=a?`${c?`&`:`?`}owner=${encodeURIComponent(a)}`:``,u=await fetch(`${n}/registry/connectors/${t}${c}${l}`,{method:`GET`,headers:{Authorization:`Basic ${s}`}});if(o.stop(),u.status===409){a&&(await e.x(u,`Failed to get connector ${e.C(t)} from the registry`),process.exit(1));let r=await cn(t,(await u.json()).availableOwners??[]),i=`${n}/registry/connectors/${t}${c}${c?`&`:`?`}owner=${encodeURIComponent(r)}`;o.text=`Getting connector ${e.C(t)} from registry...`,o.start();let l=await fetch(i,{method:`GET`,headers:{Authorization:`Basic ${s}`}});return o.stop(),l.ok||(await e.x(l,`Failed to get connector ${e.C(t)} from the registry`),process.exit(1)),await l.text()}return u.ok||(await e.x(u,`Failed to get connector ${e.C(t)} from the registry`),process.exit(1)),await u.text()}catch(r){o.stop(),e.w.error(`Failed to get connector ${e.C(t)} from the registry: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),process.exit(1)}}async#i(t,n,r,i){let a=(0,v.default)(`Getting connector from account ${e.C(t)}...`).start();try{let o=Buffer.from(r).toString(`base64`),s=i?`?format=${i}`:``,c=await fetch(`${n}/accounts/${t}/connector${s}`,{method:`GET`,headers:{Authorization:`Basic ${o}`}});return a.stop(),c.ok||(await e.x(c,`Failed to get connector from account ${e.C(t)}`),process.exit(1)),await c.text()}catch(r){a.stop(),e.w.error(`Failed to get connector from account ${e.C(t)}: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),process.exit(1)}}};const dn=`https://api.stackone.com`,fn=`https://api.stackone-dev.com`,pn=`http://localhost:4000`;var mn=class{async execute({environment:t}={}){let n=t?.toLowerCase()??`production`;try{(0,w.intro)(`${i.default.inverse(` Initialize profile `)}`);let t=await(0,w.text)({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((0,w.isCancel)(t))return(0,w.cancel)(`Configuration profile initialization cancelled`),process.exit(0);if(tn(t)){let n=await(0,w.confirm)({message:`Configuration profile with name ${e.C(t)} already exists. Do you want to overwrite it?`});if((0,w.isCancel)(n)||!n)return(0,w.cancel)(`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(0,w.text)({message:`API URL`,placeholder:pn,initialValue:pn,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((0,w.isCancel)(e))return(0,w.cancel)(`Configuration profile initialization cancelled`),process.exit(0);r=e}let a=await(0,w.password)({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if((0,w.isCancel)(a))return(0,w.cancel)(`Configuration profile initialization cancelled`),process.exit(0);nn(t,{label:t,environment:n,apiUrl:r,apiKey:a}),(0,w.outro)(`${i.default.green(`✔`)} Configuration profile ${e.C(t)} initialized successfully!`),process.exit(0)}catch(t){t?.isTtyError?e.w.error(`Prompt couldn't be rendered in the current environment`):e.w.error(`Failed to initialize configuration profile: ${t}`),process.exit(1)}}};const hn=20,$={pending:`○`,acceptRemote:`●`,acceptLocal:`◐`,acceptBoth:`◑`,current:`◉`,arrow:`→`,check:`✓`,cross:`✗`,warning:`⚠`};var gn=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=(0,D.createInterface)({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(){e.v();let t=process.stdout.columns||80;this.renderHeader(t),this.renderProgressBar(t),this.renderCurrentConflict(t),this.renderControls(t)}renderHeader(t){let n=this.connectorId,r=`${this.localVersion} ${$.arrow} ${this.remoteVersion}`,a=Math.max(0,t-17),o=Math.floor(a/2),s=a-o,c=` `.repeat(o)+`CONFLICT RESOLVER`+` `.repeat(s);e.w.log(``),e.w.log(i.default.bgBlue.white.bold(c)),e.w.log(i.default.gray(this.centerText(n,t))),e.w.log(i.default.gray(this.centerText(r,t))),e.w.log(``)}renderProgressBar(t){let n=this.conflicts.filter(e=>e.conflict.type===`conflict`),r=this.getCurrentConflictIndex(),a=n.map((e,t)=>{let n=t===r,a,o;switch(e.choice){case`remote`:a=n?$.current:$.acceptRemote,o=i.default.green;break;case`local`:a=n?$.current:$.acceptLocal,o=i.default.yellow;break;case`both`:a=n?$.current:$.acceptBoth,o=i.default.cyan;break;default:a=n?$.current:$.pending,o=n?i.default.white:i.default.gray}return o(a)}),o=n.filter(e=>e.choice!==`pending`).length,s=` Conflict ${r+1} of ${this.totalConflicts} • ${o}/${this.totalConflicts} resolved `;e.w.log(i.default.gray(this.centerText(s,t))),e.w.log(this.centerText(a.join(` `),t)),e.w.log(``)}renderCurrentConflict(t){let n=this.conflicts[this.currentIndex];if(!n||n.conflict.type!==`conflict`)return;let r=n.conflict;if(e.w.log(i.default.gray(`_`.repeat(t))),e.w.log(`
|
|
158
158
|
|
|
159
159
|
`),r.local){let t=n.choice===`local`||n.choice===`both`?i.default.yellow.bold(`${$.check} LOCAL (keeping)`):i.default.red.bold(`${$.cross} LOCAL (removing)`),a=r.local.split(`
|
|
@@ -167,9 +167,9 @@ Available skills
|
|
|
167
167
|
`),l=a.length>20?`\n${i.default.gray(`... and ${a.length-20} more lines`)}`:``;e.w.log(`${t}\n\n${c}${l}`)}e.w.log(`
|
|
168
168
|
|
|
169
169
|
`),e.w.log(i.default.gray(`_`.repeat(t))),e.w.log(``)}renderControls(t){let n=[i.default.green(`[R] Accept Remote`),i.default.yellow(`[L] Keep Local`),i.default.cyan(`[B] Keep Both`),i.default.gray(`[U] Undo`)],r=[i.default.gray(`[←/→] Navigate`),i.default.gray(`[A] Accept all remaining`)],a=this.allResolved()?[i.default.green.bold(`[Enter] Apply Changes`),i.default.gray(`[Esc] Cancel`)]:[i.default.gray(`[Enter] Next Unresolved`),i.default.gray(`[Esc] Cancel`)];e.w.log(this.centerText(n.join(` `),t)),e.w.log(``),e.w.log(this.centerText(r.join(` `),t)),e.w.log(``),e.w.log(this.centerText(a.join(` `),t)),this.allResolved()&&(e.w.log(``),e.w.log(i.default.green.bold(this.centerText(`✓ All conflicts resolved!`,t))))}renderFinalSummary(){e.v();let t=this.conflicts.filter(e=>e.conflict.type===`conflict`),n=0,r=0,a=0;for(let e of t)switch(e.choice){case`remote`:n++;break;case`local`:r++;break;case`both`:a++;break}let o=[i.default.green.bold(`Conflict resolution complete`),``,`${i.default.bold(this.totalConflicts)} conflicts resolved:`,``,`${i.default.green($.acceptRemote)} Accepted remote: ${n}`,`${i.default.yellow($.acceptLocal)} Kept local: ${r}`,`${i.default.cyan($.acceptBoth)} Kept both: ${a}`];e.w.box(o.join(`
|
|
170
|
-
`))}renderCancelled(){e.v(),e.w.log(i.default.yellow(`Conflict resolution cancelled`)),e.w.log(``),e.w.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 _n=`https://api.stackone.com`,vn=3;var yn=class{async execute({profile:t,connector:n,outputPath:r,apiUrl:a,apiKey:o,owner:s}={}){if((0,C.isMissing)(n)&&(e.w.error(`Connector identifier is required`),e.w.log(`Please provide a connector identifier using the ${e.C(`--connector`)} option in the format: ${e.C(`provider_key@version`)} or ${e.C(`provider_key`)}`),e.w.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!t&&!o&&(e.w.error(`Profile or API key is required`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),t&&o&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&a&&e.w.warn(`Specifying ${e.C(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!tn(t)){e.w.error(`Configuration profile ${e.C(t)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let n=rn();n.length>0&&(e.w.info(`Available configuration profiles:`),n.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let c=t?en(t):{apiUrl:a??_n,apiKey:o};c?.apiKey||(e.w.error(`API key is missing`),e.w.log(`Please provide a valid API key in the profile or via the ${e.C(`--api-key`)} option.`),process.exit(1));let l=c.apiUrl??_n,[u,d]=n.split(`@`),f=await this.#f(u,l,c.apiKey,d??`latest`,s),p=this.#e(f),m=p.version??`unknown`,h=this.#t(r,p.key,m),g=this.#r(h),_=g===null,v=f;if(!_){let t=this.#i(g,h);t&&(e.w.warn(t.message),t.errors.length>0&&e.y(t.errors,!1),e.w.log(``));let r=t?void 0:this.#e(g);if(this.#o(g,f)){this.#a(g,f,h);let t=r?.version??`unknown`,i=await this.#s(g,f,n,t,m);i.action===`cancel`&&((0,w.cancel)(`Pull cancelled`),process.exit(0)),i.action===`keep-local`&&(e.w.log(``),e.w.info(`Keeping local version. No changes made.`),process.exit(0)),i.action===`interactive-cancel`&&process.exit(0),i.action===`interactive`&&(v=i.resolvedContent)}else e.w.info(`No changes detected in connector configuration.`),process.exit(0)}let y=(0,T.validateYamlConnector)(v).connector,b=y?.key??p.key,x=y?.version??m,S=this.#t(r,b,x),E=S;if(S!==h){let t=await this.#n(S);e.w.log(``),t!==void 0&&(E=t)}await this.#d(E,v),_?e.w.success(`Connector ${e.C(b)}@${e.C(x)} pulled successfully (new connector)`):e.w.success(`Connector ${e.C(b)}@${e.C(x)} updated successfully`);let
|
|
170
|
+
`))}renderCancelled(){e.v(),e.w.log(i.default.yellow(`Conflict resolution cancelled`)),e.w.log(``),e.w.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 _n=`https://api.stackone.com`,vn=3;var yn=class{async execute({profile:t,connector:n,outputPath:r,apiUrl:a,apiKey:o,owner:s}={}){if((0,C.isMissing)(n)&&(e.w.error(`Connector identifier is required`),e.w.log(`Please provide a connector identifier using the ${e.C(`--connector`)} option in the format: ${e.C(`provider_key@version`)} or ${e.C(`provider_key`)}`),e.w.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!t&&!o&&(e.w.error(`Profile or API key is required`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),t&&o&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&a&&e.w.warn(`Specifying ${e.C(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!tn(t)){e.w.error(`Configuration profile ${e.C(t)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let n=rn();n.length>0&&(e.w.info(`Available configuration profiles:`),n.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let c=t?en(t):{apiUrl:a??_n,apiKey:o};c?.apiKey||(e.w.error(`API key is missing`),e.w.log(`Please provide a valid API key in the profile or via the ${e.C(`--api-key`)} option.`),process.exit(1));let l=c.apiUrl??_n,[u,d]=n.split(`@`),f=await this.#f(u,l,c.apiKey,d??`latest`,s),p=this.#e(f),m=p.version??`unknown`,h=this.#t(r,p.key,m),g=this.#r(h),_=g===null,v=f;if(!_){let t=this.#i(g,h);t&&(e.w.warn(t.message),t.errors.length>0&&e.y(t.errors,!1),e.w.log(``));let r=t?void 0:this.#e(g);if(this.#o(g,f)){this.#a(g,f,h);let t=r?.version??`unknown`,i=await this.#s(g,f,n,t,m);i.action===`cancel`&&((0,w.cancel)(`Pull cancelled`),process.exit(0)),i.action===`keep-local`&&(e.w.log(``),e.w.info(`Keeping local version. No changes made.`),process.exit(0)),i.action===`interactive-cancel`&&process.exit(0),i.action===`interactive`&&(v=i.resolvedContent)}else e.w.info(`No changes detected in connector configuration.`),process.exit(0)}let y=(0,T.validateYamlConnector)(v).connector,b=y?.key??p.key,x=y?.version??m,S=this.#t(r,b,x),E=S;if(S!==h){let t=await this.#n(S);e.w.log(``),t!==void 0&&(E=t)}await this.#d(E,v),_?e.w.success(`Connector ${e.C(b)}@${e.C(x)} pulled successfully (new connector)`):e.w.success(`Connector ${e.C(b)}@${e.C(x)} updated successfully`);let D=b===p.key?e.C(b):`${e.C(p.key)} ${i.default.whiteBright(`→`)} ${e.C(b)}`,ee=x===m?e.C(x):`${e.C(m)} ${i.default.whiteBright(`→`)} ${e.C(x)}`,O=E===h?e.C(E):`${e.C(h)}\n ${i.default.whiteBright(`→`)} ${e.C(E)}`;e.w.log(`\n${i.default.blue.inverse(` CONNECTOR DETAILS `)}\n`),e.w.log(` Provider: ${D}`),e.w.log(` Version: ${ee}`),e.w.log(` Output file: ${O}`),process.exit(0)}#e(t){let n=(0,T.validateYamlConnector)(t),r=n?.errors??[];if(n.success)return n.connector;e.w.error(`Connector pulled from the registry is not valid`),e.w.log(`Please make sure you are using the latest version of the StackOne CLI by running ${e.C(`stackone update`)}`),r.length>0&&e.y(r,!0),process.exit(1)}#t(t,n,r){let i=`${n}_v${r.replaceAll(`.`,`-`)}.s1.yaml`;return t?(m.default.existsSync(t)&&(m.default.statSync(t).isDirectory()||(e.w.error(`Output path ${e.C(t)} is not a directory`),e.w.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),h.default.resolve(t,n,i)):h.default.resolve(process.cwd(),`connectors`,n,i)}async#n(t){if(!m.default.existsSync(t))return;let n=h.default.basename(t),r=h.default.dirname(t);e.w.warn(`File ${e.C(n)} already exists at ${e.C(r)}`);let i=await(0,w.select)({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(((0,w.isCancel)(i)||i===`cancel`)&&((0,w.cancel)(`Operation cancelled. No local changes were made.`),process.exit(0)),i===`override`)return;let a=await(0,w.text)({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=h.default.join(r,e.trim());if(m.default.existsSync(t))return`File ${e} already exists`}});return(0,w.isCancel)(a)&&((0,w.cancel)(`Operation cancelled. No local changes were made.`),process.exit(0)),h.default.join(r,a.trim())}#r(e){if(!m.default.existsSync(e))return null;try{return m.default.readFileSync(e,`utf-8`)}catch{return null}}#i(t,n){try{let r=(0,T.validateYamlConnector)(t);if(!r.success){let t=r.errors??[];return{message:`Local connector ${e.C(h.default.basename(n))} has validation errors:`,errors:t}}}catch(t){return{message:`Local connector ${e.C(h.default.basename(n))} could not be validated: ${t.message}`,errors:[]}}return null}#a(t,n,r){let a=(0,E.diffLines)(t,n);if(!a.some(e=>e.added||e.removed)){e.w.info(`No changes detected in connector configuration.`);return}e.w.log(`${i.default.blue.inverse(` CHANGES `)}\n`),e.w.log(i.default.gray(`--- local: ${r}`)),e.w.log(i.default.gray(`+++ remote: StackOne Registry`)),e.w.log(``);let o=0,s=0;for(let t of a){let n=t.value.split(`
|
|
171
171
|
`).filter(e=>e!==``);if(t.added){o+=n.length;for(let t of n)e.w.log(i.default.green(`+ ${t}`))}else if(t.removed){s+=n.length;for(let t of n)e.w.log(i.default.red(`- ${t}`))}else if(n.length<=6)for(let t of n)e.w.log(i.default.gray(` ${t}`));else{for(let t=0;t<3;t++)e.w.log(i.default.gray(` ${n[t]}`));e.w.log(i.default.gray(` ... (${n.length-6} unchanged lines)`));for(let t=n.length-3;t<n.length;t++)e.w.log(i.default.gray(` ${n[t]}`))}}e.w.log(``),e.w.log(i.default.gray(`Summary: ${i.default.green(`+${o}`)} additions, ${i.default.red(`-${s}`)} deletions`))}#o(e,t){return(0,E.diffLines)(e,t).some(e=>e.added||e.removed)}async#s(t,n,r,i,a){e.w.log(``);let o=await(0,w.select)({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((0,w.isCancel)(o))return{action:`cancel`};if(o===`override`)return{action:`override`};if(o===`keep-local`)return{action:`keep-local`};if(o===`interactive`){let e=await this.#c(t,n,r,i,a);return e===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:e}}return{action:`cancel`}}async#c(t,n,r,i,a){let o=(0,E.diffLines)(t,n),s=this.#u(o);if(s.length===0)return e.w.info(`No conflicts to resolve.`),n;let c=new gn(s,r,i,a);for(;;){if((await c.resolve()).cancelled)return null;let t=c.getResolvedContent(),n=(0,T.validateYamlConnector)(t);if(n.success)return c.renderFinalSummary(),t;let r=await this.#l(n.errors);if(r===`cancel`)return e.v(),e.w.info(`Operation cancelled. No changes were made to the local connector.`),null;if(r===`save`)return e.v(),e.w.warn(`The connector was saved but it is invalid`),t;c.resetForReResolution()}}async#l(t){let{createInterface:n}=await import(`readline`);return new Promise(r=>{e.v();let a=(t||[{message:`Unknown validation error`}]).map(e=>` • ${e.message}`).join(`
|
|
172
|
-
`);e.w.box({title:`⚠️ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${a}`,style:{borderColor:`yellow`,padding:1}}),e.w.log(``),e.w.log(i.default.bold(` Choose an action:`)),e.w.log(``),e.w.log(i.default.cyan(` [B]`)+` ← Go back to conflict resolution`),e.w.log(i.default.dim(` Modify your choices to fix the validation errors`)),e.w.log(``),e.w.log(i.default.yellow(` [S]`)+` 💾 Save anyway`),e.w.log(i.default.dim(` Save the invalid configuration (not recommended)`)),e.w.log(``),e.w.log(i.default.red(` [C]`)+` ✖ Cancel`),e.w.log(i.default.dim(` Discard all changes`)),e.w.log(``);let o=n({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let s=e=>{let t=e.toString().toLowerCase(),n=()=>{process.stdin.removeListener(`data`,s),process.stdin.isTTY&&process.stdin.setRawMode(!1),o.close()};if(t===``||t===`\x1B`){n(),r(`cancel`);return}switch(t){case`b`:n(),r(`back`);break;case`s`:n(),r(`save`);break;case`c`:case`q`:n(),r(`cancel`);break}};process.stdin.on(`data`,s)})}#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(t,n){let r=h.default.dirname(t);m.default.existsSync(r)||m.default.mkdirSync(r,{recursive:!0});try{m.default.writeFileSync(t,n,`utf-8`)}catch(n){e.w.error(`Failed to write connector to file ${e.C(t)}: ${n.message}`),process.exit(1)}}async#f(t,n,r,i,a){let o=(0,v.default)(`Pulling connector ${e.C(t)}@${e.C(i)} from registry...`).start();try{let s=Buffer.from(r).toString(`base64`),c=`${n}/registry/connectors/${t}@${i}${a?`?owner=${encodeURIComponent(a)}`:``}`,l=await fetch(c,{method:`GET`,headers:{Authorization:`Basic ${s}`}});if(o.stop(),l.status===409){a&&(await this.#p(l,t,i),process.exit(1));let r=(await l.json()).availableOwners??[],c=await cn(`${t}@${i}`,r);o.text=`Pulling connector ${e.C(t)}@${e.C(i)} from registry...`,o.start();let u=`${n}/registry/connectors/${t}@${i}`,d=await fetch(`${u}?owner=${encodeURIComponent(c)}`,{method:`GET`,headers:{Authorization:`Basic ${s}`}});return o.stop(),d.ok||(await this.#p(d,t,i),process.exit(1)),await d.text()}return l.ok||(await this.#p(l,t,i),process.exit(1)),await l.text()}catch(r){o.stop(),e.w.error(`Failed to pull connector ${e.C(t)}@${e.C(i)} from the registry: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid.`),process.exit(1)}}async#p(t,n,r){switch(t.status){case 401:case 403:e.w.error(`Access denied`),e.w.log(`Please ensure that your API key is valid and has the ${e.C(`connectors:read`)} scope required to pull connectors.`);break;case 404:e.w.error(`Connector ${e.C(n)}@${e.C(r)} was not found in the registry`),await this.#m(n);break;case 429:e.w.error(`Rate limit exceeded`),e.w.log(`Too many requests. Please wait a moment before trying again.`);break;default:await e.x(t,`Failed to pull connector ${e.C(n)}`)}}async#m(t){e.w.info(`To see available versions, check the connector documentation or contact support.`)}};const bn=`https://api.stackone.com`;var xn=class{async execute({profile:t,fileOrDir:n,apiUrl:r,apiKey:a,force:o}={}){if(!t&&!a&&(e.w.error(`Profile or API key is required`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),t&&a&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&r&&e.w.warn(`Specifying ${e.C(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!tn(t)){e.w.error(`Configuration profile ${e.C(t)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let n=rn();n.length>0&&(e.w.info(`Available configuration profiles:`),n.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let s=t?en(t):{apiUrl:r??bn,apiKey:a};s?.apiKey||(e.w.error(`API key is missing`),e.w.log(`Please provide a valid API key in the profile or via the ${e.C(`--api-key`)} option.`),process.exit(1)),n||(e.w.error(`File or directory is required.`),process.exit(1));try{(0,m.statSync)(n)}catch{e.w.error(`File or directory not found: ${i.default.red(n)}`),process.exit(1)}let c=(0,m.statSync)(n),l=s.apiUrl??bn;if(c.isDirectory()){let t=On(n),r=0;t.length===0?(e.w.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(e.w.start(`Found ${t.length} connector(s) file(s). Pushing to registry...`),e.w.log(``));for(let e of t)await this.uploadFile(e,l,s.apiKey,o)&&r++;r===0?e.w.error(`Error while pushing connectors: no files were uploaded`):(e.w.log(``),e.w.info(`Upload completed: ${i.default.green(r)} of ${i.default.blue(t.length)} file(s) uploaded successfully.`)),process.exit(r>0?0:1)}else n.endsWith(`.s1.yaml`)||(e.w.error(`Only ${e.C(`.s1.yaml`)} files are supported for upload`),process.exit(1));let u=await this.uploadFile(n,l,s.apiKey,o);process.exit(u?0:1)}async uploadFile(t,n,r,i){let a=(0,v.default)(`📤 Pushing connector in ${(0,h.basename)(t)}...`).start();try{let o=Dn(t);if(!o)return!1;let s=(0,h.basename)(t),c=new FormData,l=new Blob([o],{type:`application/x-yaml`});c.append(`file`,l,s),i&&c.append(`force`,`true`);let u=Buffer.from(r).toString(`base64`),d=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${u}`},body:c});if(a.stop(),!d.ok)return d.status===409||d.status===422?await this.handleVersionConflict(d,t,n,r,i):(await e.x(d,`Failed to push connector in ${e.C(s)} to the registry`),!1);let f=await d.json();return e.w.success(`Successfully uploaded ${e.C(s)} with connector ${e.C(f.provider)}@${e.C(f.version)}`),!0}catch(r){return a.stop(),e.w.error(`Failed to upload file ${e.C(t)}: ${r}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),!1}}async handleVersionConflict(t,n,r,i,a){let o=Sn(t.status,a);o&&e.w.warn(o);let s=await t.text(),c;try{c=JSON.parse(s)}catch{}let l=D.default.valid(c?.latestVersion);if(!l)return await e.x(new Response(s,{status:t.status,statusText:t.statusText}),`Failed to push connector in ${e.C((0,h.basename)(n))} to the registry`),!1;let u=(0,m.readFileSync)(n,`utf-8`),d=Cn(u),f=d?`${e.C(d)}`:``,p=t.status===409?`Version ${f} already exists in the registry. Latest version: ${e.C(l)}`:`Version ${f} is lower than the latest version in the registry. Latest version: ${e.C(l)}`;e.w.error(p);let g=D.default.inc(l,`patch`)??l,_=D.default.inc(l,`minor`)??l,v=D.default.inc(l,`major`)??l,y=await(0,w.select)({message:`How would you like to proceed?`,options:[{value:g,label:`Bump patch version (${g})`},{value:_,label:`Bump minor version (${_})`},{value:v,label:`Bump major version (${v})`},{value:`cancel`,label:`Cancel push`}]});return(0,w.isCancel)(y)||y===`cancel`?((0,w.cancel)(`Push cancelled`),!1):((0,m.writeFileSync)(n,wn(u,y),`utf-8`),e.w.info(`Updated version to ${e.C(y)} in ${(0,h.basename)(n)}`),this.uploadFile(n,r,i,a))}};const Sn=(t,n)=>!n||t!==409?null:`${e.C(`--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.`,Cn=e=>e.match(/^\s*version: (\S+)/m)?.[1],wn=(e,t)=>e.replace(/^(\s*version: )\S+/m,`$1${t}`),Tn=e=>{try{let t=(0,T.parseYamlConnector)(e);return t.changelog?.summary?.trim()?null:`has no changelog entry for version ${t.version}`}catch{return null}},En=()=>{e.w.log(`Every published version must record what changed. Add an ${e.C(`info.changelog`)} block:`),e.w.log(``),e.w.log(i.default.gray(` info:`)),e.w.log(i.default.gray(` changelog:`)),e.w.log(i.default.gray(` summary: What changed in this version.`)),e.w.log(i.default.gray(` labels: [new-actions] # optional, one of: ${te.ChangelogLabels.join(`, `)}`)),e.w.log(``)},Dn=t=>{let n=(0,T.loadConnector)(t),r=(0,T.validateYamlConnector)(n),i=r?.errors??[];if(r.success){let r=Tn(n);if(r){e.w.error(`Connector in ${e.S(t)} ${r}`),En();return}return n}else i.length>0?(e.w.error(`Connector in ${e.S(t)} is not valid`),e.y(i,!0)):e.w.error(`Connector in ${e.S(t)} is not valid. Please check the file for errors.`)},On=e=>{let t=[],n=(0,m.readdirSync)(e,{withFileTypes:!0});for(let r of n){let n=(0,h.join)(e,r.name);r.isDirectory()?t.push(...On(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},kn=C.z.object({provider_key:C.z.string().optional(),provider_version:C.z.string().optional(),auth_config_key:C.z.string(),environment:C.z.string().default(`production`),organization_id:C.z.string().default(`cli-organization-id`),account_id:C.z.string().default(`cli-account-secure-id`),project_id:C.z.string().default(`cli-project-secure-id`),credentials:C.z.record(C.z.string(),C.z.any()).default({})}),An=C.z.record(C.z.string(),C.z.any()),jn=C.z.object({path:C.z.record(C.z.string(),C.z.any()).default({}),queryParams:C.z.record(C.z.string(),C.z.any()).default({}),header:C.z.record(C.z.string(),C.z.any()).default({}),body:C.z.record(C.z.string(),C.z.any()).default({})}),Mn=`https://api.stackone.com`;var Nn=class{async execute({connector:t,action:n,actionId:r,account:a,accountId:o,params:s,credentials:c,profile:l,outputFile:u,debug:d,apiUrl:f,apiKey:p,owner:h}={}){if(!l&&!p&&o&&(e.w.error(`Profile or API key is required when providing an account ID`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),l&&p&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),l&&f&&e.w.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),l&&!tn(l)){e.w.error(`Configuration profile ${e.C(l)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let t=rn();t.length>0&&(e.w.info(`Available configuration profiles:`),t.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let g=l?en(l):{apiUrl:f??Mn,apiKey:p};(0,C.isMissing)(a)&&(0,C.isMissing)(o)&&(e.w.error(`A valid account or account ID is required to run an action`),process.exit(1));let _;if((0,C.notMissing)(t))if(this.#a(t)){!l&&!p&&(e.w.error(`Profile or API key is required when using a connector identifier`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.`),process.exit(1));let n=this.#o(t);_=await this.#s(n,g?.apiUrl??Mn,g?.apiKey,h)}else _=this.#e(t);else (0,C.notMissing)(o)&&(_=await this.#c(o,g?.apiUrl??Mn,g?.apiKey));let v=(0,C.notMissing)(n)?this.#r(n,t):_;(0,C.isMissing)(v)&&(e.w.error(`A valid connector is required to run an action.`),process.exit(1));let y=(0,C.notMissing)(v?.actions)?Object.keys(v?.actions).length:0,b=(0,C.notMissing)(v?.actions)?Object.keys(v.actions)[y-1]:void 0,x=(0,C.notMissing)(b)?v?.actions?.[b]?.id:void 0,S=((0,C.notMissing)(r)&&!r?.startsWith(`${v.key}_`)?`${v.key}_${r}`:r)??x;(0,C.isMissing)(S)&&(e.w.error(`A valid action ID is required to run an action`),process.exit(1));let w=(0,C.notMissing)(o)?await this.#l(o,g?.apiUrl??Mn,g?.apiKey):{},T=(0,C.notMissing)(a)?this.#i(a,v.key??`unknown`,v.version??`unknown`):void 0,E=(0,C.notMissing)(c)?this.#u(c):{},ee={...w,...T,credentials:{...w.credentials??{},...E}};(0,C.isMissing)(ee)&&(e.w.error(`A valid account data is required to run an action.`),process.exit(1));let te=v.actions?.[S];(0,C.isMissing)(te)&&(e.w.error(`Action ID ${e.C(S)} not found in the connector ${e.C(v.key)}@${e.C(v.version)}.`),process.exit(1));let D=(0,C.notMissing)(s)?this.#d(s,S):{path:{},queryParams:{},header:{},body:{}},O=Date.now(),k=await this.#f({connector:v,actionId:S,account:ee,queryParams:{...D.queryParams,...d?{debug:`true`}:{}},pathParams:D.path,body:D.body,headers:D.header}),A=Date.now()-O;if((0,C.notMissing)(u))try{m.default.writeFileSync(u,JSON.stringify(k.output,null,2),`utf-8`),e.w.info(`Output written to file: ${u}`)}catch(t){e.w.error(`Failed to write output to file ${u}: ${t.message}`),process.exit(1)}else e.w.log(`\n${i.default.blue.inverse(` ACTION OUTPUT `)}`),e.b(k.output);e.w.log(``),e.w.info(`Action ${e.C(S)} from connector ${e.C(v?.key)}@${e.C(v?.version)} finished in ${i.default.yellowBright((A/1e3).toFixed(2))} seconds.`),process.exit(0)}#e=e=>{let t=e;try{t=(0,T.loadConnector)(e)}catch{}return t?this.#n(t):void 0};#t=t=>{try{return(0,T.loadConnector)(t)}catch(n){e.w.error(`Failed to load connector file from ${e.C(t)}: ${n.message}`),process.exit(1)}};#n=t=>{let n=(0,T.validateYamlConnector)(t),r=n?.errors??[];if(n.success)return n.connector||(e.w.error(`Failed to load connector.`),process.exit(1)),n.connector;r.length>0?(e.w.error(`Connector is not valid`),e.y(r,!0),process.exit(1)):(e.w.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#r=(t,n)=>{let r=t;try{r=m.default.readFileSync(t,`utf-8`)}catch{}(0,C.isMissing)(n)&&(e.w.error(`A valid connector is required to load an action.`),process.exit(1));let i=`${this.#t(n)} - ${r.split(`
|
|
172
|
+
`);e.w.box({title:`⚠️ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${a}`,style:{borderColor:`yellow`,padding:1}}),e.w.log(``),e.w.log(i.default.bold(` Choose an action:`)),e.w.log(``),e.w.log(i.default.cyan(` [B]`)+` ← Go back to conflict resolution`),e.w.log(i.default.dim(` Modify your choices to fix the validation errors`)),e.w.log(``),e.w.log(i.default.yellow(` [S]`)+` 💾 Save anyway`),e.w.log(i.default.dim(` Save the invalid configuration (not recommended)`)),e.w.log(``),e.w.log(i.default.red(` [C]`)+` ✖ Cancel`),e.w.log(i.default.dim(` Discard all changes`)),e.w.log(``);let o=n({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let s=e=>{let t=e.toString().toLowerCase(),n=()=>{process.stdin.removeListener(`data`,s),process.stdin.isTTY&&process.stdin.setRawMode(!1),o.close()};if(t===``||t===`\x1B`){n(),r(`cancel`);return}switch(t){case`b`:n(),r(`back`);break;case`s`:n(),r(`save`);break;case`c`:case`q`:n(),r(`cancel`);break}};process.stdin.on(`data`,s)})}#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(t,n){let r=h.default.dirname(t);m.default.existsSync(r)||m.default.mkdirSync(r,{recursive:!0});try{m.default.writeFileSync(t,n,`utf-8`)}catch(n){e.w.error(`Failed to write connector to file ${e.C(t)}: ${n.message}`),process.exit(1)}}async#f(t,n,r,i,a){let o=(0,v.default)(`Pulling connector ${e.C(t)}@${e.C(i)} from registry...`).start();try{let s=Buffer.from(r).toString(`base64`),c=`${n}/registry/connectors/${t}@${i}${a?`?owner=${encodeURIComponent(a)}`:``}`,l=await fetch(c,{method:`GET`,headers:{Authorization:`Basic ${s}`}});if(o.stop(),l.status===409){a&&(await this.#p(l,t,i),process.exit(1));let r=(await l.json()).availableOwners??[],c=await cn(`${t}@${i}`,r);o.text=`Pulling connector ${e.C(t)}@${e.C(i)} from registry...`,o.start();let u=`${n}/registry/connectors/${t}@${i}`,d=await fetch(`${u}?owner=${encodeURIComponent(c)}`,{method:`GET`,headers:{Authorization:`Basic ${s}`}});return o.stop(),d.ok||(await this.#p(d,t,i),process.exit(1)),await d.text()}return l.ok||(await this.#p(l,t,i),process.exit(1)),await l.text()}catch(r){o.stop(),e.w.error(`Failed to pull connector ${e.C(t)}@${e.C(i)} from the registry: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid.`),process.exit(1)}}async#p(t,n,r){switch(t.status){case 401:case 403:e.w.error(`Access denied`),e.w.log(`Please ensure that your API key is valid and has the ${e.C(`connectors:read`)} scope required to pull connectors.`);break;case 404:e.w.error(`Connector ${e.C(n)}@${e.C(r)} was not found in the registry`),await this.#m(n);break;case 429:e.w.error(`Rate limit exceeded`),e.w.log(`Too many requests. Please wait a moment before trying again.`);break;default:await e.x(t,`Failed to pull connector ${e.C(n)}`)}}async#m(t){e.w.info(`To see available versions, check the connector documentation or contact support.`)}};const bn=`https://api.stackone.com`;var xn=class{async execute({profile:t,fileOrDir:n,apiUrl:r,apiKey:a,force:o}={}){if(!t&&!a&&(e.w.error(`Profile or API key is required`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),t&&a&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),t&&r&&e.w.warn(`Specifying ${e.C(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),t&&!tn(t)){e.w.error(`Configuration profile ${e.C(t)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let n=rn();n.length>0&&(e.w.info(`Available configuration profiles:`),n.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let s=t?en(t):{apiUrl:r??bn,apiKey:a};s?.apiKey||(e.w.error(`API key is missing`),e.w.log(`Please provide a valid API key in the profile or via the ${e.C(`--api-key`)} option.`),process.exit(1)),n||(e.w.error(`File or directory is required.`),process.exit(1));try{(0,m.statSync)(n)}catch{e.w.error(`File or directory not found: ${i.default.red(n)}`),process.exit(1)}let c=(0,m.statSync)(n),l=s.apiUrl??bn;if(c.isDirectory()){let t=On(n),r=0;t.length===0?(e.w.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(e.w.start(`Found ${t.length} connector(s) file(s). Pushing to registry...`),e.w.log(``));for(let e of t)await this.uploadFile(e,l,s.apiKey,o)&&r++;r===0?e.w.error(`Error while pushing connectors: no files were uploaded`):(e.w.log(``),e.w.info(`Upload completed: ${i.default.green(r)} of ${i.default.blue(t.length)} file(s) uploaded successfully.`)),process.exit(r>0?0:1)}else n.endsWith(`.s1.yaml`)||(e.w.error(`Only ${e.C(`.s1.yaml`)} files are supported for upload`),process.exit(1));let u=await this.uploadFile(n,l,s.apiKey,o);process.exit(u?0:1)}async uploadFile(t,n,r,i){let a=(0,v.default)(`📤 Pushing connector in ${(0,h.basename)(t)}...`).start();try{let o=Dn(t);if(!o)return!1;let s=(0,h.basename)(t),c=new FormData,l=new Blob([o],{type:`application/x-yaml`});c.append(`file`,l,s),i&&c.append(`force`,`true`);let u=Buffer.from(r).toString(`base64`),d=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${u}`},body:c});if(a.stop(),!d.ok)return d.status===409||d.status===422?await this.handleVersionConflict(d,t,n,r,i):(await e.x(d,`Failed to push connector in ${e.C(s)} to the registry`),!1);let f=await d.json();return e.w.success(`Successfully uploaded ${e.C(s)} with connector ${e.C(f.provider)}@${e.C(f.version)}`),!0}catch(r){return a.stop(),e.w.error(`Failed to upload file ${e.C(t)}: ${r}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),!1}}async handleVersionConflict(t,n,r,i,a){let o=Sn(t.status,a);o&&e.w.warn(o);let s=await t.text(),c;try{c=JSON.parse(s)}catch{}let l=O.default.valid(c?.latestVersion);if(!l)return await e.x(new Response(s,{status:t.status,statusText:t.statusText}),`Failed to push connector in ${e.C((0,h.basename)(n))} to the registry`),!1;let u=(0,m.readFileSync)(n,`utf-8`),d=Cn(u),f=d?`${e.C(d)}`:``,p=t.status===409?`Version ${f} already exists in the registry. Latest version: ${e.C(l)}`:`Version ${f} is lower than the latest version in the registry. Latest version: ${e.C(l)}`;e.w.error(p);let g=O.default.inc(l,`patch`)??l,_=O.default.inc(l,`minor`)??l,v=O.default.inc(l,`major`)??l,y=await(0,w.select)({message:`How would you like to proceed?`,options:[{value:g,label:`Bump patch version (${g})`},{value:_,label:`Bump minor version (${_})`},{value:v,label:`Bump major version (${v})`},{value:`cancel`,label:`Cancel push`}]});return(0,w.isCancel)(y)||y===`cancel`?((0,w.cancel)(`Push cancelled`),!1):((0,m.writeFileSync)(n,wn(u,y),`utf-8`),e.w.info(`Updated version to ${e.C(y)} in ${(0,h.basename)(n)}`),this.uploadFile(n,r,i,a))}};const Sn=(t,n)=>!n||t!==409?null:`${e.C(`--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.`,Cn=e=>e.match(/^\s*version: (\S+)/m)?.[1],wn=(e,t)=>e.replace(/^(\s*version: )\S+/m,`$1${t}`),Tn=e=>{try{let t=(0,T.parseYamlConnector)(e);return t.changelog?.summary?.trim()?null:`has no changelog entry for version ${t.version}`}catch{return null}},En=()=>{e.w.log(`Every published version must record what changed. Add an ${e.C(`info.changelog`)} block:`),e.w.log(``),e.w.log(i.default.gray(` info:`)),e.w.log(i.default.gray(` changelog:`)),e.w.log(i.default.gray(` summary: What changed in this version.`)),e.w.log(i.default.gray(` labels: [new-actions] # optional, one of: ${ee.ChangelogLabels.join(`, `)}`)),e.w.log(``)},Dn=t=>{let n=(0,T.loadConnector)(t),r=(0,T.validateYamlConnector)(n),i=r?.errors??[];if(r.success){let r=Tn(n);if(r){e.w.error(`Connector in ${e.S(t)} ${r}`),En();return}return n}else i.length>0?(e.w.error(`Connector in ${e.S(t)} is not valid`),e.y(i,!0)):e.w.error(`Connector in ${e.S(t)} is not valid. Please check the file for errors.`)},On=e=>{let t=[],n=(0,m.readdirSync)(e,{withFileTypes:!0});for(let r of n){let n=(0,h.join)(e,r.name);r.isDirectory()?t.push(...On(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},kn=(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.`}}},An=e=>({path:e.path,query:e.queryParams,headers:e.header,body:e.body}),jn=e=>({pathParams:e.path??{},queryParams:e.query??{},headers:e.headers??{},body:e.body??{}}),Mn=(e,t)=>{switch(e.type){case`time_filter`:return{kind:`timestamp`,value:t};case`delta_token`:return{kind:`cursor`,value:t}}},Nn=(e,t,n)=>{let{in:r,key:i}=e.iterator;return Pn(n[r])[i]===t.value},Pn=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},Fn=2e3;var In=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 Ln=async({dataSyncConfig:e,baseInputs:t,checkpointIn:n,callAction:r,maxPages:i,runStartTime:a,onPage:o})=>{let s=e.incremental?(0,T.createIncrementalStrategy)(e.incremental):null,c=s?s.applyToInputs({baseInputs:t,checkpoint:n}):t,l=e.incremental&&n?Nn(e.incremental,n,c):null,u=e.pagination?(0,T.createPaginator)(e.pagination,{baseInputs:c}):null,d=Math.min(i,Fn),f=[],p=[],m=[],h=null,g=0,_=null,v=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 v(`maxIterations`);let t=h??u?.computeNextInputs({previousResponse:void 0,currentIteration:g})??c,n=await r(t);if(g++,n.response?.successful!==!0)throw new In({iteration:g,statusCode:n.response?.statusCode,providerMessage:n.response?.message,providerData:n.response?.data,inputs:t,pagesCompleted:g-1,recordsCollected:f.length});let i=(0,T.extractItems)(n,e),a=(0,C.getContentHash)(i),l=u?u.isExhausted(n,g):!0,y=s?.extractFromPage({block:n,items:i,isFinalPage:l})??null,b={iteration:g,inputs:t,itemCount:i.length,statusCode:n.response?.statusCode,exhausted:l,extractedCheckpoint:y};if(p.push(b),o?.(b),y){let e=m.findIndex(e=>e.kind===y.kind&&e.value===y.value);e!==-1&&m.splice(e,1),m.push(y)}if(_!==null&&a===_)return v(`duplicatePage`);if(f.push(...i),_=a,l)return v(`exhausted`);h=u?.computeNextInputs({previousResponse:n,currentIteration:g})}},Rn=(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`}},zn=(e,t)=>Math.min(t??e.maxPages??Fn,Fn),Bn=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 Ln({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`,Mn(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`}},Vn=({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:(0,ee.computeDataSyncFingerprint)(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}},Hn=(e,t)=>{let n=[],{incremental:r}=t;for(let r of e.phases)n.push(...Un(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 ${Gn(t)}; every sync will refetch the whole dataset if it does not.`),n},Un=(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?Wn(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},Wn=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}},Gn=e=>{let{incremental:t}=e;return t?`${t.iterator.key} in ${t.iterator.in}`:`the incremental iterator`},Kn=C.z.object({provider_key:C.z.string().optional(),provider_version:C.z.string().optional(),auth_config_key:C.z.string(),environment:C.z.string().default(`production`),organization_id:C.z.string().default(`cli-organization-id`),account_id:C.z.string().default(`cli-account-secure-id`),project_id:C.z.string().default(`cli-project-secure-id`),credentials:C.z.record(C.z.string(),C.z.any()).default({})}),qn=C.z.record(C.z.string(),C.z.any()),Jn=C.z.object({path:C.z.record(C.z.string(),C.z.any()).default({}),queryParams:C.z.record(C.z.string(),C.z.any()).default({}),header:C.z.record(C.z.string(),C.z.any()).default({}),body:C.z.record(C.z.string(),C.z.any()).default({})}),Yn=`https://api.stackone.com`;var Xn=class{async execute({connector:t,action:n,actionId:r,account:a,accountId:o,params:s,credentials:c,profile:l,outputFile:u,debug:d,apiUrl:f,apiKey:p,owner:h,syncFull:g,syncIncremental:_,syncMaxPages:v,syncPageSize:y}={}){if(!l&&!p&&o&&(e.w.error(`Profile or API key is required when providing an account ID`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`To create a profile, run ${e.C(`stackone init`)}.`),process.exit(1)),l&&p&&(e.w.error(`Please provide either a profile or an API key, not both`),process.exit(1)),l&&f&&e.w.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),l&&!tn(l)){e.w.error(`Configuration profile ${e.C(l)} not found`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.\n`);let t=rn();t.length>0&&(e.w.info(`Available configuration profiles:`),t.forEach(t=>{e.w.log(` - ${i.default.blue(t)}`)})),process.exit(1)}let b=l?en(l):{apiUrl:f??Yn,apiKey:p};(0,C.isMissing)(a)&&(0,C.isMissing)(o)&&(e.w.error(`A valid account or account ID is required to run an action`),process.exit(1));let x;if((0,C.notMissing)(t))if(this.#s(t)){!l&&!p&&(e.w.error(`Profile or API key is required when using a connector identifier`),e.w.log(`Please provide a profile using the ${e.C(`--profile`)} option or an API key using the ${e.C(`--api-key`)} option.`),e.w.log(`Run ${e.C(`stackone init`)} to create a new configuration profile.`),process.exit(1));let n=this.#c(t);x=await this.#l(n,b?.apiUrl??Yn,b?.apiKey,h)}else x=this.#n(t);else (0,C.notMissing)(o)&&(x=await this.#u(o,b?.apiUrl??Yn,b?.apiKey));let S=(0,C.notMissing)(n)?this.#a(n,t):x;(0,C.isMissing)(S)&&(e.w.error(`A valid connector is required to run an action.`),process.exit(1));let w=(0,C.notMissing)(S?.actions)?Object.keys(S?.actions).length:0,T=(0,C.notMissing)(S?.actions)?Object.keys(S.actions)[w-1]:void 0,E=(0,C.notMissing)(T)?S?.actions?.[T]?.id:void 0,D=((0,C.notMissing)(r)&&!r?.startsWith(`${S.key}_`)?`${S.key}_${r}`:r)??E;(0,C.isMissing)(D)&&(e.w.error(`A valid action ID is required to run an action`),process.exit(1));let ee=(0,C.notMissing)(o)?await this.#d(o,b?.apiUrl??Yn,b?.apiKey):{},O=(0,C.notMissing)(a)?this.#o(a,S.key??`unknown`,S.version??`unknown`):void 0,k=(0,C.notMissing)(c)?this.#f(c):{},A={...ee,...O,credentials:{...ee.credentials??{},...k}};(0,C.isMissing)(A)&&(e.w.error(`A valid account data is required to run an action.`),process.exit(1));let j=S.actions?.[D];(0,C.isMissing)(j)&&(e.w.error(`Action ID ${e.C(D)} not found in the connector ${e.C(S.key)}@${e.C(S.version)}.`),process.exit(1));let M=(0,C.notMissing)(s)?this.#p(s,D):{path:{},queryParams:{},header:{},body:{}};if(g||_!==void 0)return this.#e({connector:S,actionId:D,action:j,account:A,baseInputs:An(M),mode:g?`full`:`incremental`,checkpointValue:typeof _==`string`&&_!==``?_:void 0,maxPagesOverride:v,pageSizeOverride:y,outputFile:u,debug:d});let N=Date.now(),P=await this.#m({connector:S,actionId:D,account:A,queryParams:{...M.queryParams,...d?{debug:`true`}:{}},pathParams:M.path,body:M.body,headers:M.header}),F=Date.now()-N;if((0,C.notMissing)(u))try{m.default.writeFileSync(u,JSON.stringify(P.output,null,2),`utf-8`),e.w.info(`Output written to file: ${u}`)}catch(t){e.w.error(`Failed to write output to file ${u}: ${t.message}`),process.exit(1)}else e.w.log(`\n${i.default.blue.inverse(` ACTION OUTPUT `)}`),e.b(P.output);e.w.log(``),e.w.info(`Action ${e.C(D)} from connector ${e.C(S?.key)}@${e.C(S?.version)} finished in ${i.default.yellowBright((F/1e3).toFixed(2))} seconds.`),process.exit(0)}async#e({connector:t,actionId:n,action:r,account:a,baseInputs:o,mode:s,checkpointValue:c,maxPagesOverride:l,pageSizeOverride:u,outputFile:d,debug:f}){let p=Rn(r,s);p.ok||(e.w.error(p.reason),process.exit(1));let{dataSyncConfig:h}=p;if((0,C.notMissing)(u)){let t=kn(h.pagination,u);t.ok||(e.w.error(`Cannot override the page size: ${t.reason}`),process.exit(1)),h={...h,pagination:t.pagination}}let g=zn(h,l);e.w.info(`Data sync ${e.C(s)} run of ${e.C(n)} — pagination ${e.C(h.pagination?.type??`none`)}${(0,C.notMissing)(u)?` (page size ${e.C(String(u))})`:``}, incremental ${e.C(h.incremental?.type??`none`)}, page cap ${e.C(String(g))}`);let _=Date.now(),v,y=new k.HttpClient;try{v=await Bn({dataSyncConfig:h,mode:s,checkpointValue:c,baseInputs:o,maxPages:g,now:()=>new Date,callAction:async e=>(0,T.runAction)({mode:`action_id`,actionId:n,account:a,connector:t,...jn(e),getHttpClient:async()=>y}),onPage:(t,n)=>{e.w.log(` ${i.default.gray(n)} page ${i.default.yellowBright(t.iteration)} — ${i.default.green(t.itemCount)} records${t.exhausted?i.default.gray(` (last)`):``}`)}})}catch(e){e instanceof In&&this.#t(e,h),this.#g(e)}let b=(Date.now()-_)/1e3,x=Hn(v,h),S={actionId:n,connector:`${t.key}@${t.version}`,dataSyncConfig:h,result:v,warnings:x};if(e.w.log(`\n${i.default.blue.inverse(` DATA SYNC SUMMARY `)}`),e.b(Vn({...S,includePages:f===!0})),(0,C.notMissing)(d))try{m.default.writeFileSync(d,JSON.stringify({...Vn({...S,includePages:!0}),records:v.phases.map(e=>e.items)},null,2),`utf-8`),e.w.info(`Records and summary written to file: ${d}`)}catch(t){e.w.error(`Failed to write output to file ${d}: ${t.message}`),process.exit(1)}x.length>0&&(e.w.log(`${i.default.yellow.inverse(` WARNINGS `)}`),x.forEach(t=>e.w.warn(t))),e.w.log(``),e.w.info(`Data sync ${e.C(s)} run finished in ${i.default.yellowBright(b.toFixed(2))} seconds. Nothing was indexed.`);let w=v.phases.some(e=>e.checkpointApplied===!1)||v.phases.some(e=>e.stoppedBy===`duplicatePage`);process.exit(w?1:0)}#t(t,n){if(e.w.error(`Data sync failed on page ${e.C(String(t.iteration))} — ${e.T(String(t.statusCode??`unknown`))} ${t.providerMessage??``}`.trim()),e.w.log(`${t.pagesCompleted} page(s) and ${t.recordsCollected} record(s) succeeded before this one.\n`),(0,C.notMissing)(t.providerData)&&(e.w.log(`${i.default.red.inverse(` PROVIDER ERROR `)}`),e.b(t.providerData),e.w.log(``)),e.w.log(`${i.default.yellow.inverse(` REQUEST THAT FAILED `)}`),e.b(t.inputs),t.iteration>1&&(0,C.notMissing)(n.pagination)){let{pagination:r}=n;e.w.log(``),e.w.info(`Page 1 succeeded and page ${t.iteration} did not, so the ${e.C(r.type)} iterator is the first thing to check: the value above under ${e.C((0,ee.getIteratorLocation)(r)??`query`)} is what the provider rejected. A provider that requires a page-size argument alongside the cursor needs it supplied via ${e.C(`--params`)}, since the iterator only sets the cursor itself.`)}process.exit(1)}#n=e=>{let t=e;try{t=(0,T.loadConnector)(e)}catch{}return t?this.#i(t):void 0};#r=t=>{try{return(0,T.loadConnector)(t)}catch(n){e.w.error(`Failed to load connector file from ${e.C(t)}: ${n.message}`),process.exit(1)}};#i=t=>{let n=(0,T.validateYamlConnector)(t),r=n?.errors??[];if(n.success)return n.connector||(e.w.error(`Failed to load connector.`),process.exit(1)),n.connector;r.length>0?(e.w.error(`Connector is not valid`),e.y(r,!0),process.exit(1)):(e.w.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#a=(t,n)=>{let r=t;try{r=m.default.readFileSync(t,`utf-8`)}catch{}(0,C.isMissing)(n)&&(e.w.error(`A valid connector is required to load an action.`),process.exit(1));let i=`${this.#r(n)} - ${r.split(`
|
|
173
173
|
`).map((e,t)=>t===0?e:` ${e}`).join(`
|
|
174
|
-
`)}`;return this.#
|
|
175
|
-
Exiting watch mode...`)),process.exit(0)};Ln(),e.w.start(`Validating connectors...`);let c=await Hn(o);t=zn(t,c||{}),Bn(t,o),a.start();let l=n(o,{persistent:!0,ignoreInitial:!0}),u=async n=>{if(!n.endsWith(`.s1.yaml`)&&!n.endsWith(`s1.partial.yaml`))return;let r=n.endsWith(`s1.partial.yaml`)?await Wn(n):[n];if(!(!r||r.length===0)){e.v(),a.stop(),Ln(),e.w.log(i.default.gray(`File change detected: ${n}`)),e.w.start(`Validating connectors...`);for(let e of r){let n=await Hn(e);t=zn(t,n||{})}Bn(t,o),a.start()}};l.on(`change`,async e=>await u(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&s()}),process.on(`SIGINT`,()=>{s()})}else{let t=await Hn(o,e.w);process.exit(In(t)?1:0)}}};const zn=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},Bn=(t,n)=>{e.v(),Ln();let r=0,a=0;for(let[n,i]of Object.entries(t))i===null?r++:(e.w?.error(`Connector ${e.C(n)} is not valid`),e.y(i,!0),a++);e.w.log(``),e.w.log(i.default.blue.inverse(` Validation Summary `)),e.w.log(`Connectors path: ${e.C(n)}`),e.w.log(`${r===0?i.default.red(`0`):i.default.green(r)} valid, ${a===0?i.default.green(`0`):i.default.red(a)} invalid connectors\n`)},Vn=async e=>{let t=[],n=await(0,A.readdir)(e);for(let r of n){let n=(0,h.join)(e,r),i=await(0,A.stat)(n);i.isDirectory()?t.push(...await Vn(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},Hn=async(t,n)=>{let r=await(0,A.stat)(t),a={};if(r.isDirectory()){let r=await Vn(t);if(r.length===0)return n?.error(`No StackOne connector found in ${e.S(t)}`),n?.log(`Connector files need to have the extension ${e.C(`*.s1.yaml`)}`),null;let o=0,s=0;for(let e of r){let t=await Un(e,n);t===null?o++:(n?.log(``),s++),a[e]=t}return n?.log(``),n?.log(i.default.blue.inverse(` Validation Summary `)),n?.log(`${o===0?i.default.red(`0`):i.default.green(o)} valid, ${s===0?i.default.green(`0`):i.default.red(s)} invalid connectors`),a}else if(r.isFile()&&t.endsWith(`s1.yaml`))return a[t]=await Un(t,n),a;else if(r.isFile()&&t.endsWith(`partial.yaml`)){n?.error(`Partial connector files cannot be validated directly`),n?.log(`The file ${e.S(t)} is a partial connector file.`);let r=await Wn(t);return r&&r?.length>0&&n?.log(`Did you mean ${e.C(r[0])}?`),null}else return n?.error(`No StackOne connector found in ${e.S(t)}`),n?.log(`Connector files need to have the extension ${e.C(`*.s1.yaml`)}`),null},Un=async(t,n)=>{let r=(0,T.validateYamlConnector)((0,T.loadConnector)(t)),i=r?.errors??[];if(r.success){let r=t.split(`/`).pop()||t;return n?.success(`Connector ${e.C(r)} is valid!`),null}else if(i.length>0)return n?.error(`Connector ${e.C(t)} is not valid`),n&&e.y(i,!0),i;else return n?.error(`Connector ${e.C(t)} is not valid. Please check the file for errors`),[]},Wn=async e=>{let t=(0,h.dirname)(e);try{return(await(0,A.readdir)(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>(0,h.join)(t,e))}catch{}},Gn=`https://ai-telemetry.stackone.com`,Kn=`https://ai-telemetry.stackone-dev.com`;function qn(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 Jn(){return process.env.AI_TELEMETRY_URL?process.env.AI_TELEMETRY_URL:[process.env.AUTH_SERVER_URL,process.env.STACKONE_API_URL].some(qn)?`https://ai-telemetry.stackone-dev.com`:`https://ai-telemetry.stackone.com`}function Yn(){let e=process.env.STACKONE_AGENT_TOKEN,t=process.env.LANGSMITH_PROJECT||`stackone-agent-cli`;if(process.env.AI_TELEMETRY_URL=Jn(),e)try{(0,o.initAgentTelemetry)({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 Xn=`@stackone/cli`,Zn=2880*60*1e3,Qn=(0,l.join)((0,c.homedir)(),`.stackone`),$n=(0,l.join)(Qn,`version-check.json`),er=(e=!1)=>{let t=ir(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=tr();e&&nr(e)&&rr(e),ar({lastCheckTime:n})}},tr=()=>{try{return(0,f.execSync)(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},nr=e=>{try{let t=K();return D.default.gt(e,t)}catch{return!1}},rr=t=>{let n=K(),r=`Update available: ${i.default.dim(n)} → ${i.default.green(t)}`,a=`\n\nRun ${i.default.cyan(`stackone update`)} to update`;e.w.box(r,a)},ir=()=>{try{if(!(0,s.existsSync)($n))return null;let e=(0,s.readFileSync)($n,`utf-8`);return JSON.parse(e)}catch{return null}},ar=e=>{try{(0,s.existsSync)(Qn)||(0,s.mkdirSync)(Qn,{recursive:!0}),(0,s.writeFileSync)($n,JSON.stringify(e,null,2),`utf-8`)}catch{}};var or=class{constructor(e=new a.Command,t=K()){this.program=e,this.version=t,Yn(),this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let t=new mn,n=new xn,r=new yn,o=new on,s=new un,c=new Rn,l=new Ye,u=new Kt,d=new Pe,f=new Ne,p=new Ze,m=new qt,h=new Zt,g=new Nn,_=new Fn;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(i.default.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(e=>{t.execute({environment:e.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 a.Argument(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,t)=>{n.execute({profile:t.profile,fileOrDir:e,apiUrl:t.apiUrl,apiKey:t.apiKey,force:t.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 a.Argument(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{o.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(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.w.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),s.execute({profile:t.profile,connector:t.connector,accountId:t.accountId,format:t.format,outputFile:t.outputFile,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.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(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.w.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),r.execute({profile:t.profile,connector:t.connector,outputPath:t.output,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.owner})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new a.Argument(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{c.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(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.w.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),g.execute({connector:t.connector,action:t.action,actionId:t.actionId,account:t.account,accountId:t.accountId,params:t.params,credentials:t.credentials,profile:t.profile,outputFile:t.outputFile,debug:t.debug,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.owner})});let v=this.program.command(`agent`).description(`StackOne agent commands`);v.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 t=>{t.global&&t.local&&(e.w.error(`--global and --local are mutually exclusive. Please provide only one.`),process.exit(1));let n=t.email!==void 0,r=t.password!==void 0,a=t.passwordStdin===!0;r&&a&&(e.w.error(`--password and --password-stdin are mutually exclusive. Please provide only one.`),process.exit(1));let o=n||r||a;o&&!t.legacy&&(e.w.error(`--email, --password, and --password-stdin require --legacy.`),process.exit(1)),n&&t.email.trim()===``&&(e.w.error(`--email cannot be empty.`),process.exit(1)),r&&t.password===``&&(e.w.error(`--password cannot be empty.`),process.exit(1)),a&&(n||process.env.STACKONE_EMAIL?.trim()||(e.w.error(`--password-stdin requires --email or STACKONE_EMAIL (stdin is consumed for the password, so email cannot be prompted).`),process.exit(1)));let s={email:t.email,password:t.password,passwordFromStdin:a},c=!!process.stdin.isTTY;if(c&&!t.legacy&&!o){let e=await Gt({initialMode:t.global?`global`:t.local?`local`:null,pathFlag:t.path});process.exit(e.status===`error`?1:0)}let d=c&&!o;!t.global&&!t.local&&!d&&e.w.log(i.default.dim(`No interactive terminal detected — defaulting to global setup. Run in a terminal for the prompt, or pass --local (with --path) / --global.`));let f=tt(t.global,t.local,d);if(f===null&&(f=await Ht()),f===`local`){let e=nt(t.path,d);e===null&&(e=await Wt(process.cwd())),await u.execute({legacy:!!t.legacy,credentials:s,targetPath:e})}else await l.execute({legacy:!!t.legacy,credentials:s})}),v.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{d.execute()}),v.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(t,n)=>{let r=[`build`,`test`,`research`],a=n.mode??`build`;r.includes(a)||(e.w.error(`${i.default.red(`Invalid mode:`)} ${i.default.white(a)}. Valid modes are: ${r.join(`, `)}.`),process.exit(1));let o=n.maxTurns?parseInt(String(n.maxTurns),10):void 0;await p.execute({prompt:String(t),mode:a,maxTurns:o!==void 0&&!isNaN(o)?o:void 0,verbose:n.verbose})}),v.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 m.execute({mode:e.mode})}),v.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 h.execute({check:!!e.check,pluginDir:e.pluginDir})}),v.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 t=>{let n=[`build`,`test`,`research`];t.mode&&!n.includes(t.mode)&&(e.w.error(`❌ Error: Invalid mode "${t.mode}". Must be one of: ${n.join(`, `)}`),process.exit(1)),t.temperature!==void 0&&(isNaN(t.temperature)&&(e.w.error(`❌ Error: Temperature must be a valid number`),process.exit(1)),(t.temperature<0||t.temperature>1)&&(e.w.error(`❌ Error: Temperature must be between 0 and 1`),process.exit(1))),f.execute({mode:t.mode,connector:t.connector,action:t.action,goal:t.goal,temperature:t.temperature,verbose:t.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=>{_.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{e.w.log(`${i.default.inverse.greenBright(`StackOne`)} ${i.default.grey(`CLI`)} ${i.default.whiteBright(this.version)}`),er(!0),process.exit(0)})}run(){process.argv.includes(`version`)||er(),this.program.parse(process.argv)}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return or}});
|
|
174
|
+
`)}`;return this.#i(i)};#o=(t,n,r)=>{let i=t;try{i=m.default.readFileSync(t,`utf-8`)}catch{}try{let e=Kn.parse(JSON.parse(i));return{providerKey:n,providerVersion:r,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(t){let n=[];try{n=JSON.parse(t.message)}catch{}e.w.error(`Failed to parse account information`),e.y(n,!1),n.length===0&&e.w.log(t.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(t,n,r,i)=>{((0,C.isMissing)(t)||(0,C.isMissing)(n)||(0,C.isMissing)(r))&&(e.w.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let a=(0,v.default)();try{a.text=`Fetching connector ${e.C(t)} from registry...`,a.start();let o=Buffer.from(r).toString(`base64`),s=i?`?owner=${encodeURIComponent(i)}`:``,c=await fetch(`${n}/registry/connectors/${t}${s}`,{method:`GET`,headers:{Authorization:`Basic ${o}`}});if(a.stop(),c.status===409){i&&(await e.x(c,`Failed to fetch connector ${e.C(t)} from registry`),process.exit(1));let r=await cn(t,(await c.json()).availableOwners??[]);a.text=`Fetching connector ${e.C(t)} from registry...`,a.start();let s=await fetch(`${n}/registry/connectors/${t}?owner=${encodeURIComponent(r)}`,{method:`GET`,headers:{Authorization:`Basic ${o}`}});a.stop(),s.ok||(await e.x(s,`Failed to fetch connector ${e.C(t)} from registry`),process.exit(1));let l=await s.text(),u=this.#i(l);return e.w.success(`Fetched connector ${e.C(u.key)}@${e.C(u.version)} from registry`),u}c.ok||(await e.x(c,`Failed to fetch connector ${e.C(t)} from registry`),process.exit(1));let l=await c.text(),u=this.#i(l);return e.w.success(`Fetched connector ${e.C(u.key)}@${e.C(u.version)} from registry`),u}catch(r){a.stop(),e.w.error(`Failed to fetch connector ${e.C(t)} from registry: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),process.exit(1)}};#u=async(t,n,r)=>{((0,C.isMissing)(t)||(0,C.isMissing)(n)||(0,C.isMissing)(r))&&(e.w.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let i=(0,v.default)();try{i.text=`Fetching connector for account ${e.C(t)} from API...`,i.start();let a=Buffer.from(r).toString(`base64`),o=await fetch(`${n}/accounts/${t}/connector`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});i.stop(),o.ok||(await e.x(o,`Failed to fetch connector`),process.exit(1));let s=await o.text(),c=this.#i(s);return e.w.success(`Fetched connector ${e.C(c.key)}@${e.C(c.version)} for account ${e.C(t)}`),c}catch(t){i.stop(),e.w.error(`Failed to fetch connector: ${t.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),process.exit(1)}};#d=async(t,n,r)=>{((0,C.isMissing)(t)||(0,C.isMissing)(n)||(0,C.isMissing)(r))&&(e.w.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let i=(0,v.default)();try{i.text=`Fetching account ${e.C(t)} information from API...`,i.start();let a=Buffer.from(r).toString(`base64`),o=await fetch(`${n}/accounts/${t}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});i.stop(),o.ok||(await e.x(o,`Failed to fetch account ${e.C(t)} information`),process.exit(1));let s=await o.json();return e.w.success(`Fetched account ${e.C(t)} information from project ${e.C(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(r){i.stop(),e.w.error(`Failed to fetch account ${e.C(t)} information: ${r.message}`),e.w.log(`Please ensure that the API at ${e.T(n)} is reachable and the API key is valid`),process.exit(1)}};#f=t=>{let n=t;try{n=m.default.readFileSync(t,`utf-8`)}catch{}try{return qn.parse(JSON.parse(n))}catch(t){let n=[];try{n=JSON.parse(t.message)}catch{}e.w.error(`Failed to parse credentials`),e.y(n,!1),n.length===0&&e.w.log(t.message),process.exit(1)}};#p=(t,n)=>{let r=t;try{r=m.default.readFileSync(t,`utf-8`)}catch{}try{return Jn.parse(JSON.parse(r))}catch(t){let r=[];try{r=JSON.parse(t.message)}catch{}e.w.error(`Invalid parameters for action ${e.C(n)}.`),e.y(r,!1),r.length===0&&e.w.log(t.message),process.exit(1)}};async#m({connector:t,actionId:n,account:r,pathParams:a={},queryParams:o={},body:s={},headers:c={}}){try{let l=await(0,T.runAction)({mode:`action_id`,actionId:n,account:r,connector:t,pathParams:a,queryParams:o,body:s,headers:c,getHttpClient:async()=>new k.HttpClient});if(l.response?.successful){let e={...this.#h(o,l.steps),...(0,C.isObject)(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`;e.w.error(`Action ID ${e.C(n)} from connector ${e.C(t.key)}@${e.C(t.version)} failed with status ${l.response?.statusCode}: ${r}`);let a={...this.#h(o,l.steps)};Object.keys(a).length>0&&(e.w.log(`${i.default.yellow.inverse(` EXECUTION DETAILS `)}`),e.b(a)),process.exit(1)}}catch(e){this.#g(e)}}#h(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#g(t){let n=t;switch((0,C.isMissing)(n.errorType)&&(e.w.error(`An unknown error occurred`),e.w.log(`${t instanceof Error?t.message:String(t)}`),process.exit(1)),n.errorType){case`MISSING_ACTION_ERROR`:e.w.error(`The specified action was not found: ${n.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let t=n;e.w.error(`Invalid action inputs`),e.y(t.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:e.w.error(`Invalid cursor: ${n.message}`);break;default:e.w.error(`An error occurred: ${n.message}`)}process.exit(1)}};const Zn=(0,A.promisify)(f.exec);var Qn=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=(0,v.default)(),this.currentVersion=K()}async execute(t={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let n=await this.getLatestVersion();this.spinner.stop(),n||(e.w.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(n,this.currentVersion)?(e.w.box(`New version available: ${i.default.yellow(this.currentVersion)} → ${i.default.green(n)}`),await this.performUpdate(n)):t.force?(e.w.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(n)):e.w.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(t){this.spinner.stop(),e.w.error(`Error while trying to update StackOne CLI: ${t?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await Zn(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return O.default.gt(e,t)}async performUpdate(t){this.spinner.text=`Updating to latest version (${e.C(t)})...`,this.spinner.start();let n=`npm install -g ${this.packageName}@latest`;try{await Zn(n,{encoding:`utf-8`}),this.spinner.stop(),e.w.success(`StackOne CLI updated successfully to latest version (${e.C(t)})`)}catch{throw this.spinner.stop(),Error(`Failed to install update. Please try manually: ${n}`)}}};const $n=e=>e===null?!0:Object.values(e).some(e=>e!==null),er=()=>{e.w.log(`${i.default.gray.inverse(` CONNECTORS VALIDATION `)} ${i.default.yellow.inverse(` WATCH MODE `)}\n`)};var tr=class{async execute(t){let{watchMode:n,fileOrDir:r}=t,a=(0,v.default)(`Watching for file changes... ${i.default.gray(`(press "q" to quit)`)}`);if(!r)return;let o=(0,h.resolve)(r);try{await(0,j.stat)(o)}catch{e.w.error(`The specified path does not exist: ${o}\n`),process.exit(1)}if(n){e.v();let t={},{watch:n}=await import(`chokidar`),r=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let s=()=>{l.close(),a.stop(),r.close(),e.w.log(i.default.grey(`
|
|
175
|
+
Exiting watch mode...`)),process.exit(0)};er(),e.w.start(`Validating connectors...`);let c=await ar(o);t=nr(t,c||{}),rr(t,o),a.start();let l=n(o,{persistent:!0,ignoreInitial:!0}),u=async n=>{if(!n.endsWith(`.s1.yaml`)&&!n.endsWith(`s1.partial.yaml`))return;let r=n.endsWith(`s1.partial.yaml`)?await sr(n):[n];if(!(!r||r.length===0)){e.v(),a.stop(),er(),e.w.log(i.default.gray(`File change detected: ${n}`)),e.w.start(`Validating connectors...`);for(let e of r){let n=await ar(e);t=nr(t,n||{})}rr(t,o),a.start()}};l.on(`change`,async e=>await u(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&s()}),process.on(`SIGINT`,()=>{s()})}else{let t=await ar(o,e.w);process.exit($n(t)?1:0)}}};const nr=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},rr=(t,n)=>{e.v(),er();let r=0,a=0;for(let[n,i]of Object.entries(t))i===null?r++:(e.w?.error(`Connector ${e.C(n)} is not valid`),e.y(i,!0),a++);e.w.log(``),e.w.log(i.default.blue.inverse(` Validation Summary `)),e.w.log(`Connectors path: ${e.C(n)}`),e.w.log(`${r===0?i.default.red(`0`):i.default.green(r)} valid, ${a===0?i.default.green(`0`):i.default.red(a)} invalid connectors\n`)},ir=async e=>{let t=[],n=await(0,j.readdir)(e);for(let r of n){let n=(0,h.join)(e,r),i=await(0,j.stat)(n);i.isDirectory()?t.push(...await ir(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},ar=async(t,n)=>{let r=await(0,j.stat)(t),a={};if(r.isDirectory()){let r=await ir(t);if(r.length===0)return n?.error(`No StackOne connector found in ${e.S(t)}`),n?.log(`Connector files need to have the extension ${e.C(`*.s1.yaml`)}`),null;let o=0,s=0;for(let e of r){let t=await or(e,n);t===null?o++:(n?.log(``),s++),a[e]=t}return n?.log(``),n?.log(i.default.blue.inverse(` Validation Summary `)),n?.log(`${o===0?i.default.red(`0`):i.default.green(o)} valid, ${s===0?i.default.green(`0`):i.default.red(s)} invalid connectors`),a}else if(r.isFile()&&t.endsWith(`s1.yaml`))return a[t]=await or(t,n),a;else if(r.isFile()&&t.endsWith(`partial.yaml`)){n?.error(`Partial connector files cannot be validated directly`),n?.log(`The file ${e.S(t)} is a partial connector file.`);let r=await sr(t);return r&&r?.length>0&&n?.log(`Did you mean ${e.C(r[0])}?`),null}else return n?.error(`No StackOne connector found in ${e.S(t)}`),n?.log(`Connector files need to have the extension ${e.C(`*.s1.yaml`)}`),null},or=async(t,n)=>{let r=(0,T.validateYamlConnector)((0,T.loadConnector)(t)),i=r?.errors??[];if(r.success){let r=t.split(`/`).pop()||t;return n?.success(`Connector ${e.C(r)} is valid!`),null}else if(i.length>0)return n?.error(`Connector ${e.C(t)} is not valid`),n&&e.y(i,!0),i;else return n?.error(`Connector ${e.C(t)} is not valid. Please check the file for errors`),[]},sr=async e=>{let t=(0,h.dirname)(e);try{return(await(0,j.readdir)(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>(0,h.join)(t,e))}catch{}},cr=`https://ai-telemetry.stackone.com`,lr=`https://ai-telemetry.stackone-dev.com`;function ur(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 dr(){return process.env.AI_TELEMETRY_URL?process.env.AI_TELEMETRY_URL:[process.env.AUTH_SERVER_URL,process.env.STACKONE_API_URL].some(ur)?`https://ai-telemetry.stackone-dev.com`:`https://ai-telemetry.stackone.com`}function fr(){let e=process.env.STACKONE_AGENT_TOKEN,t=process.env.LANGSMITH_PROJECT||`stackone-agent-cli`;if(process.env.AI_TELEMETRY_URL=dr(),e)try{(0,o.initAgentTelemetry)({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 pr=e=>{let t=e.trim();return/^\d+$/.test(t)?Number(t):NaN},mr=`@stackone/cli`,hr=2880*60*1e3,gr=(0,l.join)((0,c.homedir)(),`.stackone`),_r=(0,l.join)(gr,`version-check.json`),vr=(e=!1)=>{let t=Sr(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=yr();e&&br(e)&&xr(e),Cr({lastCheckTime:n})}},yr=()=>{try{return(0,f.execSync)(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},br=e=>{try{let t=K();return O.default.gt(e,t)}catch{return!1}},xr=t=>{let n=K(),r=`Update available: ${i.default.dim(n)} → ${i.default.green(t)}`,a=`\n\nRun ${i.default.cyan(`stackone update`)} to update`;e.w.box(r,a)},Sr=()=>{try{if(!(0,s.existsSync)(_r))return null;let e=(0,s.readFileSync)(_r,`utf-8`);return JSON.parse(e)}catch{return null}},Cr=e=>{try{(0,s.existsSync)(gr)||(0,s.mkdirSync)(gr,{recursive:!0}),(0,s.writeFileSync)(_r,JSON.stringify(e,null,2),`utf-8`)}catch{}};var wr=class{constructor(e=new a.Command,t=K()){this.program=e,this.version=t,fr(),this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let t=new mn,n=new xn,r=new yn,o=new on,s=new un,c=new tr,l=new Ye,u=new Kt,d=new Pe,f=new Ne,p=new Ze,m=new qt,h=new Zt,g=new Xn,_=new Qn;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(i.default.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(e=>{t.execute({environment:e.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 a.Argument(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,t)=>{n.execute({profile:t.profile,fileOrDir:e,apiUrl:t.apiUrl,apiKey:t.apiKey,force:t.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 a.Argument(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{o.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(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.w.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),s.execute({profile:t.profile,connector:t.connector,accountId:t.accountId,format:t.format,outputFile:t.outputFile,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.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(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.w.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),r.execute({profile:t.profile,connector:t.connector,outputPath:t.output,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.owner})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new a.Argument(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{c.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)`,pr).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)`,pr).description(`Run a connector action`).action(t=>{[t.builtin,t.custom,t.owner].filter(Boolean).length>1&&(e.w.error(`--builtin, --custom, and --owner are mutually exclusive. Please provide only one.`),process.exit(1)),t.syncFull&&t.syncIncremental!==void 0&&(e.w.error(`--sync-full and --sync-incremental are mutually exclusive. Please provide only one.`),process.exit(1)),t.syncIncremental===``&&(e.w.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)),t.syncMaxPages!==void 0&&(Number.isNaN(t.syncMaxPages)||t.syncMaxPages<1)&&(e.w.error(`--sync-max-pages must be a positive integer.`),process.exit(1)),t.syncPageSize!==void 0&&(Number.isNaN(t.syncPageSize)||t.syncPageSize<1)&&(e.w.error(`--sync-page-size must be a positive integer.`),process.exit(1)),t.syncPageSize!==void 0&&!t.syncFull&&!t.syncIncremental&&(e.w.error(`--sync-page-size only applies to --sync-full or --sync-incremental.`),process.exit(1)),g.execute({connector:t.connector,action:t.action,actionId:t.actionId,account:t.account,accountId:t.accountId,params:t.params,credentials:t.credentials,profile:t.profile,outputFile:t.outputFile,debug:t.debug,apiUrl:t.apiUrl,apiKey:t.apiKey,owner:t.builtin?`builtin`:t.custom?`custom`:t.owner,syncFull:t.syncFull,syncIncremental:t.syncIncremental,syncMaxPages:t.syncMaxPages,syncPageSize:t.syncPageSize})});let v=this.program.command(`agent`).description(`StackOne agent commands`);v.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 t=>{t.global&&t.local&&(e.w.error(`--global and --local are mutually exclusive. Please provide only one.`),process.exit(1));let n=t.email!==void 0,r=t.password!==void 0,a=t.passwordStdin===!0;r&&a&&(e.w.error(`--password and --password-stdin are mutually exclusive. Please provide only one.`),process.exit(1));let o=n||r||a;o&&!t.legacy&&(e.w.error(`--email, --password, and --password-stdin require --legacy.`),process.exit(1)),n&&t.email.trim()===``&&(e.w.error(`--email cannot be empty.`),process.exit(1)),r&&t.password===``&&(e.w.error(`--password cannot be empty.`),process.exit(1)),a&&(n||process.env.STACKONE_EMAIL?.trim()||(e.w.error(`--password-stdin requires --email or STACKONE_EMAIL (stdin is consumed for the password, so email cannot be prompted).`),process.exit(1)));let s={email:t.email,password:t.password,passwordFromStdin:a},c=!!process.stdin.isTTY;if(c&&!t.legacy&&!o){let e=await Gt({initialMode:t.global?`global`:t.local?`local`:null,pathFlag:t.path});process.exit(e.status===`error`?1:0)}let d=c&&!o;!t.global&&!t.local&&!d&&e.w.log(i.default.dim(`No interactive terminal detected — defaulting to global setup. Run in a terminal for the prompt, or pass --local (with --path) / --global.`));let f=tt(t.global,t.local,d);if(f===null&&(f=await Ht()),f===`local`){let e=nt(t.path,d);e===null&&(e=await Wt(process.cwd())),await u.execute({legacy:!!t.legacy,credentials:s,targetPath:e})}else await l.execute({legacy:!!t.legacy,credentials:s})}),v.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{d.execute()}),v.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(t,n)=>{let r=[`build`,`test`,`research`],a=n.mode??`build`;r.includes(a)||(e.w.error(`${i.default.red(`Invalid mode:`)} ${i.default.white(a)}. Valid modes are: ${r.join(`, `)}.`),process.exit(1));let o=n.maxTurns?parseInt(String(n.maxTurns),10):void 0;await p.execute({prompt:String(t),mode:a,maxTurns:o!==void 0&&!isNaN(o)?o:void 0,verbose:n.verbose})}),v.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 m.execute({mode:e.mode})}),v.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 h.execute({check:!!e.check,pluginDir:e.pluginDir})}),v.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 t=>{let n=[`build`,`test`,`research`];t.mode&&!n.includes(t.mode)&&(e.w.error(`❌ Error: Invalid mode "${t.mode}". Must be one of: ${n.join(`, `)}`),process.exit(1)),t.temperature!==void 0&&(isNaN(t.temperature)&&(e.w.error(`❌ Error: Temperature must be a valid number`),process.exit(1)),(t.temperature<0||t.temperature>1)&&(e.w.error(`❌ Error: Temperature must be between 0 and 1`),process.exit(1))),f.execute({mode:t.mode,connector:t.connector,action:t.action,goal:t.goal,temperature:t.temperature,verbose:t.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=>{_.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{e.w.log(`${i.default.inverse.greenBright(`StackOne`)} ${i.default.grey(`CLI`)} ${i.default.whiteBright(this.version)}`),vr(!0),process.exit(0)})}run(){process.argv.includes(`version`)||vr(),this.program.parse(process.argv)}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return wr}});
|